diff --git a/.gitignore b/.gitignore index 0cd429187..4a15c6679 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,9 @@ node_modules/ /.claude/* !/.claude/memory/ !/.claude/settings.json +# The team stamp templates carry files that land under a target repo's .claude/. +!/templates/team-stamp/files/.claude/ +!/tests/fixtures/team-stamp/files/.claude/ # Legacy / retired artifacts the kit no longer writes: review output now lives in # the spec's `## Review` section, and the spec location unified onto docs/specs/ diff --git a/CHANGELOG.md b/CHANGELOG.md index db42ddbfd..b2be5b5ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,6 +78,7 @@ All notable changes to dwarves-kit are documented here. ### Added - Visual proof capture, the `proof_capture` module (new `bin/proof-capture`, new `lib/proof-capture/`, new opt-in `[modules] proof_capture`, default off, additive, NO default change): `proof-capture run page ` makes a PNG with a headless Chromium-family browser on a throwaway profile, `proof-capture run tape ` makes a GIF with `vhs`. It starts the child in its own process group, ends that group on success, deadline or a catchable signal, and keeps a watchdog for a KILL. It reads no kit file, so the directory also runs alone. With `[proof] visual` on, `proof-gate.sh contract` adds one `capture:` line after the `visual:` line for a ui page or tui task when the module files are present; the `visual:` text and every output with the knob off are unchanged. `commands/verify.md` Step 7b names the command and tells the reader to open the image before `proof-asset put`. Proof: `docs/verification/visual-proof-module.md`. - Agent surface (new `agents/ui-acceptance-verifier.md`, new `lib/ui-verify/`, additive, MINOR): first slice, scenario layer only. `kit:ui-acceptance-verifier` is a read-only lens that runs the kit's runner over a pull request preview and returns a per-criterion PASS, FAIL or NO-CHECK in the acceptance-verifier grammar. The lead writes a `scenario.json` from the acceptance criteria; the runner drives a pinned headless Chromium with its sandbox on, refuses hosts and ports the lead did not name, gives the browser no proxy and none of its own environment, uses only an install root nobody else could have written, and derives every row status itself. `/kit:battery` gains one "Lens escalation" row for a UI change with a preview URL. The install root is a new `cache ui-verify` data-path entry (env `UI_VERIFY_HOME`); `--doctor` checks it. Playwright is an external dependency the operator installs, and the runner returns NO-CHECK rows, never PASS, on a host that lacks it. Not in this slice: token, layout, pixel and accessibility checks, a vision pass, preview discovery from the pull request, and a login or storage state, so a page behind a sign-in cannot be verified (a `skip` entry is NO-CHECK and the verdict escalates). The surface (`schema: 1`, exit codes, doctor output, `UI_VERIFY_HOME`, the stdout rows, the `result.json` fields) is provisional until one consumer repo has run it, and a PASS proves what the page showed the runner. +- `lib/stamp.sh` and `/kit:stamp`: write a kit-free agent harness into a repo whose team does not run the kit (a self-contained `AGENTS.md`, a project hook, a PR shape CI job with its local twin, an owners check, a merge guard, an Issues queue, a tagged changelog, a digest). Idempotent, never overwrites an edited file, reports drift, offers a per-file diff after an upgrade. Templates under `templates/team-stamp/`. - Command surface (`lib/queue/orchestrate.sh` `_serial_level_join`, additive, NO change with `verify = "off"`): a tiered serial run joins once per DAG level. At the top of every cycle, before anything dispatches, each level whose sub-goals and lower levels are all checked and that has no `.orchestrate/join-level-.ok` runs `[test] join_cmd` on origin's current base tree in a throwaway worktree, judged against the committed known-failures list with an executed count that may not drop below the last green level's. Every config key is read at the base sha pinned before the first dispatch. A red join halts the loop and a re-run joins the level again before dispatching; a stale base (origin unreachable or ahead) halts; a tiered run with no `join_cmd` halts at the first due level. The serial loop never merges (each worker merges its own PR), so unlike the wave join this one runs after the level's merges, on the base, not on a pinned pre-merge tree. A level is 0 with no `depends`, else 1 plus its deepest dependency. Proof: `docs/verification/serial-path-join.md`. - `lib/gate/known-failures.sh` (`read`, `classify`, `guard`, `suite`): the lead-committed known-failures list and the node suite scope of a tiered mega-goal. `tests/test-known-failures.sh`, `tests/test-orchestrate-tiered.sh`, `tests/lib/node-fixture.sh` and the verify-off golden `tests/fixtures/orchestrate-golden/off.txt` pin it. - Install surface (additive, `--no-mods` unchanged): `install.sh` now loads five Claude Code mods, not one. New vendored mods under `integrations/claude-code/`: `secrets-veil` and `memory-lens` (MIT) and `loop-detective` and `context-inspector` (Apache-2.0), each with its `LICENSE` and a `VENDORED.md` that pins the source commit and lists the local patches. One mod list drives the full install, the plugin-compat install (checkout paths) and `--uninstall` (every kit path, and only those). A mod is skipped with `[skip] already loaded from ` when `env.CLAUDE_CODE_PLUGIN_DIRS` already holds another entry that loads a plugin of that name (manifest name, else folder name, leading `~` expanded), and the kit's own entry for it leaves the list. `memory-lens` trusts no repo `.claude/memory` until `~/.claude/memory-lens/trusted-roots` lists a prefix. Patches to the two upstream mods: no raw failure excerpt and no status row in loop-detective, no status row and hashed non-file export targets in context-inspector. Pinned by `tests/test-install-mods.sh` and each mod's own tests. See `integrations/claude-code/README.md`. diff --git a/commands/stamp.md b/commands/stamp.md new file mode 100644 index 000000000..f477e405b --- /dev/null +++ b/commands/stamp.md @@ -0,0 +1,87 @@ +--- +description: "Write a kit-free agent harness into a repo whose team does not run the kit: self-contained AGENTS.md and a people's copy, a project hook that blocks a bare merge and a push or commit on the default branch, session-start lessons, a ship playbook, a PR shape CI job with its local twin, an owners check, a merge guard, a negative control, an Issues work queue, a tagged changelog, a digest and a proof guide. Idempotent, never overwrites an edited file, reports drift." +--- + +You are stamping a repo with the team harness. One operator runs the kit; the teammates and their +coding agents do not. Every file this writes is a plain copy the repo owns and runs with no kit +installed: no file names a path under the kit, and the stamp adds no daemon and no service. + +## Run + +`$ARGUMENTS` may name a target dir (default: the repo root) and any of the value flags below. + +1. Resolve the target: default `.` (`git rev-parse --show-toplevel`). It must be a git repo. +2. Dry run first, then write (idempotent, non-destructive): + + ``` + bash "${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/dwarves-kit}/lib/stamp.sh" --dry-run --owner + bash "${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/dwarves-kit}/lib/stamp.sh" --owner + ``` + + The first pull request that introduces the stamp into a repo touches every door (the workflows, `scripts/`, `.claude/`, the rules files). A second person reads it and approves it, or the operator merges it by hand: the merge guard cannot judge its own first copy. + +3. Report the status lines it printed (`created`, `merged`, `unchanged`, `edited (left alone)`, + `older stamp (run --refresh)`, `missing`) and any two-line refusal with its `Fix:` line. The + operator reviews and commits the files; the stamp commits nothing. + +## Flags + +| Flag | Default | Used for | +|---|---|---| +| `--owner ` | required | the owner row of every generated script in `OWNERS.md` | +| `--default-branch ` | `origin/HEAD`, else refuse | the guard, the merge guard, the checks | +| `--tags a,b` | `product,dev` (`dev` is always added) | changelog tags; release notes drop `dev:` | +| `--product-paths a/,b/` | `src/` | paths that owe a tagged changelog line | +| `--door-paths p,q` and `--door-approver ` | empty | paths that need a second person's approval before merge | +| `--board-file ` | empty | the board the queue and the digest read | +| `--decision-tag ` | `decision` | the tag of a board row that waits on a human | + +A value is remembered in `.claude/team-stamp.lock`, so a re-run with no flags renders the same bytes. + +## Modes + +- `--check`: write nothing; exit 0 only when every file is present and unchanged. +- `--dry-run`: print what would be written. +- `--refresh`: after a kit upgrade, print one unified diff per file whose template changed, and + the `--take ` command for it. It writes nothing. +- `--take `: replace exactly one file the repo did not edit (its hash equals its lock hash), + keeping the old copy as `.orig`. An edited file is refused and its diff printed; the + operator applies it by hand. `--take` also swaps adopt's own `AGENTS.md` pointer and proof + marker for the stamp's versions. +- `--only `: limit the run to named template groups (group tests use it). + +## What it writes + +The file list lives in the team stamp spec under `docs/specs/` ("Generated files"). In short: + +- `AGENTS.md` (the kit marker on line 1, a closing optional-kit section naming only the public + URL) and `docs/TEAM-WORKFLOW.md`, with a CI parity check between them. +- `.claude/settings.json` (merged by entry, never rewritten), `scripts/agent-guard.sh`, + `scripts/agent-lessons.sh`, `.claude/memory/` seeded with five CI lessons, the `ship-pr` skill. +- `.github/workflows/ci.yml` (always `runs-on: [self-hosted]`), `scripts/pr-shape.sh`, + `scripts/check.sh` (the local twin), `scripts/check-owners.sh`, `OWNERS.md`, + `scripts/pr-merge.sh`, `scripts/negctl.sh`, each with its own test under `scripts/test-*.sh`. +- The issue form, `scripts/issues-from-rows.sh`, the PR template, `CHANGELOG.md`, + `scripts/release-notes.sh`, `scripts/team-digest.sh`, `docs/verification/README.md`, and a + `.kit.toml` with the proof gate on and the lane gate off. + +`OWNERS.md`, `CHANGELOG.md` and the lesson notes are written once and then belong to the repo. + +## Order with adopt + +Either order works. Stamp first: adopt leaves the stamp's files alone. Adopt first: the stamp +reports adopt's `AGENTS.md`, proof marker and `.kit.toml` as left alone; `--take AGENTS.md` and +`--take docs/verification/README.md` swap the first two; a `.kit.toml` with `lane_gates = true` +gets a two-line drift report and is never edited. Kit hook entries in `.claude/settings.json` +are counted in a note and left in place. + +## Limits + +- It binds Claude Code through the project hook and every other agent through CI. A person who + merges from the GitHub site passes everything on a plan without branch protection; the + generated rules say so. +- The workflow needs a self-hosted runner. Without one it queues; `bash scripts/check.sh` is the + check until one exists. +- Language test jobs, product playbooks and the list of irreversible paths are the repo's own. + +Detail: `lib/stamp/README.md` (how a template group plugs in), and the team stamp spec under `docs/specs/`. diff --git a/docs/MANUAL.md b/docs/MANUAL.md index 12f2eaff8..c5333d3eb 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -86,6 +86,14 @@ Index by loop stage (formerly "leg"; [`reference/workflow-paths.md`](reference/w **When to invoke:** the first time in a repo, or after editing `[modules]` in `.kit.toml` (`--refresh` re-wires). `--check` is status only. `--with a,b,c` seeds those modules in a FRESH `.kit.toml`. `--single-source` keeps one agent guide instead of a CLAUDE.md/AGENTS.md pair. Several repos at once: `bin/wrap adopt ...`. **Common gotcha:** idempotent and non-destructive. A repo's own `AGENTS.md`, `CLAUDE.md`, or `.kit.toml` is never overwritten, and `--with` on an existing `.kit.toml` is a no-op. It installs pointers, never a copy of `lib/` or the full WORKFLOW. Detail: `commands/adopt.md`. +### `/kit:stamp` + +**Phase:** front door (a kit-free harness for a repo whose team does not run the kit) +**Reads:** the target dir, its `origin/HEAD` for the default branch, its existing `AGENTS.md`, `.kit.toml`, `.claude/settings.json` and `.claude/team-stamp.lock`, and `templates/team-stamp/` +**Writes:** plain repo-owned files: a self-contained `AGENTS.md` and `docs/TEAM-WORKFLOW.md`, a project hook that blocks a bare merge and a push or commit on the default branch, session-start lessons, a ship playbook, a PR shape CI job with its local twin `scripts/check.sh`, an owners check, a merge guard, a negative control, an Issues work queue, a tagged changelog with release notes, a digest, a proof guide, and the lock. It merges `.claude/settings.json` by entry and commits nothing +**When to invoke:** once per repo, by the operator (`--owner ` is required), then `--check` to confirm and `--refresh` after a kit upgrade, which prints a diff per file and the `--take ` command for it +**Common gotcha:** a file the repo edited is never overwritten, and `--take` refuses it and prints the diff to apply by hand. The generated files run with no kit installed. The workflow always runs on `[self-hosted]`; without a runner, `scripts/check.sh` is the check. Detail: `lib/stamp/README.md` + ### `/kit:grill` **Phase:** intake (between type classification and the phase-0 `Done=` line) diff --git a/docs/implementation-notes/team-stamp.md b/docs/implementation-notes/team-stamp.md new file mode 100644 index 000000000..c6b1a18d3 --- /dev/null +++ b/docs/implementation-notes/team-stamp.md @@ -0,0 +1,102 @@ +# team-stamp: implementation notes + +Spec: `docs/specs/SPEC-425-team-stamp.md`. Only deltas from the spec. One `## ` section per build group; append yours, do not edit another group's. + +## G0 engine + +### Decisions the spec did not make +- D1. The manifest row has five tab-separated columns: `action source target mode keys`. The group name is the manifest file name (`NN-.tsv`), not a column. A column is never empty: `-` means no keys. +- D2. The row kinds are `copy`, `seed`, `jsonmerge`, `hook`. `hook` runs a script and writes its stdout, seed-once. The script reads `STAMP_TARGETS_FILE` (selected groups), `STAMP_ALL_TARGETS_FILE` (every group, even under `--only`) and `STAMP_VALUES_FILE`. A `hook` source `lib/...` is kit-relative, any other path is under the templates root. +- D3. `--only ` restricts a run to named groups. Group tests need it; the spec lists no such flag. +- D4. Values come from flag, else the lock, else a default, so a second run with no flags renders the same bytes. Without that a re-run could not be idempotent. +- D5. A template that uses a key its row does not declare, or a row that declares an unknown key, aborts the run. It catches typos and keeps the contract honest. +- D6. `jsonmerge` is judged by "would the merge change anything", not by a lock hash. It merges by `hooks` entry (match on `matcher`, then on `command`); other top-level keys of the template are ignored. +- D7. A `seed` or `hook` file that is deleted is created again on the next run; one that exists is never read. The spec says "created when absent" without the deleted case. +- D8. A new base value `DECISION_TAG` (flag `--decision-tag`, default `decision`) joins the spec's list; derived values are `TAGS_ERE`, `TAGS_COLON`, `TAGS_AWK`, `PRODUCT_ERE`, `PRODUCT_ARRAY`, `DOOR_ARRAY`, `DOOR_CASE`. `DOOR_ARRAY` is the empty string when no door path is set. +- D9. The owners seed is `lib/stamp/owners-seed.sh`, owned by G0 (validation moved it out of G4). It writes the whole `OWNERS.md` (rule text and one row per script, test and workflow in the merged manifest) so a group needs no `OWNERS.md.tpl`. +- D10. Interplay notes print at the end of a default, `--check`, `--dry-run` and `--refresh` run: a `.kit.toml` row whose file sets `lane_gates = true` is a two-line drift line (exit 1 under `--check`); kit hook commands in `.claude/settings.json` are counted in a `note:` line and never edited. + +### Changes from the spec +- C1. `--take` on an edited file cannot print "the diff between the lock's rendering and the new template": the lock holds a hash, not the rendering. It prints the diff from the current file to the new template and says the left side includes the repo's edits. +- C2. Default branch: `origin/HEAD`, else refuse. The parameter table said "else `main`"; edge case 2 says refuse and no guess. Edge case 2 wins (fail closed). The spec table was amended to match. +- C3. `--take` also accepts a file that is not in the lock when it is a known kit file: adopt's pointer, an old kit copy (`lib/adopt/agents-known.sha256`), or adopt's proof marker (first line `# Verification (proof-of-done marker)`, at most 8 lines). The spec's adopt-interplay table promises that swap; amendment 2 only struck `--force-file`. +- C4. `--check` exits 1 for every status except `unchanged`, `older stamp` included (the spec said "matches the lock"). +- C5. The target's `.orig` backups are guarded against symlinks like every target; a second `--take` of the same file writes `.orig.1`, never overwrites a backup. +- C6. The validation asked to move `## Picture` under `## Design`. Kept as `## Picture` (the spec template requires that heading on a full-lane spec) and added the lock-state sketch inside `## Design`. + +- C7. The lock was first written with bare hex (`file `). A secret scan on the operator's machine reads a bare 64-hex run as a key, so the lock now writes `sha256:` (follow-up commit after the engine commit). An older lock with bare hex still reads. Every group must keep any hash it carries in the marker form (the shellcheck pin of the CI template: `sha256=`), and no template or fixture may hold a hex literal. + +### Open questions +- Q1. Test row 42 (negctl refusing a syntax-only red) and the rest of the validation's per-script rows are G7 to G9 work; the spec carries them. +- Q2. Not re-probed by this build: the validation's guard misses `gh api .../merge`, `$g pr merge`, `env -i`, `timeout`, `git push --all/--mirror`. Seven findings were reproduced against the source (door arrays under `set -u`, python3 in release-notes, label precondition, checkout override, fixture literals, `fix:` casing, the `.kit.toml` kit header); G3 re-probes the guard cases. + +## G1 rules docs, G2 lessons +- Dropped from the source rules: the evidence and docs-layout sections, the dash rule, board-ID minting, product playbooks, the `--allow-ci-change` and `--refresh` flags, the weekly demo, the direction list, the chat-channel line, the figure. `.kit.toml` holds only the two gate keys. +- Five seed lessons, not the source's eight. `agent-lessons.sh` resolves the repo from its own location, not from `CLAUDE_PROJECT_DIR`. +- Parity rule: every `AGENTS.md` heading has a `[Heading](../AGENTS.md#slug)` link in `docs/TEAM-WORKFLOW.md`; `pr-shape.sh` applies the same comparison. + +## G3 hook +- The override bug is fixed: on the default branch a word counts as a branch only after `-b` or `-c` or when it names an existing branch; `--` marks the rest as paths. +- The PR number is parsed from `gh pr merge 7` (flags first, `-R owner/repo 7`, a PR URL). With no number the fix line is `bash scripts/pr-merge.sh --wait "$(gh pr view [] --json number --jq .number)"`; a branch word is pasted only when it matches `[A-Za-z0-9._/-]+`. +- Blocked with a test row each: `env -i git commit`, `timeout 5 git push origin `, `nice`, `sudo -u`, `git push --all`, `git push --mirror` (unless `--dry-run`), `gh api .../pulls/N/merge -X PUT`, `$g pr merge`. +- Known misses (listed in the guard header and the lesson): commands built from variables, functions, aliases or `$(...)`; scripts or tools that run git or gh themselves; git aliases and push config; merges from the GitHub site; a `gh api` merge that does not spell PUT; commits made by other tools. +- Fails open on broken JSON, empty stdin, a non-string command, a missing cwd, no jq, no awk, no git. A block uses internal code 42, mapped to exit 2. No jq: allows with one note (no pure-shell fallback, no python3). + +## G9 playbook and digest +- The digest prints its GitHub sections when the board file is empty, with `no board file set; nothing to read` for the board part. A missing `gh` prints a note and exits 0. +- Dropped from the digest: the `#gate-`, `#ws-` and size tag filters; the note about the team agent's own copy. + +## G4 owners, G5 queue, G6 changelog +- No `files/OWNERS.md.tpl`: `OWNERS.md` is a `hook` row on `lib/stamp/owners-seed.sh`. The check's `Fix:` line carries a paste-ready row. +- `check-owners.sh` reads one `| Path | What | Owner | Sponsor |` table; a first cell without backticks is a job row. A repo's own `scripts/*` is refused as "no owner yet". Table fields split on byte 037. +- Issue body headings are `###`, matching what `task.yml` writes. `issues-from-rows.sh` applies only the `ready` label; `--apply` creates all three labels first. An empty board file prints a note and exits 0 before the `gh` check. +- `release-notes.sh` is awk, no python3. `CHANGELOG.md` ends at `## [Unreleased]` with no entries, so `release-notes.sh Unreleased` refuses with "no entry for a user" until the first entry. + +## G7 merge guard and negctl +- Dropped: `--allow-ci-change` and its CI-path rules, the stale-rules refusal and `--refresh`, the kit merge-head variable, `--dry-run --all`, the separate owner-door list. +- Kept beyond the task row: newest run per check, the two-producer refusal, "the `changes` job must pass" (couples the guard to the workflow's job name), the UNKNOWN-mergeability wait, the 100-file cap when a door list is set. With a named approver, that login must approve unless they wrote the PR. +- Progress lines precede the refusal pair on stderr: a test reads the last two lines. +- A "red" is a load error when the output has no assertion line and the exit is 126 or 127, or it shows a syntax-error message. A silent red prints ``. + +## G8a pr-shape, G8b check and CI +- pr-shape reads env `PR_TITLE` (required), `PR_BODY` or `PR_BODY_FILE`, `BASE_SHA` (default `origin/`), `HEAD_SHA` (default `HEAD`); the diff is `BASE_SHA...HEAD_SHA`. Last stdout line `checks: N failed, M passed`; exit 0, 1, or 2 for bad input. The proof check needs a non-zero `Exit:` inside the `NEGATIVE CONTROL` block; `.kit.toml` counts as a behavior path. +- Dropped from pr-shape: the dash check, the evidence-branch check, the docs-layout check, the board-file special case, the product-path exemptions, board-ID minting. +- `ci.yml` takes `PRODUCT_ERE` for the `changes` path filter and exposes `outputs.product`. The owners gate is the BASE copy run with `$0` set to `scripts/check-owners.sh`; `pr-shape.sh` runs from a copy aside. `actions/checkout` is pinned by full sha with the tag in a trailing comment; shellcheck is pinned per platform with `sha256=`; both from `gh api`, none typed. +- Twin set: three `twin:` entries in both `ci.yml` and `check.sh` (`check-owners.sh`, `pr-shape.sh` with its four env inputs, the `test-*.sh` loop). `check.sh` runs every `scripts/test-*.sh` (about a minute on a full stamp). + +## Cross-cutting +- A `Fix:` line exists to be pasted. A value from the repo, the PR or `gh` enters a `Fix:` command only when it matches a narrow safe character set; otherwise the line is a plain instruction. Rule lines pass repo text through a filter that replaces unsafe characters with `?`. Each group's generated test has an injection case and runs every printed `Fix:` line through `bash -c`. + +## G10 integration +- The groups stamped together without a change to a manifest, a key name or a file mode: 39 rows, `check-owners.sh` passes on the tracked stamp (21 rows), a second run is all `unchanged`, `--check` exits 0. +- Engine fix: the `jsonmerge` entry check looked only in the first group of a matcher. After adopt wired its hooks the stamp's entry sat in a second `Bash` group and the next stamp appended it again. The merge now looks across every group with the same matcher. A test row pins it. +- Trust wording, settled against the vendor permissions page ("What runs before you trust a folder"): hooks in settings files are "Used" in both untrusted cases, only a parent folder trusted and `claude -p` or the SDK in a never-trusted folder. The three docs now say Claude Code uses the hook even in a folder not yet trusted, and no longer tell a teammate to trust it first. +- Doc claims checked against the real scripts: `release-notes.sh` with no argument refuses (exit 2) and shows no usage, so the table row now reads `release-notes.sh Unreleased` with `--help` for usage; `check.sh` reads the title from the first commit and an empty body when no PR is open, so `SKILL.md` now says to pass `--title` and `--body`; the guard lesson was re-synced with the guard header (adds the graphql merge, `git -c alias`, and the jq or awk off switch) and cut under the size limit. +- `tests/test-stamp-kitfree.sh` prints the failing lines of a generated test, not its tail. The generated negctl test failed once or twice in five runs under host load (loads above 100) and passed on a quiet host; not a template defect. +- The privacy section of `tests/test-stamp-e2e.sh` always runs the generic leak scan (home path, email, `op://`, bare hex) and fails on a hit. The denylist scan runs only when `STAMP_DENYLIST_FILE` is present and prints one SKIP line otherwise: the list belongs to one private repo, and a plain `run-all` on any machine must not go red. When it runs it scans the branch diff, commit messages, templates, fixtures, the proof and a stamped repo, and allows only `uses: owner/repo@<40-hex> # v...` and `sha256` marked 64-hex. +- `tests/test-stamp-refusals.sh` runs each distinct `Fix:` line through `bash -c` once, in a copy, with a 10 second alarm; `check.sh` forwards the checks' own refusals before its own pair, so that case accepts `pr-shape` as a second rule prefix. +- Exit codes seen across the scripts: usage errors exit 2 (`pr-merge`, `issues-from-rows`, `team-digest`, `check`, `release-notes` without a section), `negctl` exits 64 on usage and 2 on a dirty tracked tree; the suite pins them. + +## Security review fixes +- CI was three jobs in round 1; round 2 removed the `tests` job (see below). `changes` and `pr-shape` run only scripts copied from the base revision. A fork guard sits on each job. The base-has-no-copy fallback (use the PR's copy) is gone: that job fails and the first stamp pull request is merged by hand. `check.sh` runs the two jobs' commands locally, so the twin set is unchanged. +- The workflow file comes from the pull request, so `pr-merge.sh` now binds it: both `changes` and `pr-shape` from the workflow `CI`, and the harness files are default doors. `--door-paths` adds to the list (it no longer replaces an empty one). The `Door setting` table of the rules docs now reads "added to the harness's own files". +- `gh pr view --json reviews` reports `authorAssociation`, `commit.oid` and `author.login` per review (read from a real read-only call on a public repo). Bot reviewers can appear with a plain login (for example an app reviewer with a CONTRIBUTOR association), so the association test is the main bot filter and the `[bot]` and `app/` pattern is a second one. +- The self-copy check compares `scripts/pr-merge.sh` with `origin/:scripts/pr-merge.sh`. It cannot stop a pull request's copy that deleted the check; the protection there is that no `Fix:` line sends anyone to run that copy, and `scripts/` is a door. +- `stamp.sh`: the report of values in use is printed after the required-key checks, so a missing-owner refusal still ends in exactly two lines. It goes to stderr as `using: KEY=value (flag|lock|default|origin/HEAD)`; the tests that counted non-`unchanged` lines now also skip `using:` lines. +- The rule-line filter lost the colon in `check-owners.sh`, `issues-from-rows.sh` and `release-notes.sh`, and every filter cuts at 80 characters. A title with a colon now shows `?` in the digest and in progress lines (`fix? text`). `issues-from-rows.sh` prints `: ` itself so its own colon stays. +- A backslash inside a command word (`g\h`) is a documented miss of the guard; a backslash before the word is read. +- Gauntlet checker: its first draft compared gate files against a pristine stamp that had never been `git add`ed, so the comparison passed with nothing to compare. The hostile-repository row in Tier 1 caught it; the checker now fails check 9 when the pristine list is empty. +- `git diff` with `-c diff.external=` (an empty value) printed nothing instead of disabling the driver. The checker uses `--no-ext-diff --no-textconv` on every diff. + +## Security review round 2 fixes +- The `tests` job is gone from `ci.yml`; a stub comment says a repo adds its own once it has an ephemeral runner. The workflow header says nothing in these two jobs executes a file of the pull request. `check.sh` and the twin test lost the matching row. +- `pr-merge.sh`: runs are filtered to this pull request (`actions/runs` for the head, `pull_requests[].number`, then the rollup `detailsUrl` run id); the base must be the default branch; approvals older than the last `base_ref_changed` timeline event do not count; the changed files come from `pulls/<n>/files` (`filename` and `previous_filename`, 3000 cap, a read failure refuses). Every read must succeed and parse: a failed read refuses and is never read as "nothing found". +- Doors: the whole `.github/` directory, `scripts/`, `.claude/`, `OWNERS.md`, `AGENTS.md` and `CLAUDE.md` at any depth, `.mcp.json`, `docs/TEAM-WORKFLOW.md`, `.kit.toml`. Matching lowercases both sides. The self-copy check stops only an honest out-of-date copy (header and rules docs say so). +- Owners check: exact ownership, areas chosen by lowercase, lowercase collisions refused, NUL-delimited listing, names with a newline, control byte or non-ASCII byte refused with a plain instruction. `pr-shape.sh` refuses a head tree with two paths equal when lowercased. +- Board cells (the ID and login of a row) go through the same rule-line filter as titles in `issues-from-rows.sh`. +- `stamp.sh`: `--product-paths` and the tag list are tried as `grep -E` patterns on empty input and refused on exit 2 when they do not compile; a leading `*` in a product path is refused (it is a glob where the pattern wants a regex). +- Registry: the internal names `KIT_MARKER` and `KIT_PATTERN` of `lib/stamp.sh` are renamed (`AGENTS_MARKER`, `LEAK_PATTERN`) so `test-config-registry` finds no orphan row; no allowlist entry was added. `tests/test-adopt.sh` "known list complete against git log" is red on this branch before and after this work: it is a pre-existing red that PR #1189 fixes, not touched here. +- Gauntlet: the key goes into the probe container by name (`-e ANTHROPIC_API_KEY`), the echoed verdict is cut to capital letters, the image runs as the non-root user `node` that owns `/work`, and the seed is copied with `cp -R` (no preserved host ownership). The run record and the README say the scrub matches the exact key only and the key is rotated after every round. The gauntlet `gh` shim now answers the four `gh api` reads of the merge guard. The container path is still NOT executed on the build host; these changes are unverified until the operator's first run. +- Runs of this pull request: the `actions/runs` documentation says `pull_requests` lists every open pull request that shares the head sha or branch, not the one that triggered the run. A filter on "this number appears" would let a second pull request on the same head (with a weak base) lend its green runs, so a run counts only when its `pull_requests` list is exactly this pull request. A legitimate second pull request on the same head is refused with "has not passed"; close it. +- The `gh` fields the guard reads were confirmed, not guessed: `gh pr view --help` for the top-level names; one read-only `gh pr view --json reviews,statusCheckRollup` on a public PR for the sub-fields (`reviews[].author.login`, `.authorAssociation`, `.commit.oid`, `.state`, `.submittedAt`; check run `detailsUrl`, `workflowName`, `name`, `status`, `conclusion`, `startedAt`, `completedAt`); `gh api` reads on the same repo for `workflow_runs[].id`, `.path`, `.pull_requests[].number`, `pulls/<n>/files` `.filename`, `pulls/<n>` `.head.sha`; the REST description for `previous_filename`, the `head_sha` and `event` query parameters; the event documentation for the `base_ref_changed` timeline event and its `created_at`. No live example of a rename or a base change was available on the public repo; those two rest on the documentation. +- `check.sh` and `pr-shape.sh` read the changed paths and the head tree NUL-delimited. A path with a newline counts as a product path in `check.sh` and is refused as a collision in `pr-shape.sh`. diff --git a/docs/reference/FEATURES.md b/docs/reference/FEATURES.md index 2c30f9d8a..ac8d08ded 100644 --- a/docs/reference/FEATURES.md +++ b/docs/reference/FEATURES.md @@ -13,35 +13,36 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | Command | Trigger | Description | Specs | Tests | |---|---|---|---|---| | `/kit:absorb` | `[H/I]` | Maintainer-only: audit the kit's upstream sources (Credits drift + seed-rescan) and draft a dated, proposal-only absorption report. Does no… | SPEC-004, SPEC-007, SPEC-009 +7 | test-command-emit-sweep.sh, test-hooks.sh, test-meta-spec-depth.sh +1 | -| `/kit:adopt` | `[H/I]` | Adopt the current (or a target) repo into the dwarves-kit operate-contract: write a small AGENTS.md pointer (never over a repo's own file) … | SPEC-004, SPEC-013, SPEC-014 +44 | test-adopt.sh, test-clean-room.sh, test-command-emit-sweep.sh +24 | -| `/kit:assign` | `[H/I]` | Turn a backlog item (ID-NNN) into a scoped goal draft and route it into the right WORKFLOW lane. Writes .claude/goals/, never executes. | SPEC-006, SPEC-007, SPEC-024 +35 | test-context-note-shape.sh, test-hooks.sh, test-meta-contract.sh +5 | +| `/kit:adopt` | `[H/I]` | Adopt the current (or a target) repo into the dwarves-kit operate-contract: write a small AGENTS.md pointer (never over a repo's own file) … | SPEC-004, SPEC-013, SPEC-014 +45 | test-adopt.sh, test-clean-room.sh, test-command-emit-sweep.sh +27 | +| `/kit:assign` | `[H/I]` | Turn a backlog item (ID-NNN) into a scoped goal draft and route it into the right WORKFLOW lane. Writes .claude/goals/, never executes. | SPEC-006, SPEC-007, SPEC-024 +36 | test-context-note-shape.sh, test-hooks.sh, test-meta-contract.sh +5 | | `/kit:battery` | `[H/I]` | The full independent-verification battery for a finished branch: a fresh-context acceptance verifier that RE-EXECUTES the verification comm… | SPEC-239, SPEC-244, SPEC-245 +11 | test-battery-gate.sh, test-board-work.sh, test-boundary-lint.sh +12 | | `/kit:debug` | `[H/I]` | Systematic debug loop: root cause before any fix. Four phases, an evidence ledger, the 3-fix architecture wall. Use for any bug, defect, re… | SPEC-006, SPEC-013, SPEC-014 +19 | test-command-triggers.sh, test-config-registry.sh, test-doc-figures.sh +8 | -| `/kit:design` | `[H/I]` | Opt-in interactive solution-design beat between /think and /spec. Use when the operator wants to shape HOW to build after the idea passed /… | SPEC-003, SPEC-004, SPEC-005 +162 | test-anomalies-advisor.sh, test-board-mirror-cleanup.sh, test-ceremony-fits-diff.sh +40 | +| `/kit:design` | `[H/I]` | Opt-in interactive solution-design beat between /think and /spec. Use when the operator wants to shape HOW to build after the idea passed /… | SPEC-003, SPEC-004, SPEC-005 +163 | test-anomalies-advisor.sh, test-board-mirror-cleanup.sh, test-ceremony-fits-diff.sh +40 | | `/kit:devs-team` | `[H/I]` | Parallel multi-lens critique of a solution design (the active spec if present, else the decision brief). Dispatches 5 engineering lenses, m… | SPEC-016, SPEC-018, SPEC-019 +14 | test-gate-vocab-recording.sh, test-meta-review-verifiers.sh, test-meta-spec-depth.sh +1 | | `/kit:dispatch` | `[H/I]` | Fire several disjoint VALIDATED specs concurrently, each in its own worktree, then converge. Cross-goal fan-out behind a disjointness gate … | SPEC-002, SPEC-016, SPEC-017 +114 | test-advisor.sh, test-agent-effectiveness.sh, test-attempt-state-race.sh +52 | -| `/kit:docs` | `[H/I]` | Update all project documentation to match the current codebase. Cross-references the diff against every doc file and fixes drift. | SPEC-001, SPEC-002, SPEC-003 +292 | conform.sh, test-active-spec-pick.sh, test-adapters.sh +161 | +| `/kit:docs` | `[H/I]` | Update all project documentation to match the current codebase. Cross-references the diff against every doc file and fixes drift. | SPEC-001, SPEC-002, SPEC-003 +293 | conform.sh, test-active-spec-pick.sh, test-adapters.sh +172 | | `/kit:draft-agent` | `[H/I]` | Meta-agent agent-builder. From a one-line description, generates a new subagent definition OR a mega-goal sub-goal file and (by default) in… | SPEC-089, SPEC-108, SPEC-139 +1 | test-agent-effectiveness.sh, test-command-emit-sweep.sh, test-meta-agent.sh +1 | -| `/kit:execute` | `[H/I]` | Whole-spec execution with verification. Dispatches one builder for the whole spec, verifies every task's criteria once at the end, retries … | SPEC-001, SPEC-003, SPEC-004 +82 | test-board-work.sh, test-break-it.sh, test-config-registry.sh +29 | +| `/kit:execute` | `[H/I]` | Whole-spec execution with verification. Dispatches one builder for the whole spec, verifies every task's criteria once at the end, retries … | SPEC-001, SPEC-003, SPEC-004 +83 | test-board-work.sh, test-break-it.sh, test-config-registry.sh +29 | | `/kit:explain` | `[H/I]` | Turn a merged change into a literate-diff explainer a human READS to understand: background -> goal + intuition -> a prose-ordered diff -> … | SPEC-050, SPEC-060, SPEC-094 +25 | test-boundary-lint.sh, test-clean-room.sh, test-command-emit-sweep.sh +13 | | `/kit:feature-map` | `[H/I]` | Build or refresh a source-cited, agent-checkable feature inventory for ANY target project you point it at: per-module spec + a top-level ch… | SPEC-218, SPEC-219, SPEC-220 +2 | test-command-emit-sweep.sh | -| `/kit:gauntlet` | `[H/I]` | Probe-convergence engine: a bounded-revise loop that converges an ARTIFACT (docs, a runbook, a spec, an API surface) toward a FIXED OUTCOME… | SPEC-226, SPEC-227, SPEC-228 +10 | test-config-registry.sh, test-doc-figures.sh, test-gauntlet-consumer.sh +6 | +| `/kit:gauntlet` | `[H/I]` | Probe-convergence engine: a bounded-revise loop that converges an ARTIFACT (docs, a runbook, a spec, an API surface) toward a FIXED OUTCOME… | SPEC-226, SPEC-227, SPEC-228 +11 | test-config-registry.sh, test-doc-figures.sh, test-gauntlet-consumer.sh +7 | | `/kit:greenlight` | `[H/I]` | Post-push CI-green lane: snapshots an open PR's checks via gh, classifies each failure real vs flaky, fixes real ones via the kit:fix-agent… | SPEC-019, SPEC-217, SPEC-369 | test-audit-verdict-grammar.sh, test-gate-ledger-actions.sh, test-ql-verdict.sh | | `/kit:grill` | `[H/I]` | Universal intake interview: one type-shaped question at a time, each with a recommended answer, until the task is actually understood. Answ… | SPEC-058, SPEC-059, SPEC-063 +27 | test-anomalies-advisor.sh, test-ceremony-lens.sh, test-config-stamp.sh +17 | | `/kit:kit-health` | `[H/I]` | Run a self-assessment of the kit against its own philosophy. Checks file count, hook performance, source citations, and structural health. | SPEC-001, SPEC-002, SPEC-004 +18 | test-command-emit-sweep.sh, test-meta-docs-registry.sh, test-meta-goal-ledger.sh +4 | | `/kit:mega` | `[H/I]` | Turn a multi-objective destination into a sequenced roadmap of dependent sub-goals: decompose, front-load every clarification once, set the… | SPEC-034, SPEC-036, SPEC-088 +53 | test-adapters.sh, test-advisor.sh, test-bin-forwarders.sh +44 | -| `/kit:next` | `[H/I]` | Pick up the next undone task from the spec. Loads context, shows acceptance criteria, lets you drive the implementation. | SPEC-001, SPEC-002, SPEC-003 +146 | smoke.sh, test-active-spec-pick.sh, test-adapters.sh +95 | +| `/kit:next` | `[H/I]` | Pick up the next undone task from the spec. Loads context, shows acceptance criteria, lets you drive the implementation. | SPEC-001, SPEC-002, SPEC-003 +147 | smoke.sh, test-active-spec-pick.sh, test-adapters.sh +103 | | `/kit:onboard` | `[H/I]` | Guided first-run: detect the install mode, offer /kit:adopt for this repo, pick modules, capture the consumer knobs that make them work, di… | SPEC-199, SPEC-213, SPEC-232 +3 | test-clean-room.sh, test-command-emit-sweep.sh, test-onboard-detect.sh | | `/kit:pitch` | `[H/I]` | Assemble an outward buy-in doc from what a gated run already produced: the spec, the proof-of-done, the implementation-notes, and the gate … | SPEC-140, SPEC-141, SPEC-193 +7 | test-gate-validate-round.sh, test-outcome-emit-sweep.sh, test-pitch.sh +2 | | `/kit:prototype` | `[H/I]` | Opt-in throwaway-spike beat beside /kit:design. Builds throwaway code that answers ONE design question: a logic/state model driven by hand … | SPEC-075, SPEC-206, SPEC-207 +3 | test-picture-section.sh | | `/kit:quiz-gate` | `[H/I]` | The ★-tap NUDGE before merging a significant+worthy gate PR: a 5-question quiz built from the ACTUAL diff+tests, handed to the operator's… | SPEC-125, SPEC-127, SPEC-136 +3 | test-boundary-lint.sh, test-install-modules.sh, test-kit-contract.sh +3 | | `/kit:retro` | `[H/I]` | Run a retrospective after shipping. Captures what worked, what didn't, and action items for the next cycle. Outputs to docs/retro/RETRO.md. | SPEC-002, SPEC-003, SPEC-006 +48 | smoke.sh, test-command-emit-sweep.sh, test-gate-vocab-recording.sh +10 | | `/kit:review-team` | `[H/I]` | Parallel code review with 3 specialist lenses plus the kit-default kit:advisor extra lens. Dispatches the security, architecture, and test-… | SPEC-002, SPEC-003, SPEC-007 +50 | test-advisor.sh, test-config-registry.sh, test-every-step-review.sh +10 | -| `/kit:review` | `[H/I]` | Paranoid code review. Security, architecture, regressions, missing tests, edge cases. Produces actionable TODOS. | SPEC-001, SPEC-002, SPEC-003 +155 | smoke.sh, test-adopt.sh, test-advisor.sh +90 | +| `/kit:review` | `[H/I]` | Paranoid code review. Security, architecture, regressions, missing tests, edge cases. Produces actionable TODOS. | SPEC-001, SPEC-002, SPEC-003 +156 | smoke.sh, test-adopt.sh, test-advisor.sh +91 | | `/kit:ship` | `[H/I]` | Ship: review gate, tests, version bump, changelog, conventional commit, docs update, PR. Complete pipeline from done to merged. | SPEC-001, SPEC-002, SPEC-003 +111 | test-active-spec-pick.sh, test-adopt.sh, test-board-mirror.sh +64 | | `/kit:spec-validate` | `[H/I]` | Adversarial review of a spec before implementation. 7 specialist lenses attack the spec from different angles (6 advisory, 1 blocking on th… | SPEC-002, SPEC-003, SPEC-004 +70 | test-command-emit-sweep.sh, test-design-record.sh, test-every-step-review.sh +10 | -| `/kit:spec` | `[H/I]` | Generate a development spec from a feature idea or decision brief. Creates docs/specs/ with structured requirements. | SPEC-001, SPEC-002, SPEC-003 +241 | test-active-spec-pick.sh, test-audit-verdict-grammar.sh, test-bin-forwarders.sh +109 | -| `/kit:start` | `[H/I]` | Detect project state and suggest the right next command. The entry point for any session. | SPEC-002, SPEC-003, SPEC-004 +94 | test-anomalies-advisor.sh, test-audit-cadence.sh, test-board-add.sh +95 | +| `/kit:spec` | `[H/I]` | Generate a development spec from a feature idea or decision brief. Creates docs/specs/ with structured requirements. | SPEC-001, SPEC-002, SPEC-003 +242 | test-active-spec-pick.sh, test-audit-verdict-grammar.sh, test-bin-forwarders.sh +110 | +| `/kit:stamp` | `[H/I]` | Write a kit-free agent harness into a repo whose team does not run the kit: self-contained AGENTS.md and a people's copy, a project hook th… | SPEC-066, SPEC-108, SPEC-120 +9 | run-all.sh, test-board-brief.sh, test-board-health.sh +28 | +| `/kit:start` | `[H/I]` | Detect project state and suggest the right next command. The entry point for any session. | SPEC-002, SPEC-003, SPEC-004 +95 | test-anomalies-advisor.sh, test-audit-cadence.sh, test-board-add.sh +96 | | `/kit:test-plan-review-team` | `[H/I]` | Parallel multi-lens adversarial critique of a spec's test plan (the ## Test plan section), with a bounded revise loop that tightens it. Dis… | SPEC-031, SPEC-052, SPEC-062 +14 | test-meta-docs-registry.sh, test-meta-review-verifiers.sh, test-meta-vmodel-dispatch.sh +3 | | `/kit:test-plan` | `[H/I]` | Derive a test-case coverage matrix from a spec's acceptance criteria before /kit:execute. Writes a `## Test plan` section into the active s… | SPEC-004, SPEC-016, SPEC-018 +38 | test-ceremony-lens.sh, test-e2e.sh, test-gate-ledger-inherit.sh +15 | | `/kit:test-write` | `[H/I]` | Turn a SOLID-verdict `## Test plan critique` into real, executing test code via `kit:test-writer`, one case per matrix row. Never dispatche… | SPEC-203, SPEC-227, SPEC-237 +2 | test-test-writer-contract.sh | @@ -50,7 +51,7 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | `/kit:verify` | `[H/I]` | Re-run the test levels (kit:task-verifier + kit:integration-verifier + kit:acceptance-verifier, plus kit:system-verifier only with --full) … | SPEC-002, SPEC-003, SPEC-006 +57 | test-board-digest.sh, test-board-hermes.sh, test-board-lock-required.sh +35 | | `/kit:visual-team` | `[H/I]` | Parallel multi-lens critique of a visual/UI design. Dispatches 5 design lenses, merges findings, reports a verdict. Report-only, downstream… | SPEC-016, SPEC-018, SPEC-019 +12 | test-command-emit-sweep.sh, test-meta-review-verifiers.sh, test-meta-spec-depth.sh +1 | | `/kit:wayfind` | `[H]` | Plan a chunk of work too big for one agent session as a shared decision map: map.md + typed decision tickets in the mega-goal folder, resol… | SPEC-206, SPEC-207, SPEC-217 +2 | - | -| `/kit:wrap` | `[H/I]` | The session-scoped landing step after ship: flips board rows, merges green PRs, checks deploys, tidies worktrees, prints the skim-first rep… | SPEC-020, SPEC-060, SPEC-072 +75 | test-bin-forwarders.sh, test-board-lock-required.sh, test-board-work.sh +55 | +| `/kit:wrap` | `[H/I]` | The session-scoped landing step after ship: flips board rows, merges green PRs, checks deploys, tidies worktrees, prints the skim-first rep… | SPEC-020, SPEC-060, SPEC-072 +76 | test-bin-forwarders.sh, test-board-lock-required.sh, test-board-work.sh +63 | ## Agents @@ -134,7 +135,7 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | `post-compact-reinject.sh` | `[E]` | SessionStart | SessionStart hook (matcher compact) that re-injects the critical project rules compaction strips from context. | SPEC-003, SPEC-010, SPEC-034 +5 | test-active-spec-pick.sh, test-hooks.sh, test-install-modules.sh +2 | | `pre-compact-backup.sh` | `[E]` | PreCompact | PreCompact hook that saves a structured snapshot of the session before auto-compaction. | SPEC-010, SPEC-084, SPEC-334 +3 | test-active-spec-pick.sh, test-hooks.sh, test-install-modules.sh +3 | | `prose-rag.sh` | `[E]` | UserPromptSubmit | UserPromptSubmit shim that injects prior-note recall when PROSE_RAG_INJECT=1; dormant otherwise. | SPEC-194, SPEC-204, SPEC-249 +6 | smoke.sh, test-adopt.sh, test-bin-forwarders.sh +8 | -| `safety-gate.sh` | `[E]` | PreToolUse | PreToolUse hook that blocks destructive deletes, direct pushes to main or master, and force-pushes. | SPEC-003, SPEC-014, SPEC-019 +15 | test-anchor-module-gate.sh, test-codex-hooks.sh, test-codex-manifest.sh +12 | +| `safety-gate.sh` | `[E]` | PreToolUse | PreToolUse hook that blocks destructive deletes, direct pushes to main or master, and force-pushes. | SPEC-003, SPEC-014, SPEC-019 +16 | test-anchor-module-gate.sh, test-codex-hooks.sh, test-codex-manifest.sh +12 | | `secrets-guard.sh` | `[E]` | PreToolUse | PreToolUse hook that blocks the agent from reading secret files, with the path canonicalized first. | SPEC-014, SPEC-084, SPEC-288 +4 | test-codex-hooks.sh, test-codex-manifest.sh, test-entry.sh +6 | | `ship-gate.sh` | `[E]` | PreToolUse | PreToolUse hook that refuses a push onto a default branch, or a push or PR when the spec lane has a required gate with no ran or override e… | SPEC-006, SPEC-042, SPEC-044 +88 | test-active-spec-pick.sh, test-anchor-module-gate.sh, test-ceremony-fits-diff.sh +52 | | `slop-cleaner.sh` | `[E]` | Stop | Stop hook that nudges, never blocks, on bloat signals in recently modified source files after long sessions. | SPEC-013, SPEC-014, SPEC-084 +4 | test-anchor-module-gate.sh, test-codex-hooks.sh, test-egress-visible.sh +3 | @@ -146,7 +147,7 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | Verb | Trigger | Source | Description | Specs | Tests | |---|---|---|---|---|---| -| `adopt pointer` | `[V]` | `lib/adopt.sh` | inject the small AGENTS.md pointer, proof marker and CLAUDE.md loader into a target repo, hash-safe and idempotent | SPEC-047, SPEC-048, SPEC-049 +14 | test-adopt.sh, test-clean-room.sh, test-gate-opt-in.sh +12 | +| `adopt pointer` | `[V]` | `lib/adopt.sh` | inject the small AGENTS.md pointer, proof marker and CLAUDE.md loader into a target repo, hash-safe and idempotent | SPEC-047, SPEC-048, SPEC-049 +15 | test-adopt.sh, test-clean-room.sh, test-gate-opt-in.sh +15 | | `board state-check` | `[V]` | `lib/board/state_check.py` | validate the stored state values of a repo's own registry file; block new drift at commit, report existing drift | SPEC-428 | test-state-check.sh | | `board work` | `[V]` | `lib/board/work.sh` | one table of who is on what, how far along and who is stuck, joined at call time from board, git, Orca and the run ledger; read-only | SPEC-366, SPEC-370, SPEC-430 | test-board-work.sh, test-mega-box.sh, test-orchestrate-orca.sh | | `check-edit` | `[V]` | `lib/gate/check-edit.sh` | check-edit signal for execute: did the build weaken the checks the spec names, from a base ref diff | SPEC-369 | test-whole-spec-dispatch.sh | @@ -158,5 +159,6 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | `push-refs` | `[V]` | `lib/gate/push-refs.sh` | fail-closed parser that names which refs a shell command pushes, used by the ship-gate | SPEC-044, SPEC-045, SPEC-048 +43 | test-active-spec-pick.sh, test-clean-room.sh, test-codex-hooks.sh +37 | | `recheck-sample decide` | `[V]` | `lib/gate/recheck-sample.sh` | decide and record whether an execute run rechecks its end-verifier PASSes, keyed on the rid | SPEC-369, SPEC-421 | test-whole-spec-dispatch.sh | | `spec-depth` | `[V]` | `lib/spec/spec-depth.sh` | read and check the Depth line of a spec header: level, wants and check verbs | SPEC-292, SPEC-372, SPEC-379 | test-meta-spec-depth.sh, test-meta.sh, test-research-arch-contract.sh +2 | +| `stamp` | `[V]` | `lib/stamp.sh` | write a kit-free agent harness into a repo as plain files the repo owns, idempotent, never overwriting an edited file | SPEC-066, SPEC-108, SPEC-120 +9 | run-all.sh, test-board-brief.sh, test-board-health.sh +28 | | `stats ceremony` | `[V]` | `lib/stats/src/stats/ceremony.py` | ceremony lens: gate work and subagent dispatches versus progress and catches, per gate, from the run ledger | SPEC-367 | test-ceremony-lens.sh | diff --git a/docs/reference/architecture.md b/docs/reference/architecture.md index 9b19502a6..8fbd7516d 100644 --- a/docs/reference/architecture.md +++ b/docs/reference/architecture.md @@ -154,6 +154,7 @@ Every command and agent mapped to its V-model arm, grouped so the left side (BUI | `/kit:start` | command | Session entry | cross-phase | Detects project state and recommends the right next command; never executes | | `/kit:onboard` | command | First-run onboarding | cross-phase | Interactive first-run orchestrator: detects install mode via `lib/onboard-detect.sh`, offers `/kit:adopt`, picks modules (bridging the plugin path's missing `--with`), captures consumer knobs from the SPEC-198 registry, discloses plugin-path gaps, ends with a two-idea tour (lane, proof of done) plus a menu; CALLS start/adopt/config, reimplements none (ADR-0034 fence); previews + confirms every write | | `/kit:adopt` | command | Repo onboarding | cross-phase | Writes a small AGENTS.md pointer (never over a repo's own file) + proof marker + a CLAUDE.md pointer into a target repo (idempotent, via `lib/adopt.sh`); wires the classifiers so the ship-gate engages there | +| `/kit:stamp` | command | Repo onboarding | cross-phase | Writes a kit-free agent harness into a target repo (idempotent, via `lib/stamp.sh`): rules docs, a project hook, a CI job with its local twin, owners, a merge guard, negative control, work queue, changelog and digest scripts; the files are repo-owned and run with no kit installed. | | `/kit:kit-health` | command | Maintainer audit | cross-phase | Self-assessment against PHILOSOPHY.md; run before tagging; not part of the normal cycle | | `/kit:absorb` | command | Upstream maintenance | cross-phase | Audits Credits drift + seed-rescan; proposal-only; maintainer-only connective tissue | | `/kit:debug` | command | Bug lane (off-cycle) | cross-phase | Off-cycle loop: root cause before any fix; evidence ledger; 3-fix architecture wall | diff --git a/docs/specs/SPEC-425-team-stamp.md b/docs/specs/SPEC-425-team-stamp.md new file mode 100644 index 000000000..6c1194931 --- /dev/null +++ b/docs/specs/SPEC-425-team-stamp.md @@ -0,0 +1,526 @@ +# Spec: team stamp, a kit-free agent harness written into a repo +Generated: 2026-11-25 +Status: DRAFT +Lane: full (the build adds a verb that writes enforcement scripts, a hook, a CI workflow and a merge guard into other people's repos) +Depth: research (repo: how adopt writes, hashes and refuses today, and what the hand-fitted repo's files really contain) + research (outside: the current Claude Code hook and skill contracts, fetched, not recalled) +Type: spec-feature +File: `docs/specs/SPEC-425-team-stamp.md` +References: `lib/adopt.sh` (imitate: never overwrite, hash-decided drift line, jq MERGE into `.claude/settings.json`, symlink refusal through `lib/config/safe-path.sh`, `--check`/`--dry-run`/`--refresh`); `lib/adopt/known-hashes.sh` (imitate: the known-hash list is regenerated from history, never typed); `lib/gate/negctl.sh` (the kit's negative control; the stamped `scripts/negctl.sh` is its kit-free sibling, see Decision DEC-6); `commands/gauntlet.md` (the engine that records the Done run); `docs/briefs/DECISION-BRIEF-team-stamp.md` (the design contract, build step 3). + +## Problem + +One operator runs the kit. Three teammates do not, and their coding agents do most of the work. A private product repo was fitted by hand (about twenty files over two days) and the teammates' agents then followed the rules with no kit: four PRs arrived with a proof file, a board link and a tagged changelog line, and CI caught the one rule an agent missed. + +The kit cannot produce that harness. `adopt` writes a pointer that sends an agent to a path under the kit, and every kit gate runs only where the plugin is installed. A rule that lives only in the kit binds the operator and nobody else. Doing the hand fit again for the next repo costs two days and drifts from the first copy. + +## Terms + +- stamp: the verb `lib/stamp.sh` and the set of plain files it writes. The files are repo-owned copies. After the write the kit has no part in them. +- kit-free: a generated file reads, runs and tests with no kit on the machine: no kit path in its text, no kit binary on `PATH`, no kit directory under `HOME`. +- lock: `.claude/team-stamp.lock`, the stamp's own record of what it wrote (stamp version, parameter values, one sha256 per file). It is plain text and kit-free. It exists so "the repo edited this file" can be told from "this is an older stamp copy" (see DEC-3). +- door: a path list where a change needs a second person's approval before merge. +- twin: `scripts/check.sh`, the local script that runs the CI job's checks with the same inputs. + +Canonical home for new terms: the repo glossary `CONTEXT.md` (stamp, kit-free, lock, door, twin), written with this spec. + +## Solution + +### Approaches considered + +1. A new verb `lib/stamp.sh` next to `lib/adopt.sh`, with the files as templates under `templates/team-stamp/`, rendered with a small value set. Tradeoff: one more verb and about 45 template files to keep true; the generated files are plain, so the kit never needs to be present after the write. +2. Extend `adopt` with `--team`. Tradeoff: `adopt` is the kit-pointer verb and the adopt-pointer row is changing it right now; a second personality in one 645-line script doubles its refusal surface, and a stamp must work on a repo the kit never adopted. +3. A template repo or `gh repo create --template`. Tradeoff: fixes only new repos, carries no drift report and no upgrade path, and a template repo is one more thing to keep current. + +### Chosen approach + why + +Approach 1. The brief says "a new verb next to adopt". It shares adopt's discipline (never overwrite, hash-decided drift, jq merge, symlink refusal) by copying the shape, not by sourcing adopt's code, so the pointer worker's edits to `lib/adopt.sh` cannot break it and it cannot break them. The one shared surface is the first line of `AGENTS.md` (the kit marker): the stamp reads line 1 of `lib/adopt/AGENTS.pointer.md` at stamp time and refuses if that line does not start with `<!-- kit:agents-pointer`. That is read-only and survives the pointer rewrite. + +### Extensibility & boundaries + +- The dimension that grows is the file set: a new generic piece is one template plus one manifest row plus its test, in its own `manifest.d/NN-<group>.tsv`. The engine knows no file by name. +- Units: `lib/stamp.sh` (arguments, values, render, write, lock, drift, refresh), `templates/team-stamp/` (content only), `manifest.d/*.tsv` (what goes where). A template never contains logic the engine needs; the engine never contains repo-rule text. + +## Picture + +``` + operator, with the kit teammate's agent, no kit + ───────────────────── ────────────────────────── + bash lib/stamp.sh [flags] <repo> + │ reads + v + templates/team-stamp/ (stamp writes once, then steps out) + manifest.d/*.tsv files/** ──render values──> <repo>/ + │ AGENTS.md docs/TEAM-WORKFLOW.md L1 advice + │ jq merge (never rewrite) .claude/settings.json ──┐ + v scripts/agent-guard.sh <┘ L2 hook + .claude/team-stamp.lock (sha256 per file) scripts/agent-lessons.sh .claude/memory/ + .github/workflows/ci.yml L3 CI + scripts/{pr-shape,check,check-owners, + pr-merge,negctl,issues-from-rows, + release-notes,team-digest}.sh L3/L4 + OWNERS.md CHANGELOG.md .kit.toml ... + + refusal at L2 or L3: <tool>: <the rule, one line> + Fix: <the command, next line> +``` + +## Design + +### Vendor contract (fetched 2026-11-25, not recalled) + +Sources: https://code.claude.com/docs/en/hooks and https://code.claude.com/docs/en/skills. Both fetches succeeded; each page was larger than one read (hooks 293,835 characters, skills 121,231), so each answer below says which part was read. A statement the fetch did not show is marked UNCONFIRMED and the build re-reads it before relying on it. + +| Generated file depends on | Contract text (verbatim where quoted) | +|---|---| +| `.claude/settings.json` structure | `hooks` > event name > list of matcher groups, each `{ "matcher": "Bash", "hooks": [ { "type": "command", "command": "<shell command>" } ] }`. `type` is one of `command`, `http`, `mcp_tool`, `prompt`, `agent`. The page example uses `${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh` as the command. | +| project root variable | "`${CLAUDE_PROJECT_DIR}`: the project root where the session started." In a linked worktree it "still points at the project root where the session started", so the stamped scripts resolve the repo from the hook's `cwd` field when they need the worktree. | +| `scripts/agent-guard.sh` input | The hook receives JSON on stdin with common fields `session_id`, `cwd`, `permission_mode`, `transcript_path`, `hook_event_name`, and for PreToolUse "The `tool_name`, `tool_input`, and `tool_use_id` fields are event-specific." For Bash, `tool_input.command` is "The shell command to execute". | +| `scripts/agent-guard.sh` decision | "**Blocking error**: your hook exits 2. On events that can block, Claude Code stops the action." For PreToolUse, "A hook that blocks by exiting 2 routes the same way as `deny`: Claude sees the stderr message as the denial reason." Exit 0 with no output "means no decision; normal permission flow applies." "Claude never sees stderr from a hook that exits 0." Any other exit code is a non-blocking error: the action goes ahead. Structured form: `{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"..."}}` ("`deny` prevents the tool call"; the reason "shown to Claude"). The stamp uses exit 2 with the two lines on stderr, so the guard needs no JSON writer and works with `jq` absent. | +| `scripts/agent-lessons.sh` output | SessionStart "Claude Code adds plain-text stdout as context that Claude can see and act on." Its matcher filters on `source`: `startup`, `resume`, `clear`, `compact`, `fork`. "A hook's `additionalContext`, `systemMessage`, and `initialUserMessage` strings, and its plain stdout, are capped at 10,000 characters." Over the cap, "Claude Code saves the output to a file in the session directory" and shows a path plus a preview of "up to the first 2,000 characters", and "doesn't ask Claude to read the file". The generated `MEMORY.md` index therefore stays under 8,000 characters and `agent-lessons.sh` truncates with a notice at 9,000. | +| `.claude/skills/ship-pr/SKILL.md` | Project path `.claude/skills/<skill-name>/SKILL.md`, loaded in "Sessions in this repository" ("Commit it so your team gets it too"). Frontmatter is read "only when the opening `---` is the file's first line". Fields: `name` ("Defaults to the directory name"), `description` ("What the skill does and when to use it"; description plus `when_to_use` is "truncated at 1,536 characters"), `disable-model-invocation`, `user-invocable`, `allowed-tools`. "Claude Code ignores a field it doesn't recognize without reporting an error", so a misspelled key fails silently and the test must check the exact key names. "Only `description` is recommended." The skill ships with `name` and `description` only: no `allowed-tools` (a project skill's `allowed-tools` applies even in a folder never trusted, so the stamp grants none). | +| Trust of a project hook (read 2026-11-25) | https://code.claude.com/docs/en/permissions, "What runs before you trust a folder": the row "Hooks in settings files, the `env` block and helper commands ..." reads "Used" in both columns, the two situations in which the folder itself is not trusted: "you trusted only a parent folder, or you ran `claude -p` or the SDK there, which never shows the trust dialog". The same page: "Claude Code shows the trust dialog in interactive terminal sessions, but not in `claude -p` or SDK sessions." So a project hook in `.claude/settings.json` runs without the teammate trusting the folder first, and the generated docs say exactly that; frontmatter hooks of a project subagent are "Not used" untrusted and the stamp ships none. | + +### Generated files + +One row per brief table row. "Value" names the stamp parameter the file takes; "agnostic" means byte-identical in every repo. Source templates live under `templates/team-stamp/files/<target path>` (a `.tpl` suffix when the file takes a value). Each script's test is generated beside it as `scripts/test-<name>.sh` and is itself kit-free. Kit-side tests are `tests/test-stamp-<group>.sh`. + +| # | Brief row | Target path | Source template | Generated test | Agnostic or value | Group | +|---|---|---|---|---|---|---| +| 1 | Agent rules | `AGENTS.md` | `files/AGENTS.md.tpl` | `tests/test-stamp-rules.sh` (kit side: line 1 marker, section anchors, no kit path, closing section) | value: default branch, door table, tags, product paths | G1 | +| 2 | People's copy | `docs/TEAM-WORKFLOW.md` | `files/docs/TEAM-WORKFLOW.md.tpl` | `tests/test-stamp-rules.sh`; parity run by `scripts/test-pr-shape.sh` | same values as row 1 | G1 | +| 3 | Command guard | `scripts/agent-guard.sh` | `files/scripts/agent-guard.sh.tpl` | `scripts/test-agent-guard.sh` (from `files/scripts/test-agent-guard.sh.tpl`) | value: default branch | G3 | +| 4 | Command guard | `.claude/settings.json` | `files/.claude/settings.json` (a `jsonmerge` row: checked by entry, never by file hash) | `tests/test-stamp-hook.sh` (merge keeps foreign keys, idempotent) | agnostic | G3 | +| 5 | Lessons | `scripts/agent-lessons.sh` | `files/scripts/agent-lessons.sh` | `scripts/test-agent-lessons.sh` (from `files/scripts/test-agent-lessons.sh`) | agnostic | G2 | +| 6 | Lessons | `.claude/memory/MEMORY.md` plus five seed notes | `files/.claude/memory/*.md` (`seed` rows: created when absent, never drift-checked after) | `scripts/test-agent-lessons.sh` (index links resolve, size under cap) | agnostic | G2 | +| 7 | Playbook | `.claude/skills/ship-pr/SKILL.md` | `files/.claude/skills/ship-pr/SKILL.md.tpl` | `tests/test-stamp-playbook.sh` (frontmatter keys exact, every command in it exists as a generated script) | value: default branch | G9 | +| 8 | PR shape | `scripts/pr-shape.sh` | `files/scripts/pr-shape.sh.tpl` | `scripts/test-pr-shape.sh` (from a `.tpl`) | value: tags, product paths, board file, default branch | G8a | +| 9 | PR shape | `.github/workflows/ci.yml` | `files/.github/workflows/ci.yml.tpl` | `scripts/test-check.sh` (twin parity), `actionlint` when present | agnostic: always `runs-on: [self-hosted]` | G8b | +| 10 | Local check | `scripts/check.sh` | `files/scripts/check.sh.tpl` | `scripts/test-check.sh` (from a `.tpl`) | value: tags, product paths | G8b | +| 11 | Owners | `OWNERS.md` | `hook` row: `lib/stamp/owners-seed.sh`, built from the merged manifest (a `seed` file, repo-owned after the first write) | `tests/test-stamp.sh` (the seed lists every script), and in G10 `check-owners.sh` passes on a full stamp | value: owner login | G0 | +| 12 | Owners | `scripts/check-owners.sh` | `files/scripts/check-owners.sh` | `scripts/test-check-owners.sh` (from `files/scripts/test-check-owners.sh`) | agnostic | G4 | +| 13 | Merge guard | `scripts/pr-merge.sh` | `files/scripts/pr-merge.sh.tpl` | `scripts/test-pr-merge.sh` (from a `.tpl`) | value: default branch, door paths, door approver login | G7 | +| 14 | Negative control | `scripts/negctl.sh` | `files/scripts/negctl.sh` | `scripts/test-negctl.sh` | agnostic | G7 | +| 15 | Work queue | `.github/ISSUE_TEMPLATE/task.yml` | `files/.github/ISSUE_TEMPLATE/task.yml` | `tests/test-stamp-queue.sh` (YAML parses, section ids match what the script reads) | agnostic | G5 | +| 16 | Work queue | `scripts/issues-from-rows.sh` | `files/scripts/issues-from-rows.sh.tpl` | `scripts/test-issues-from-rows.sh` (from a `.tpl`) | value: board file | G5 | +| 17 | Work queue | `.github/pull_request_template.md` | `files/.github/pull_request_template.md` | `tests/test-stamp-queue.sh` (carries `Closes #`) | agnostic | G5 | +| 18 | Changelog | `CHANGELOG.md` (tag list, `[Unreleased]`) | `files/CHANGELOG.md.tpl` (a `seed` row) | `scripts/test-release-notes.sh` | value: tags | G6 | +| 19 | Changelog | `scripts/release-notes.sh` | `files/scripts/release-notes.sh.tpl` | `scripts/test-release-notes.sh` (from a `.tpl`) | value: tags (the team-tooling tag is `dev`) | G6 | +| 20 | Digest | `scripts/team-digest.sh` | `files/scripts/team-digest.sh.tpl` | `scripts/test-team-digest.sh` (from a `.tpl`) | value: decision tag, board file | G9 | +| 21 | Proof guide | `docs/verification/README.md` | `files/docs/verification/README.md.tpl` | `tests/test-stamp-rules.sh` | agnostic | G1 | +| 22 | Gate config | `.kit.toml` | `files/.kit.toml` | `tests/test-stamp-rules.sh` (`proof_of_done = true`, `lane_gates = false`) | agnostic | G1 | + +Every test of a valued script is itself a `.tpl`, rendered with the same values, and reads them from the repo (never a literal `main`, tag or path). The kit-free run stamps with non-default values: `--default-branch master`, two custom tags, a custom product path, a door path and a board file. + +Row classes: `copy` (drift-checked), `seed` (created when absent, never drift-checked after: `OWNERS.md`, `CHANGELOG.md`, `.claude/memory/MEMORY.md`, and the seed notes), `jsonmerge` (`.claude/settings.json`, judged by whether the merge would add anything, so a repo or adopt adding its own entries is not drift), `hook` (a generator script's stdout, seed-once). + +Not generated, because the brief's table does not list them: the board-ID mint script, the doc-link check, evidence-branch rules, and any language job. The workflow carries stub language jobs as comments only (the brief: language test jobs are left to the repo). + +Parameters, set by flags and recorded in the lock: + +| Flag | Default | Used by | +|---|---|---| +| `--default-branch` | `git symbolic-ref refs/remotes/origin/HEAD`, else refuse (never a guess) | rows 1, 2, 3, 7, 8, 13 | +| `--owner <login>` | none: refuse with the fix line | row 11 | +| `--tags a,b,c` | `product,dev` (`dev` is always present and is the team-tooling tag) | rows 1, 8, 10, 18, 19 | +| `--product-paths a/,b/` | `src/` | rows 8, 10 | +| `--door-paths a,b` and `--door-approver <login>` | empty door list: the second-person rule is written, listing no path | row 13, rows 1, 2 | +| `--board-file <path>` | empty: only `Closes #n` and `no-board-row:` satisfy the board link; `issues-from-rows.sh` and `team-digest.sh` print one line (`no board file set; nothing to read`) and exit 0 | rows 8, 16, 20 | +| `--decision-tag <word>` | `decision` (the tag a board row carries when it waits on a human) | row 20 | + +Derived values the templates may use (read-only, computed from the flags): `TAGS_ERE`, `TAGS_COLON`, `TAGS_AWK`, `PRODUCT_ERE`, `PRODUCT_ARRAY`, `DOOR_ARRAY` (empty when no door path is set), `DOOR_CASE`, and `AGENTS_MARKER` (line 1 of the adopt pointer template, read at stamp time, refused unless it starts `<!-- kit:agents-pointer`). Their exact forms are fixed in `lib/stamp/README.md`. + +Board grammar, shared by rows 8, 16 and 20 (the file is optional; the format is the one the hand-fitted repo used): a Markdown table whose rows read `| ID-NNN | item | notes | status |`; a row is queued when its status starts with `queued`; the notes carry `#<github-login>` to assign, `Done when: <one check>` to make it ready, and `#<decision-tag> #P0` to mark a decision that waits on a human; `executing`, `shipped`, `dropped`, `parked` are the other states the digest reads. `issues-from-rows.sh` creates one issue per queued, tagged, ready row and needs the labels `ready`, `one-way-door` and `blocked` to exist: its `--apply` run first creates any that is missing with `gh label create` (idempotent), and its dry run prints that step. + +### Interplay with adopt (the second reader of the same files) + +| File | Stamp first, adopt later | Adopt first, stamp later | +|---|---|---| +| `AGENTS.md` | adopt sees an existing file and leaves it (its line 1 is the kit marker, so `is_adopted` holds) | stamp sees a file that is the kit pointer or an old kit copy by hash: it reports it, writes nothing, and prints `Fix: bash lib/stamp.sh --take AGENTS.md <repo>` which replaces only a file whose hash is a known kit pointer | +| `docs/verification/README.md` | adopt leaves the stamp's guide (it never overwrites the marker) | the file is adopt's four-line marker: same rule as `AGENTS.md`, `--take` swaps it for the guide; any other content is a drift line | +| `.kit.toml` | adopt never overwrites; the stamp's `lane_gates = false` stands | the file has `lane_gates = true`: drift line plus `Fix: set lane_gates = false in .kit.toml`; never edited by the stamp | +| `.claude/settings.json` | adopt's jq merge adds kit hooks beside the stamp's two | the stamp's jq merge adds its two entries beside the kit's; both keep each other's keys | +| `CLAUDE.md` | the stamp writes none (agents-only shape); adopt's loader is its own | untouched | + +A stamp run never edits adopt's managed `<!-- kit:adopt -->` block. + +### CI trust design (security review) + +Two jobs, one trust rule: a job that judges a pull request executes nothing from the pull request. + +| Job | Runs | Never | +|---|---|---| +| `changes` | the owners check and the path filter, both copied from the BASE revision | executes a file from the PR head | +| `pr-shape` | `scripts/pr-shape.sh` copied from the BASE revision, shellcheck pinned by digest | executes a file from the PR head (shellcheck reads changed files and does not run them) | + +There is no job that runs the pull request's own `scripts/test-*.sh`. A hosted-or-self-hosted runner that executes a pull request's test code runs untrusted code, so the stamp leaves that to a stub comment in `ci.yml`: a repo adds its own test job after it has an ephemeral runner. `scripts/check.sh` runs the same two jobs' commands locally (the twin set is unchanged); the local `scripts/test-*.sh` run is the author's own, on the author's machine. + +Every job carries `if: github.event.pull_request.head.repo.full_name == github.repository`, so a fork's pull request does not run on the self-hosted runner. A skipped job leaves its check missing and the merge guard refuses. A base that holds no copy of a gate script (the pull request that introduces the stamp) fails the job: it is merged by hand after a second person reads it. The workflow comment and both rules docs say: use an ephemeral runner or a container job, a long-lived runner keeps what a pull request's tests write, not for public repos. + +GitHub runs the workflow file of a pull request from the pull request's own merge commit, so the base-copy rule protects the scripts and not the workflow. The merge guard is what binds the workflow (below), and the workflow files are doors. The workflow header says that nothing in these two jobs executes a file of the pull request. + +### Merge guard trust design (security review) + +- Both checks `changes` and `pr-shape` must have passed from the workflow named `CI`, each on the head the guard judged. Only runs of THIS pull request count: the guard reads the `pull_request` runs of `ci.yml` for the head from `actions/runs` (a run counts only when its `pull_requests` list holds exactly this pull request: GitHub lists every open pull request that shares the head, so a run that also names another pull request is not trusted) and keeps a rollup entry only when its `detailsUrl` carries one of those run ids. A status context, another workflow of the same name, or a run of another pull request does not count. +- The base must be the default branch (`gh pr edit <n> --base <default>` is the fix). The guard refuses a pull request aimed at any other base. +- Default doors, always on, matched case-insensitively (the path and the pattern are both lowered): the whole `.github/` directory, `scripts/`, `.claude/`, `OWNERS.md`, `AGENTS.md` and `CLAUDE.md` at any depth, `.mcp.json`, `docs/TEAM-WORKFLOW.md`, `.kit.toml`. `--door-paths` adds to them. A change to the hook settings, the lessons index, a model-instruction file or an `agent-*` script runs in every teammate's next session, so it is a door; the rules docs say so. The first pull request that introduces the stamp touches every door. +- The changed-file list comes from the REST `pulls/<n>/files` endpoint with both `filename` and `previous_filename` (a rename out of a door is a door change), 3000 files at most; a list at the cap, or a read that fails, refuses. +- An approval counts only when it is the reviewer's latest decision, its `commit.oid` equals the judged head, it was submitted after the last `base_ref_changed` event on the pull request's timeline, its `authorAssociation` is OWNER, MEMBER or COLLABORATOR, the reviewer is not the author and not a bot (`[bot]` suffix or `app/` prefix), and, when `{{DOOR_APPROVER}}` is set, the login matches. A field `gh pr view --json reviews` does not report (checked against a real read-only call on a public repo: `reviews[].authorAssociation`, `reviews[].commit.oid`, `reviews[].author.login`, `reviews[].state`, `reviews[].submittedAt`) means the approval does not count. The other `gh` fields were checked the same way: `statusCheckRollup[].detailsUrl`, `.workflowName`, `.name`, `.status`, `.conclusion`, `.startedAt`, `.completedAt` on a real PR; `actions/runs` `workflow_runs[].id`, `.path` (exact, for example `.github/workflows/ci.yml`) and `.pull_requests[].number` on a real open PR of a public repo; `pulls/<n>` `.head.sha` and `pulls/<n>/files` `.filename` on a public PR, `previous_filename` and the issue timeline `base_ref_changed` event with `created_at` in the GitHub REST description and event documentation. +- Self-copy check: the guard refuses to run when its text differs from `origin/<default>:scripts/pr-merge.sh` (after a fetch whose failure it reports), with `Fix: git checkout <default> && git pull, then run it again`; with no copy on the default branch it refuses and says to merge the first stamp pull request by hand. No `Fix:` line tells anyone to check out a pull request and run its scripts: the conflict fix is `gh pr update-branch <n>`. Limit: a pull request's copy that removed the check is not stopped by it; the protection is that nobody is told to run that copy and that `scripts/` is a door. The check stops only an honest out-of-date copy. + +### Owners check and case (security review, round 2) + +A file system that folds case (macOS, Windows) can hold `SCRIPTS/x.sh` and `scripts/x.sh` as one file, while git tracks them as two paths. Rules: the owners check selects its areas (`scripts/`, `.github/workflows/`) by lowercase, so a case variant is still checked; ownership itself is an exact match between a tracked path and a row, never a lowercase one, so `scripts/Deploy.sh` does not ride on a row for `scripts/deploy.sh`. Two tracked paths, or a tracked path and a row path, that are equal when lowercased are refused. The tracked list is read NUL-delimited (`git -c core.quotePath=false ls-files -z`); a name under an owned area that holds a newline, a control byte or a byte above 0x7F is refused with a plain instruction, never skipped. `pr-shape.sh` refuses a head tree that holds two paths equal when lowercased. Doors fold case, because a door match never decides ownership and the file list from the REST endpoint is JSON. + +### Picture and lock states + +The wiring picture is `## Picture` above. The states a file passes through, as the engine decides them from three hashes (current file, lock, rendered template): + +``` + lock lists it? + no yes + file absent -> created -> missing (never re-created) + file present + == template -> unchanged (enters lock) current == lock ? + != template -> edited (left alone) yes: template == current -> unchanged + "not written by stamp" yes: template != current -> older stamp -> --refresh diff -> --take + no : edited (left alone), diff printed by --take, never replaced + seed / hook rows : absent -> created ; present -> unchanged, whatever its bytes + jsonmerge rows : merge would add nothing -> unchanged ; else merged (foreign keys kept) +``` + +## Technical Design + +### Interfaces (I/O contract) + +- Inputs: `lib/stamp.sh [--check | --dry-run | --refresh | --take <path>] [flags above] <target-dir>`. `--check` exits 0 when every drift-checked file exists and matches the lock, every `seed` and `hook` file exists, every `jsonmerge` entry is present, and no interplay drift line is printed; else 1, writing nothing. `--dry-run` prints what would be written. Default (no mode flag) writes missing files only. `--refresh` writes nothing and prints, per file whose template changed since the lock, a unified diff and `Fix: bash lib/stamp.sh --take <path> <repo>`. `--take <path>` replaces exactly one file, and only when the file's current hash equals its lock hash (unedited); the old content is first copied to `<path>.orig`. For an edited file `--take` refuses and prints the diff between the lock's rendering and the new template with `Fix: apply the diff above by hand`; the stamp never replaces an edited file. +- Outputs: the files in the table, `.claude/team-stamp.lock`, and report lines `created`, `unchanged`, `edited (left alone)`, `older stamp (run --refresh)`, `missing`. +- Invariants: no write outside the target; no write through a symlink (`kit_refuse_symlink_path` over every target path and its parents); a failed run leaves the tree as found (write to a temp name, then rename); no generated file contains a path under the kit; a re-run with the same inputs prints only `unchanged`. + +### Data model changes + +The lock, one file, plain text, parseable with `awk`: + +``` +stamp-version 1 +value default-branch main +value owner <login> +... +file <path> <group> sha256:<hex as written> +``` + +### Where the verb lives, and why + +`lib/stamp.sh` with a `# kit-verb: stamp | ...` header, `lib/stamp/README.md`, `templates/team-stamp/`, and `commands/stamp.md` (`/kit:stamp`). This is how adopt is wired: `lib/adopt.sh` carries a `# kit-verb:` header that `lib/registry/feature-registry.sh` reads into `docs/reference/FEATURES.md`; the human door is `commands/adopt.md`; there is no `bin/` entry and no `lib/config/modules.tsv` row (adopt is "no install module" in `lib/config/module-registry.md`). The stamp has no hook of its own and no kit knob, so it gets no module row either. `wrap adopt` composes adopt for a fleet; a `wrap stamp` is out of scope (see Out of Scope). + +### Generator rules as behavior + +1. Kit-free output: the render step scans every rendered file for the kit-path patterns below before writing and aborts the whole run on a hit. Patterns: `\.claude/dwarves-kit`, `CLAUDE_PLUGIN_ROOT`, `KIT_ROOT`, `lib/gate/`, `/bin/(gate|classify|wrap|board)`, and any absolute path under the operator's home. The only allowed kit text is line 1 of `AGENTS.md` (the marker) and the one public URL `https://github.com/dwarvesf/dwarves-kit` in `AGENTS.md`'s closing "if the kit is installed" section, which names no local path. +2. Refusal text: every refusal prints exactly two lines, first `<tool>: <the rule in one line>`, then `Fix: <the command>`. The rule line says what is forbidden and why in plain words; the fix line is a command that can be pasted. pr-shape prints one pair per failed check. The kit-side test `tests/test-stamp-refusals.sh` runs every refusal in the generated scripts and asserts `^Fix: ` is the line right after the rule line. +3. Runner label: the generated workflow always has `runs-on: [self-hosted]` and never a GitHub-hosted label (`ubuntu-*`, `macos-*`, `windows-*`); a test on the template text pins that. A repo with a named pool edits its own file, and the stamp then reports it as edited and leaves it. Why: the estate rule is zero hosted-runner spend, and the org template "CI (self-hosted)" is the same shape. A repo with no self-hosted runner gets a workflow that queues and never starts, which costs nothing and fails closed; the twin `scripts/check.sh` is how a PR is checked until a runner exists. +4. Shellcheck in CI: no hosted image can be assumed to have it. The job installs a pinned release and checks its sha256 before use, picking the asset by `uname -m` (the hand-fitted job pinned one architecture only). The build fetches both digests from the release metadata with `gh api` and records the release tag in the template; no digest is typed from memory. +5. Idempotence: all writes go through one `write_if_absent` and one lock update. Two runs in a row produce no diff (`git status --porcelain` empty on the second). +6. Drift: for each manifest file the stamp compares three hashes: current file, lock, and the rendered template. Current != lock means the repo edited it (`edited (left alone)`, with the line count that differs). Current == lock != template means an older stamp copy (`older stamp`). Missing means `missing` and the file is re-created on a default run only when the lock never listed it. +7. Upgrade offer: `--refresh` prints one unified diff per `older stamp` file and the `--take` command for it. It never applies any. + +### Task split for the build + +Groups are independently testable and in dependency order. Files in a group are disjoint from every other group's (each group owns its own `manifest.d/NN-<group>.tsv`, so no shared manifest file), so groups on the same rung can build in parallel in separate worktrees. + +``` +G0 engine, manifest hook row, derived values, adopt interplay, owners seed + | + +-- G1 rules docs G2 lessons G3 hook G4 owners check + +-- G5 queue G6 changelog G7 merge+negctl G9 playbook+digest (rung 2, parallel) + | + +-- G8a pr-shape -- G8b check + ci (rung 3, in order) + | + +-- G10 integration (cross-group tests) -- G11 gauntlet run (rungs 4, 5) +``` + +Rung 1: G0 alone. Rung 2 (parallel, disjoint): G1, G2, G3, G4, G5, G6, G7, G9 (G9's checks that need other groups' files wait for G10). Rung 3: G8a, then G8b (G8a needs G1 anchors and G6's tag convention; G8b's twin test needs G8a). Rung 4: G10, which holds every test that needs more than one group's files. Rung 5: G11. + +## Task Breakdown + +### Phase 1: Foundation + +- [x] TASK-G0 engine (parallel: no). Files: `lib/stamp.sh`, `lib/stamp/README.md`, `lib/stamp/owners-seed.sh`, `tests/test-stamp.sh`, `tests/test-stamp-kitfree.sh`, `tests/fixtures/team-stamp/`. Done when: manifest rows of four kinds (`copy`, `seed`, `jsonmerge`, `hook`) from `manifest.d/*.tsv`; `{{KEY}}` render with the base and derived values (ERE, glob and array forms) and the kit marker; `write_if_absent`, the lock, `--check`, `--dry-run`, `--refresh`, `--take`, `--only`; the jq merge; symlink refusal; the kit-path scan; the adopt interplay code (`--take` on a known pointer hash or adopt's proof marker, the `.kit.toml` `lane_gates = true` drift line, a note for foreign kit hook entries); the owners seed built from the merged manifest by a `hook` row; a portable sha256 (`sha256sum`, else `shasum -a 256`); the README section "How a group plugs in". Test: `bash tests/test-stamp.sh && bash tests/test-stamp-kitfree.sh fixture`. + +### Phase 2: Pieces (rung 2, all parallel) + +- [x] TASK-G1 rules docs. Files: `files/AGENTS.md.tpl`, `files/docs/TEAM-WORKFLOW.md.tpl`, `files/docs/verification/README.md.tpl`, `files/.kit.toml`, `manifest.d/10-rules.tsv`, `tests/test-stamp-rules.sh`. Done when: line 1 of `AGENTS.md` is `{{AGENTS_MARKER}}`; sections commands, playbooks, lessons, team rules, never, and a closing optional-kit section that names only the public URL; every `AGENTS.md` heading has an anchor in `TEAM-WORKFLOW.md`; the proof guide states the `Command:`, `Output:`, `Exit:`, `NEGATIVE CONTROL`, `Verdict:` shape in the form `pr-shape` accepts; `.kit.toml` sets `proof_of_done = true` and `lane_gates = false` and its header comments name no kit path; the limit sentence (a merge from the GitHub site passes everything on a plan without branch protection), the trust-the-folder step and the optional-kit section appear in both docs, each pinned by a test. Test: `bash tests/test-stamp-rules.sh`. +- [x] TASK-G2 lessons. Files: `files/scripts/agent-lessons.sh`, `files/scripts/test-agent-lessons.sh`, `files/.claude/memory/MEMORY.md` and five notes (`seed` rows), `manifest.d/20-lessons.tsv`, `tests/test-stamp-lessons.sh`. Done when: the script prints the index, exits 0 when it is missing, truncates with a notice past 9,000 characters; each note has `name` and `description` frontmatter, is under 1,200 characters, carries no personal name; the guard lesson lists the guard's known misses (see G3). Test: `bash tests/test-stamp-lessons.sh`. +- [x] TASK-G3 hook. Files: `files/scripts/agent-guard.sh.tpl`, `files/scripts/test-agent-guard.sh.tpl`, `files/.claude/settings.json`, `manifest.d/30-hook.tsv`, `tests/test-stamp-hook.sh`. Done when: the guard blocks (exit 2, two lines on stderr) a bare `gh pr merge`, a push to the default branch (`git push origin main`, `git push origin HEAD:main`, a bare `git push` while on it), a commit on the default branch; allows `bash scripts/pr-merge.sh --wait 5`, `echo "gh pr merge"`, a feature-branch push and commit; the `Fix:` line carries the PR number parsed from the command, never the text `<number>` when a number is present; a file checkout (`git checkout README.md; git commit` on the default branch) is NOT read as a branch switch; no `python3` anywhere in the script (JSON is read with `jq`, else the command is allowed with a one-line note); every miss the build probes (`env -i git commit`, `timeout 5 git push origin main`, `git push --all`, `git push --mirror`, `gh api .../merge`, an indirect `$g pr merge`) is either blocked with a test or named in the lessons note as a known miss, and the test file holds a row per probe; the settings merge adds a PreToolUse `Bash` entry and a SessionStart entry and keeps foreign keys. Test: `bash tests/test-stamp-hook.sh`. +- [x] TASK-G4 owners check. Files: `files/scripts/check-owners.sh`, `files/scripts/test-check-owners.sh`, `manifest.d/40-owners.tsv` (carries the `hook` row for `OWNERS.md` built by G0's seed), `tests/test-stamp-owners.sh`. Done when: the check fails (two-line refusal) on a tracked script, workflow or job with no row, a row pointing at a missing path, an empty owner, an agent owner with no sponsor, and its tracked-path list covers `scripts/` and `.github/workflows/` of any repo (not only the stamp's own files). Test: `bash tests/test-stamp-owners.sh`. +- [x] TASK-G5 queue. Files: `files/.github/ISSUE_TEMPLATE/task.yml`, `files/.github/pull_request_template.md`, `files/scripts/issues-from-rows.sh.tpl`, `files/scripts/test-issues-from-rows.sh.tpl`, `manifest.d/50-queue.tsv`, `tests/test-stamp-queue.sh`. Done when: the form writes `Goal`, `Done when`, `Scope`, optional `Notes`; the script reads the board grammar above, turns queued tagged ready rows into issues with `gh` faked, one issue per row, idempotent on a second run, creates the missing labels `ready`, `one-way-door`, `blocked` on `--apply`, and with an empty `--board-file` prints one line and exits 0; the PR template has a `Closes #` line. Test: `bash tests/test-stamp-queue.sh`. +- [x] TASK-G6 changelog. Files: `files/CHANGELOG.md.tpl` (`seed`), `files/scripts/release-notes.sh.tpl`, `files/scripts/test-release-notes.sh.tpl`, `manifest.d/60-changelog.tsv`, `tests/test-stamp-changelog.sh`. Done when: `[Unreleased]` carries the tag list; `release-notes.sh` is awk, bash, git and coreutils only (no `python3`, no `jq`), reads the tag list from the stamped value, drops `dev:` lines, and refuses an untagged line with a two-line refusal; a test runs it with `python3` absent from `PATH`. Test: `bash tests/test-stamp-changelog.sh`. +- [x] TASK-G7 merge guard and negctl. Files: `files/scripts/pr-merge.sh.tpl`, `files/scripts/test-pr-merge.sh.tpl`, `files/scripts/negctl.sh`, `files/scripts/test-negctl.sh`, `manifest.d/70-merge.tsv`, `tests/test-stamp-merge.sh`. Done when: with `gh` faked, the guard waits for checks, refuses a draft, a red check, a pending check at timeout, a conflict, and a change under a door path without a second person's approval (the author never counts as the second person); merges a clean PR pinned to the judged head; `--dry-run` merges nothing; an empty door list works under bash 3.2 with `set -u` (a test runs it); the default branch and the approver login come from the stamped values, never `main` or a login typed in the script; the guard knows only the brief's behaviors (checks, draft, conflict, second person), with no `--allow-ci-change`, no stale-rules refusal and no kit merge-head environment variable; every refusal is the two-line form. `negctl.sh` runs green, break, red, restore, green, refuses a dirty tree before mutating, refuses a "red" that is only a load or syntax error (the capture shows no assertion line), and prints a block with `Command:`, `Output:`, `Exit:`, `NEGATIVE CONTROL`, `Verdict: RED, as expected` in the form `pr-shape` accepts. Test: `bash tests/test-stamp-merge.sh`. +- [x] TASK-G9 playbook and digest. Files: `files/.claude/skills/ship-pr/SKILL.md.tpl`, `files/scripts/team-digest.sh.tpl`, `files/scripts/test-team-digest.sh.tpl`, `manifest.d/90-digest.tsv`, `tests/test-stamp-playbook.sh`. Done when: SKILL.md starts with `---` on line 1 and has exactly the keys `name` and `description`; the digest prints merged PRs, open PRs, open issues with assignee and decisions waiting (rows tagged `#<decision-tag> #P0`) from a faked `gh`; it exits 0 with a note when `gh` is absent and when `--board-file` is empty; the date arithmetic branches on `uname -s` (GNU `date -d`, BSD `date -v`). The check that every `bash scripts/...` command in SKILL.md names a generated script waits for G10. Test: `bash tests/test-stamp-playbook.sh`. + +### Phase 3: CI layer (rung 3, in order) + +- [x] TASK-G8a pr-shape. Files: `files/scripts/pr-shape.sh.tpl`, `files/scripts/test-pr-shape.sh.tpl`, `manifest.d/80-pr-shape.tsv`, `tests/test-stamp-pr-shape.sh`. Done when: pr-shape checks conventional title, proof file with a `Verdict: RED` negative-control block for a behavior change (or `no-proof:` with a 10+ character reason), board link (`Closes #n`, board file changed, or `no-board-row:`), tagged changelog line for product paths (or `no-changelog:`), shellcheck on changed shell files (a missing shellcheck is a skip with a notice locally and a failure when `CI=true`), and rule parity (`AGENTS.md` and `docs/TEAM-WORKFLOW.md`, `no-rule-mirror:` waives it); each failure prints the rule line then `Fix:` with that exact casing. Test: `bash tests/test-stamp-pr-shape.sh`. +- [x] TASK-G8b check and CI. Files: `files/scripts/check.sh.tpl`, `files/scripts/test-check.sh.tpl`, `files/.github/workflows/ci.yml.tpl`, `manifest.d/85-ci.tsv`, `tests/test-stamp-ci.sh`. Done when: the workflow has jobs `changes` (owners check, path filter) and `pr-shape`, takes gate scripts from the base revision, sets `permissions: contents: read`, picks the shellcheck asset by `uname -s` and `uname -m` and verifies its sha256 with `sha256sum` or `shasum -a 256`; `check.sh` runs the same commands with the same inputs. The twin check compares a defined set: the commands the `pr-shape` job runs that are repo scripts or lint calls (`bash scripts/*.sh`, `shellcheck`), minus the install, checkout and base-copy steps; the test asserts the set is non-empty and that each member appears in `check.sh`. Test: `bash tests/test-stamp-ci.sh`. + +### Phase 4: Integration and proof + +- [x] TASK-G10 integration. Files: `commands/stamp.md`, `tests/test-stamp-e2e.sh`, `tests/test-stamp-refusals.sh`, `tests/test-stamp-adopt-interplay.sh`, `tests/test-stamp-cross.sh`, `docs/verification/team-stamp.md`, `CONTEXT.md` (the terms), `CHANGELOG.md`; regenerated `docs/reference/FEATURES.md`; and the one-line mentions the docs lint demands. Done when: the full stamp on an empty git repo writes the 22 rows' files, a second run is a no-op, a kit-free pass runs every generated test with the kit absent, every refusal passes the two-line check; and the cross-group tests pass: `check-owners.sh` passes on a full stamp (test row 24), every `bash scripts/...` command in `SKILL.md` names a generated script, every script the guard's fix lines name exists, and `negctl.sh` output is accepted by `pr-shape.sh`'s proof check. The privacy section of `tests/test-stamp-e2e.sh` follows AC14. Test: `bash tests/test-stamp-e2e.sh && bash tests/test-stamp-refusals.sh && bash tests/test-stamp-adopt-interplay.sh && bash tests/test-stamp-cross.sh`. +- [ ] TASK-G11 gauntlet run (built and Tier 1 green; Tier 2 not run). Files: `tests/gauntlet/team-stamp/` (card, checker, clean-room runner, Tier 1 command), `docs/verification/gauntlet/<date>-team-stamp-scratch/` (the run record). Done when: the run in "The gauntlet run" below ends with an unaided SOLID verdict. Test: `bash tests/gauntlet/team-stamp/tier1.sh`, then the engine's recorded run. + +## The gauntlet run + +Slots (preset: custom, recorded as `preset: custom` in `ROUNDS.md`): + +| Slot | Value | +|---|---| +| Artifact under convergence | `templates/team-stamp/**` and `lib/stamp.sh` (the reviser edits only these), rendered into a scratch repo each round | +| Outcome contract | the card: "add one small function with a test to this repo and get it merged by the repo's own rules"; checker: the PR record shows title, proof file, changelog tag, board link; `scripts/check.sh` exits 0 with the PR's own title and body; no `gh pr merge` was issued bare; no path under the kit was read | +| Probe framing | "You are a teammate's coding agent. Read only this repo's files. Complete the card and submit per the repo's own rules." | +| Clean room | repo kind: `git archive HEAD` of the stamped scratch repo into a container with `git`, `bash`, `jq`, `shellcheck`, a `gh` shim, Claude Code, an empty `HOME`, no kit directory, and one spend-capped model key | + +What runs on this machine with no hosted-runner spend: Docker (v29) and `container` are installed, so the clean room is local. Nothing in the run touches GitHub Actions. The probe holds no GitHub credential (the engine's one-key invariant), so "opens a PR" is a `gh` shim inside the clean room that records `gh pr create` arguments (title, body, base, head) and the `gh pr view`, `gh pr checks` and `gh pr merge` calls into `submission/pr.json`, and answers them from the scratch repo's local state. "Passes the generated CI" is judged by the checker replaying, from the base revision, the exact commands `ci.yml` runs in its `pr-shape` job (the twin `scripts/check.sh` runs the same commands; `tests/test-stamp-ci.sh` asserts every `run:` command in `ci.yml` appears in `check.sh`). That is a local replay of the workflow, not a hosted run, and the record says so. + +Tier 1 (deterministic, every round, before any paid probe): stamp into a scratch repo, run every generated test with the kit absent from `PATH` and `HOME`; pipe a PreToolUse JSON for `gh pr merge 7 --squash` into `scripts/agent-guard.sh` and assert exit 2, stderr line 1 names the rule, line 2 is `Fix: bash scripts/pr-merge.sh --wait 7`; do the same for `git push origin main` and a commit on the default branch. This is the "bare merge blocked with the fix line" half of the Done line, shown without relying on the probe choosing to try it. + +Tier 2: the probe. The card tells it to merge when green. If it tries a bare merge, the real project hook fires inside the clean room and the transcript shows the denial; if it goes straight to `scripts/pr-merge.sh`, the record notes that no denial was exercised by the probe and rests on Tier 1. + +Optional Tier 3, only with the operator's say-so: a private scratch repo on GitHub with a self-hosted runner attached, one real PR, the run id recorded. It is not required for SOLID and is not run unattended, because the repo would need a runner and the hosted label is forbidden. + +Cost note: the probe is Sonnet, cap 3 rounds, per `commands/gauntlet.md`. + +## After state + +- [x] `bash lib/stamp.sh --owner <login> <repo>` on an empty git repo writes the 22 rows' files and the lock. (Today: no such verb; adopt writes a kit pointer only.) +- [x] A second run prints only `unchanged` and `git status --porcelain` shows nothing new. (Today: n/a.) +- [x] Editing any generated file and re-running leaves the edit and prints `edited (left alone)`. (Today: n/a.) +- [x] `grep -rEn` for the kit-path patterns over a stamped repo returns only line 1 of `AGENTS.md` and the one public URL; every generated test passes with the kit absent from `PATH` and `HOME`. (Today: the adopt pointer sends an agent to `~/.claude/dwarves-kit/AGENTS.md`.) +- [x] A bare `gh pr merge` fed to `scripts/agent-guard.sh` exits 2 with `Fix: bash scripts/pr-merge.sh --wait <n>`. (Today: the kit's `hooks/safety-gate.sh` has no bare-merge block and is plugin-bound.) +- [x] The generated workflow has `runs-on: [self-hosted]` and no GitHub-hosted runner label, and `actionlint` accepts it (exit 0 on the rendered workflow). (Today: none generated.) +- [ ] A recorded gauntlet run under `docs/verification/gauntlet/` ends SOLID for the card above. (Tier 1 is green and recorded; Tier 2, the probe, has NOT run: no container runtime on the build host and the probe key is metered. The "bare merge is blocked with the fix line" half of the Done line is shown by Tier 1; the "clean-room agent opens a PR that passes the generated CI" half is not. Operator command: `ANTHROPIC_API_KEY=<capped probe key> RUN_OUT=docs/verification/gauntlet/<date>-custom-team-stamp-scratch/round-N bash tests/gauntlet/team-stamp/run.sh`.) +- [x] `docs/reference/FEATURES.md` lists `stamp`. +- [ ] `bash tests/run-all.sh --changed origin/master` is green (the lead runs it). + +## Quality requirements + +none (no `docs/QUALITY.md` entry is touched). + +## Acceptance Criteria (global) + +| AC | Check | +|---|---| +| AC1 file set: the manifest rows equal the 22 rows of the table above, and no file outside it is written except the lock | `tests/test-stamp-e2e.sh` file-set section | +| AC2 kit-free text: no rendered file matches a kit-path pattern, except line 1 of `AGENTS.md` and the one public URL | `tests/test-stamp-kitfree.sh all` (greps every generated file) | +| AC3 kit-free run: every generated `scripts/test-*.sh` passes with `PATH` holding only git, bash, jq, coreutils and a `gh` fake, and `HOME` an empty temp dir | `tests/test-stamp-kitfree.sh all` (run section) | +| AC4 idempotent: a second run writes nothing and prints only `unchanged` | `tests/test-stamp.sh` | +| AC5 never overwrites: an edited file, a file replaced by a symlink, and a file with a changed mode are left as found | `tests/test-stamp.sh` | +| AC6 drift report: `edited (left alone)`, `older stamp`, `missing` each reported with the right file, exit codes of `--check` | `tests/test-stamp.sh` | +| AC7 upgrade offer: `--refresh` prints one diff per `older stamp` file and writes none; `--take <path>` replaces one, keeps `<path>.orig`, refuses an edited file and prints the diff to apply by hand | `tests/test-stamp.sh` | +| AC8 hook refusals: each of bare merge, push to default branch, commit on default branch prints the rule line then `Fix:` and exits 2; allowed lookalikes exit 0 | `scripts/test-agent-guard.sh` and `tests/test-stamp-refusals.sh` | +| AC9 CI refusals: pr-shape (title, proof, board link, changelog, shellcheck, parity), check-owners (no row, dead row, empty owner, no sponsor), pr-merge (draft, red, pending, conflict, door without second person, author as second person), release-notes (untagged line) each print rule then `Fix:` | the generated test of each script and `tests/test-stamp-refusals.sh` | +| AC10 parity: a PR changing `AGENTS.md` and not `docs/TEAM-WORKFLOW.md` fails; `no-rule-mirror:` with a reason passes; both changed passes | `scripts/test-pr-shape.sh` | +| AC11 runner: the workflow has `runs-on: [self-hosted]` only, and a scan of the template text finds no `ubuntu-`, `macos-` or `windows-` label; `actionlint` passes when installed | `tests/test-stamp-ci.sh` | +| AC12 twin: the defined command set of the `pr-shape` job (see G8b) is non-empty and every member appears in `check.sh` with the same inputs | `tests/test-stamp-ci.sh` | +| AC13 adopt interplay: both orders in the interplay table behave as stated; `.claude/settings.json` foreign keys survive; the kit marker is line 1 of `AGENTS.md` and `adopt --check` reports adopted | `tests/test-stamp-adopt-interplay.sh` | +| AC14 privacy: the generic leak-shape scan always runs and can always fail: the branch diff, the templates, the fixtures, the proof and the gauntlet record hold no absolute home path, email, `op://` reference, or bare 40-hex or 64-hex run (the only allowed shapes are `uses: owner/repo@<40-hex> # v...` and a 64-hex run right after a `sha256` marker); fixture shas and emails are generated at run time, never typed. The denylist scan (a file kept outside the repo, named in `STAMP_DENYLIST_FILE`) runs when that variable is present and matches nothing in the branch, a stamped repo or the shipped files; when it is absent the suite prints one `SKIP` line naming the variable and passes. A variable naming a missing file fails. The lead runs it with the list before the PR opens | `tests/test-stamp-e2e.sh` privacy section | +| AC15 gauntlet: the Done run ends with an unaided SOLID verdict, Tier 1 green, and a record under `docs/verification/gauntlet/` | the run record | +| AC19 scan-safe digests: the lock writes every hash as `sha256:<hex>`, and any hash a generated file carries (the shellcheck pin in `ci.yml`) is `sha256=<hex>` or `sha256: <hex>`; staging a full stamp leaves no bare 64-hex run outside those markers; no template or test fixture in the kit holds a hex literal of 40 or 64 digits (digests are computed at run time) | `tests/test-stamp.sh` staged-diff scan; per group, the same scan over its stamp | +| AC17 limits and guidance: the limit sentence, the optional-kit section and the trust-the-folder step appear in both docs; `.kit.toml` sets `proof_of_done = true` and `lane_gates = false`; the vendor contract is re-read at build time and the build records the fetch in `docs/implementation-notes/team-stamp.md` | `tests/test-stamp-rules.sh`; the implementation notes | +| AC18 repo-living files: a `seed` or `hook` file the repo edited never drifts; `--check` is clean on a healthy repo after the repo edits `OWNERS.md`, `CHANGELOG.md` and `MEMORY.md` | `tests/test-stamp.sh` | +| AC20 CI trust: `changes` and `pr-shape` run no file from the PR head and there is no job that runs the PR's tests; every job carries the fork guard; a base with no gate copy fails the job; the header says the workflow comes from the PR and to use an ephemeral runner | `tests/test-stamp-ci.sh` | +| AC21 merge guard trust: both checks from workflow CI, from runs of this pull request only, are required; the base must be the default branch; the harness files (the whole `.github/` directory, instruction files at any depth, `.mcp.json`) are doors matched case-insensitively, renames count by both names, the list comes from REST with a 3000 cap, and `--door-paths` adds; an approval counts only at the judged head, after the last base change, from OWNER, MEMBER or COLLABORATOR, not a bot, not the author; the guard refuses a copy that differs from `origin/<default>` and the bootstrap case; no Fix line checks out a PR | `scripts/test-pr-merge.sh`, `tests/test-stamp-merge.sh` | +| AC22 engine hardening: a flag value with a newline, CR or tab is refused first; `..` and a leading `/` are refused in path-like values; every run prints the values and their source; the take backup never goes through a symlink | `tests/test-stamp.sh` | +| AC23 one rule-line filter: no colon, 80 characters, in every generated script; titles, ids and file names never forge a `Fix:` line; the digest filters titles; the guard reads `\gh`; negctl refuses a mutate command that moved HEAD | `tests/test-stamp-refusals.sh`, the generated tests | +| AC24 gauntlet trust: the host reads only six named regular files out of the checker's output dir (a symlink at any name, a symlinked dir and an oversize file are refused); the checker treats the probe's repository as data (neutral copy, pristine gate files laid over the view, NUL lists), a hostile repository leaves no marker, an edited gate script fails check 9; the key scrub scans binaries and scans again. The container path itself is not run on the build host | `tests/gauntlet/team-stamp/tier1.sh` | +| AC25 case and exact owners: a tracked case variant needs its own exact row; two paths equal when lowercased are refused in the owners check and in pr-shape; a name with a newline, a control byte or a non-ASCII byte under an owned area is refused, not skipped; a door in another case is still a door | `scripts/test-check-owners.sh`, `scripts/test-pr-shape.sh`, `scripts/test-pr-merge.sh`, `tests/test-stamp-refusals.sh` | +| AC16 negative control: making the guard allow a bare merge, making the render skip the kit-path scan, and making `write_if_absent` overwrite each turn the matching test red | `docs/verification/team-stamp.md` | + +## Verification + +```bash +bash tests/test-stamp.sh +bash tests/test-stamp-kitfree.sh all +bash tests/test-stamp-e2e.sh +bash tests/test-stamp-refusals.sh +bash tests/test-stamp-adopt-interplay.sh +bash tests/gauntlet/team-stamp/tier1.sh +bash tests/run-all.sh --changed origin/master +``` + +Per-group suites (`tests/test-stamp-<group>.sh`) run as each group lands. Negative control: `bash lib/gate/negctl.sh <worktree> "<test-cmd>" "<mutate-cmd>"` once per behavior in AC16. + +## Edge Cases + +1. Target is not a git repo: refuse (`Fix: git init`), because the default-branch value and the guard need one. +2. No `origin` and no `--default-branch`: refuse with the fix line; never guess a branch name. +3. `AGENTS.md` exists and is the repo's own file: left alone, drift line with line count, and the stamp reports that rows 1 and 2 are not parity-checked until the operator merges by hand. +4. The target path or a parent is a symlink: refuse the run before any write. +5. `jq` missing at stamp time: refuse (`.claude/settings.json` merge needs it); the generated scripts themselves need no `jq` (guard falls back to `python3`, then allows with a note). +6. `.claude/settings.json` is invalid JSON: refuse, write nothing. +7. Two hook entries already present from an earlier stamp: the merge matches by command string and adds nothing. +8. `--owner` names a login with a space or `@`: refuse. +9. A repo with a `CHANGELOG.md` already: left alone, drift line; the tag list is printed so the operator can add it. +10. Kit upgrade changes a template while the repo edited the same file: `edited (left alone)` wins; `--refresh` prints the diff against the stamp's own rendering, not against the edit. +11. The pointer worker changes line 1 of the pointer to a new version: the stamp copies whatever line 1 is, so the marker follows. +12. The probe writes a PR body with CRLF line ends or a mention-only `#12`: pr-shape must handle both as the hand-fitted tests did (a mention is not a close). +14. `.kit.toml` header comments or any generated comment names a kit path: the render scan refuses the run. +15. A new repo's first PR adds its own `scripts/*` without an owner row: `check-owners.sh` fails it, as designed; the stamp's own files all have rows from the seed. +16. A self-hosted runner that is macOS: the shellcheck install branches on `uname -s` and `uname -m`, and the digest on `uname -s`. +13. A repo with a named runner pool edits `ci.yml` by hand: the stamp reports `edited (left alone)` and never restores `[self-hosted]`. + +## Failure modes + +| Failure class | Detection signal | Mitigation / recovery | +|---|---|---| +| A template leaks a product name, person, org, channel id or private path into the kit | AC14 scan, plus the lead's denylist run | the build strips to placeholders (see DEC-7); the run aborts before any template ships | +| A generated file points back at the kit | AC2 grep; the render-time scan aborts the run | fix the template; the scan is the second line | +| Guard fails open on its own bug | `scripts/test-agent-guard.sh` has a fault-injection case (broken stdin, missing `jq` and `python3`) | exit 0 by design, so CI and `pr-merge.sh` are the binding layer; the generated docs say the hook is advice with teeth | +| The folder is not trusted, so the hook might not load | none needed: the vendor page lists settings-file hooks as used in both untrusted cases | the generated docs state that; CI still binds | +| A person merges from the GitHub site | none (no branch protection on the plan) | the limit is stated in the generated rules, as the brief requires | +| The workflow queues forever for lack of a runner | PR checks stay pending | `scripts/check.sh` is the interim check; `pr-merge.sh --wait` reports pending, never merges on it | +| Pinned shellcheck digest wrong or release gone | CI step fails on `sha256sum -c` | fail closed; the template comment says how to re-pin from release metadata | +| Stamp and adopt both edit `.claude/settings.json` | AC13 | both use a keyed jq merge; neither rewrites the file | + +## Out of Scope + +- A `wrap stamp` fleet verb, and any automatic commit or PR of the stamp's output (the operator reviews and commits, as with adopt). +- Language test jobs, product playbooks (`ui-change`, `device-check` and the like), the list of irreversible paths beyond the flag, and who posts the digest. +- The digest post to a chat channel and the bot credential problem it brought (host-specific, per the brief). +- Agents other than Claude Code get the rules file and CI only; the stamp adds no per-agent hook for them. +- Removing foreign kit hook entries from `.claude/settings.json` (no `--drop-kit-hooks`). A repo adopted on a machine without the plugin carries kit hook commands that point under the kit; the stamp reports them and never edits them. +- A `--runner-label` flag and an `actionlint.yaml` for a custom label: the generated workflow is always `[self-hosted]`. +- The adopt pointer rewrite and the lane gate sizing (build steps 1 and 2 of the brief, other workers). +- Board-ID minting, the doc-link check, evidence-branch rules, a dash check: not in the brief's table. + +## Touches + +- `lib/stamp.sh` +- `lib/stamp/**` +- `templates/team-stamp/**` +- `commands/stamp.md` +- `tests/test-stamp.sh` +- `tests/test-stamp-kitfree.sh` +- `tests/test-stamp-rules.sh` +- `tests/test-stamp-lessons.sh` +- `tests/test-stamp-hook.sh` +- `tests/test-stamp-owners.sh` +- `tests/test-stamp-queue.sh` +- `tests/test-stamp-changelog.sh` +- `tests/test-stamp-merge.sh` +- `tests/test-stamp-playbook.sh` +- `tests/test-stamp-ci.sh` +- `tests/test-stamp-e2e.sh` +- `tests/test-stamp-refusals.sh` +- `tests/test-stamp-adopt-interplay.sh` +- `tests/test-stamp-cross.sh` +- `tests/test-stamp-pr-shape.sh` +- `docs/implementation-notes/team-stamp.md` +- `docs/verification/team-stamp.md` +- `CONTEXT.md` +- `tests/fixtures/team-stamp/**` +- `tests/gauntlet/team-stamp/**` +- `docs/verification/gauntlet/**` + +## Decision Log + +- DEC-1: the verb is `lib/stamp.sh` with its own templates, not an `adopt` flag. Why: `adopt` is mid-change for the pointer row and is kit-pointer shaped; a stamp must work on a repo the kit never adopted. Rejected: `adopt --team`, a template repo. +- DEC-2: the file table of the brief is the scope: 22 rows, no board-ID mint script, no doc-link check, no dash check, no evidence-branch rules, though the hand-fitted repo has them. Why: the brief says follow the table, do not add or drop. +- DEC-3: the stamp keeps a lock file of per-file hashes. Why: the kit side holds no list of what a stamp rendered for a given repo (values change the bytes), so "edited by the repo" cannot be told from "older stamp copy" without it. adopt needs no lock because its pointer is one fixed file with a fixed known-hash list. Alternative rejected: a known-hash list per value set, which grows without bound. +- DEC-4: default `OWNERS.md` and `docs/TEAM-WORKFLOW.md` paths follow the brief (`OWNERS.md` at the root, `docs/TEAM-WORKFLOW.md`), not the placement the hand-fitted repo chose from its own docs layout rule. +- DEC-5: the runner label is always `[self-hosted]`, never a hosted label (estate rule), and there is no flag for it. A repo with a named pool edits its own `ci.yml`; the stamp reports the edit as drift and leaves it. +- DEC-6: the stamped `scripts/negctl.sh` is a kit-free sibling of `lib/gate/negctl.sh`, not a copy by path. Why: the kit's script lives under the kit and the generated files must not point there. Cost: two copies can drift; `tests/test-stamp-merge.sh` runs both against one fixture and compares the blocks' shape (the five labelled parts), not their bytes. +- DEC-7: strip rule for the hand-fitted files: every product name, org name, repo slug, runner pool name, chat channel and person login becomes a `{{PLACEHOLDER}}` from the parameter table or is removed with the sentence around it. The token list and its replacements are in the phase report, outside the repo. +- DEC-8: refusal format is two lines, `<tool>: <rule>` then `Fix: <command>`, unified across the guard, pr-shape, owners, merge guard and release notes. The hand-fitted scripts used three slightly different shapes. +- DEC-9: five seed lessons (procps, `CI=true`, queued run, text-matching guard, stale checks). The "late ID minting" lesson of the hand-fitted repo is dropped because the ID mint script is not in the table. +- DEC-10: no module row and no kit knob. The stamp is a hand-run generator like adopt; flags carry every value. +- DEC-11: the stamp reads line 1 of the pointer template at run time. Why: the pointer worker is changing that file, and a copied literal would go stale. + +- DEC-12: a `hook` row kind lets one generator script build a file from the merged manifest (the owners seed). Rejected: seeding in group G4, which runs before G8 and cannot know the CI files. +- DEC-13: repo-living files (`OWNERS.md`, `CHANGELOG.md`, `MEMORY.md`) are `seed` rows. Rejected: lock hashes for them, which made `--check` fail on a healthy repo. +- DEC-15: two CI jobs (changes, pr-shape) with a fork guard on each; both run only base copies. The earlier third job, `tests`, is removed (DEC-21). Rejected: one job running everything in order (a PR test could swap the gate). +- DEC-16: the harness files are default doors and `--door-paths` adds to them. Rejected: leaving doors empty by default (the workflow, the hook and the guard itself would merge on a green check alone). +- DEC-17: an approval counts at the judged head, from OWNER, MEMBER or COLLABORATOR, not a bot, not the author. Rejected: counting any approval (a stale one, an outside account on a public repo, or a bot would unlock a door). +- DEC-18: the merge guard refuses to run when its text differs from the default branch copy. Rejected: nothing else; it costs one fetch and closes the "run the PR's copy" path. +- DEC-19: one rule-line filter in every generated script: drop the colon, keep a short set of safe characters, cut at 80 characters. Titles, ids and file names reach a rule line only through it. +- DEC-20: nothing a probe wrote is read, written, listed or executed by a host process except six named result files. The probe's work lives in a named volume; a second container with no key and no network, the volume read-only, checks it; the host copies out `verdict.txt`, `checker-output.txt`, `pr.json`, `calls.jsonl`, `clean-diff.patch` and `transcript.jsonl` as regular non-symlink files under a size cap. Inside the checker the repository is still data: a neutral copy of objects, refs and HEAD, pristine gate files laid over the clone, NUL-delimited lists. A hostile repository can forge its own verdict inside the container (stated in the run record); it cannot reach the host. The container path is not executed on the build host. +- DEC-21: no CI job runs a pull request's own tests. Why: the second security review showed that a job that executes PR code on a self-hosted runner can plant files the gate jobs, the cache or the next run read, whatever the job isolation. Rejected: keeping the job with isolation (the runner is the shared part). A repo that has an ephemeral runner adds its own job. +- DEC-22: doors match case-insensitively, and the owners check matches ownership exactly, selecting areas by lowercase and refusing lowercase collisions. Why: on a case-folding file system the names that GitHub, git and the disk show can differ. Rejected: lowercase compare for ownership (a differently cased file would ride on another file's row). +- DEC-23: the merge guard counts only runs of this pull request, requires the default branch as base, and ignores approvals older than the last base change. Why: a run on another pull request with the same head sha, a retarget after approval, and a stale approval each unlocked a door in the review. +- DEC-14: `pr-merge.sh` carries only the brief's behaviors. The hand-fitted repo's `--allow-ci-change`, stale-rules refusal and kit merge environment variable are dropped. + +## Open questions + +1. (closed) Whether a project `settings.json` hook runs before the teammate trusts the folder: it does; see the vendor table. +2. (closed, see Out of Scope) Foreign kit hook entries in `.claude/settings.json` are reported, never edited. +3. The Done line's "passes the generated CI" is met by a local replay of the workflow's commands plus the twin; a hosted-pool run (Tier 3) needs a self-hosted runner and the operator's say-so. +4. The shellcheck release tag and its two digests are fetched at build time; the spec fixes the method, not the values. + +## Test plan +Date: 2026-11-25 +Source: this spec's ## Acceptance Criteria + +| # | Case | Category | Covers (AC) | Expected | Proof | +|---|------|----------|-------------|----------|-------| +| 1 | Stamp an empty git repo with `--owner` | happy-path | AC1 | exactly the 22 rows' files plus the lock exist | `bash tests/test-stamp-e2e.sh` file-set section | +| 2 | Second run, same flags | happy-path | AC4 | prints only `unchanged`, `git status --porcelain` unchanged | `bash tests/test-stamp.sh` | +| 3 | Grep every generated file for kit-path patterns | security/abuse | AC2 | zero hits except line 1 of `AGENTS.md` and the public URL | `bash tests/test-stamp-kitfree.sh all` | +| 4 | Run every generated `scripts/test-*.sh` with a stripped `PATH`, an empty `HOME` and non-default values (`--default-branch master`, two custom tags, a custom product path); the run fails when it finds no test to run | happy-path | AC3 | all exit 0 and the count is above zero | `bash tests/test-stamp-kitfree.sh all` | +| 5 | Plant a kit path in one template | failure-injection | AC2 | render aborts, nothing written | `bash tests/test-stamp.sh` scan case | +| 6 | Edit a generated file, re-run | boundary/edge | AC5 | edit kept, `edited (left alone)` | `bash tests/test-stamp.sh` | +| 7 | Replace a target with a symlink, re-run | security/abuse | AC5 | run refused, no write | `bash tests/test-stamp.sh` | +| 8 | Delete a generated file the lock lists, `--check` | boundary/edge | AC6 | `missing`, exit 1, no re-create without default run rule | `bash tests/test-stamp.sh` | +| 9 | Change a template, `--refresh` | happy-path | AC7 | one diff per older file, nothing written | `bash tests/test-stamp.sh` | +| 10 | `--take` an edited file | boundary/edge | AC7 | refused, diff printed, `Fix:` line says apply by hand; file untouched | `bash tests/test-stamp.sh` | +| 11 | `--take` an unedited older file | happy-path | AC7 | replaced, `.orig` kept, lock updated | `bash tests/test-stamp.sh` | +| 12 | Guard: bare `gh pr merge 7 --squash` | happy-path | AC8 | exit 2; line 1 rule; line 2 `Fix: bash scripts/pr-merge.sh --wait 7` | `bash scripts/test-agent-guard.sh` in a stamped repo | +| 13 | Guard: `git push origin main`, `git push origin HEAD:main`, bare `git push` on main | happy-path | AC8 | each exit 2 with `Fix:` line | `bash scripts/test-agent-guard.sh` | +| 14 | Guard: `git commit` while on the default branch | happy-path | AC8 | exit 2, fix is `git switch -c <type>/<slug>` | `bash scripts/test-agent-guard.sh` | +| 15 | Guard: `echo "gh pr merge"`, `rg 'git push'`, push of a feature branch, `bash scripts/pr-merge.sh --wait 5` | boundary/edge | AC8 | exit 0 | `bash scripts/test-agent-guard.sh` | +| 16 | Guard: garbage on stdin, no `jq`, no `python3` | failure-injection | AC8 | exit 0 with a note; never traps a session | `bash scripts/test-agent-guard.sh` | +| 17 | pr-shape: non-conventional title | happy-path | AC9 | rule line plus `Fix:` line, exit 1 | `bash scripts/test-pr-shape.sh` | +| 18 | pr-shape: behavior change, no proof file; proof without a RED verdict; `no-proof:` with a short reason | boundary/edge | AC9 | first two fail with a pair, third fails, a 10+ character reason passes | `bash scripts/test-pr-shape.sh` | +| 19 | pr-shape: no board link; body that only mentions `#12`; `Closes #12` with CRLF | boundary/edge | AC9 | mention fails, close passes both line ends | `bash scripts/test-pr-shape.sh` | +| 20 | pr-shape: product path changed with no tagged changelog line; with an untagged line | boundary/edge | AC9 | both fail; `no-changelog:` passes | `bash scripts/test-pr-shape.sh` | +| 21 | pr-shape: changed script fails shellcheck; shellcheck absent with and without `CI=true` | failure-injection | AC9 | fail; absent skips locally with a notice, fails under `CI=true` | `bash scripts/test-pr-shape.sh` | +| 22 | pr-shape: `AGENTS.md` changed alone, `docs/TEAM-WORKFLOW.md` alone, both, alone with `no-rule-mirror:` | happy-path | AC10 | first two fail, last two pass | `bash scripts/test-pr-shape.sh` | +| 23 | check-owners: new script without a row; dead row; empty owner; agent owner with no sponsor | happy-path | AC9 | each fails with a pair; a complete table passes | `bash scripts/test-check-owners.sh` | +| 24 | Owner seed: every generated script has a row | regression | AC9 | `check-owners.sh` passes on a full stamp (needs every group, so it runs in G10) | `bash tests/test-stamp-cross.sh` | +| 25 | pr-merge with fake `gh`: draft, red, pending to timeout, conflict | happy-path | AC9 | each refused with a pair, none merged | `bash scripts/test-pr-merge.sh` | +| 26 | pr-merge: door path changed, no approval; approval by the author; approval by another person | security/abuse | AC9 | first two refused, third merges | `bash scripts/test-pr-merge.sh` | +| 27 | pr-merge: head moves after judgment | failure-injection | AC9 | merge pinned to the judged head is refused by the fake | `bash scripts/test-pr-merge.sh` | +| 28 | release-notes: untagged line; `dev:` line | boundary/edge | AC9 | untagged refused with a pair; `dev:` dropped from the notes | `bash scripts/test-release-notes.sh` | +| 29 | ci.yml: scan for runner labels | security/abuse | AC11 | only `self-hosted`; none of `ubuntu-`, `macos-`, `windows-` | `bash tests/test-stamp-ci.sh` | +| 30 | Plant `ubuntu-latest` in the workflow template text | failure-injection | AC11 | the template-text scan fails | `bash tests/test-stamp-ci.sh` | +| 31 | `actionlint` on the rendered workflow | happy-path | AC11 | passes when installed | `bash tests/test-stamp-ci.sh` | +| 32 | Twin parity: every `run:` command of `pr-shape` appears in `check.sh` | regression | AC12 | none missing | `bash tests/test-stamp-ci.sh` | +| 33 | Adopt then stamp, and stamp then adopt, in a scratch repo | happy-path | AC13 | table behavior; settings foreign keys kept; `adopt --check` exit 0 | `bash tests/test-stamp-adopt-interplay.sh` | +| 34 | Stamp over a repo whose `AGENTS.md` is its own file | boundary/edge | AC5 AC13 | file untouched, drift line with line count | `bash tests/test-stamp-adopt-interplay.sh` | +| 35 | Leak-shaped strings and the outside denylist over all templates | security/abuse | AC14 | zero matches | `STAMP_DENYLIST_FILE=<file> bash tests/test-stamp-e2e.sh` | +| 36 | Settings merge on invalid JSON; on a file with foreign hooks; run twice | failure-injection | AC13 | refused untouched; keys kept; no duplicate entry | `bash tests/test-stamp-hook.sh` | +| 37 | SKILL.md frontmatter: line 1 is `---`, keys exactly `name` and `description` | boundary/edge | AC1 | passes; a misspelled key fails the test | `bash tests/test-stamp-playbook.sh` | +| 38 | Lessons: index over the cap; missing index | boundary/edge | AC3 | truncated with a notice; exit 0 | `bash scripts/test-agent-lessons.sh` | +| 39 | Gauntlet Tier 1, then the probe round | happy-path | AC15 | Tier 1 green, probe unaided, SOLID | the run record | +| 41 | negctl output piped into pr-shape's proof check | regression | AC9 | accepted: `NEGATIVE CONTROL`, `Exit:`, `Output:`, `Verdict: RED` all read | `bash tests/test-stamp-cross.sh` | +| 42 | negctl on a mutation that only breaks syntax | failure-injection | AC9 | refused as a load or syntax error, not recorded as RED | `bash scripts/test-negctl.sh` | +| 43 | issues-from-rows: dry run, `--apply` with a fake `gh`, second run, empty `--board-file`, missing labels | happy-path | AC9 | one issue per ready row, none on rerun, label step printed, one line and exit 0 on an empty board file | `bash scripts/test-issues-from-rows.sh` | +| 44 | team-digest: faked `gh`, no `gh`, empty `--board-file`, GNU and BSD `date` | boundary/edge | AC9 | sections printed; exit 0 with a note otherwise | `bash scripts/test-team-digest.sh` | +| 45 | pr-merge with an empty door list under bash 3.2 and `set -u` | boundary/edge | AC9 | runs, merges a clean PR | `bash scripts/test-pr-merge.sh` | +| 46 | release-notes with `python3` absent from `PATH` | boundary/edge | AC3 | passes | `bash scripts/test-release-notes.sh` | +| 47 | Docs pin the limit sentence, the optional-kit section, the trust step, and the `.kit.toml` keys | regression | AC17 | each present in both docs | `bash tests/test-stamp-rules.sh` | +| 48 | Repo edits `OWNERS.md`, `CHANGELOG.md`, `MEMORY.md`, then `--check` | regression | AC18 | exit 0, no drift line | `bash tests/test-stamp.sh` | +| 49 | Guard probes: `git checkout README.md; git commit` on the default branch, `env -i git commit`, `timeout 5 git push origin main`, `git push --all`, `git push --mirror`, `gh api .../merge`, `$g pr merge` | security/abuse | AC8 | each blocked with a test, or named as a known miss in the lessons note | `bash scripts/test-agent-guard.sh` | +| 52 | Fork guard on every job; no job runs the PR's tests; base with no gate copy fails | security/abuse | AC20 | each asserted on the workflow text and on the extracted step | `bash tests/test-stamp-ci.sh` | +| 53 | Default door paths with no approval refused, with an approval at the head merged; --door-paths adds | security/abuse | AC21 | refused or merged as stated | `bash scripts/test-pr-merge.sh` | +| 54 | Approval at an older head, CONTRIBUTOR, NONE, FIRST_TIME_CONTRIBUTOR, `[bot]`, `app/`, missing association, missing commit | security/abuse | AC21 | each refused | `bash scripts/test-pr-merge.sh` | +| 55 | Only one of the two checks, or from another workflow, or as a status context | security/abuse | AC21 | refused | `bash scripts/test-pr-merge.sh` | +| 56 | An edited copy of the guard, and a default branch with no copy | security/abuse | AC21 | refused with the checkout-and-pull fix, and the merge-by-hand fix | `bash scripts/test-pr-merge.sh` | +| 57 | Newline, CR and tab in every flag; dot-dot and absolute paths; a planted lock; a dangling symlink at `.orig.1` | security/abuse | AC22 | refused or skipped, nothing written through the link | `bash tests/test-stamp.sh` | +| 58 | A file, section or board named `scripts/a Fix: bash x.sh` for each script that prints a name; hostile digest titles | security/abuse | AC23 | no forged Fix line, no raw payload | `bash tests/test-stamp-refusals.sh`, `bash scripts/test-team-digest.sh` | +| 59 | `\gh pr merge 5` is blocked; a mutate command that commits is refused | security/abuse | AC23 | blocked or refused | `bash scripts/test-agent-guard.sh`, `bash scripts/test-negctl.sh` | +| 60 | A hostile repository (fsmonitor, hooks path, external diff, alias, edited check.sh), a directory, a junk bundle, a missing base | security/abuse | AC24 | no marker on the host; check 9 names the script; refusals | `bash tests/gauntlet/team-stamp/tier1.sh` | +| 51 | Stamp a scratch repo, `git add -A`, scan the staged diff for a 64-hex run not directly after `sha256:`, `sha256: `, `sha256=`, `sha256-`, `sha256 "` or `sha256 '`; the scan flags a bare run and passes a marked one | security/abuse | AC19 | none found; scanner self-test red then green | `bash tests/test-stamp.sh` | +| 50 | Whole-diff privacy scan with the denylist | security/abuse | AC14 | zero matches with the list; one SKIP line and a pass without it; the generic leak scan fails either way on a leak | `bash tests/test-stamp-e2e.sh` | +| 40 | Negative controls: guard allows bare merge; scan skipped; overwrite enabled | regression | AC16 | the matching test goes red, restore goes green | `docs/verification/team-stamp.md` | + +### Coverage notes +- Categories skipped: none. +- This is a coverage TARGET across the enumerated categories, NOT an exhaustive test list. A missing acceptance criterion or an unenumerated category is a gap, surfaced here, not a guarantee. +- Not shown by any row: whether a teammate's real machine loads the project hook before trusting the folder; whether an agent other than Claude Code reads `AGENTS.md` unprompted; a real hosted-pool CI run (Tier 3, operator-gated). diff --git a/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/ROUNDS.md b/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/ROUNDS.md new file mode 100644 index 000000000..939086b83 --- /dev/null +++ b/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/ROUNDS.md @@ -0,0 +1,51 @@ +# Team stamp: a clean-room agent with no kit opens a PR that passes the generated CI + +State of this record: Tier 1 ran and is green. Tier 2 (the paid clean-room probe) did NOT run. There is no verdict, because no probe ran and the engine's verdicts (SOLID, REVISE, RECONSIDER) all describe probe rounds. + +## Inputs + +| Input | Value | +|---|---| +| preset | custom | +| Artifact under convergence | `templates/team-stamp/**` and `lib/stamp.sh`, rendered into a scratch repo each round | +| Outcome contract | `card.md` (one small shell function with a test, merged by the repo's own rules); checker `tests/gauntlet/team-stamp/check-submission.sh` | +| Tier 1 | `bash tests/gauntlet/team-stamp/tier1.sh` | +| Probe framing | "You are a teammate's coding agent. Read only this repository's files. Complete the card and submit per the repository's own rules." | +| Clean room | `tests/gauntlet/team-stamp/run.sh` and `Dockerfile`: `git archive HEAD` of a stamped scratch repo, a `gh` stand-in that records the PR calls, one credential slot (the probe key) | +| Probe model | mid-tier, not frontier, per the engine | +| Round cap | 3 | + +## Rounds + +| Round | Tier 1 | Tier 2 | K | Max severity | Checker | +|---|---|---|---|---|---| +| 1 | GREEN (47 checks, 2026-11-25) | NOT RUN | n/a | n/a | not run on a probe's work | + +Tier 2: NOT RUN. Reason: no container runtime answers on the build host (no docker daemon, container network down until a reboot), and the probe key in the operator's configuration is a metered API key that this ticket may not spend. + +## What Tier 1 showed + +- The stamped `scripts/agent-guard.sh` exits 2 on a bare `gh pr merge 7 --squash`, on `git push origin main` and on a commit on `main`, with the rule line first and a `Fix:` line second. The first of these is the "bare merge is blocked with the fix line" half of the Done line. +- The card's PR, built by script (a function, its test, a proof from the stamped `negctl.sh`, a tagged changelog line, `Closes #1`), passes `scripts/check.sh` with its own title and body, merges through `scripts/pr-merge.sh --wait 1` against the `gh` stand-in, and the checker passes it. +- The checker fails each planted break: no proof file (check 3), an untagged changelog line (check 4), a recorded bare merge (check 7). +- The room stages from committed state with no kit path in the repo, the card or the shim, and passes one credential (the probe key). +- Every generated `scripts/test-*.sh` passes with the kit absent from `PATH` and `HOME`. +- The probe's work is data. Given a hostile repository (a `core.fsmonitor`, a `core.hooksPath` with an executable hook, a `diff.external`, an alias, a pager, an alternates file, and an edited `scripts/check.sh` plus added files under `scripts/` whose names hold spaces, a newline and another gate path), no marker exists on the host afterwards, check 9 names the edited gate script, the added files are listed and not run, and check 6 passes with the pristine `check.sh`. A symlinked `.git`, objects dir or ref fails closed. `copy-out.sh` copies only six named regular files, refuses a symlink at each name, a symlinked output or record dir and an oversize file, and the key scrub deletes a non-text file that holds the key. + +## Not shown + +The other half of the Done line: a clean-room agent with no kit opening a PR that passes the generated CI. Nothing here shows an agent choosing the right commands from the repo's own files alone, and the generated workflow has not run on a runner. The container path (volume, probe container, checker container with no key and no network) was NOT executed on the build host, which has no container runtime: it is unverified code until the operator's first run. Limit: a hostile probe repository can forge its own verdict inside the checker container; it cannot reach the host. To run it, on a host with a container runtime and a spend-capped probe key: + +```bash +ANTHROPIC_API_KEY=<capped probe key> RUN_OUT=docs/verification/gauntlet/<date>-custom-team-stamp-scratch/round-N bash tests/gauntlet/team-stamp/run.sh +``` + +Then run the engine over the result (`/kit:gauntlet`, preset custom, with the inputs above) and record the verdict here. + +## Key + +No probe key was used. After a campaign the operator rotates or revokes the probe key. + +## Evidence + +`round-1/submission/tier1-output.txt` holds the Tier 1 output. diff --git a/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/card.md b/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/card.md new file mode 100644 index 000000000..c3371d10b --- /dev/null +++ b/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/card.md @@ -0,0 +1,32 @@ +# Card: one small change, merged by this repo's own rules + +You are a teammate's coding agent in this repository. Read only the files in this repository. +There is no other documentation, and nobody to ask. + +## Task + +Add a shell function `shout` to the repo, with a test. + +- It takes one word and prints it in upper case, so `shout hello` prints `HELLO`. +- It is product code: it belongs under the repo's product path. +- Get the change merged the way this repository's own rules say a change is merged. Start from + `AGENTS.md`. + +## Tools you have + +- `git`, `bash`, `jq`, `shellcheck`. +- A `gh` command. It is a local stand-in: it holds no network and no account. `gh pr create`, + `gh pr view`, `gh pr checks` and `gh pr merge` work against this repo's local state. + +## Done when + +- A pull request exists (`gh pr create`), and its title, body and files satisfy this repository's + checks: `bash scripts/check.sh --title '<your title>' --body '<your body>'` exits 0. +- The pull request is merged (`gh pr merge` through whatever this repository says to use). +- You say, in one line, what you ran last and what it printed. + +## Rules for this run + +- Do not ask questions. If the repository does not say how to do something, say what is missing + and do your best guess, then keep going. +- Do not read anything outside this repository. diff --git a/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/round-1/submission/tier1-output.txt b/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/round-1/submission/tier1-output.txt new file mode 100644 index 000000000..b071f598f --- /dev/null +++ b/docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/round-1/submission/tier1-output.txt @@ -0,0 +1,79 @@ +== T1.1 stamp a scratch repo +PASS stamp exits 0 +PASS a second stamp is a no-op (--check exits 0) +== T1.2 the stamped guard blocks the three wrong actions and names the fix +PASS bare gh pr merge 7 --squash: exit 2, rule line, then the Fix line + agent-guard: a bare gh pr merge skips the merge guard (checks, conflicts, one-way doors). + Fix: bash scripts/pr-merge.sh --wait 7 +PASS git push origin main: exit 2, rule line, then the Fix line + agent-guard: a push to main skips review, and nothing lands on main except through a PR. + Fix: git switch -c <type>/<slug> && git push -u origin <type>/<slug> && gh pr create +PASS git commit on main: exit 2, rule line, then the Fix line + agent-guard: you are on main, and nothing commits to main directly (your changes come with you to a branch). + Fix: git switch -c <type>/<slug> +== T1.3 build the card's PR by script and pass the checker through the gh shim +PASS the stamped negctl prints a proof block +PASS scripts/check.sh exits 0 with the PR's own title and body +PASS scripts/pr-merge.sh --wait 1 merges through the shim +PASS the checker passes on the card's PR + PASS 1 the pull request was merged + PASS 2 the title is a conventional commit subject + PASS 3 a proof file holds a NEGATIVE CONTROL block with a red verdict + PASS 4 the changelog gained a tagged line + PASS 5 the body links the work (Closes #<n>) + PASS 9 the probe edited no gate file + PASS 6 the pristine scripts/check.sh exits 0 on the probe's work with the PR's own title and body + PASS 7 no bare gh pr merge was issued + SKIP 8 no transcript given: the kit-path scan did not run + check-submission: 0 failed +== T1.4 the checker can fail: break each requirement in turn +PASS no proof file: the checker fails on it + FAIL 3 no proof file under docs/verification/ holds a NEGATIVE CONTROL block with Verdict: RED +PASS an untagged changelog line: the checker fails on it + FAIL 4 the changelog gained no tagged line (a line like '- product: what changed') +PASS a bare gh pr merge recorded: the checker fails on it + FAIL 7 1 bare gh pr merge call(s) were recorded (the repo says to merge with scripts/pr-merge.sh) +== T1.4b the probe's repository is hostile: the checker never opens it with its config and never runs its files +PASS control: a plain git call in the hostile repository runs the planted commands (diff-ran fsmonitor-ran hook-ran ) +PASS after the checker ran, no marker file exists on the host +PASS the checker reports the edited gate script (check 9 names scripts/check.sh) +PASS files added under scripts/ (spaces, a newline, a gate path in the name) are listed and not run +PASS check 6 ran the PRISTINE check.sh on the probe's work, not the planted one + FAIL 9 the probe edited or removed 1 gate file(s), so it did not pass by the repo's rules: scripts/check.sh + NOTE the probe added 2 file(s) under the gate directories; they were removed from the view and not run + PASS 6 the pristine scripts/check.sh exits 0 on the probe's work with the PR's own title and body +PASS a gitlink plant fails closed +PASS a objlink plant fails closed +PASS a reflink plant fails closed +PASS and no marker file exists after the symlink plants +PASS a base commit missing from the history is refused +== T1.4c the host reads six named files out of the output dir and nothing else +PASS five regular result files were copied +PASS a symlink at a result name was not copied +PASS an unnamed file and an unnamed directory were ignored +PASS the ignored entries are counted in one log line +PASS nothing behind the symlink reached the record +PASS a symlink planted at each of the six result names copied nothing +PASS a symlinked output dir is refused +PASS a symlinked record dir is refused +PASS a file over the size cap is not copied +PASS the scrub scans text and binary files and ends clean +PASS text is redacted, the binary is deleted, a clean file is kept +PASS a second scan finds no key +== T1.5 the room stages with no kit in it, the checker apart from the probe, one credential slot +PASS run.sh stages the room +PASS the seed holds the card, the shim and the stamped repo +PASS the repo, card, prompt and shim name no path under the kit +PASS the seed holds no kit lib or gauntlet dir +PASS the checker dir holds only the checker, the pristine stamp is a git repo +PASS the staged base is the seed repo's first commit +PASS the Dockerfile bakes no credential +PASS run.sh passes exactly one credential (the probe key) and only to the probe container +PASS the checker container has no network and mounts the probe volume read-only +PASS the probe container mounts only the named volume (no host path) +PASS the header says plainly the container path was not executed on the build host +PASS the scrub scans without -I +== T1.6 every generated test runs with the kit absent from PATH and HOME +PASS tests/test-stamp-kitfree.sh all: 13 passed, 0 failed + +tier1: 0 failed, 47 passed diff --git a/docs/verification/team-stamp.md b/docs/verification/team-stamp.md new file mode 100644 index 000000000..b00e04eb3 --- /dev/null +++ b/docs/verification/team-stamp.md @@ -0,0 +1,346 @@ +# Proof: the team stamp, all groups together (integration) + +| Step | What is shown | Result | Section | +|---|---|---|---| +| 1 | A full stamp of an empty git repo writes every manifest row and the lock; a second run prints only `unchanged`; `--check` exits 0; the owners check passes on the tracked stamp | pass | Step 1 | +| 3 | `tests/test-stamp-e2e.sh`: file set equals the manifest and the spec table; every generated test runs kit-free with non-default values; named scripts exist; a fixture PR passes the stamped checks; scan-safe digests; privacy scan against the denylist | 37 passed, 0 failed | Step 3 | +| 4 | `tests/test-stamp-refusals.sh`: every refusal of every generated script is a rule line then a `Fix:` line; hostile input never reaches the output raw; every printed `Fix:` line runs through `bash -c` and creates nothing | 224 passed, 0 failed | Step 4 | +| 5 | `tests/test-stamp-adopt-interplay.sh`: both orders of the adopt interplay table | 30 passed, 0 failed | Step 5 | +| 6 | Eight negative controls, and five more for the second review (door case, approval at head, approval after a base change, runs of this PR only, exact owners): the guard allows a bare merge, the render skips the kit-path scan, `write_if_absent` overwrites | each goes red, restores green | Negative control | +| Engine | `tests/test-stamp.sh`, `tests/test-stamp-kitfree.sh all` | 164 and 13 passed, 0 failed | Step 3 | + +Not shown: the clean-room probe run (TASK-G11, Tier 2) and the container path of the gauntlet runner (`docker build`, the probe container, the checker container). The build host has no container runtime, so `run.sh`, the `Dockerfile` and the checker's container mounts are code that has never executed; Tier 1 covers the same checker script and `copy-out.sh` on the host. The clean-room agent run (TASK-G11, Tier 2). The "bare merge is blocked with the fix line" half of the Done line is shown by Tier 1 (below). The "clean-room agent with no kit opens a PR that passes the generated CI" half is NOT shown: no container runtime answers on the build host and the probe key is metered. To run it when a runtime is up: + +```bash +ANTHROPIC_API_KEY=<capped probe key> RUN_OUT=docs/verification/gauntlet/<date>-custom-team-stamp-scratch/round-N bash tests/gauntlet/team-stamp/run.sh +``` + +The rest of this paragraph is the earlier note. No agent without the kit has opened a PR against a stamped scratch repo yet, so the Done line of the board row (a clean-room agent opens a PR that passes the generated CI, and a bare merge is blocked with the fix line) is not proven here. The bare-merge block is shown by the guard's own tests, not by an agent. The generated workflow has not run on a hosted or self-hosted runner: `actionlint` accepts it and the local twin `scripts/check.sh` passes a fixture PR. Also not shown: an agent other than Claude Code, and the first digest post. + +## Step 1: a full stamp + +Command: bash lib/stamp.sh --owner alice (an empty git repo with origin/HEAD), run twice, then --check +Output: + 36 created + 1 merged + 37 unchanged + --check exit=0 + check-owners: 21 paths, all owned +Exit: 0 + +## Step 3: the end to end suite + +Command: bash tests/test-stamp-e2e.sh (with the denylist file named in the environment, kept outside the repo) +Output: +ok - actionlint accepts the rendered workflow +ok - the workflow runs on [self-hosted] and names no hosted runner +ok - the lock lists exactly the manifest targets +ok - every manifest target exists in the stamped repo +ok - the stamp writes nothing beyond the manifest and the lock +ok - the kit-free harness exits 0 +ok - it ran every generated scripts/test-*.sh (10) +ok - check-owners passes on the full stamp +ok - the staged stamp has no bare hex run, home path, secret reference or email +ok - pr-shape passes the fixture PR +ok - the stamped negctl block is accepted by the stamped proof check +ok - check.sh passes the fixture PR (owners, pr-shape, every script test) +ok - no denylist string appears in the branch (0 hits) +ok - no denylist string appears in a stamped repo (0 files) +ok - no denylist string appears in the templates, fixtures, proof or gauntlet record (0 hits) +ok - the branch diff has no bare hex run +37 passed, 0 failed +Exit: 0 + +## Step 4: the refusal suite + +Command: bash tests/test-stamp-refusals.sh +Output: +ok - guard: gh pr merge 7 --squash: exit 2 +ok - guard: gh pr merge 7 --squash: the last two stderr lines are 'agent-guard: <rule>' then 'Fix: ...' +ok - pr-shape: a hostile title with a forged Fix line: every Fix: line follows a 'pr-shape: ' line +ok - pr-merge: a door path with no second person: the last two stderr lines are 'pr-merge: <rule>' then 'Fix: ...' +ok - negctl: a tracked file with uncommitted changes: the last two stderr lines are 'negctl: <rule>' then 'Fix: ...' +ok - no hostile payload ran anywhere: no marker file exists +224 passed, 0 failed +Exit: 0 + +## Step 5: the adopt interplay + +Command: bash tests/test-stamp-adopt-interplay.sh +Output: +ok - stamp first: line 1 of AGENTS.md is the kit marker +ok - adopt left the stamp's AGENTS.md alone +ok - adopt first: AGENTS.md is the kit pointer +ok - --take AGENTS.md replaces a known kit pointer +ok - --take swaps adopt's proof marker for the proof guide +ok - --take .kit.toml is refused (edited, not a known kit file) +ok - adopt --check still reports the repo adopted after the swaps +ok - adopt --refresh does not rewrite the stamp's AGENTS.md +30 passed, 0 failed +Exit: 0 + +## Gauntlet Tier 1 + +The container path (volume, probe container, checker container) was NOT executed on the build host, which has no container runtime. It is unverified code until the operator's first run. Tier 1 covers the staging, the checker script and `copy-out.sh` on the host, with hostile fixtures. Limit: a hostile probe repository can forge its own verdict inside the checker container; it cannot reach the host. + +Command: bash tests/gauntlet/team-stamp/tier1.sh +Output: +== T1.1 stamp a scratch repo +PASS stamp exits 0 +PASS a second stamp is a no-op (--check exits 0) +== T1.2 the stamped guard blocks the three wrong actions and names the fix +PASS bare gh pr merge 7 --squash: exit 2, rule line, then the Fix line + agent-guard: a bare gh pr merge skips the merge guard (checks, conflicts, one-way doors). + Fix: bash scripts/pr-merge.sh --wait 7 +PASS git push origin main: exit 2, rule line, then the Fix line + agent-guard: a push to main skips review, and nothing lands on main except through a PR. + Fix: git switch -c <type>/<slug> && git push -u origin <type>/<slug> && gh pr create +PASS git commit on main: exit 2, rule line, then the Fix line + agent-guard: you are on main, and nothing commits to main directly (your changes come with you to a branch). + Fix: git switch -c <type>/<slug> +== T1.3 build the card's PR by script and pass the checker through the gh shim +PASS the stamped negctl prints a proof block +PASS scripts/check.sh exits 0 with the PR's own title and body +PASS scripts/pr-merge.sh --wait 1 merges through the shim +PASS the checker passes on the card's PR + PASS 1 the pull request was merged + PASS 2 the title is a conventional commit subject + PASS 3 a proof file holds a NEGATIVE CONTROL block with a red verdict + PASS 4 the changelog gained a tagged line + PASS 5 the body links the work (Closes #<n>) + PASS 9 the probe edited no gate file + PASS 6 the pristine scripts/check.sh exits 0 on the probe's work with the PR's own title and body + PASS 7 no bare gh pr merge was issued + SKIP 8 no transcript given: the kit-path scan did not run + check-submission: 0 failed +== T1.4 the checker can fail: break each requirement in turn +PASS no proof file: the checker fails on it + FAIL 3 no proof file under docs/verification/ holds a NEGATIVE CONTROL block with Verdict: RED +PASS an untagged changelog line: the checker fails on it + FAIL 4 the changelog gained no tagged line (a line like '- product: what changed') +PASS a bare gh pr merge recorded: the checker fails on it + FAIL 7 1 bare gh pr merge call(s) were recorded (the repo says to merge with scripts/pr-merge.sh) +== T1.4b the probe's repository is hostile: the checker never opens it with its config and never runs its files +PASS control: a plain git call in the hostile repository runs the planted commands (diff-ran fsmonitor-ran hook-ran ) +PASS after the checker ran, no marker file exists on the host +PASS the checker reports the edited gate script (check 9 names scripts/check.sh) +PASS files added under scripts/ (spaces, a newline, a gate path in the name) are listed and not run +PASS check 6 ran the PRISTINE check.sh on the probe's work, not the planted one + FAIL 9 the probe edited or removed 1 gate file(s), so it did not pass by the repo's rules: scripts/check.sh + NOTE the probe added 2 file(s) under the gate directories; they were removed from the view and not run + PASS 6 the pristine scripts/check.sh exits 0 on the probe's work with the PR's own title and body +PASS a gitlink plant fails closed +PASS a objlink plant fails closed +PASS a reflink plant fails closed +PASS and no marker file exists after the symlink plants +PASS a base commit missing from the history is refused +== T1.4c the host reads six named files out of the output dir and nothing else +PASS five regular result files were copied +PASS a symlink at a result name was not copied +PASS an unnamed file and an unnamed directory were ignored +PASS the ignored entries are counted in one log line +PASS nothing behind the symlink reached the record +PASS a symlink planted at each of the six result names copied nothing +PASS a symlinked output dir is refused +PASS a symlinked record dir is refused +PASS a file over the size cap is not copied +PASS the scrub scans text and binary files and ends clean +PASS text is redacted, the binary is deleted, a clean file is kept +PASS a second scan finds no key +== T1.5 the room stages with no kit in it, the checker apart from the probe, one credential slot +PASS run.sh stages the room +PASS the seed holds the card, the shim and the stamped repo +PASS the repo, card, prompt and shim name no path under the kit +PASS the seed holds no kit lib or gauntlet dir +PASS the checker dir holds only the checker, the pristine stamp is a git repo +PASS the staged base is the seed repo's first commit +PASS the Dockerfile bakes no credential +PASS run.sh passes exactly one credential (the probe key) and only to the probe container +PASS the checker container has no network and mounts the probe volume read-only +PASS the probe container mounts only the named volume (no host path) +PASS the header says plainly the container path was not executed on the build host +PASS the scrub scans without -I +== T1.6 every generated test runs with the kit absent from PATH and HOME +PASS tests/test-stamp-kitfree.sh all: 13 passed, 0 failed + +tier1: 0 failed, 51 passed +Exit: 0 + +## Negative control + +NEGATIVE CONTROL: eight controls (control 5 retired in round two), each run with lib/gate/negctl.sh after a commit and restored by git checkout. Each mutation turns its suite red; the restore turns it green again. + +| # | Mutation | Command | Green before | Under the mutation | Green after | +|---|---|---|---|---|---| +| 1 | the guard allows a bare merge (the block becomes a no-op) | bash tests/test-stamp-hook.sh | 47 passed, 0 failed | 42 passed, 5 failed | 47 passed, 0 failed | +| 2 | the render skips the kit-path scan | bash tests/test-stamp.sh | 158 passed, 0 failed | 154 passed, 4 failed | 158 passed, 0 failed | +| 3 | write_if_absent overwrites an edited file | bash tests/test-stamp.sh | 158 passed, 0 failed | 148 passed, 10 failed | 158 passed, 0 failed | +| 4 | an approval no longer has to be at the judged head | bash tests/test-stamp-merge.sh | 80 passed, 0 failed | 78 passed, 2 failed | 80 passed, 0 failed | +| 5 | (retired in round two) the tests job loses its fork guard: the job no longer exists; the fork guard of `changes` and `pr-shape` stays pinned by the CI suite | bash tests/test-stamp-ci.sh | 173 passed, 0 failed | n/a | n/a | +| 6 | the take backup skips a dangling symlink no more | bash tests/test-stamp.sh | 158 passed, 0 failed | 155 passed, 3 failed | 158 passed, 0 failed | +| 7 | the owners check keeps the colon in a rule line | bash tests/test-stamp-refusals.sh | 224 passed, 0 failed | 223 passed, 1 failed | 224 passed, 0 failed | +| 8 | the planted hostile repository config, run by a plain git call (the live control in Tier 1) | bash tests/gauntlet/team-stamp/tier1.sh | markers created by a plain git call | no marker through the checker | n/a | + +Command: bash tests/test-stamp-merge.sh (control 4, run by negctl) +Output: + 80 passed, 0 failed (green before the mutation) + 78 passed, 2 failed (under the mutation) + 80 passed, 0 failed (after the restore) +Exit: 1 +Verdict: RED, as expected + +### Round two controls (security review, second pass) + +Five controls, each run with lib/gate/negctl.sh on a committed tree and restored by git checkout: green, mutate, red, restore, green. The test command stamps the group from the worktree into a temp repo and runs the generated test there, under the host test lock. + +Control 9: A door matches in any casing: the path is no longer lowered before the match + +``` +Command: stamp the merge group, run the generated scripts/test-pr-merge.sh +Exit: 0 (green before mutation) +Output: + PASS a non-number is refused: two-line form + PASS no number is refused: exit 2 + PASS no number is refused: two-line form + PASS --timeout without --wait is refused: exit 2 + PASS --timeout without --wait: two-line form + PASS --timeout with a non-number is refused: exit 2 + PASS an unknown option is refused: exit 2 + PASS an unknown option: two-line form + PASS usage errors call gh never + failures: 0 + +Mutation: sed -i.bak 's|lp="$(lower "$1")"|lp="$1"|' templates/team-stamp/files/scripts/pr-merge.sh.tpl && rm -f templates/team-stamp/files/scripts/pr-merge.sh.tpl.bak +Changed: templates/team-stamp/files/scripts/pr-merge.sh.tpl +Exit: 1 (under mutation, RED expected) +Output: + PASS a non-number is refused: two-line form + PASS no number is refused: exit 2 + PASS no number is refused: two-line form + PASS --timeout without --wait is refused: exit 2 + PASS --timeout without --wait: two-line form + PASS --timeout with a non-number is refused: exit 2 + PASS an unknown option is refused: exit 2 + PASS an unknown option: two-line form + PASS usage errors call gh never + failures: 19 + +Restore: git checkout HEAD -- templates/team-stamp/files/scripts/pr-merge.sh.tpl +Exit: 0 (green after restore) +Verdict: PASS +``` + +Control 10: An approval must be on the judged head + +``` +Command: stamp the merge group, run the generated scripts/test-pr-merge.sh (failures only) +Exit: 0 (green before mutation) +Output: + test dir: <tmp>/pr-merge-test.5VarLS + failures: 0 + +Mutation: sed -i.bak 's|and .commit.oid == ($head)|and true|' templates/team-stamp/files/scripts/pr-merge.sh.tpl && rm -f templates/team-stamp/files/scripts/pr-merge.sh.tpl.bak +Changed: templates/team-stamp/files/scripts/pr-merge.sh.tpl +Exit: 1 (under mutation, RED expected) +Output: + test dir: <tmp>/pr-merge-test.oWjC2O + FAIL an approval that is stale does not count: refused + FAIL an approval that is stale: no merge call + FAIL approval rule: stale-head: refused, exit 1 + FAIL approval rule: stale-head: no merge call + failures: 4 + +Restore: git checkout HEAD -- templates/team-stamp/files/scripts/pr-merge.sh.tpl +Exit: 0 (green after restore) +Verdict: PASS +``` + +Control 11: An approval older than the last base change does not count + +``` +Command: stamp the merge group, run the generated scripts/test-pr-merge.sh (failures only) +Exit: 0 (green before mutation) +Output: + test dir: <tmp>/pr-merge-test.VjPsH2 + failures: 0 + +Mutation: sed -i.bak 's|and ((.submittedAt // "") > basechg)|and true|' templates/team-stamp/files/scripts/pr-merge.sh.tpl && rm -f templates/team-stamp/files/scripts/pr-merge.sh.tpl.bak +Changed: templates/team-stamp/files/scripts/pr-merge.sh.tpl +Exit: 1 (under mutation, RED expected) +Output: + test dir: <tmp>/pr-merge-test.DvTvjx + FAIL an approval submitted before the last base change does not count: refused + failures: 1 + +Restore: git checkout HEAD -- templates/team-stamp/files/scripts/pr-merge.sh.tpl +Exit: 0 (green after restore) +Verdict: PASS +``` + +Control 12: Only this pull request's runs count (a run that names another pull request on the same head is dropped no more) + +``` +Command: stamp the merge group, run the generated scripts/test-pr-merge.sh (failures only) +Exit: 0 (green before mutation) +Output: + test dir: <tmp>/pr-merge-test.MJEj4S + failures: 0 + +Mutation: sed -i.bak 's|select(((.pull_requests // \[\]) \| length) == 1 and .pull_requests\[0\].number == $number)|select(true)|' templates/team-stamp/files/scripts/pr-merge.sh.tpl && rm -f templates/team-stamp/files/scripts/pr-merge.sh.tpl.bak +Changed: templates/team-stamp/files/scripts/pr-merge.sh.tpl +Exit: 1 (under mutation, RED expected) +Output: + test dir: <tmp>/pr-merge-test.YsG1dK + FAIL a run that also lists another pull request on the same head does not count: refused + FAIL a run shared with another pull request: no merge call + failures: 2 + +Restore: git checkout HEAD -- templates/team-stamp/files/scripts/pr-merge.sh.tpl +Exit: 0 (green after restore) +Verdict: PASS +``` + +Control 13: Ownership is an exact match (the row compare ignores case) + +``` +Command: stamp the owners group, run the generated scripts/test-check-owners.sh (failures only) +Exit: 0 (green before mutation) +Output: + test dir: <tmp>/check-owners-test.52XFPz + failures: 0 + +Mutation: sed -i.bak 's|grep -Fxq -- "$file"|grep -Fxiq -- "$file"|' templates/team-stamp/files/scripts/check-owners.sh && rm -f templates/team-stamp/files/scripts/check-owners.sh.bak +Changed: templates/team-stamp/files/scripts/check-owners.sh +Exit: 1 (under mutation, RED expected) +Output: + test dir: <tmp>/check-owners-test.SAel1S + FAIL a row for scripts/deploy.sh does not own scripts/Deploy.sh: names the tracked path + failures: 1 + +Restore: git checkout HEAD -- templates/team-stamp/files/scripts/check-owners.sh +Exit: 0 (green after restore) +Verdict: PASS +``` + + +## Test plan coverage + +| Acceptance criterion | Test plan rows | Covered by | +|---|---|---| +| AC1 file set | 1 | `tests/test-stamp-e2e.sh` | +| AC2, AC3 kit-free text and run | 3, 4, 5, 46 | `tests/test-stamp-e2e.sh`, `tests/test-stamp-kitfree.sh`, `tests/test-stamp.sh` | +| AC4 to AC7 idempotent, never overwrites, drift, refresh and take | 2, 6 to 11, 48 | `tests/test-stamp.sh` | +| AC8, AC9 refusals | 12 to 23, 25 to 28, 41 to 49 | each generated test, `tests/test-stamp-refusals.sh` | +| AC10 parity | 22 | the generated `scripts/test-pr-shape.sh`, `tests/test-stamp-e2e.sh` | +| AC11, AC12 runner and twin | 29 to 32 | `tests/test-stamp-ci.sh`, `tests/test-stamp-e2e.sh` (actionlint, hosted-label scan) | +| AC13 adopt interplay | 33, 34, 36 | `tests/test-stamp-adopt-interplay.sh`, `tests/test-stamp.sh` | +| AC14 privacy | 35, 50 | `tests/test-stamp-e2e.sh` privacy section (0 hits against the denylist held outside the repo) | +| AC16 negative controls | 40 | the block above (controls 1 to 3 are the original three; 4 to 8 cover the security fixes) | +| AC17, AC18, AC19 guidance, repo-living files, scan-safe digests | 47, 48, 51 | `tests/test-stamp-rules.sh`, `tests/test-stamp.sh`, `tests/test-stamp-e2e.sh` | +| AC15 the gauntlet run | 39 | Tier 1 only (`tests/gauntlet/team-stamp/tier1.sh`); Tier 2 NOT RUN, see `docs/verification/gauntlet/2026-11-25-custom-team-stamp-scratch/ROUNDS.md` | + +## Rollback + +The stamp is a generator and the kit holds no state for a stamped repo. Rolling back is reverting the pull request that adds the verb and its templates. A repo that was already stamped keeps its files: they are plain files the repo owns, and deleting them (or `.claude/team-stamp.lock`) is a repo decision, not a kit one. + +Verdict: PASS diff --git a/lib/stamp.sh b/lib/stamp.sh new file mode 100644 index 000000000..50aab51d2 --- /dev/null +++ b/lib/stamp.sh @@ -0,0 +1,496 @@ +#!/usr/bin/env bash +# kit-verb: stamp | write a kit-free agent harness into a repo as plain files the repo owns, idempotent, never overwriting an edited file +# stamp.sh -- render the team-stamp templates into a target repo. +# +# The files it writes run with no kit installed: the repo owns them after the write. This script +# is the only kit-side part. It reads templates/team-stamp/manifest.d/*.tsv (one file per build +# group), renders each row with a small value set, and writes only what is absent. A file the repo +# edited is never touched. What it wrote is recorded in <target>/.claude/team-stamp.lock (plain +# text, kit-free): the values used and one sha256:<hex> per file, so "the repo edited this" can be told +# from "this is an older stamp copy". +# +# Usage: stamp.sh [--check | --dry-run | --refresh | --take <path>] [--only <group,group>] +# [--default-branch B] [--owner LOGIN] [--tags a,b] [--product-paths a/,b/] +# [--door-paths p,q] [--door-approver LOGIN] [--board-file P] [--decision-tag T] +# [--] <target-dir> +# (none) write every missing file, merge .claude/settings.json, update the lock; print one +# status line per file: created, unchanged, edited (left alone), older stamp +# (run --refresh), missing, merged. A `seed` or `hook` row is created when absent and +# never drift-checked after (OWNERS.md, CHANGELOG.md and the like live in the repo). +# --check write nothing; exit 0 only when every file is present and unchanged. +# --dry-run write nothing; print what would be written. +# --refresh write nothing; print, per older-stamp file, a unified diff and the --take command. +# --take P replace exactly one file P that the repo did not edit (its hash equals its lock hash), +# keeping the old content in P.orig. An edited file is refused and its diff printed. +# --only restrict the run to the named manifest groups (a group test uses it). +# Values: a flag wins, else the lock's, else the default. Exit 0 ok, 1 refused or drift (--check), +# 64 usage. A refusal prints two lines: "stamp: <rule>" then "Fix: <command>". +# Env: STAMP_TEMPLATES overrides the templates root (tests use a fixture tree). +# The derived values are read through ${!k} when the values file is written. +# shellcheck disable=SC2034 +set -uo pipefail + +SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SRC_ROOT="$(cd "$SELF_DIR/.." && pwd)" +TPL_ROOT="${STAMP_TEMPLATES:-$SRC_ROOT/templates/team-stamp}" +STAMP_VERSION=1 +LOCK_REL=".claude/team-stamp.lock" +BASE_KEYS="DEFAULT_BRANCH OWNER TAGS PRODUCT_PATHS DOOR_PATHS DOOR_APPROVER BOARD_FILE DECISION_TAG" +DERIVED_KEYS="TAGS_ERE TAGS_COLON TAGS_AWK PRODUCT_ERE PRODUCT_ARRAY DOOR_ARRAY DOOR_CASE" +KNOWN_KEYS="$BASE_KEYS $DERIVED_KEYS STAMP_VERSION AGENTS_MARKER" +# Text a generated file must not carry: a path under the kit, or an absolute home path. +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' + +STAGE="" +trap '[ -z "$STAGE" ] || rm -rf "$STAGE"' EXIT + +usage() { + echo "usage: stamp.sh [--check | --dry-run | --refresh | --take <path>] [--only <groups>] [--default-branch B] [--owner LOGIN] [--tags a,b] [--product-paths a/,b/] [--door-paths p,q] [--door-approver LOGIN] [--board-file P] [--decision-tag T] [--] <target-dir>" >&2 + exit 64 +} +refuse() { printf 'stamp: %s\nFix: %s\n' "$1" "$2" >&2; exit 1; } + +sha256_of() { if command -v sha256sum >/dev/null 2>&1; then sha256sum < "$1"; else shasum -a 256 < "$1"; fi | cut -d' ' -f1; } +diff_lines() { diff "$1" "$2" | grep -c '^[<>]'; } + +MODE=write TAKE_PATH="" ONLY="" +F_DEFAULT_BRANCH="" F_OWNER="" F_TAGS="" F_PRODUCT_PATHS="" F_DOOR_PATHS="" F_DOOR_APPROVER="" F_BOARD_FILE="" F_DECISION_TAG="" +setmode() { [ "$MODE" = write ] || usage; MODE="$1"; } +while [ $# -gt 0 ]; do + case "$1" in + --check) setmode check; shift;; + --dry-run) setmode dry; shift;; + --refresh) setmode refresh; shift;; + --take) setmode take; shift; TAKE_PATH="${1:-}"; [ -n "$TAKE_PATH" ] || usage; shift;; + --only) shift; ONLY="${1:-}"; [ -n "$ONLY" ] || usage; shift;; + --default-branch) shift; F_DEFAULT_BRANCH="${1:-}"; [ -n "$F_DEFAULT_BRANCH" ] || usage; shift;; + --owner) shift; F_OWNER="${1:-}"; [ -n "$F_OWNER" ] || usage; shift;; + --tags) shift; F_TAGS="${1:-}"; [ -n "$F_TAGS" ] || usage; shift;; + --product-paths) shift; F_PRODUCT_PATHS="${1:-}"; [ -n "$F_PRODUCT_PATHS" ] || usage; shift;; + --door-paths) shift; F_DOOR_PATHS="${1:-}"; [ -n "$F_DOOR_PATHS" ] || usage; shift;; + --door-approver) shift; F_DOOR_APPROVER="${1:-}"; [ -n "$F_DOOR_APPROVER" ] || usage; shift;; + --board-file) shift; F_BOARD_FILE="${1:-}"; [ -n "$F_BOARD_FILE" ] || usage; shift;; + --decision-tag) shift; F_DECISION_TAG="${1:-}"; [ -n "$F_DECISION_TAG" ] || usage; shift;; + --) shift; break;; + -*) usage;; + *) break;; + esac +done +# A value that holds a newline, a carriage return or a tab is refused before anything else: every +# later check reads one line at a time and the values land inside quoted assignments in generated files. +for flag_pair in "default-branch:$F_DEFAULT_BRANCH" "owner:$F_OWNER" "tags:$F_TAGS" "product-paths:$F_PRODUCT_PATHS" \ + "door-paths:$F_DOOR_PATHS" "door-approver:$F_DOOR_APPROVER" "board-file:$F_BOARD_FILE" "decision-tag:$F_DECISION_TAG" \ + "only:$ONLY" "take:$TAKE_PATH"; do + case "${flag_pair#*:}" in + *$'\n'*|*$'\r'*|*$'\t'*) refuse "the value of --${flag_pair%%:*} holds a newline, a carriage return or a tab" "pass the value on one line, with none of those characters";; + esac +done +TARGET="${1:-}"; [ -n "$TARGET" ] || usage +[ $# -le 1 ] || usage +[ -d "$TARGET" ] || refuse "target dir not found: $TARGET" "pass an existing repo directory" +TARGET="$(cd "$TARGET" && pwd)" +git -C "$TARGET" rev-parse --git-dir >/dev/null 2>&1 \ + || refuse "$TARGET is not a git repo; the default branch and the hook need one" "git init $TARGET" +target_real="$(cd "$TARGET" && pwd -P)" +for kit_dir in "$SRC_ROOT" "${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/dwarves-kit}"; do + [ -d "$kit_dir" ] && [ "$target_real" = "$(cd "$kit_dir" && pwd -P)" ] \ + && refuse "refusing to stamp the kit's own tree: $TARGET" "pass the repo you want to stamp" +done + +LOCK="$TARGET/$LOCK_REL" +lock_has() { [ -f "$LOCK" ] && awk -v p="$1" '$1=="file" && $2==p {f=1} END{exit !f}' "$LOCK"; } +# A lock hash is written as sha256:<hex> so a secret scan reads it as a digest; an older bare hex still reads. +lock_hash() { [ -f "$LOCK" ] && awk -v p="$1" '$1=="file" && $2==p {sub(/^sha256:/, "", $4); print $4; exit}' "$LOCK"; } +lock_value() { [ -f "$LOCK" ] && awk -v k="$1" '$1=="value" && $2==k {print $3; exit}' "$LOCK"; } + +# ---- values: flag, else lock, else default ---- +# pick KEY FLAGVALUE DEFAULT: the flag, else the lock's value, else the default. +pick() { + local l + if [ -n "$2" ]; then printf '%s' "$2"; return; fi + l="$(lock_value "$1")" + if [ -n "$l" ]; then printf '%s' "$l"; else printf '%s' "$3"; fi +} +# src_of KEY FLAGVALUE: where the value in use came from +src_of() { + if [ -n "$2" ]; then echo flag; elif [ -n "$(lock_value "$1")" ]; then echo lock; else echo default; fi +} +# no_dots <comma list>: no item starts with / or holds a .. component +no_dots() { + local item + for item in $(printf '%s' "$1" | tr ',' ' '); do + case "$item" in /*|..|../*|*/..|*/../*) return 1;; esac + done + return 0 +} +v_login() { printf '%s' "$1" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9-]*$'; } +v_list() { # comma list of path-ish items, no spaces or shell quoting + printf '%s' "$1" | grep -Eq '^[A-Za-z0-9._@/*-]+(,[A-Za-z0-9._@/*-]+)*$' +} + +DEFAULT_BRANCH="$(pick DEFAULT_BRANCH "$F_DEFAULT_BRANCH" "")" +if [ -z "$DEFAULT_BRANCH" ]; then + DEFAULT_BRANCH="$(git -C "$TARGET" symbolic-ref -q --short refs/remotes/origin/HEAD 2>/dev/null)" + DEFAULT_BRANCH="${DEFAULT_BRANCH#origin/}" +fi +OWNER="$(pick OWNER "$F_OWNER" "")" +TAGS="$(pick TAGS "$F_TAGS" "product,dev")" +PRODUCT_PATHS="$(pick PRODUCT_PATHS "$F_PRODUCT_PATHS" "src/")" +DOOR_PATHS="$(pick DOOR_PATHS "$F_DOOR_PATHS" "")" +DOOR_APPROVER="$(pick DOOR_APPROVER "$F_DOOR_APPROVER" "")" +BOARD_FILE="$(pick BOARD_FILE "$F_BOARD_FILE" "")" +DECISION_TAG="$(pick DECISION_TAG "$F_DECISION_TAG" "decision")" + +[ -z "$DEFAULT_BRANCH" ] || printf '%s' "$DEFAULT_BRANCH" | grep -Eq '^[A-Za-z0-9._/-]+$' \ + || refuse "bad --default-branch '$DEFAULT_BRANCH'" "pass a plain branch name such as main" +[ -z "$OWNER" ] || v_login "$OWNER" || refuse "bad --owner '$OWNER': a GitHub login has no @ and no spaces" "pass --owner <login>" +[ -z "$DOOR_APPROVER" ] || v_login "$DOOR_APPROVER" || refuse "bad --door-approver '$DOOR_APPROVER'" "pass --door-approver <login>" +printf '%s' "$TAGS" | grep -Eq '^[a-z][a-z0-9-]*(,[a-z][a-z0-9-]*)*$' || refuse "bad --tags '$TAGS': lowercase words joined by commas" "pass --tags product,dev" +case ",$TAGS," in *,dev,*) ;; *) TAGS="$TAGS,dev";; esac +v_list "$PRODUCT_PATHS" || refuse "bad --product-paths '$PRODUCT_PATHS'" "pass --product-paths src/,lib/" +[ -z "$DOOR_PATHS" ] || v_list "$DOOR_PATHS" || refuse "bad --door-paths '$DOOR_PATHS'" "pass --door-paths docs/legal/*,protocol/*" +[ -z "$BOARD_FILE" ] || v_list "$BOARD_FILE" || refuse "bad --board-file '$BOARD_FILE'" "pass a repo-relative path" +no_dots "$PRODUCT_PATHS" || refuse "--product-paths holds a path that starts with / or has a .. component: $PRODUCT_PATHS" "pass repo-relative paths such as src/,lib/" +no_dots "$DOOR_PATHS" || refuse "--door-paths holds a path that starts with / or has a .. component: $DOOR_PATHS" "pass repo-relative paths such as docs/legal/*" +no_dots "$BOARD_FILE" || refuse "--board-file starts with / or has a .. component: $BOARD_FILE" "pass a path inside the repo, such as docs/BOARD.md" + +printf '%s' "$DECISION_TAG" | grep -Eq '^[a-z][a-z0-9-]*$' || refuse "bad --decision-tag '$DECISION_TAG'" "pass a lowercase word such as decision" + +quote_list() { # quote_list a,b -> "a" "b" (shell array body); empty in, empty out + printf '%s' "$1" | awk -F, 'NF && $1 != "" {for(i=1;i<=NF;i++) printf "%s\"%s\"", (i>1?" ":""), $i}' +} +TAGS_ERE="$(printf '%s' "$TAGS" | tr ',' '|')" +TAGS_COLON="$(printf '%s' "$TAGS" | awk -F, '{for(i=1;i<=NF;i++) printf "%s%s:", (i>1?" ":""), $i}')" +TAGS_AWK="$(printf '%s' "$TAGS" | awk -F, '{for(i=1;i<=NF;i++) printf "%s\"%s\"", (i>1?", ":""), $i}')" +PRODUCT_ERE="^($(printf '%s' "$PRODUCT_PATHS" | sed 's/[.]/\\./g' | tr ',' '|'))" +PRODUCT_ARRAY="$(quote_list "$PRODUCT_PATHS")" +# a pattern the generated scripts will feed to grep -E must be valid there: run it on empty input and +# refuse exit 2 (an invalid pattern would silently turn "is this a product path" into false). A product +# path may not start with * either. +for pat_pair in "product-paths:$PRODUCT_ERE" "tags:^($TAGS_ERE)"; do + printf '' | grep -E -- "${pat_pair#*:}" >/dev/null 2>&1 + [ "$?" -ne 2 ] || refuse "--${pat_pair%%:*} makes an invalid grep -E pattern: ${pat_pair#*:}" "pass plain paths such as --product-paths src/,lib/ (no regex characters)" +done +case ",$PRODUCT_PATHS," in *,\**) refuse "--product-paths has an item that starts with *: $PRODUCT_PATHS" "pass plain paths such as --product-paths src/,lib/";; esac +DOOR_ARRAY="$(quote_list "$DOOR_PATHS")" +if [ -n "$DOOR_PATHS" ]; then DOOR_CASE="$(printf '%s' "$DOOR_PATHS" | tr ',' '|')"; else DOOR_CASE=".stamp-no-door-path"; fi + +# ---- manifest: manifest.d/NN-<group>.tsv, five tab-separated columns ---- +ACT=(); SRC=(); TGT=(); MOD=(); KEY=(); GRP=() +n=0; seen_groups=" "; seen_targets=" " +ALL_TARGETS="" # every target of every group, whatever --only selected +mf_refuse() { refuse "$1 ($2)" "fix the row in $2"; } +shopt -s nullglob +for mf in "$TPL_ROOT"/manifest.d/*.tsv; do + g="$(basename "$mf" .tsv | sed -E 's/^[0-9]+-//')" + skip=0 + if [ -n "$ONLY" ]; then case ",$ONLY," in *",$g,"*) ;; *) skip=1;; esac; fi + [ "$skip" -eq 1 ] || seen_groups="$seen_groups$g " + while IFS=$'\t' read -r a s t m k rest || [ -n "$a" ]; do + case "$a" in ''|'#'*) continue;; esac + [ -z "$rest" ] || mf_refuse "a manifest row has more than five columns" "$mf" + case "$a" in copy|seed|jsonmerge|hook) ;; *) mf_refuse "unknown action '$a'" "$mf";; esac + printf '%s' "$t" | grep -Eq '^[A-Za-z0-9_@.][A-Za-z0-9._@-]*(/[A-Za-z0-9._@-]+)*$' || mf_refuse "bad target '$t'" "$mf" + case "/$t/" in */../*|*/./*) mf_refuse "bad target '$t'" "$mf";; esac + printf '%s' "$m" | grep -Eq '^[0-7]{3,4}$' || mf_refuse "bad mode '$m' for $t" "$mf" + [ -n "$k" ] || mf_refuse "empty keys column for $t (write - for none)" "$mf" + case "$seen_targets" in *" $t "*) mf_refuse "target $t is listed twice" "$mf";; esac + seen_targets="$seen_targets$t " + ALL_TARGETS="$ALL_TARGETS$t +" + [ "$skip" -eq 0 ] || continue + if [ "$a" = hook ]; then + case "$s" in lib/*) gsrc="$SRC_ROOT/$s";; *) gsrc="$TPL_ROOT/$s";; esac + [ -f "$gsrc" ] || mf_refuse "hook script not found: $s" "$mf" + SRC[n]="$gsrc" + else + [ -f "$TPL_ROOT/$s" ] || mf_refuse "template not found: $s" "$mf" + SRC[n]="$TPL_ROOT/$s" + fi + ACT[n]="$a"; TGT[n]="$t"; MOD[n]="$m"; KEY[n]="$k"; GRP[n]="$g" + n=$((n + 1)) + done < "$mf" +done +shopt -u nullglob +if [ -n "$ONLY" ]; then + for g in $(printf '%s' "$ONLY" | tr ',' ' '); do + case "$seen_groups" in *" $g "*) ;; *) refuse "no manifest group named '$g'" "list groups with: ls $TPL_ROOT/manifest.d";; esac + done +fi +[ "$n" -gt 0 ] || refuse "no manifest rows under $TPL_ROOT/manifest.d" "add a manifest.d/NN-<group>.tsv" + +# ---- symlink guard over every path the run reads or writes ---- +# shellcheck source=lib/config/safe-path.sh +source "$SELF_DIR/config/safe-path.sh" || refuse "safe-path.sh missing" "restore lib/config/safe-path.sh" +guard_paths=("$LOCK") +i=0; while [ "$i" -lt "$n" ]; do guard_paths+=("$TARGET/${TGT[i]}" "$TARGET/${TGT[i]}.orig"); i=$((i + 1)); done +guard_msg="$(kit_refuse_symlink_path "$TARGET" "${guard_paths[@]}" 2>&1)" \ + || refuse "$(printf '%s' "$guard_msg" | head -n 1); nothing was written" "replace the symlink with a regular path, or stamp a different repo" + +# ---- required keys ---- +need_key() { # need_key KEY: does any selected row declare it + local j=0; while [ "$j" -lt "$n" ]; do case ",${KEY[j]}," in *",$1,"*) return 0;; esac; j=$((j + 1)); done; return 1 +} +i=0; while [ "$i" -lt "$n" ]; do + for k in $(printf '%s' "${KEY[i]}" | tr ',' ' '); do + [ "$k" = "-" ] && continue + case " $KNOWN_KEYS " in *" $k "*) ;; *) refuse "${TGT[i]} declares the unknown key $k" "use one of: $KNOWN_KEYS";; esac + done + i=$((i + 1)) +done +if need_key DEFAULT_BRANCH && [ -z "$DEFAULT_BRANCH" ]; then + refuse "no default branch: this repo has no origin/HEAD and no --default-branch was given" "bash lib/stamp.sh --default-branch main $TARGET" +fi +if need_key OWNER && [ -z "$OWNER" ]; then + refuse "no owner: OWNERS.md needs one login" "bash lib/stamp.sh --owner <github-login> $TARGET" +fi +# every value in use, and where it came from, so a value taken silently from the lock is seen +{ + printf 'using: DEFAULT_BRANCH=%s (%s)\n' "${DEFAULT_BRANCH:-none}" "$([ -n "$F_DEFAULT_BRANCH" ] && echo flag || { [ -n "$(lock_value DEFAULT_BRANCH)" ] && echo lock || echo origin/HEAD; })" + printf 'using: OWNER=%s (%s)\n' "${OWNER:-none}" "$(src_of OWNER "$F_OWNER")" + printf 'using: TAGS=%s (%s)\n' "$TAGS" "$(src_of TAGS "$F_TAGS")" + printf 'using: PRODUCT_PATHS=%s (%s)\n' "$PRODUCT_PATHS" "$(src_of PRODUCT_PATHS "$F_PRODUCT_PATHS")" + printf 'using: DOOR_PATHS=%s (%s)\n' "${DOOR_PATHS:-none}" "$(src_of DOOR_PATHS "$F_DOOR_PATHS")" + printf 'using: DOOR_APPROVER=%s (%s)\n' "${DOOR_APPROVER:-none}" "$(src_of DOOR_APPROVER "$F_DOOR_APPROVER")" + printf 'using: BOARD_FILE=%s (%s)\n' "${BOARD_FILE:-none}" "$(src_of BOARD_FILE "$F_BOARD_FILE")" + printf 'using: DECISION_TAG=%s (%s)\n' "$DECISION_TAG" "$(src_of DECISION_TAG "$F_DECISION_TAG")" +} >&2 + +AGENTS_MARKER="" +if need_key AGENTS_MARKER; then + AGENTS_MARKER="$(head -n 1 "$SRC_ROOT/lib/adopt/AGENTS.pointer.md" 2>/dev/null | tr -d '\r')" + case "$AGENTS_MARKER" in "<!-- kit:agents-pointer"*) ;; *) refuse "line 1 of lib/adopt/AGENTS.pointer.md is not the kit marker" "restore lib/adopt/AGENTS.pointer.md";; esac +fi + +STAGE="$(mktemp -d "${TMPDIR:-/tmp}/stamp.XXXXXX")" || exit 1 +VALUES="$STAGE/values.tsv" +{ + for k in $KNOWN_KEYS; do + case "$k" in STAMP_VERSION) v="$STAMP_VERSION";; *) v="${!k}";; esac + printf '%s\t%s\n' "$k" "$v" + done +} > "$VALUES" + +render() { # render <template> -> stdout + awk -F'\t' ' + FNR == NR { v[$1] = $2; next } + { line = $0; out = "" + while ((i = index(line, "{{")) > 0) { + rest = substr(line, i + 2); j = index(rest, "}}") + if (j == 0) break + k = substr(rest, 1, j - 1) + if (k in v) { out = out substr(line, 1, i - 1) v[k]; line = substr(rest, j + 2) } + else { out = out substr(line, 1, i + 1); line = rest } + } + print out line }' "$VALUES" "$1" +} + +# ---- plan: render every row into the stage, check it, decide its status ---- +ST=(); DET=() +TARGETS_FILE="$STAGE/targets.txt"; ALL_TARGETS_FILE="$STAGE/all-targets.txt" +i=0; while [ "$i" -lt "$n" ]; do printf '%s\n' "${TGT[i]}"; i=$((i + 1)); done > "$TARGETS_FILE" +printf '%s' "$ALL_TARGETS" > "$ALL_TARGETS_FILE" + +stage_row() { # stage_row i: leave the new content of row i in $STAGE/r<i> + local i="$1" used k out="$STAGE/r$1" + case "${ACT[i]}" in + hook) + ( cd "$TARGET" && STAMP_TARGETS_FILE="$TARGETS_FILE" STAMP_ALL_TARGETS_FILE="$ALL_TARGETS_FILE" STAMP_VALUES_FILE="$VALUES" bash "${SRC[i]}" "$TARGET" ) > "$out" 2>"$STAGE/err" \ + || refuse "hook for ${TGT[i]} failed: $(head -n 1 "$STAGE/err")" "run the generator by hand: bash ${SRC[i]} $TARGET";; + *) + used="$(grep -o '{{[A-Za-z_][A-Za-z0-9_]*}}' "${SRC[i]}" | tr -d '{}' | sort -u)" + for k in $used; do + case ",${KEY[i]}," in *",$k,"*) ;; *) refuse "template for ${TGT[i]} uses {{$k}} but its manifest row does not declare it" "add $k to the keys column of the row for ${TGT[i]}";; esac + done + render "${SRC[i]}" > "$out";; + esac + if grep -Eq '\{\{[A-Za-z_][A-Za-z0-9_]*\}\}' "$out"; then + refuse "${TGT[i]} still holds an unresolved {{KEY}} after the render" "use only these keys: $KNOWN_KEYS" + fi + if grep -Eq "$LEAK_PATTERN" "$out" || { [ -n "${HOME:-}" ] && [ "${#HOME}" -gt 1 ] && grep -qF "$HOME" "$out"; }; then + refuse "${TGT[i]} would carry a path under the kit or an absolute home path: $(grep -En "$LEAK_PATTERN" "$out" | head -n 1 | cut -c1-80)" "remove that text from the template; generated files must run with no kit" + fi +} + +merge_json() { # merge_json i: write the merged settings JSON to $STAGE/m<i> + local i="$1" cur base + cur="$TARGET/${TGT[i]}"; base="$STAGE/base$1.json" + command -v jq >/dev/null 2>&1 || refuse "jq is needed to merge ${TGT[i]}" "install jq, then re-run" + if [ -f "$cur" ]; then + jq -e 'type == "object"' "$cur" >/dev/null 2>&1 || refuse "${TGT[i]} is not a JSON object; nothing was written" "fix ${TGT[i]} by hand, then re-run" + cp "$cur" "$base" + else + echo '{}' > "$base" + fi + jq --slurpfile tpl "$STAGE/r$i" ' + def mergegroups($new): reduce $new[] as $g (.; + reduce $g.hooks[] as $h (.; + ($g.matcher // "") as $m + | (map(select((.matcher // "") == $m) | (.hooks // [])[] | (.command // "")) | index($h.command)) as $have + | if $have != null then . + else (map(.matcher // "") | index($m)) as $ix + | if $ix == null then . + [($g | .hooks = [$h])] else .[$ix].hooks = ((.[$ix].hooks // []) + [$h]) end + end)); + .hooks = ((.hooks // {}) as $h + | reduce (($tpl[0].hooks // {}) | to_entries[]) as $e ($h; .[$e.key] = ((.[$e.key] // []) | mergegroups($e.value)))) + ' "$base" > "$STAGE/m$i" || refuse "could not merge ${TGT[i]}" "fix ${TGT[i]} by hand, then re-run" +} + +# copy rows first, then hook rows (a hook reads the target lists only) +i=0; while [ "$i" -lt "$n" ]; do [ "${ACT[i]}" = hook ] || stage_row "$i"; i=$((i + 1)); done +i=0; while [ "$i" -lt "$n" ]; do [ "${ACT[i]}" != hook ] || stage_row "$i"; i=$((i + 1)); done + +i=0; while [ "$i" -lt "$n" ]; do + t="$TARGET/${TGT[i]}"; new="$STAGE/r$i"; ST[i]=""; DET[i]="" + if [ "${ACT[i]}" = jsonmerge ]; then + merge_json "$i" + if [ ! -e "$t" ]; then ST[i]=merge + elif [ "$(jq -cS . "$t")" = "$(jq -cS . "$STAGE/m$i")" ]; then ST[i]=unchanged + else ST[i]=merge; fi + elif [ "${ACT[i]}" = seed ] || [ "${ACT[i]}" = hook ]; then + if [ -e "$t" ]; then ST[i]=unchanged; else ST[i]=create; fi + elif [ ! -e "$t" ]; then + if lock_has "${TGT[i]}"; then ST[i]=missing; else ST[i]=create; fi + else + cur="$(sha256_of "$t")"; rend="$(sha256_of "$new")" + if lock_has "${TGT[i]}"; then + if [ "$cur" = "$(lock_hash "${TGT[i]}")" ]; then + if [ "$cur" = "$rend" ]; then ST[i]=unchanged; else ST[i]=older; fi + else ST[i]=edited; DET[i]="$(diff_lines "$t" "$new") lines differ"; fi + elif [ "$cur" = "$rend" ]; then ST[i]=unchanged; + else ST[i]=edited; DET[i]="not written by stamp, $(diff_lines "$t" "$new") lines differ"; fi + fi + i=$((i + 1)) +done + +say() { # say STATUS PATH [detail] + if [ -n "${3:-}" ]; then printf '%s: %s (%s)\n' "$1" "$2" "$3"; else printf '%s: %s\n' "$1" "$2"; fi +} + +report() { # report: one status line per row for the current mode + local i=0 s + while [ "$i" -lt "$n" ]; do + s="${ST[i]}" + case "$s" in + unchanged) say unchanged "${TGT[i]}";; + create) case "$MODE" in dry) say "would create" "${TGT[i]}";; check|refresh) say missing "${TGT[i]}";; *) say created "${TGT[i]}";; esac;; + merge) case "$MODE" in dry) say "would merge" "${TGT[i]}";; check|refresh) say missing "${TGT[i]}" "settings entries absent";; *) say merged "${TGT[i]}";; esac;; + missing) say missing "${TGT[i]}" "the lock lists it; not re-created";; + edited) say "edited (left alone)" "${TGT[i]}" "${DET[i]}";; + older) say "older stamp (run --refresh)" "${TGT[i]}";; + esac + i=$((i + 1)) + done +} + +row_of() { # row_of path -> index or empty + local i=0; while [ "$i" -lt "$n" ]; do [ "${TGT[i]}" = "$1" ] && { echo "$i"; return; }; i=$((i + 1)); done +} + +write_row() { # write_row i: atomic write of the staged content, mode from the manifest + local i="$1" t src tmp + t="$TARGET/${TGT[i]}" + src="$STAGE/r$i"; [ "${ACT[i]}" = jsonmerge ] && src="$STAGE/m$i" + mkdir -p "$(dirname "$t")" || exit 1 + tmp="$(mktemp "$(dirname "$t")/.stamp.XXXXXX")" || exit 1 + cp "$src" "$tmp" && chmod "${MOD[i]}" "$tmp" && mv "$tmp" "$t" \ + || { rm -f "$tmp"; echo "stamp: failed to write $t" >&2; exit 1; } +} + +LOCK_UPDATES="$STAGE/lock-updates.txt"; : > "$LOCK_UPDATES" +note_lock() { printf 'file %s %s sha256:%s\n' "${TGT[$1]}" "${GRP[$1]}" "$(sha256_of "$TARGET/${TGT[$1]}")" >> "$LOCK_UPDATES"; } + +write_lock() { + local new="$STAGE/lock.new" k v + { + echo "stamp-version $STAMP_VERSION" + for k in $BASE_KEYS; do v="${!k}"; printf 'value %s %s\n' "$k" "$v"; done + { [ -f "$LOCK" ] && grep '^file ' "$LOCK"; cat "$LOCK_UPDATES"; } | awk '{ last[$2] = $0 } END { for (p in last) print last[p] }' | LC_ALL=C sort -k2 + } > "$new" + if [ -f "$LOCK" ] && cmp -s "$new" "$LOCK"; then return 0; fi + mkdir -p "$(dirname "$LOCK")" || exit 1 + local tmp; tmp="$(mktemp "$(dirname "$LOCK")/.stamp.XXXXXX")" || exit 1 + cp "$new" "$tmp" && chmod 0644 "$tmp" && mv "$tmp" "$LOCK" || { rm -f "$tmp"; echo "stamp: failed to write the lock" >&2; exit 1; } +} + +is_known_kit_file() { # is_known_kit_file <file>: adopt's own pointer, an old kit copy, or adopt's proof marker + local f="$1" h + h="$(sha256_of "$f")" + [ "$h" = "$(sha256_of "$SRC_ROOT/lib/adopt/AGENTS.pointer.md" 2>/dev/null)" ] && return 0 + grep -q "^$h " "$SRC_ROOT/lib/adopt/agents-known.sha256" 2>/dev/null && return 0 + [ "$(head -n 1 "$f" | tr -d '\r')" = "# Verification (proof-of-done marker)" ] && [ "$(grep -c '' "$f")" -le 8 ] +} + +interplay_notes() { # lines only a reader of adopt's files can write; returns 1 when one is a drift line + local rc=0 k="$TARGET/.kit.toml" sj="$TARGET/.claude/settings.json" c + if [ -n "$(row_of .kit.toml)" ] && [ -f "$k" ] && grep -Eq '^[[:space:]]*lane_gates[[:space:]]*=[[:space:]]*true' "$k"; then + printf 'stamp: .kit.toml sets lane_gates = true; a team repo runs with it off\nFix: set lane_gates = false in .kit.toml\n' + rc=1 + fi + if [ -f "$sj" ] && command -v jq >/dev/null 2>&1; then + c="$(jq '[ (.hooks // {}) | .[] | .[] | (.hooks // [])[] | (.command // "") | select(contains("dwarves-kit")) ] | length' "$sj" 2>/dev/null)" + [ "${c:-0}" -gt 0 ] && printf 'note: .claude/settings.json holds %s kit hook command(s); the stamp leaves them in place\n' "$c" + fi + return $rc +} + +drift=0 +case "$MODE" in + check|dry|refresh) + report + interplay_notes || [ "$MODE" != check ] || drift=1 + if [ "$MODE" = refresh ]; then + i=0; while [ "$i" -lt "$n" ]; do + if [ "${ST[i]}" = older ]; then + echo "--- ${TGT[i]} (current, as stamped)"; echo "+++ ${TGT[i]} (new template)" + diff -u "$TARGET/${TGT[i]}" "$STAGE/r$i" | tail -n +3 + echo "Fix: bash lib/stamp.sh --take ${TGT[i]} $TARGET" + fi + i=$((i + 1)) + done + fi + if [ "$MODE" = check ]; then + i=0; while [ "$i" -lt "$n" ]; do [ "${ST[i]}" = unchanged ] || drift=1; i=$((i + 1)); done + fi + exit "$drift";; + take) + p="${TAKE_PATH#./}"; ix="$(row_of "$p")" + [ -n "$ix" ] || refuse "$p is not a stamped file" "pick one of: $(tr '\n' ' ' < "$TARGETS_FILE")" + [ "${ACT[ix]}" != jsonmerge ] || refuse "$p is merged into, never replaced" "edit $p by hand" + case "${ACT[ix]}" in seed|hook) refuse "$p is seeded once and then belongs to the repo" "edit $p by hand";; esac + t="$TARGET/$p" + [ -f "$t" ] || refuse "$p is not present" "bash lib/stamp.sh $TARGET" + cur="$(sha256_of "$t")"; rend="$(sha256_of "$STAGE/r$ix")" + if [ "$cur" = "$rend" ]; then say unchanged "$p"; note_lock "$ix"; write_lock; exit 0; fi + ok=0 + if lock_has "$p"; then [ "$cur" = "$(lock_hash "$p")" ] && ok=1 + else is_known_kit_file "$t" && ok=1; fi + if [ "$ok" -ne 1 ]; then + echo "--- $p (current, includes the repo's edits)"; echo "+++ $p (new template)" + diff -u "$t" "$STAGE/r$ix" | tail -n +3 + refuse "$p was edited, so the stamp does not replace it" "apply the diff above by hand" + fi + # the backup name skips anything that exists, a dangling symlink included, and is checked like every + # target; the copy goes to a temp name and is renamed, so a link is replaced and never followed + bak="$t.orig"; c=0 + while [ -e "$bak" ] || [ -L "$bak" ]; do c=$((c + 1)); bak="$t.orig.$c"; done + guard_msg="$(kit_refuse_symlink_path "$TARGET" "$bak" 2>&1)" || refuse "$(printf '%s' "$guard_msg" | head -n 1); no backup was made" "move the symlink away, then run --take again" + tmpb="$(mktemp "$(dirname "$bak")/.stamp.XXXXXX")" || exit 1 + cp -p "$t" "$tmpb" && mv "$tmpb" "$bak" || { rm -f "$tmpb"; echo "stamp: could not write the backup $bak" >&2; exit 1; } + write_row "$ix"; note_lock "$ix"; write_lock + say replaced "$p" "old copy kept as ${bak#"$TARGET"/}" + exit 0;; +esac + +# default write run +i=0; while [ "$i" -lt "$n" ]; do + case "${ST[i]}" in + create|merge) write_row "$i"; note_lock "$i";; + unchanged) case "${ACT[i]}" in seed|hook) ;; *) note_lock "$i";; esac;; + esac + i=$((i + 1)) +done +report +interplay_notes || true +write_lock +exit 0 diff --git a/lib/stamp/README.md b/lib/stamp/README.md new file mode 100644 index 000000000..52af52216 --- /dev/null +++ b/lib/stamp/README.md @@ -0,0 +1,92 @@ +# stamp + +Writes a kit-free agent harness into a repo as plain files the repo owns. This directory holds the notes; the driver is `lib/stamp.sh` and the templates are `templates/team-stamp/`. The verb knows no file by name: every file comes from a manifest row. + +**Entry points** +- `lib/stamp.sh [--check | --dry-run | --refresh | --take <path>] [--only <groups>] [value flags] <target-dir>`. Default writes what is missing, merges `.claude/settings.json`, and updates the lock. Never overwrites a file the repo edited. +- `.claude/team-stamp.lock` in the target: the values used and one `sha256:<hex>` per written file (the marker keeps a secret scan from reading a digest as a key). Plain text, kit-free. Any hash a template carries uses the same marker form: `sha256:<hex>`, `sha256=<hex>` or `sha256: <hex>`, never a bare run of hex. + +**Tests**: `bash tests/test-stamp.sh` (engine, against `tests/fixtures/team-stamp/`) and `bash tests/test-stamp-kitfree.sh <group|fixture|all>`. + +**Spec and notes**: `docs/specs/SPEC-425-team-stamp.md`, `docs/implementation-notes/team-stamp.md`. + +## How a group plugs in + +A group is one manifest file plus its templates. Add exactly `templates/team-stamp/manifest.d/NN-<group>.tsv` and files under `templates/team-stamp/files/`. No group edits `lib/stamp.sh`, another group's manifest, or this README. + +### Manifest row + +Five tab-separated columns. Blank lines and lines starting with `#` are ignored. A column is never empty (write `-` for no keys). + +``` +action<TAB>source<TAB>target<TAB>mode<TAB>keys +``` + +| Column | Meaning | +|---|---| +| action | `copy`: render, write when absent, drift-checked after. `seed`: like `copy`, but never drift-checked once it exists (repo-living files such as `OWNERS.md`, `CHANGELOG.md`, `.claude/memory/MEMORY.md`); created again when deleted. `jsonmerge`: merge the rendered JSON object into the target by `hooks` entry (match on `matcher`, then on `command`); other keys of the target are kept, a duplicate is never added, invalid JSON refuses the run. `hook`: run a script, write its stdout as the file, seed-once. | +| source | `copy`, `seed`, `jsonmerge`: a path under `templates/team-stamp/`, normally `files/<target path>`, with a `.tpl` suffix when the file takes a value. `hook`: a script, `lib/stamp/<name>.sh` (relative to the kit root) or a path under the templates root. | +| target | Repo-relative path, no `..`, no spaces. Unique across every group. | +| mode | Octal, `0644` or `0755`. Applied only to a file the stamp creates. | +| keys | Comma list of the `{{KEY}}` names the template uses, or `-`. A template that uses an undeclared key, or declares an unknown key, aborts the run. | + +The group name is the manifest file name after `NN-` and before `.tsv`. `NN` orders the files; it carries no other meaning. + +A `hook` script runs with the target repo as its working directory and gets `$1` = the target path. It reads `$STAMP_TARGETS_FILE` (every target of the selected groups, one per line), `$STAMP_ALL_TARGETS_FILE` (every target of every group, even under `--only`; use this for a seed built from the merged manifest) and `$STAMP_VALUES_FILE` (`KEY<TAB>value`). It prints the file content to stdout and exits 0. + +### Values: `{{KEY}}` names + +| Key | From | Example for `--tags app,lib` etc. | +|---|---|---| +| `DEFAULT_BRANCH` | `--default-branch`, else `origin/HEAD`, else refuse | `main` | +| `OWNER` | `--owner` (no default, refuses when a row needs it) | `alice` | +| `TAGS` | `--tags`, default `product,dev`; `dev` is always added | `app,lib,dev` | +| `PRODUCT_PATHS` | `--product-paths`, default `src/` | `src/,lib/` | +| `DOOR_PATHS` | `--door-paths`, default empty | `docs/legal/*,protocol/*` | +| `DOOR_APPROVER` | `--door-approver`, default empty | `carol` | +| `BOARD_FILE` | `--board-file`, default empty | `docs/BOARD.md` | +| `DECISION_TAG` | `--decision-tag`, default `decision` | `decision` | +| `TAGS_ERE` | derived | `app|lib|dev` | +| `TAGS_COLON` | derived | `app: lib: dev:` | +| `TAGS_AWK` | derived | `"app", "lib", "dev"` | +| `PRODUCT_ERE` | derived, dots escaped | `^(src/|lib/)` | +| `PRODUCT_ARRAY` | derived, a bash array body | `"src/" "lib/"` | +| `DOOR_ARRAY` | derived, a bash array body, **empty when no door path is set** (a script must guard an empty array under `set -u` on bash 3.2) | `"docs/legal/*" "protocol/*"` | +| `DOOR_CASE` | derived, a `case` pattern; a never-matching word when empty | `docs/legal/*|protocol/*` | +| `STAMP_VERSION` | the engine | `1` | +| `AGENTS_MARKER` | line 1 of `lib/adopt/AGENTS.pointer.md`, refused unless it starts `<!-- kit:agents-pointer` | the adopt marker | + +The engine refuses any flag value that holds a newline, a carriage return or a tab before it reads anything else, then matches the whole value against a narrow character set (no space, no shell quote, no `{{`). A path-like value (`--board-file`, `--product-paths`, `--door-paths`) may not start with `/` or hold a `..` component. Every run prints the values in use and whether each came from a flag, the lock or a default (`using: KEY=value (source)` on stderr), so a value taken silently from a planted lock is seen. Values are remembered in the lock, so a re-run with no flags renders the same bytes. + +### What the engine checks on every rendered file + +- No `{{KEY}}` is left. +- No kit path (`.claude/dwarves-kit`, `CLAUDE_PLUGIN_ROOT`, `KIT_ROOT`, `lib/gate/`, `/bin/gate|classify|wrap|board`) and no absolute home path. One hit refuses the whole run before any write. +- No write through a symlink, no write outside the target. + +A refusal prints two lines: `stamp: <rule>` then `Fix: <command>`. A status line is `<status>: <path>`: `created`, `merged`, `unchanged`, `edited (left alone)`, `older stamp (run --refresh)`, `missing`. + +### Test conventions + +- A test of a valued script is a `.tpl` too, and reads the stamped values from the repo, never a literal `main` or a fixed tag. The kit-free run uses non-default values. +- A generated test is `scripts/test-<name>.sh`. `tests/test-stamp-kitfree.sh` runs every one of them with the kit absent from `PATH` and `HOME`. + +### Group test recipe + +Run the group through the harness; it finds the group by file name: + +```bash +bash tests/test-stamp-kitfree.sh <group> # <group> is the name after NN- in manifest.d, e.g. hook +``` + +That stamps only that group into a fresh temp repo with non-default values (`--default-branch master --owner testowner --tags app,lib --product-paths app/,pkg/ --door-paths 'docs/legal/*' --door-approver reviewer --decision-tag decision --board-file docs/BOARD.md`), greps every file the lock lists for kit paths, and runs each stamped `scripts/test-*.sh` with a stripped `PATH` and an empty `HOME`. + +For your own `tests/test-stamp-<group>.sh`, stamp the group yourself: + +```bash +T="$(mktemp -d)"; git -C "$T" init -q +bash lib/stamp.sh --only <group> --default-branch main --owner testowner "$T" +# now assert on "$T"; run "$T"/scripts/test-<name>.sh; rerun lib/stamp.sh to prove it is idempotent +``` + +`bash tests/test-stamp.sh` drives the engine with `STAMP_TEMPLATES=tests/fixtures/team-stamp`, a two-group fixture tree that is the format reference for a manifest. diff --git a/lib/stamp/owners-seed.sh b/lib/stamp/owners-seed.sh new file mode 100644 index 000000000..8eb87797c --- /dev/null +++ b/lib/stamp/owners-seed.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# owners-seed.sh -- hook script for the OWNERS.md manifest row. Prints a full OWNERS.md with one +# row for every script and workflow in the merged manifest (every group, even under --only), so a +# freshly stamped repo passes its own owners check. The repo owns the file after the first write. +# Env from lib/stamp.sh: STAMP_ALL_TARGETS_FILE, STAMP_VALUES_FILE. Arg 1: the target repo. +set -uo pipefail +owner="$(awk -F'\t' '$1=="OWNER"{print $2; exit}' "$STAMP_VALUES_FILE")" +[ -n "$owner" ] || { echo "owners-seed: no OWNER value" >&2; exit 1; } + +cat <<'HEAD' +# Owners + +## Rule + +- Every script, workflow and scheduled or deployed job has one owner. +- An owner is a GitHub login (`@login`) or a named agent. An agent owner also names a sponsor: the human who answers for that agent. +- The owner keeps it working, reviews changes to it, and retires it. +- A PR that adds a script, a workflow or a job adds its row in the same PR. +- Claiming ownership is editing the row in a PR. `scripts/check-owners.sh` fails CI when a file has no row, a row points at a missing path, or an owner or a needed sponsor is empty. + +## Scripts and workflows + +| Path | What it does | Owner | Sponsor | +|---|---|---|---| +HEAD + +LC_ALL=C sort "$STAMP_ALL_TARGETS_FILE" | while IFS= read -r p; do + case "$p" in + scripts/test-*.sh) what="Test for scripts/${p#scripts/test-}";; + scripts/*) what="Generated by the team stamp";; + .github/workflows/*) what="CI workflow generated by the team stamp";; + *) continue;; + esac + printf '| `%s` | %s | @%s | |\n' "$p" "$what" "$owner" +done diff --git a/templates/team-stamp/files/.claude/memory/MEMORY.md b/templates/team-stamp/files/.claude/memory/MEMORY.md new file mode 100644 index 000000000..258512307 --- /dev/null +++ b/templates/team-stamp/files/.claude/memory/MEMORY.md @@ -0,0 +1,9 @@ +# Repo lessons + +Each line is one lesson that cost time once. Read the note before you do the work it covers. Add a note in the PR that paid for it: `AGENTS.md`, section "Lessons". Keep this file under 8,000 characters. + +- [CI runner has no procps](ci-runner-has-no-procps.md): no `kill`, `pgrep`, `ps` or `rsync` binary on a slim runner; use the shell built-in `kill -0` and `cp` in tests. +- [CI sets CI=true](ci-sets-ci-true.md): a script that branches on `CI` acts differently in CI; tests set or clear it on purpose. +- [Queued run missing from lists](queued-run-missing-from-lists.md): a branch filter can miss a queued run; wait by run id or by the PR check rollup. +- [Guards match command text](guards-match-command-text.md): the hook sees command text only and has known misses; do not hide a command from it, CI is the second line. +- [Stale checks after a rule change](stale-checks-after-a-rule-change.md): green checks are from the old rules; update the branch with `gh pr update-branch`, never close and reopen to refresh CI. diff --git a/templates/team-stamp/files/.claude/memory/ci-runner-has-no-procps.md b/templates/team-stamp/files/.claude/memory/ci-runner-has-no-procps.md new file mode 100644 index 000000000..238e504c4 --- /dev/null +++ b/templates/team-stamp/files/.claude/memory/ci-runner-has-no-procps.md @@ -0,0 +1,10 @@ +--- +name: ci-runner-has-no-procps +description: A CI runner image can lack kill, pgrep, ps and rsync, so a test that runs one passes on a laptop and fails in CI. +--- + +A slim CI runner image may ship no procps. `kill`, `pgrep` and `ps` then do not exist as programs (`which pgrep ps` exits 1), and `rsync` can be missing too. A test that ran one of them passed on a laptop and failed on the first runner run. + +**Why:** a laptop always has these tools, so a local green run proves nothing about the runner. + +**How to apply:** in a test, or a script a test runs, never run `kill`, `pgrep`, `ps` or `rsync` as a program. Use the shell built-in `kill -0 <pid>`, a marker file a surviving child would leave, or `cp -Rp` and `find`. A test that fails only in CI: suspect a missing tool first, then check the image. diff --git a/templates/team-stamp/files/.claude/memory/ci-sets-ci-true.md b/templates/team-stamp/files/.claude/memory/ci-sets-ci-true.md new file mode 100644 index 000000000..41ab05258 --- /dev/null +++ b/templates/team-stamp/files/.claude/memory/ci-sets-ci-true.md @@ -0,0 +1,10 @@ +--- +name: ci-sets-ci-true +description: GitHub Actions exports CI=true, so a script that branches on CI acts differently there; tests must set or clear it on purpose. +--- + +The runner exports `CI=true`. `scripts/pr-shape.sh` relies on it: a missing shellcheck is skipped on a laptop with a notice and is a failure when `CI=true`, so the check cannot pass silently in CI. A test that does not control `CI` gives a different answer on a laptop than on the runner. + +**Why:** the same script has two modes, and only one of them runs on your machine. A green local run can hide a red CI run. + +**How to apply:** a test of a CI-aware script clears the variable for the local case (`env -u CI ...`) and sets `CI=true` for the CI case. To reproduce a CI-only failure, run the script with `CI=true` on the command line. diff --git a/templates/team-stamp/files/.claude/memory/guards-match-command-text.md b/templates/team-stamp/files/.claude/memory/guards-match-command-text.md new file mode 100644 index 000000000..ec069bff6 --- /dev/null +++ b/templates/team-stamp/files/.claude/memory/guards-match-command-text.md @@ -0,0 +1,12 @@ +--- +name: guards-match-command-text +description: The agent hook matches the text of a command, so a variable or a script file hides a command from it; CI is the second line. +--- + +`scripts/agent-guard.sh` is text matching on the command line, not a shell parser. It guards Claude Code only, and without `jq` or `awk` it is off. + +Known misses: a command built from variables, functions, aliases or command substitution; a script, make target or tool that runs git or gh itself; a push set up through a git alias, `git -c alias.x=push`, or config; a merge from the GitHub site or any client other than gh; a `gh api` merge that does not spell PUT as a word, or a graphql call other than a literal `mergePullRequest`; a commit made by an editor or a GUI. `scripts/test-agent-guard.sh` holds one row per probe. + +**Why:** the hook says the fix at the moment of the mistake. It is not a wall. CI job `pr-shape` and `scripts/pr-merge.sh` bind. + +**How to apply:** never hide a command from the hook to get past it. When it blocks you, read the fix line and use it. diff --git a/templates/team-stamp/files/.claude/memory/queued-run-missing-from-lists.md b/templates/team-stamp/files/.claude/memory/queued-run-missing-from-lists.md new file mode 100644 index 000000000..4ac8b0b73 --- /dev/null +++ b/templates/team-stamp/files/.claude/memory/queued-run-missing-from-lists.md @@ -0,0 +1,10 @@ +--- +name: queued-run-missing-from-lists +description: A queued CI run can be missing from filtered run lists, so wait for a run by its id or by the PR's check rollup, never by a branch filter. +--- + +A `pull_request` run once sat `queued` for 15 minutes. The unfiltered run list showed it. The `status=queued` list and `gh run list --branch <name>` did not, so no runner saw demand and none started. Cancel and rerun fixed it. The cause was not found. + +**Why:** a wait loop on a filtered list never returns, and CI looks hung while the fleet is healthy. + +**How to apply:** after a push, get the run id from the unfiltered list: `gh api "repos/<owner>/<repo>/actions/runs?per_page=5"`. Then wait on that id: `gh run view <id> --json status,conclusion`. If the run stays `queued` and only the unfiltered list shows it: `gh run cancel <id>`, wait for `completed`, then `gh run rerun <id>`. Do not claim CI is green from a list that may be missing the run. `scripts/pr-merge.sh --wait <number>` reads the PR's own check rollup and never merges on a pending check. diff --git a/templates/team-stamp/files/.claude/memory/stale-checks-after-a-rule-change.md b/templates/team-stamp/files/.claude/memory/stale-checks-after-a-rule-change.md new file mode 100644 index 000000000..b22423b80 --- /dev/null +++ b/templates/team-stamp/files/.claude/memory/stale-checks-after-a-rule-change.md @@ -0,0 +1,10 @@ +--- +name: stale-checks-after-a-rule-change +description: A PR keeps the green checks of the rules it ran under, and a close and reopen can run CI on an old merge commit, so a rule change needs a branch update. +--- + +CI runs a PR on its merge with the default branch at the time of the run. After a new check merged in `scripts/pr-shape.sh`, open PRs stayed green on the old rules and were one command from merging. A close and reopen ran the OLD rules again: the event carried a merge commit computed before the default branch moved. A plain re-run replays the old event too. + +**Why:** a green check means the PR passed the rules of that run, not today's rules. Reopens also leave cancelled runs on the same head commit. + +**How to apply:** after `scripts/pr-shape.sh` or `.github/workflows/ci.yml` changes on the default branch, update every open PR with `gh pr update-branch <n>` (a merge, no force push). Never close and reopen a PR to refresh CI: push a commit (an empty one works) for a new head and clean checks. A run's log shows its rules in the checkout line `Merge <head> into <base>`. diff --git a/templates/team-stamp/files/.claude/settings.json b/templates/team-stamp/files/.claude/settings.json new file mode 100644 index 000000000..c577991ad --- /dev/null +++ b/templates/team-stamp/files/.claude/settings.json @@ -0,0 +1,25 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "bash \"${CLAUDE_PROJECT_DIR}/scripts/agent-lessons.sh\"" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "bash \"${CLAUDE_PROJECT_DIR}/scripts/agent-guard.sh\"" + } + ] + } + ] + } +} diff --git a/templates/team-stamp/files/.claude/skills/ship-pr/SKILL.md.tpl b/templates/team-stamp/files/.claude/skills/ship-pr/SKILL.md.tpl new file mode 100644 index 000000000..0f7c9c195 --- /dev/null +++ b/templates/team-stamp/files/.claude/skills/ship-pr/SKILL.md.tpl @@ -0,0 +1,90 @@ +--- +name: ship-pr +description: Take a GitHub issue to a merged PR in this repo. Use when asked to do, build, fix or ship an issue or a board row, or when a change is ready to push. Covers claim, branch, proof file, scripts/check.sh, the PR, merge with scripts/pr-merge.sh and clean up. +--- + +# Ship a PR + +Run every command from the repo root of your worktree. The rules behind each step are in `AGENTS.md`, section "Team rules"; the reasons are in `docs/TEAM-WORKFLOW.md`. This file holds the commands only. + +## 1. Take the issue + +```sh +gh issue list --assignee @me --label ready --state open +gh issue view <n> +gh issue edit <n> --add-assignee @me +``` + +- Read `## Goal`, `## Done when` and `## Scope`. Done when is your finish check. +- Which issue you may take, and what a PR with no issue says: `AGENTS.md`, sections "Work queue" and "What a PR carries". +- Secrets or access: stop and ask a human (`AGENTS.md`, section "Never"). A `one-way-door` label means step 7 applies. +- To see what is open and what waits on a decision: `bash scripts/team-digest.sh`. + +## 2. Branch in a worktree + +```sh +git fetch origin {{DEFAULT_BRANCH}} +git worktree add .claude/worktrees/<slug> -b <type>/<slug> origin/{{DEFAULT_BRANCH}} +cd .claude/worktrees/<slug> +``` + +- `<type>` is feat, fix, refactor, docs, test or chore. The slug is two to five kebab-case words. Never commit on `{{DEFAULT_BRANCH}}`. + +## 3. Build + +- Make the change. Run the commands for your paths from `AGENTS.md`, section "Commands". +- One logical change per commit. Write the message to a file, then `git commit -F <file>`. Subject `type(scope): subject`, 72 characters or less. Stage explicit paths. +- What the PR must carry (changelog line, docs, owners row, board row): `AGENTS.md`, sections "What a PR carries" and "Changelog". A new script, workflow or job gets a row in `OWNERS.md`; check it with `bash scripts/check-owners.sh`. + +## 4. Proof + +When a PR owes a proof, and what CI reads in it, is in `AGENTS.md`, section "Proof". Write `docs/verification/<slug>.md` as `docs/verification/README.md` says: a proof file with `Command:` / `Output:` / `Exit:` / `Verdict:` blocks and pasted output, and a negative control. Commit the work first, then run the negative control: + +```sh +bash scripts/negctl.sh "<test command>" "<command that breaks one thing>" +``` + +It shows green, red, restore, green and prints the block to paste into the proof file. + +## 5. Check before you push + +```sh +bash scripts/check.sh +``` + +- It runs the same checks as CI with the same inputs. A red check prints the rule and a `Fix:` line. Do what the fix line says, commit, rerun. +- With no PR open yet, check.sh reads the title from the first commit and an empty body, so a body rule fails. Give it the PR text: `bash scripts/check.sh --title '<type(scope): subject>' --body 'Closes #<n>'`. +- Run your own language tests as well; the stamp ships none. + +## 6. Open the PR + +```sh +git push -u origin <type>/<slug> +gh pr create --title "<type(scope): subject>" --body-file <file> +``` + +- Write the body file from `.github/pull_request_template.md`. `Closes #<n>` stands alone on its line. The title becomes the commit subject on `{{DEFAULT_BRANCH}}`. +- When the repo keeps a board file and the issue came from a row, set that row to its shipped state in the same PR. + +## 7. One-way door + +If the PR touches a door in `AGENTS.md`, section "One-way doors", add the line that section names to the body, with a link to the second person's comment. Without their yes, stop and ask. + +## 8. Merge, waiting for CI + +```sh +bash scripts/pr-merge.sh --wait --dry-run <n> +bash scripts/pr-merge.sh --wait <n> +``` + +- `--wait` polls the PR's checks until none is pending, then judges: it refuses a draft, a red or pending check, a conflict, and a change under a door path without a second person's yes. `--dry-run` prints the verdict and merges nothing. +- A refusal prints the rule and a `Fix:` line. A conflict: merge `origin/{{DEFAULT_BRANCH}}` into the branch and push. A red check: read the failing log with `gh run view <run id> --log-failed`, fix, push, run the merge again. +- A repo with no self-hosted runner shows its checks as pending. Run `bash scripts/check.sh` in its place; `--wait` never merges on a pending check. + +## 9. Clean up + +Never use a bare `gh pr merge`: the hook stops it and CI finds it later. After the merge, from the checkout you started in, remove only your own worktree and branch: `git worktree remove .claude/worktrees/<slug>` and `git branch -d <type>/<slug>`. + +## Done when + +`gh pr view <n> --json state --jq .state` prints `MERGED`, issue #<n> is closed, the board row (if any) is updated, and your worktree is gone. diff --git a/templates/team-stamp/files/.github/ISSUE_TEMPLATE/task.yml b/templates/team-stamp/files/.github/ISSUE_TEMPLATE/task.yml new file mode 100644 index 000000000..4a7cdfe89 --- /dev/null +++ b/templates/team-stamp/files/.github/ISSUE_TEMPLATE/task.yml @@ -0,0 +1,31 @@ +name: Task +description: One unit of work for one agent run. +body: + - type: markdown + attributes: + value: | + An issue is one unit of work for one agent run. Add the `ready` label once Goal and Done when are filled. The form writes the sections as `### Goal`, `### Done when`, `### Scope` and `### Notes`. + - type: textarea + id: goal + attributes: + label: Goal + description: One or two sentences. What is true when this is done? + validations: + required: true + - type: textarea + id: done_when + attributes: + label: Done when + description: One check a machine or a person can run. + validations: + required: true + - type: textarea + id: scope + attributes: + label: Scope + description: Paths in, paths out, links. + - type: textarea + id: notes + attributes: + label: Notes + description: Optional. Context, options, a blocker. diff --git a/templates/team-stamp/files/.github/pull_request_template.md b/templates/team-stamp/files/.github/pull_request_template.md new file mode 100644 index 000000000..6af54ef2d --- /dev/null +++ b/templates/team-stamp/files/.github/pull_request_template.md @@ -0,0 +1,10 @@ +## What +<!-- One or two sentences: what changed and why. --> + +## Proof +<!-- The docs/verification/<slug>.md file for a behavior change, or pasted command output of the thing running. --> + +## Bookkeeping +<!-- Rules: AGENTS.md and docs/TEAM-WORKFLOW.md. --> +<!-- Optional marker lines, one per line, each with a reason of 10+ characters: no-board-row:, no-changelog:, no-proof:, no-rule-mirror: --> +Closes # diff --git a/templates/team-stamp/files/.github/workflows/ci.yml.tpl b/templates/team-stamp/files/.github/workflows/ci.yml.tpl new file mode 100644 index 000000000..a0b8480b0 --- /dev/null +++ b/templates/team-stamp/files/.github/workflows/ci.yml.tpl @@ -0,0 +1,183 @@ +# CI for pull requests. Every job runs on a self-hosted runner: this file never names a +# GitHub-hosted runner label, because the team pays for no hosted minutes. A repo with a named +# runner pool edits runs-on in its own copy. Until a runner is attached, a run waits in the queue +# and never starts; bash scripts/check.sh runs the same checks on your machine. +# +# Where this binds. GitHub runs the workflow file of a pull request from the pull request's own +# merge commit, so a pull request can edit THIS file. "Gate scripts from the base revision" protects +# the scripts, not the workflow. What binds the workflow is scripts/pr-merge.sh: it merges only when +# both checks `changes` and `pr-shape` passed on the head it judged, each from the workflow named CI, +# and a pull request that touches .github/workflows/ is a door that needs a second person's approval. +# +# Runners. Nothing in this file executes a file from a pull request: both jobs run only scripts +# copied from the base revision. A job that runs the pull request's own code (tests, builds) belongs +# on a separate runner label or in a container job, never on the runner that runs `changes` and +# `pr-shape`: a long-lived runner keeps what a pull request's code writes, for the next run, the next +# pull request and the other repos on that host. Not for public repos. A pull request from a fork +# does not run here: the two jobs carry the `if:` guard below. A skipped job leaves its check +# missing, and the merge guard then refuses. scripts/check.sh runs the generated script tests on +# your own machine. +# +# Jobs +# changes scripts/check-owners.sh (every script and workflow has an owner), then a path filter +# whose output "product" is true when a product path or this file changed. The repo's +# own build and test jobs hang off it (see the end of the file). +# scripts/pr-merge.sh waits for this job to pass, so keep the job name changes. +# pr-shape scripts/pr-shape.sh with the title and body of the pull request (title, proof file, +# board link, changelog tag, shellcheck, rule parity). +# +# `changes` and `pr-shape` run ONLY scripts copied from the base revision. They never execute a file +# from the pull request head; shellcheck reads changed files and does not run them. +# +# The gate scripts (check-owners.sh and pr-shape.sh) are the copies from the BASE revision, so a pull +# request cannot weaken the checks it is judged by. A gate script the base does not have yet (the +# pull request that introduces the stamp) fails the job: merge that first pull request by hand. +# The title and body reach pr-shape.sh through env: entries and never through script text. +# +# Twin set: the commands below are the gate commands. scripts/check.sh runs each of them with the +# same inputs. Keep this list and the same list at the top of scripts/check.sh in step with the jobs. +# twin: check-owners.sh +# twin: pr-shape.sh env PR_TITLE PR_BODY BASE_SHA HEAD_SHA +# +# Pins. Every action is pinned by a full commit sha, with its release tag in the comment after it. +# The shellcheck release is pinned by tag and by the sha256 of each build; a download whose digest +# differs fails the job. To move a pin, read the release metadata: +# gh api repos/actions/checkout/releases/latest --jq .tag_name +# gh api repos/actions/checkout/git/ref/tags/<tag> --jq .object.sha +# gh api repos/koalaman/shellcheck/releases/tags/<tag> --jq '.assets[] | [.name, .digest] | @tsv' +# Pinned here: shellcheck v0.11.0, one .tar.gz build per platform. A shell step picks the build by +# uname -s and uname -m, and checks the digest with sha256sum, or shasum -a 256 when sha256sum is absent. +name: CI + +on: + pull_request: + types: [opened, synchronize, reopened, edited] + +permissions: + contents: read + +jobs: + changes: + if: github.event.pull_request.head.repo.full_name == github.repository + runs-on: [self-hosted] + outputs: + product: ${{ steps.filter.outputs.product }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Take the owners check from the base revision + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + set -euo pipefail + gate="$RUNNER_TEMP/gate" + mkdir -p "$gate" + git cat-file -e "$BASE_SHA^{commit}" || { echo "gate: base $BASE_SHA is not in this checkout" >&2; exit 1; } + f=check-owners.sh + if git cat-file -e "$BASE_SHA:scripts/$f" 2>/dev/null; then + git show "$BASE_SHA:scripts/$f" > "$gate/$f" + echo "gate: scripts/$f is the copy from base $BASE_SHA" + else + echo "gate: base has no scripts/$f: this is the pull request that introduces the stamp. Merge it by hand (a second person reads it first); no check can judge it." >&2 + exit 1 + fi + [ -s "$gate/$f" ] || { echo "gate: $f is empty" >&2; exit 1; } + + # check-owners.sh works in the folder above its own path. The copy sits outside the checkout, + # so it is read as text and told its path is scripts/check-owners.sh of this checkout. + - name: Every script and workflow has an owner + run: bash -c "$(cat "$RUNNER_TEMP/gate/check-owners.sh")" "$PWD/scripts/check-owners.sh" + + - name: Path filter + id: filter + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + self='^\.github/workflows/ci\.yml$' + product_re='{{PRODUCT_ERE}}' + files="$(git diff --name-only "$BASE_SHA...$HEAD_SHA")" + if grep -Eq "$self|$product_re" <<<"$files"; then + echo "product=true" >> "$GITHUB_OUTPUT" + else + echo "product=false" >> "$GITHUB_OUTPUT" + fi + cat "$GITHUB_OUTPUT" + + pr-shape: + if: github.event.pull_request.head.repo.full_name == github.repository + runs-on: [self-hosted] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Install pinned shellcheck + env: + SHELLCHECK_VERSION: "0.11.0" + run: | + set -euo pipefail + case "$(uname -s)-$(uname -m)" in + Linux-x86_64) platform="linux.x86_64"; want="sha256=b7af85e41cc99489dcc21d66c6d5f3685138f06d34651e6d34b42ec6d54fe6f6" ;; + Linux-aarch64 | Linux-arm64) platform="linux.aarch64"; want="sha256=68a8133197a50beb8803f8d42f9908d1af1c5540d4bb05fdfca8c1fa47decefc" ;; + Darwin-x86_64) platform="darwin.x86_64"; want="sha256=c2c15e08df0e8fbc374c335b230a7ee958c313fa5714817a59aa59f1aa594f51" ;; + Darwin-arm64 | Darwin-aarch64) platform="darwin.aarch64"; want="sha256=339b930feb1ea764467013cc1f72d09cd6b869ebf1013296ba9055ab2ffbd26f" ;; + *) echo "shellcheck: no pinned build for $(uname -s) $(uname -m)" >&2; exit 1 ;; + esac + asset="shellcheck-v${SHELLCHECK_VERSION}.${platform}.tar.gz" + dir="$RUNNER_TEMP/shellcheck-install" + mkdir -p "$dir" + curl -fsSL --retry 3 -o "$dir/$asset" \ + "https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/${asset}" + if command -v sha256sum >/dev/null 2>&1; then + got="$(sha256sum "$dir/$asset")" + else + got="$(shasum -a 256 "$dir/$asset")" + fi + got="${got%% *}" + if [ "$got" != "${want#sha256=}" ]; then + echo "shellcheck: the digest of $asset is sha256=$got, not the pinned ${want}" >&2 + exit 1 + fi + tar -xzf "$dir/$asset" -C "$dir" + echo "$dir/shellcheck-v${SHELLCHECK_VERSION}" >> "$GITHUB_PATH" + "$dir/shellcheck-v${SHELLCHECK_VERSION}/shellcheck" --version + + - name: Take the PR shape check from the base revision + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + set -euo pipefail + gate="$RUNNER_TEMP/gate" + mkdir -p "$gate" + git cat-file -e "$BASE_SHA^{commit}" || { echo "gate: base $BASE_SHA is not in this checkout" >&2; exit 1; } + f=pr-shape.sh + if git cat-file -e "$BASE_SHA:scripts/$f" 2>/dev/null; then + git show "$BASE_SHA:scripts/$f" > "$gate/$f" + echo "gate: scripts/$f is the copy from base $BASE_SHA" + else + echo "gate: base has no scripts/$f: this is the pull request that introduces the stamp. Merge it by hand (a second person reads it first); no check can judge it." >&2 + exit 1 + fi + [ -s "$gate/$f" ] || { echo "gate: $f is empty" >&2; exit 1; } + + - name: PR shape + env: + PR_TITLE: ${{ github.event.pull_request.title }} + PR_BODY: ${{ github.event.pull_request.body }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: bash "$RUNNER_TEMP/gate/pr-shape.sh" + + # The repo's own build and test jobs go here, one per toolchain, as a stub for now. A job that runs + # the pull request's own code belongs on a SEPARATE runner label or in a container job, never on + # the runner that runs `changes` and `pr-shape`. Each one waits for the filter: + # needs: changes + # if: needs.changes.outputs.product == 'true' + # pins every action by full commit sha, and passes no pull request text into a run: line (use an + # env: entry). It does not run on [self-hosted] alone: give it its own label. diff --git a/templates/team-stamp/files/.kit.toml b/templates/team-stamp/files/.kit.toml new file mode 100644 index 000000000..4f621b029 --- /dev/null +++ b/templates/team-stamp/files/.kit.toml @@ -0,0 +1,9 @@ +# .kit.toml: gate settings for tools that read this file. Nothing in this repo needs them. +# Only the keys set here matter; every other key follows the tool's own default. + +[gate] +# On: a change to a behavior path needs a proof file (docs/verification/README.md says how). +proof_of_done = true +# Off on purpose: this team merges reversible work without an approver, and the full lane would ask +# for many recorded phases on every CI or config edit. The proof gate stays on and is the check that binds. +lane_gates = false diff --git a/templates/team-stamp/files/AGENTS.md.tpl b/templates/team-stamp/files/AGENTS.md.tpl new file mode 100644 index 000000000..d06c6331c --- /dev/null +++ b/templates/team-stamp/files/AGENTS.md.tpl @@ -0,0 +1,110 @@ +{{AGENTS_MARKER}} +# Agent rules + +This file is the repo's instruction file for every coding agent and every teammate. Everything you need is in this file and the files it names. No plugin or extra tool is required: a shell with `git` and `gh`, plus the toolchains your own code needs, is enough. + +[docs/TEAM-WORKFLOW.md](docs/TEAM-WORKFLOW.md) gives the reasons behind each rule. The rules themselves live only here. + +## Commands + +Run `bash scripts/check.sh` before every push. It runs the same checks as CI, with the same inputs: the owners check, the PR shape check and every script test. Run each command from the repo root. + +| Task | Run | When | +|---|---|---| +| Before a push | `bash scripts/check.sh` | every PR | +| Merge | `bash scripts/pr-merge.sh --wait <number>` | the PR is ready; never a bare `gh pr merge` | +| Script tests | `bash scripts/test-<name>.sh` for the script you changed | anything under `scripts/` | +| Negative control | `bash scripts/negctl.sh "<test command>" "<mutate command>"` (commit first; it prints the block for the proof file) | a proof for a behavior change | +| Owners | `bash scripts/check-owners.sh` | a new script, workflow or job | +| Work queue | `bash scripts/issues-from-rows.sh` for a dry run, then `--apply` | after the board file changes | +| Team digest | `bash scripts/team-digest.sh` | in place of a stand-up | +| Release notes | `bash scripts/release-notes.sh Unreleased` (`--help` for usage) | when you cut a release | +| Lessons | `bash scripts/agent-lessons.sh` | before work a lesson may cover | +| Language tests | the repo's own build and test commands: add a row here for each | the paths each one covers | + +- Branch: `git switch -c <type>/<short-slug>`. Never work on `{{DEFAULT_BRANCH}}`. +- PR title and commit subject: a conventional commit, `type(scope): subject`, 72 characters or less. Types: `feat`, `fix`, `refactor`, `docs`, `test`, `chore`, `ci`, `build`, `perf`. +- CI runs the owners check (job `changes`) and the PR shape check (job `pr-shape`) on a self-hosted runner. A repo with no runner shows the checks as pending: run `bash scripts/check.sh` instead, and `pr-merge.sh --wait` never merges on a pending check. Language test jobs are the repo's to add. +- `scripts/agent-guard.sh` is a hook, not a command: you never run it by hand. + +## Playbooks + +Claude Code loads these as project skills. Any other agent reads the file as a plain step list. + +- `.claude/skills/ship-pr/SKILL.md`: an issue to a merged PR: claim, branch, build, proof, `scripts/check.sh`, PR, checks, `scripts/pr-merge.sh`, clean up. + +## Lessons + +`.claude/memory/MEMORY.md` lists what past work already paid for, one line each. Claude Code prints it at session start through the hook in `.claude/settings.json`. Other agents: run `bash scripts/agent-lessons.sh` or read the file. Read the note before you do the work it covers. + +Add a lesson when your PR paid for one. One note per lesson, in the same PR: a file `.claude/memory/<slug>.md` with `name` and `description` in the frontmatter, then the fact, the why and how to apply it, under 1,200 characters, with no personal names and no dates. Add one line to `MEMORY.md`. Keep `MEMORY.md` under 8,000 characters: Claude Code caps hook output at 10,000 characters and shows only a short preview of more. + +## Team rules + +These rules apply to every agent and teammate. + +### Work queue +- Your work comes from GitHub Issues. If the repo keeps a board file, it is the plan. List yours: `gh issue list --assignee @me --label ready --state open`. +- An issue is one unit of work for one agent run. Body: `## Goal`, `## Done when` (one check you can run), `## Scope`, optional `## Notes`. +- Labels: `ready` (Goal and Done when are set, an agent may take it), `one-way-door` (a second person says yes before merge), `blocked` (waits on something named in the body). +- Claim an issue by assigning yourself, before you build. An unassigned `ready` issue is free to take. An assigned issue with no linked PR after 7 days goes back to unassigned; anyone may release it. +- Work under a day: open a draft PR at once. + +### What a PR carries +- `Closes #<n>` in the body, the issue that holds the work. When the repo keeps a board file and the issue came from a row, the same PR updates that row. +- No issue and no row (a typo, a tooling fix): one body line `no-board-row: <reason, 10+ characters>`. +- Fix any doc the change makes wrong, in the same PR. +- Optional marker lines in the PR body: `no-board-row:`, `no-changelog:`, `no-proof:` and `no-rule-mirror:` (each with a reason of 10+ characters), and `One-way door:` (see below). +- A change to `AGENTS.md` or `docs/TEAM-WORKFLOW.md` changes both, so the two stay in step. A change that truly needs only one puts `no-rule-mirror: <reason>` in the PR body. + +### Proof +- A change to a behavior path adds `docs/verification/<slug>.md`, one file per PR: a proof file with `Command:`, `Output:`, `Exit:` and `Verdict:` blocks and pasted output. How to write one: [docs/verification/README.md](docs/verification/README.md). +- A behavior path is any changed file that is not documentation: not `.md` or `.txt`, and not an image, PDF or CSV under `docs/`. +- The proof file holds a negative control: break the change on purpose, show the test go red, restore. That block is headed `NEGATIVE CONTROL` and ends `Verdict: RED, as expected`. Commit first so the restore works; `scripts/negctl.sh` prints the block. +- CI requires a proof file that the PR adds or changes, that is not the README, with an `Exit:` line, an `Output:` line followed by a non-empty line, a line that starts `Verdict: RED`, and the words `NEGATIVE CONTROL`. +- A change with no behavior effect (a comment, a rename, formatting) puts `no-proof: <reason, 10+ characters>` in the PR body instead. +- `docs/verification/README.md` is never a proof. + +### Changelog +- A change under {{PRODUCT_PATHS}} adds a `CHANGELOG.md` line under `## [Unreleased]`. Every line starts with one tag from this list: {{TAGS_COLON}}. The tag `dev:` marks team tooling and stays out of the release notes. +- No effect a user sees: `no-changelog: <reason, 10+ characters>` in the PR body. + +### One-way doors +A door is hard to undo after it ships: money and pricing, legal and consent text, a data format a shipped client reads, deleting production data, secrets and access. Get a second person's yes, recorded in the PR, before you change one: the line `One-way door: <door>. Second yes: #<github-login>` in the PR body, with a link to their comment. The author cannot be the second yes. Reversible work merges when checks pass, with no approval. Unsure? Treat it as a door. + +| Door setting | Value | +|---|---| +| Paths the merge guard checks, added to the harness's own files below (a comma list; blank means none added) | {{DOOR_PATHS}} | +| Who says the second yes for those paths (blank means any person other than the author) | {{DOOR_APPROVER}} | + +The harness's own files are always doors: `.github/` (the whole directory), `scripts/`, `.claude/`, `OWNERS.md`, `AGENTS.md` and `CLAUDE.md` at any depth, `.mcp.json`, `docs/TEAM-WORKFLOW.md` and `.kit.toml`. A file an agent reads as instructions is a door: other agent instruction or tool config files a team uses are added with `--door-paths`. The merge guard needs a second person's approval for any pull request that touches one of them or a path in that table. Review those changes like code that runs on every teammate's machine: a change to the hook settings (`.claude/settings.json`), the lessons index (`.claude/memory/`) or an `agent-*` script runs in every teammate's next session. For every other door, the `One-way door:` line and the reviewer are the control. The first pull request that introduces the stamp touches every door: a second person reads it, and it is merged by hand. + +### Merge +- Merge with `bash scripts/pr-merge.sh --wait <number>`, never a bare `gh pr merge`. `--wait` polls the checks until none is pending (`--timeout <seconds>`). It refuses a draft, a red or pending check, a conflict (fix: `gh pr update-branch <number>`), a missing `changes` or `pr-shape` check from the workflow `CI`, and a change under a door path without a second person's approval given on the head it judged (an owner, member or collaborator who is not the author and not a bot). It merges the exact head it judged. It refuses to run when its own text differs from the default branch's copy: never run a pull request's copy of a script. +- `--dry-run` prints the verdict and merges nothing. +- Never push to `{{DEFAULT_BRANCH}}` and never commit on it. + +### Checks +- CI job `pr-shape` fails a PR with a title that is not a conventional commit, a behavior change with no valid proof (see Proof) or no board link (a changed board file, a `Closes #<n>` line or `no-board-row:`), product code with no tagged `CHANGELOG.md` line, a changed shell script that fails shellcheck, or a change to only one of `AGENTS.md` and `docs/TEAM-WORKFLOW.md`. Run it first: `bash scripts/check.sh`, which runs `scripts/pr-shape.sh` with the same inputs as CI. +- Every new script, workflow or job gets an owner row in `OWNERS.md` in the same PR. An agent owner names a sponsor, a person who answers for it. +- Every refusal from a script prints two lines: the rule, then `Fix:` and a command you can paste. Run the fix. + +### Limits +- GitHub cannot enforce any of this without branch protection. A person who merges from the GitHub site passes everything, on a plan without branch protection. +- GitHub runs a pull request's own copy of the workflow file, so a pull request can edit `.github/workflows/ci.yml`. What binds it is the merge guard: it needs both checks from the workflow `CI`, and a change to the workflows is a door that needs a second person. +- The two CI jobs run on a self-hosted runner and run only scripts copied from the base revision. A job that runs a pull request's own code (tests, builds) belongs on a separate runner label or in a container job, never on the runner that runs `changes` and `pr-shape`. Not for public repos. A pull request from a fork does not run on it. +- Two machines back the rules instead: a Claude Code hook (`.claude/settings.json`, `scripts/agent-guard.sh`) for agents that run in Claude Code, and the CI check `pr-shape` for everyone. The hook blocks a bare `gh pr merge`, a push to `{{DEFAULT_BRANCH}}` and a commit on `{{DEFAULT_BRANCH}}`, and prints the fix. It is advice with teeth, not a wall: see the lesson "Guards match command text". +- Claude Code uses a hook from `.claude/settings.json` even in a folder not yet trusted (only a parent folder trusted, or a `claude -p` run), so a teammate needs no extra step. +- Agents other than Claude Code get no hook: CI is their stop. + +## Never +- Never push to `{{DEFAULT_BRANCH}}`, never commit on it, never run a bare `gh pr merge`. +- Never hide a command from the hook (in a variable or a helper script) to get past it. The rule still holds and CI finds the break later. +- Never touch secrets or access. Stop and ask a human. +- Never paste a secret, a token or a private key into a file, a PR, an issue or a proof. +- Never invent output. A proof holds what the command printed, not what it should print. +- Never merge a PR whose check is red or pending. + +## Optional kit + +Nothing above needs a plugin. If you also use dwarves-kit, its contract is at https://github.com/dwarvesf/dwarves-kit and its gates read `.kit.toml`. Where its generic rules differ from the rules above, this repo's rules win. diff --git a/templates/team-stamp/files/CHANGELOG.md.tpl b/templates/team-stamp/files/CHANGELOG.md.tpl new file mode 100644 index 000000000..de803ff1f --- /dev/null +++ b/templates/team-stamp/files/CHANGELOG.md.tpl @@ -0,0 +1,13 @@ +# Changelog + +All notable changes to this project are in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). + +## How to read this + +Every entry under `## [Unreleased]` and under each later version starts with a tag, a colon and a space. The tags of this repo are: {{TAGS_COLON}} + +`dev:` is the team-tooling tag: CI, docs, scripts and agent rules. `dev:` lines stay out of the public release notes (`bash scripts/release-notes.sh Unreleased`). The other tags name a part of the product. + +Example entry: `- dev: Add the owners check to CI.` + +## [Unreleased] diff --git a/templates/team-stamp/files/docs/TEAM-WORKFLOW.md.tpl b/templates/team-stamp/files/docs/TEAM-WORKFLOW.md.tpl new file mode 100644 index 000000000..980b0048c --- /dev/null +++ b/templates/team-stamp/files/docs/TEAM-WORKFLOW.md.tpl @@ -0,0 +1,147 @@ +# Team workflow + +How a small team ships fast with AI agents and still stays in sync. This page gives the reasons. The rules themselves live in [`AGENTS.md`](../AGENTS.md), one home for agents and people alike. Each rule below links to its section there. + +## Why + +- Everyone builds with an AI agent. Work starts at the keyboard, not in a meeting. +- Nobody waits for an owner. Every teammate shares the product, so every idea counts. +- Stand-ups and plan-first talks cost more than they give, so the way to stay in sync changes: sync on running things after the work, not on talk before it. +- A rule that only one person's tools enforce binds that person and nobody else. These rules ride in the repo, so they bind every agent and every teammate. + +## The loop + +``` + idea --> claim an issue --> build with AI --> PR = the proposal --> merge when green + (30 s) (no meeting) (proof + changelog) (no approval) + | | | + v v v + issue shows who PR closes its issue digest by script + builds what and carries its proof + + one-way doors only ---> a second person says yes +``` + +## The rules + +Each rule gives the reason. The rule itself, with its conditions, marker lines and commands, lives in `AGENTS.md` and nowhere else. Follow the link. + +### 1. Claim first + +GitHub Issues are the work queue. One issue is one unit of work for one agent run, with a goal and a check that says it is done. + +Why: a claim takes 30 seconds and shows the whole team who builds what. Two people on the same task is the cost of skipping it. A stale claim blocks others, so an old one is released. + +The rule: [Work queue](../AGENTS.md#work-queue). + +### 2. Reversible work merges without an approver + +Merge your own PR when the checks pass. Nobody approves it. Reversible means a revert undoes it: code, docs, tests, a prototype behind a flag. + +Why: waiting for a person is the delay this workflow removes. A revert is cheap, a wait is not. Not sure it is reversible? Treat it as a one-way door (rule 3). + +Merge with `bash scripts/pr-merge.sh --wait <number>`, never a bare `gh pr merge`. The script waits for the checks and refuses a draft, a red or pending check, a conflict, and a change under a door path without a second person's yes. + +The rule: [Merge](../AGENTS.md#merge) and [Checks](../AGENTS.md#checks). + +### 3. One-way doors need a second person's yes + +A one-way door is hard to undo after it ships. A charged customer cannot be un-charged. A lawyer reads the legal text and people rely on it. A shipped client cannot be recalled. Deleted data does not come back. A leaked key cannot be taken back. For these, a second person says yes first. The author never counts as the second person. + +| Door setting | Value | +|---|---| +| Paths the merge guard checks | {{DOOR_PATHS}} | +| Who says the second yes for those paths | {{DOOR_APPROVER}} | + +A blank path cell means no path is added to the harness's own files, which are always doors: `.github/` (the whole directory), `scripts/`, `.claude/`, `OWNERS.md`, `AGENTS.md` and `CLAUDE.md` at any depth, `.mcp.json`, `docs/TEAM-WORKFLOW.md` and `.kit.toml`. A file an agent reads as instructions is a door; other agent instruction or tool config files a team uses are added with `--door-paths`. A pull request that touches a door needs an approval from a second person on the head the merge guard judged, from an owner, member or collaborator who is not the author and not a bot. A blank approver cell means any such person. Review a change to the hook settings, the lessons index or an `agent-*` script as code that runs in every teammate's next session. The first pull request that introduces the stamp touches every door: a second person reads it, and it is merged by hand. + +Agents follow the same list. An agent stops and asks a human before it touches secrets or access. + +The rule: [One-way doors](../AGENTS.md#one-way-doors) and [Never](../AGENTS.md#never). + +### 4. The PR carries its own bookkeeping + +Ask your agent to do all of this in the same PR. Nobody files it later: later does not happen. The PR closes its issue, fixes the docs the code made wrong, and carries its proof and its changelog line. + +Why: a proof you did not run is the agent's word. The proof file and its negative control make "done" something a second person can re-run. The changelog line makes the next release note write itself. Tags in use: {{TAGS}}. The tag `dev` marks team tooling and stays out of the release notes. + +The rules: [What a PR carries](../AGENTS.md#what-a-pr-carries), [Proof](../AGENTS.md#proof) and [Changelog](../AGENTS.md#changelog). Product code lives under {{PRODUCT_PATHS}}. + +### 5. A digest replaces the stand-up + +One script reads GitHub and the board file and prints a short markdown page. No meeting, no status chat. See "Digest" below. + +Every script and job has an owner, a person or a named agent with a sponsor, so a broken one is never nobody's problem. The rule: [Checks](../AGENTS.md#checks). + +## What a good PR looks like + +The PR is the proposal. The reader should know in one minute what it does and that it works. The PR template has a section for each part. + +| Part | What goes in | +|---|---| +| Closes | `Closes #<n>`, the issue that holds the work | +| Proof | A proof file with a negative control. Run it yourself, do not trust the agent's word. See [Proof](../AGENTS.md#proof) | +| Changelog | A tagged line under `[Unreleased]` for product code | +| One-way door line | Only when the PR touches a door in rule 3 | + +How to write the proof: [`verification/README.md`](verification/README.md). The one local check before a push: `bash scripts/check.sh`. The commands by area: [Commands](../AGENTS.md#commands). + +## When ideas collide + +Two people want different things for the same part of the product. + +1. Each builds a small prototype on their own branch. Claim an issue each, with a note that points at the other. +2. Neither merges. Both show the running prototype to the team. +3. The team picks one. If the team cannot, the owner picks. +4. The loser's PR closes with a short note. + +Do not argue in a thread first. A demo settles it faster. + +## Digest + +``` +bash scripts/team-digest.sh # last 24 hours +bash scripts/team-digest.sh --hours 72 # after a weekend +``` + +- It needs only `gh` (logged in) and the standard tools. It writes markdown to stdout and posts nothing. +- It shows: PRs merged in the window, open PRs, open issues with assignee, and the board rows that wait on a human decision. +- Read it instead of a stand-up. Reply in the PR or the issue, not in a meeting. + +## From board rows to issues + +After the board file changes, whoever merged it runs `bash scripts/issues-from-rows.sh` for a dry run, then `--apply`. It makes one issue per queued, tagged, ready row, and a rerun creates nothing twice. Then each person hands their issues to their own agents: `gh issue list --assignee @me --label ready --state open`. The issue's Done when is the finish check. + +## Limits + +GitHub cannot enforce any of this without branch protection. A person who merges from the GitHub site passes everything, on a plan without branch protection. + +Two machines back the rules instead: a Claude Code hook for the agents that run in it, and the CI check `pr-shape` for everyone. The hook is advice with teeth, not a wall. Claude Code uses a hook from `.claude/settings.json` even in a folder not yet trusted (only a parent folder trusted, or a `claude -p` run), so a teammate needs no extra step. Agents other than Claude Code meet only the CI check. + +A pull request can edit the workflow file itself, because GitHub runs the pull request's copy. The merge guard is what binds it: it needs both checks `changes` and `pr-shape` from the workflow `CI`, and a change to `.github/workflows/` is a door that needs a second person. The two CI jobs run on a self-hosted runner and run only scripts copied from the base revision. A job that runs a pull request's own code (tests, builds) belongs on a separate runner label or in a container job, never on the runner that runs `changes` and `pr-shape`, because a long-lived runner keeps what a pull request's code writes. Not for public repos. + +The rule: [Limits](../AGENTS.md#limits). + +## Optional kit + +The owner may use dwarves-kit on a machine. Nothing here needs it, and it is not part of these rules. The closing section of `AGENTS.md` says what to know: [Optional kit](../AGENTS.md#optional-kit). + +## Rule index + +Every section of `AGENTS.md` has its anchor here, so a change to one shows up in the other. The check `scripts/pr-shape.sh` keeps the two files in step. + +- [Agent rules](../AGENTS.md#agent-rules) +- [Commands](../AGENTS.md#commands) +- [Playbooks](../AGENTS.md#playbooks) +- [Lessons](../AGENTS.md#lessons) +- [Team rules](../AGENTS.md#team-rules) +- [Work queue](../AGENTS.md#work-queue) +- [What a PR carries](../AGENTS.md#what-a-pr-carries) +- [Proof](../AGENTS.md#proof) +- [Changelog](../AGENTS.md#changelog) +- [One-way doors](../AGENTS.md#one-way-doors) +- [Merge](../AGENTS.md#merge) +- [Checks](../AGENTS.md#checks) +- [Limits](../AGENTS.md#limits) +- [Never](../AGENTS.md#never) +- [Optional kit](../AGENTS.md#optional-kit) diff --git a/templates/team-stamp/files/docs/verification/README.md.tpl b/templates/team-stamp/files/docs/verification/README.md.tpl new file mode 100644 index 000000000..11e9da9ba --- /dev/null +++ b/templates/team-stamp/files/docs/verification/README.md.tpl @@ -0,0 +1,88 @@ +# Verification: how to write a proof + +A proof is a file that shows a change works. Anyone can read it, run its commands and get the same result. This page has everything you need to write one. + +## One file per PR + +- Write `docs/verification/<slug>.md`. The slug is the branch name without the type, for example `fix-login-timeout`. +- One file per PR, so two PRs never conflict on a proof. Add to your own file. Do not edit another PR's file: proofs are dated evidence. +- A change to any file that is not documentation needs one. CI job `pr-shape` fails the PR without it. The rule is in [`AGENTS.md`](../../AGENTS.md#proof). +- This README is never a proof. Editing it does not count. +- A change with no behavior effect (a comment, a rename, formatting) puts one line in the PR body: `no-proof: <reason, 10+ characters>`. CI prints the reason and skips the proof check. + +## The block shape + +Every claim is one block. Run the command yourself and paste what it printed. The shape, with placeholders in angle brackets: + +``` +Command: <the exact command, from the repo root> +Output: +<the lines the command printed, trimmed to the ones that matter> +Exit: <the real exit code> +Verdict: PASS +``` + +- `Command:` the exact command, from the repo root. +- `Output:` real output on the lines right below the label. Trim to the lines that matter and say how many you cut. Never write "should work" or invent a line. +- `Exit:` the real exit code. +- `Verdict:` `PASS`, or `RED, as expected` for a negative control. + +CI reads the file, not only its name. At least one proof file in the PR must hold: + +1. an `Exit:` line; +2. an `Output:` line with a non-empty line right after it; +3. a line that starts `Verdict: RED`; +4. the words `NEGATIVE CONTROL` (any case). + +A missing part fails `pr-shape`, and the message names it. Paste real output: a file that has the labels and no real run is not a proof, and a reader will see that. + +## What goes in the file + +1. A title, `# Verification: <what changed>`, and one paragraph on what the PR does. +2. A green run: one block for each test, build or check that covers the change. Include `bash scripts/check.sh` run on the branch. Trim the output inside the block; store no raw log file anywhere. +3. A negative control (next section). +4. "Not proven": a list of what you did not run or could not run. +5. "Rollback", only for a stateful change. + +## The negative control + +A green run alone proves little: a test that cannot fail proves nothing. Show that the test goes red when the change is broken. + +1. Commit the work first. The restore step below only brings back committed text. +2. Break one thing the change adds: remove a check, flip a condition, drop a line. +3. Run the test that should catch it. Paste the block with the failing lines and `Verdict: RED, as expected`. +4. Restore the file: `git checkout -- <file>`. +5. Run the test again. Paste the green block. + +The block for step 3 reads like this: + +``` +NEGATIVE CONTROL: <the one thing you broke> +Command: <the test command> +Output: +<the failing lines> +Exit: <non-zero> +Verdict: RED, as expected +``` + +Name the one thing you broke. If the test stays green, the test is too weak: fix the test, then repeat. + +`scripts/negctl.sh` runs these steps for you and prints the block. Give it the test command and a command that breaks one thing: + +```sh +bash scripts/negctl.sh "<the test command>" "<a command that breaks one thing>" +``` + +It refuses a tree with uncommitted changes to tracked files, wants green before and red under the break, refuses a red that is only a load or syntax error, restores the files the break changed, and wants green again. It exits 0 only for green, red, green. Paste the block it prints. + +## Not proven + +List what the proof does not show, in plain words. Examples: a device run when no device was at hand, a job on the CI runner that you only ran locally, an agent other than Claude Code, a path that needs a credential you do not have. A short honest list is better than a long claim. + +## Rollback + +For a stateful change (a deploy, data, a migration, a secret), add a "Rollback" section: the command that undoes it, what it leaves behind, and whether you ran it. A reversible change says how to revert. An irreversible one is a one-way door: see [`docs/TEAM-WORKFLOW.md`](../TEAM-WORKFLOW.md) rule 3. + +## Limits of a proof + +A proof is a reader's check, not a lock. A person who merges from the GitHub site passes everything, on a plan without branch protection, and the Claude Code hook is advice with teeth, not a wall. [`docs/TEAM-WORKFLOW.md`](../TEAM-WORKFLOW.md) lists both limits. diff --git a/templates/team-stamp/files/scripts/agent-guard.sh.tpl b/templates/team-stamp/files/scripts/agent-guard.sh.tpl new file mode 100644 index 000000000..029911603 --- /dev/null +++ b/templates/team-stamp/files/scripts/agent-guard.sh.tpl @@ -0,0 +1,483 @@ +#!/usr/bin/env bash +# agent-guard.sh - Claude Code PreToolUse hook for the Bash tool. It stops three +# wrong actions at the moment they happen and says what to do instead. +# +# 1. a bare `gh pr merge` (or the merge API) -> merge with scripts/pr-merge.sh +# 2. a push that lands on {{DEFAULT_BRANCH}} -> push a branch and open a PR +# 3. `git commit` while on {{DEFAULT_BRANCH}} -> create a branch first +# +# Wired in .claude/settings.json. Claude Code sends the hook JSON on stdin +# (tool_input.command, cwd); exit 2 blocks and shows stderr to the agent, and any +# other exit lets the command run. A block prints exactly two lines: the rule, +# then `Fix:` with a command. Every internal failure exits 0, so a bug in this +# file never traps a session. +# +# JSON is read with jq. Without jq the guard is off: it prints one note and +# allows. Without awk it is off the same way. No network, and no git call unless +# the command holds `git commit` or `git push`. +# +# What this guard does not catch. It is text matching on the command line, not a +# shell parser, so CI (the PR shape check) and scripts/pr-merge.sh are the layers +# that bind. Known misses: +# - a command word split by a backslash in its middle (`g\h`); a backslash before the word (`\gh`) is read +# - a command built from variables, functions, aliases or command substitution +# (`$(gh pr merge 5)`, `$g push origin {{DEFAULT_BRANCH}}`); only the shape +# `$g pr merge` is read +# - a script, make target or tool that runs git or gh itself (`bash x.sh`, +# `xargs`, `find -exec`, `ssh host ...`) +# - a push configured away from its words (a git alias, `remote.<name>.push`, +# `push.default`), and `git -c alias.x=push x` +# - a merge from the GitHub site or any client other than gh +# - a `gh api` merge that does not spell the method PUT as a word, or a graphql +# call other than a literal `mergePullRequest` +# - a commit made by a tool other than `git commit` (an editor, a GUI) +# What it does read: `;` `&&` `||` `|` and newline splits outside quotes, heredoc +# bodies are skipped, `bash -c` and `eval` payloads are checked, and the wrappers +# sudo, env, command, exec, nohup, time, nice, timeout, stdbuf and setsid are +# skipped, so `echo "gh pr merge"` and `rg 'git push'` pass. +set -o pipefail + +default_branch="{{DEFAULT_BRANCH}}" +merge_cmd='bash scripts/pr-merge.sh --wait' + +note() { printf 'agent-guard: %s\n' "$1" >&2; } + +command -v jq >/dev/null 2>&1 || { + note "jq is not installed, so the guard is off" + exit 0 +} +command -v awk >/dev/null 2>&1 || { + note "awk is not installed, so the guard is off" + exit 0 +} + +input="$(cat)" || exit 0 +parsed="$(printf '%s' "$input" | jq -r '(.cwd // ""), (.tool_input.command // "")' 2>/dev/null)" || { + note "could not read the hook input, allowing" + exit 0 +} +cmd="" cwd="" +case "$parsed" in +*" +"*) + cwd="${parsed%% +*}" + cmd="${parsed#* +}" + ;; +esac +[ -n "$cmd" ] || exit 0 + +# Fast path: most commands never mention gh, git or a shell string. +case "$cmd" in +*gh* | *git* | *" -c"* | *eval* | *'$'*) ;; +*) exit 0 ;; +esac + +eff_dir="${cwd:-$PWD}" +branch_override="" +depth=0 + +# A block ends the whole check. 42 is the private "blocked" signal that the outer +# wrapper turns into exit 2, so no other failure can ever read as a block. +block() { # block <rule> <fix> + printf 'agent-guard: %s\nFix: %s\n' "$1" "$2" >&2 + exit 42 +} + +# One part per line; separators inside quotes become control characters, so a +# quoted `;` or `&&` does not split. Heredoc bodies are dropped. +split_parts() { + awk ' + BEGIN { inq = ""; hd = "" } + function flush() { if (seg ~ /[^ \t]/) print seg; seg = "" } + { + if (hd != "") { + t = $0 + gsub(/^[ \t]+|[ \t]+$/, "", t) + if (t == hd) hd = "" + next + } + line = $0 + n = length(line) + pending = "" + for (i = 1; i <= n; i++) { + c = substr(line, i, 1) + if (inq != "") { + if (c == inq) { inq = ""; seg = seg c } + else if (inq == "\"" && c == "\\") { seg = seg c substr(line, i + 1, 1); i++ } + else if (c == ";") seg = seg "\001" + else if (c == "&") seg = seg "\002" + else if (c == "|") seg = seg "\003" + else seg = seg c + continue + } + if (c == "\\") { seg = seg c substr(line, i + 1, 1); i++; continue } + if (c == "\"" || c == "\047") { inq = c; seg = seg c; continue } + if (c == "#" && (i == 1 || substr(line, i - 1, 1) ~ /[ \t]/)) break + if (c == ";" || c == "&" || c == "|") { flush(); continue } + if (c == "<" && substr(line, i, 2) == "<<" && substr(line, i, 3) != "<<<") { + j = i + 2 + if (substr(line, j, 1) == "-") j++ + while (substr(line, j, 1) == " ") j++ + q = substr(line, j, 1) + if (q == "\"" || q == "\047") j++ + w = "" + while (j <= n && substr(line, j, 1) ~ /[A-Za-z0-9_]/) { w = w substr(line, j, 1); j++ } + if (w != "") pending = w + seg = seg "<<" + i++ + continue + } + seg = seg c + } + if (inq != "") seg = seg "\004" + else flush() + if (pending != "") hd = pending + } + END { flush() }' +} + +branch_of() { # branch_of <dir> + if [ -n "$branch_override" ]; then + printf '%s' "$branch_override" + return + fi + git -C "$1" symbolic-ref --short -q HEAD 2>/dev/null || true +} + +resolve_dir() { # resolve_dir <path>: relative to the current effective dir + local d="$1" + case "$d" in + "~"*) d="$HOME${d#\~}" ;; + esac + case "$d" in + /*) printf '%s' "$d" ;; + *) printf '%s/%s' "$eff_dir" "$d" ;; + esac +} + +is_branch() { # is_branch <dir> <name>: a local branch, or a remote one git would track + git -C "$1" rev-parse --verify -q "refs/heads/$2" >/dev/null 2>&1 && return 0 + [ -n "$(git -C "$1" for-each-ref --format=x "refs/remotes/*/$2" 2>/dev/null)" ] +} + +# block_merge <number> <branch word>: the fix names the PR when the command did. +block_merge() { + local fix + if [ -n "$1" ]; then + fix="$merge_cmd $1" + elif [ -n "$2" ]; then + fix="$merge_cmd \"\$(gh pr view $2 --json number --jq .number)\"" + else + fix="$merge_cmd \"\$(gh pr view --json number --jq .number)\"" + fi + block "a bare gh pr merge skips the merge guard (checks, conflicts, one-way doors)." "$fix" +} + +# check_pr_merge <words after merge>: find the PR number, else a branch word. +check_pr_merge() { + local a skip=0 num="" word="" + for a in "$@"; do + if [ "$skip" -eq 1 ]; then + skip=0 + continue + fi + case "$a" in + -R | --repo | -b | --body | -F | --body-file | -t | --subject | -A | --author-email | --match-head-commit) skip=1 ;; + -*) ;; + *) + [ -z "$num$word" ] || continue + case "$a" in + "") ;; + *[!0-9]*) + case "$a" in + */pull/[0-9]*) + num="${a##*/pull/}" + num="${num%%[!0-9]*}" + ;; + *[!A-Za-z0-9._/-]*) ;; + *) word="$a" ;; + esac + ;; + *) num="$a" ;; + esac + ;; + esac + done + block_merge "$num" "$word" +} + +# check_gh_api <words after api>: only a PUT to .../pulls/<n>/merge, or a literal +# mergePullRequest mutation, is read as a merge. +check_gh_api() { + local a put=0 num="" merge=0 + for a in "$@"; do + case "$a" in + PUT | put | -XPUT | -Xput | --method=PUT | --method=put) put=1 ;; + *mergePullRequest*) block_merge "" "" ;; + */pulls/[0-9]*/merge*) + merge=1 + num="${a#*/pulls/}" + num="${num%%[!0-9]*}" + ;; + esac + done + if [ "$merge" -eq 1 ] && [ "$put" -eq 1 ]; then block_merge "$num" ""; fi + return 0 +} + +# check_gh <words after gh>: group and verb are the first two words that are not flags. +check_gh() { + local -a args=("$@") + local j=0 m="${#args[@]}" group="" gi=0 verb="" vi=0 + while [ "$j" -lt "$m" ]; do + case "${args[$j]}" in + -R | --repo) + j=$((j + 2)) + continue + ;; + -*) ;; + *) + if [ -z "$group" ]; then + group="${args[$j]}" + gi="$j" + else + verb="${args[$j]}" + vi="$j" + break + fi + ;; + esac + j=$((j + 1)) + done + case "$group:$verb" in + pr:merge) check_pr_merge "${args[@]:$((vi + 1))}" ;; + api:*) check_gh_api "${args[@]:$((gi + 1))}" ;; + esac + return 0 +} + +check_git() { # check_git <words...>, the words after `git` + local dir="$eff_dir" sub="" i=0 + local -a w=("$@") + while [ "$i" -lt "${#w[@]}" ]; do + case "${w[$i]}" in + -C) + dir="$(resolve_dir "${w[$((i + 1))]:-.}")" + i=$((i + 2)) + ;; + -c) + i=$((i + 2)) + ;; + -*) i=$((i + 1)) ;; + *) + sub="${w[$i]}" + i=$((i + 1)) + break + ;; + esac + done + local -a rest=("${w[@]:$i}") + + case "$sub" in + switch | checkout) + # A branch change earlier in the same command decides the later parts. + # `git checkout README.md` restores a file and switches nothing: a word + # counts as a branch only after -b, -c or --create, or when it names a + # branch that exists. A `--` marks the rest as paths. + local target="" prev="" a created=0 pathmode=0 detach=0 + for a in "${rest[@]}"; do + case "$prev" in + -c | -b | -B | -C | --create | --force-create) + if [ -z "$target" ]; then + target="$a" + created=1 + fi + ;; + esac + case "$a" in + --) pathmode=1 ;; + -d | --detach) detach=1 ;; + -*) ;; + *) [ -n "$target" ] || target="$a" ;; + esac + prev="$a" + done + if [ "$pathmode" -eq 1 ]; then + : + elif [ "$detach" -eq 1 ]; then + branch_override="(detached)" + elif [ -n "$target" ] && { [ "$created" -eq 1 ] || is_branch "$dir" "$target"; }; then + branch_override="$target" + fi + ;; + commit) + local a dry=0 b + for a in "${rest[@]}"; do + [ "$a" != "--dry-run" ] || dry=1 + done + [ "$dry" -eq 0 ] || return 0 + b="$(branch_of "$dir")" + if [ "$b" = "$default_branch" ]; then + block "you are on $default_branch, and nothing commits to $default_branch directly (your changes come with you to a branch)." \ + "git switch -c <type>/<slug>" + fi + ;; + push) + local a skip=0 dry=0 tags=0 sweep=0 remote_seen=0 b r dst + local -a refs=() + for a in "${rest[@]}"; do + if [ "$skip" -eq 1 ]; then + skip=0 + continue + fi + case "$a" in + -n | --dry-run) dry=1 ;; + --tags) tags=1 ;; + --all | --mirror) sweep=1 ;; + -o | --push-option | --repo | --receive-pack | --exec) skip=1 ;; + -*) ;; + *) + if [ "$remote_seen" -eq 0 ]; then + remote_seen=1 + else + refs+=("$a") + fi + ;; + esac + done + [ "$dry" -eq 0 ] || return 0 + b="$(branch_of "$dir")" + local msg="a push to $default_branch skips review, and nothing lands on $default_branch except through a PR." + local fix="git switch -c <type>/<slug> && git push -u origin <type>/<slug> && gh pr create" + if [ "$sweep" -eq 1 ]; then + block "git push --all and --mirror push every branch, $default_branch included, and nothing lands on $default_branch except through a PR." \ + "git push -u origin <type>/<slug> && gh pr create" + fi + if [ "${#refs[@]}" -eq 0 ]; then + if [ "$tags" -eq 0 ] && [ "$b" = "$default_branch" ]; then block "$msg" "$fix"; fi + return 0 + fi + for r in "${refs[@]}"; do + r="${r#+}" + case "$r" in + *:*) dst="${r#*:}" ;; + *) dst="$r" ;; + esac + dst="${dst#refs/heads/}" + if [ "$dst" = "$default_branch" ]; then block "$msg" "$fix"; fi + if [ "$dst" = "HEAD" ] && [ "$b" = "$default_branch" ]; then block "$msg" "$fix"; fi + done + ;; + esac + return 0 +} + +check_segment() { # check_segment <one part> + local seg="$1" word i=0 + local -a w=() + # shellcheck disable=SC2162 + read -a w <<<"$seg" || true + local n="${#w[@]}" + local -a c=() + for ((i = 0; i < n; i++)); do + word="${w[$i]//\"/}" + word="${word//\'/}" + c+=("${word//\\/}") # a backslash before a word (\gh) is the same word to the shell + done + + # Skip shell keywords, VAR=value words and command wrappers (with their own + # flags and the timeout duration) to reach the real command word. + local wrapped=0 prevw="" + i=0 + while [ "$i" -lt "$n" ]; do + word="${c[$i]#(}" + case "$word" in + "" | if | then | else | do | while | until | '!' | '{') i=$((i + 1)) ;; + sudo | env | command | exec | nohup | time | nice | timeout | stdbuf | setsid) + wrapped=1 + prevw="$word" + i=$((i + 1)) + ;; + [A-Za-z_]*=*) i=$((i + 1)) ;; + -n | -u | -s | -k | -g | -C | -U | -S) + [ "$wrapped" -eq 1 ] || break + i=$((i + 2)) + ;; + -*) + [ "$wrapped" -eq 1 ] || break + i=$((i + 1)) + ;; + [0-9]*) + [ "$prevw" = "timeout" ] || break + prevw="" + i=$((i + 1)) + ;; + *) break ;; + esac + done + [ "$i" -lt "$n" ] || return 0 + local first="${c[$i]#(}" + case "$first" in + '$'*) ;; + *) first="${first##*/}" ;; + esac + local -a args=("${c[@]:$((i + 1))}") + + case "$first" in + cd | pushd) + case "${args[0]:-}" in + "" | - | *'$'*) ;; + *) eff_dir="$(resolve_dir "${args[0]}")" ;; + esac + ;; + gh | '$'*) + check_gh "${args[@]}" + ;; + git) + check_git "${args[@]}" + ;; + bash | sh | zsh | dash | ksh | eval) + [ "$depth" -lt 3 ] || return 0 + local k=0 m="${#args[@]}" found=0 + if [ "$first" = "eval" ]; then + found=1 + else + while [ "$k" -lt "$m" ]; do + case "${args[$k]}" in + -c | -[a-z]*c) + found=1 + k=$((k + 1)) + break + ;; + esac + k=$((k + 1)) + done + fi + if [ "$found" -eq 1 ]; then + local payload="${args[*]:$k}" + payload="$(printf '%s' "$payload" | tr '\001\002\003\004' ';&|\n')" + depth=$((depth + 1)) + check_command "$payload" + depth=$((depth - 1)) + fi + ;; + esac + return 0 +} + +check_command() { # check_command <command string> + local line + while IFS= read -r line; do + check_segment "$line" + done <<EOF +$(printf '%s\n' "$1" | split_parts 2>/dev/null) +EOF + return 0 +} + +( check_command "$cmd" ) +rc=$? +[ "$rc" -ne 42 ] || exit 2 +exit 0 diff --git a/templates/team-stamp/files/scripts/agent-lessons.sh b/templates/team-stamp/files/scripts/agent-lessons.sh new file mode 100755 index 000000000..923bd9f5a --- /dev/null +++ b/templates/team-stamp/files/scripts/agent-lessons.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# agent-lessons.sh - print the repo lesson index for a coding agent. +# The Claude Code SessionStart hook in .claude/settings.json runs it, and plain stdout from that +# hook becomes context. Any agent can run it by hand. +# The hook output is capped at 10,000 characters, so the index stays under 8,000 and this script +# cuts at a whole line below 9,000 and says so. +# Always exits 0: a missing index must never block a session. bash 3.2 safe. +limit=9000 +root="$(cd "$(dirname "$0")/.." && pwd)" +index="$root/.claude/memory/MEMORY.md" + +[ -f "$index" ] || exit 0 +size="$(wc -c < "$index" | tr -d ' ')" +if [ "$size" -le "$limit" ]; then + cat "$index" + exit 0 +fi + +LC_ALL=C awk -v max="$limit" '{ n += length($0) + 1; if (n > max) exit; print }' "$index" +echo +echo "agent-lessons: the index is $size characters and this output stops below $limit. Read the rest in .claude/memory/MEMORY.md and shorten that file to under 8,000 characters." +exit 0 diff --git a/templates/team-stamp/files/scripts/check-owners.sh b/templates/team-stamp/files/scripts/check-owners.sh new file mode 100755 index 000000000..bfd9ee7ea --- /dev/null +++ b/templates/team-stamp/files/scripts/check-owners.sh @@ -0,0 +1,149 @@ +#!/usr/bin/env bash +# check-owners.sh - fail when a tracked script or workflow has no owner row in OWNERS.md. +# +# bash scripts/check-owners.sh +# +# Checked: every tracked file under scripts/ and .github/workflows/ has a row (the path in the row +# matches the tracked path byte for byte; only the choice of owned areas ignores case); every row that +# names a path (the first cell in backticks) names a path that exists; every owner cell is +# filled; an owner that is not an @login is an agent and needs a sponsor. A row whose first cell +# has no backticks is a job with no file: only its owner and sponsor are checked. Rows are read +# from every table in OWNERS.md: | Path | What it does | Owner | Sponsor |. +# Each offender prints a two-line refusal on stderr (the rule, then a Fix line). Exit 1 when any +# refusal printed. A repo's own scripts that are not in OWNERS.md yet refuse until a row is added. +set -euo pipefail +# Byte-wise matching: a name is judged by its bytes, never by a locale. +export LC_ALL=C +cd "$(dirname "$0")/.." + +OWNERS=OWNERS.md +refusals="" +# Repo text (a file name, a table cell) is attacker-chosen. clean() makes it printable on one line +# (every character outside a small set becomes ?); safe() says it may sit inside a pasted command. +clean() { local s="${1:0:80}"; printf '%s' "${s//[!A-Za-z0-9._\/@ ,=#()+-]/?}"; } +safe() { [[ "$1" =~ ^[A-Za-z0-9._/@][A-Za-z0-9._/@-]*$ ]]; } +refuse() { # refuse <rule> <fix>: queue one two-line refusal + refusals="${refusals}check-owners: $1 +Fix: $2 +" +} +finish() { + printf '%s' "$refusals" >&2 + exit 1 +} + +git rev-parse --git-dir >/dev/null 2>&1 || { refuse "this is not a git repository, so there is no list of tracked files" "git init"; finish; } +if [ ! -f "$OWNERS" ]; then + refuse "$OWNERS is missing" "printf '# Owners\\n\\n| Path | What it does | Owner | Sponsor |\\n|---|---|---|---|\\n' > $OWNERS" + finish +fi + +# One line per table row: path, owner, sponsor, label (separated by byte 037). The path is empty for a job with no file. +# A header row is the row right before a |---| separator row; it is dropped. +rows="$(awk -F'|' ' + BEGIN { SEP = "\037" } + function trim(s) { gsub(/^[ \t]+|[ \t]+$/, "", s); return s } + function emit(line, c, first, path, label) { + split(line, c, "|") + first = trim(c[2]) + if (first == "") return + if (first ~ /^`.*`$/) { path = first; gsub(/`/, "", path); label = path } + else { path = ""; label = first } + print path SEP trim(c[4]) SEP trim(c[5]) SEP label + } + function flush() { if (have) { emit(buf); have = 0 } } + /^\|/ { + line = $0; gsub(/\r/, "", line) + if (line ~ /^\|[ \t]*:?-+:?[ \t]*\|/) { have = 0; next } + flush(); buf = line; have = 1; next + } + { flush() } + END { flush() } +' "$OWNERS")" + +# Doors match any casing; ownership matches the exact path. Lower case decides only which tracked +# files fall under an owned area, so SCRIPTS/x.sh needs a row. A row names a tracked path byte for +# byte, and two paths that are the same name in lower case but differ in case are refused: a +# case-insensitive checkout can write one over the other. +owned_area() { + case "$1" in + [Ss][Cc][Rr][Ii][Pp][Tt][Ss]/*) return 0 ;; + [.][Gg][Ii][Tt][Hh][Uu][Bb]/[Ww][Oo][Rr][Kk][Ff][Ll][Oo][Ww][Ss]/*) return 0 ;; + esac + return 1 +} +owned_paths="$(printf '%s\n' "$rows" | awk -F'\037' '$1 != "" { print $1 }')" +row_stream="$(printf '%s\n' "$rows" | awk -F'\037' '$1 != "" { print "r:" $1 }')" + +# The tracked paths are read NUL-delimited, so a newline in a name cannot split one path into two. +count=0 +odd_owned=0 +tracked_owned="" +all_stream="" +while IFS= read -r -d '' file; do + case "$file" in + *[![:print:]]*) + # a name no row can write and no pasted command can hold: refused when it sits in an owned area + if owned_area "$file"; then odd_owned=$((odd_owned + 1)); fi + continue + ;; + esac + all_stream="${all_stream}t:${file} +" + if owned_area "$file"; then + tracked_owned="${tracked_owned}${file} +" + fi +done < <(git -c core.quotePath=false ls-files -z) + +if [ "$odd_owned" -gt 0 ]; then + refuse "$odd_owned tracked path(s) under scripts/ or .github/workflows/ have a name with a newline, a control byte or a byte above 0x7F, so no row can name them" \ + "rename each with git mv to a name of printable ASCII characters only (find them in the output of git ls-files: git wraps such a name in double quotes)" +fi + +collide="$(printf '%s\n%s\n' "$all_stream" "$row_stream" | awk ' + NF == 0 { next } + { e = substr($0, 3); k = tolower(e) + if (k in seen) { if (seen[k] != e && !(k in rep)) { rep[k] = 1; if (n++ < 3) printf "%s / %s; ", e, seen[k] } } + else seen[k] = e }')" +if [ -n "$collide" ]; then + refuse "paths that are the same name in lower case but differ in case (ownership matches the exact path): $(clean "${collide%; }")" \ + "git mv one of the tracked paths to a name that differs in more than case, or correct the Path cell of its row in $OWNERS" +fi + +while IFS= read -r file; do + [ -n "$file" ] || continue + count=$((count + 1)) + if ! printf '%s\n' "$owned_paths" | grep -Fxq -- "$file"; then + if safe "$file"; then + fix="printf '%s\\n' '| \`$file\` | what it does | @github-login | |' >> $OWNERS" + else + fix="add a row for that file to $OWNERS by hand (its name holds characters this script will not put in a command)" + fi + refuse "no owner yet for $(clean "$file"); every script and workflow needs a row in $OWNERS" "$fix" + fi +done <<EOF2 +$tracked_owned +EOF2 + +while IFS=$'\037' read -r path owner sponsor label; do + [ -n "$label" ] || continue + if [ -n "$path" ] && [ ! -e "$path" ]; then + if safe "$path"; then + fix="grep -vF '\`$path\`' $OWNERS > $OWNERS.new && mv $OWNERS.new $OWNERS" + else + fix="delete that row from $OWNERS by hand (its path holds characters this script will not put in a command)" + fi + refuse "row names a path that does not exist: $(clean "$path")" "$fix" + fi + if [ -z "$owner" ]; then + refuse "empty owner: $(clean "$label")" "\${EDITOR:-vi} $OWNERS # put a @github-login in the Owner cell of that row" + elif [ "${owner#@}" = "$owner" ] && [ -z "$sponsor" ]; then + refuse "agent owner $(clean "$owner") has no sponsor: $(clean "$label")" "\${EDITOR:-vi} $OWNERS # name the human who answers for that agent in the Sponsor cell of its row" + fi +done <<EOF2 +$rows +EOF2 + +[ -z "$refusals" ] || finish +echo "check-owners: $count paths, all owned" diff --git a/templates/team-stamp/files/scripts/check.sh.tpl b/templates/team-stamp/files/scripts/check.sh.tpl new file mode 100644 index 000000000..54042e6d3 --- /dev/null +++ b/templates/team-stamp/files/scripts/check.sh.tpl @@ -0,0 +1,236 @@ +#!/usr/bin/env bash +# check.sh - the one local command before a push. It runs the checks CI runs (.github/workflows/ci.yml, +# jobs changes and pr-shape) with the same inputs, so a red CI run is a red local run first. +# Needs git and bash. No token, no network. +# +# bash scripts/check.sh owners, PR shape, the script tests +# bash scripts/check.sh --title 'feat(x): y' --body 'Closes #12' +# bash scripts/check.sh --title 'feat(x): y' --body-file body.txt +# bash scripts/check.sh --help +# +# Twin set: the gate commands. ci.yml carries the same list at its top and runs each of them with +# the same inputs. Keep the two lists, and the commands below, in step with ci.yml. +# twin: check-owners.sh +# twin: pr-shape.sh env PR_TITLE PR_BODY BASE_SHA HEAD_SHA +# The generated script tests below are not in CI (a job that runs a pull request's own code does not +# belong on the gate runner); check.sh runs them on your machine. +# +# PR title and body. The first source that applies wins: +# 1. arguments: --title, --body or --body-file +# 2. environment: PR_TITLE, PR_BODY or PR_BODY_FILE (the names pr-shape.sh reads) +# 3. gh pr view, only when gh is on PATH and steps 1 and 2 gave no title and no body. It reads the +# open PR of this branch with your own gh login; this script sets no token and the no-gh path +# needs none. +# 4. otherwise the title is the first commit subject on the branch and the body is empty, so a rule +# that reads the body (Closes #n, no-proof:, no-changelog:) fails here as it would in CI with an +# empty body. Pass --body to give it. +# BASE_SHA and HEAD_SHA default to the merge base with origin/{{DEFAULT_BRANCH}} and to HEAD; set them +# to check another range. PR shape reads commits, so commit first. +# +# Output: "ok <check>" lines, the checks' own lines, and "check: N failed, M passed" last. Every +# failed step prints exactly two lines on stderr, "check: <the rule>" then "Fix: <a command>". +# Exit 0 when no step failed, 1 when one or more failed, 2 for bad usage or no base revision. +# +# Safety: a PR title, a body, a file name and a test's output are attacker-chosen text. A value reaches +# an output line only through clean() (every character outside letters, digits and ._/@- and space +# becomes ?) or, for a test's own output behind " | ", through show(), and reaches a Fix line only +# when safe_arg() accepts it. bash 3.2 safe. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 2 + +DEFAULT_BRANCH='{{DEFAULT_BRANCH}}' +self='^\.github/workflows/ci\.yml$' +product_re='{{PRODUCT_ERE}}' + +clean() { printf '%s' "${1:0:80}" | LC_ALL=C tr -c 'A-Za-z0-9._/@ -' '?'; } +# show: the same filter for a test's own output, which keeps : , = ( ) # + % and brackets so a summary line reads +# normally; a $, a quote and a backtick still become ?, and a line is always printed behind " | ". +show() { printf '%s' "${1:0:200}" | LC_ALL=C tr -c 'A-Za-z0-9._/@ :,=#()+%[]-' '?'; } +safe_re='^[A-Za-z0-9._/@-]+$' +safe_arg() { case "$1" in -* | "") return 1 ;; esac; [[ "$1" =~ $safe_re ]]; } +strip() { printf '%s' "$1" | LC_ALL=C tr -d '\000-\037\177'; } + +fails=0 +passed=0 +ok() { + passed=$((passed + 1)) + printf 'ok %s\n' "$1" +} +note() { printf 'note %s\n' "$1"; } +detail() { printf ' | %s\n' "$(show "$1")"; } +# refuse <rule> <fix>: a failed step; the two-line refusal on stderr. +refuse() { + fails=$((fails + 1)) + printf 'check: %s\nFix: %s\n' "$(strip "$1")" "$(strip "$2")" >&2 +} +# die <rule> <fix>: bad usage or no base revision; the two-line refusal, then exit 2. +die() { + printf 'check: %s\nFix: %s\n' "$(strip "$1")" "$(strip "$2")" >&2 + exit 2 +} +usage() { + awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0" +} + +# ---- arguments +title="" body="" have_title=0 have_body=0 body_file="" title_src="" body_src="" +while [ $# -gt 0 ]; do + case "$1" in + -h | --help) + usage + exit 0 + ;; + --title) + [ $# -ge 2 ] || die "--title needs a value" "bash scripts/check.sh --title 'feat(x): y'" + title="$2" + have_title=1 + title_src="the --title argument" + shift + ;; + --body) + [ $# -ge 2 ] || die "--body needs a value" "bash scripts/check.sh --body 'Closes #12'" + [ -z "$body_file" ] || die "give --body or --body-file, not both" "bash scripts/check.sh --body-file <file>" + body="$2" + have_body=1 + body_src="the --body argument" + shift + ;; + --body-file) + [ $# -ge 2 ] || die "--body-file needs a file name" "bash scripts/check.sh --body-file <file>" + [ "$have_body" -eq 0 ] || die "give --body or --body-file, not both" "bash scripts/check.sh --body-file <file>" + body_file="$2" + shift + ;; + *) die "unknown option $(clean "$1")" "bash scripts/check.sh --help" ;; + esac + shift +done +read_body_file() { # read_body_file <path> <source label> + [ -f "$1" ] && [ -r "$1" ] || die "the body file $(clean "$1") is not a readable file" "bash scripts/check.sh --body-file <a readable file>" + body="$(cat "$1")" + have_body=1 + body_src="$2" +} +if [ -n "$body_file" ]; then read_body_file "$body_file" "the --body-file argument"; fi + +# ---- environment +if [ "$have_title" -eq 0 ] && [ -n "${PR_TITLE-}" ]; then + title="$PR_TITLE" + have_title=1 + title_src="PR_TITLE" +fi +if [ "$have_body" -eq 0 ]; then + if [ -n "${PR_BODY_FILE-}" ]; then + read_body_file "$PR_BODY_FILE" "PR_BODY_FILE" + elif [ "${PR_BODY+set}" = set ]; then + body="$PR_BODY" + have_body=1 + body_src="PR_BODY" + fi +fi + +# ---- the range +git rev-parse --git-dir >/dev/null 2>&1 || die "this is not a git repository" "git init" +resolve() { # resolve <rev>: the commit id, or fail + case "$1" in -* | "") return 1 ;; esac + git rev-parse --verify -q "$1^{commit}" 2>/dev/null +} +if [ -n "${BASE_SHA-}" ]; then + base="$(resolve "$BASE_SHA")" || die "BASE_SHA $(clean "$BASE_SHA") does not resolve in this clone" "git fetch origin $DEFAULT_BRANCH # then unset BASE_SHA or set it to a commit" +else + base="$(git merge-base "origin/$DEFAULT_BRANCH" HEAD 2>/dev/null)" || die "no merge base with origin/$DEFAULT_BRANCH" "git fetch origin $DEFAULT_BRANCH" +fi +head_ref="${HEAD_SHA:-HEAD}" +head="$(resolve "$head_ref")" || die "HEAD_SHA $(clean "$head_ref") does not resolve in this clone" "git status --short # then unset HEAD_SHA or set it to a commit" +# The changed paths are read NUL-delimited, so a newline in a name cannot split one path into two. A path +# that holds a newline cannot ride a line list: it is kept as a "?" line and counts as a product path. +files="" odd_path=0 +while IFS= read -r -d '' p; do + case "$p" in + *$'\n'*) + odd_path=1 + files="${files}? +" + ;; + *) files="${files}${p} +" ;; + esac +done < <(git diff --name-only -z "$base...$head" 2>/dev/null) + +if [ -n "$(git status --porcelain 2>/dev/null)" ]; then + note "uncommitted changes are not checked: PR shape reads commits, so commit first" +fi +if [ -z "$files" ]; then + note "no committed change against origin/$DEFAULT_BRANCH yet" +fi + +# ---- the PR text, when the arguments and the environment gave none +if [ "$have_title" -eq 0 ] && [ "$have_body" -eq 0 ] && command -v gh >/dev/null 2>&1; then + if t="$(gh pr view --json title --jq .title 2>/dev/null </dev/null)" && [ -n "$t" ]; then + title="$t" + have_title=1 + title_src="the open PR (gh pr view)" + body="$(gh pr view --json body --jq .body 2>/dev/null </dev/null || true)" + have_body=1 + body_src="the open PR (gh pr view)" + fi +fi +if [ "$have_title" -eq 0 ]; then + title="$(git log --reverse --format=%s "$base..$head" 2>/dev/null | head -n 1)" + title_src="the first commit subject on this branch" +fi +if [ "$have_body" -eq 0 ]; then + body="" + body_src="empty (nothing was given)" +fi +note "PR title comes from $title_src; the body comes from $body_src" + +# ---- 1. every script and workflow has an owner (job changes) +if [ ! -f scripts/check-owners.sh ]; then + refuse "scripts/check-owners.sh is missing, so owners are not checked" "git checkout origin/$DEFAULT_BRANCH -- scripts/check-owners.sh" +elif bash scripts/check-owners.sh; then + ok "owners: check-owners.sh passed" +else + refuse "owners: a script or workflow has no row in OWNERS.md, or a row is broken (the lines above name it)" "bash scripts/check-owners.sh # fix each line above, then run it again" +fi + +# ---- 2. PR shape, with the inputs CI gives it (job pr-shape) +if [ ! -f scripts/pr-shape.sh ]; then + refuse "scripts/pr-shape.sh is missing, so the PR shape is not checked" "git checkout origin/$DEFAULT_BRANCH -- scripts/pr-shape.sh" +elif [ -z "$files" ]; then + ok "pr-shape: skipped, no commit on this branch yet" +elif PR_TITLE="$title" PR_BODY="$body" PR_BODY_FILE='' BASE_SHA="$base" HEAD_SHA="$head" bash scripts/pr-shape.sh; then + ok "pr-shape: no check failed" +else + refuse "pr-shape: a check failed (the lines above name each rule)" "bash scripts/check.sh --title '<the PR title>' --body '<the PR body>' # after you fix each rule above" +fi + +# ---- 3. the script tests (job pr-shape) +ran=0 +for t in scripts/test-*.sh; do + [ -f "$t" ] || continue + ran=$((ran + 1)) + if out="$(bash "$t" 2>&1)"; then + ok "script test: $(clean "$t") ($(show "$(printf '%s\n' "$out" | tail -n 1)"))" + else + while IFS= read -r l; do + detail "$l" + done <<EOF +$(printf '%s\n' "$out" | tail -n 15) +EOF + if safe_arg "$t"; then + refuse "script test failed: $t" "bash $t # read the FAIL lines, fix the script or its test, run it again" + else + refuse "a script test failed: $(clean "$t")" "run each scripts/test-*.sh by hand and fix the one that fails" + fi + fi +done +if [ "$ran" -eq 0 ]; then ok "script tests: none in scripts/"; fi + +# ---- the path filter of job changes +if [ "$odd_path" -eq 1 ] || grep -Eq "$self|$product_re" <<<"$files"; then + note "a product path or the workflow changed: CI runs the repo's own build and test jobs for it; run those commands before you push" +fi + +printf 'check: %s failed, %s passed\n' "$fails" "$passed" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/issues-from-rows.sh.tpl b/templates/team-stamp/files/scripts/issues-from-rows.sh.tpl new file mode 100755 index 000000000..98f28c96a --- /dev/null +++ b/templates/team-stamp/files/scripts/issues-from-rows.sh.tpl @@ -0,0 +1,197 @@ +#!/usr/bin/env bash +# issues-from-rows.sh - create one GitHub issue per queued board row that is ready for an agent. +# +# bash scripts/issues-from-rows.sh dry run: print what would be created +# bash scripts/issues-from-rows.sh --dry-run the same, spelled out +# bash scripts/issues-from-rows.sh --apply create the labels and the issues +# bash scripts/issues-from-rows.sh --board-file PATH board file, default {{BOARD_FILE}} +# +# The board is a Markdown table whose rows read `| ID-NNN | item | notes | status |`. A row +# qualifies when its status starts with `queued`, its notes carry a `Done when:` text, and it has +# a #<github-login> tag. A row tagged #{{DECISION_TAG}} waits on a human and is skipped. The issue gets: +# title ID-NNN: <row title> +# body ### Goal (the notes before Done when:), ### Done when, ### Scope +# label ready +# assignee the login from the tag +# The labels ready, one-way-door and blocked must exist: --apply creates any that is missing +# first (the dry run prints that step). A row is skipped when an open or closed issue whose +# title starts with `ID-NNN:` exists, so a rerun creates nothing new. With no board file set it +# prints one line and exits 0. Row text is untrusted: it reaches gh only as an argument, never +# through eval or an unquoted expansion. Needs gh, logged in. bash 3.2 safe. +set -euo pipefail + +BOARD_DEFAULT='{{BOARD_FILE}}' +DECISION_TAG='{{DECISION_TAG}}' + +refuse() { # refuse <rule> <fix>: the two-line refusal on stderr + printf 'issues-from-rows: %s\nFix: %s\n' "$1" "$2" >&2 +} +# Repo text and gh output are attacker-chosen. clean() makes text printable on one line (every +# character outside a small set becomes ?); safe() says a value may sit inside a pasted command. +clean() { local s="${1:0:80}"; printf '%s' "${s//[!A-Za-z0-9._\/@ ,=#()+-]/?}"; } +safe() { [[ "$1" =~ ^[A-Za-z0-9._/@][A-Za-z0-9._/@-]*$ ]]; } +first_line() { clean "$(printf '%s\n' "$1" | head -n 1)"; } + +usage() { + cat <<'EOF2' +Usage: issues-from-rows.sh [--dry-run | --apply] [--board-file PATH] [--help] + +One issue per queued row that has a #<github-login> tag and a Done when: text. +Dry run is the default and creates nothing. +EOF2 +} + +apply=0 +board="$BOARD_DEFAULT" +while [ $# -gt 0 ]; do + case "$1" in + --dry-run) apply=0; shift ;; + --apply) apply=1; shift ;; + --board-file) + [ $# -ge 2 ] || { refuse "--board-file needs a path" "bash scripts/issues-from-rows.sh --help"; exit 2; } + board="$2"; shift 2 ;; + -h | --help) usage; exit 0 ;; + *) refuse "unknown argument: $(clean "$1")" "bash scripts/issues-from-rows.sh --help"; exit 2 ;; + esac +done + +if [ -z "$board" ]; then + echo "issues-from-rows: no board file set; nothing to read" + exit 0 +fi + +command -v gh >/dev/null 2>&1 || { refuse "gh is not installed" "brew install gh # or see https://cli.github.com, then: gh auth login"; exit 1; } +root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" +case "$board" in +/*) board_path="$board" ;; +*) board_path="$root/$board" ;; +esac +[ -f "$board_path" ] || { + if safe "$board_path"; then + fix="mkdir -p \"${board_path%/*}\" && printf '| ID | Item | Notes | Status |\\n|---|---|---|---|\\n' > $board_path" + else + fix="create the board file by hand (its path holds characters this script will not put in a command)" + fi + refuse "board file not found: $(clean "$board")" "$fix" + exit 1 +} + +# Labels first: a missing label would make every issue create fail. +if ! labels="$(gh label list --limit 200 --json name --jq '.[].name' </dev/null 2>&1)"; then + refuse "gh label list failed: $(first_line "$labels")" "gh auth status" + exit 1 +fi +make_label() { # make_label <name> <color> <description> + if printf '%s\n' "$labels" | grep -Fxq -- "$1"; then return 0; fi + if [ "$apply" -eq 0 ]; then + echo "would create label: $1" + return 0 + fi + if out="$(gh label create "$1" --color "$2" --description "$3" </dev/null 2>&1)"; then + echo "created label: $1" + else + refuse "gh label create $1 failed: $(first_line "$out")" "gh auth status" + exit 1 + fi +} +make_label ready 0E8A16 "Goal and Done when are filled; an agent can pick this up" +make_label one-way-door B60205 "Hard to undo; needs a second person before merge" +make_label blocked D93F0B "Waiting on something outside this issue" + +# Titles of every issue, open and closed, one per line. +if ! existing="$(gh issue list --state all --limit 500 --json number,title --jq '.[].title' </dev/null 2>&1)"; then + refuse "gh issue list failed: $(first_line "$existing")" "gh auth status" + exit 1 +fi +if [ -n "$existing" ] && [ "$(printf '%s\n' "$existing" | wc -l)" -ge 500 ]; then + echo "issues-from-rows: note: 500 issues listed, older ones may be missing, so a rerun could duplicate" >&2 +fi + +# One record per candidate, tab separated: +# ROW<TAB>id<TAB>login<TAB>title<TAB>goal<TAB>done_when +# NODONE<TAB>id<TAB>login queued and tagged, but no Done when: text +records="$(DECISION_TAG="$DECISION_TAG" awk -F'|' ' +function trim(s) { gsub(/^[ \t]+|[ \t]+$/, "", s); return s } +function strip_tags(s, n, w, i, out) { + n = split(s, w, /[ \t]+/); out = "" + for (i = 1; i <= n; i++) { + if (w[i] ~ /^#[A-Za-z][A-Za-z0-9_-]*[.,;]?$/) continue + out = out (out == "" ? "" : " ") w[i] + } + return out +} +/^\| ID-[0-9]+ / { + id = trim($2); item = trim($3); notes = trim($4); status = trim($5) + split(status, st, /[ \[]/) + if (st[1] != "queued") next + n = split(notes, w, /[ \t]+/); login = ""; wait = 0 + for (i = 1; i <= n; i++) { + t = w[i] + if (t !~ /^#/) continue + gsub(/[.,;)]+$/, "", t) + if (t == "#" ENVIRON["DECISION_TAG"]) { wait = 1; continue } + if (t ~ /^#(agent|P[0-3]|later|S|M|L|critical)$/) continue + if (login == "" && t ~ /^#[A-Za-z0-9][A-Za-z0-9-]*$/) login = substr(t, 2) + } + if (wait || login == "") next + p = index(notes, "Done when:") + if (p == 0) { print "NODONE\t" id "\t" login; next } + goal = strip_tags(trim(substr(notes, 1, p - 1))) + done = strip_tags(trim(substr(notes, p + 10))) + if (done == "") { print "NODONE\t" id "\t" login; next } + if (goal == "") goal = item + gsub(/\t/, " ", item); gsub(/\t/, " ", goal); gsub(/\t/, " ", done) + print "ROW\t" id "\t" login "\t" item "\t" goal "\t" done +}' "$board_path")" + +nl=' +' +created=0 existed=0 nodone=0 failed=0 +while IFS=$'\t' read -r kind id login title goal check; do + [ -n "$kind" ] || continue + if [ "$kind" = "NODONE" ]; then + nodone=$((nodone + 1)) + echo "skip: $(clean "$id") has a #$(clean "$login") tag but no Done when: text" + continue + fi + case "$nl$existing$nl" in + *"$nl$id:"*) + existed=$((existed + 1)) + echo "skip: $(clean "$id") already has an issue" + continue + ;; + esac + issue_title="$id: $title" + if [ "$apply" -eq 0 ]; then + created=$((created + 1)) + echo "would create: $(clean "$id"): $(clean "$title") (assignee $(clean "$login"), label ready)" + continue + fi + body="### Goal + +$goal + +### Done when + +$check + +### Scope + +Board row $id in $board" + if url="$(gh issue create --title "$issue_title" --body "$body" --label ready --assignee "$login" </dev/null 2>&1)"; then + created=$((created + 1)) + echo "created: $(clean "$id"): $(clean "$title") $(clean "$url")" + else + failed=$((failed + 1)) + refuse "gh issue create failed for $(clean "$id"): $(first_line "$url")" "gh auth status" + fi +done <<EOF2 +$records +EOF2 + +if [ "$apply" -eq 0 ]; then + echo "issues-from-rows: dry run, $created to create, $existed with an issue, $nodone without Done when" +else + echo "issues-from-rows: $created created, $existed with an issue, $nodone without Done when, $failed failed" +fi +[ "$failed" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/negctl.sh b/templates/team-stamp/files/scripts/negctl.sh new file mode 100644 index 000000000..c9b4dddc6 --- /dev/null +++ b/templates/team-stamp/files/scripts/negctl.sh @@ -0,0 +1,290 @@ +#!/usr/bin/env bash +# negctl.sh - the negative control in one command: green, break one thing, red, restore, green. +# +# bash scripts/negctl.sh "<test command>" "<mutate command>" +# bash scripts/negctl.sh --help +# +# Example: +# bash scripts/negctl.sh "bash scripts/test-release-notes.sh" "sed -i.bak 's/dev:/dov:/' scripts/release-notes.sh" +# +# Steps, all run through bash -c in the repo root: +# 1. refuse when a tracked file has uncommitted changes (the restore uses git) +# 2. run the test: it must exit 0 +# 3. run the mutate command: it must change at least one tracked file +# 4. run the test: it must exit non-zero, else the test does not cover the break. +# A red run that is only a load or syntax error is refused: it proves nothing. +# The red counts when its output holds a failed-assertion line (FAIL, not ok, +# N failed, failures: N). Without one, exit 126 or 127 or a shell syntax-error +# message marks a load error. +# 5. restore: git checkout the changed files, remove the untracked files the +# mutation created (proved by comparing the untracked list before and after; +# a file that existed before the mutation is never removed) +# 6. run the test: it must exit 0 again +# A trap restores on any exit, Ctrl-C included. Progress goes to stderr. A refusal +# ends stderr with exactly two lines: the rule, then a "Fix:" line. On success +# stdout holds the proof block: NEGATIVE CONTROL, Command, Output (the last +# 15 lines of the red run), Exit, Verdict. +# +# The test command and the mutate command are the operator's own arguments and run through +# bash -c by design. Nothing else reaches a shell: a file name from the tree is only ever passed +# quoted after "--", and test output is only printed, with control characters removed and +# every line indented (so it cannot pass for a refusal). Text from the tree or from test output +# that is echoed into a rule line has every character outside A-Za-z0-9._/@- , comma and space +# replaced by ?. +# +# The mutation must edit tracked files. A tracked file the mutation adds to git +# cannot be restored by checkout: it is named and left in place. +# +# Exit codes: 0 green, red, green; 1 a step failed or the red was a load error; +# 2 refused before anything ran (dirty tree, not a git work tree); 64 bad usage. +# bash 3.2 safe. +set -euo pipefail + +usage() { + awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0" +} + +# refuse <exit code> <rule> <fix>: restore any break first, so nothing prints after the pair, +# then print two lines on stderr and leave. +armed=0 +refuse() { + [ "$armed" -eq 0 ] || restore + printf 'negctl: %s\nFix: %s\n' "$2" "$3" >&2 + exit "$1" +} + +# clean <text>: every character outside A-Za-z0-9._/@- , comma and space becomes ?. +clean() { printf '%s' "${1:0:80}" | LC_ALL=C tr -c 'A-Za-z0-9._/@ ,-' '?'; } +# plain <file>: the file with control characters (an escape, a carriage return) removed. +plain() { LC_ALL=C sed "s/[$(printf '\001-\010\013-\037\177')]//g" <"$1"; } + +use_fix='bash scripts/negctl.sh "<test command>" "<mutate command>"' + +case "${1-}" in +-h | --help) + usage + exit 0 + ;; +esac +if [ "$#" -ne 2 ] || [ -z "$1" ] || [ -z "$2" ]; then + refuse 64 "need exactly two arguments, a test command and a mutate command" "$use_fix" +fi +test_cmd="$1" +mutate_cmd="$2" + +if ! top="$(git rev-parse --show-toplevel 2>/dev/null)" || ! git rev-parse --verify -q HEAD >/dev/null 2>&1; then + refuse 2 "REFUSED, this is not a git work tree with a commit" 'git init && git add -A && git commit -m "init"' +fi +cd "$top" +if [ -n "$(git status --porcelain --untracked-files=no)" ]; then + refuse 2 "REFUSED, tracked files have uncommitted changes and the restore step uses git" 'git commit -am "wip: before the negative control"' +fi + +work="$(mktemp -d "${TMPDIR:-/tmp}/negctl.XXXXXX")" +out="$work/out" +created="$work/created" +: >"$created" +child="" +mutating=0 +created_known=0 +restore_failed=0 +stuck_said=0 +rc=0 + +tracked_changes() { git -c core.quotepath=off diff HEAD --no-renames --name-only; } +untracked_files() { git -c core.quotepath=off ls-files --others --exclude-standard | LC_ALL=C sort; } +# plain runs to a file first: bash 5.3 was seen to crash on a function inside a pipeline on a loaded host. +show_tail() { plain "$out" >"$work/tail-plain"; tail -n 15 "$work/tail-plain" | sed 's/^/ /' >&2; } + +# The test runs as a background job in its own process group, so a signal to +# negctl can stop the whole test tree before the restore starts. +kill_child() { + [ -n "$child" ] || return 0 + kill -TERM -- "-$child" 2>/dev/null || kill -TERM "$child" 2>/dev/null || true + wait "$child" 2>/dev/null || true + child="" +} + +run_test() { + set -m + ( + trap - INT TERM HUP + exec bash -c "$test_cmd" + ) >"$out" 2>&1 </dev/null & + child=$! + set +m + rc=0 + wait "$child" || rc=$? + child="" +} + +# A red run proves something only when the test ran and failed an assertion. +# Prints why and returns 0 when the red run is a load or syntax error instead. +assert_re='^[[:space:]]*(FAIL|not ok|--- FAIL|AssertionError)|[1-9][0-9]* (failed|failing)|failures: [1-9]|test result: FAILED' +load_re='syntax error|unexpected EOF|unexpected end of file' +red_load_error() { + local code="$1" clean="$work/red-clean" line + sed $'s/\x1b\\[[0-9;]*[A-Za-z]//g' "$out" >"$clean" + if grep -aEq "$assert_re" "$clean"; then + return 1 + fi + case "$code" in + 126 | 127) + echo "exit $code, the test command could not run" + return 0 + ;; + esac + if line="$(grep -aE -m1 "$load_re" "$clean")"; then + printf '%s\n' "$line" | sed 's/^[[:space:]]*//' | cut -c1-100 | LC_ALL=C tr -c 'A-Za-z0-9._/@ \n,-' '?' + return 0 + fi + return 1 +} + +on_signal() { + echo "negctl: interrupted, restoring" >&2 + exit "$1" +} + +# Idempotent: a second call finds nothing left to do. Signals are ignored while +# it runs so a second Ctrl-C cannot leave the break in place. +restore() { + trap '' INT TERM HUP + kill_child + local f + local to_restore=() stuck=() + while IFS= read -r f; do + [ -n "$f" ] || continue + if git cat-file -e "HEAD:$f" 2>/dev/null; then + to_restore+=("$f") + else + stuck+=("$f") + fi + done <<EOF +$(tracked_changes) +EOF + if [ "${#to_restore[@]}" -gt 0 ]; then + git checkout -q HEAD -- "${to_restore[@]}" || { + [ "$stuck_said" -eq 1 ] || echo "negctl: git checkout failed for: $(clean "${to_restore[*]}")" >&2 + stuck_said=1 + restore_failed=1 + } + fi + if [ "${#stuck[@]}" -gt 0 ]; then + [ "$stuck_said" -eq 1 ] || echo "negctl: not in HEAD, left in place: $(clean "${stuck[*]}")" >&2 + stuck_said=1 + restore_failed=1 + fi + if [ "$mutating" -eq 1 ] && [ "$created_known" -eq 0 ]; then + echo "negctl: stopped while the mutation ran; untracked files it may have created were left alone" >&2 + mutating=0 + fi + if [ -s "$created" ]; then + untracked_files >"$work/now" + LC_ALL=C comm -12 "$created" "$work/now" >"$work/remove" + while IFS= read -r f; do + [ -n "$f" ] || continue + rm -f -- "$f" + done <"$work/remove" + : >"$created" + fi + trap 'on_signal 130' INT + trap 'on_signal 143' TERM + trap 'on_signal 129' HUP +} + +cleanup() { + local status=$? + restore + case "$work" in + */negctl.*) rm -rf "$work" ;; + esac + if [ "$status" -eq 0 ] && [ "$restore_failed" -ne 0 ]; then + status=1 + fi + exit "$status" +} + +trap cleanup EXIT +trap 'on_signal 130' INT +trap 'on_signal 143' TERM +trap 'on_signal 129' HUP +armed=1 + +echo "negctl: 1/4 test before the change" >&2 +run_test +if [ "$rc" -ne 0 ]; then + show_tail + refuse 1 "the test is not green before the change, nothing was mutated" "$test_cmd" +fi +if [ -n "$(tracked_changes)" ]; then + refuse 1 "the test changed tracked files by itself, so a mutation cannot be told apart; restored" "git status --short" +fi + +head_before="$(git rev-parse HEAD 2>/dev/null || true)" +untracked_files >"$work/before" +mutating=1 +mutate_rc=0 +(bash -c "$mutate_cmd") >"$work/mutate-out" 2>&1 || mutate_rc=$? +untracked_files >"$work/after" +LC_ALL=C comm -13 "$work/before" "$work/after" >"$created" +created_known=1 +if [ "$mutate_rc" -ne 0 ]; then + plain "$work/mutate-out" >"$work/mutate-plain" + tail -n 15 "$work/mutate-plain" | sed 's/^/ /' >&2 + refuse 1 "the mutate command failed with exit $mutate_rc; restored" "$mutate_cmd" +fi +if [ "$(git rev-parse HEAD 2>/dev/null || true)" != "$head_before" ]; then + moved_fix="git reflog -5" + case "$head_before" in *[!0-9a-f]* | "") ;; *) moved_fix="git reset --soft $head_before" ;; esac + refuse 1 "the mutate command moved HEAD (it committed or switched branch), and a restore cannot undo that" "$moved_fix" +fi +changed="$(tracked_changes)" +if [ -z "$changed" ]; then + refuse 1 "the mutation changed no tracked file; restored" "git ls-files" +fi +changed_line="$(printf '%s\n' "$changed" | LC_ALL=C tr -c 'A-Za-z0-9._/@ \n-' '?' | paste -sd, - | sed 's/,/, /g')" + +echo "negctl: 2/4 test with the break in place (changed: $changed_line)" >&2 +run_test +red_rc="$rc" +if [ "$red_rc" -eq 0 ]; then + show_tail + refuse 1 "the test stayed green with the break in place: the test does not cover it; restored" "$use_fix" +fi +if load_line="$(red_load_error "$red_rc")"; then + show_tail + refuse 1 "REFUSED, the red run is a load or syntax error, not a failing assertion ($load_line); restored" "$use_fix" +fi +if [ -s "$out" ]; then + plain "$out" >"$work/out-plain" + tail -n 15 "$work/out-plain" >"$work/red-tail" +else + echo "<no output>" >"$work/red-tail" +fi + +echo "negctl: 3/4 restore" >&2 +restore +if [ -n "$(tracked_changes)" ] || [ "$restore_failed" -ne 0 ]; then + refuse 1 "the tree is not restored" "git status --short" +fi + +echo "negctl: 4/4 test after the restore" >&2 +run_test +if [ "$rc" -ne 0 ]; then + show_tail + refuse 1 "the test is not green after the restore" "$test_cmd" +fi +restore +if [ "$restore_failed" -ne 0 ]; then + refuse 1 "the tree is not restored" "git status --short" +fi + +echo "NEGATIVE CONTROL: broke $changed_line" +echo "Command: $test_cmd" +echo "Output:" +cat "$work/red-tail" +echo "Exit: $red_rc" +echo "Verdict: RED, as expected" +echo +echo "Broke: $mutate_cmd (changed: $changed_line). Restored with git checkout; the tree is clean. The test was green before (exit 0) and is green again (exit 0)." diff --git a/templates/team-stamp/files/scripts/pr-merge.sh.tpl b/templates/team-stamp/files/scripts/pr-merge.sh.tpl new file mode 100644 index 000000000..729dac2d2 --- /dev/null +++ b/templates/team-stamp/files/scripts/pr-merge.sh.tpl @@ -0,0 +1,477 @@ +#!/usr/bin/env bash +# pr-merge.sh - the merge guard. Squash-merge a PR only when it is safe. +# +# bash scripts/pr-merge.sh <number> check, then merge and delete the branch +# bash scripts/pr-merge.sh --wait <number> wait for pending checks, then check and merge +# bash scripts/pr-merge.sh --dry-run <number> print the verdict, merge nothing +# bash scripts/pr-merge.sh --wait --timeout <seconds> <number> bound the wait (default 900) +# bash scripts/pr-merge.sh --help +# +# This plan cannot make GitHub require checks before a merge, so this script does +# it for the people and agents who follow the rules. It refuses a draft, a +# failing or pending check, a merge conflict, and a PR that changes a door path +# without an approving review from a second person. +# +# What binds the workflow file. GitHub runs a pull request's own copy of the workflow, so a PR can +# edit it. This script therefore requires BOTH checks `changes` and `pr-shape`, each from the +# workflow named CI, on the head it judged, and treats the harness's own files as doors: .github/, +# scripts/, OWNERS.md, docs/TEAM-WORKFLOW.md and .kit.toml at the root; .claude/, .cursor/, +# .vscode/, .mcp.json, AGENTS.md, CLAUDE.md, CLAUDE.local.md and GEMINI.md at any depth. Paths are +# matched in lower case, so `.CLAUDE/x` is a door too. A path (current or previous name) with ANY byte +# outside printable ASCII is a door as well: a case-insensitive disk can fold a non-ASCII spelling +# (U+017F, U+212A, others) onto a guarded name, and no list of code points is complete. A repo's +# --door-paths ADD to that list. The first pull request that introduces the stamp +# touches every door: merge it by hand, after a second person has read it. +# +# Which runs count. The check rollup of a head lists runs of every pull request on that head, so a +# check counts only when its run id is a pull_request run of THIS pull request on the stamped +# workflow file (read from the actions runs API). The pull request's base must be the default +# branch, and a run counts only when it was created after the last base change of the pull request (a +# re-run keeps its creation time and the base it first ran against). The guard also refuses when the +# head commit belongs to any other pull request in any state. GitHub lists on a run every open pull request that shares its head, so a run counts only +# when this pull request is the only one listed: a second pull request on the same head, with a base +# whose checks pass anything, cannot lend its runs. The changed files come from the REST files list, paginated, with each previous name +# (a rename out of a door is a door change); more than 3000 files, or any failed read, refuses. +# +# An approval counts only when all of these hold: it is the reviewer's latest decision, it was made +# on the head commit this script judged (a push after the approval voids it), the reviewer's +# association with the repo is OWNER, MEMBER or COLLABORATOR, the reviewer is not the PR's author and +# not a bot account, it was submitted after the pull request's last base change (a retarget voids +# it), and, when a door approver is set, the login matches. A review field gh does not report means +# the approval does not count. +# +# This script refuses to run when its own text differs from origin/<default branch>:scripts/pr-merge.sh. +# That stops an honest out-of-date copy. It does NOT stop a hostile copy, which can simply omit the check. +# The defence against a hostile copy is that nobody runs a pull request's copy (no Fix line says to) +# and that scripts/ is a door. +# +# Only the newest run of each check name counts, so an old failed run that was +# fixed and rerun does not block. A check name reported by more than one producer +# is refused: a workflow a PR adds could emit a passing check with the same name. +# Zero other checks is green only when the "changes" and "pr-shape" jobs passed: they run on every +# pull request, so passing ones prove CI ran. +# +# --wait polls the PR every 15 seconds until no check is pending, then judges as +# usual. --timeout <seconds> bounds the wait: on timeout it exits 1 and names the +# checks still pending. A draft is refused at once, with no waiting. +# PR_MERGE_POLL_SECS sets the poll interval. Under --wait, mergeability UNKNOWN +# (GitHub has not computed it yet, as right after a push) counts as pending too. +# Without --wait it is refused. +# +# The merge is pinned to the head the script judged (--match-head-commit), so a +# push after the check makes GitHub refuse the merge. +# +# Needs gh and git. Exit 0 merged (or dry-run clean), 1 refused or timed out, 2 bad usage. +# Every refusal prints two lines on stderr: the rule, then a "Fix:" line. +set -euo pipefail +# Byte-wise matching: a path is judged by its bytes, never by a locale. +export LC_ALL=C + +# Doors match any casing; ownership (scripts/check-owners.sh) matches the exact path. +# Door paths (case globs, written in lower case: a path is lowered before it is matched; * crosses a +# slash; an extra pattern from --door-paths is lowered too). BASE_DOORS are the harness's own files and are always +# doors. DOORS holds the paths this repo added with --door-paths; it may be empty. +BASE_DOORS=(".github/*" "scripts/*" ".claude/*" "*/.claude/*" ".mcp.json" "*/.mcp.json" "owners.md" "agents.md" "*/agents.md" "claude.md" "*/claude.md" "claude.local.md" "*/claude.local.md" "gemini.md" "*/gemini.md" ".cursor/*" "*/.cursor/*" ".vscode/*" "*/.vscode/*" "docs/team-workflow.md" ".kit.toml") +DOORS=({{DOOR_ARRAY}}) +# The login that must approve a door change. Empty means any person other than the author. +APPROVER="{{DOOR_APPROVER}}" +# The branch this repo merges into. +DEFAULT_BRANCH="{{DEFAULT_BRANCH}}" +# The workflow whose checks count. +CI_WORKFLOW="CI" +# The stamped workflow file; a run counts only when its path ends with this. +CI_FILE=".github/workflows/ci.yml" +MAX_FILES=3000 + +usage() { + awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0" +} + +# Text from gh (check names, file paths, logins, error lines) is chosen by whoever wrote the PR. +# clean <text>: every character outside A-Za-z0-9._/@- , comma and space becomes ?, a newline +# included, so that text cannot forge a second line or carry an escape sequence. +clean() { printf '%s' "${1:0:80}" | LC_ALL=C tr -c 'A-Za-z0-9._/@ ,-' '?'; } +# is_safe <text>: succeeds only for a non-empty value of A-Za-z0-9._/@- that does not start with -. +# Only such a value is ever put into a "Fix:" command; the PR number is checked to be digits. +is_safe() { + case "$1" in + '' | -* | *[!A-Za-z0-9._/@-]*) return 1 ;; + esac + return 0 +} + +# fail <exit code> <rule> <fix>: the two-line refusal for a usage error. +fail() { + printf 'pr-merge: %s\nFix: %s\n' "$2" "$3" >&2 + exit "$1" +} + +dry=0 +waiting=0 +limit=900 +limit_set=0 +number="" +while [ $# -gt 0 ]; do + case "$1" in + --help | -h) + usage + exit 0 + ;; + --dry-run) dry=1 ;; + --wait) waiting=1 ;; + --timeout) + case "${2:-}" in + '' | *[!0-9]*) fail 2 "--timeout needs a number of seconds" "bash scripts/pr-merge.sh --wait --timeout 900 <number>" ;; + esac + limit="$2" + limit_set=1 + shift + ;; + -*) fail 2 "unknown option $(clean "$1")" "bash scripts/pr-merge.sh --help" ;; + *) + [ -z "$number" ] || fail 2 "one PR number only" "bash scripts/pr-merge.sh --wait <number>" + number="$1" + ;; + esac + shift +done +case "$number" in +'' | *[!0-9]*) fail 2 "give a PR number" "bash scripts/pr-merge.sh --wait <number>" ;; +esac +if [ "$limit_set" -eq 1 ] && [ "$waiting" -eq 0 ]; then + fail 2 "--timeout needs --wait" "bash scripts/pr-merge.sh --wait --timeout $limit $number" +fi + +# One gh call, judged from its JSON (never from a piped `gh pr checks`). +# The rollup lists every run on the head commit, across workflow runs, so each +# check name is judged by its newest entry only. Newest = latest startedAt, then +# completedAt, then the worse class. A queued or in-progress entry with no real +# start time counts as the newest. A CheckRun is pending until COMPLETED, ok on +# SUCCESS, NEUTRAL or SKIPPED, failing otherwise. A status context is ok on SUCCESS, +# pending on PENDING or EXPECTED, failing otherwise. An approval counts when it is +# the reviewer's latest decision (comments do not change it) and the reviewer is +# not the author. `ambiguous=` lists the check names whose entries come from more +# than one producer (workflow name plus kind). Every string that comes back has its +# control characters (a newline, an escape) replaced by ?, so one value is one line. +# shellcheck disable=SC2016 +JQ=' +def ctl: if type == "string" then gsub("[\\x00-\\x1f\\x7f]"; "?") else . end; +def cls: + if .__typename == "StatusContext" then + (if .state == "SUCCESS" then "ok" + elif (.state == "PENDING" or .state == "EXPECTED") then "pending" + else "failing" end) + elif .status != "COMPLETED" then "pending" + elif (.conclusion == "SUCCESS" or .conclusion == "NEUTRAL" or .conclusion == "SKIPPED") then "ok" + else "failing" end; +def nm: ((.name // .context) | ctl); +def rank: if cls == "ok" then 0 elif cls == "pending" then 1 else 2 end; +def started: (.startedAt // .createdAt // ""); +def stamp: + if cls == "pending" and (started == "" or (started | startswith("0001"))) then "9999" + else started end; +def newest: group_by(nm) | map(sort_by([stamp, (.completedAt // ""), rank]) | last); +def producer: ((.workflowName // "") + "|" + (.__typename // "")); +def runid: ([(.detailsUrl // "") | capture("/actions/runs/(?<id>[0-9]+)(/|$)")] | (.[0].id) // null); +def mine: (runid) as $r | ($r == null) or (($r | tonumber) as $n | any(runs[]; . == $n)); +((.statusCheckRollup // []) | map(select(mine))) as $all +| ($all | newest) as $checks +| .author.login as $author +| (.headRefOid // "") as $head +| "draft=\(.isDraft)", + "mergeable=\(.mergeable | tostring | ctl)", + "base=\((.baseRefName // "") | ctl)", + "failing=\([$checks[] | select(cls == "failing") | nm] | join(","))", + "ambiguous=\([$all | group_by(nm)[] | select((map(producer) | unique | length) > 1) | .[0] | nm] | join(","))", + "pending=\([$checks[] | select(cls == "pending") | nm] | join(","))", + "author=\(.author.login | ctl)", + "head=\((.headRefOid // "") | ctl)", + "changes_passed=\([$checks[] | select(.__typename == "CheckRun" and .name == "changes" and .workflowName == wf and (runid != null) and .status == "COMPLETED" and .conclusion == "SUCCESS")] | length)", + "shape_passed=\([$checks[] | select(.__typename == "CheckRun" and .name == "pr-shape" and .workflowName == wf and (runid != null) and .status == "COMPLETED" and .conclusion == "SUCCESS")] | length)", + "approvals=\([(.reviews // []) | map(select(.state == "APPROVED" or .state == "CHANGES_REQUESTED" or .state == "DISMISSED")) | group_by(.author.login)[] | sort_by(.submittedAt) | last | select(.state == "APPROVED" and (.author.login // "") != "" and .author.login != $author and ((.commit.oid // "") != "") and .commit.oid == ($head) and ((.authorAssociation // "") | IN("OWNER", "MEMBER", "COLLABORATOR")) and (.author.login | test("\\[bot\\]$|^app/") | not) and ((.submittedAt // "") > basechg)) | .author.login | ctl] | join(","))", + empty +' + +JQ="def wf: \"$CI_WORKFLOW\"; $JQ" + +draft="" mergeable="" base="" failing="" pending="" ambiguous="" changes_passed=0 shape_passed=0 approvals="" author="" head="" +doors="" nfiles=0 +readfail="" otherprs="" +tab=$'\t' + +lower() { printf '%s' "$1" | tr 'A-Z' 'a-z'; } + +# A path with a byte outside 0x20 to 0x7E is a door, whatever it looks like. A case-insensitive disk can +# fold a non-ASCII spelling (U+017F to s, U+212A to k, and others) onto a guarded path, and no list of +# code points is complete. This byte rule is the layer that does not depend on such a list. +# odd_path <path>: succeeds when the path holds a byte outside 0x20 to 0x7E (the locale is C, so a +# multibyte character counts as bytes). +odd_path() { + case "$1" in + *[![:print:]]*) return 0 ;; + esac + return 1 +} + +# match_doors <path>: succeeds when the path is a door: a byte outside printable ASCII, or the lowered +# path matches a lowered door pattern. oddseen is set when the byte rule fired. +oddseen=0 +match_doors() { + local lp pattern + if odd_path "$1"; then + oddseen=1 + return 0 + fi + lp="$(lower "$1")" + for pattern in "${BASE_DOORS[@]}" ${DOORS[@]+"${DOORS[@]}"}; do + pattern="$(lower "$pattern")" + # shellcheck disable=SC2254 + case "$lp" in + $pattern) return 0 ;; + esac + done + return 1 +} + +# Read the PR and fill the variables above. Every read must succeed and parse, or the load fails and +# the PR is refused: a read that fails is never treated as "nothing found". +load() { + local out line path head1 head2 runs_out run_ids base_changes basechg files_out prefix prs_out + readfail="" + oddseen=0 + otherprs="" + if ! head1="$(gh api "repos/{owner}/{repo}/pulls/$number" --jq '.head.sha' 2>/dev/null)" || ! is_safe "$head1"; then + printf 'pr-merge: gh could not read PR #%s (is gh installed and logged in?)\nFix: gh auth status\n' "$number" >&2 + return 1 + fi + # the last time the base branch of this pull request changed + basechg="" + if ! base_changes="$(gh api --paginate "repos/{owner}/{repo}/issues/$number/timeline?per_page=100" \ + --jq '.[] | select(.event == "base_ref_changed") | .created_at' 2>/dev/null)"; then + readfail="${readfail:-the timeline of this pull request could not be read}" + else + while IFS= read -r line; do + [ -n "$line" ] || continue + case "$line" in + [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z) [ "$line" \> "$basechg" ] && basechg="$line" ;; + *) readfail="${readfail:-the timeline of this pull request could not be parsed}" ;; + esac + done <<EOF +$base_changes +EOF + fi + # the pull_request runs of THIS pull request on the stamped workflow file, for this head, created after + # the last base change (a re-run keeps its creation time and its first base) + if ! runs_out="$(gh api --paginate "repos/{owner}/{repo}/actions/runs?head_sha=$head1&event=pull_request&per_page=100" \ + --jq ".workflow_runs[] | select((.path // \"\") | endswith(\"/$CI_FILE\") or . == \"$CI_FILE\") | select(((.pull_requests // []) | length) == 1 and .pull_requests[0].number == $number) | select((.created_at // \"\") > \"$basechg\") | .id" 2>/dev/null)"; then + readfail="the workflow runs of this pull request could not be read" + fi + run_ids="" + while IFS= read -r line; do + [ -n "$line" ] || continue + case "$line" in *[!0-9]*) readfail="the workflow runs of this pull request could not be parsed"; break ;; esac + run_ids="${run_ids:+$run_ids,}$line" + done <<EOF +$runs_out +EOF + # every pull request this head commit belongs to, in any state: a second one makes the runs of this + # head ambiguous, because a run lists only OPEN pull requests + otherprs="" + if ! prs_out="$(gh api --paginate "repos/{owner}/{repo}/commits/$head1/pulls?per_page=100" --jq '.[] | .number' 2>/dev/null)"; then + readfail="${readfail:-the pull requests of the head commit could not be read}" + else + while IFS= read -r line; do + [ -n "$line" ] || continue + case "$line" in + *[!0-9]*) readfail="${readfail:-the pull requests of the head commit could not be parsed}" ;; + "$number") ;; + *) otherprs="${otherprs:+$otherprs,}$line" ;; + esac + done <<EOF +$prs_out +EOF + fi + # the changed files, with the previous name of a rename: one name per line, controls replaced by ? + if ! files_out="$(gh api --paginate "repos/{owner}/{repo}/pulls/$number/files?per_page=100" \ + --jq '.[] | ("f " + ((.filename // "") | gsub("[\\x00-\\x1f\\x7f]"; "\u00bf"))), (if .previous_filename then "p " + (.previous_filename | gsub("[\\x00-\\x1f\\x7f]"; "\u00bf")) else empty end)' 2>/dev/null)"; then + readfail="${readfail:-the changed files of this pull request could not be read}" + fi + # the head again, after the files read: a head that moved in between makes the file list another head's + if ! head2="$(gh api "repos/{owner}/{repo}/pulls/$number" --jq '.head.sha' 2>/dev/null)" || [ "$head2" != "$head1" ]; then + readfail="${readfail:-the head moved while the changed files were read}" + fi + prefix="def wf: \"$CI_WORKFLOW\"; def runs: [${run_ids}]; def basechg: \"$basechg\"; " + if ! out="$(gh pr view "$number" --json statusCheckRollup,isDraft,mergeable,baseRefName,author,reviews,headRefOid --jq "$prefix$JQ" 2>/dev/null)"; then + printf 'pr-merge: gh could not read PR #%s (is gh installed and logged in?)\nFix: gh auth status\n' "$number" >&2 + return 1 + fi + draft="" mergeable="" base="" failing="" pending="" ambiguous="" changes_passed=0 shape_passed=0 approvals="" author="" head="" + doors="" nfiles=0 + while IFS= read -r line; do + case "$line" in + draft=*) draft="${line#draft=}" ;; + mergeable=*) mergeable="${line#mergeable=}" ;; + base=*) base="${line#base=}" ;; + failing=*) failing="${line#failing=}" ;; + pending=*) pending="${line#pending=}" ;; + ambiguous=*) ambiguous="${line#ambiguous=}" ;; + changes_passed=*) changes_passed="${line#changes_passed=}" ;; + shape_passed=*) shape_passed="${line#shape_passed=}" ;; + approvals=*) approvals="${line#approvals=}" ;; + author=*) author="${line#author=}" ;; + head=*) head="${line#head=}" ;; + esac + done <<EOF +$out +EOF + [ "$head" = "$head1" ] || readfail="${readfail:-the head moved while the pull request was read}" + nfiles=0 + while IFS= read -r path; do + case "$path" in + "f "?*) nfiles=$((nfiles + 1)) ;; + "p "?*) ;; + *) continue ;; + esac + path="${path#[fp] }" + if match_doors "$path"; then doors="${doors:+$doors, }$path"; fi + done <<EOF +$files_out +EOF + # GitHub lists at most 3000 files: a pull request that long cannot be judged + if [ "$nfiles" -ge "$MAX_FILES" ]; then readfail="${readfail:-the pull request has too many files to judge}"; fi + [ "$nfiles" -gt 0 ] || readfail="${readfail:-the changed files of this pull request came back empty}" + return 0 +} + +# Wait on the PR's own rollup, never a filtered run list: those can lag. +# A draft skips the wait and is refused by judge. +wait_for_checks() { + local interval start commas + interval="${PR_MERGE_POLL_SECS:-15}" + start=$SECONDS + # Right after a push the rollup is empty: no check has registered yet. Every PR + # runs the changes job, so no passed changes job and no failure also means wait. + # GitHub also reports mergeable UNKNOWN until it computes it: wait that out too. + while [ "$draft" != "true" ]; do + if [ -z "$pending" ]; then + if { [ "$changes_passed" -eq 0 ] || [ "$shape_passed" -eq 0 ]; } && [ -z "$failing" ]; then + pending="checks not registered yet" + elif [ "$mergeable" = "UNKNOWN" ] && [ -z "$failing" ]; then + pending="mergeability UNKNOWN" + else + break + fi + fi + if [ $((SECONDS - start)) -ge "$limit" ]; then + printf 'pr-merge: timed out after %ss waiting on #%s, still pending: %s (a run with no runner stays queued; scripts/check.sh is the local check)\nFix: gh run list --limit 10\n' "$limit" "$number" "$(clean "$pending")" >&2 + exit 1 + fi + commas="${pending//[^,]/}" + echo "pr-merge: waiting on $((${#commas} + 1)) pending check(s) of #$number ($((SECONDS - start))s of ${limit}s): $(clean "$pending")" >&2 + sleep "$interval" + load || exit 1 + done +} + +# One refusal per line: the rule, a tab, the fix. +refusals="" +refuse() { + refusals="${refusals}${1}${tab}${2} +" +} + +# The one judgment, for the PR that load just read. It fills refusals and merges nothing. +judge() { + local author_lc approver_lc approvals_lc wait_fix reviewer_fix + refusals="" + wait_fix="bash scripts/pr-merge.sh --wait $number" + + [ -z "$readfail" ] || refuse "$readfail, so the pull request cannot be judged" "gh auth status" + [ "$base" = "$DEFAULT_BRANCH" ] || refuse "the base of this pull request is $(clean "$base"), not the default branch $DEFAULT_BRANCH" "gh pr edit $number --base $DEFAULT_BRANCH" + [ -z "$otherprs" ] || refuse "the head commit also belongs to another pull request ($(clean "$otherprs")), so the runs of this head cannot be told from that pull request's" "close the other pull request or push a new commit to this branch, then run $wait_fix" + [ "$draft" != "true" ] || refuse "the PR is a draft" "gh pr ready $number" + [ -z "$failing" ] || refuse "failing check: $(clean "$failing")" "gh pr checks $number" + [ -z "$pending" ] || refuse "pending check: $(clean "$pending")" "$wait_fix" + [ -z "$ambiguous" ] || refuse "check reported by more than one workflow or app (a PR may add a workflow that emits the same name): $(clean "$ambiguous")" "gh pr checks $number" + [ "$changes_passed" -ge 1 ] || refuse "the changes check has not passed from the workflow $CI_WORKFLOW on this head, so CI has not run" "$wait_fix" + [ "$shape_passed" -ge 1 ] || refuse "the pr-shape check has not passed from the workflow $CI_WORKFLOW on this head" "$wait_fix" + case "$mergeable" in + MERGEABLE) ;; + CONFLICTING) + refuse "merge conflicts with the base branch" "on your own branch run: git fetch origin && git merge origin/$DEFAULT_BRANCH, resolve the conflicts, push, then run bash scripts/pr-merge.sh --wait $number from a $DEFAULT_BRANCH checkout" + ;; + *) refuse "mergeability is $(clean "$mergeable"), try again in a minute" "$wait_fix" ;; + esac + + if [ -n "$doors" ]; then + author_lc="$(lower "$author")" + approver_lc="$(lower "$APPROVER")" + approvals_lc="$(lower "$approvals")" + reviewer_fix="ask a person other than the author to approve PR $number, then run $wait_fix" + if [ -n "$APPROVER" ] && [ "$approver_lc" != "$author_lc" ] && is_safe "$APPROVER"; then + reviewer_fix="gh pr edit $number --add-reviewer $APPROVER" + fi + if [ "$oddseen" -eq 1 ]; then + reviewer_fix="ask a second person to approve PR $number (a file name with a byte outside printable ASCII can collide with a guarded path on a case-insensitive disk), then run $wait_fix" + fi + if [ -z "$approvals" ]; then + refuse "touches a door path ($(clean "$doors")) and has no approving review on this head from a second person (owner, member or collaborator, not a bot)" "$reviewer_fix" + elif [ -n "$APPROVER" ] && [ "$approver_lc" != "$author_lc" ]; then + case ",$approvals_lc," in + *",$approver_lc,"*) ;; + *) refuse "touches a door path ($(clean "$doors")): needs an approving review from $(clean "$APPROVER")" "$reviewer_fix" ;; + esac + fi + fi + + if ! is_safe "$head"; then + refuse "gh did not report a usable head commit, so the merge cannot be pinned" "gh pr view $number --json headRefOid" + fi + return 0 +} + +# self_check: this copy must be the default branch's copy. A pull request's own edited copy of this +# script is never the one that judges it. +self_check() { + local self dir ref + self="${BASH_SOURCE[0]}" + dir="$(cd "$(dirname "$self")" && pwd)" + is_safe "$DEFAULT_BRANCH" || fail 1 "the default branch name in this script is not a plain name" "bash scripts/pr-merge.sh --help" + ref="origin/$DEFAULT_BRANCH" + if ! git -C "$dir" fetch -q origin "$DEFAULT_BRANCH" 2>/dev/null; then + echo "pr-merge: note: could not fetch origin $DEFAULT_BRANCH; comparing with the copy fetched last" >&2 + fi + if ! git -C "$dir" cat-file -e "$ref:scripts/pr-merge.sh" 2>/dev/null; then + fail 1 "$ref holds no scripts/pr-merge.sh, so this copy cannot be checked: this is the pull request that introduces the stamp" "merge the first stamp pull request by hand, after a second person has read it" + fi + git -C "$dir" show "$ref:scripts/pr-merge.sh" 2>/dev/null | cmp -s - "$self" || + fail 1 "this copy of scripts/pr-merge.sh differs from $ref, so it may be a pull request's own copy" "git checkout $DEFAULT_BRANCH && git pull, then run it again" +} +self_check + +load || exit 1 +if [ "$waiting" -eq 1 ]; then + wait_for_checks +fi +judge + +if [ -n "$refusals" ]; then + while IFS="$tab" read -r rule fix; do + [ -n "$rule" ] || continue + printf 'pr-merge: refused #%s: %s\nFix: %s\n' "$number" "$rule" "$fix" >&2 + done <<EOF +$refusals +EOF + exit 1 +fi + +if [ "$dry" -eq 1 ]; then + echo "pr-merge: #$number would merge (dry run, nothing merged)" + exit 0 +fi +echo "pr-merge: #$number is clear, merging head $(clean "$head")" +if ! merge_out="$(gh pr merge "$number" --squash --delete-branch --match-head-commit "$head" 2>&1)"; then + printf 'pr-merge: refused #%s: gh did not merge head %s: %s\nFix: %s\n' "$number" "$(clean "$head")" "$(clean "$(printf '%s\n' "$merge_out" | sed -n 1p)")" "bash scripts/pr-merge.sh --wait $number" >&2 + exit 1 +fi +[ -z "$merge_out" ] || printf 'pr-merge: gh said: %s\n' "$(clean "$(printf '%s\n' "$merge_out" | sed -n 1p)")" diff --git a/templates/team-stamp/files/scripts/pr-shape.sh.tpl b/templates/team-stamp/files/scripts/pr-shape.sh.tpl new file mode 100644 index 000000000..9439d1604 --- /dev/null +++ b/templates/team-stamp/files/scripts/pr-shape.sh.tpl @@ -0,0 +1,450 @@ +#!/usr/bin/env bash +# pr-shape.sh - check the shape of one pull request. CI runs it (job pr-shape) and so does +# scripts/check.sh, with the same inputs. +# +# Inputs, all read as data (never evaluated, never used as a format string or a pattern): +# PR_TITLE required. The pull request title. +# PR_BODY the pull request body, CRLF or LF line ends. Default empty. +# PR_BODY_FILE a file that holds the body; used instead of PR_BODY when set. +# BASE_SHA the base revision. Default origin/{{DEFAULT_BRANCH}}. +# HEAD_SHA the head revision. Default HEAD. +# The diff is BASE_SHA...HEAD_SHA (the changes since the merge base). CI passes the four values +# from the pull request event through env: entries, with no token and no gh call; a local run +# passes the same four. Files are read from HEAD_SHA, never from the working tree. +# +# PR_TITLE='feat(x): y' PR_BODY='Closes #12' BASE_SHA=<base> HEAD_SHA=<head> bash scripts/pr-shape.sh +# +# Output: "ok <check>: ..." lines and detail lines on stdout; every failed check prints exactly +# two lines on stderr, "pr-shape: <the rule>" then "Fix: <what to do>". All failed checks print in +# one run. A last stdout line "checks: N failed" ends the run. Exit 0 when none failed, 1 when +# one or more failed, 2 for bad inputs (also a two-line refusal). +# +# Checks: +# 1. title a conventional commit subject on one line, 72 characters or less +# 2. proof a behavior path changed (any changed file that is not documentation), so the PR +# adds or changes a proof file docs/verification/<slug>.md (not a README) with a +# NEGATIVE CONTROL block: an Output: label followed by a non-empty line, an Exit: +# line with a non-zero code, and a line that starts Verdict: RED, in that block. +# Or a body line "no-proof: <reason of 10+ characters>" +# 3. board a behavior path changed, so one of: the body has a line "Closes #<n>" (Fixes and +# Resolves count too; a bare mention like #12 does not); the board file +# ({{BOARD_FILE}}, when one is set) changed; or a body line +# "no-board-row: <reason of 10+ characters>" +# 4. changelog every entry line the PR adds under "## [Unreleased]" in CHANGELOG.md starts with +# a tag ({{TAGS_COLON}}); a change under a product path adds at least one such +# line, or the body has "no-changelog: <reason of 10+ characters>" +# 5. lint severity warning on changed shell files (a .sh file or a shell shebang), by the tool +# named shellcheck; with none on PATH the check is skipped with a notice, and +# it fails when CI=true +# 6. parity AGENTS.md and docs/TEAM-WORKFLOW.md change together, and every AGENTS.md +# heading has a link [Heading](../AGENTS.md#anchor) in docs/TEAM-WORKFLOW.md. +# 7. case no two paths of the head tree differ only in case (the merge guard matches doors in any +# casing; the owners check matches the exact path) +# A body line "no-rule-mirror: <reason of 10+ characters>" waives it +# A reason line starts at the first column of a body line. A reason that is a placeholder in +# angle brackets does not count. +# +# Safety: a title, body, file name, heading or changelog line is attacker-chosen text. A value +# reaches a rule line, a detail line or an ok line only through clean() (every character outside +# letters, digits and ._/@- and space becomes ?), and reaches a Fix line only when safe_arg() +# accepts it; otherwise the Fix line is a plain instruction. bash 3.2 safe. +set -uo pipefail + +TAGS_ERE='{{TAGS_ERE}}' +TAGS_COLON='{{TAGS_COLON}}' +PRODUCT_ERE='{{PRODUCT_ERE}}' +BOARD_FILE='{{BOARD_FILE}}' +DEFAULT_BRANCH='{{DEFAULT_BRANCH}}' + +clean() { printf '%s' "${1:0:80}" | LC_ALL=C tr -c 'A-Za-z0-9._/@ -' '?'; } +safe_re='^[A-Za-z0-9._/@-]+$' +safe_arg() { case "$1" in -* | "") return 1 ;; esac; [[ "$1" =~ $safe_re ]]; } + +fails=0 +passed=0 +ok() { + passed=$((passed + 1)) + printf 'ok %s\n' "$1" +} +detail() { printf ' | %s\n' "$(clean "$1")"; } +# refuse <rule> <fix>: the two-line refusal. Control characters are dropped from both lines. +refuse() { + local rule fix + rule="$(printf '%s' "$1" | LC_ALL=C tr -d '\000-\037\177')" + fix="$(printf '%s' "$2" | LC_ALL=C tr -d '\000-\037\177')" + printf 'pr-shape: %s\nFix: %s\n' "$rule" "$fix" >&2 + fails=$((fails + 1)) +} +die() { + printf 'pr-shape: %s\nFix: %s\n' "$1" "$2" >&2 + exit 2 +} + +work="" +cleanup() { + case "$work" in + */pr-shape.*) rm -rf "$work" ;; + esac +} +trap cleanup EXIT + +# ---- inputs +if [ "${PR_TITLE+set}" != set ]; then + die "PR_TITLE is not set, so there is no title to check" "PR_TITLE='feat(x): y' BASE_SHA='<base>' HEAD_SHA='<head>' bash scripts/pr-shape.sh" +fi +title="$PR_TITLE" +body="${PR_BODY-}" +if [ -n "${PR_BODY_FILE-}" ]; then + [ -r "$PR_BODY_FILE" ] || die "PR_BODY_FILE is set but is not a readable file" "unset PR_BODY_FILE or point it at the body text" + body="$(cat "$PR_BODY_FILE")" +fi +body_clean="$(printf '%s' "$body" | tr -d '\r')" + +resolve() { # resolve <rev>: the commit id, or fail + case "$1" in -* | "") return 1 ;; esac + git rev-parse --verify -q "$1^{commit}" 2>/dev/null +} +base_ref="${BASE_SHA:-origin/$DEFAULT_BRANCH}" +head_ref="${HEAD_SHA:-HEAD}" +base_sha="$(resolve "$base_ref")" || die "the base revision $(clean "$base_ref") does not resolve in this clone" "git fetch origin # then set BASE_SHA to the base commit" +head_sha="$(resolve "$head_ref")" || die "the head revision $(clean "$head_ref") does not resolve in this clone" "git status --short # then set HEAD_SHA to the head commit" + +work="$(mktemp -d "${TMPDIR:-/tmp}/pr-shape.XXXXXX")" || die "cannot make a temp directory" "export TMPDIR=<a writable directory>" +range="$base_sha...$head_sha" +if ! git -c core.quotepath=off diff --name-status -M -z "$range" >"$work/ns" 2>"$work/ns.err"; then + die "git diff $range failed: $(clean "$(head -n 1 "$work/ns.err")")" "git fetch --unshallow # the clone needs the history between base and head" +fi + +# ---- classify the changed paths +# nondoc_paths: stdin paths minus the documentation: a .md, .txt or .markdown file, and under +# docs/ an image, PDF, CSV, rst or adoc file. A path that looks like a secret is never a doc. +nondoc_paths() { + awk '{ lc = tolower($0) } + $0 == "" { next } + lc ~ /(^|\/)[^\/]*credentials?[^\/]*$|(^|\/)secrets?\/|\.(pem|key|p12|pfx)$|(^|\/)\.env/ { print; next } + $0 ~ /\.(md|txt|markdown)$/ { next } + $0 ~ /^docs\// && $0 ~ /\.(rst|adoc|png|jpe?g|gif|webp|svg|pdf|csv)$/ { next } + { print }' +} +is_product() { printf '%s\n' "$1" | grep -Eq "$PRODUCT_ERE"; } + +all_paths="" proof_files="" shell_files="" +product=0 board_changed=0 changelog_changed=0 agents_changed=0 wf_changed=0 odd_path=0 +while IFS= read -r -d '' status; do + p1="" p2="" + IFS= read -r -d '' p1 + case "$status" in R* | C*) IFS= read -r -d '' p2 ;; esac + path="${p2:-$p1}" + case "$p1$p2" in + *$'\n'*) + # A path with a newline cannot ride a line list: count it as product behavior. + odd_path=1 + product=1 + continue + ;; + esac + all_paths="${all_paths}${p1} +${path} +" + if is_product "$p1" || is_product "$path"; then product=1; fi + if [ "$p1" = AGENTS.md ] || [ "$path" = AGENTS.md ]; then agents_changed=1; fi + if [ "$p1" = docs/TEAM-WORKFLOW.md ] || [ "$path" = docs/TEAM-WORKFLOW.md ]; then wf_changed=1; fi + case "$status" in D*) continue ;; esac + case "$path" in + docs/verification/README.md | docs/verification/*/README.md) ;; + docs/verification/*.md) proof_files="${proof_files}${path} +" ;; + CHANGELOG.md) changelog_changed=1 ;; + esac + if [ -n "$BOARD_FILE" ] && [ "$path" = "$BOARD_FILE" ]; then board_changed=1; fi + first="$(git show "$head_sha:$path" 2>/dev/null | head -n 1)" + case "$path" in + *.sh) shell_files="${shell_files}${path} +" ;; + *) + if printf '%s' "$first" | grep -Eq '^#![[:space:]]*([^ ]*/)?(env +)?(ba)?sh([[:space:]]|$)'; then + shell_files="${shell_files}${path} +" + fi + ;; + esac +done <"$work/ns" +behavior=0 +if [ "$odd_path" -eq 1 ] || [ -n "$(printf '%s' "$all_paths" | nondoc_paths)" ]; then behavior=1; fi + +# marker_ok <name>: true when a body line starts "<name>:" and holds a reason of 10+ characters. +# The reason is left in marker_reason. +marker_reason="" +marker_ok() { + local line r + marker_reason="" + while IFS= read -r line; do + case "$line" in + "$1":*) + r="${line#"$1":}" + r="${r#"${r%%[![:space:]]*}"}" + r="${r%"${r##*[![:space:]]}"}" + case "$r" in "<"*">") continue ;; esac + if [ "${#r}" -ge 10 ]; then + marker_reason="$r" + return 0 + fi + ;; + esac + done <<<"$body_clean" + return 1 +} + +# ---- 1. title +title_re='^(feat|fix|refactor|docs|test|chore|ci|build|perf)(\([a-z0-9._/-]+\))?: .+' +title_ok=0 +case "$title" in +*$'\n'* | *$'\r'*) ;; +*) if [[ "$title" =~ $title_re ]] && [ "${#title}" -le 72 ]; then title_ok=1; fi ;; +esac +if [ "$title_ok" -eq 1 ]; then + ok "title: a conventional commit subject" +else + refuse "title is not one line of type(scope): subject with a known type (feat fix refactor docs test chore ci build perf) and 72 characters or less (${#title} now)" \ + "gh pr edit <number> --title 'fix(scripts): short subject'" +fi + +# ---- 2. proof +# proof_missing <path>: what the proof file lacks, one phrase per line; nothing when it is a proof. +proof_missing() { + git show "$head_sha:$1" 2>/dev/null | tr -d '\r' | awk ' + { + line = $0 + if (prevout && st && line ~ /[^[:space:]]/) out = 1 + prevout = (line ~ /^[[:space:]]*Output:/) + if (tolower(line) ~ /negative control/) { seen = 1; if (!st) { st = 1; ex = 0; out = 0 } } + if (st && line ~ /^[[:space:]]*Exit:[[:space:]]*[1-9][0-9]*/) ex = 1 + if (st && line ~ /^[[:space:]]*Verdict:/) { + if (line ~ /^[[:space:]]*Verdict: RED/) { + red = 1 + if (ex && out) good = 1; else { lastex = ex; lastout = out } + st = 0 + } else { ex = 0; out = 0 } + } + } + END { + if (good) exit 0 + if (!seen) print "the words NEGATIVE CONTROL" + else if (!red) print "a line that starts Verdict: RED after the NEGATIVE CONTROL heading" + else { + if (!lastex) print "an Exit: line with a non-zero code inside the NEGATIVE CONTROL block" + if (!lastout) print "an Output: line followed by a non-empty line inside the NEGATIVE CONTROL block" + } + exit 1 + }' +} +negctl_fix='bash scripts/negctl.sh "<test command>" "<command that breaks one thing>" # paste its block into docs/verification/<slug>.md, or put the body line no-proof: <reason, 10+ characters>' +if [ "$behavior" -eq 0 ]; then + ok "proof: no behavior path changed" +elif marker_ok no-proof; then + ok "proof: skipped by the body line no-proof: $(clean "$marker_reason")" +elif [ -z "$proof_files" ]; then + refuse "a behavior path changed and the PR adds or changes no proof file docs/verification/<slug>.md (a README is not one)" "$negctl_fix" +else + proof_good="" + proof_report="" + while IFS= read -r f; do + [ -n "$f" ] || continue + miss="$(proof_missing "$f")" && { + proof_good="$f" + break + } + proof_report="${proof_report}$(clean "$f") lacks $(printf '%s' "$miss" | paste -sd, - | sed 's/,/, /g'). " + done <<EOF +$proof_files +EOF + if [ -n "$proof_good" ]; then + ok "proof: $(clean "$proof_good") holds a NEGATIVE CONTROL block with Verdict: RED" + else + refuse "no proof file in this PR holds a valid NEGATIVE CONTROL block: ${proof_report% }" "$negctl_fix" + fi +fi + +# ---- 3. board link +closes=0 +if grep -Eiq '^(closes|fixes|resolves) #[0-9]+' <<<"$body_clean"; then closes=1; fi +if [ "$behavior" -eq 0 ]; then + ok "board: no behavior path changed" +elif [ "$closes" -eq 1 ]; then + ok "board: the body has a Closes #<n> line" +elif [ "$board_changed" -eq 1 ]; then + ok "board: the board file changed" +elif marker_ok no-board-row; then + ok "board: no-board-row line with a reason" +else + if [ -n "$BOARD_FILE" ]; then + refuse "a behavior path changed and nothing links the PR to its work: no Closes #<n> line in the body, $BOARD_FILE unchanged, no no-board-row: line (a bare mention like #12 is not a close)" \ + "add the body line 'Closes #<n>' for the issue that holds the work, or update the row in $BOARD_FILE, or add the body line 'no-board-row: <reason, 10+ characters>'" + else + refuse "a behavior path changed and nothing links the PR to its work: no Closes #<n> line in the body and no no-board-row: line (a bare mention like #12 is not a close)" \ + "add the body line 'Closes #<n>' for the issue that holds the work, or the body line 'no-board-row: <reason, 10+ characters>'" + fi +fi + +# ---- 4. changelog. Only the lines this PR adds under [Unreleased] are read. +tag_re="^[-*] ($TAGS_ERE):( |\$)" +cl_untagged=0 +cl_tagged=0 +cl_detail="" +if [ "$changelog_changed" -eq 1 ]; then + added_nums="$(git diff -U0 --no-color --no-ext-diff "$range" -- CHANGELOG.md 2>/dev/null | + awk '/^@@ / { s = $3; sub(/^\+/, "", s); n = split(s, p, ","); first = p[1] + 0; cnt = (n > 1 ? p[2] + 0 : 1); for (i = 0; i < cnt; i++) print first + i }' | tr '\n' ',')" + while IFS=$'\t' read -r kind num text; do + case "$kind" in + T) cl_tagged=$((cl_tagged + 1)) ;; + U) + cl_untagged=$((cl_untagged + 1)) + if [ "$cl_untagged" -le 5 ]; then cl_detail="${cl_detail}line $num: $text +"; fi + ;; + esac + done <<EOF +$(git show "$head_sha:CHANGELOG.md" 2>/dev/null | tr -d '\r' | + awk -v nums="$added_nums" -v re="$tag_re" ' + BEGIN { n = split(nums, a, ","); for (i = 1; i <= n; i++) if (a[i] != "") add[a[i]] = 1 } + /^## / { unrel = ($0 ~ /^## \[Unreleased\]/); next } + unrel && (NR in add) && /^[-*] / { + if ($0 ~ re) print "T\t" NR; else print "U\t" NR "\t" substr($0, 1, 80) + }') +EOF +fi +if [ "$cl_untagged" -gt 0 ]; then + refuse "$cl_untagged entry line(s) added under [Unreleased] in CHANGELOG.md do not start with a tag ($TAGS_COLON)" \ + "start each added line under ## [Unreleased] in CHANGELOG.md with one of: $TAGS_COLON" + while IFS= read -r l; do + [ -n "$l" ] && detail "$l" + done <<EOF +$cl_detail +EOF +elif [ "$product" -eq 0 ]; then + ok "changelog: no product path changed" +elif [ "$cl_tagged" -gt 0 ]; then + ok "changelog: the PR adds a tagged line under [Unreleased]" +elif marker_ok no-changelog; then + ok "changelog: no-changelog line with a reason" +else + refuse "a product path ($PRODUCT_ERE) changed and the PR adds no tagged line under [Unreleased] in CHANGELOG.md" \ + "add a line under ## [Unreleased] in CHANGELOG.md that starts with one of: $TAGS_COLON, or add the body line 'no-changelog: <reason, 10+ characters>'" +fi + +# ---- 5. shellcheck on the changed shell files, read from the head revision +if [ -z "$shell_files" ]; then + ok "shellcheck: no shell file changed" +elif ! command -v shellcheck >/dev/null 2>&1; then + if [ "${CI-}" = "true" ]; then + refuse "shellcheck is not installed on this runner and shell files changed" \ + "add the shellcheck install step to the workflow job pr-shape, before the pr-shape step" + else + ok "shellcheck: skipped, shellcheck is not installed here (CI fails this case)" + fi +else + lintdir="$work/lint" + mkdir -p "$lintdir" + count=0 + bad_names="" + bad_count=0 + first_bad="" + while IFS= read -r f; do + [ -n "$f" ] || continue + count=$((count + 1)) + git show "$head_sha:$f" >"$lintdir/f$count.sh" 2>/dev/null + shell_opt=() + if ! head -n 1 "$lintdir/f$count.sh" | grep -q '^#!'; then shell_opt=(-s bash); fi + if ! out="$(cd "$lintdir" && shellcheck -S warning -f gcc ${shell_opt[@]+"${shell_opt[@]}"} -- "f$count.sh" 2>&1)"; then + bad_count=$((bad_count + 1)) + [ -n "$first_bad" ] || first_bad="$f" + if [ "$bad_count" -le 5 ]; then bad_names="${bad_names}$(clean "$f"), "; fi + while IFS= read -r l; do + [ -n "$l" ] || continue + detail "$(clean "$f") $l" + done <<EOF +$(printf '%s\n' "$out" | sed -n 's/^[^:]*:\([0-9][0-9]*\):[0-9][0-9]*: .*\[\(SC[0-9][0-9]*\)\]$/line \1 \2/p' | head -n 6) +EOF + fi + done <<EOF +$shell_files +EOF + if [ "$bad_count" -eq 0 ]; then + ok "shellcheck: $count shell file(s) clean at severity warning" + elif safe_arg "$first_bad"; then + refuse "shellcheck finds warnings in $bad_count changed shell file(s): ${bad_names%, }" \ + "shellcheck -S warning $first_bad # fix each finding, then run it on the other files named above" + else + refuse "shellcheck finds warnings in $bad_count changed shell file(s): ${bad_names%, }" \ + "run shellcheck -S warning on each changed shell file and fix each finding" + fi +fi + +# ---- 6. rule parity +headings() { # headings <rev>: every AGENTS.md heading outside a code fence, one per line + git show "$1:AGENTS.md" 2>/dev/null | tr -d '\r' | + awk '/^```/ { f = !f; next } !f && /^#+ / { sub(/^#+ +/, ""); sub(/ +$/, ""); print }' +} +slug() { printf '%s' "$1" | tr 'A-Z' 'a-z' | LC_ALL=C tr -cd 'a-z0-9 -' | tr ' ' '-'; } +has_both=0 +if git cat-file -e "$head_sha:AGENTS.md" 2>/dev/null && git cat-file -e "$head_sha:docs/TEAM-WORKFLOW.md" 2>/dev/null; then has_both=1; fi +mirror_fix="change both files in this PR, or add the body line 'no-rule-mirror: <reason, 10+ characters>'" +if [ "$agents_changed" -eq 0 ] && [ "$wf_changed" -eq 0 ]; then + ok "parity: neither rule file changed" +elif marker_ok no-rule-mirror; then + ok "parity: skipped by the body line no-rule-mirror" +elif [ "$has_both" -eq 0 ]; then + ok "parity: one of the two rule files is absent, nothing to compare" +elif [ "$agents_changed" -ne "$wf_changed" ]; then + if [ "$agents_changed" -eq 1 ]; then + refuse "AGENTS.md changed and docs/TEAM-WORKFLOW.md did not; the two files stay in step" "$mirror_fix" + else + refuse "docs/TEAM-WORKFLOW.md changed and AGENTS.md did not; the two files stay in step" "$mirror_fix" + fi +else + wf_text="$(git show "$head_sha:docs/TEAM-WORKFLOW.md" 2>/dev/null | tr -d '\r')" + nolink=0 + nolink_slugs="" + while IFS= read -r h; do + [ -n "$h" ] || continue + s="$(slug "$h")" + if ! grep -qF -- "[$h](../AGENTS.md#$s)" <<<"$wf_text"; then + nolink=$((nolink + 1)) + if [ "$nolink" -le 5 ]; then nolink_slugs="${nolink_slugs}${s:-empty}, "; fi + fi + done <<EOF +$(headings "$head_sha") +EOF + if [ "$nolink" -eq 0 ]; then + ok "parity: both rule files changed and every AGENTS.md heading has its link" + else + refuse "$nolink AGENTS.md heading(s) have no link in docs/TEAM-WORKFLOW.md, anchors: ${nolink_slugs%, }" \ + "add a line [Heading text](../AGENTS.md#anchor) to docs/TEAM-WORKFLOW.md for each anchor named above" + fi +fi + +# ---- 7. no two paths that differ only in case. The merge guard matches doors in any casing and the +# owners check matches the exact path; a case-insensitive checkout (macOS, Windows) can write one path +# over the other. The tree is read NUL-delimited. A name that holds a newline cannot ride a line list +# and is refused with the same fix. +tree_list="" tree_odd=0 +while IFS= read -r -d '' tp; do + case "$tp" in + *$'\n'*) + tree_odd=$((tree_odd + 1)) + ;; + *) tree_list="${tree_list}${tp} +" ;; + esac +done < <(git ls-tree -r --name-only -z "$head_sha" 2>/dev/null) +collide="$(printf '%s' "$tree_list" | awk '{ k = tolower($0); if (k in seen) { if (seen[k] != $0 && n++ < 3) printf "%s ", $0 } else seen[k] = $0 }')" +if [ -z "$collide" ] && [ "$tree_odd" -eq 0 ]; then + ok "case: no two paths differ only in case" +else + [ "$tree_odd" -eq 0 ] || collide="${collide}($tree_odd path(s) with a newline in the name) " + refuse "two paths differ only in case, so one can overwrite the other on a case-insensitive checkout: $(clean "${collide% }")" \ + "git mv <one of the paths> <a name that differs in more than case>" +fi + +printf 'checks: %s failed, %s passed\n' "$fails" "$passed" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/release-notes.sh.tpl b/templates/team-stamp/files/scripts/release-notes.sh.tpl new file mode 100755 index 000000000..66fa3c9fc --- /dev/null +++ b/templates/team-stamp/files/scripts/release-notes.sh.tpl @@ -0,0 +1,135 @@ +#!/usr/bin/env bash +# Print the public release notes for one CHANGELOG.md section. +# +# bash scripts/release-notes.sh Unreleased # the section waiting for a release +# bash scripts/release-notes.sh 0.3.0 [changelog] # a version section, optional file path +# +# Every entry starts with a tag from this repo's list ({{TAGS}}), then a colon and a space. +# Public notes keep every tag except `dev:`. A heading left with no entries is dropped. Exit 1 +# when the section is missing, an entry has no tag, or nothing is left for a user to read. Each +# refusal prints two lines on stderr: the rule, then a Fix line. awk, bash and coreutils only. +set -euo pipefail + +TAGS='{{TAGS}}' +TAGS_ERE='{{TAGS_ERE}}' + +# Repo text and arguments are attacker-chosen. clean() makes text printable on one line (every +# character outside a small set becomes ?); safe() says a value may sit inside a pasted command. +clean() { local s="${1:0:80}"; printf '%s' "${s//[!A-Za-z0-9._\/@ ,=#()+-]/?}"; } +safe() { [[ "$1" =~ ^[A-Za-z0-9._/@][A-Za-z0-9._/@-]*$ ]]; } +refuse() { # refuse <rule> <fix>: the two-line refusal on stderr + printf 'release-notes: %s\nFix: %s\n' "$1" "$2" >&2 +} + +usage() { + cat <<'EOF2' +Usage: release-notes.sh <section> [changelog] + +Print the public release notes of one CHANGELOG.md section: every entry except the `dev:` ones. +<section> is Unreleased or a version (0.3.0 or v0.3.0). The changelog defaults to CHANGELOG.md +at the repo root. +EOF2 +} + +case "${1-}" in +-h | --help) usage; exit 0 ;; +"") refuse "no section given" "bash scripts/release-notes.sh Unreleased"; exit 2 ;; +esac +[ "$#" -le 2 ] || { refuse "too many arguments" "bash scripts/release-notes.sh --help"; exit 2; } + +section="$1" +if [[ "$section" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then section="${section#v}"; fi +case "$0" in +*/*) here="${0%/*}" ;; +*) here="." ;; +esac +file="${2:-$here/../CHANGELOG.md}" +if [ ! -f "$file" ]; then + if safe "$file"; then + fix="printf '# Changelog\\n\\n## [Unreleased]\\n' > $file" + else + fix="create the changelog by hand (its path holds characters this script will not put in a command)" + fi + refuse "$(clean "$file") not found" "$fix" + exit 1 +fi + +rc=0 +result="$(SEC="$section" TAGS_ERE="$TAGS_ERE" awk ' +function add(line, c) { + c = substr(line, 1, 1) + if (line ~ /^[-*] /) { nb++; kind[nb] = "entry"; txt[nb] = line; first[nb] = line } + else if ((c == " " || c == "\t") && nb > 0 && kind[nb] == "entry") { txt[nb] = txt[nb] "\n" line } + else if (line ~ /^### /) { nb++; kind[nb] = "head"; txt[nb] = line } + else { nb++; kind[nb] = "text"; txt[nb] = line } +} +function emit(s, a, k, c) { + if (s == "") { c = 1; a[1] = "" } else c = split(s, a, "\n") + for (k = 1; k <= c; k++) { + if (a[k] == "") { if (printed) pending = 1; continue } + if (pending) { print ""; pending = 0 } + print a[k]; printed = 1 + } +} +BEGIN { hdr = "## [" ENVIRON["SEC"] "]"; tre = "^[-*] (" ENVIRON["TAGS_ERE"] "):( |$)" } +{ sub(/\r$/, "") } +!found { if (index($0, hdr) == 1) found = 1; next } +!done { + if ($0 ~ /^## / || $0 ~ /^\[[^]]+\]: /) { done = 1; next } + add($0) +} +END { + if (!found) { print "ERR\tNOSECTION\t"; exit 1 } + for (i = 1; i <= nb; i++) + if (kind[i] == "entry" && first[i] !~ tre) { print "ERR\tUNTAGGED\t" substr(first[i], 1, 100); exit 1 } + m = 0; users = 0 + for (i = 1; i <= nb; i++) { + if (kind[i] == "entry" && first[i] ~ /^[-*] dev:( |$)/) continue + ki[++m] = i + if (kind[i] == "entry") users++ + } + if (users == 0) { print "ERR\tNOUSER\t"; exit 1 } + for (j = 1; j <= m; j++) { + i = ki[j] + if (kind[i] == "head") { + keep = 0 + for (k = j + 1; k <= m; k++) { + ii = ki[k] + if (kind[ii] == "head") break + if (kind[ii] == "entry" || txt[ii] ~ /[^ \t\r\n]/) { keep = 1; break } + } + if (!keep) continue + } + emit(txt[i]) + } +}' "$file")" || rc=$? + +if [ "$rc" -ne 0 ]; then + if safe "$file"; then edit="\${EDITOR:-vi} $file # "; else edit="edit the changelog by hand: "; fi + IFS=$'\t' read -r _ kind detail <<EOF2 +$result +EOF2 + case "$kind" in + NOSECTION) + if safe "$section" && safe "$file"; then + fix="printf '\\n## [%s]\\n' '$section' >> $file" + else + fix="add that section heading to the changelog by hand (a name holds characters this script will not put in a command)" + fi + refuse "no ## [$(clean "$section")] section in $(clean "$file")" "$fix" + ;; + UNTAGGED) + refuse "entry without a tag (${TAGS//,/, }): $(clean "$detail")" "${edit}start the entry with one of: ${TAGS//,/: }:" + ;; + *) + product="" + oldifs="$IFS" + IFS=',' + for t in $TAGS; do [ "$t" = dev ] || product="$product $t:"; done + IFS="$oldifs" + refuse "[$(clean "$section")] has no entry for a user; only dev: lines, or none at all" "${edit}add an entry tagged with one of:${product:- a product tag}" + ;; + esac + exit 1 +fi +printf '%s\n' "$result" diff --git a/templates/team-stamp/files/scripts/team-digest.sh.tpl b/templates/team-stamp/files/scripts/team-digest.sh.tpl new file mode 100644 index 000000000..572f18995 --- /dev/null +++ b/templates/team-stamp/files/scripts/team-digest.sh.tpl @@ -0,0 +1,189 @@ +#!/usr/bin/env bash +# Team digest: what merged, what is open, who works on what, what waits on a +# decision. Reads GitHub through `gh` and the board file. Prints markdown to +# stdout. Posts nothing and writes nothing. +# +# bash scripts/team-digest.sh # last 24 hours +# bash scripts/team-digest.sh --hours 72 # a longer window +# bash scripts/team-digest.sh --board-file PATH +# +# With no `gh` it prints one note and exits 0. With no board file set it prints +# the GitHub sections and one note in place of the board sections. Run it from a +# current checkout so the board file is fresh. bash 3.2 safe. +set -euo pipefail + +board_default="{{BOARD_FILE}}" +decision_tag="{{DECISION_TAG}}" + +usage() { + cat <<'EOF' +Usage: team-digest.sh [--hours N] [--board-file PATH] [--help] + +Prints a markdown digest to stdout: + 1. PRs merged in the last N hours (default 24) + 2. Open PRs with author and age + 3. Open issues with assignee and whether they carry the ready label + 4. Executing rows: board rows whose status starts with executing + 5. Decisions waiting: open board rows tagged with the decision tag and #P0, first 10 + +Needs gh (logged in) and standard tools. Posts nothing. + --hours N window for merged PRs, a whole number + --board-file PATH board file, default the stamped board file (empty: no board part) +EOF +} + +refuse() { # refuse <rule> <fix> + printf 'team-digest: %s\nFix: %s\n' "$1" "$2" >&2 + exit 2 +} + +hours=24 +board="$board_default" +while [ $# -gt 0 ]; do + case "$1" in + --hours) + [ $# -ge 2 ] || refuse "--hours needs a value." "bash scripts/team-digest.sh --hours 72" + hours="$2"; shift 2 ;; + --board-file) + [ $# -ge 2 ] || refuse "--board-file needs a path." "bash scripts/team-digest.sh --board-file docs/BOARD.md" + board="$2"; shift 2 ;; + -h|--help) usage; exit 0 ;; + *) refuse "unknown argument: $1" "bash scripts/team-digest.sh --help" ;; + esac +done + +case "$hours" in + ''|*[!0-9]*) refuse "--hours must be a whole number." "bash scripts/team-digest.sh --hours 24" ;; +esac + +if ! command -v gh >/dev/null 2>&1; then + echo "team-digest: gh is not installed; nothing to read" + exit 0 +fi + +root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" +case "$board" in + "") ;; + /*) ;; + *) board="$root/$board" ;; +esac + +# ISO time N hours ago. The branch is on the OS: BSD date takes -v, GNU date takes -d. +case "$(uname -s 2>/dev/null || echo unknown)" in + Darwin|*BSD) + since="$(date -u -v-"${hours}"H +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -d "${hours} hours ago" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null)" || since="" ;; + *) + since="$(date -u -d "${hours} hours ago" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-"${hours}"H +%Y-%m-%dT%H:%M:%SZ 2>/dev/null)" || since="" ;; +esac +[ -n "$since" ] || refuse "could not compute the window start with this date command." "bash scripts/team-digest.sh --hours 24 (run it where date supports -d or -v)" + +echo "# Team digest" +echo +echo "Window: merged since $since (last ${hours}h)." +echo + +# Titles, logins and board cells are chosen by whoever wrote them: every one goes through cl (jq and awk) +# or clean (shell), which keeps a short set of safe characters, so a title cannot forge a line. +clean() { local s="${1:0:80}"; printf '%s' "${s//[!A-Za-z0-9._\/@ ,=#()+-]/?}"; } +JQ_CL='def cl: (. // "") | tostring | gsub("[^A-Za-z0-9._/@ ,=#()+-]"; "?") | .[0:80]; ' + +echo "## Merged PRs" +echo +if merged="$(gh pr list --state merged --limit 100 --search "merged:>=${since}" \ + --json number,title,author,mergedAt \ + --jq "$JQ_CL"'sort_by(.mergedAt) | reverse | .[] | "- #\(.number | cl) \(.title | cl) (\(.author.login | cl))"' 2>&1)"; then + if [ -n "$merged" ]; then echo "$merged"; else echo "- none"; fi +else + echo "- gh failed: $(clean "$merged")" +fi +echo + +echo "## Open PRs" +echo +# shellcheck disable=SC2016 # $h and $age are jq variables +if open="$(gh pr list --state open --limit 100 \ + --json number,title,author,createdAt,isDraft \ + --jq "$JQ_CL"'.[] | ((now - (.createdAt | fromdateiso8601)) / 3600 | floor) as $h + | (if $h >= 48 then "\($h / 24 | floor)d" else "\($h)h" end) as $age + | "- #\(.number | cl) \(.title | cl) (\(.author.login | cl), \($age) old\(if .isDraft then ", draft" else "" end))"' 2>&1)"; then + if [ -n "$open" ]; then echo "$open"; else echo "- none"; fi +else + echo "- gh failed: $(clean "$open")" +fi +echo + +echo "## Open issues" +echo +# shellcheck disable=SC2016 # $who is a jq variable +if issues="$(gh issue list --state open --limit 100 \ + --json number,title,assignees,labels \ + --jq "$JQ_CL"'.[] | ([.assignees[].login | cl] | join(",")) as $who + | "- #\(.number | cl) \(.title | cl) (\(if $who == "" then "unassigned" else $who end), \(if any(.labels[]; .name == "ready") then "ready" else "not ready" end))"' 2>&1)"; then + if [ -n "$issues" ]; then echo "$issues"; else echo "- none"; fi +else + echo "- gh failed: $(clean "$issues")" +fi +echo + +if [ -z "$board" ]; then + echo "## Board" + echo + echo "- no board file set; nothing to read" + exit 0 +fi +if [ ! -f "$board" ]; then + echo "## Board" + echo + echo "- board file not found: $(clean "$board")" + exit 0 +fi + +# Row shape: | ID-NNN | item | notes and tags | status |. Notes never hold a raw pipe. +awk_common=' +function trim(s) { gsub(/^[ \t]+|[ \t]+$/, "", s); return s } +function cl(s) { gsub(/[^A-Za-z0-9._\/@ ,=#()+-]/, "?", s); return substr(s, 1, 80) } +function has_tag(notes, tag, n, w, i, t) { + n = split(notes, w, /[ \t]+/) + for (i = 1; i <= n; i++) { + t = w[i] + gsub(/[.,;)]+$/, "", t) + if (t == tag) return 1 + } + return 0 +} +function owner_tags(notes, dtag, n, w, i, t, out) { + n = split(notes, w, /[ \t]+/); out = "" + for (i = 1; i <= n; i++) { + t = w[i] + if (t !~ /^#/) continue + gsub(/[.,;)]+$/, "", t) + if (t ~ /^#P[0-3]$/ || t == dtag) continue + out = out " " cl(t) + } + return out +} +' + +echo "## Executing rows" +echo +executing="$(awk -F'|' -v dtag="#$decision_tag" "$awk_common"' + /^\| ID-[0-9]+ / { + status = trim($5) + if (status !~ /^executing/) next + split(status, s, /[ \[]/) + printf "- %s (%s)%s, %s\n", cl(trim($2)), cl(trim($3)), owner_tags($4, dtag), cl(s[1]) + }' "$board")" +if [ -n "$executing" ]; then echo "$executing"; else echo "- none"; fi +echo + +echo "## Decisions waiting" +echo +waiting="$(awk -F'|' -v dtag="#$decision_tag" "$awk_common"' + /^\| ID-[0-9]+ / { + status = trim($5) + if (status ~ /^(shipped|dropped|parked)/) next + if (!has_tag($4, dtag) || !has_tag($4, "#P0")) next + if (++count > 10) next + printf "- %s (%s)\n", cl(trim($2)), cl(trim($3)) + }' "$board")" +if [ -n "$waiting" ]; then echo "$waiting"; else echo "- none"; fi diff --git a/templates/team-stamp/files/scripts/test-agent-guard.sh.tpl b/templates/team-stamp/files/scripts/test-agent-guard.sh.tpl new file mode 100644 index 000000000..51ba42e95 --- /dev/null +++ b/templates/team-stamp/files/scripts/test-agent-guard.sh.tpl @@ -0,0 +1,217 @@ +#!/usr/bin/env bash +# test-agent-guard.sh - feed canned hook JSON to agent-guard.sh and check the +# exit code (2 blocks, 0 allows) and the two-line message of every block. Temp +# git repos stand in for "on the default branch" and "on a feature branch". No +# network. jq builds the JSON here, so the test is skipped when jq is missing. +# Leaves its temp dir behind; the path is printed. +set -euo pipefail +cd "$(dirname "$0")/.." +GUARD="$PWD/scripts/agent-guard.sh" +DEFB="{{DEFAULT_BRANCH}}" +if ! command -v jq >/dev/null 2>&1; then + echo "test-agent-guard: jq is needed to build the test JSON, skipping" + exit 0 +fi +BASH_BIN="$(command -v bash)" +T="$(mktemp -d "${TMPDIR:-/tmp}/agent-guard-test.XXXXXX")" +echo "test dir: $T" + +mkrepo() { # mkrepo <dir> <branch to stand on> + mkdir -p "$1" + git -C "$1" init -q --template= + git -C "$1" symbolic-ref HEAD "refs/heads/$DEFB" + git -C "$1" -c user.name=t -c user.email=t@example.invalid -c commit.gpgsign=false commit -q --allow-empty -m init + git -C "$1" branch feat/x + if [ "$2" != "$DEFB" ]; then git -C "$1" symbolic-ref HEAD "refs/heads/$2"; fi +} +mkrepo "$T/on-default" "$DEFB" +mkrepo "$T/on-feat" feat/x +mkdir -p "$T/not-a-repo" +DEF="$T/on-default" +FEAT="$T/on-feat" +NOREPO="$T/not-a-repo" + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } + +# run_raw <json>: sets rc and writes stderr to $T/err +run_raw() { + rc=0 + printf '%s' "$1" | "$BASH_BIN" "$GUARD" >"$T/out" 2>"$T/err" || rc=$? +} + +hook_json() { # hook_json <cwd> <command> + jq -n --arg c "$2" --arg d "$1" \ + '{hook_event_name:"PreToolUse",tool_name:"Bash",cwd:$d,tool_input:{command:$c}}' +} + +# two_lines: the last run printed exactly the rule line and the Fix line. +two_lines() { + [ "$(wc -l <"$T/err" | tr -d ' ')" = "2" ] && + [ "$(sed -n 1p "$T/err" | cut -c1-13)" = "agent-guard: " ] && + [ "$(sed -n 2p "$T/err" | cut -c1-5)" = "Fix: " ] +} + +# case_run <label> <block|allow> <cwd> <command> [stderr must contain] +case_run() { + local label="$1" want="$2" cwd="$3" command="$4" needle="${5:-}" + run_raw "$(hook_json "$cwd" "$command")" + if [ "$want" = block ]; then + if [ "$rc" -eq 2 ]; then ok "$label: blocked (exit 2)"; else bad "$label: expected exit 2, got $rc"; fi + if two_lines; then ok "$label: two lines, rule then Fix"; else bad "$label: stderr is not rule + Fix"; fi + if [ -n "$needle" ]; then + if grep -Fq -- "$needle" "$T/err"; then ok "$label: message names the fix"; else bad "$label: message lacks '$needle'"; fi + fi + else + if [ "$rc" -eq 0 ]; then ok "$label: allowed (exit 0)"; else bad "$label: expected exit 0, got $rc"; fi + if [ ! -s "$T/err" ]; then ok "$label: silent"; else bad "$label: printed to stderr"; fi + fi +} + +# case_fix <label> <cwd> <command> <the exact Fix line> +case_fix() { + run_raw "$(hook_json "$2" "$3")" + if [ "$rc" -eq 2 ] && two_lines && [ "$(sed -n 2p "$T/err")" = "$4" ]; then + ok "$1: $4" + else + bad "$1: rc $rc, wanted '$4', got '$(sed -n 2p "$T/err")'" + fi +} + +PRFIX='Fix: bash scripts/pr-merge.sh --wait' +PUSH_FIX="gh pr create" +COMMIT_FIX="git switch -c <type>/<slug>" + +# A bare merge, and the PR number in the fix line. +case_fix "gh pr merge 7" "$FEAT" "gh pr merge 7 --squash" "$PRFIX 7" +case_fix "number after the flags" "$FEAT" "gh pr merge --squash --delete-branch 12" "$PRFIX 12" +case_fix "flag with a value first" "$FEAT" "gh pr merge -R owner/repo 8" "$PRFIX 8" +case_fix "PR url" "$FEAT" "gh pr merge https://github.com/owner/repo/pull/31 --squash" "$PRFIX 31" +case_fix "number after cd and &&" "$FEAT" "cd x && gh pr merge 5" "$PRFIX 5" +case_fix "inside bash -c" "$FEAT" "bash -c \"gh pr merge 5\"" "$PRFIX 5" +case_fix "after an env assignment" "$FEAT" "GH_TOKEN=x gh pr merge 5" "$PRFIX 5" +case_fix "a backslash before the command word (\\gh)" "$FEAT" "\\gh pr merge 5" "$PRFIX 5" +case_run "\\git push origin {{DEFAULT_BRANCH}}" block "$FEAT" "\\git push origin {{DEFAULT_BRANCH}}" +case_fix "no number: the current branch's PR" "$FEAT" "gh pr merge --auto" "$PRFIX \"\$(gh pr view --json number --jq .number)\"" +case_fix "a branch word instead of a number" "$FEAT" "gh pr merge feat/y --squash" "$PRFIX \"\$(gh pr view feat/y --json number --jq .number)\"" +case_fix "an odd word is not pasted into the fix" "$FEAT" "gh pr merge 'a;b' " "$PRFIX \"\$(gh pr view --json number --jq .number)\"" +run_raw "$(hook_json "$FEAT" "gh pr merge 7")" +if grep -Fq "<number>" "$T/err"; then bad "fix line carries the text <number>"; else ok "fix line carries no <number> placeholder"; fi + +# Allowed lookalikes. +case_run "pr-merge.sh is the right path" allow "$FEAT" "bash scripts/pr-merge.sh --wait 5" +case_run "pr-merge.sh dry run" allow "$FEAT" "bash scripts/pr-merge.sh --wait --dry-run 5" +case_run "gh pr view" allow "$FEAT" "gh pr view 12 --json state" +case_run "gh pr create" allow "$FEAT" "gh pr create --title x --body y" +case_run "echo mentions gh pr merge" allow "$FEAT" "echo \"gh pr merge\"" +case_run "echo mentions gh pr merge 5" allow "$FEAT" "echo \"merge with gh pr merge 5\"" +case_run "quoted separator does not split" allow "$FEAT" "echo \"first; gh pr merge 5\"" +case_run "a comment body that says pr merge" allow "$FEAT" "gh issue comment 5 --body \"pr merge later\"" +case_run "command -v gh" allow "$FEAT" "command -v gh" +case_run "rg mentions git push" allow "$FEAT" "rg 'git push origin $DEFB' docs" +case_run "git log --grep mentions push" allow "$FEAT" "git log --grep \"git push origin $DEFB\"" + +# Pushes that land on the default branch. +case_run "push origin default" block "$FEAT" "git push origin $DEFB" "$PUSH_FIX" +case_run "push HEAD:default" block "$FEAT" "git push origin HEAD:$DEFB" "$PUSH_FIX" +case_run "force push +default" block "$FEAT" "git push --force origin +$DEFB" "$PUSH_FIX" +case_run "push refs/heads/default" block "$FEAT" "git push origin feat/x:refs/heads/$DEFB" "$PUSH_FIX" +case_run "git -C <dir> push origin default" block "$NOREPO" "git -C $FEAT push origin $DEFB" "$PUSH_FIX" +case_run "bare git push on default" block "$DEF" "git push" "$PUSH_FIX" +case_run "git push origin on default" block "$DEF" "git push origin" "$PUSH_FIX" +case_run "push HEAD while on default" block "$DEF" "git push origin HEAD" "$PUSH_FIX" +case_run "git -C <default repo> push (bare)" block "$NOREPO" "git -C $DEF push" "$PUSH_FIX" +case_run "cd <default repo> && git push" block "$NOREPO" "cd $DEF && git push" "$PUSH_FIX" +case_run "push feature branch" allow "$FEAT" "git push origin feat/x" +case_run "push -u feature branch" allow "$FEAT" "git push -u origin feat/x" +case_run "bare git push on a feature branch" allow "$FEAT" "git push" +case_run "push dry run to default" allow "$FEAT" "git push --dry-run origin $DEFB" +case_run "push default:feature (source is default)" allow "$FEAT" "git push origin $DEFB:feat/y" +case_run "push tags from default" allow "$DEF" "git push --tags" + +# Commits on the default branch. +case_fix "commit on default" "$DEF" "git commit -m x" "Fix: $COMMIT_FIX" +case_run "add and commit with a message file" block "$DEF" "git add a && git commit -F msg.txt" "$COMMIT_FIX" +case_run "git -C <default repo> commit" block "$NOREPO" "git -C $DEF commit -m x" "$COMMIT_FIX" +case_run "commit on a feature branch" allow "$FEAT" "git commit -m \"docs: mention gh pr merge\"" +case_run "commit message from a heredoc that names gh pr merge" allow "$FEAT" "git commit -F - <<EOF +docs: say gh pr merge is blocked +gh pr merge 5 +EOF" +case_run "switch to a new branch, then commit, from default" allow "$DEF" "git switch -c feat/y && git commit -m x" +case_run "checkout -b, then commit, from default" allow "$DEF" "git checkout -b feat/y; git commit -m x" +case_run "checkout an existing branch, then commit, from default" allow "$DEF" "git checkout feat/x && git commit -m x" +case_run "back to default, then commit, from a feature branch" block "$FEAT" "git checkout $DEFB && git commit -m x" "$COMMIT_FIX" +case_run "commit dry run on default" allow "$DEF" "git commit --dry-run" +case_run "commit outside a repo" allow "$NOREPO" "git commit -m x" +case_run "git status on default" allow "$DEF" "git status" +case_run "plain command" allow "$FEAT" "ls -la" + +# Probes that once slipped past a text-matching guard. +case_run "file checkout is not a branch switch" block "$DEF" "git checkout README.md; git commit -m x" "$COMMIT_FIX" +case_run "file checkout with && is not a branch switch" block "$DEF" "git checkout README.md && git commit -m x" "$COMMIT_FIX" +case_run "checkout -- <path> is not a branch switch" block "$DEF" "git checkout -- README.md; git commit -m x" "$COMMIT_FIX" +case_run "restore a file from a branch is not a switch" block "$DEF" "git checkout feat/x -- README.md; git commit -m x" "$COMMIT_FIX" +case_run "env -i git commit" block "$DEF" "env -i git commit -m x" "$COMMIT_FIX" +case_run "env VAR=1 git push origin default" block "$FEAT" "env FOO=1 git push origin $DEFB" "$PUSH_FIX" +case_run "timeout 5 git push origin default" block "$FEAT" "timeout 5 git push origin $DEFB" "$PUSH_FIX" +case_run "timeout -k 2 5 git commit" block "$DEF" "timeout -k 2 5 git commit -m x" "$COMMIT_FIX" +case_run "nice -n 5 git commit" block "$DEF" "nice -n 5 git commit -m x" "$COMMIT_FIX" +case_run "sudo -u someone git commit" block "$DEF" "sudo -u someone git commit -m x" "$COMMIT_FIX" +case_run "git push --all" block "$FEAT" "git push --all origin" "every branch" +case_run "git push --mirror" block "$FEAT" "git push --mirror origin" "every branch" +case_run "git push --all dry run" allow "$FEAT" "git push --all --dry-run" +case_fix "gh api merge with -X PUT" "$FEAT" "gh api repos/o/r/pulls/9/merge -X PUT" "$PRFIX 9" +case_fix "gh api merge with --method PUT" "$FEAT" "gh api --method PUT repos/{owner}/{repo}/pulls/9/merge" "$PRFIX 9" +case_run "gh api graphql mergePullRequest" block "$FEAT" "gh api graphql -f query=mutation{mergePullRequest(input:{pullRequestId:X}){clientMutationId}}" "$PRFIX" +case_run "gh api reads a PR" allow "$FEAT" "gh api repos/o/r/pulls/9" +case_run "gh api reads merge status" allow "$FEAT" "gh api repos/o/r/pulls/9/merge" +case_fix "\$g pr merge" "$FEAT" "g=gh; \$g pr merge 7" "$PRFIX 7" +case_fix "\${g} pr merge with no number" "$FEAT" "\${g} pr merge --squash" "$PRFIX \"\$(gh pr view --json number --jq .number)\"" +case_run "a variable that is not a merge" allow "$FEAT" "\$EDITOR README.md" + +# Bad input never traps a session. +run_raw '{not json' +if [ "$rc" -eq 0 ]; then ok "malformed JSON: allowed (exit 0)"; else bad "malformed JSON: expected exit 0, got $rc"; fi +run_raw '' +if [ "$rc" -eq 0 ]; then ok "empty input: allowed (exit 0)"; else bad "empty input: expected exit 0, got $rc"; fi +run_raw '{"tool_name":"Bash","tool_input":{}}' +if [ "$rc" -eq 0 ]; then ok "no command field: allowed (exit 0)"; else bad "no command field: expected exit 0, got $rc"; fi +run_raw '{"tool_input":{"command":["gh","pr","merge"]}}' +if [ "$rc" -eq 0 ]; then ok "command is not a string: allowed (exit 0)"; else bad "command is not a string: expected exit 0, got $rc"; fi +case_run "cwd is not a directory" allow "$T/missing" "git commit -m x" + +# A PATH with only the tools the guard needs, minus one. +mkbin() { # mkbin <dir> <tool>... + local d="$1" t p + shift + mkdir -p "$d" + for t in "$@"; do + p="$(command -v "$t" 2>/dev/null || true)" + if [ -n "$p" ]; then ln -sf "$p" "$d/$t"; fi + done +} +BLOCK_JSON="$(hook_json "$FEAT" "gh pr merge 5")" +COMMIT_JSON="$(hook_json "$DEF" "git commit -m x")" + +mkbin "$T/bin-nojq" bash cat awk tr git +rc=0 +printf '%s' "$BLOCK_JSON" | PATH="$T/bin-nojq" "$BASH_BIN" "$GUARD" >"$T/out" 2>"$T/err" || rc=$? +if [ "$rc" -eq 0 ] && [ "$(wc -l <"$T/err" | tr -d ' ')" = "1" ] && grep -Fq "jq is not installed" "$T/err"; then ok "no jq: allowed with one note"; else bad "no jq: rc $rc"; fi + +mkbin "$T/bin-noawk" bash cat jq tr git +rc=0 +printf '%s' "$BLOCK_JSON" | PATH="$T/bin-noawk" "$BASH_BIN" "$GUARD" >"$T/out" 2>"$T/err" || rc=$? +if [ "$rc" -eq 0 ] && [ "$(wc -l <"$T/err" | tr -d ' ')" = "1" ] && grep -Fq "awk is not installed" "$T/err"; then ok "no awk: allowed with one note"; else bad "no awk: rc $rc"; fi + +mkbin "$T/bin-nogit" bash cat jq awk tr +rc=0 +printf '%s' "$COMMIT_JSON" | PATH="$T/bin-nogit" "$BASH_BIN" "$GUARD" >"$T/out" 2>"$T/err" || rc=$? +if [ "$rc" -eq 0 ]; then ok "no git: a commit check allows (exit 0)"; else bad "no git: expected exit 0, got $rc"; fi +rc=0 +printf '%s' "$BLOCK_JSON" | PATH="$T/bin-nogit" "$BASH_BIN" "$GUARD" >"$T/out" 2>"$T/err" || rc=$? +if [ "$rc" -eq 2 ] && two_lines; then ok "no git: a bare merge still blocks"; else bad "no git: bare merge rc $rc"; fi + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-agent-lessons.sh b/templates/team-stamp/files/scripts/test-agent-lessons.sh new file mode 100755 index 000000000..1d40c04b9 --- /dev/null +++ b/templates/team-stamp/files/scripts/test-agent-lessons.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# test-agent-lessons.sh - tests for scripts/agent-lessons.sh and for the lesson notes of this repo. +# bash scripts/test-agent-lessons.sh +# Needs only bash and the standard tools. bash 3.2 safe. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +SCRIPT="$ROOT/scripts/agent-lessons.sh" +MEM="$ROOT/.claude/memory" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "PASS $1"; } +no() { FAIL=$((FAIL + 1)); echo "FAIL $1"; } +expect() { local label="$1"; shift; if "$@"; then ok "$label"; else no "$label"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-agent-lessons.XXXXXX")" || exit 1 + +# A scratch repo holds a copy of the script, so the script finds the scratch index. +scratch() { # scratch <name> -> a dir with scripts/agent-lessons.sh and .claude/memory/ + local d="$WORK/$1" + mkdir -p "$d/scripts" "$d/.claude/memory" + cp "$SCRIPT" "$d/scripts/agent-lessons.sh" + echo "$d" +} +chars() { wc -c < "$1" | tr -d ' '; } + +# 1. the index is printed as it is +S="$(scratch small)" +printf '# Repo lessons\n\n- [One](one.md): a lesson.\n' > "$S/.claude/memory/MEMORY.md" +bash "$S/scripts/agent-lessons.sh" > "$WORK/small.out" 2> "$WORK/small.err" +rc=$? +expect "prints a small index unchanged" cmp -s "$S/.claude/memory/MEMORY.md" "$WORK/small.out" +expect "exits 0 with an index" [ "$rc" -eq 0 ] +expect "prints nothing on stderr with an index" [ ! -s "$WORK/small.err" ] + +# 2. a missing index never blocks a session +M="$(scratch missing)" +bash "$M/scripts/agent-lessons.sh" > "$WORK/missing.out" 2> "$WORK/missing.err" +rc=$? +expect "exits 0 when the index is missing" [ "$rc" -eq 0 ] +expect "prints nothing when the index is missing" [ ! -s "$WORK/missing.out" ] +M2="$(scratch nomemdir)" +rmdir "$M2/.claude/memory" +bash "$M2/scripts/agent-lessons.sh" > /dev/null 2>&1 +expect "exits 0 when the memory folder is missing" [ "$?" -eq 0 ] + +# 3. an index over the cap is cut at a whole line with a notice +B="$(scratch big)" +{ + echo "# Repo lessons" + i=0 + while [ "$i" -lt 200 ]; do + i=$((i + 1)) + echo "- [Lesson $i](lesson-$i.md): a line that pads the index well past the cap, number $i, so the cut is measurable." + done +} > "$B/.claude/memory/MEMORY.md" +bigsize="$(chars "$B/.claude/memory/MEMORY.md")" +expect "the fixture index is over 9,000 characters ($bigsize)" [ "$bigsize" -gt 9000 ] +bash "$B/scripts/agent-lessons.sh" > "$WORK/big.out" 2> "$WORK/big.err" +rc=$? +expect "exits 0 with an oversized index" [ "$rc" -eq 0 ] +expect "an oversized index ends with a notice" bash -c "tail -n 1 '$WORK/big.out' | grep -q '^agent-lessons: the index is $bigsize characters'" +bigout="$(chars "$WORK/big.out")" +expect "the output stays under the 10,000 character hook cap ($bigout)" [ "$bigout" -lt 10000 ] +expect "the output keeps the first line" bash -c "[ \"\$(head -n 1 '$WORK/big.out')\" = '# Repo lessons' ]" +expect "the cut is on a whole line" bash -c "grep -v '^agent-lessons: ' '$WORK/big.out' | grep -v '^\$' | tail -n 1 | grep -q '\\.\$'" +expect "the body is cut below 9,000 characters" bash -c "[ \$(grep -v '^agent-lessons: ' '$WORK/big.out' | wc -c | tr -d ' ') -le 9001 ]" + +# 4. an index of exactly 9,000 characters is printed whole +E="$(scratch edge)" +head -c 8999 "$B/.claude/memory/MEMORY.md" > "$E/.claude/memory/MEMORY.md" +printf '\n' >> "$E/.claude/memory/MEMORY.md" +bash "$E/scripts/agent-lessons.sh" > "$WORK/edge.out" 2>&1 +expect "an index of 9,000 characters is printed whole" cmp -s "$E/.claude/memory/MEMORY.md" "$WORK/edge.out" + +# 5. the index and the notes of this repo +if [ -f "$MEM/MEMORY.md" ]; then + expect "the repo index is under 8,000 characters ($(chars "$MEM/MEMORY.md"))" [ "$(chars "$MEM/MEMORY.md")" -lt 8000 ] + bad=0; n=0 + for link in $(grep -o '([A-Za-z0-9._-]*\.md)' "$MEM/MEMORY.md" | tr -d '()'); do + n=$((n + 1)) + [ -f "$MEM/$link" ] || { bad=$((bad + 1)); echo " the index links $link and no such note exists"; } + done + expect "the repo index links at least one note ($n)" [ "$n" -gt 0 ] + expect "every link in the repo index reaches a note" [ "$bad" -eq 0 ] + unlisted=0; badnote=0 + for note in "$MEM"/*.md; do + b="$(basename "$note")" + [ "$b" = "MEMORY.md" ] && continue + grep -qF "($b)" "$MEM/MEMORY.md" || { unlisted=$((unlisted + 1)); echo " $b is not listed in the index"; } + fm="$(awk 'NR==1 && $0=="---" {f=1; next} f && $0=="---" {exit} f {print}' "$note")" + [ "$(head -n 1 "$note")" = "---" ] || { badnote=$((badnote + 1)); echo " $b: line 1 is not ---"; } + printf '%s\n' "$fm" | grep -q '^name: .' || { badnote=$((badnote + 1)); echo " $b: no name in the frontmatter"; } + printf '%s\n' "$fm" | grep -q '^description: .' || { badnote=$((badnote + 1)); echo " $b: no description in the frontmatter"; } + [ "$(chars "$note")" -lt 1200 ] || { badnote=$((badnote + 1)); echo " $b: $(chars "$note") characters, the cap is 1,200"; } + done + expect "every note is listed in the repo index" [ "$unlisted" -eq 0 ] + expect "every note has name and description frontmatter and is under 1,200 characters" [ "$badnote" -eq 0 ] +else + no "the repo has .claude/memory/MEMORY.md" +fi + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-check-owners.sh b/templates/team-stamp/files/scripts/test-check-owners.sh new file mode 100755 index 000000000..d9444fb80 --- /dev/null +++ b/templates/team-stamp/files/scripts/test-check-owners.sh @@ -0,0 +1,282 @@ +#!/usr/bin/env bash +# test-check-owners.sh - run check-owners.sh against throwaway git repos. No network. +# Each case builds a small repo with a copy of the script, an OWNERS.md and some tracked files. +# Leaves its temp dir behind; the path is printed. +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +SCRIPT="$HERE/check-owners.sh" +T="$(mktemp -d "${TMPDIR:-/tmp}/check-owners-test.XXXXXX")" +echo "test dir: $T" + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } +expect() { # expect <label> <condition command...> + local label="$1" + shift + if "$@" >/dev/null 2>&1; then ok "$label"; else bad "$label"; fi +} + +mkrepo() { # mkrepo: a fresh repo with the script tracked; prints its path + local r + r="$(mktemp -d "$T/repo.XXXXXX")" + mkdir -p "$r/scripts" "$r/.github/workflows" + git -C "$r" init -q 2>/dev/null + cp "$SCRIPT" "$r/scripts/check-owners.sh" + printf '%s\n' '#!/usr/bin/env bash' 'echo build' >"$r/scripts/build.sh" + printf '%s\n' 'name: ci' >"$r/.github/workflows/ci.yml" + printf '%s\n' '# a product file, not tracked by the check' >"$r/README.md" + git -C "$r" add -A 2>/dev/null + echo "$r" +} +HEAD_ROWS='# Owners + +## Rule + +- Every script and workflow has one owner. + +## Scripts and workflows + +| Path | What it does | Owner | Sponsor | +|---|---|---|---|' +FULL_ROWS='| `scripts/check-owners.sh` | Owners check | @alice | | +| `scripts/build.sh` | Build | @alice | | +| `.github/workflows/ci.yml` | CI | @alice | |' +write_owners() { # write_owners <repo> [rows...]: header plus the given rows + local r="$1" + shift + { printf '%s\n' "$HEAD_ROWS"; [ "$#" -eq 0 ] || printf '%s\n' "$@"; } >"$r/OWNERS.md" +} +run() { # run <repo> <name>: stdout in $T/<name>, stderr in $T/<name>.err, exit in $rc + rc=0 + (cd "$1" && bash scripts/check-owners.sh) >"$T/$2" 2>"$T/$2.err" || rc=$? +} +has() { grep -Fq -- "$2" "$T/$1"; } +# pairs_ok <name>: stderr is an even number of lines, each odd line starts "check-owners: ", each even "Fix: " +pairs_ok() { + awk 'NR % 2 == 1 && $0 !~ /^check-owners: / { exit 1 } NR % 2 == 0 && $0 !~ /^Fix: / { exit 1 } END { exit (NR == 0 || NR % 2 != 0) }' "$T/$1.err" +} +lines_of() { wc -l <"$T/$1" | tr -d ' '; } + +# 1. a complete table passes +r="$(mkrepo)" +write_owners "$r" "$FULL_ROWS" +run "$r" full +expect "complete table: exit 0" [ "$rc" -eq 0 ] +expect "complete table: reports the count" has full "check-owners: 3 paths, all owned" +expect "complete table: stderr empty" [ ! -s "$T/full.err" ] + +# 1b. lower case decides which tracked files fall under an owned area, so a script in a differently +# cased directory needs a row too (ownership itself matches the exact path, see 1c) +for odd in "SCRIPTS/x.sh" "Scripts/Y.sh" ".GitHub/Workflows/ci2.yml"; do + r="$(mkrepo)" + # written straight into the index, so the case survives a case-insensitive filesystem + blob="$(printf '%s\n' '#!/usr/bin/env bash' | git -C "$r" hash-object -w --stdin)" + git -C "$r" update-index --add --cacheinfo "100644,$blob,$odd" + write_owners "$r" "$FULL_ROWS" + tag="case-$(printf '%s' "$odd" | tr -c 'A-Za-z0-9' '_')" + run "$r" "$tag" + expect "differently cased $odd with no row: exit 1" [ "$rc" -eq 1 ] + expect "differently cased $odd with no row: names it" has "$tag.err" "no owner yet for $odd" +done + +# 1c. ownership is an exact byte match. A row for scripts/deploy.sh does not own scripts/Deploy.sh, and +# two paths that are the same name in lower case are refused. Paths go straight into the index so the +# case and the bytes survive any filesystem. +addpath() { # addpath <repo> <path> + local blob + blob="$(printf '%s\n' '#!/usr/bin/env bash' | git -C "$1" hash-object -w --stdin)" + git -C "$1" update-index --add --cacheinfo "100644,$blob,$2" +} +r="$(mkrepo)" +addpath "$r" "scripts/Deploy.sh" +write_owners "$r" "$FULL_ROWS" "| \`scripts/deploy.sh\` | Deploy | @alice | |" +run "$r" exact +expect "a row for scripts/deploy.sh does not own scripts/Deploy.sh: exit 1" [ "$rc" -eq 1 ] +expect "a row for scripts/deploy.sh does not own scripts/Deploy.sh: names the tracked path" has exact.err "no owner yet for scripts/Deploy.sh" +expect "a row for scripts/deploy.sh does not own scripts/Deploy.sh: names the case clash" has exact.err "same name in lower case" +expect "exact match: rule then Fix" pairs_ok exact +r="$(mkrepo)" +addpath "$r" "scripts/Build.sh" +write_owners "$r" "$FULL_ROWS" +run "$r" clash +expect "two tracked paths equal in lower case: exit 1" [ "$rc" -eq 1 ] +expect "two tracked paths equal in lower case: names the clash" bash -c 'grep -q "same name in lower case" "$1" && grep -q "scripts/Build.sh" "$1" && grep -q "scripts/build.sh" "$1"' _ "$T/clash.err" +r="$(mkrepo)" +addpath "$r" "SCRIPTS/x.sh" +mkdir -p "$r/SCRIPTS" && printf '%s\n' '#!/usr/bin/env bash' >"$r/SCRIPTS/x.sh" +write_owners "$r" "$FULL_ROWS" "| \`SCRIPTS/x.sh\` | Cased exactly | @alice | |" +run "$r" exactrow +expect "SCRIPTS/x.sh with an exact row: exit 0" [ "$rc" -eq 0 ] +r="$(mkrepo)" +addpath "$r" "SCRIPTS/x.sh" +write_owners "$r" "$FULL_ROWS" +run "$r" needsrow +expect "SCRIPTS/x.sh with no row: exit 1" [ "$rc" -eq 1 ] +expect "SCRIPTS/x.sh needs a row: names it" has needsrow.err "no owner yet for SCRIPTS/x.sh" + +# 1d. a tracked name under an owned area with a byte above 0x7F, a control byte or a newline is refused, +# never skipped; a name outside the owned areas is not this check's business +for kind in nonascii newline control; do + case "$kind" in + nonascii) odd="$(printf 'scripts/caf\303\251.sh')" ;; + newline) odd="$(printf 'scripts/a\nb.sh')" ;; + control) odd="$(printf '.github/workflows/c\001d.yml')" ;; + esac + r="$(mkrepo)" + if ! addpath "$r" "$odd" 2>/dev/null; then + echo "NOTE odd name ($kind): git refuses the name, case skipped" + continue + fi + write_owners "$r" "$FULL_ROWS" + run "$r" "odd-$kind" + expect "odd name ($kind) under an owned area: exit 1" [ "$rc" -eq 1 ] + expect "odd name ($kind): the refusal says no row can name it" has "odd-$kind.err" "no row can name them" + expect "odd name ($kind): the Fix line is a plain instruction" grep -q '^Fix: rename each with git mv' "$T/odd-$kind.err" + expect "odd name ($kind): rule then Fix" pairs_ok "odd-$kind" +done +r="$(mkrepo)" +addpath "$r" "docs/caf$(printf '\303\251').md" +write_owners "$r" "$FULL_ROWS" +run "$r" oddelsewhere +expect "a non-ASCII name outside the owned areas: exit 0" [ "$rc" -eq 0 ] + +# 2. a tracked script with no row +r="$(mkrepo)" +printf '%s\n' '#!/usr/bin/env bash' >"$r/scripts/new-thing.sh" +git -C "$r" add -A +write_owners "$r" "$FULL_ROWS" +run "$r" norow +expect "script with no row: exit 1" [ "$rc" -eq 1 ] +expect "script with no row: names it" has norow.err "check-owners: no owner yet for scripts/new-thing.sh" +expect "script with no row: exactly two lines" [ "$(lines_of norow.err)" -eq 2 ] +expect "script with no row: rule then Fix" pairs_ok norow +fixline="$(grep '^Fix: ' "$T/norow.err" | sed 's/^Fix: //')" +(cd "$r" && bash -c "$fixline") +run "$r" norow2 +expect "script with no row: the Fix line, pasted, makes the check pass" [ "$rc" -eq 0 ] + +# 3. a workflow with no row +r="$(mkrepo)" +printf '%s\n' 'name: nightly' >"$r/.github/workflows/nightly.yml" +git -C "$r" add -A +write_owners "$r" "$FULL_ROWS" +run "$r" nowf +expect "workflow with no row: exit 1" [ "$rc" -eq 1 ] +expect "workflow with no row: names it" has nowf.err ".github/workflows/nightly.yml" + +# 4. a repo's own script that predates OWNERS.md refuses too +r="$(mkrepo)" +printf '%s\n' '#!/usr/bin/env bash' >"$r/scripts/legacy-deploy.sh" +git -C "$r" add -A +write_owners "$r" "$FULL_ROWS" +run "$r" legacy +expect "pre-existing script: refused as no owner yet" has legacy.err "no owner yet for scripts/legacy-deploy.sh" + +# 5. a row that points at a missing path +r="$(mkrepo)" +write_owners "$r" "$FULL_ROWS" '| `scripts/gone.sh` | Was removed | @alice | |' +run "$r" dead +expect "dead row: exit 1" [ "$rc" -eq 1 ] +expect "dead row: names the path" has dead.err "row names a path that does not exist: scripts/gone.sh" +expect "dead row: rule then Fix" pairs_ok dead +fixline="$(grep '^Fix: ' "$T/dead.err" | sed 's/^Fix: //')" +(cd "$r" && bash -c "$fixline") +run "$r" dead2 +expect "dead row: the Fix line, pasted, makes the check pass" [ "$rc" -eq 0 ] + +# 6. an empty owner +r="$(mkrepo)" +write_owners "$r" '| `scripts/check-owners.sh` | Owners check | @alice | |' '| `scripts/build.sh` | Build | | |' '| `.github/workflows/ci.yml` | CI | @alice | |' +run "$r" noowner +expect "empty owner: exit 1" [ "$rc" -eq 1 ] +expect "empty owner: names the row" has noowner.err "empty owner: scripts/build.sh" +expect "empty owner: rule then Fix" pairs_ok noowner + +# 7. an agent owner needs a sponsor +r="$(mkrepo)" +write_owners "$r" '| `scripts/check-owners.sh` | Owners check | @alice | |' '| `scripts/build.sh` | Build | build-agent | |' '| `.github/workflows/ci.yml` | CI | @alice | |' +run "$r" nosponsor +expect "agent owner, no sponsor: exit 1" [ "$rc" -eq 1 ] +expect "agent owner, no sponsor: names the owner" has nosponsor.err "agent owner build-agent has no sponsor" +expect "agent owner, no sponsor: rule then Fix" pairs_ok nosponsor +write_owners "$r" '| `scripts/check-owners.sh` | Owners check | @alice | |' '| `scripts/build.sh` | Build | build-agent | @alice |' '| `.github/workflows/ci.yml` | CI | @alice | |' +run "$r" sponsor +expect "agent owner with a sponsor: exit 0" [ "$rc" -eq 0 ] + +# 8. several offenders: one pair each +r="$(mkrepo)" +write_owners "$r" '| `scripts/check-owners.sh` | Owners check | | |' '| `scripts/gone.sh` | Gone | @alice | |' +run "$r" many +expect "several offenders: four lines (build.sh and ci.yml unowned, empty owner, dead row)" [ "$(lines_of many.err)" -eq 8 ] +expect "several offenders: every line pairs" pairs_ok many + +# 9. a job with no file: owner and sponsor are checked, the path is not +r="$(mkrepo)" +write_owners "$r" "$FULL_ROWS" '| nightly-backup | Cron job on the build host | @alice | |' +run "$r" job +expect "job row with an owner: exit 0" [ "$rc" -eq 0 ] +write_owners "$r" "$FULL_ROWS" '| nightly-backup | Cron job on the build host | | |' +run "$r" job2 +expect "job row with no owner: exit 1" [ "$rc" -eq 1 ] +expect "job row with no owner: names the job" has job2.err "empty owner: nightly-backup" + +# 10. rows are read from a second table and from CRLF files +r="$(mkrepo)" +{ printf '%s\n' "$HEAD_ROWS" "$FULL_ROWS" '' '## Jobs' '' '| Name | Where | Owner | Sponsor |' '|---|---|---|---|' '| report | cron | @alice | |'; } | sed 's/$/\r/' >"$r/OWNERS.md" +run "$r" crlf +expect "CRLF file with a second table: exit 0" [ "$rc" -eq 0 ] + +# 11. no OWNERS.md, and not a git repo +r="$(mkrepo)" +run "$r" noowners +expect "no OWNERS.md: exit 1" [ "$rc" -eq 1 ] +expect "no OWNERS.md: says so, rule then Fix" pairs_ok noowners +expect "no OWNERS.md: names the file" has noowners.err "OWNERS.md is missing" +mkdir -p "$T/nogit/scripts" +cp "$SCRIPT" "$T/nogit/scripts/check-owners.sh" +rc=0 +(cd "$T/nogit" && bash scripts/check-owners.sh) >"$T/nogit.out" 2>"$T/nogit.out.err" || rc=$? +expect "not a git repo: exit 1" [ "$rc" -eq 1 ] +expect "not a git repo: rule then Fix" pairs_ok nogit.out + +# 12. an untracked script is not required to have a row +r="$(mkrepo)" +printf '%s\n' '#!/usr/bin/env bash' >"$r/scripts/scratch.sh" +write_owners "$r" "$FULL_ROWS" +run "$r" untracked +expect "untracked file: exit 0" [ "$rc" -eq 0 ] + +# 13. hostile names: nothing from the repo reaches a pasted command, a second Fix line or the terminal +payload="x'" +payload="$payload"'$(touch PWNED)`touch PWNED`;touch PWNED' +no_shell_chars() { ! grep -F -e '$(' -e '`' -e "'" "$T/$1.err"; } +no_pwned() { [ -z "$(find "$1" -name 'PWNED*' -not -path '*/.git/*')" ]; } +r="$(mkrepo)" +esc="$(printf 'scripts/e\033[31mred.sh')" +nlname="$(printf 'scripts/a\nFix: bash -c evil.sh')" +made=0 +if printf '#!/usr/bin/env bash\n' >"$r/scripts/$payload.sh" 2>/dev/null \ + && printf '#!/usr/bin/env bash\n' >"$r/$esc" 2>/dev/null \ + && printf '#!/usr/bin/env bash\n' >"$r/$nlname" 2>/dev/null; then + made=1 +fi +if [ "$made" -eq 0 ]; then + echo "NOTE hostile file names: this filesystem refuses the names, case skipped" +else + git -C "$r" add -A 2>/dev/null + write_owners "$r" "$FULL_ROWS" "| \`scripts/gone$payload\` | Dead row | @alice | |" "| $payload | A job with a hostile name | | |" "| \`scripts/build-$payload\` | Agent row | agent$payload | |" + run "$r" evil + expect "hostile names: exit 1" [ "$rc" -eq 1 ] + expect "hostile names: stderr is only rule and Fix pairs (no faked second Fix line)" pairs_ok evil + expect "hostile names: no command substitution, backtick or quote in the output" no_shell_chars evil + expect "hostile names: no escape byte in the output" bash -c '! grep -q "$(printf "\033")" "$1"' _ "$T/evil.err" + grep '^Fix: ' "$T/evil.err" >"$T/evil.fix" || true + while IFS= read -r l; do + (cd "$r" && EDITOR=true bash -c "${l#Fix: }") >/dev/null 2>&1 || true + done <"$T/evil.fix" + expect "hostile names: running every printed Fix line creates no PWNED file" no_pwned "$r" +fi + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-check.sh.tpl b/templates/team-stamp/files/scripts/test-check.sh.tpl new file mode 100644 index 000000000..9362de340 --- /dev/null +++ b/templates/team-stamp/files/scripts/test-check.sh.tpl @@ -0,0 +1,419 @@ +#!/usr/bin/env bash +# test-check.sh - run check.sh in temp git repos. No network and no token: a fake gh and a PATH with +# no gh at all stand in for it. The owners check and the PR shape check are stubs that log what they +# were given, so a case can say exactly which inputs reached them; when the real pr-shape.sh and +# check-owners.sh sit beside this file, a last group runs check.sh against them. The default branch, +# tags and product paths are the stamped values. Leaves its temp dir behind; the path is printed. +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +CHECK="$HERE/check.sh" +PRSHAPE="$HERE/pr-shape.sh" +OWNERS_SH="$HERE/check-owners.sh" +CIYML="$HERE/../.github/workflows/ci.yml" +BRANCH='{{DEFAULT_BRANCH}}' +TAGS='{{TAGS}}' +PRODUCT_PATHS='{{PRODUCT_PATHS}}' +PRODUCT_ERE='{{PRODUCT_ERE}}' +unset CI PR_TITLE PR_BODY PR_BODY_FILE BASE_SHA HEAD_SHA || true +T="$(mktemp -d "${TMPDIR:-/tmp}/check-test.XXXXXX")" +echo "test dir: $T" + +# P1: the first product tag; PP1: the first product path +P1="" +oldifs="$IFS" +IFS=',' +for t in $TAGS; do + [ "$t" = dev ] && continue + [ -n "$P1" ] || P1="$t" +done +PP1="${PRODUCT_PATHS%%,*}" +IFS="$oldifs" +[ -n "$P1" ] || { echo "test needs one product tag besides dev in: $TAGS"; exit 1; } +[ -n "$PP1" ] || { echo "test needs a product path in: $PRODUCT_PATHS"; exit 1; } + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } +expect() { # expect <label> <condition command...> + local label="$1" + shift + if "$@" >/dev/null 2>&1; then ok "$label"; else bad "$label"; fi +} + +mkbin() { # mkbin <dir> <tool>...: a PATH directory holding only these tools + local d="$1" t p + shift + mkdir -p "$d" + for t in "$@"; do + p="$(command -v "$t" 2>/dev/null || true)" + case "$p" in /*) ln -sf "$p" "$d/$t" ;; esac + done +} +TOOLS="bash git awk sed grep mktemp dirname basename mkdir cat printf tr head tail sort cut wc ls cp mv rm date uname env sh cmp diff find xargs readlink chmod touch tee" +mkbin "$T/bin-nogh" $TOOLS +# A fake gh: pr view answers from FAKE_TITLE and FAKE_BODY, or fails when FAKE_NOPR=1. It logs each call. +mkdir -p "$T/bin-gh" +cat >"$T/bin-gh/gh" <<'EOF' +#!/bin/bash +echo "$*" >>"${STUB_DIR:?}/gh.calls" +[ "${FAKE_NOPR-}" = "1" ] && exit 1 +case "$*" in +*"--json title"*) printf '%s\n' "${FAKE_TITLE-}" ;; +*"--json body"*) printf '%s\n' "${FAKE_BODY-}" ;; +*) exit 1 ;; +esac +EOF +chmod +x "$T/bin-gh/gh" +mkbin "$T/bin-gh" $TOOLS + +R="" +n=0 +g() { git -C "$R" -c user.name=t -c user.email=t@example.invalid -c commit.gpgsign=false -c core.autocrlf=false -c core.hooksPath=/dev/null "$@"; } +put() { # put <path> <content> + mkdir -p "$R/$(dirname "$1")" + printf '%s\n' "$2" >"$R/$1" +} +commit_all() { # commit_all <subject> + g add -A + g commit -q -m "$1" +} +write_stubs() { + cat >"$R/scripts/pr-shape.sh" <<'EOF' +#!/usr/bin/env bash +d="${STUB_DIR:?}" +printf '%s' "${PR_TITLE-unset}" >"$d/title" +printf '%s' "${PR_BODY-unset}" >"$d/body" +printf '%s' "${PR_BODY_FILE-unset}" >"$d/body_file" +printf '%s' "${BASE_SHA-unset}" >"$d/base" +printf '%s' "${HEAD_SHA-unset}" >"$d/head" +echo called >>"$d/prshape.calls" +echo "checks: 0 failed, 1 passed" +if [ "${STUB_PRSHAPE_RC:-0}" -ne 0 ]; then + printf 'pr-shape: stub refusal\nFix: true\n' >&2 +fi +exit "${STUB_PRSHAPE_RC:-0}" +EOF + cat >"$R/scripts/check-owners.sh" <<'EOF' +#!/usr/bin/env bash +echo called >>"${STUB_DIR:?}/owners.calls" +if [ "${STUB_OWNERS_RC:-0}" -ne 0 ]; then + printf 'check-owners: stub refusal\nFix: true\n' >&2 +fi +exit "${STUB_OWNERS_RC:-0}" +EOF +} +# new_repo <stub|real>: a base commit with check.sh and the two scripts it calls, origin/<branch> at +# that commit, then a feature branch +new_repo() { + n=$((n + 1)) + R="$T/repo$n" + mkdir -p "$R/scripts" + git -C "$R" init -q --template= + git -C "$R" symbolic-ref HEAD "refs/heads/$BRANCH" + cp "$CHECK" "$R/scripts/check.sh" + put README.md "readme" + if [ "$1" = real ]; then + cp "$PRSHAPE" "$R/scripts/pr-shape.sh" + cp "$OWNERS_SH" "$R/scripts/check-owners.sh" + put OWNERS.md "# Owners + +| Path | What it does | Owner | Sponsor | +|---|---|---|---| +| \`scripts/check.sh\` | local check | @t | | +| \`scripts/pr-shape.sh\` | PR shape | @t | | +| \`scripts/check-owners.sh\` | owners | @t | |" + put CHANGELOG.md "# Changelog + +## [Unreleased] + +- $P1: an existing tagged line" + else + write_stubs + fi + commit_all base + g update-ref "refs/remotes/origin/$BRANCH" "$(g rev-parse HEAD)" + g checkout -q -b feat/x +} +# run_check <name> <PATH dir> [VAR=value ...] [-- args]: stdout in $T/<name>.out, stderr in $T/<name>.err, +# exit in $rc, the stubs' logs in $T/stub-<name>/ +run_check() { + local name="$1" bindir="$2" + shift 2 + local vars=() + while [ $# -gt 0 ] && [ "$1" != "--" ]; do + vars+=("$1") + shift + done + [ $# -eq 0 ] || shift + mkdir -p "$T/stub-$name" + rc=0 + (cd "$R" && env STUB_DIR="$T/stub-$name" ${vars[@]+"${vars[@]}"} PATH="$bindir" bash scripts/check.sh "$@") \ + >"$T/$name.out" 2>"$T/$name.err" || rc=$? +} +has() { grep -Fq -- "$2" "$T/$1.out" "$T/$1.err"; } +lacks() { ! grep -Fq -- "$2" "$T/$1.out" "$T/$1.err"; } +rc_is() { [ "$rc" -eq "$1" ]; } +file_is() { # file_is <name> <stub file> <expected>: the stub saw exactly this value + printf '%s' "$3" >"$T/expected" + cmp -s "$T/expected" "$T/stub-$1/$2" +} +called() { [ -f "$T/stub-$1/$2.calls" ]; } +not_called() { [ ! -f "$T/stub-$1/$2.calls" ]; } +# pairs_ok <name>: stderr is whole pairs, a rule line "<tool>: " then a line "Fix: " +pairs_ok() { + awk 'NR % 2 == 1 && $0 !~ /^[A-Za-z-]+: / { bad = 1 } NR % 2 == 0 && $0 !~ /^Fix: / { bad = 1 } END { exit (bad || NR == 0 || NR % 2 == 1) }' "$T/$1.err" +} +# run_fixes <name>: run every Fix: line through bash -c in the fixture +run_fixes() { + local l + while IFS= read -r l; do + [ -n "$l" ] || continue + (cd "$R" && bash -c "${l#Fix: }" </dev/null) >/dev/null 2>&1 || true + done <<EOF +$(grep '^Fix: ' "$T/$1.err" || true) +EOF +} +no_payload() { ! grep -Eq '\$\(touch|^Fix: rm -rf' "$T/$1.out" "$T/$1.err"; } +no_pwned() { [ -z "$(find "$R" "$T" -name 'PWNED*' 2>/dev/null)" ]; } +sq="'" + +# 1. a docs-only branch, nothing passed, no gh at all: the title is the first commit subject +new_repo stub +put docs/a.md "plain doc" +commit_all "docs: add a page" +BASE0="$(g rev-parse "origin/$BRANCH")" +HEAD0="$(g rev-parse HEAD)" +run_check c1 "$T/bin-nogh" +expect "docs-only, gh absent: exit 0" rc_is 0 +expect "docs-only: the owners check ran" called c1 owners +expect "docs-only: pr-shape ran" called c1 prshape +expect "docs-only: the title is the first commit subject" file_is c1 title "docs: add a page" +expect "docs-only: the body is empty" file_is c1 body "" +expect "docs-only: BASE_SHA is the merge base with origin/$BRANCH" file_is c1 base "$BASE0" +expect "docs-only: HEAD_SHA is HEAD" file_is c1 head "$HEAD0" +expect "docs-only: PR_BODY_FILE is cleared for pr-shape" file_is c1 body_file "" +expect "docs-only: says where the title came from" has c1 "PR title comes from the first commit subject on this branch" +expect "docs-only: ends with 0 failed" has c1 "check: 0 failed" +expect "docs-only: nothing on stderr" test ! -s "$T/c1.err" +expect "docs-only: no path filter note" lacks c1 "a product path or the workflow changed" + +# 2. arguments beat the environment +run_check c2 "$T/bin-nogh" "PR_TITLE=fix: from env" "PR_BODY=env body" -- --title "feat(x): from args" --body "Closes #12" +expect "arguments: exit 0" rc_is 0 +expect "arguments: the title reached pr-shape" file_is c2 title "feat(x): from args" +expect "arguments: the body reached pr-shape" file_is c2 body "Closes #12" +expect "arguments: says so" has c2 "PR title comes from the --title argument; the body comes from the --body argument" +# 3. the environment alone +run_check c3 "$T/bin-nogh" "PR_TITLE=fix: from env" "PR_BODY=Closes #4" +expect "environment: the title reached pr-shape" file_is c3 title "fix: from env" +expect "environment: the body reached pr-shape" file_is c3 body "Closes #4" +expect "environment: says so" has c3 "PR title comes from PR_TITLE; the body comes from PR_BODY" +# 3b. BASE_SHA and HEAD_SHA from the environment are passed through +run_check c3b "$T/bin-nogh" "BASE_SHA=$BASE0" "HEAD_SHA=$HEAD0" +expect "BASE_SHA and HEAD_SHA from the environment: exit 0" rc_is 0 +expect "BASE_SHA from the environment reached pr-shape" file_is c3b base "$BASE0" + +# 4. the body from a file +printf 'Closes #3\r\nmore\n' >"$T/body.txt" +run_check c4 "$T/bin-nogh" -- --title "feat(x): y" --body-file "$T/body.txt" +expect "--body-file: exit 0" rc_is 0 +expect "--body-file: the text reached pr-shape" file_is c4 body "$(printf 'Closes #3\r\nmore')" +run_check c4b "$T/bin-nogh" "PR_BODY_FILE=$T/body.txt" -- --title "feat(x): y" +expect "PR_BODY_FILE: the text reached pr-shape" file_is c4b body "$(printf 'Closes #3\r\nmore')" +run_check c4c "$T/bin-nogh" -- --title "feat(x): y" --body-file "$T/no-such-file" +expect "an unreadable body file: exit 2" rc_is 2 +expect "an unreadable body file: a two-line refusal" pairs_ok c4c +expect "an unreadable body file: pr-shape never ran" not_called c4c prshape +run_check c4d "$T/bin-nogh" -- --body "x" --body-file "$T/body.txt" +expect "--body with --body-file: exit 2" rc_is 2 +expect "--body with --body-file: a two-line refusal" pairs_ok c4d + +# 5. gh: used only when nothing was passed +run_check c5 "$T/bin-gh" "FAKE_TITLE=fix(x): from the open PR" "FAKE_BODY=Closes #7" +expect "open PR: exit 0" rc_is 0 +expect "open PR: the title came from gh" file_is c5 title "fix(x): from the open PR" +expect "open PR: the body came from gh" file_is c5 body "Closes #7" +expect "open PR: says so" has c5 "the open PR (gh pr view)" +run_check c5b "$T/bin-gh" FAKE_NOPR=1 +expect "gh without a PR: falls back to the first commit subject" file_is c5b title "docs: add a page" +run_check c5c "$T/bin-gh" "FAKE_TITLE=fix(x): from the open PR" -- --title "feat(x): passed" +expect "a title was passed: gh is never called" not_called c5c gh +expect "a title was passed: the passed title wins" file_is c5c title "feat(x): passed" +run_check c5d "$T/bin-gh" "FAKE_TITLE=fix(x): from the open PR" "PR_BODY=Closes #1" +expect "a body was passed: gh is never called" not_called c5d gh + +# 6. a failed step fails the check and names itself in a two-line refusal +run_check c6 "$T/bin-nogh" STUB_PRSHAPE_RC=1 +expect "pr-shape fails: exit 1" rc_is 1 +expect "pr-shape fails: only whole pairs on stderr" pairs_ok c6 +expect "pr-shape fails: the step is named" has c6 "check: pr-shape: a check failed" +expect "pr-shape fails: the count is 1" has c6 "check: 1 failed, 2 passed" +run_check c6b "$T/bin-nogh" STUB_OWNERS_RC=1 +expect "owners fails: exit 1" rc_is 1 +expect "owners fails: only whole pairs on stderr" pairs_ok c6b +expect "owners fails: the step is named" has c6b "check: owners: a script or workflow has no row" +expect "owners fails: pr-shape still ran" called c6b prshape +run_check c6c "$T/bin-nogh" STUB_OWNERS_RC=1 STUB_PRSHAPE_RC=1 +expect "both fail: the count is 2" has c6c "check: 2 failed, 1 passed" + +# 7. the script tests: a green one is listed, a red one fails the check +printf '#!/usr/bin/env bash\necho "PASS one"\necho "failures: 0"\n' >"$R/scripts/test-fine.sh" +commit_all "test: add a fine test" +run_check c7 "$T/bin-nogh" +expect "a green script test: exit 0" rc_is 0 +expect "a green script test: listed with its last line" has c7 "script test: scripts/test-fine.sh (failures: 0)" +printf '#!/usr/bin/env bash\necho "FAIL one"\necho "failures: 1"\nexit 1\n' >"$R/scripts/test-broken.sh" +commit_all "test: add a broken test" +run_check c7b "$T/bin-nogh" +expect "a red script test: exit 1" rc_is 1 +expect "a red script test: its last lines are shown" has c7b " | failures: 1" +expect "a red script test: the rule names it" has c7b "check: script test failed: scripts/test-broken.sh" +expect "a red script test: the Fix runs it" has c7b "Fix: bash scripts/test-broken.sh" +expect "a red script test: only whole pairs on stderr" pairs_ok c7b +expect "a red script test: the green one still ran" has c7b "script test: scripts/test-fine.sh" + +# 8. attacker-chosen text: no raw payload in the output, no forged Fix line, no PWNED file +new_repo stub +hostile="scripts/test-a${sq}\$(touch PWNED).sh" +if printf '#!/usr/bin/env bash\necho "FAIL one"\necho "Fix: rm -rf x"\nexit 1\n' >"$R/$hostile" 2>/dev/null && [ -f "$R/$hostile" ]; then + commit_all "test: add a test with a hostile name" + run_check c8 "$T/bin-nogh" + run_fixes c8 + expect "a test named with a quote and a command: exit 1" rc_is 1 + expect "the test name payload: not in the output" no_payload c8 + expect "the test name payload: only whole pairs on stderr" pairs_ok c8 + expect "the test name payload: the name is shown filtered" has c8 "scripts/test-a???touch PWNED?.sh" + expect "the test name payload: the Fix is a plain instruction" has c8 "Fix: run each scripts/test-*.sh by hand" + expect "the test name payload: running every Fix line creates no PWNED" no_pwned +else + echo "skipped: the test name case (the filesystem refused the name)" +fi +new_repo stub +put docs/a.md "plain doc" +commit_all "docs: add a page" +inj_title="$(printf 'feat: x $(touch PWNED)\nFix: rm -rf x')" +inj_body="$(printf 'Closes #1\nFix: rm -rf x\n$(touch PWNED)')" +run_check c8b "$T/bin-nogh" -- --title "$inj_title" --body "$inj_body" +run_fixes c8b +expect "a title and body with a command and a forged Fix line: exit 0 (a stub judges them)" rc_is 0 +expect "the title payload reached pr-shape untouched" file_is c8b title "$inj_title" +expect "the title payload: not in the output" no_payload c8b +expect "the title payload: running every Fix line creates no PWNED" no_pwned +run_check c8c "$T/bin-nogh" STUB_PRSHAPE_RC=1 "PR_TITLE=$inj_title" +run_fixes c8c +expect "a failing pr-shape with a payload title: exit 1" rc_is 1 +expect "a failing pr-shape with a payload title: not in the output" no_payload c8c +expect "a failing pr-shape with a payload title: running every Fix line creates no PWNED" no_pwned +inj_base="$(printf 'x $(touch PWNED)\nFix: rm -rf x')" +run_check c8d "$T/bin-nogh" "BASE_SHA=$inj_base" +run_fixes c8d +expect "a BASE_SHA holding a command: exit 2" rc_is 2 +expect "a BASE_SHA holding a command: only whole pairs on stderr" pairs_ok c8d +expect "a BASE_SHA holding a command: not in the output" no_payload c8d +expect "a BASE_SHA holding a command: running every Fix line creates no PWNED" no_pwned +run_check c8e "$T/bin-nogh" "HEAD_SHA=$inj_base" +run_fixes c8e +expect "a HEAD_SHA holding a command: exit 2" rc_is 2 +expect "a HEAD_SHA holding a command: not in the output" no_payload c8e +expect "a HEAD_SHA holding a command: running every Fix line creates no PWNED" no_pwned +run_check c8f "$T/bin-nogh" -- $'--bogus\nFix: rm -rf x' +run_fixes c8f +expect "an unknown option holding a forged Fix line: exit 2" rc_is 2 +expect "an unknown option holding a forged Fix line: not in the output" no_payload c8f +expect "an unknown option holding a forged Fix line: only whole pairs on stderr" pairs_ok c8f +run_check c8g "$T/bin-nogh" -- --body-file "$T/x\$(touch PWNED)" +run_fixes c8g +expect "a body file name holding a command: exit 2" rc_is 2 +expect "a body file name holding a command: not in the output" no_payload c8g +expect "a body file name holding a command: running every Fix line creates no PWNED" no_pwned + +# 9. usage and refusals +new_repo stub +g update-ref -d "refs/remotes/origin/$BRANCH" +run_check c9 "$T/bin-nogh" +expect "no origin/$BRANCH: exit 2" rc_is 2 +expect "no origin/$BRANCH: names the fix" has c9 "Fix: git fetch origin $BRANCH" +expect "no origin/$BRANCH: a two-line refusal" pairs_ok c9 +run_check c9b "$T/bin-nogh" -- --nope +expect "an unknown option: exit 2" rc_is 2 +expect "an unknown option: names --help" has c9b "Fix: bash scripts/check.sh --help" +run_check c9c "$T/bin-nogh" -- --title +expect "--title with no value: exit 2" rc_is 2 +expect "--title with no value: a two-line refusal" pairs_ok c9c +run_check c9d "$T/bin-nogh" -- --help +expect "--help: exit 0" rc_is 0 +expect "--help: prints the twin set" has c9d "twin: pr-shape.sh env PR_TITLE PR_BODY BASE_SHA HEAD_SHA" +expect "--help: says where the PR text comes from" has c9d "gh pr view" +new_repo stub +run_check c9e "$T/bin-nogh" +expect "no commit on the branch yet: exit 0" rc_is 0 +expect "no commit on the branch yet: pr-shape is skipped" has c9e "pr-shape: skipped, no commit on this branch yet" +expect "no commit on the branch yet: pr-shape never ran" not_called c9e prshape +put docs/b.md "not committed" +run_check c9f "$T/bin-nogh" +expect "an uncommitted file: noted" has c9f "uncommitted changes are not checked" + +# 10. the path filter of job changes +new_repo stub +mkdir -p "$R/$PP1" +printf 'x\n' >"$R/${PP1}main.rs" +commit_all "feat: touch a product path" +run_check c10 "$T/bin-nogh" +expect "a product path changed: the filter note" has c10 "a product path or the workflow changed" +new_repo stub +put .github/workflows/ci.yml "name: CI" +commit_all "ci: touch the workflow" +run_check c10b "$T/bin-nogh" +expect "the workflow changed: the filter note" has c10b "a product path or the workflow changed" +if [ -f "$CIYML" ]; then + expect "ci.yml carries the product filter of check.sh" grep -Fq "product_re='$PRODUCT_ERE'" "$CIYML" +fi +expect "check.sh carries the stamped product filter" grep -Fq "product_re='$PRODUCT_ERE'" "$CHECK" +expect "check.sh carries the stamped default branch" grep -Fq "DEFAULT_BRANCH='$BRANCH'" "$CHECK" + +# 11. the real owners check and the real pr-shape, when they sit beside this file +if [ -f "$PRSHAPE" ] && [ -f "$OWNERS_SH" ]; then + new_repo real + put docs/a.md "plain doc" + commit_all "docs: add a page" + run_check c11 "$T/bin-nogh" + expect "real scripts, docs-only change: exit 0" rc_is 0 + expect "real scripts: the owners check passed" has c11 "all owned" + expect "real scripts: pr-shape ended its run" has c11 "checks: 0 failed" + + new_repo real + mkdir -p "$R/$PP1" + printf 'x\n' >"$R/${PP1}main.rs" + commit_all "feat(app): change the product" + run_check c11b "$T/bin-nogh" + expect "real scripts, a product change with no proof: exit 1" rc_is 1 + expect "real scripts, no proof: only whole pairs on stderr" pairs_ok c11b + expect "real scripts, no proof: pr-shape names the rule" has c11b "pr-shape: a behavior path changed and the PR adds or changes no proof file" + expect "real scripts, no proof: check names the step" has c11b "check: pr-shape: a check failed" + + mkdir -p "$R/docs/verification" + printf '# Verification: the change\n\nCommand: bash scripts/test-x.sh\nExit: 0\nOutput:\nPASS one\nVerdict: PASS\n\n## Negative control\n\nCommand: bash scripts/test-x.sh\nExit: 1\nOutput:\nFAIL one\nVerdict: RED, as expected\n' >"$R/docs/verification/change.md" + printf '\n- %s: the product change\n' "$P1" >>"$R/CHANGELOG.md" + commit_all "docs: add the proof and the changelog line" + run_check c11c "$T/bin-nogh" -- --title "feat(app): change the product" --body "Closes #12" + expect "real scripts, a product change with proof, tag and body: exit 0" rc_is 0 + expect "real scripts: the passed body reached the board check" has c11c "the body has a Closes #<n> line" + run_check c11d "$T/bin-nogh" -- --title "feat(app): change the product" + expect "real scripts, the same change with no body: exit 1" rc_is 1 + expect "real scripts, no body: pr-shape names the board rule" has c11d "pr-shape: a behavior path changed and nothing links the PR to its work" + + new_repo real + put docs/a.md "plain doc" + commit_all "docs: add a page" + run_check c11e "$T/bin-nogh" -- --title "$inj_title" --body "$inj_body" + run_fixes c11e + expect "real pr-shape with a payload title: exit 1" rc_is 1 + expect "real pr-shape with a payload title: not in the output" no_payload c11e + expect "real pr-shape with a payload title: only whole pairs on stderr" pairs_ok c11e + expect "real pr-shape with a payload title: running every Fix line creates no PWNED" no_pwned +else + echo "skipped: the real-script cases (pr-shape.sh and check-owners.sh are not stamped beside this file)" +fi + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-issues-from-rows.sh.tpl b/templates/team-stamp/files/scripts/test-issues-from-rows.sh.tpl new file mode 100755 index 000000000..1f7e87094 --- /dev/null +++ b/templates/team-stamp/files/scripts/test-issues-from-rows.sh.tpl @@ -0,0 +1,316 @@ +#!/usr/bin/env bash +# test-issues-from-rows.sh - run issues-from-rows.sh against a fixture board and a fake gh on +# PATH. The fake serves a canned issue list and a canned label list, records every `issue create` +# and `label create` call one argument per line, and adds what was created to its lists, so a +# second run shows the idempotence. No network. Leaves its temp dir behind; the path is printed. +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +SCRIPT="$HERE/issues-from-rows.sh" +STAMPED_BOARD='{{BOARD_FILE}}' +TAG='{{DECISION_TAG}}' +T="$(mktemp -d "${TMPDIR:-/tmp}/issues-from-rows-test.XXXXXX")" +echo "test dir: $T" + +mkdir -p "$T/bin" +cat >"$T/bin/gh" <<'EOF' +#!/bin/bash +# fake gh: `issue list` and `label list` print canned files; `issue create` and `label create` +# record their arguments and add what they made to the canned file. +case "$1 $2" in +"issue list") + printf '%s\n' "$*" >>"$FAKE_T/list-calls" + [ -f "$FAKE_T/list-fails" ] && { echo "${FAKE_BOOM:-boom}" >&2; exit 1; } + cat "$FAKE_T/existing" + ;; +"issue create") + printf 'CALL issue\n' >>"$FAKE_T/calls" + title="" + while [ $# -gt 0 ]; do + printf 'ARG:%s\n' "$1" >>"$FAKE_T/calls" + [ "$1" = "--title" ] && title="$2" + shift + done + printf '%s\n' "$title" >>"$FAKE_T/existing" + echo "https://github.example/issues/1" + ;; +"label list") + [ -f "$FAKE_T/label-list-fails" ] && { echo "nolabels" >&2; exit 1; } + cat "$FAKE_T/labels" + ;; +"label create") + printf 'CALL label\nLABEL:%s\n' "$3" >>"$FAKE_T/calls" + [ -f "$FAKE_T/label-create-fails" ] && { echo "denied" >&2; exit 1; } + printf '%s\n' "$3" >>"$FAKE_T/labels" + ;; +*) exit 1 ;; +esac +EOF +chmod +x "$T/bin/gh" +export FAKE_T="$T" +export PATH="$T/bin:$PATH" + +# Fixture board. Row shape: | ID | Item | Notes | Status |. +cat >"$T/BACKLOG.md" <<'EOF' +# Backlog + +| ID | Item | Notes & source | Status | +|---|---|---|---| +| ID-001 | Plain tagged row | Make the thing work. Done when: the test passes. #P1 #alice #S | queued | +| ID-002 | Tagged row with no check | Make the other thing work. #P1 #alice #S | queued | +| ID-004 | Shipped row | Was done. Done when: it ran. #P1 #alice #S | shipped [(#5)] | +| ID-005 | Open issue row | Has an issue already. Done when: it exists. #P1 #bob #S | queued | +| ID-006 | Closed issue row | Had an issue, now closed. Done when: it was closed. #P1 #bob #S | queued | +| ID-007 | Fix the "quoted" thing with a `tick` and $HOME and 'single' | Goal with $(touch PWNED) and `touch PWNED2` inside. Done when: run $(touch PWNED3) and expect "ok". #P1 #carol #S | queued | +| ID-008 | Agent row | Unassigned build work. Done when: it builds. #P1 #agent #S | queued | +| ID-009 | Tags before the login | Reorder the tags. Done when: the order is right. #P1 #critical #dave-x #M | queued | +| ID-070 | Prefix neighbour | Its id is a prefix of another issue id. Done when: it is created. #P1 #erin #S | queued | +| ID-010 | Parked row | Waiting. Done when: the trigger fires. #P2 #alice #S | parked [waiting on X] | +EOF +printf '| ID-003 | Decision row | Pick a price. Done when: the owner decides. #P0 #%s #S | queued |\n' "$TAG" >>"$T/BACKLOG.md" + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } +expect() { # expect <label> <condition command...> + local label="$1" + shift + if "$@" >/dev/null 2>&1; then ok "$label"; else bad "$label"; fi +} + +reset() { # reset: a fresh call log, the canned issue list, the canned label list + : >"$T/calls" + : >"$T/list-calls" + rm -f "$T/list-fails" "$T/label-list-fails" "$T/label-create-fails" + cat >"$T/existing" <<'EOF' +ID-005: Open issue row +ID-006: Closed issue row +ID-0701: A different row whose id starts with ID-070 +Some plain title +EOF + printf '%s\n' bug enhancement >"$T/labels" +} +# run <name> <args...>: output in $T/out-<name> (stdout), $T/err-<name> (stderr), exit code in $rc +run() { + local name="$1" + shift + rc=0 + (cd "$T" && bash "$SCRIPT" --board-file "$T/BACKLOG.md" "$@") >"$T/out-$name" 2>"$T/err-$name" || rc=$? +} +has() { grep -Fq -- "$2" "$T/out-$1"; } +hasnt() { ! grep -Fq -- "$2" "$T/out-$1"; } +errhas() { grep -Fq -- "$2" "$T/err-$1"; } +issue_calls() { grep -c '^CALL issue$' "$T/calls" || true; } +label_calls() { grep -c '^CALL label$' "$T/calls" || true; } +no_calls() { [ ! -s "$T/calls" ]; } +called_with() { grep -Fxq -- "ARG:$1" "$T/calls"; } +# pair <name>: stderr is exactly the two-line refusal +pair() { + [ "$(wc -l <"$T/err-$1" | tr -d ' ')" -eq 2 ] \ + && sed -n 1p "$T/err-$1" | grep -q '^issues-from-rows: ' \ + && sed -n 2p "$T/err-$1" | grep -q '^Fix: ' +} +# body_of_call <title>: the --body argument of the call with that title +body_of_call() { + awk -v want="ARG:$1" ' + $0 == "CALL issue" { t = ""; on = 0 } + $0 == "ARG:--title" { getline; t = $0; next } + $0 == "ARG:--body" { on = (t == want); first = 1; next } + /^ARG:--(label|assignee|title)$/ { on = 0 } + on { line = $0; if (first) { sub(/^ARG:/, "", line); first = 0 } print line }' "$T/calls" +} + +# 1. dry run is the default and creates nothing +reset +run dry +expect "default run: exit 0" [ "$rc" -eq 0 ] +expect "default run: creates nothing" no_calls +expect "default run: lists a tagged row" has dry "would create: ID-001: Plain tagged row (assignee alice, label ready)" +expect "default run: summary says dry run" has dry "issues-from-rows: dry run, 4 to create, 2 with an issue, 1 without Done when" +expect "default run: prints the label step for each missing label" bash -c 'grep -Fq "would create label: ready" "$1" && grep -Fq "would create label: one-way-door" "$1" && grep -Fq "would create label: blocked" "$1"' _ "$T/out-dry" +reset +run dry2 --dry-run +expect "--dry-run: creates nothing" no_calls + +# 2. skips +expect "row with no Done when: skipped and named" has dry "skip: ID-002 has a #alice tag but no Done when: text" +expect "decision row: not listed" hasnt dry "ID-003" +expect "shipped row: not listed" hasnt dry "ID-004" +expect "parked row: not listed" hasnt dry "ID-010" +expect "#agent row: not listed" hasnt dry "ID-008" +expect "row with an open issue: skipped" has dry "skip: ID-005 already has an issue" +expect "row with a closed issue: skipped" has dry "skip: ID-006 already has an issue" +expect "an issue ID-0701 does not hide ID-070" has dry "would create: ID-070: Prefix neighbour" +expect "login found after other tags" has dry "would create: ID-009: Tags before the login (assignee dave-x, label ready)" + +# 3. apply creates the labels first, then the right issues, with the right arguments +reset +run apply --apply +expect "--apply: exit 0" [ "$rc" -eq 0 ] +expect "--apply: three labels created" [ "$(label_calls)" -eq 3 ] +expect "--apply: label ready created" grep -Fxq "LABEL:ready" "$T/calls" +expect "--apply: label one-way-door created" grep -Fxq "LABEL:one-way-door" "$T/calls" +expect "--apply: label blocked created" grep -Fxq "LABEL:blocked" "$T/calls" +expect "--apply: every label is created before the first issue" bash -c 'awk "/^CALL issue\$/ { seen = 1 } /^CALL label\$/ { if (seen) bad = 1 } END { exit bad }" "$1"' _ "$T/calls" +expect "--apply: four issues created" [ "$(issue_calls)" -eq 4 ] +expect "--apply: lists the issues once" [ "$(wc -l <"$T/list-calls" | tr -d ' ')" -eq 1 ] +expect "--apply: the issue list covers every state" grep -Fq -- "--state all" "$T/list-calls" +expect "--apply: title is ID-NNN: title" called_with "ID-001: Plain tagged row" +expect "--apply: label ready on the issue" called_with "ready" +expect "--apply: assignee is the login" called_with "alice" +body="$(body_of_call "ID-001: Plain tagged row")" +expect "body: Goal section holds the notes before Done when" grep -Fxq -- "Make the thing work." <<<"$body" +expect "body: Done when section holds the check" grep -Fxq -- "the test passes." <<<"$body" +expect "body: Scope names the board row and the board file" grep -Fxq -- "Board row ID-001 in $T/BACKLOG.md" <<<"$body" +expect "body: sections match the task form, in order" [ "$(grep -E '^### ' <<<"$body" | tr '\n' ',')" = "### Goal,### Done when,### Scope," ] +expect "body: tags are not copied into the text" bash -c '! grep -Fq "#alice" <<<"$1"' _ "$body" + +# 4. untrusted text survives intact and never runs +q_title='ID-007: Fix the "quoted" thing with a `tick` and $HOME and '"'single'" +expect "quotes, backtick, dollar: title arrives intact" called_with "$q_title" +qbody="$(body_of_call "$q_title")" +expect "untrusted body: command substitution kept as text" grep -Fq -- '$(touch PWNED)' <<<"$qbody" +expect "untrusted body: backticks kept as text" grep -Fq -- '`touch PWNED2`' <<<"$qbody" +expect "untrusted body: nothing executed in the test dir" bash -c '! ls "$1"/PWNED* >/dev/null 2>&1' _ "$T" +expect "untrusted body: nothing executed in the working dir" bash -c '! ls PWNED* >/dev/null 2>&1' + +# 5. idempotence: the second --apply sees the first run's titles and labels +run apply2 --apply +expect "second --apply: exit 0" [ "$rc" -eq 0 ] +expect "second --apply: creates no more issues" [ "$(issue_calls)" -eq 4 ] +expect "second --apply: creates no more labels" [ "$(label_calls)" -eq 3 ] +expect "second --apply: every row has an issue" has apply2 "issues-from-rows: 0 created, 6 with an issue, 1 without Done when, 0 failed" + +# 6. labels that already exist are left alone +reset +printf '%s\n' ready one-way-door blocked >"$T/labels" +run haslabels --apply +expect "labels present: none created" [ "$(label_calls)" -eq 0 ] +expect "labels present: issues still created" [ "$(issue_calls)" -eq 4 ] +reset +printf '%s\n' ready >"$T/labels" +run onelabel +expect "one label present: only the other two are named in the dry run" bash -c '! grep -Fq "would create label: ready" "$1" && grep -Fq "would create label: blocked" "$1"' _ "$T/out-onelabel" + +# 7. failures: each is the two-line refusal +reset +: >"$T/list-fails" +run listfail --apply +expect "gh issue list fails: exit 1" [ "$rc" -eq 1 ] +expect "gh issue list fails: nothing created" [ "$(issue_calls)" -eq 0 ] +expect "gh issue list fails: says why" errhas listfail "gh issue list failed" +expect "gh issue list fails: rule then Fix" pair listfail +reset +: >"$T/label-list-fails" +run labellist --apply +expect "gh label list fails: exit 1, nothing created" bash -c '[ "$1" -eq 1 ] && [ ! -s "$2" ]' _ "$rc" "$T/calls" +expect "gh label list fails: rule then Fix" pair labellist +reset +: >"$T/label-create-fails" +run labelcreate --apply +expect "gh label create fails: exit 1, no issue created" bash -c '[ "$1" -eq 1 ] && [ "$(grep -c "^CALL issue\$" "$2" || true)" -eq 0 ]' _ "$rc" "$T/calls" +expect "gh label create fails: rule then Fix" pair labelcreate +run badarg --nope +expect "unknown argument: exit 2" [ "$rc" -eq 2 ] +expect "unknown argument: rule then Fix" pair badarg +rc=0 +(cd "$T" && bash "$SCRIPT" --board-file "$T/missing.md") >"$T/out-nofile" 2>"$T/err-nofile" || rc=$? +expect "missing board file: exit 1" [ "$rc" -eq 1 ] +expect "missing board file: rule then Fix" pair nofile + +# 8. no gh on PATH +mkdir -p "$T/bin-nogh" +for tool in bash env git awk sed grep cat printf tr wc dirname head; do + p="$(command -v "$tool" 2>/dev/null || true)" + case "$p" in /*) ln -sf "$p" "$T/bin-nogh/$tool" ;; esac +done +rc=0 +(cd "$T" && PATH="$T/bin-nogh" bash "$SCRIPT" --board-file "$T/BACKLOG.md") >"$T/out-nogh" 2>"$T/err-nogh" || rc=$? +expect "no gh: exit 1" [ "$rc" -eq 1 ] +expect "no gh: says so, rule then Fix" pair nogh +expect "no gh: names gh" errhas nogh "gh is not installed" + +# 9. an empty board file value: one line, exit 0, gh never called +reset +run empty --board-file "" +expect "empty board file: exit 0" [ "$rc" -eq 0 ] +expect "empty board file: one line" [ "$(wc -l <"$T/out-empty" | tr -d ' ')" -eq 1 ] +expect "empty board file: says there is nothing to read" has empty "no board file set; nothing to read" +expect "empty board file: gh never called" bash -c '[ ! -s "$1" ] && [ ! -s "$2" ]' _ "$T/calls" "$T/list-calls" +rc=0 +(cd "$T" && PATH="$T/bin-nogh" bash "$SCRIPT" --board-file "") >"$T/out-empty2" 2>&1 || rc=$? +expect "empty board file: exit 0 even with no gh installed" [ "$rc" -eq 0 ] + +# 10. the stamped default board file +reset +mkdir -p "$T/repo/scripts" +git -C "$T/repo" init -q 2>/dev/null +cp "$SCRIPT" "$T/repo/scripts/issues-from-rows.sh" +if [ -z "$STAMPED_BOARD" ]; then + rc=0 + (cd "$T/repo" && bash scripts/issues-from-rows.sh) >"$T/out-default" 2>&1 || rc=$? + expect "stamped with no board file: exit 0 and the one-line note" bash -c '[ "$1" -eq 0 ] && grep -Fq "no board file set; nothing to read" "$2"' _ "$rc" "$T/out-default" +else + mkdir -p "$T/repo/$(dirname "$STAMPED_BOARD")" + cp "$T/BACKLOG.md" "$T/repo/$STAMPED_BOARD" + rc=0 + (cd "$T/repo/scripts" && bash issues-from-rows.sh --apply) >"$T/out-default" 2>&1 || rc=$? + expect "stamped board file: read with no argument, from a subdirectory" bash -c '[ "$1" -eq 0 ] && grep -Fq "created: ID-001: Plain tagged row" "$2"' _ "$rc" "$T/out-default" + expect "stamped board file: the Scope line names it" grep -Fxq -- "Board row ID-001 in $STAMPED_BOARD" "$T/calls" +fi + +# 11. hostile text (a path, an argument, gh output, a row title) never reaches a pasted command, a +# second Fix line or the terminal +payload="x'" +payload="$payload"'$(touch PWNED)`touch PWNED`;touch PWNED' +no_shell_chars() { ! grep -F -e '$(' -e '`' -e "'" "$1"; } +hdir="$T/hostile" +mkdir -p "$hdir" +reset +rc=0 +(cd "$hdir" && bash "$SCRIPT" --board-file "$hdir/$payload.md") >"$T/out-h1" 2>"$T/err-h1" || rc=$? +expect "hostile board path: exit 1, rule then Fix" bash -c '[ "$1" -eq 1 ]' _ "$rc" +expect "hostile board path: the refusal is exactly two lines" pair h1 +rc=0 +(cd "$hdir" && bash "$SCRIPT" "--$payload") >"$T/out-h2" 2>"$T/err-h2" || rc=$? +expect "hostile argument: exit 2, rule then Fix" bash -c '[ "$1" -eq 2 ]' _ "$rc" +expect "hostile argument: the refusal is exactly two lines" pair h2 +: >"$T/list-fails" +FAKE_BOOM="$payload" run hostgh --apply +expect "hostile gh error text: exit 1, rule then Fix" bash -c '[ "$1" -eq 1 ]' _ "$rc" +expect "hostile gh error text: the refusal is exactly two lines" pair hostgh +rm -f "$T/list-fails" +printf '| ID-001 | %s title | Goal here. Done when: it is ok. #alice | queued |\n' "$payload" >"$T/HBOARD.md" +reset +rc=0 +(cd "$hdir" && bash "$SCRIPT" --board-file "$T/HBOARD.md" --apply) >"$T/out-h4" 2>"$T/err-h4" || rc=$? +expect "hostile row title: the issue is still created" bash -c '[ "$1" -eq 0 ] && [ "$(grep -c "^CALL issue\$" "$2")" -eq 1 ]' _ "$rc" "$T/calls" +# a row whose ID cell and login carry a Fix: line and an escape byte: every echoed line is filtered +esc="$(printf '\033')" +{ + printf '| ID-7 Fix: bash x.sh%s[31m | t | Goal. Done when: ok. #alice | queued |\n' "$esc" + printf '| ID-8 Fix: rm x%s[2J | t | Goal. #alice | queued |\n' "$esc" + printf '| ID-005 Fix: touch PWNED | t | Goal. Done when: ok. #alice | queued |\n' +} >"$T/IDBOARD.md" +reset +rc=0 +(cd "$hdir" && bash "$SCRIPT" --board-file "$T/IDBOARD.md") >"$T/out-h5" 2>"$T/err-h5" || rc=$? +expect "hostile ID cell: dry run exits 0" bash -c '[ "$1" -eq 0 ]' _ "$rc" +expect "hostile ID cell: the colon of a Fix: line is not echoed" bash -c '! grep -Fq "Fix:" "$1"' _ "$T/out-h5" +expect "hostile ID cell: the row is still listed, filtered" has h5 "would create: ID-7 Fix? bash x.sh?" +reset +rc=0 +(cd "$hdir" && bash "$SCRIPT" --board-file "$T/IDBOARD.md" --apply) >"$T/out-h6" 2>"$T/err-h6" || rc=$? +expect "hostile ID cell: apply output carries no Fix: text" bash -c '! grep -Fq "Fix:" "$1"' _ "$T/out-h6" +for n in h1 h2 hostgh h4 h5 h6; do + expect "hostile $n: no command substitution, backtick or quote in stderr" no_shell_chars "$T/err-$n" + expect "hostile $n: no command substitution, backtick or quote in stdout" no_shell_chars "$T/out-$n" + expect "hostile $n: no escape byte in the output" bash -c '! cat "$1" "$2" | grep -q "$(printf "\033")"' _ "$T/out-$n" "$T/err-$n" + grep -h '^Fix: ' "$T/err-$n" >"$T/fix-$n" || true + while IFS= read -r l; do + (cd "$hdir" && EDITOR=true bash -c "${l#Fix: }") >/dev/null 2>&1 || true + done <"$T/fix-$n" +done +expect "hostile text: running every printed Fix line creates no PWNED file" bash -c '[ -z "$(find "$1" -name "PWNED*")" ]' _ "$T" + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-negctl.sh b/templates/team-stamp/files/scripts/test-negctl.sh new file mode 100644 index 000000000..c68127c77 --- /dev/null +++ b/templates/team-stamp/files/scripts/test-negctl.sh @@ -0,0 +1,349 @@ +#!/usr/bin/env bash +# test-negctl.sh - run negctl.sh in a temp git repo built per case. No network. +# Every case starts from a repo whose test is "a.txt still says good". +# Leaves its temp dir behind; the path is printed. +set -euo pipefail +SCRIPT="$(cd "$(dirname "$0")" && pwd)/negctl.sh" +T="$(mktemp -d "${TMPDIR:-/tmp}/negctl-test.XXXXXX")" +echo "test dir: $T" + +export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } +expect() { # expect <label> <condition command...> + local label="$1" + shift + if "$@" >/dev/null 2>&1; then ok "$label"; else bad "$label"; fi +} + +# mkrepo <name>: a committed repo with a.txt (good), b.txt (keep) and test.sh. +mkrepo() { + R="$T/$1" + mkdir -p "$R" + ( + cd "$R" + git init -q + git config user.name negctl-test + git config user.email negctl-test@example.invalid + git config commit.gpgsign false + printf 'good\n' >a.txt + printf 'keep\n' >b.txt + cat >test.sh <<'EOS' +echo "checking a.txt" +grep -q good a.txt || { echo "FAIL a.txt lost good"; exit 1; } +echo "ok a.txt" +EOS + git add a.txt b.txt test.sh + git commit -q -m init + ) +} + +# run_ng <name> <test cmd> <mutate cmd>: output in $T/<name>.out and .err, exit code in $rc. +run_ng() { + local name="$1" + rc=0 + (cd "$R" && bash "$SCRIPT" "$2" "$3") >"$T/$name.out" 2>"$T/$name.err" || rc=$? +} + +clean_tree() { [ -z "$(git -C "$R" status --porcelain)" ]; } +a_is_good() { [ "$(cat "$R/a.txt")" = "good" ]; } +out_has() { grep -qF -- "$2" "$T/$1.out"; } +err_has() { grep -qF -- "$2" "$T/$1.err"; } +# a refusal ends stderr with the rule line, then a "Fix:" line +two_line_refusal() { + local last2 + last2="$(tail -n 2 "$T/$1.err")" + [ "$(printf '%s\n' "$last2" | sed -n 1p | cut -c1-8)" = "negctl: " ] && + [ "$(printf '%s\n' "$last2" | sed -n 2p | cut -c1-5)" = "Fix: " ] +} +# the parts a pull request check reads in a negative control block +block_is_accepted() { + grep -Eq '^[[:space:]]*Exit:' "$T/$1.out" && + awk '{ if (prev && $0 != "") f = 1; prev = ($0 ~ /^[[:space:]]*Output:/) } END { exit !f }' "$T/$1.out" && + grep -Eq '^[[:space:]]*Verdict: RED' "$T/$1.out" && + grep -Eiq 'negative control' "$T/$1.out" && + grep -Eq '^Command: ' "$T/$1.out" +} + +# happy path +mkrepo happy +run_ng happy "bash test.sh" "printf 'bad\n' > a.txt" +expect "happy: green, red, green: exit 0" [ "$rc" -eq 0 ] +expect "happy: NEGATIVE CONTROL heading names what was broken" out_has happy "NEGATIVE CONTROL: broke a.txt" +expect "happy: Command line printed" out_has happy "Command: bash test.sh" +expect "happy: Exit line is the red exit" out_has happy "Exit: 1" +expect "happy: Output holds the red run" out_has happy "FAIL a.txt lost good" +expect "happy: Verdict line" out_has happy "Verdict: RED, as expected" +expect "happy: closing line says restored and green" out_has happy "green again" +expect "happy: block order is heading, Command, Output, Exit, Verdict" bash -c \ + 'awk "/^NEGATIVE CONTROL/{a=NR} /^Command:/{b=NR} /^Exit:/{c=NR} /^Output:/{d=NR} /^Verdict:/{e=NR} END{exit !(a<b && b<d && d<c && c<e)}" "$0"' "$T/happy.out" +expect "happy: the block passes the proof check" block_is_accepted happy +expect "happy: a.txt restored" a_is_good +expect "happy: tree clean after" clean_tree + +# the proof block keeps only the tail of a long red run +mkrepo tail +cat >"$R/test.sh" <<'EOS' +i=0 +while [ "$i" -lt 40 ]; do echo "line $i"; i=$((i + 1)); done +echo "FAIL a.txt lost good" +grep -q good a.txt +EOS +git -C "$R" add test.sh +git -C "$R" commit -q -m "long output" +run_ng tail "bash test.sh" "printf 'bad\n' > a.txt" +expect "tail: exit 0" [ "$rc" -eq 0 ] +expect "tail: the last line of the red run is kept" out_has tail "FAIL a.txt lost good" +expect "tail: an early line is cut" bash -c '! grep -qF "line 0" "$0"' "$T/tail.out" +expect "tail: at most 15 lines between Output and Exit" bash -c \ + 'n=$(awk "/^Output:/{f=1;next} /^Exit:/{f=0} f" "$0" | wc -l); [ "$n" -le 15 ]' "$T/tail.out" + +# a red run with no output at all still gives a block the proof check reads +mkrepo silent +cat >"$R/test.sh" <<'EOS' +grep -q good a.txt +EOS +git -C "$R" add test.sh +git -C "$R" commit -q -m "silent test" +run_ng silent "bash test.sh" "printf 'bad\n' > a.txt" +expect "silent: exit 0" [ "$rc" -eq 0 ] +expect "silent: Output holds a placeholder line" out_has silent "<no output>" +expect "silent: the block passes the proof check" block_is_accepted silent + +# a dirty tree is refused and nothing runs +mkrepo dirty +printf 'edited\n' >"$R/a.txt" +run_ng dirty "touch $T/dirty-ran; bash test.sh" "printf 'bad\n' > a.txt" +expect "dirty: refused with exit 2" [ "$rc" -eq 2 ] +expect "dirty: names the refusal" err_has dirty "REFUSED" +expect "dirty: two-line refusal" two_line_refusal dirty +expect "dirty: the test never ran" [ ! -e "$T/dirty-ran" ] +expect "dirty: the uncommitted edit is untouched" [ "$(cat "$R/a.txt")" = "edited" ] +expect "dirty: no proof block on stdout" bash -c '! grep -q "NEGATIVE CONTROL" "$0"' "$T/dirty.out" + +# a test that is red before the change +mkrepo prered +run_ng prered "exit 1" "touch $T/prered-mutated; printf 'bad\n' > a.txt" +expect "prered: exit 1" [ "$rc" -eq 1 ] +expect "prered: says nothing was mutated" err_has prered "the test is not green before the change, nothing was mutated" +expect "prered: two-line refusal" two_line_refusal prered +expect "prered: the mutation never ran" [ ! -e "$T/prered-mutated" ] +expect "prered: tree clean" clean_tree + +# a mutation that changes nothing +mkrepo nochange +run_ng nochange "bash test.sh" "true" +expect "nochange: exit 1" [ "$rc" -eq 1 ] +expect "nochange: says the mutation changed no tracked file" err_has nochange "the mutation changed no tracked file" +expect "nochange: two-line refusal" two_line_refusal nochange +expect "nochange: tree clean" clean_tree + +# a mutation that only creates an untracked file changes no tracked file +mkrepo onlynew +run_ng onlynew "bash test.sh" "echo x > only-new.tmp" +expect "onlynew: exit 1" [ "$rc" -eq 1 ] +expect "onlynew: says the mutation changed no tracked file" err_has onlynew "the mutation changed no tracked file" +expect "onlynew: the file it created is removed" [ ! -e "$R/only-new.tmp" ] + +# a break the test does not catch +mkrepo uncaught +run_ng uncaught "bash test.sh" "printf 'changed\n' > b.txt" +expect "uncaught: exit 1" [ "$rc" -eq 1 ] +expect "uncaught: says the test does not cover it" err_has uncaught "the test stayed green with the break in place: the test does not cover it" +expect "uncaught: two-line refusal" two_line_refusal uncaught +expect "uncaught: b.txt restored" [ "$(cat "$R/b.txt")" = "keep" ] +expect "uncaught: tree clean" clean_tree + +# a red that is only a syntax error is refused, not recorded as RED +mkrepo syntax +run_ng syntax "bash test.sh" "printf 'if then\n' > test.sh" +expect "syntax: exit 1" [ "$rc" -eq 1 ] +expect "syntax: names a load or syntax error" err_has syntax "load or syntax error" +expect "syntax: two-line refusal" two_line_refusal syntax +expect "syntax: no RED block on stdout" bash -c '! grep -q "Verdict: RED" "$0"' "$T/syntax.out" +expect "syntax: test.sh restored" bash -c 'grep -q "lost good" "$0"' "$R/test.sh" +expect "syntax: tree clean" clean_tree + +# a red that is only a missing test file (exit 127) is refused too +mkrepo missing +run_ng missing "bash test.sh" "rm test.sh" +expect "missing test file: exit 1" [ "$rc" -eq 1 ] +expect "missing test file: names a load or syntax error" err_has missing "load or syntax error" +expect "missing test file: two-line refusal" two_line_refusal missing +expect "missing test file: test.sh restored" [ -f "$R/test.sh" ] +expect "missing test file: tree clean" clean_tree + +# exit 127 from the command itself, with no assertion line, is a load error +mkrepo cmd127 +run_ng cmd127 "bash test.sh" "printf 'exit 127\n' > test.sh" +expect "exit 127: exit 1" [ "$rc" -eq 1 ] +expect "exit 127: names a load or syntax error" err_has cmd127 "load or syntax error" +expect "exit 127: tree clean" clean_tree + +# an assertion line makes the red count, even beside a syntax-error message +mkrepo assertwins +cat >"$R/test.sh" <<'EOS' +grep -q good a.txt && exit 0 +echo "FAIL a.txt lost good (syntax error near the end of the line)" +exit 1 +EOS +git -C "$R" add test.sh +git -C "$R" commit -q -m "assertion beside noise" +run_ng assertwins "bash test.sh" "printf 'bad\n' > a.txt" +expect "assertion beside a syntax-error message: exit 0" [ "$rc" -eq 0 ] +expect "assertion beside a syntax-error message: Verdict line" out_has assertwins "Verdict: RED, as expected" + +# test output is data: an escape sequence is removed, and a line that looks like a refusal stays indented +mkrepo hostile +cat >"$R/test.sh" <<'EOS' +printf '\033[31mFAIL a.txt lost good\033[0m\n' +printf 'Fix: rm -rf x\n' +grep -q good a.txt +EOS +git -C "$R" add test.sh +git -C "$R" commit -q -m "hostile output" +run_ng hostile "bash test.sh" "printf 'bad\n' > a.txt" +expect "hostile output: exit 0" [ "$rc" -eq 0 ] +expect "hostile output: no escape byte on stdout" bash -c '! grep -q "$(printf "\033")" "$0"' "$T/hostile.out" +expect "hostile output: the failing line is still shown" out_has hostile "FAIL a.txt lost good" +mkrepo hostilepre +cat >"$R/test.sh" <<'EOS' +printf 'Fix: rm -rf x\n' +exit 1 +EOS +git -C "$R" add test.sh +git -C "$R" commit -q -m "hostile red before" +run_ng hostilepre "bash test.sh" "printf 'bad\n' > a.txt" +expect "hostile output before the change: exit 1" [ "$rc" -eq 1 ] +expect "hostile output before the change: exactly one Fix: line starts a line" bash -c '[ "$(grep -c "^Fix: " "$0")" -eq 1 ]' "$T/hostilepre.err" +expect "hostile output before the change: two-line refusal" two_line_refusal hostilepre + +# a mutate command that commits moves HEAD: refused, and the fix names the old head +mkrepo moved +head_old="$(git -C "$R" rev-parse HEAD)" +run_ng moved "bash test.sh" "printf 'bad\n' > a.txt; git commit -qam moved" +expect "moved head: exit 1" [ "$rc" -eq 1 ] +expect "moved head: names the moved HEAD" err_has moved "moved HEAD" +expect "moved head: two-line refusal" two_line_refusal moved +expect "moved head: the Fix line names the old head" err_has moved "Fix: git reset --soft $head_old" + +# a mutation that creates new untracked files +mkrepo created +run_ng created "bash test.sh" "printf 'bad\n' > a.txt; echo x > new.tmp; mkdir -p sub; echo y > sub/new2.tmp" +expect "created: exit 0" [ "$rc" -eq 0 ] +expect "created: new.tmp removed" [ ! -e "$R/new.tmp" ] +expect "created: sub/new2.tmp removed" [ ! -e "$R/sub/new2.tmp" ] +expect "created: nothing untracked left" [ -z "$(git -C "$R" ls-files --others --exclude-standard)" ] +expect "created: tree clean" clean_tree + +# a file that was untracked before the run survives +mkrepo preexisting +printf 'mine\n' >"$R/scratch.txt" +run_ng preexisting "bash test.sh" "printf 'bad\n' > a.txt; echo x > new.tmp" +expect "preexisting: exit 0" [ "$rc" -eq 0 ] +expect "preexisting: the old untracked file is untouched" [ "$(cat "$R/scratch.txt")" = "mine" ] +expect "preexisting: the new file is removed" [ ! -e "$R/new.tmp" ] + +# the mutation is staged, two files, one deleted +mkrepo staged +run_ng staged "bash test.sh" "printf 'bad\n' > a.txt; git add a.txt; rm b.txt" +expect "staged: exit 0" [ "$rc" -eq 0 ] +expect "staged: a.txt restored" a_is_good +expect "staged: b.txt restored" [ "$(cat "$R/b.txt")" = "keep" ] +expect "staged: index and tree clean" clean_tree + +# the mutate command fails after it changed a file +mkrepo mutfail +run_ng mutfail "bash test.sh" "printf 'bad\n' > a.txt; exit 3" +expect "mutfail: exit 1" [ "$rc" -eq 1 ] +expect "mutfail: names the exit code" err_has mutfail "the mutate command failed with exit 3" +expect "mutfail: two-line refusal" two_line_refusal mutfail +expect "mutfail: a.txt restored" a_is_good +expect "mutfail: tree clean" clean_tree + +# a mutation that adds a file to git cannot be restored by checkout +mkrepo addnew +run_ng addnew "bash test.sh" "printf 'bad\n' > a.txt; echo x > added.tmp; git add added.tmp" +expect "addnew: exit 1" [ "$rc" -eq 1 ] +expect "addnew: names the file it left" err_has addnew "left in place: added.tmp" +expect "addnew: two-line refusal, nothing printed after the Fix line" two_line_refusal addnew +expect "addnew: a.txt restored" a_is_good +expect "addnew: the added file is left in place" [ -e "$R/added.tmp" ] + +# the trap: a signal while the red run is going +wait_for() { # wait_for <file>: up to about 30 seconds + local i=0 + while [ ! -e "$1" ] && [ "$i" -lt 300 ]; do + sleep 0.1 + i=$((i + 1)) + done + [ -e "$1" ] +} + +mkrepo sigext +cat >"$T/sigext-test.sh" <<EOS +n=\$(cat "$T/sigext-count" 2>/dev/null || echo 0) +echo \$((n + 1)) >"$T/sigext-count" +if [ "\$n" -ge 1 ]; then + echo \$\$ >"$T/sigext-pid" + touch "$T/sigext-started" + exec sleep 30 +fi +grep -q good a.txt +EOS +cd "$R" +bash "$SCRIPT" "bash $T/sigext-test.sh" "printf 'bad\n' > a.txt; echo x > new.tmp" >"$T/sigext.out" 2>"$T/sigext.err" & +pid=$! +cd - >/dev/null +if wait_for "$T/sigext-started"; then + kill -TERM "$pid" +else + kill -KILL "$pid" 2>/dev/null || true +fi +rc=0 +wait "$pid" || rc=$? +expect "sigext: TERM during the red run: exit 143" [ "$rc" -eq 143 ] +expect "sigext: a.txt restored" a_is_good +expect "sigext: the created file is removed" [ ! -e "$R/new.tmp" ] +expect "sigext: tree clean" clean_tree +expect "sigext: the test process is gone" bash -c '! kill -0 "$(cat "$0")"' "$T/sigext-pid" + +# the trap: the test kills negctl itself in the red run +mkrepo sigself +cat >"$T/sigself-test.sh" <<EOS +n=\$(cat "$T/sigself-count" 2>/dev/null || echo 0) +echo \$((n + 1)) >"$T/sigself-count" +if [ "\$n" -ge 1 ]; then + kill -TERM \$PPID + sleep 30 +fi +grep -q good a.txt +EOS +run_ng sigself "bash $T/sigself-test.sh" "printf 'bad\n' > a.txt" +expect "sigself: the test kills negctl: exit 143" [ "$rc" -eq 143 ] +expect "sigself: a.txt restored" a_is_good +expect "sigself: tree clean" clean_tree + +# usage and refusals outside a repo +mkrepo usage +run_ng usage "bash test.sh" "" +expect "usage: an empty mutate command: exit 64" [ "$rc" -eq 64 ] +expect "usage: two-line refusal" two_line_refusal usage +rc=0 +(cd "$R" && bash "$SCRIPT") >"$T/noargs.out" 2>"$T/noargs.err" || rc=$? +expect "usage: no arguments: exit 64" [ "$rc" -eq 64 ] +rc=0 +(cd "$R" && bash "$SCRIPT" --help) >"$T/help.out" 2>&1 || rc=$? +expect "--help: exit 0" [ "$rc" -eq 0 ] +expect "--help: shows the usage line" out_has help "negctl.sh \"<test command>\" \"<mutate command>\"" +mkdir -p "$T/nogit" +rc=0 +(cd "$T/nogit" && GIT_CEILING_DIRECTORIES="$T" bash "$SCRIPT" "true" "true") >"$T/nogit.out" 2>"$T/nogit.err" || rc=$? +expect "outside a git work tree: exit 2" [ "$rc" -eq 2 ] +expect "outside a git work tree: names the refusal" err_has nogit "REFUSED" +expect "outside a git work tree: two-line refusal" two_line_refusal nogit + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-pr-merge.sh.tpl b/templates/team-stamp/files/scripts/test-pr-merge.sh.tpl new file mode 100644 index 000000000..5fe36fb2a --- /dev/null +++ b/templates/team-stamp/files/scripts/test-pr-merge.sh.tpl @@ -0,0 +1,826 @@ +#!/usr/bin/env bash +# test-pr-merge.sh - run pr-merge.sh against a fake gh that serves canned PR JSON per case. +# The fake runs the script's --jq expression through jq, so jq must be on PATH here +# (pr-merge.sh itself needs gh only). No network. Door cases run a copy of the script with +# a known door list, so they hold for any stamped values; one case reads the stamped list. +# Leaves its temp dir behind; the path is printed. +set -uo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +SCRIPT_SRC="$HERE/pr-merge.sh" +if ! command -v jq >/dev/null 2>&1; then + echo "test-pr-merge: jq not found, skipping (the fake gh needs it)" + exit 0 +fi +T="$(mktemp -d "${TMPDIR:-/tmp}/pr-merge-test.XXXXXX")" +echo "test dir: $T" + +# The values this repo was stamped with. +DEFAULT_BRANCH="{{DEFAULT_BRANCH}}" + +# The script refuses to run unless its text equals origin/<default branch>:scripts/pr-merge.sh. Every +# copy under test therefore lives in a throwaway git repo whose origin is itself, with that text on +# the default branch. selfrepo <dir> <source script>: make <dir>/scripts/pr-merge.sh that way. +selfrepo() { + mkdir -p "$1/scripts" + cp "$2" "$1/scripts/pr-merge.sh" + ( + cd "$1" || exit 1 + git init -q + git checkout -q -b "$DEFAULT_BRANCH" 2>/dev/null || git symbolic-ref HEAD "refs/heads/$DEFAULT_BRANCH" + git add scripts/pr-merge.sh + git -c user.name=t -c user.email=t@example.invalid commit -q -m copy + git remote add origin "$1" + git fetch -q origin "$DEFAULT_BRANCH" + ) >/dev/null 2>&1 +} +SCRIPT="$T/self/scripts/pr-merge.sh" +selfrepo "$T/self" "$SCRIPT_SRC" + +mkdir -p "$T/bin" +# fake gh. `pr view` serves $T/case.json through the --jq expression, except that the Nth `pr view` +# call serves $T/seq-N.json when that file exists (a rollup that changes between polls). `gh api` serves +# the REST shapes the script reads, built from the same case file and run through the script's own --jq +# expression: the pull request (head), its files, the workflow runs of its head, its timeline. Setting +# FAKE_API_FAIL=<part of an endpoint> makes the matching api call fail. `pr merge` is recorded, and fails +# the way GitHub does when the pinned head is not the live head in $T/live-head. +cat >"$T/bin/gh" <<'EOF' +#!/bin/bash +T="@T@" +echo "gh $*" >> "$T/calls" +pick() { # the case file for the next pr view + local n src + n=$(( $(grep -c '^gh pr view' "$T/calls") + $1 )) + src="$T/case.json" + if [ -f "$T/seq-$n.json" ]; then src="$T/seq-$n.json"; fi + printf '%s' "$src" +} +if [ "$1 $2" = "pr view" ]; then + expr="" + while [ $# -gt 0 ]; do + if [ "$1" = "--jq" ]; then expr="$2"; fi + shift + done + jq -r "$expr" "$(pick 0)" +elif [ "$1" = "api" ]; then + ep="" expr="" + shift + while [ $# -gt 0 ]; do + case "$1" in + --jq) expr="$2"; shift ;; + --paginate) ;; + -*) ;; + *) ep="$1" ;; + esac + shift + done + if [ -n "${FAKE_API_FAIL:-}" ]; then case "$ep" in *"$FAKE_API_FAIL"*) echo "gh: HTTP 500" >&2; exit 1 ;; esac; fi + src="$(pick 1)" + case "$ep" in + repos/*/commits/*/pulls*) jq '(.apiCommitPrs // [{number: 7}])' "$src" | jq -r "$expr" ;; + repos/*/pulls/*/files*) jq '[.files[] | {filename: .path, previous_filename: (.previous // null)}]' "$src" | jq -r "$expr" ;; + repos/*/actions/runs*) jq '{workflow_runs: (.apiRuns // [{id: 101, event: "pull_request", path: ".github/workflows/ci.yml", created_at: "2026-01-02T00:00:00Z", pull_requests: [{number: 7}]}])}' "$src" | jq -r "$expr" ;; + repos/*/issues/*/timeline*) jq '(.apiTimeline // [])' "$src" | jq -r "$expr" ;; + repos/*/pulls/*) + n=$(grep -c '/pulls/[0-9]* --jq' "$T/calls") + if [ "$n" -ge 2 ] && [ -f "$T/head2" ]; then + jq -n --arg h "$(cat "$T/head2")" '{head: {sha: $h}}' | jq -r "$expr" + else + jq '{head: {sha: .headRefOid}}' "$src" | jq -r "$expr" + fi ;; + *) echo "fake gh: unexpected api call: $ep" >&2; exit 1 ;; + esac +elif [ "$1 $2" = "pr merge" ]; then + want="" + while [ $# -gt 0 ]; do + if [ "$1" = "--match-head-commit" ]; then want="$2"; fi + shift + done + if [ -f "$T/live-head" ] && [ "$want" != "$(cat "$T/live-head")" ]; then + echo "GraphQL: Head branch was modified. Review and try the merge again. (mergePullRequest)" >&2 + exit 1 + fi + exit 0 +else + exit 1 +fi +EOF +sed -i.bak "s|@T@|$T|" "$T/bin/gh" && rm -f "$T/bin/gh.bak" +chmod +x "$T/bin/gh" +export PATH="$T/bin:$PATH" + +CHK_OK='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"SUCCESS"}' +CHK_DOCS='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"SKIPPED"}' +CHK_FAIL='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"FAILURE"}' +CHK_PEND='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build","status":"IN_PROGRESS","conclusion":""}' +CHK_RERUN='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1","startedAt":"2026-01-01T00:00:00Z"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"FAILURE","startedAt":"2026-01-01T00:01:00Z"},{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"SUCCESS","startedAt":"2026-01-01T00:05:00Z"}' +CHK_TWOMAKERS='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"added-by-the-pr"}' +FILE_PLAIN='{"path":"docs/README.md"},{"path":"app/src/lib.rs"}' +FILE_DOOR='{"path":"docs/README.md"},{"path":"zz-door/vectors/pair.json"}' +REV_NONE='' +REV_OTHER='{"author":{"login":"reviewer"},"authorAssociation":"MEMBER","commit":{"oid":"head-judged"},"state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"}' +REV_CAROL='{"author":{"login":"carol"},"authorAssociation":"MEMBER","commit":{"oid":"head-judged"},"state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"}' +REV_SELF='{"author":{"login":"author"},"authorAssociation":"MEMBER","commit":{"oid":"head-judged"},"state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"}' +REV_REVOKED='{"author":{"login":"reviewer"},"authorAssociation":"MEMBER","commit":{"oid":"head-judged"},"state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"},{"author":{"login":"reviewer"},"authorAssociation":"MEMBER","commit":{"oid":"head-judged"},"state":"CHANGES_REQUESTED","submittedAt":"2026-01-03T00:00:00Z"}' + +HEAD_SHA="head-judged" +OTHER_HEAD="head-pushed-later" + +DEFAULT_COMMIT_PRS='[{"number":7}]' +DEFAULT_RUNS='[{"id":101,"event":"pull_request","path":".github/workflows/ci.yml","created_at":"2026-01-02T00:00:00Z","pull_requests":[{"number":7}]}]' + +# mkcase_at <file> <isDraft> <mergeable> <checks> <files> <reviews> +mkcase_at() { + local file="$1" + shift + printf '{"isDraft":%s,"mergeable":"%s","author":{"login":"%s"},"statusCheckRollup":[%s],"files":[%s],"reviews":[%s],"headRefOid":"%s","headRefName":"%s","baseRefName":"%s","apiRuns":%s,"apiTimeline":%s,"apiCommitPrs":%s}\n' \ + "$1" "$2" "${CASE_AUTHOR:-author}" "$3" "$4" "$5" "${CASE_HEAD-$HEAD_SHA}" "${CASE_BRANCH:-feature/x}" "${CASE_BASE:-$DEFAULT_BRANCH}" \ + "${CASE_RUNS:-$DEFAULT_RUNS}" "${CASE_TIMELINE:-[]}" "${CASE_COMMIT_PRS:-$DEFAULT_COMMIT_PRS}" >"$file" +} +# mkcase <isDraft> <mergeable> <checks> <files> <reviews>: what every pr view serves; +# it also drops the sequence of the case before. Call mkseq after it. +mkcase() { + rm -f "$T"/seq-*.json "$T/live-head" "$T/head2" + mkcase_at "$T/case.json" "$@" +} +# mkseq <N> <isDraft> <mergeable> <checks> <files> <reviews>: what the Nth pr view serves +mkseq() { + local n="$1" + shift + mkcase_at "$T/seq-$n.json" "$@" +} + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } +expect() { # expect <label> <condition command...> + local label="$1" + shift + if "$@" >/dev/null 2>&1; then ok "$label"; else bad "$label"; fi +} + +merged() { grep -qx "gh pr merge 7 --squash --delete-branch --match-head-commit $HEAD_SHA" "$T/calls"; } +not_merged() { ! grep -q "^gh pr merge" "$T/calls"; } +views_are() { [ "$(grep -c '^gh pr view' "$T/calls")" -eq "$1" ]; } +calls_are() { [ "$(grep '^gh ' "$T/calls" | grep -vc '^gh api')" -eq "$1" ]; } +api_calls_are() { [ "$(grep -c '^gh api' "$T/calls")" -eq "$1" ]; } +# every refusal is two lines on stderr: a rule line, then a "Fix: " line (progress lines are skipped) +two_line_form() { + awk ' + /^pr-merge: (waiting on|note:)/ { next } + /^Fix: / { if (!want) bad = 1; want = 0; next } + { if (want) bad = 1; want = 1 } + END { if (want) bad = 1; exit bad }' "$T/err-$1" +} +fix_is() { grep -qxF "Fix: $2" "$T/err-$1"; } + +# variant <name> <door array body> <approver>: a copy of the script with other door values +variant() { + mkdir -p "$T/v-$1" + sed -e "s|^DOORS=(.*)\$|DOORS=($2)|" -e "s|^APPROVER=\".*\"\$|APPROVER=\"$3\"|" "$SCRIPT_SRC" >"$T/v-$1.src" + selfrepo "$T/v-$1" "$T/v-$1.src" +} +variant door '"zz-door/*" "zz-two/*"' '' +variant approver '"zz-door/*"' 'carol' +variant nodoor '' '' + +# Polls in the --wait tests run fast. +export PR_MERGE_POLL_SECS=0.1 + +# run <name> <args...>: fresh call log, stdout in $T/out-<name>, stderr in $T/err-<name>, exit code +# in $rc. SUT names the script (the stamped one unless a case sets another), RUNNER the bash. +SUT="$SCRIPT" +RUNNER="bash" +run() { + local name="$1" + shift + : >"$T/calls" + rc=0 + (cd "$T" && "$RUNNER" "$SUT" "$@") >"$T/out-$name" 2>"$T/err-$name" || rc=$? +} +text_has() { grep -qF -- "$2" "$T/out-$1" "$T/err-$1"; } + +# the stamped values are the ones in the script +expect "stamped default branch is in the script" grep -qxF 'DEFAULT_BRANCH="{{DEFAULT_BRANCH}}"' "$SCRIPT" +expect "stamped approver is in the script" grep -qxF 'APPROVER="{{DOOR_APPROVER}}"' "$SCRIPT" +expect "stamped door list is in the script" grep -qxF 'DOORS=({{DOOR_ARRAY}})' "$SCRIPT" +expect "the script holds only the brief's rules: no CI-path flag" bash -c '! grep -q "allow-ci-change" "$0"' "$SCRIPT" +expect "the script holds only the brief's rules: no kit head variable" bash -c '! grep -q "KIT_" "$0"' "$SCRIPT" +if [ "$DEFAULT_BRANCH" != "main" ]; then + expect "no literal main branch in the script" bash -c '! grep -Eq "origin/main|[^a-z]main[^a-z]" "$0"' "$SCRIPT" +fi + +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run green 7 +expect "green merges: exit 0" [ "$rc" -eq 0 ] +expect "green merges: squash, delete-branch and the judged head in the call" merged +expect "green merges: one pr view and one pr merge, nothing else" calls_are 2 + +mkcase false MERGEABLE "$CHK_DOCS" "$FILE_PLAIN" "$REV_NONE" +run docs 7 +expect "docs-only (other jobs skipped, changes passed) merges" merged + +mkcase false MERGEABLE "$CHK_RERUN" "$FILE_PLAIN" "$REV_NONE" +run rerun 7 +expect "an old failed run, rerun green, merges: only the newest run counts" merged + +mkcase false MERGEABLE "" "$FILE_PLAIN" "$REV_NONE" +run nochecks 7 +expect "zero checks is refused: exit 1" [ "$rc" -eq 1 ] +expect "zero checks is refused: names the changes job" text_has nochecks "changes check has not passed" +expect "zero checks is refused: two-line form" two_line_form nochecks +expect "zero checks is refused: no merge call" not_merged + +mkcase true MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run draft 7 +expect "draft refused: exit 1" [ "$rc" -eq 1 ] +expect "draft refused: says draft" text_has draft "is a draft" +expect "draft refused: two-line form, fix is gh pr ready" fix_is draft "gh pr ready 7" +expect "draft refused: two-line form" two_line_form draft +expect "draft refused: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_FAIL" "$FILE_PLAIN" "$REV_NONE" +run failing 7 +expect "failing check refused: exit 1" [ "$rc" -eq 1 ] +expect "failing check refused: names the check" text_has failing "failing check: build" +expect "failing check refused: two-line form" two_line_form failing +expect "failing check refused: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_PEND" "$FILE_PLAIN" "$REV_NONE" +run pending 7 +expect "pending check refused without --wait: exit 1" [ "$rc" -eq 1 ] +expect "pending check refused: names the check" text_has pending "pending check: build" +expect "pending check refused: the fix is --wait" fix_is pending "bash scripts/pr-merge.sh --wait 7" +expect "pending check refused: two-line form" two_line_form pending +expect "pending check refused: no merge call" not_merged +expect "pending check refused: a single gh call" calls_are 1 + +mkcase false MERGEABLE "$CHK_TWOMAKERS" "$FILE_PLAIN" "$REV_NONE" +run ambiguous 7 +expect "a check name from two producers is refused" [ "$rc" -eq 1 ] +expect "a check name from two producers: names it, two-line form" two_line_form ambiguous +expect "a check name from two producers: no merge call" not_merged + +mkcase false CONFLICTING "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run conflict 7 +expect "conflict refused: exit 1" [ "$rc" -eq 1 ] +expect "conflict refused: says conflicts" text_has conflict "merge conflicts" +expect "conflict refused: the fix is a plain instruction for the author's own branch, never a checkout of the PR" text_has conflict "on your own branch run: git fetch origin && git merge origin/$DEFAULT_BRANCH, resolve the conflicts, push, then run bash scripts/pr-merge.sh --wait 7 from a $DEFAULT_BRANCH checkout" +expect "conflict refused: two-line form" two_line_form conflict +expect "conflict refused: no merge call" not_merged + +mkcase false UNKNOWN "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run nowaitunknown 7 +expect "no wait, mergeability UNKNOWN: refused, exit 1" [ "$rc" -eq 1 ] +expect "no wait, mergeability UNKNOWN: says try again" text_has nowaitunknown "mergeability is UNKNOWN, try again in a minute" +expect "no wait, mergeability UNKNOWN: two-line form" two_line_form nowaitunknown + +# --wait: poll the PR's own rollup until nothing is pending, then judge as usual. +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +mkseq 1 false MERGEABLE "$CHK_PEND" "$FILE_PLAIN" "$REV_NONE" +mkseq 2 false MERGEABLE "$CHK_PEND" "$FILE_PLAIN" "$REV_NONE" +run waitgreen --wait 7 +expect "wait, pending then green: exit 0" [ "$rc" -eq 0 ] +expect "wait, pending then green: merge call recorded" merged +expect "wait, pending then green: read the PR three times" views_are 3 +expect "wait, pending then green: progress line counts pending checks" text_has waitgreen "waiting on 1 pending check" + +# Right after a push no check has registered: an empty rollup is still a wait. +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +mkseq 1 false MERGEABLE "" "$FILE_PLAIN" "$REV_NONE" +run waitempty --wait 7 +expect "wait, no checks yet then green: exit 0" [ "$rc" -eq 0 ] +expect "wait, no checks yet then green: read the PR twice" views_are 2 +expect "wait, no checks yet then green: says why it waits" text_has waitempty "checks not registered yet" + +# Right after a push GitHub has not computed mergeability: UNKNOWN is a wait too. +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +mkseq 1 false UNKNOWN "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +mkseq 2 false UNKNOWN "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run waitunknown --wait 7 +expect "wait, mergeability UNKNOWN then MERGEABLE: exit 0" [ "$rc" -eq 0 ] +expect "wait, mergeability UNKNOWN then MERGEABLE: read the PR three times" views_are 3 + +mkcase false UNKNOWN "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run waitunknowntimeout --wait --timeout 1 7 +expect "wait, mergeability stays UNKNOWN: exit 1" [ "$rc" -eq 1 ] +expect "wait, mergeability stays UNKNOWN: the timeout line names it" text_has waitunknowntimeout "still pending: mergeability UNKNOWN" +expect "wait, mergeability stays UNKNOWN: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_FAIL" "$FILE_PLAIN" "$REV_NONE" +mkseq 1 false MERGEABLE "$CHK_PEND" "$FILE_PLAIN" "$REV_NONE" +run waitred --wait 7 +expect "wait, pending then red: exit 1" [ "$rc" -eq 1 ] +expect "wait, pending then red: names the failing check" text_has waitred "failing check: build" +expect "wait, pending then red: two-line form" two_line_form waitred +expect "wait, pending then red: no merge call" not_merged +expect "wait, pending then red: read the PR twice" views_are 2 + +mkcase false MERGEABLE "$CHK_PEND" "$FILE_PLAIN" "$REV_NONE" +run waittimeout --wait --timeout 1 7 +expect "wait that never finishes: exit 1" [ "$rc" -eq 1 ] +expect "wait that never finishes: no merge call" not_merged +expect "wait timeout line names the pending check" text_has waittimeout "timed out after 1s waiting on #7, still pending: build" +expect "wait timeout: two-line form (the rule, then the fix)" two_line_form waittimeout +expect "wait timeout: the fix line is the last line" bash -c 'tail -n 1 "$0" | grep -q "^Fix: "' "$T/err-waittimeout" + +mkcase true MERGEABLE "$CHK_PEND" "$FILE_PLAIN" "$REV_NONE" +run waitdraft --wait 7 +expect "wait on a draft: exit 1" [ "$rc" -eq 1 ] +expect "wait on a draft: says draft" text_has waitdraft "is a draft" +expect "wait on a draft: read the PR once, no polling" views_are 1 +expect "wait on a draft: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run waitnopending --wait 7 +expect "wait on a PR with nothing pending: one pr view, then the merge" calls_are 2 + +# --dry-run judges and merges nothing. +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run dry --dry-run 7 +expect "dry-run on green: exit 0" [ "$rc" -eq 0 ] +expect "dry-run on green: says dry run" text_has dry "dry run" +expect "dry-run on green: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +mkseq 1 false MERGEABLE "$CHK_PEND" "$FILE_PLAIN" "$REV_NONE" +run waitdry --dry-run --wait 7 +expect "dry-run with wait: exit 0, waited, nothing merged" bash -c '[ "$1" -eq 0 ]' _ "$rc" +expect "dry-run with wait: read the PR twice" views_are 2 +expect "dry-run with wait: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_FAIL" "$FILE_PLAIN" "$REV_NONE" +run dryred --dry-run 7 +expect "dry-run on red: refused, exit 1" [ "$rc" -eq 1 ] +expect "dry-run on red: no merge call" not_merged + +# The merge is pinned to the judged head: GitHub refuses it when the head moved after the check. +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +printf '%s\n' "$OTHER_HEAD" >"$T/live-head" +run moved 7 +expect "head moved after the judgment: exit 1" [ "$rc" -eq 1 ] +expect "head moved after the judgment: the call was pinned to the judged head" merged +expect "head moved after the judgment: names the refusal, two-line form" two_line_form moved +expect "head moved after the judgment: the fix judges it again" fix_is moved "bash scripts/pr-merge.sh --wait 7" + +# --wait pins the head of the final poll, not the first read. +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +CASE_HEAD=$OTHER_HEAD mkseq 1 false MERGEABLE "$CHK_PEND" "$FILE_PLAIN" "$REV_NONE" +run pinwait --wait 7 +expect "wait: merge is pinned to the head of the last poll, not the first" merged + +# One-way doors, with a known door list (zz-door/*, zz-two/*) and no named approver. +SUT="$T/v-door/scripts/pr-merge.sh" +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_NONE" +run door 7 +expect "door path without approval refused: exit 1" [ "$rc" -eq 1 ] +expect "door path refused: names the path" text_has door "zz-door/vectors/pair.json" +expect "door path refused: with no named approver the fix is a plain instruction" grep -q '^Fix: ask a person other than the author to approve PR 7' "$T/err-door" +expect "door path refused: two-line form" two_line_form door +expect "door path refused: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_SELF" +run doorself 7 +expect "door path with only the author's approval refused" [ "$rc" -eq 1 ] +expect "door path with only the author's approval: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_REVOKED" +run doorrevoked 7 +expect "door path with a later change request refused" [ "$rc" -eq 1 ] + +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_OTHER" +run dooroked 7 +expect "door path with another person's approval merges: exit 0" [ "$rc" -eq 0 ] +expect "door path with approval: merge call recorded" merged + +# An approval counts only on the judged head, from a reviewer whose association is OWNER, MEMBER or +# COLLABORATOR, who is not a bot. Each variant below is refused; the control line merges. +rev_with() { # rev_with <login> <association> <commit oid> + printf '{"author":{"login":"%s"},"authorAssociation":%s,"commit":{"oid":"%s"},"state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"}' "$1" "$2" "$3" +} +for v in "stale|reviewer|\"MEMBER\"|head-from-before" "contributor|reviewer|\"CONTRIBUTOR\"|head-judged" "none|reviewer|\"NONE\"|head-judged" \ + "noassoc|reviewer|null|head-judged" "bot|release-bot[bot]|\"MEMBER\"|head-judged" "appbot|app/helper|\"COLLABORATOR\"|head-judged" "nocommit|reviewer|\"MEMBER\"|"; do + IFS='|' read -r vtag vlogin vassoc void <<EOF +$v +EOF + mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$(rev_with "$vlogin" "$vassoc" "$void")" + run "appr-$vtag" 7 + expect "an approval that is $vtag does not count: refused" [ "$rc" -eq 1 ] + expect "an approval that is $vtag: no merge call" not_merged +done +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$(rev_with reviewer '"COLLABORATOR"' head-judged)" +run appr-collab 7 +expect "an approval from a collaborator on the judged head merges" merged +# Runs: a run that lists two pull requests (a second PR shares the head) does not count. +CASE_RUNS='[{"id":101,"event":"pull_request","path":".github/workflows/ci.yml","created_at":"2026-01-02T00:00:00Z","pull_requests":[{"number":7},{"number":8}]}]' mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run sharedhead 7 +expect "a run that also lists another pull request on the same head does not count: refused" [ "$rc" -eq 1 ] +expect "a run shared with another pull request: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run nodoorpath 7 +expect "a PR that touches no door path merges without a review" merged + +# The changed files come from the REST list: 100 files are read like any other; 3000 or more cannot be judged. +files100="" +i=0 +while [ "$i" -lt 100 ]; do + files100="${files100:+$files100,}{\"path\":\"docs/f$i.md\"}" + i=$((i + 1)) +done +mkcase false MERGEABLE "$CHK_OK" "$files100" "$REV_NONE" +run files100 7 +expect "100 plain files are read and merge (no 100-file cap)" merged +files3000="" +i=0 +while [ "$i" -lt 3000 ]; do + files3000="${files3000:+$files3000,}{\"path\":\"docs/g$i.md\"}" + i=$((i + 1)) +done +mkcase false MERGEABLE "$CHK_OK" "$files3000" "$REV_NONE" +run files3000 7 +expect "3000 files cannot be judged: refused" [ "$rc" -eq 1 ] +expect "3000 files: says too many files" text_has files3000 "too many files" +expect "3000 files: no merge call" not_merged + +# A named approver: the approval must come from that login, unless they wrote the PR. +SUT="$T/v-approver/scripts/pr-merge.sh" +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_OTHER" +run approther 7 +expect "named approver, approval from someone else: refused" [ "$rc" -eq 1 ] +expect "named approver, approval from someone else: names the approver" text_has approther "needs an approving review from carol" +expect "named approver, approval from someone else: two-line form" two_line_form approther +expect "named approver, approval from someone else: the fix adds the approver" fix_is approther "gh pr edit 7 --add-reviewer carol" +expect "named approver, approval from someone else: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_CAROL" +run apprcarol 7 +expect "named approver approves: merges" merged + +CASE_AUTHOR=carol mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_OTHER" +run apprauthor 7 +expect "the approver wrote the PR, another person approves: merges" merged + +CASE_AUTHOR=carol mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_NONE" +run apprauthornone 7 +expect "the approver wrote the PR, nobody approves: refused" [ "$rc" -eq 1 ] + +CASE_AUTHOR=carol mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" '{"author":{"login":"carol"},"authorAssociation":"MEMBER","commit":{"oid":"head-judged"},"state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"}' +run apprself 7 +expect "the approver approves their own PR: refused (the author is never the second person)" [ "$rc" -eq 1 ] + +# An empty door list under set -u. Bash 3.2 dies on an empty array expansion that is not guarded. +if /bin/bash --version 2>/dev/null | head -n 1 | grep -q 'version 3\.'; then + EMPTY_RUNNER="/bin/bash" +else + EMPTY_RUNNER="bash" + echo "note: /bin/bash here is not bash 3.x, so the empty-door-list cases run under the bash on PATH" +fi +SUT="$T/v-nodoor/scripts/pr-merge.sh" +RUNNER="$EMPTY_RUNNER" +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run emptydoors 7 +expect "empty door list, set -u: a clean PR merges" merged +expect "empty door list, set -u: exit 0" [ "$rc" -eq 0 ] +expect "empty door list, set -u: no unbound variable error" bash -c '! grep -q "unbound" "$0"' "$T/err-emptydoors" +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_NONE" +run emptydoorsany 7 +expect "empty door list: no path needs a second person" merged +mkcase false MERGEABLE "$CHK_OK" "$files100" "$REV_NONE" +run emptydoors100 7 +expect "empty door list: 100 plain files merge with no second person" merged +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run emptydoorsdry --dry-run 7 +expect "empty door list: dry-run exit 0" [ "$rc" -eq 0 ] +mkcase true MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run emptydoorsdraft 7 +expect "empty door list: a draft is still refused, two-line form" two_line_form emptydoorsdraft +RUNNER="bash" + +# The stamped script, with whatever door list this repo was stamped with. +SUT="$SCRIPT" +door_line="$(grep -m1 '^DOORS=(' "$SCRIPT")" +stamped_first="$(bash -c "$door_line"'; if [ "${#DOORS[@]}" -gt 0 ]; then printf "%s" "${DOORS[0]}"; fi')" +if [ -n "$stamped_first" ]; then + # a path that matches the first stamped glob + stamped_path="$(printf '%s' "$stamped_first" | sed 's/\*/x/g')" + mkcase false MERGEABLE "$CHK_OK" "{\"path\":\"$stamped_path\"}" "$REV_NONE" + run stampeddoor 7 + expect "stamped door list: a change under $stamped_first needs a second person" [ "$rc" -eq 1 ] + expect "stamped door list: two-line form" two_line_form stampeddoor + expect "stamped door list: no merge call" not_merged +else + mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_NONE" + run stampednodoor 7 + expect "stamped door list is empty: the stamped script merges a clean PR" merged +fi + +# Text from gh is chosen by whoever wrote the PR. None of it may reach the output raw, a newline +# in it may not forge a second Fix: line or a second file, and no printed Fix: line may run it. +SUT="$SCRIPT" +mkdir -p "$T/x" +CHK_EVIL='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build$(touch PWNED)\nFix: rm -rf x\u001b[2J","status":"COMPLETED","conclusion":"FAILURE"}' +CHK_EVILPEND='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"build$(touch PWNED)\nFix: rm -rf x","status":"IN_PROGRESS","conclusion":""}' +# every printed Fix: line, run through bash -c, must leave the sentinel dir and create no PWNED +fixes_inert() { + (cd "$T" && grep '^Fix: ' "$T/err-$1" | sed 's/^Fix: //' | while IFS= read -r f; do bash -c "$f" >/dev/null 2>&1 </dev/null; done) + [ ! -e "$T/PWNED" ] && [ -d "$T/x" ] +} +no_raw_payload() { + ! grep -qF '$(' "$T/out-$1" "$T/err-$1" && + ! grep -q '^Fix: rm' "$T/err-$1" && + ! grep -q "$(printf '\033')" "$T/out-$1" "$T/err-$1" +} +fix_lines_are() { [ "$(grep -c '^Fix: ' "$T/err-$1")" -eq "$2" ]; } + +mkcase false MERGEABLE "$CHK_EVIL" "$FILE_PLAIN" "$REV_NONE" +run evilfail 7 +expect "hostile check name, red: refused, exit 1" [ "$rc" -eq 1 ] +expect "hostile check name, red: two-line form" two_line_form evilfail +expect "hostile check name, red: exactly one Fix: line, none forged" fix_lines_are evilfail 1 +expect "hostile check name, red: no raw payload in the output" no_raw_payload evilfail +expect "hostile check name, red: the Fix: lines are inert under bash -c" fixes_inert evilfail +expect "hostile check name, red: no merge call" not_merged + +mkcase false MERGEABLE "$CHK_EVILPEND" "$FILE_PLAIN" "$REV_NONE" +run evilpend --wait --timeout 1 7 +expect "hostile check name, pending to timeout: exit 1" [ "$rc" -eq 1 ] +expect "hostile check name, pending to timeout: two-line form" two_line_form evilpend +expect "hostile check name, pending to timeout: exactly one Fix: line" fix_lines_are evilpend 1 +expect "hostile check name, pending to timeout: no raw payload" no_raw_payload evilpend +expect "hostile check name, pending to timeout: Fix: lines are inert" fixes_inert evilpend + +SUT="$T/v-door/scripts/pr-merge.sh" +mkcase false MERGEABLE "$CHK_OK" '{"path":"docs/ok.md\nfile=zz-door/forged"}' "$REV_NONE" +run forgedfile 7 +expect "a newline in a path does not forge a door file: the PR merges" merged +mkcase false MERGEABLE "$CHK_OK" '{"path":"zz-door/a$(touch PWNED)\nFix: rm -rf x"}' "$REV_NONE" +run evildoor 7 +expect "hostile door path: refused, exit 1" [ "$rc" -eq 1 ] +expect "hostile door path: two-line form, one Fix: line" fix_lines_are evildoor 1 +expect "hostile door path: no raw payload" no_raw_payload evildoor +expect "hostile door path: Fix: lines are inert" fixes_inert evildoor +SUT="$SCRIPT" + +CASE_BRANCH="fix/it's;touch PWNED" mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run evilbranch 7 +expect "a head branch with a single quote: the PR merges" merged +expect "a head branch with a single quote: never printed" bash -c '! grep -qF "it'\''s" "$1" "$2"' _ "$T/out-evilbranch" "$T/err-evilbranch" +expect "a head branch with a single quote: nothing was run" [ ! -e "$T/PWNED" ] + +CASE_HEAD='abc; touch PWNED' mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run evilhead 7 +expect "a head that is not a plain id: refused, exit 1" [ "$rc" -eq 1 ] +expect "a head that is not a plain id: two-line form" two_line_form evilhead +expect "a head that is not a plain id: no merge call" not_merged +expect "a head that is not a plain id: the payload is not echoed" bash -c '! grep -qF "; touch" "$1" "$2"' _ "$T/out-evilhead" "$T/err-evilhead" +expect "a head that is not a plain id: the Fix: lines are inert" fixes_inert evilhead + + +# --- the harness's own files are doors by default; --door-paths add to them --- +SUT="$T/v-nodoor/scripts/pr-merge.sh" +for dp in ".github/workflows/ci.yml" "scripts/x.sh" ".claude/settings.json" "OWNERS.md" "AGENTS.md" "docs/TEAM-WORKFLOW.md" ".kit.toml"; do + mkcase false MERGEABLE "$CHK_OK" "{\"path\":\"$dp\"}" "$REV_NONE" + tag="${dp//[^A-Za-z0-9]/_}" + run "defdoor-$tag" 7 + expect "default door $dp with no approval: refused, even with an empty --door-paths list" [ "$rc" -eq 1 ] + mkcase false MERGEABLE "$CHK_OK" "{\"path\":\"$dp\"}" "$REV_OTHER" + run "defdoorok-$tag" 7 + expect "default door $dp with a second person's approval at the head: merges" merged +done +mkcase false MERGEABLE "$CHK_OK" '{"path":"src/app.js"}' "$REV_NONE" +run notadoor 7 +expect "a path outside the harness's files needs no second person" merged +SUT="$T/v-door/scripts/pr-merge.sh" +mkcase false MERGEABLE "$CHK_OK" '{"path":"zz-two/a"},{"path":"scripts/y.sh"}' "$REV_NONE" +run adddoor 7 +expect "--door-paths adds to the default list: a listed path is a door" [ "$rc" -eq 1 ] +SUT="$SCRIPT" + +# --- an approval counts only at the judged head, from owner, member or collaborator, not a bot --- +SUT="$T/v-door/scripts/pr-merge.sh" +rev() { # rev <login> <association> <commit oid> [state] + printf '{"author":{"login":"%s"},"authorAssociation":"%s","commit":{"oid":"%s"},"state":"%s","submittedAt":"2026-01-02T00:00:00Z"}' "$1" "$2" "$3" "${4:-APPROVED}" +} +refused_door() { # refused_door <label> <reviews json> + mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$2" + run "appr-$1" 7 + expect "approval rule: $1: refused, exit 1" [ "$rc" -eq 1 ] + expect "approval rule: $1: two-line form" two_line_form "appr-$1" + expect "approval rule: $1: no merge call" not_merged +} +refused_door stale-head "$(rev reviewer MEMBER head-an-earlier-commit)" +refused_door contributor "$(rev reviewer CONTRIBUTOR head-judged)" +refused_door none-association "$(rev reviewer NONE head-judged)" +refused_door first-timer "$(rev reviewer FIRST_TIME_CONTRIBUTOR head-judged)" +refused_door bot-login "$(rev 'dependabot[bot]' MEMBER head-judged)" +refused_door app-login "$(rev 'app/some-app' COLLABORATOR head-judged)" +refused_door missing-association '{"author":{"login":"reviewer"},"commit":{"oid":"head-judged"},"state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"}' +refused_door missing-commit '{"author":{"login":"reviewer"},"authorAssociation":"MEMBER","state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"}' +for assoc in OWNER MEMBER COLLABORATOR; do + mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$(rev reviewer "$assoc" head-judged)" + run "assoc-$assoc" 7 + expect "approval rule: $assoc at the head merges" merged +done +# an older approval at the old head plus a fresh one at the head: the latest decision counts +mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$(rev reviewer MEMBER head-an-earlier-commit),$(rev reviewer MEMBER head-judged | sed 's/2026-01-02/2026-01-05/')" +run "appr-refreshed" 7 +expect "approval rule: a fresh approval at the head after a stale one merges" merged +SUT="$SCRIPT" + +# --- both checks, from the workflow named CI --- +mkcase false MERGEABLE '{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"}' "$FILE_PLAIN" "$REV_NONE" +run noshape 7 +expect "no pr-shape check: refused, exit 1" [ "$rc" -eq 1 ] +expect "no pr-shape check: names it" text_has noshape "the pr-shape check has not passed" +expect "no pr-shape check: no merge call" not_merged +mkcase false MERGEABLE '{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"}' "$FILE_PLAIN" "$REV_NONE" +run nochanges 7 +expect "no changes check: refused, exit 1" [ "$rc" -eq 1 ] +mkcase false MERGEABLE '{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"other"}' "$FILE_PLAIN" "$REV_NONE" +run shapeotherwf 7 +expect "pr-shape from another workflow: refused" [ "$rc" -eq 1 ] +mkcase false MERGEABLE '{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"other"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/101/job/1"}' "$FILE_PLAIN" "$REV_NONE" +run changesotherwf 7 +expect "changes from another workflow: refused" [ "$rc" -eq 1 ] +mkcase false MERGEABLE '{"__typename":"StatusContext","context":"changes","state":"SUCCESS"},{"__typename":"StatusContext","context":"pr-shape","state":"SUCCESS"}' "$FILE_PLAIN" "$REV_NONE" +run statusctx 7 +expect "status contexts named changes and pr-shape do not stand in for the checks: refused" [ "$rc" -eq 1 ] + +# --- the guard runs only when its text equals the default branch's copy --- +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +mkdir -p "$T/edited" +cp "$SCRIPT_SRC" "$T/edited.src" +printf '# a pull request edit\n' >>"$T/edited.src" +selfrepo "$T/edited" "$SCRIPT_SRC" +cp "$T/edited.src" "$T/edited/scripts/pr-merge.sh" +SUT="$T/edited/scripts/pr-merge.sh" +run editedcopy 7 +expect "an edited copy refuses to run: exit 1" [ "$rc" -eq 1 ] +expect "an edited copy: names the difference from the default branch" text_has editedcopy "differs from origin/$DEFAULT_BRANCH" +expect "an edited copy: the fix is a checkout of the default branch and a pull" fix_is editedcopy "git checkout $DEFAULT_BRANCH && git pull, then run it again" +expect "an edited copy: two-line form" two_line_form editedcopy +expect "an edited copy: gh was never called" calls_are 0 +mkdir -p "$T/boot/scripts" +cp "$SCRIPT_SRC" "$T/boot/scripts/pr-merge.sh" +(cd "$T/boot" && git init -q && git remote add origin "$T/boot") >/dev/null 2>&1 +SUT="$T/boot/scripts/pr-merge.sh" +run bootstrap 7 +expect "a default branch with no copy yet (the bootstrap PR): refused, exit 1" [ "$rc" -eq 1 ] +expect "bootstrap: says to merge the first stamp pull request by hand" fix_is bootstrap "merge the first stamp pull request by hand, after a second person has read it" +expect "bootstrap: two-line form" two_line_form bootstrap +expect "bootstrap: gh was never called" calls_are 0 +SUT="$SCRIPT" +run selfok 7 +expect "the default branch's own copy runs" merged +expect "no Fix: line of this script tells anyone to check out a pull request" bash -c '! grep -q "gh pr checkout" "$0"' "$SCRIPT_SRC" + + +# --- case, instruction files, renames, base, runs of another PR, base changes, failed reads --- +SUT="$T/v-nodoor/scripts/pr-merge.sh" +for dp in ".CLAUDE/settings.json" "SCRIPTS/x.sh" "Owners.md" "Docs/Team-Workflow.md" ".GitHub/actions/a/action.yml" "CLAUDE.md" "tools/deep/CLAUDE.md" "pkg/AGENTS.md" ".mcp.json" ".github/actions/setup/action.yml" "pkg/.claude/settings.json" "sub/dir/.mcp.json" "CLAUDE.local.md" "app/CLAUDE.local.md" "GEMINI.md" "x/Gemini.md" ".cursor/rules/a.mdc" "app/.cursor/rules/a.mdc" ".vscode/tasks.json" "app/.VSCode/tasks.json"; do + tag="${dp//[^A-Za-z0-9]/_}" + mkcase false MERGEABLE "$CHK_OK" "{\"path\":\"$dp\"}" "$REV_NONE" + run "door2-$tag" 7 + expect "door by case or by instruction file: $dp refused with no approval" [ "$rc" -eq 1 ] + expect "door by case or by instruction file: $dp: no merge call" not_merged +done +mkcase false MERGEABLE "$CHK_OK" '{"path":"docs/old.json","previous":".claude/settings.json"}' "$REV_NONE" +run renamedout 7 +expect "a rename out of a door is a door change: refused" [ "$rc" -eq 1 ] +expect "a rename out of a door: names the previous path" text_has renamedout ".claude/settings.json" +mkcase false MERGEABLE "$CHK_OK" '{"path":"docs/old.json","previous":".claude/settings.json"}' "$REV_OTHER" +run renamedoutok 7 +expect "a rename out of a door with a second person's approval merges" merged +CASE_BASE=other-branch mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run wrongbase 7 +expect "a base that is not the default branch: refused" [ "$rc" -eq 1 ] +expect "a base that is not the default branch: says so, two-line form" two_line_form wrongbase +expect "a base that is not the default branch: the fix retargets the PR" fix_is wrongbase "gh pr edit 7 --base $DEFAULT_BRANCH" +CHK_OTHERPR='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/999/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"SUCCESS","workflowName":"CI","detailsUrl":"https://github.com/o/r/actions/runs/999/job/2"}' +mkcase false MERGEABLE "$CHK_OTHERPR" "$FILE_PLAIN" "$REV_NONE" +run otherpr 7 +expect "green checks that belong to another PR's runs on the same head do not count: refused" [ "$rc" -eq 1 ] +expect "green checks of another PR's runs: says the checks have not passed" text_has otherpr "has not passed" +CHK_OTHERFAIL="$CHK_OK"',{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"FAILURE","detailsUrl":"https://github.com/o/r/actions/runs/999/job/3"}' +mkcase false MERGEABLE "$CHK_OTHERFAIL" "$FILE_PLAIN" "$REV_NONE" +run otherprfail 7 +expect "a failed run of another PR does not block this PR" merged +CASE_RUNS='[{"id":101,"event":"pull_request","path":".github/workflows/other.yml","created_at":"2026-01-02T00:00:00Z","pull_requests":[{"number":7}]}]' mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run otherworkflow 7 +expect "a run of another workflow file does not count: refused" [ "$rc" -eq 1 ] +CASE_RUNS='[{"id":101,"event":"pull_request","path":".github/workflows/ci.yml","created_at":"2026-01-05T00:00:00Z","pull_requests":[{"number":7}]}]' CASE_TIMELINE='[{"event":"base_ref_changed","created_at":"2026-01-03T00:00:00Z"},{"event":"labeled","created_at":"2026-01-09T00:00:00Z"}]' mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_OTHER" +SUT="$T/v-door/scripts/pr-merge.sh" +run basechg 7 +expect "an approval submitted before the last base change does not count: refused" [ "$rc" -eq 1 ] +CASE_TIMELINE='[{"event":"base_ref_changed","created_at":"2026-01-01T00:00:00Z"}]' mkcase false MERGEABLE "$CHK_OK" "$FILE_DOOR" "$REV_OTHER" +run basechgold 7 +expect "an approval submitted after the last base change counts: merges" merged +SUT="$T/v-nodoor/scripts/pr-merge.sh" +for part in "actions/runs" "/files" "/timeline" "pulls/7" "commits/"; do + mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" + : >"$T/calls"; rc=0 + (cd "$T" && FAKE_API_FAIL="$part" bash "$SUT" 7) >"$T/out-apifail" 2>"$T/err-apifail" || rc=$? + expect "a failed read of $part refuses: exit 1" [ "$rc" -eq 1 ] + expect "a failed read of $part: no merge call" not_merged + expect "a failed read of $part: two-line form" two_line_form apifail +done +# --- bytes outside printable ASCII are a door; the head is read again; runs and commits of other PRs --- +# The path functions, taken from the script text and tested with byte strings, so these rows do not depend on +# what the file system does with the names. +LONGS="$(printf '\305\277')" # U+017F +KELVIN="$(printf '\342\204\252')" # U+212A +ACUTE="$(printf '\303\251')" +( + LC_ALL=C + export LC_ALL + BASE_DOORS=() + DOORS=() + eval "$(sed -n '/^BASE_DOORS=/p' "$SCRIPT")" + eval "$(sed -n '/^lower() /p' "$SCRIPT")" + eval "$(sed -n '/^odd_path() {/,/^}/p' "$SCRIPT")" + eval "$(sed -n '/^oddseen=0/p' "$SCRIPT")" + eval "$(sed -n '/^match_doors() {/,/^}/p' "$SCRIPT")" + f=0 + chk() { if "$@"; then echo "PASS path function: $*" | cut -c1-90; else echo "FAIL path function: $*"; f=$((f + 1)); fi; } + chk odd_path "${LONGS}cripts/a.sh" + chk odd_path ".${KELVIN}it.toml" + chk odd_path "docs/caf$ACUTE.md" + chk odd_path "$(printf 'a\001b')" + chk odd_path "$(printf 'a\177b')" + chk ! odd_path "scripts/a b.sh" + chk ! odd_path "docs/plain~name.md" + chk match_doors "${LONGS}cripts/a.sh" + chk match_doors ".${KELVIN}it.toml" + chk match_doors "docs/caf$ACUTE.md" + chk match_doors ".CLAUDE/settings.json" + chk match_doors "x/y/CLAUDE.local.md" + chk ! match_doors "docs/readme.md" + exit "$f" +) >"$T/out-pathfn" 2>&1 +rc=$? +cat "$T/out-pathfn" +expect "the path functions: every byte-string row holds" [ "$rc" -eq 0 ] +SUT="$T/v-nodoor/scripts/pr-merge.sh" +for odd in "${LONGS}cripts/a.sh" ".${KELVIN}it.toml" "docs/caf$ACUTE.md" "$(printf 'docs/a\001b.md')"; do + tag="odd-$(printf '%s' "$odd" | od -An -tx1 | tr -d ' \n' | cut -c1-12)" + if ! printf '%s' "$odd" | jq -Rs . >/dev/null 2>&1; then echo "NOTE $tag: jq refuses the name, case skipped"; continue; fi + mkcase false MERGEABLE "$CHK_OK" "{\"path\":$(printf '%s' "$odd" | jq -Rs .)}" "$REV_NONE" + run "$tag" 7 + expect "a changed path with a byte outside printable ASCII is a door ($tag): refused with no approval" [ "$rc" -eq 1 ] + expect "a non-ASCII door ($tag): the fix says to ask a second person and names the collision" grep -q 'Fix: ask a second person to approve PR 7 (a file name with a byte outside printable ASCII' "$T/err-$tag" + expect "a non-ASCII door ($tag): two-line form" two_line_form "$tag" + expect "a non-ASCII door ($tag): no merge call" not_merged + mkcase false MERGEABLE "$CHK_OK" "{\"path\":$(printf '%s' "$odd" | jq -Rs .)}" "$REV_OTHER" + run "$tag-ok" 7 + expect "a non-ASCII door ($tag) with a second person's approval: merges" merged +done +mkcase false MERGEABLE "$CHK_OK" "{\"path\":\"docs/old.md\",\"previous\":$(printf '%s' "${LONGS}cripts/a.sh" | jq -Rs .)}" "$REV_NONE" +run oddprev 7 +expect "a previous name with a non-ASCII byte is a door too: refused" [ "$rc" -eq 1 ] +# the head is read again after the files: a head that moved in between refuses +mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +printf '%s' "head-moved-meanwhile" >"$T/head2" +run headmoved 7 +expect "a head that moved between the first read and the files read: refused" [ "$rc" -eq 1 ] +expect "a head that moved: says so" text_has headmoved "the head moved" +expect "a head that moved: no merge call" not_merged +rm -f "$T/head2" +# the head commit belongs to another pull request +CASE_COMMIT_PRS='[{"number":7},{"number":9}]' mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run commitprs 7 +expect "the head commit also belongs to another pull request (any state): refused" [ "$rc" -eq 1 ] +expect "another pull request on the head commit: names it" text_has commitprs "belongs to another pull request (9)" +expect "another pull request on the head commit: no merge call" not_merged +# a run created before the last base change does not count; one created after it does +CASE_TIMELINE='[{"event":"base_ref_changed","created_at":"2026-01-03T00:00:00Z"}]' mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run oldrun 7 +expect "a run created before the last base change does not count: refused" [ "$rc" -eq 1 ] +expect "a run created before the last base change: the checks have not passed" text_has oldrun "has not passed" +CASE_RUNS='[{"id":101,"event":"pull_request","path":".github/workflows/ci.yml","created_at":"2026-01-04T00:00:00Z","pull_requests":[{"number":7}]}]' CASE_TIMELINE='[{"event":"base_ref_changed","created_at":"2026-01-03T00:00:00Z"}]' mkcase false MERGEABLE "$CHK_OK" "$FILE_PLAIN" "$REV_NONE" +run newrun 7 +expect "a run created after the last base change counts: merges" merged +SUT="$SCRIPT" + +# Usage errors are two-line refusals too. +run helpflag --help +expect "--help prints usage: exit 0" [ "$rc" -eq 0 ] +expect "--help prints usage: shows the dry-run flag" text_has helpflag "--dry-run" +expect "--help prints usage: shows the wait flag" text_has helpflag "--wait" +run badarg abc +expect "a non-number is refused: exit 2" [ "$rc" -eq 2 ] +expect "a non-number is refused: two-line form" two_line_form badarg +run nonumber +expect "no number is refused: exit 2" [ "$rc" -eq 2 ] +expect "no number is refused: two-line form" two_line_form nonumber +run timeoutalone --timeout 5 7 +expect "--timeout without --wait is refused: exit 2" [ "$rc" -eq 2 ] +expect "--timeout without --wait: two-line form" two_line_form timeoutalone +run timeoutbad --wait --timeout abc 7 +expect "--timeout with a non-number is refused: exit 2" [ "$rc" -eq 2 ] +run unknownopt --force 7 +expect "an unknown option is refused: exit 2" [ "$rc" -eq 2 ] +expect "an unknown option: two-line form" two_line_form unknownopt +expect "usage errors call gh never" calls_are 0 + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-pr-shape.sh.tpl b/templates/team-stamp/files/scripts/test-pr-shape.sh.tpl new file mode 100644 index 000000000..99695afdf --- /dev/null +++ b/templates/team-stamp/files/scripts/test-pr-shape.sh.tpl @@ -0,0 +1,796 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2034 +# test-pr-shape.sh - run pr-shape.sh against a temp git repo built per case. No network. The tags, +# product paths, board file and default branch are the stamped values, so the cases hold for any +# list that has dev and one product tag. The shellcheck cases run when shellcheck is installed; +# the cases with no shellcheck on PATH always run. The negctl case runs when scripts/negctl.sh sits +# beside this file. Leaves its temp dir behind; the path is printed. +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +SCRIPT="$HERE/pr-shape.sh" +NEGCTL="$HERE/negctl.sh" +BRANCH='{{DEFAULT_BRANCH}}' +BOARD='{{BOARD_FILE}}' +TAGS='{{TAGS}}' +PRODUCT_PATHS='{{PRODUCT_PATHS}}' +T="$(mktemp -d "${TMPDIR:-/tmp}/pr-shape-test.XXXXXX")" +echo "test dir: $T" +HAVE_SC=0 +command -v shellcheck >/dev/null 2>&1 && HAVE_SC=1 + +# P1: the first product tag; PP: the product path prefixes +P1="" +PP=() +oldifs="$IFS" +IFS=',' +for t in $TAGS; do + [ "$t" = dev ] && continue + [ -n "$P1" ] || P1="$t" +done +for p in $PRODUCT_PATHS; do PP+=("$p"); done +IFS="$oldifs" +[ -n "$P1" ] || { echo "test needs one product tag besides dev in: $TAGS"; exit 1; } +[ "${#PP[@]}" -gt 0 ] || { echo "test needs a product path in: $PRODUCT_PATHS"; exit 1; } + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } +expect() { # expect <label> <condition command...> + local label="$1" + shift + if "$@" >/dev/null 2>&1; then ok "$label"; else bad "$label"; fi +} + +R="" +n=0 +g() { git -C "$R" -c user.name=t -c user.email=t@example.invalid -c commit.gpgsign=false -c core.autocrlf=false -c core.hooksPath=/dev/null "$@"; } +put() { # put <path> <content> + mkdir -p "$R/$(dirname "$1")" + printf '%s\n' "$2" >"$R/$1" +} +AGENTS_BASE="# Agent rules + +## Proof + +## Merge" +WF_BASE="- [Agent rules](../AGENTS.md#agent-rules) +- [Proof](../AGENTS.md#proof) +- [Merge](../AGENTS.md#merge)" +CL_BASE="# Changelog + +## [Unreleased] + +- $P1: an existing tagged line +- a legacy line with no tag + +## [0.2.0] + +- Old line with no tag." +# new_repo: a base commit with the rule files, a changelog, a proof, a script and a doc +new_repo() { + n=$((n + 1)) + R="$T/repo$n" + mkdir -p "$R" + git -C "$R" init -q --template= + git -C "$R" symbolic-ref HEAD "refs/heads/$BRANCH" + put README.md "readme" + put AGENTS.md "$AGENTS_BASE" + put docs/TEAM-WORKFLOW.md "$WF_BASE" + put CHANGELOG.md "$CL_BASE" + put docs/verification/old.md "old proof" + put docs/guides/notes.md "notes" + if [ -n "$BOARD" ]; then put "$BOARD" "| ID-001 | first | note | queued |"; fi + mkdir -p "$R/scripts" + printf '#!/usr/bin/env bash\necho old\n' >"$R/scripts/old.sh" + g add -A + g commit -q -m base + BASE="$(g rev-parse HEAD)" +} +finish() { # finish: commit the working changes as the PR head + g add -A + g commit -q -m change + HEAD_="$(g rev-parse HEAD)" +} +# pairs_ok <name>: stderr is whole pairs, a rule line "pr-shape: " then a line "Fix: " +pairs_ok() { + awk 'NR % 2 == 1 && $0 !~ /^pr-shape: / { bad = 1 } NR % 2 == 0 && $0 !~ /^Fix: / { bad = 1 } END { exit (bad || NR == 0 || NR % 2 == 1) }' "$T/$1.err" +} +npairs() { echo $(($(wc -l <"$T/$1.err") / 2)); } +# run <name> <title> <body>: stdout in $T/<name>.out, stderr in $T/<name>.err, exit in $rc +run() { + local name="$1" title="$2" body="$3" + rc=0 + (cd "$R" && env -u CI -u PR_BODY_FILE PR_TITLE="$title" PR_BODY="$body" BASE_SHA="$BASE" HEAD_SHA="$HEAD_" bash "$SCRIPT") \ + >"$T/$name.out" 2>"$T/$name.err" || rc=$? + if [ "$rc" -eq 1 ] && ! pairs_ok "$name"; then bad "refusal shape of $name: stderr is not rule/Fix pairs"; fi +} +has() { grep -Fq -- "$2" "$T/$1.out" "$T/$1.err"; } +lacks() { ! grep -Fq -- "$2" "$T/$1.out" "$T/$1.err"; } +failed() { grep -Fq -- "pr-shape: $2" "$T/$1.err"; } +rc_is() { [ "$rc" -eq "$1" ]; } +rc_pairs() { [ "$rc" -eq "$1" ] && pairs_ok "$2"; } +one_pair() { [ "$(npairs "$1")" -eq 1 ] && failed "$1" "$2"; } +n_pairs() { [ "$(npairs "$1")" -eq "$2" ]; } + +GOOD_TITLE="feat(scripts): add the thing" +CLOSES="Closes #12" +FULL_PROOF="# Verification: the thing + +Command: bash scripts/test-thing.sh +Exit: 0 +Output: +PASS one +Verdict: PASS + +## Negative control + +Command: bash scripts/test-thing.sh +Exit: 1 +Output: +FAIL one +Verdict: RED, as expected" +# behav_files <proof content or ->: a script change, then the proof +behav_files() { + new_repo + printf '#!/usr/bin/env bash\necho new\n' >"$R/scripts/new.sh" + if [ "$1" != "-" ]; then put docs/verification/new.md "$1"; fi +} +behav_repo() { + behav_files "$1" + finish +} + +# 1. a good behavioral PR +behav_repo "$FULL_PROOF" +run good "$GOOD_TITLE" "$CLOSES" +expect "good behavioral PR: exit 0" rc_is 0 +expect "good behavioral PR: nothing on stderr" test ! -s "$T/good.err" +expect "good behavioral PR: final line" has good "checks: 0 failed" + +# 2. titles +new_repo +put docs/guides/new.md "doc" +finish +run t1 "Update stuff" "" +expect "bad title (no type): exit 1" rc_is 1 +expect "bad title: one pair naming the rule" one_pair t1 "title is not one line" +expect "bad title: the Fix line has the capital F" grep -q '^Fix: ' "$T/t1.err" +run t2 "feat(Scripts): add the thing" "" +expect "upper-case scope: exit 1" rc_is 1 +run t3 "feat(scripts): this subject is much too long for the seventy two character limit" "" +expect "title over 72 characters: exit 1" rc_is 1 +run t4 "docs(x): fine" "" +expect "title with a scope: exit 0" rc_is 0 +run t5 "docs: fine" "" +expect "title without a scope: exit 0" rc_is 0 +run t6 "$(printf 'docs: first line\nsecond line')" "" +expect "a two-line title: exit 1" rc_is 1 + +# 3. proof +behav_repo "-" +run pnone "$GOOD_TITLE" "$CLOSES" +expect "behavior change, no proof file: exit 1" rc_is 1 +expect "no proof file: one pair naming the rule" one_pair pnone "a behavior path changed and the PR adds or changes no proof file" +expect "no proof file: the Fix names negctl and the escape line" grep -q '^Fix: bash scripts/negctl.sh .*no-proof: <reason' "$T/pnone.err" + +NOEXIT_PROOF="${FULL_PROOF//Exit: 1/Code: 1}" +NOOUT_PROOF="${FULL_PROOF//Output:/Result:}" +NORED_PROOF="${FULL_PROOF//Verdict: RED, as expected/Verdict: PASS}" +NONC_PROOF="${FULL_PROOF//egative control/egative run}" +EXIT0_PROOF="${FULL_PROOF//Exit: 1/Exit: 0}" +BLANKOUT_PROOF="Command: x +Exit: 0 +Output: + +PASS one +Verdict: PASS + +## Negative control + +Command: x +Exit: 1 +Output: + +Verdict: RED, as expected" +ENDOUT_PROOF="## Negative control +Command: x +Exit: 1 +Verdict: RED, as expected +Output:" +for pc in "NOEXIT:no Exit line:Exit:" "NOOUT:no Output label:Output:" "BLANKOUT:Output then a blank line:Output:" "ENDOUT:Output as the last line:Output:" \ + "NORED:no RED verdict:Verdict: RED" "NONC:no negative control words:NEGATIVE CONTROL" "EXIT0:a control with Exit 0:Exit:"; do + var="${pc%%:*}_PROOF" + rest="${pc#*:}" + label="${rest%%:*}" + want="${rest#*:}" + behav_repo "${!var}" + run pbad "$GOOD_TITLE" "$CLOSES" + expect "proof with $label: exit 1" rc_is 1 + expect "proof with $label: one pair" n_pairs pbad 1 + expect "proof with $label: names what is missing" has pbad "$want" +done + +behav_repo "Command: x +Exit: 0 +Output: +text +## Negative control +Command: x +Output: + indented output + Exit: 2 + Verdict: RED, as expected" +run pcase "$GOOD_TITLE" "$CLOSES" +expect "indented lines, any-case heading: exit 0" rc_is 0 +behav_repo "Command: x +Exit: 1 +Output: +text +the Verdict: RED came later +negative control" +run pmid "$GOOD_TITLE" "$CLOSES" +expect "Verdict: RED in the middle of a line: exit 1" rc_is 1 +behav_repo "$(printf '%s\n' "$FULL_PROOF" | awk '{ printf "%s\r\n", $0 }')" +run pcrlf "$GOOD_TITLE" "$CLOSES" +expect "proof file with CRLF line ends: exit 0" rc_is 0 + +behav_files "-" +put docs/verification/README.md "$FULL_PROOF" +finish +run pread "$GOOD_TITLE" "$CLOSES" +expect "a full README as the only proof: exit 1" rc_is 1 +behav_files "-" +put docs/verification/new/README.md "$FULL_PROOF" +printf 'PNG\n' >"$R/docs/verification/new/shot.png" +finish +run pimg "$GOOD_TITLE" "$CLOSES" +expect "a nested README and an image only: exit 1" rc_is 1 +behav_files "-" +g rm -q docs/verification/old.md +finish +run pdel "$GOOD_TITLE" "$CLOSES" +expect "a deleted proof file only: exit 1" rc_is 1 +behav_files "-" +put docs/verification/old.md "$FULL_PROOF" +finish +run pedit "$GOOD_TITLE" "$CLOSES" +expect "an old proof file changed to a full one: exit 0" rc_is 0 +behav_files "-" +put docs/verification/old.md "$NOEXIT_PROOF" +put docs/verification/new.md "$NORED_PROOF" +finish +run ptwo "$GOOD_TITLE" "$CLOSES" +expect "two incomplete proof files: exit 1, one pair" rc_pairs 1 ptwo +expect "two incomplete proof files: both are named" has ptwo "docs/verification/new.md lacks" +behav_files "-" +put docs/verification/old.md "$NOEXIT_PROOF" +put docs/verification/new.md "$FULL_PROOF" +finish +run pone "$GOOD_TITLE" "$CLOSES" +expect "one complete proof file among two: exit 0" rc_is 0 + +behav_repo "-" +run npok "$GOOD_TITLE" "Summary +no-proof: comment rewording, no behavior effect +$CLOSES" +expect "no-proof line with a reason: exit 0" rc_is 0 +expect "no-proof line: prints the reason, filtered" has npok "no-proof: comment rewording" +run npshort "$GOOD_TITLE" "no-proof: n/a +$CLOSES" +expect "no-proof with a short reason: exit 1" rc_is 1 +run npmid "$GOOD_TITLE" "see no-proof: a reason that is long enough +$CLOSES" +expect "no-proof not at the line start: exit 1" rc_is 1 +run npph "$GOOD_TITLE" "no-proof: <reason, 10+ characters> +$CLOSES" +expect "no-proof left as the placeholder: exit 1" rc_is 1 +run npcrlf "$GOOD_TITLE" "$(printf 'Summary\r\nno-proof: comment rewording, no behavior effect\r\nCloses #12\r\n')" +expect "no-proof and Closes with CRLF line ends: exit 0" rc_is 0 +run npnb "$GOOD_TITLE" "no-proof: comment rewording, no behavior effect" +expect "no-proof alone does not excuse the board link: exit 1" rc_is 1 +expect "no-proof alone: the board check fails" failed npnb "a behavior path changed and nothing links" +behav_repo "$NOEXIT_PROOF" +run npover "$GOOD_TITLE" "no-proof: comment rewording, no behavior effect +$CLOSES" +expect "no-proof skips the content check: exit 0" rc_is 0 + +# a behavior path is any changed file that is not documentation +for bp in package-lock.json Makefile snapshots/home.png fixtures/a.json web/index.html data/a.bin docs/secrets/notes.md docs/archive.zip .github/workflows/x.yml .claude/settings.json .kit.toml; do + new_repo + mkdir -p "$R/$(dirname "$bp")" + printf 'changed\n' >"$R/$bp" + finish + run bp "chore: touch a path" "$CLOSES" + expect "behavior path $bp without proof: the proof check fails" failed bp "a behavior path changed and the PR adds or changes no proof file" +done +for dp in README.md docs/guides/OWNERS.md docs/guides/note.txt docs/assets/shot.png docs/product/a.svg docs/product/data.csv .github/pull_request_template.md .claude/memory/a.md docs/verification/x/shot.png; do + new_repo + mkdir -p "$R/$(dirname "$dp")" + printf 'changed\n' >"$R/$dp" + finish + run dp "docs: touch a doc" "" + expect "documentation path $dp: no proof demanded" has dp "ok proof: no behavior path changed" +done + +# 4. board link +behav_repo "$FULL_PROOF" +run noboard "$GOOD_TITLE" "" +expect "no board link: exit 1" rc_is 1 +expect "no board link: the Fix names the ways in" grep -q "^Fix: .*Closes #<n>.*no-board-row: <reason" "$T/noboard.err" +run nbr "$GOOD_TITLE" "Summary +no-board-row: tooling fix with no backlog item" +expect "no-board-row line with a reason: exit 0" rc_is 0 +run nbrshort "$GOOD_TITLE" "no-board-row: n/a" +expect "no-board-row with a short reason: exit 1" rc_is 1 +run nbrmid "$GOOD_TITLE" "see no-board-row: a reason that is long enough" +expect "no-board-row not at the line start: exit 1" rc_is 1 +for cl in "Summary +Closes #12" "Closes #12" "fixes #7" "RESOLVES #9"; do + run closes "$GOOD_TITLE" "$cl" + expect "close line [$(printf '%s' "$cl" | tail -n 1)]: exit 0" rc_is 0 +done +run closescrlf "$GOOD_TITLE" "$(printf 'Summary\r\nCloses #12\r\n')" +expect "Closes #12 with CRLF line ends: exit 0" rc_is 0 +run mention "$GOOD_TITLE" "This follows up on #12 and relates to #13." +expect "a body that only mentions #12: exit 1" rc_is 1 +expect "a body that only mentions #12: the board check fails" failed mention "a behavior path changed and nothing links" +for cl in "Closes #" "this PR closes #12 when merged" "Closes #twelve"; do + run closesbad "$GOOD_TITLE" "$cl" + expect "not a close [$cl]: exit 1" rc_is 1 +done +if [ -n "$BOARD" ]; then + behav_files "$FULL_PROOF" + put "$BOARD" "| ID-001 | first | note | executing |" + finish + run boardchg "$GOOD_TITLE" "" + expect "the board file changed: exit 0" rc_is 0 + expect "the board rule names the board file" has noboard "$BOARD unchanged" +else + expect "no board file set: the rule does not name one" lacks noboard "unchanged, no no-board-row" +fi + +# 5. changelog +cl_put() { # cl_put <extra lines placed under [Unreleased]> + local extra="$1" + put CHANGELOG.md "${CL_BASE/- a legacy line with no tag/- a legacy line with no tag +${extra}}" +} +product_change() { # product_change <path>: a product change that passes the proof check + mkdir -p "$R/$(dirname "$1")" + printf 'changed\n' >"$R/$1" + put docs/verification/new.md "$FULL_PROOF" +} +PFILE="${PP[0]}main.rs" +CL_TITLE="fix(app): change the thing" + +new_repo +printf '#!/usr/bin/env bash\necho new\n' >"$R/scripts/new.sh" +put docs/verification/new.md "$FULL_PROOF" +finish +run cltool "chore(scripts): add a script" "$CLOSES" +expect "tooling-only PR, no changelog: exit 0" rc_is 0 +expect "tooling-only PR: says no product path" has cltool "ok changelog: no product path changed" + +new_repo +product_change "$PFILE" +finish +run clnone "$CL_TITLE" "$CLOSES" +expect "product path without a changelog line: exit 1" rc_is 1 +expect "product path without a changelog line: one pair" n_pairs clnone 1 +expect "product path: the rule names the tags" has clnone "$P1:" +expect "product path: the Fix names the escape line" grep -q "^Fix: .*no-changelog: <reason" "$T/clnone.err" +run clesc "$CL_TITLE" "$CLOSES +no-changelog: internal refactor, no change a user sees" +expect "no-changelog line with a reason: exit 0" rc_is 0 +run clshort "$CL_TITLE" "$CLOSES +no-changelog: n/a" +expect "no-changelog with a short reason: exit 1" rc_is 1 +run clmid "$CL_TITLE" "$CLOSES +see no-changelog: a reason that is long enough" +expect "no-changelog not at the line start: exit 1" rc_is 1 +run clcrlf "$CL_TITLE" "$(printf 'Closes #12\r\nno-changelog: internal refactor, no change a user sees\r\n')" +expect "no-changelog with CRLF line ends: exit 0" rc_is 0 + +for pp in "${PP[@]}"; do + new_repo + product_change "${pp}x/file.rs" + finish + run clpath "$CL_TITLE" "$CLOSES" + expect "product path $pp without a changelog line: exit 1" rc_is 1 +done +new_repo +mkdir -p "$R/${PP[0]}" +printf 'old\n' >"$R/${PP[0]}old.rs" +g add -A +g commit -q -m "add a product file" +BASE="$(g rev-parse HEAD)" +g rm -q "${PP[0]}old.rs" +put docs/verification/new.md "$FULL_PROOF" +finish +run cldel "$CL_TITLE" "$CLOSES" +expect "a deleted product file without a changelog line: exit 1" rc_is 1 +new_repo +mkdir -p "$R/${PP[0]}" +printf 'old\n' >"$R/${PP[0]}old.rs" +g add -A +g commit -q -m "add a product file" +BASE="$(g rev-parse HEAD)" +g mv "${PP[0]}old.rs" scripts/moved.rs +put docs/verification/new.md "$FULL_PROOF" +finish +run clren "$CL_TITLE" "$CLOSES" +expect "a product file renamed out of the product path: exit 1" rc_is 1 + +new_repo +product_change "$PFILE" +cl_put "- $P1: a new tagged line" +finish +run cltag "$CL_TITLE" "$CLOSES" +expect "product path with a tagged line: exit 0" rc_is 0 +expect "product path with a tagged line: says so" has cltag "ok changelog: the PR adds a tagged line" +new_repo +product_change "$PFILE" +put CHANGELOG.md "${CL_BASE} +- $P1: a tagged line under a released version" +finish +run clrelonly "$CL_TITLE" "$CLOSES" +expect "a tagged line only under a released version: exit 1" rc_is 1 + +for tg in $(printf '%s' "$TAGS" | tr ',' ' '); do + new_repo + put docs/guides/new.md "doc" + cl_put "- ${tg}: a line" + finish + run cltg "docs: add a note" "" + expect "tag $tg: exit 0" rc_is 0 +done +new_repo +product_change "$PFILE" +cl_put "- notatag: a misspelled tag" +finish +run clwrong "$CL_TITLE" "$CLOSES" +expect "added line with a wrong tag: exit 1" rc_is 1 +expect "added line with a wrong tag: names the line" has clwrong "line 7" +new_repo +put docs/guides/new.md "doc" +cl_put "- a new line with no tag" +finish +run clnotag "docs: add a note" "" +expect "added untagged line, no product path: exit 1" rc_is 1 +new_repo +put docs/guides/new.md "doc" +cl_put "- $P1:no space after the colon" +finish +run clspace "docs: add a note" "" +expect "added line with no space after the colon: exit 1" rc_is 1 +run clescbad "docs: add a note" "no-changelog: internal refactor, no change a user sees" +expect "no-changelog does not excuse an untagged line: exit 1" rc_is 1 +new_repo +put docs/guides/new.md "doc" +cl_put "- dev: a tagged line" +finish +run clold "docs: add a note" "" +expect "an old untagged line stays untouched: exit 0" rc_is 0 +new_repo +put docs/guides/new.md "doc" +put CHANGELOG.md "${CL_BASE} +- an untagged line under a released version" +finish +run clrel "docs: add a note" "" +expect "an untagged line added under a released version: exit 0" rc_is 0 +new_repo +put docs/guides/new.md "doc" +cl_put "### Fixed + +- $P1: a tagged line + an indented continuation line" +finish +run clcont "docs: add a note" "" +expect "added heading, blank and continuation lines: exit 0" rc_is 0 + +# 6. shellcheck +if [ "$HAVE_SC" -eq 1 ]; then + new_repo + printf '#!/usr/bin/env bash\nunused_var=1\n' >"$R/scripts/warn.sh" + put docs/verification/new.md "$FULL_PROOF" + finish + run scwarn "$GOOD_TITLE" "$CLOSES" + expect "shell file with a warning: exit 1" rc_is 1 + expect "shell file with a warning: one pair naming the file" one_pair scwarn "shellcheck finds warnings in 1 changed shell file(s): scripts/warn.sh" + expect "shell file with a warning: the Fix is a command" grep -q '^Fix: shellcheck -S warning scripts/warn.sh' "$T/scwarn.err" + new_repo + printf '#!/usr/bin/env bash\nunused_var=1\n' >"$R/scripts/old.sh" + finish + run scold "chore: touch an old script" "no-board-row: tests only, no new behavior +no-proof: tests only, no new behavior" + expect "a changed old script with a warning: exit 1" rc_is 1 + expect "a changed old script with a warning: only shellcheck fails" one_pair scold "shellcheck finds warnings" + new_repo + printf '#!/bin/bash\nunused_var=1\n' >"$R/runme" + finish + run scshebang "docs: pretend" "" + expect "a file with a bash shebang and no .sh name is linted" failed scshebang "shellcheck finds warnings" + new_repo + printf 'unused_var=1\n' >"$R/scripts/noshebang.sh" + finish + run scnoshe "docs: pretend" "" + expect "a .sh file with no shebang is linted as bash" failed scnoshe "shellcheck finds warnings" + new_repo + printf '#!/usr/bin/env bash\necho "$1"\n' >"$R/scripts/clean.sh" + put docs/verification/new.md "$FULL_PROOF" + finish + run scok "$GOOD_TITLE" "$CLOSES" + expect "clean shell file: exit 0" rc_is 0 + expect "clean shell file: counted" has scok "shellcheck: 1 shell file(s) clean" +else + echo "skipped: shellcheck cases (shellcheck is not installed here)" +fi + +mkbin() { # mkbin <dir> <tool>... + local d="$1" t p + shift + mkdir -p "$d" + for t in "$@"; do + p="$(command -v "$t" 2>/dev/null || true)" + case "$p" in /*) ln -sf "$p" "$d/$t" ;; esac + done +} +mkbin "$T/bin-nosc" bash sh env git awk sed grep mktemp dirname basename mkdir cat printf tr head cut rm paste sort wc ls tail +new_repo +printf '#!/usr/bin/env bash\necho new\n' >"$R/scripts/new.sh" +put docs/verification/new.md "$FULL_PROOF" +finish +rc=0 +(cd "$R" && PATH="$T/bin-nosc" CI="" PR_TITLE="$GOOD_TITLE" PR_BODY="$CLOSES" BASE_SHA="$BASE" HEAD_SHA="$HEAD_" "$T/bin-nosc/bash" "$SCRIPT") >"$T/nosc.out" 2>"$T/nosc.err" || rc=$? +expect "no shellcheck, local: exit 0" rc_is 0 +expect "no shellcheck, local: prints the skip notice" has nosc "skipped, shellcheck is not installed" +rc=0 +(cd "$R" && PATH="$T/bin-nosc" CI=true PR_TITLE="$GOOD_TITLE" PR_BODY="$CLOSES" BASE_SHA="$BASE" HEAD_SHA="$HEAD_" "$T/bin-nosc/bash" "$SCRIPT") >"$T/nosc-ci.out" 2>"$T/nosc-ci.err" || rc=$? +expect "no shellcheck, CI=true: exit 1 with one pair" rc_pairs 1 nosc-ci +expect "no shellcheck, CI=true: names the cause" failed nosc-ci "shellcheck is not installed on this runner" +new_repo +put docs/guides/new.md "doc" +finish +rc=0 +(cd "$R" && PATH="$T/bin-nosc" CI=true PR_TITLE="docs: add a doc" PR_BODY="" BASE_SHA="$BASE" HEAD_SHA="$HEAD_" "$T/bin-nosc/bash" "$SCRIPT") >"$T/nosc-docs.out" 2>"$T/nosc-docs.err" || rc=$? +expect "no shellcheck, CI=true, no shell file changed: exit 0" rc_is 0 + +# 7. rule parity +new_repo +put AGENTS.md "${AGENTS_BASE} + +## Never" +finish +run pa "docs: change the rules" "" +expect "AGENTS.md alone: exit 1" rc_is 1 +expect "AGENTS.md alone: one pair naming the file" one_pair pa "AGENTS.md changed and docs/TEAM-WORKFLOW.md did not" +expect "AGENTS.md alone: the Fix names the escape line" grep -q "^Fix: .*no-rule-mirror: <reason" "$T/pa.err" +new_repo +put docs/TEAM-WORKFLOW.md "${WF_BASE} +Another line." +finish +run pw "docs: change the rules" "" +expect "TEAM-WORKFLOW.md alone: exit 1" rc_is 1 +expect "TEAM-WORKFLOW.md alone: names the file" failed pw "docs/TEAM-WORKFLOW.md changed and AGENTS.md did not" +run pwesc "docs: change the rules" "no-rule-mirror: the wording only needs one file" +expect "alone with no-rule-mirror and a reason: exit 0" rc_is 0 +run pwshort "docs: change the rules" "no-rule-mirror: skip" +expect "alone with a short no-rule-mirror reason: exit 1" rc_is 1 +run pwcrlf "docs: change the rules" "$(printf 'Summary\r\nno-rule-mirror: the wording only needs one file\r\n')" +expect "no-rule-mirror with CRLF line ends: exit 0" rc_is 0 +new_repo +put AGENTS.md "${AGENTS_BASE} + +## Never" +put docs/TEAM-WORKFLOW.md "${WF_BASE} +- [Never](../AGENTS.md#never)" +finish +run pb "docs: change the rules" "" +expect "both changed, every heading linked: exit 0" rc_is 0 +new_repo +put AGENTS.md "${AGENTS_BASE} + +## Never + +\`\`\` +# not a heading, inside a fence +\`\`\`" +put docs/TEAM-WORKFLOW.md "${WF_BASE} +- [Never](../AGENTS.md#never)" +finish +run pfence "docs: change the rules" "" +expect "a hash line inside a code fence is not a heading: exit 0" rc_is 0 +new_repo +put AGENTS.md "${AGENTS_BASE} + +## Never" +put docs/TEAM-WORKFLOW.md "${WF_BASE} +Another line." +finish +run pnolink "docs: change the rules" "" +expect "both changed, a new heading with no link: exit 1" rc_is 1 +expect "both changed, a new heading with no link: names the anchor" failed pnolink "1 AGENTS.md heading(s) have no link in docs/TEAM-WORKFLOW.md, anchors: never" +run pnolinkesc "docs: change the rules" "no-rule-mirror: this heading is mirrored later" +expect "a missing link with no-rule-mirror: exit 0" rc_is 0 +new_repo +g rm -q docs/TEAM-WORKFLOW.md +put AGENTS.md "${AGENTS_BASE} + +## Never" +finish +run pabsent "docs: change the rules" "" +expect "one rule file absent at head: parity is skipped, exit 0" rc_is 0 + +# 7b. two paths that differ only in case are refused (the guard matches doors in any casing; a case-insensitive +# checkout would let one overwrite the other). The paths go straight into the index. +for pair in ".claude/settings.json:.CLAUDE/settings.json" "scripts/a.sh:SCRIPTS/a.sh" "OWNERS.md:Owners.md"; do + new_repo + first="${pair%%:*}"; second="${pair##*:}" + blob1="$(printf 'one\n' | g hash-object -w --stdin)"; blob2="$(printf 'two\n' | g hash-object -w --stdin)" + g update-index --add --cacheinfo "100644,$blob1,$first" + g update-index --add --cacheinfo "100644,$blob2,$second" + g commit -q -m change + HEAD_="$(g rev-parse HEAD)" + tag="case-$(printf '%s' "$pair" | tr -c 'A-Za-z0-9' '_')" + run "$tag" "docs: add two files" "no-proof: a case plant for the test, no behavior change" + expect "case collision $pair: exit 1" rc_is 1 + expect "case collision $pair: two-line refusal" rc_pairs 1 "$tag" + expect "case collision $pair: names the rule" failed "$tag" "two paths differ only in case" +done +# a name with a newline cannot ride a line list: the tree is read NUL-delimited and refuses it +new_repo +blob1="$(printf 'one\n' | g hash-object -w --stdin)" +if g update-index --add --cacheinfo "100644,$blob1,docs/a +b.txt" 2>/dev/null; then + g commit -q -m change + HEAD_="$(g rev-parse HEAD)" + run casenl "docs: add a file" "no-proof: a name plant for the test, no behavior change" + expect "a path with a newline in the tree: exit 1" rc_is 1 + expect "a path with a newline in the tree: names the rule" failed casenl "two paths differ only in case" +else + echo "NOTE a newline in a path: git refuses the name, case skipped" +fi +new_repo +printf 'x\n' >"$R/docs/guides/other.md" +finish +run casefine "docs: add a guide" "no-proof: a plain docs change, no behavior change" +expect "no case collision: the case check passes" has casefine "ok case: no two paths differ only in case" + +# 8. every failed check prints, in one run +behav_repo "-" +run many "Update stuff" "" +expect "title, proof and board fail together: exit 1" rc_is 1 +expect "three failures print three pairs" n_pairs many 3 +expect "the last stdout line counts the failures" has many "checks: 3 failed" + +# 9. inputs +rc=0 +(cd "$R" && env -u PR_TITLE -u CI BASE_SHA="$BASE" HEAD_SHA="$HEAD_" bash "$SCRIPT") >"$T/usage.out" 2>"$T/usage.err" || rc=$? +expect "no PR_TITLE: exit 2 with a pair" rc_pairs 2 usage +rc=0 +(cd "$R" && env -u CI PR_TITLE="$GOOD_TITLE" BASE_SHA="no-such-rev" HEAD_SHA="$HEAD_" bash "$SCRIPT") >"$T/badref.out" 2>"$T/badref.err" || rc=$? +expect "an unknown base: exit 2 with a pair" rc_pairs 2 badref +rc=0 +(cd "$R" && env -u CI PR_TITLE="$GOOD_TITLE" BASE_SHA="--output=x" HEAD_SHA="$HEAD_" bash "$SCRIPT") >"$T/optref.out" 2>"$T/optref.err" || rc=$? +expect "a base that looks like an option: exit 2" rc_pairs 2 optref +expect "a base that looks like an option: nothing written" test ! -e "$R/x" +behav_repo "$FULL_PROOF" +g update-ref "refs/remotes/origin/$BRANCH" "$BASE" +rc=0 +(cd "$R" && env -u CI -u BASE_SHA -u HEAD_SHA PR_TITLE="$GOOD_TITLE" PR_BODY="$CLOSES" bash "$SCRIPT") >"$T/defs.out" 2>"$T/defs.err" || rc=$? +expect "BASE_SHA and HEAD_SHA default to origin/$BRANCH and HEAD: exit 0" rc_is 0 +printf 'Summary\r\nCloses #12\r\n' >"$T/body.txt" +rc=0 +(cd "$R" && env -u CI -u PR_BODY PR_BODY_FILE="$T/body.txt" PR_TITLE="$GOOD_TITLE" BASE_SHA="$BASE" HEAD_SHA="$HEAD_" bash "$SCRIPT") >"$T/bf.out" 2>"$T/bf.err" || rc=$? +expect "PR_BODY_FILE with CRLF line ends: exit 0" rc_is 0 +behav_files "-" +finish +put docs/verification/new.md "$FULL_PROOF" +run wt "$GOOD_TITLE" "$CLOSES" +expect "an uncommitted proof file does not count: exit 1" rc_is 1 + +# 10. attacker-chosen text: no raw payload in the output, no forged Fix: line, no PWNED file +# run_fixes <name>: run every Fix: line through bash -c in the fixture +run_fixes() { + local l + while IFS= read -r l; do + [ -n "$l" ] || continue + (cd "$R" && bash -c "${l#Fix: }" </dev/null) >/dev/null 2>&1 || true + done <<EOF +$(grep '^Fix: ' "$T/$1.err" || true) +EOF +} +no_payload() { # no_payload <name>: no raw payload text and no forged Fix: line in the output + ! grep -Fq -e '$(touch' -e 'Fix: rm -rf' "$T/$1.out" "$T/$1.err" +} +no_pwned() { [ -z "$(find "$R" "$T" -name 'PWNED*' 2>/dev/null)" ]; } +sq="'" + +new_repo +printf '#!/usr/bin/env bash\necho new\n' >"$R/scripts/new.sh" +finish +run inj1 "$(printf 'feat: x $(touch PWNED)\nFix: rm -rf x')" "$(printf 'Closes #1\nFix: rm -rf x\n$(touch PWNED)')" +run_fixes inj1 +expect "a title with a command and a forged Fix line: exit 1" rc_is 1 +expect "the title payload: not in the output" no_payload inj1 +expect "the title payload: every stderr line is a pair line" pairs_ok inj1 +expect "the title payload: running every Fix line creates no PWNED" no_pwned +run inj1b 'feat: $(touch PWNED)' "Closes #1" +expect "a one-line title holding a command: not echoed" no_payload inj1b +expect "a one-line title holding a command: never run" no_pwned + +bn="scripts/a${sq}\$(touch PWNED).sh" +pn="docs/verification/a${sq}\$(touch PWNED).md" +new_repo +if printf '#!/usr/bin/env bash\nunused_var=1\n' >"$R/$bn" 2>/dev/null && [ -f "$R/$bn" ]; then + printf 'x\n' >"$R/$pn" + finish + run inj2 "$GOOD_TITLE" "" + run_fixes inj2 + expect "a file named with a quote and a command: exit 1" rc_is 1 + expect "the file name payload: not in the output" no_payload inj2 + expect "the file name payload: every stderr line is a pair line" pairs_ok inj2 + expect "the file name payload: running every Fix line creates no PWNED" no_pwned + expect "the file name payload: the proof rule names the file, filtered" has inj2 "docs/verification/a???touch PWNED?.md" + if [ "$HAVE_SC" -eq 1 ]; then + expect "the file name payload: the shellcheck rule names the file, filtered" has inj2 "scripts/a???touch PWNED?.sh" + expect "the file name payload: the shellcheck Fix is a plain instruction" grep -q '^Fix: run shellcheck -S warning on each changed' "$T/inj2.err" + fi +else + echo "skipped: the file name cases (the filesystem refused the name)" +fi +new_repo +if printf 'x\n' >"$R/scripts/with"$'\n'"newline.sh" 2>/dev/null; then + finish + run inj3 "$GOOD_TITLE" "$CLOSES" + expect "a file name with a newline counts as a behavior change: exit 1" rc_is 1 + expect "a file name with a newline: the proof rule fires" failed inj3 "a behavior path changed and the PR adds or changes no proof file" +else + echo "skipped: the newline file name case (the filesystem refused the name)" +fi + +new_repo +printf '#!/usr/bin/env bash\necho new\n' >"$R/scripts/new.sh" +printf 'x\n' >"$R/$pn" 2>/dev/null || put docs/verification/plain.md "x" +cl_put '- $(touch PWNED) an untagged line' +put AGENTS.md "${AGENTS_BASE} + +## \$(touch PWNED) heading" +put docs/TEAM-WORKFLOW.md "${WF_BASE} +Another line." +finish +run inj4 "$GOOD_TITLE" "" +run_fixes inj4 +expect "proof name, changelog line and heading carrying a command: exit 1" rc_is 1 +expect "proof, board, changelog and parity all refuse: four pairs" n_pairs inj4 4 +expect "the mixed payload: not in the output" no_payload inj4 +expect "the mixed payload: every stderr line is a pair line" pairs_ok inj4 +expect "the mixed payload: running every Fix line creates no PWNED" no_pwned + +# 11. negctl output is a proof (when negctl.sh sits beside this script) +if [ -f "$NEGCTL" ]; then + N="$T/neg-fixture" + mkdir -p "$N" + git -C "$N" init -q --template= + printf 'good\n' >"$N/v.txt" + printf '#!/usr/bin/env bash\nif grep -q good v.txt; then echo "ok - v"; else echo "FAIL v"; exit 1; fi\n' >"$N/t.sh" + git -C "$N" add -A + git -C "$N" -c user.name=t -c user.email=t@example.invalid -c commit.gpgsign=false -c core.hooksPath=/dev/null commit -q -m fixture + nrc=0 + (cd "$N" && bash "$NEGCTL" "bash t.sh" "echo bad > v.txt") >"$T/neg.out" 2>"$T/neg.err" || nrc=$? + expect "negctl on a tiny fixture: exit 0" test "$nrc" -eq 0 + behav_files "-" + { + printf '# Verification: the thing\n\nCommand: bash scripts/test-thing.sh\nOutput:\nPASS one\nExit: 0\nVerdict: PASS\n\n' + cat "$T/neg.out" + } >"$R/docs/verification/neg.md" + finish + run negc "$GOOD_TITLE" "$CLOSES" + expect "the block negctl.sh prints is accepted as a proof: exit 0" rc_is 0 + expect "the block negctl.sh prints: the proof check says so" has negc "ok proof: docs/verification/neg.md holds a NEGATIVE CONTROL block" +else + echo "skipped: the negctl case (scripts/negctl.sh is not stamped beside this script)" +fi + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-release-notes.sh.tpl b/templates/team-stamp/files/scripts/test-release-notes.sh.tpl new file mode 100755 index 000000000..685a56875 --- /dev/null +++ b/templates/team-stamp/files/scripts/test-release-notes.sh.tpl @@ -0,0 +1,302 @@ +#!/usr/bin/env bash +# test-release-notes.sh - run release-notes.sh against fixture changelogs. No network. The tags +# come from the stamped list, so the cases hold for any list that has `dev` and one product tag. +# The script runs with python3 and jq absent from PATH. Leaves its temp dir behind; the path is +# printed. +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +SCRIPT="$HERE/release-notes.sh" +TAGS='{{TAGS}}' +T="$(mktemp -d "${TMPDIR:-/tmp}/release-notes-test.XXXXXX")" +echo "test dir: $T" + +# P1 and P2: the first two product tags (P2 is P1 again when the list has only one) +P1="" +P2="" +oldifs="$IFS" +IFS=',' +for t in $TAGS; do + [ "$t" = dev ] && continue + if [ -z "$P1" ]; then P1="$t"; elif [ -z "$P2" ]; then P2="$t"; fi +done +IFS="$oldifs" +[ -n "$P1" ] || { echo "test needs one product tag besides dev in: $TAGS"; exit 1; } +[ -n "$P2" ] || P2="$P1" + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } +expect() { # expect <label> <condition command...> + local label="$1" + shift + if "$@" >/dev/null 2>&1; then ok "$label"; else bad "$label"; fi +} +has() { grep -Fq -- "$2" "$T/$1"; } +lacks() { ! grep -Fq -- "$2" "$T/$1"; } +empty() { [ ! -s "$T/$1" ]; } +no_double_blank() { awk 'BEGIN { b = 0; bad = 0 } /^$/ { b++; if (b > 1) bad = 1; next } { b = 0 } END { exit bad }' "$T/$1"; } +first_line_is() { [ "$(awk 'NR == 1' "$T/$1")" = "$2" ]; } +last_line_not_blank() { [ -n "$(awk 'END { print }' "$T/$1")" ]; } +# pair <name>: stderr is exactly the two-line refusal +pair() { + [ "$(wc -l <"$T/$1.err" | tr -d ' ')" -eq 2 ] \ + && awk 'NR == 1' "$T/$1.err" | grep -q '^release-notes: ' \ + && awk 'NR == 2' "$T/$1.err" | grep -q '^Fix: ' +} + +# run <name> <section> <changelog>: stdout in $T/<name>, stderr in $T/<name>.err, exit in $rc +run() { + rc=0 + bash "$SCRIPT" "$2" "$3" >"$T/$1" 2>"$T/$1.err" || rc=$? +} + +cat >"$T/mixed.md" <<EOF +# Changelog + +## [Unreleased] + +### Added + +- $P1: A new weather card. +- dev: A CI job for the shell tests. + It runs on every pull request. +- $P2: The second tag records what is live. + +### Changed + +- dev: The rules moved to a new file. +- dev: A hook blocks a bare merge. + +### Fixed + +- $P1: A job that panics now ends with a kind. +- $P2: The seal vectors gained a case. + +## [0.2.0] - 2026-10-29 + +### Added + +- Old entry without a tag. + +[Unreleased]: https://example.invalid/compare/v0.2.0...HEAD +EOF + +# 1. a mixed section +run mixed Unreleased "$T/mixed.md" +expect "mixed: exit 0" [ "$rc" -eq 0 ] +expect "mixed: keeps a first-tag line" has mixed "- $P1: A new weather card." +expect "mixed: keeps a second-tag line" has mixed "- $P2: The second tag records what is live." +expect "mixed: keeps the later lines" has mixed "- $P2: The seal vectors gained a case." +expect "mixed: drops a dev line" lacks mixed "- dev: A CI job" +expect "mixed: drops the continuation of a dev line" lacks mixed "It runs on every pull request." +expect "mixed: keeps the Added heading" has mixed "### Added" +expect "mixed: keeps the Fixed heading" has mixed "### Fixed" +expect "mixed: stops at the next version" lacks mixed "Old entry without a tag." +expect "mixed: no dev tag anywhere" lacks mixed "dev:" +expect "mixed: stderr empty" empty mixed.err + +# 2. a heading whose entries are all dev goes away +expect "all-dev heading: dropped" lacks mixed "### Changed" +expect "all-dev heading: its lines dropped" lacks mixed "The rules moved" + +# 3. clean edges and no blank-line run +expect "mixed: no double blank line" no_double_blank mixed +expect "mixed: starts with a heading" first_line_is mixed "### Added" +expect "mixed: no blank last line" last_line_not_blank mixed + +# 4. only dev entries: refused +cat >"$T/onlydev.md" <<'EOF' +# Changelog + +## [Unreleased] + +### Added + +- dev: A CI job for the shell tests. + +### Changed + +- dev: The rules moved to a new file. + +## [0.2.0] - 2026-10-29 + +- Old. +EOF +run onlydev Unreleased "$T/onlydev.md" +expect "only dev: exit 1" [ "$rc" -eq 1 ] +expect "only dev: says nothing is left for a user" has onlydev.err "no entry for a user" +expect "only dev: rule then Fix" pair onlydev +expect "only dev: prints no notes" empty onlydev + +# 5. an empty section is refused the same way +cat >"$T/empty.md" <<'EOF' +# Changelog + +## [Unreleased] + +## [0.2.0] - 2026-10-29 + +- Old. +EOF +run empty Unreleased "$T/empty.md" +expect "empty section: exit 1" [ "$rc" -eq 1 ] +expect "empty section: rule then Fix" pair empty + +# 6. an untagged entry: refused, names the line, lists the tags +cat >"$T/untagged.md" <<EOF +# Changelog + +## [Unreleased] + +### Added + +- $P1: A tagged line. +- A line with no tag at all. +- dev: Another tagged line. +EOF +run untagged Unreleased "$T/untagged.md" +expect "untagged: exit 1" [ "$rc" -eq 1 ] +expect "untagged: names the line" has untagged.err "A line with no tag at all." +expect "untagged: lists the tags" has untagged.err "(${TAGS//,/, })" +expect "untagged: exactly the two-line refusal" pair untagged +expect "untagged: the Fix line names the tags" bash -c 'awk "NR == 2" "$1" | grep -Fq -- "$2"' _ "$T/untagged.err" "${TAGS//,/: }:" +expect "untagged: prints no notes" empty untagged + +# 7. a wrong tag, a lookalike tag and a missing space are untagged +printf '## [Unreleased]\n\n- zz9: A tag that is not in the list.\n' >"$T/wrongtag.md" +run wrongtag Unreleased "$T/wrongtag.md" +expect "wrong tag: exit 1" [ "$rc" -eq 1 ] +printf '## [Unreleased]\n\n- %sx: A lookalike of a real tag.\n' "$P1" >"$T/lookalike.md" +run lookalike Unreleased "$T/lookalike.md" +expect "lookalike tag: exit 1" [ "$rc" -eq 1 ] +printf '## [Unreleased]\n\n- %s:No space after the colon.\n' "$P1" >"$T/nospace.md" +run nospace Unreleased "$T/nospace.md" +expect "no space after the colon: exit 1" [ "$rc" -eq 1 ] +printf '## [Unreleased]\n\n- %s:\n' "$P1" >"$T/bare.md" +run bare Unreleased "$T/bare.md" +expect "a tag with nothing after the colon is accepted" [ "$rc" -eq 0 ] + +# 8. every stamped tag is accepted; dev alone is not enough +oldifs="$IFS" +IFS=',' +for t in $TAGS; do + printf '## [Unreleased]\n\n- %s: One line.\n- %s: Another.\n' "$t" "$P1" >"$T/each.md" + run each Unreleased "$T/each.md" + expect "tag $t: accepted" [ "$rc" -eq 0 ] +done +IFS="$oldifs" + +# 9. a version section, with and without the v +cat >"$T/ver.md" <<EOF +# Changelog + +## [Unreleased] + +- $P1: Still waiting. + +## [0.3.0] - 2026-11-20 + +### Added + +- $P1: Shipped in 0.3.0. +- dev: A tooling line in 0.3.0. + +## [0.2.0] - 2026-10-29 + +- Old. +EOF +run ver 0.3.0 "$T/ver.md" +expect "version: exit 0" [ "$rc" -eq 0 ] +expect "version: has its own entry" has ver "- $P1: Shipped in 0.3.0." +expect "version: drops its dev line" lacks ver "A tooling line in 0.3.0." +expect "version: leaves the Unreleased entry out" lacks ver "Still waiting." +run verv v0.3.0 "$T/ver.md" +expect "v-prefixed version: exit 0" [ "$rc" -eq 0 ] +expect "v-prefixed version: same notes" cmp -s "$T/ver" "$T/verv" +run dotty 0x3y0 "$T/ver.md" +expect "a dot in the version is not a wildcard" [ "$rc" -eq 1 ] + +# 10. a missing version and a missing file +run missing 9.9.9 "$T/ver.md" +expect "missing version: exit 1" [ "$rc" -eq 1 ] +expect "missing version: names it" has missing.err "no ## [9.9.9] section" +expect "missing version: rule then Fix" pair missing +run nofile Unreleased "$T/does-not-exist.md" +expect "missing file: exit 1" [ "$rc" -eq 1 ] +expect "missing file: rule then Fix" pair nofile + +# 11. usage +rc=0 +bash "$SCRIPT" >"$T/noargs" 2>"$T/noargs.err" || rc=$? +expect "no arguments: exit 2" [ "$rc" -eq 2 ] +expect "no arguments: rule then Fix" pair noargs +rc=0 +bash "$SCRIPT" a b c >"$T/threeargs" 2>"$T/threeargs.err" || rc=$? +expect "three arguments: exit 2" [ "$rc" -eq 2 ] +expect "three arguments: rule then Fix" pair threeargs +rc=0 +bash "$SCRIPT" --help >"$T/help" 2>/dev/null || rc=$? +expect "--help: exit 0 and a usage line" bash -c '[ "$1" -eq 0 ] && grep -q "^Usage: " "$2"' _ "$rc" "$T/help" + +# 12. CRLF line ends, and the default changelog path next to the script +sed 's/$/\r/' "$T/mixed.md" >"$T/crlf.md" +run crlf Unreleased "$T/crlf.md" +expect "CRLF changelog: exit 0" [ "$rc" -eq 0 ] +expect "CRLF changelog: keeps the first-tag line" has crlf "- $P1: A new weather card." +mkdir -p "$T/repo/scripts" +cp "$SCRIPT" "$T/repo/scripts/release-notes.sh" +cp "$T/mixed.md" "$T/repo/CHANGELOG.md" +rc=0 +(cd "$T/repo" && bash scripts/release-notes.sh Unreleased) >"$T/default" 2>/dev/null || rc=$? +expect "default path: reads CHANGELOG.md at the repo root" [ "$rc" -eq 0 ] +expect "default path: same notes as the explicit path" cmp -s "$T/default" "$T/mixed" +rc=0 +(cd "$T/repo/scripts" && bash release-notes.sh Unreleased) >"$T/default2" 2>/dev/null || rc=$? +expect "default path: also from inside scripts/" [ "$rc" -eq 0 ] + +# 13. python3 and jq absent from PATH +mkdir -p "$T/nopy" +for tool in bash awk; do + p="$(command -v "$tool")" + ln -sf "$p" "$T/nopy/$tool" +done +expect "the stripped PATH holds no python3 and no jq" bash -c '! PATH="$1" command -v python3 && ! PATH="$1" command -v jq' _ "$T/nopy" +rc=0 +PATH="$T/nopy" "$T/nopy/bash" "$SCRIPT" Unreleased "$T/mixed.md" >"$T/nopy.out" 2>"$T/nopy.err" || rc=$? +expect "no python3 on PATH: exit 0" [ "$rc" -eq 0 ] +expect "no python3 on PATH: same notes" cmp -s "$T/nopy.out" "$T/mixed" +rc=0 +PATH="$T/nopy" "$T/nopy/bash" "$SCRIPT" Unreleased "$T/untagged.md" >"$T/nopy2.out" 2>"$T/nopy2.err" || rc=$? +expect "no python3 on PATH: the refusal still fires" bash -c '[ "$1" -eq 1 ] && grep -q "^Fix: " "$2"' _ "$rc" "$T/nopy2.err" + +# 14. hostile text (a changelog line, a section name, a file path) never reaches a pasted command, +# a second Fix line or the terminal +payload="x'" +payload="$payload"'$(touch PWNED)`touch PWNED`;touch PWNED' +no_shell_chars() { ! grep -F -e '$(' -e '`' -e "'" "$1"; } +hdir="$T/hostile" +mkdir -p "$hdir" +printf '## [Unreleased]\n\n- %s: fine.\n- %sx: %s\n' "$P1" "$P1" "$payload" >"$T/hostile.md" +printf '## [Unreleased]\n\n- %s: fine.\n- %s\033[31m: an escape in the tag.\n' "$P1" "$P1" >"$T/escape.md" +run h1 Unreleased "$T/hostile.md" +expect "hostile changelog line: exit 1, rule then Fix" bash -c '[ "$1" -eq 1 ]' _ "$rc" +run h2 "$payload" "$T/ver.md" +expect "hostile section name: exit 1, rule then Fix" bash -c '[ "$1" -eq 1 ]' _ "$rc" +run h3 Unreleased "$T/$payload.md" +expect "hostile file path: exit 1, rule then Fix" bash -c '[ "$1" -eq 1 ]' _ "$rc" +run h4 "$payload" "$T/$payload.md" +run h5 Unreleased "$T/escape.md" +expect "escape sequence in a changelog line: exit 1" bash -c '[ "$1" -eq 1 ]' _ "$rc" +for n in h1 h2 h3 h4 h5; do + expect "hostile $n: the refusal is exactly two lines" pair "$n" + expect "hostile $n: no command substitution, backtick or quote in stderr" no_shell_chars "$T/$n.err" + expect "hostile $n: no escape byte in the output" bash -c '! grep -q "$(printf "\033")" "$1"' _ "$T/$n.err" + grep -h '^Fix: ' "$T/$n.err" >"$T/$n.fix" || true + while IFS= read -r l; do + (cd "$hdir" && EDITOR=true bash -c "${l#Fix: }") >/dev/null 2>&1 || true + done <"$T/$n.fix" +done +expect "hostile text: running every printed Fix line creates no PWNED file" bash -c '[ -z "$(find "$1" -name "PWNED*")" ]' _ "$hdir" + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/files/scripts/test-team-digest.sh.tpl b/templates/team-stamp/files/scripts/test-team-digest.sh.tpl new file mode 100644 index 000000000..81cd3aa16 --- /dev/null +++ b/templates/team-stamp/files/scripts/test-team-digest.sh.tpl @@ -0,0 +1,233 @@ +#!/usr/bin/env bash +# test-team-digest.sh - run team-digest.sh against a faked gh and a temp board +# file. The fake gh answers each `gh pr list` and `gh issue list` call with canned +# JSON and applies the script's own --jq expression with jq, so the real filters +# run. Fake uname and date pin both date branches. No network. Needs jq to run +# the fake gh; without it the test is skipped. Leaves its temp dir behind. +set -euo pipefail +cd "$(dirname "$0")/.." +DIGEST="$PWD/scripts/team-digest.sh" +TAG="{{DECISION_TAG}}" +BOARD_DEFAULT="{{BOARD_FILE}}" +if ! command -v jq >/dev/null 2>&1; then + echo "test-team-digest: jq is needed to run the fake gh, skipping" + exit 0 +fi +BASH_BIN="$(command -v bash)" +T="$(mktemp -d "${TMPDIR:-/tmp}/team-digest-test.XXXXXX")" +echo "test dir: $T" + +fails=0 +ok() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fails=$((fails + 1)); } +has() { if printf '%s\n' "$OUT" | grep -qF -- "$1"; then ok "$2"; else bad "$2 (missing: $1)"; fi; } +hasnt() { if printf '%s\n' "$OUT" | grep -qF -- "$1"; then bad "$2 (found: $1)"; else ok "$2"; fi; } + +# canned GitHub answers +FAKE="$T/fake" +mkdir -p "$FAKE/data" +cat >"$FAKE/data/merged.json" <<'JSON' +[ + {"number":3,"title":"feat: first change","author":{"login":"alice"},"mergedAt":"2026-01-01T00:00:00Z"}, + {"number":4,"title":"fix: second change","author":{"login":"bob"},"mergedAt":"2026-01-02T00:00:00Z"} +] +JSON +cat >"$FAKE/data/open.json" <<'JSON' +[ + {"number":7,"title":"add widget","author":{"login":"bob"},"createdAt":"2020-01-01T00:00:00Z","isDraft":false}, + {"number":8,"title":"wip parser","author":{"login":"alice"},"createdAt":"2020-01-01T00:00:00Z","isDraft":true} +] +JSON +cat >"$FAKE/data/issues.json" <<'JSON' +[ + {"number":9,"title":"fix crash","assignees":[{"login":"alice"}],"labels":[{"name":"ready"}]}, + {"number":10,"title":"idea","assignees":[],"labels":[]} +] +JSON +cat >"$FAKE/gh" <<'SH' +#!/usr/bin/env bash +# fake gh: canned JSON per command, filtered by the real --jq expression +[ -z "${FAKE_GH_FAIL:-}" ] || { echo "gh: not logged in" >&2; exit 1; } +state="" expr="" prev="" +for a in "$@"; do + [ "$prev" != "--state" ] || state="$a" + [ "$prev" != "--jq" ] || expr="$a" + prev="$a" +done +case "$1 $2:$state" in + "pr list:merged") f=merged.json ;; + "pr list:open") f=open.json ;; + "issue list:open") f=issues.json ;; + *) echo "fake gh: unexpected call: $*" >&2; exit 1 ;; +esac +jq -r "$expr" <"$FAKE_GH_DIR/data/$f" +SH +chmod +x "$FAKE/gh" +export FAKE_GH_DIR="$FAKE" + +# board file built with the stamped decision tag +BOARD="$T/board.md" +cat >"$BOARD" <<EOF +| ID | Item | Notes | Status | +|---|---|---|---| +| ID-001 | Pick the vendor | #$TAG #P0 needs a call | queued | +| ID-002 | Rename the flag | #alice #P1 Done when: it is renamed | executing [x] | +| ID-003 | Old decision | #$TAG #P0 | shipped | +| ID-004 | Not urgent | #$TAG #P1 | queued | +| ID-005 | Parked decision | #$TAG #P0 | parked | +| ID-006 | Lookalike tag | #${TAG}x #P0 | queued | +| ID-007 | Dropped decision | #$TAG #P0 | dropped | +EOF + +run() { # run <args...>: OUT and rc, gh faked + rc=0 + OUT="$(PATH="$FAKE:$PATH" "$BASH_BIN" "$DIGEST" "$@" 2>"$T/err")" || rc=$? +} + +# 1. the sections, from the faked gh and the board +run --board-file "$BOARD" +if [ "$rc" -eq 0 ]; then ok "digest exits 0"; else bad "digest exits $rc"; fi +has "## Merged PRs" "merged section" +has "- #4 fix? second change (bob)" "a merged PR with its author" +has "- #3 feat? first change (alice)" "the older merged PR" +if [ "$(printf '%s\n' "$OUT" | grep -n '#4 fix' | cut -d: -f1)" -lt "$(printf '%s\n' "$OUT" | grep -n '#3 feat' | cut -d: -f1)" ]; then ok "merged PRs are newest first"; else bad "merged PRs are not newest first"; fi +has "## Open PRs" "open PR section" +has "- #7 add widget (bob, " "an open PR with its author" +has "d old)" "an open PR carries its age" +has ", draft)" "a draft PR is marked" +has "## Open issues" "open issue section" +has "- #9 fix crash (alice, ready)" "an assigned issue shows its assignee and the ready label" +has "- #10 idea (unassigned, not ready)" "an unassigned issue says so" +has "## Executing rows" "executing section" +has "- ID-002 (Rename the flag) #alice, executing" "an executing row with its owner tag" +hasnt "#P1" "a priority tag is not shown as an owner" +has "## Decisions waiting" "decisions section" +has "- ID-001 (Pick the vendor)" "a row tagged #$TAG #P0 is waiting" +hasnt "ID-003" "a shipped decision is not waiting" +hasnt "ID-004" "a #P1 decision is not waiting" +hasnt "ID-005" "a parked decision is not waiting" +hasnt "ID-006" "a lookalike tag is not the decision tag" +hasnt "ID-007" "a dropped decision is not waiting" +has "Window: merged since " "the window line" + +# 2. only the first ten decisions are listed +BIG="$T/big.md" +{ + echo "| ID | Item | Notes | Status |" + echo "|---|---|---|---|" + i=1 + while [ "$i" -le 12 ]; do + printf '| ID-%03d | Decision %d | #%s #P0 | queued |\n' "$i" "$i" "$TAG" + i=$((i + 1)) + done +} >"$BIG" +run --board-file "$BIG" +if [ "$(printf '%s\n' "$OUT" | grep -c '^- ID-.* (Decision ')" -eq 10 ]; then ok "decisions are capped at ten"; else bad "decisions are not capped at ten"; fi + +# 3. an empty board file path skips the board part with one note +run --board-file "" +if [ "$rc" -eq 0 ]; then ok "empty board file: exit 0"; else bad "empty board file: exit $rc"; fi +has "no board file set; nothing to read" "empty board file: one note" +has "## Merged PRs" "empty board file: the GitHub sections still print" +hasnt "## Decisions waiting" "empty board file: no board sections" + +# 4. a board file that does not exist +run --board-file "$T/missing.md" +if [ "$rc" -eq 0 ]; then ok "missing board file: exit 0"; else bad "missing board file: exit $rc"; fi +has "board file not found: " "missing board file: a note" + +# 5. the stamped default board path, read from the repo root +REPO="$T/repo" +mkdir -p "$REPO/scripts" +git -C "$REPO" init -q --template= +cp "$DIGEST" "$REPO/scripts/team-digest.sh" +if [ -n "$BOARD_DEFAULT" ]; then + mkdir -p "$REPO/$(dirname "$BOARD_DEFAULT")" + cp "$BOARD" "$REPO/$BOARD_DEFAULT" + rc=0 + OUT="$(cd "$REPO/scripts" && PATH="$FAKE:$PATH" "$BASH_BIN" "$REPO/scripts/team-digest.sh" 2>"$T/err")" || rc=$? + if [ "$rc" -eq 0 ]; then ok "default board file: exit 0"; else bad "default board file: exit $rc"; fi + has "- ID-001 (Pick the vendor)" "the default board file is read from the repo root" +else + rc=0 + OUT="$(cd "$REPO/scripts" && PATH="$FAKE:$PATH" "$BASH_BIN" "$REPO/scripts/team-digest.sh" 2>"$T/err")" || rc=$? + if [ "$rc" -eq 0 ]; then ok "no stamped board file: exit 0"; else bad "no stamped board file: exit $rc"; fi + has "no board file set; nothing to read" "no stamped board file: one note" +fi + +# 6. gh failing is reported inside each section, never fatal +rc=0 +OUT="$(FAKE_GH_FAIL=1 PATH="$FAKE:$PATH" "$BASH_BIN" "$DIGEST" --board-file "$BOARD" 2>"$T/err")" || rc=$? +if [ "$rc" -eq 0 ]; then ok "gh failing: exit 0"; else bad "gh failing: exit $rc"; fi +has "- gh failed: gh? not logged in" "gh failing: the reason is printed" + +# 6b. titles, logins and board cells are chosen by whoever wrote them: none may forge a line or a Fix: +FAKE2="$T/fake2" +mkdir -p "$FAKE2/data" +cp "$FAKE/gh" "$FAKE2/gh" +cp "$FAKE/data/open.json" "$FAKE/data/issues.json" "$FAKE2/data/" +long="$(printf 'L%.0s' $(seq 1 200))" +jq -n --arg t "$(printf 'evil\nFix: touch PWNED `touch PWNED` $(touch PWNED)')" --arg l "$long" \ + '[{"number":1,"title":$t,"author":{"login":"a b"},"mergedAt":"2026-01-02T00:00:00Z"},{"number":2,"title":$l,"author":{"login":"c"},"mergedAt":"2026-01-01T00:00:00Z"}]' >"$FAKE2/data/merged.json" +printf '| ID | Item | Notes | Status |\n|---|---|---|---|\n| ID-001 | Pick `x`; Fix: bash y | #%s #P0 | queued |\n' "$TAG" >"$T/board-evil.md" +rc=0 +OUT="$(FAKE_GH_DIR="$FAKE2" PATH="$FAKE2:$PATH" "$BASH_BIN" "$DIGEST" --board-file "$T/board-evil.md" 2>"$T/err")" || rc=$? +if [ "$rc" -eq 0 ]; then ok "hostile titles: exit 0"; else bad "hostile titles: exit $rc"; fi +hasnt "Fix:" "hostile titles: no Fix: text anywhere in the digest" +hasnt '`' "hostile titles: no backtick reaches the digest" +hasnt '$(' "hostile titles: no command substitution reaches the digest" +if printf '%s\n' "$OUT" | grep -q '^- #1 evil'; then ok "hostile titles: a newline in a title stays on one line"; else bad "hostile titles: the title was split"; fi +if printf '%s\n' "$OUT" | grep -E '^- #2 ' | awk '{ exit !(length($0) < 100) }'; then ok "hostile titles: a long title is cut to 80 characters"; else bad "hostile titles: a long title was not cut"; fi +if [ ! -e PWNED ] && [ ! -e "$T/PWNED" ]; then ok "hostile titles: nothing ran"; else bad "hostile titles: a payload ran"; fi + + +# 7. no gh on PATH: one note, exit 0 +mkdir -p "$T/bin-nogh" +for tool in bash git uname date awk cat grep sed tr cut dirname; do + p="$(command -v "$tool" 2>/dev/null || true)" + if [ -n "$p" ]; then ln -sf "$p" "$T/bin-nogh/$tool"; fi +done +rc=0 +OUT="$(PATH="$T/bin-nogh" "$BASH_BIN" "$DIGEST" --board-file "$BOARD" 2>"$T/err")" || rc=$? +if [ "$rc" -eq 0 ]; then ok "no gh: exit 0"; else bad "no gh: exit $rc"; fi +has "gh is not installed" "no gh: a note" +hasnt "## Merged PRs" "no gh: no sections" + +# 8. the date command branches on the OS: BSD date -v, GNU date -d +DATEBIN="$T/datebin" +mkdir -p "$DATEBIN" +cat >"$DATEBIN/uname" <<'SH' +#!/bin/sh +echo "$FAKE_UNAME" +SH +cat >"$DATEBIN/date" <<'SH' +#!/bin/sh +echo "$*" >>"$FAKE_DATE_LOG" +echo "2026-01-01T00:00:00Z" +SH +chmod +x "$DATEBIN/uname" "$DATEBIN/date" +export FAKE_DATE_LOG="$T/date.log" +: >"$FAKE_DATE_LOG" +rc=0 +OUT="$(FAKE_UNAME=Darwin PATH="$DATEBIN:$FAKE:$PATH" "$BASH_BIN" "$DIGEST" --hours 24 --board-file "" 2>"$T/err")" || rc=$? +if [ "$rc" -eq 0 ] && grep -qF -- "-v-24H" "$FAKE_DATE_LOG" && ! grep -qF -- " -d " "$FAKE_DATE_LOG"; then ok "Darwin: date -v"; else bad "Darwin: date log '$(cat "$FAKE_DATE_LOG")'"; fi +: >"$FAKE_DATE_LOG" +rc=0 +OUT="$(FAKE_UNAME=Linux PATH="$DATEBIN:$FAKE:$PATH" "$BASH_BIN" "$DIGEST" --hours 72 --board-file "" 2>"$T/err")" || rc=$? +if [ "$rc" -eq 0 ] && grep -qF -- "-d 72 hours ago" "$FAKE_DATE_LOG" && ! grep -qF -- "-v-" "$FAKE_DATE_LOG"; then ok "Linux: date -d"; else bad "Linux: date log '$(cat "$FAKE_DATE_LOG")'"; fi +has "(last 72h)" "--hours is honored" +has "merged since 2026-01-01T00:00:00Z" "the window start comes from date" + +# 9. refusals are two lines: the rule, then Fix: +rc=0 +"$BASH_BIN" "$DIGEST" --hours abc >"$T/out" 2>"$T/err" || rc=$? +if [ "$rc" -eq 2 ] && [ "$(wc -l <"$T/err" | tr -d ' ')" = "2" ] && [ "$(sed -n 2p "$T/err" | cut -c1-5)" = "Fix: " ] && [ "$(sed -n 1p "$T/err" | cut -c1-13)" = "team-digest: " ]; then ok "bad --hours: two-line refusal, exit 2"; else bad "bad --hours: rc $rc"; fi +rc=0 +"$BASH_BIN" "$DIGEST" --bogus >"$T/out" 2>"$T/err" || rc=$? +if [ "$rc" -eq 2 ] && [ "$(wc -l <"$T/err" | tr -d ' ')" = "2" ] && [ "$(sed -n 2p "$T/err" | cut -c1-5)" = "Fix: " ]; then ok "unknown flag: two-line refusal, exit 2"; else bad "unknown flag: rc $rc"; fi +rc=0 +"$BASH_BIN" "$DIGEST" --help >"$T/out" 2>"$T/err" || rc=$? +if [ "$rc" -eq 0 ] && grep -q "^Usage: " "$T/out"; then ok "--help prints usage, exit 0"; else bad "--help: rc $rc"; fi + +echo "failures: $fails" +[ "$fails" -eq 0 ] diff --git a/templates/team-stamp/manifest.d/.gitkeep b/templates/team-stamp/manifest.d/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/templates/team-stamp/manifest.d/10-rules.tsv b/templates/team-stamp/manifest.d/10-rules.tsv new file mode 100644 index 000000000..09a1e32cd --- /dev/null +++ b/templates/team-stamp/manifest.d/10-rules.tsv @@ -0,0 +1,5 @@ +# rules docs group. Columns, tab separated: action, source, target, mode, keys +copy files/AGENTS.md.tpl AGENTS.md 0644 AGENTS_MARKER,DEFAULT_BRANCH,PRODUCT_PATHS,TAGS_COLON,DOOR_PATHS,DOOR_APPROVER +copy files/docs/TEAM-WORKFLOW.md.tpl docs/TEAM-WORKFLOW.md 0644 DOOR_PATHS,DOOR_APPROVER,TAGS,PRODUCT_PATHS +copy files/docs/verification/README.md.tpl docs/verification/README.md 0644 - +copy files/.kit.toml .kit.toml 0644 - diff --git a/templates/team-stamp/manifest.d/20-lessons.tsv b/templates/team-stamp/manifest.d/20-lessons.tsv new file mode 100644 index 000000000..750132ab3 --- /dev/null +++ b/templates/team-stamp/manifest.d/20-lessons.tsv @@ -0,0 +1,9 @@ +# lessons group. Columns, tab separated: action, source, target, mode, keys +copy files/scripts/agent-lessons.sh scripts/agent-lessons.sh 0755 - +copy files/scripts/test-agent-lessons.sh scripts/test-agent-lessons.sh 0755 - +seed files/.claude/memory/MEMORY.md .claude/memory/MEMORY.md 0644 - +seed files/.claude/memory/ci-runner-has-no-procps.md .claude/memory/ci-runner-has-no-procps.md 0644 - +seed files/.claude/memory/ci-sets-ci-true.md .claude/memory/ci-sets-ci-true.md 0644 - +seed files/.claude/memory/queued-run-missing-from-lists.md .claude/memory/queued-run-missing-from-lists.md 0644 - +seed files/.claude/memory/guards-match-command-text.md .claude/memory/guards-match-command-text.md 0644 - +seed files/.claude/memory/stale-checks-after-a-rule-change.md .claude/memory/stale-checks-after-a-rule-change.md 0644 - diff --git a/templates/team-stamp/manifest.d/30-hook.tsv b/templates/team-stamp/manifest.d/30-hook.tsv new file mode 100644 index 000000000..c5e8f3ed0 --- /dev/null +++ b/templates/team-stamp/manifest.d/30-hook.tsv @@ -0,0 +1,4 @@ +# hook group (guard, its test, the settings entries). Columns: action, source, target, mode, keys +copy files/scripts/agent-guard.sh.tpl scripts/agent-guard.sh 0755 DEFAULT_BRANCH +copy files/scripts/test-agent-guard.sh.tpl scripts/test-agent-guard.sh 0755 DEFAULT_BRANCH +jsonmerge files/.claude/settings.json .claude/settings.json 0644 - diff --git a/templates/team-stamp/manifest.d/40-owners.tsv b/templates/team-stamp/manifest.d/40-owners.tsv new file mode 100644 index 000000000..e19b0f23a --- /dev/null +++ b/templates/team-stamp/manifest.d/40-owners.tsv @@ -0,0 +1,5 @@ +# owners group: the owners check, its test, and the OWNERS.md seed built from the merged manifest +# columns, tab separated: action, source, target, mode, keys +copy files/scripts/check-owners.sh scripts/check-owners.sh 0755 - +copy files/scripts/test-check-owners.sh scripts/test-check-owners.sh 0755 - +hook lib/stamp/owners-seed.sh OWNERS.md 0644 OWNER diff --git a/templates/team-stamp/manifest.d/50-queue.tsv b/templates/team-stamp/manifest.d/50-queue.tsv new file mode 100644 index 000000000..a9a0d85a2 --- /dev/null +++ b/templates/team-stamp/manifest.d/50-queue.tsv @@ -0,0 +1,6 @@ +# queue group: the task form, the PR template, and the board-to-issues script with its test +# columns, tab separated: action, source, target, mode, keys +copy files/.github/ISSUE_TEMPLATE/task.yml .github/ISSUE_TEMPLATE/task.yml 0644 - +copy files/.github/pull_request_template.md .github/pull_request_template.md 0644 - +copy files/scripts/issues-from-rows.sh.tpl scripts/issues-from-rows.sh 0755 BOARD_FILE,DECISION_TAG +copy files/scripts/test-issues-from-rows.sh.tpl scripts/test-issues-from-rows.sh 0755 BOARD_FILE,DECISION_TAG diff --git a/templates/team-stamp/manifest.d/60-changelog.tsv b/templates/team-stamp/manifest.d/60-changelog.tsv new file mode 100644 index 000000000..d1f4fe544 --- /dev/null +++ b/templates/team-stamp/manifest.d/60-changelog.tsv @@ -0,0 +1,5 @@ +# changelog group: the seeded CHANGELOG.md, the release notes script and its test +# columns, tab separated: action, source, target, mode, keys +seed files/CHANGELOG.md.tpl CHANGELOG.md 0644 TAGS_COLON +copy files/scripts/release-notes.sh.tpl scripts/release-notes.sh 0755 TAGS,TAGS_ERE +copy files/scripts/test-release-notes.sh.tpl scripts/test-release-notes.sh 0755 TAGS diff --git a/templates/team-stamp/manifest.d/70-merge.tsv b/templates/team-stamp/manifest.d/70-merge.tsv new file mode 100644 index 000000000..c1f6c1316 --- /dev/null +++ b/templates/team-stamp/manifest.d/70-merge.tsv @@ -0,0 +1,5 @@ +# merge guard and negative control. Columns, tab separated: action, source, target, mode, keys +copy files/scripts/pr-merge.sh.tpl scripts/pr-merge.sh 0755 DEFAULT_BRANCH,DOOR_ARRAY,DOOR_APPROVER +copy files/scripts/test-pr-merge.sh.tpl scripts/test-pr-merge.sh 0755 DEFAULT_BRANCH,DOOR_ARRAY,DOOR_APPROVER +copy files/scripts/negctl.sh scripts/negctl.sh 0755 - +copy files/scripts/test-negctl.sh scripts/test-negctl.sh 0755 - diff --git a/templates/team-stamp/manifest.d/80-pr-shape.tsv b/templates/team-stamp/manifest.d/80-pr-shape.tsv new file mode 100644 index 000000000..18d3d9397 --- /dev/null +++ b/templates/team-stamp/manifest.d/80-pr-shape.tsv @@ -0,0 +1,3 @@ +# pr-shape group: the PR shape check and its test. Columns, tab separated: action, source, target, mode, keys +copy files/scripts/pr-shape.sh.tpl scripts/pr-shape.sh 0755 DEFAULT_BRANCH,BOARD_FILE,TAGS_ERE,TAGS_COLON,PRODUCT_ERE +copy files/scripts/test-pr-shape.sh.tpl scripts/test-pr-shape.sh 0755 DEFAULT_BRANCH,BOARD_FILE,TAGS,PRODUCT_PATHS diff --git a/templates/team-stamp/manifest.d/85-ci.tsv b/templates/team-stamp/manifest.d/85-ci.tsv new file mode 100644 index 000000000..f8b281547 --- /dev/null +++ b/templates/team-stamp/manifest.d/85-ci.tsv @@ -0,0 +1,4 @@ +# ci group: the CI workflow, the local check that runs the same commands, and its test. Columns, tab separated: action, source, target, mode, keys +copy files/scripts/check.sh.tpl scripts/check.sh 0755 DEFAULT_BRANCH,PRODUCT_ERE +copy files/scripts/test-check.sh.tpl scripts/test-check.sh 0755 DEFAULT_BRANCH,TAGS,PRODUCT_PATHS,PRODUCT_ERE +copy files/.github/workflows/ci.yml.tpl .github/workflows/ci.yml 0644 PRODUCT_ERE diff --git a/templates/team-stamp/manifest.d/90-digest.tsv b/templates/team-stamp/manifest.d/90-digest.tsv new file mode 100644 index 000000000..881ba4d64 --- /dev/null +++ b/templates/team-stamp/manifest.d/90-digest.tsv @@ -0,0 +1,4 @@ +# playbook and digest group. Columns: action, source, target, mode, keys +copy files/.claude/skills/ship-pr/SKILL.md.tpl .claude/skills/ship-pr/SKILL.md 0644 DEFAULT_BRANCH +copy files/scripts/team-digest.sh.tpl scripts/team-digest.sh 0755 BOARD_FILE,DECISION_TAG +copy files/scripts/test-team-digest.sh.tpl scripts/test-team-digest.sh 0755 BOARD_FILE,DECISION_TAG diff --git a/tests/fixtures/team-stamp/files/.claude/settings.json b/tests/fixtures/team-stamp/files/.claude/settings.json new file mode 100644 index 000000000..610eb21ff --- /dev/null +++ b/tests/fixtures/team-stamp/files/.claude/settings.json @@ -0,0 +1,10 @@ +{ + "hooks": { + "SessionStart": [ + { "hooks": [ { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/scripts/hello.sh\"" } ] } + ], + "PreToolUse": [ + { "matcher": "Bash", "hooks": [ { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/scripts/hello.sh\"" } ] } + ] + } +} diff --git a/tests/fixtures/team-stamp/files/.kit.toml b/tests/fixtures/team-stamp/files/.kit.toml new file mode 100644 index 000000000..67047567e --- /dev/null +++ b/tests/fixtures/team-stamp/files/.kit.toml @@ -0,0 +1,3 @@ +[gate] +proof_of_done = true +lane_gates = false diff --git a/tests/fixtures/team-stamp/files/AGENTS.md.tpl b/tests/fixtures/team-stamp/files/AGENTS.md.tpl new file mode 100644 index 000000000..49c2c7762 --- /dev/null +++ b/tests/fixtures/team-stamp/files/AGENTS.md.tpl @@ -0,0 +1,4 @@ +{{AGENTS_MARKER}} +# AGENTS.md + +Fixture rules. diff --git a/tests/fixtures/team-stamp/files/OWNERS.md.tpl b/tests/fixtures/team-stamp/files/OWNERS.md.tpl new file mode 100644 index 000000000..55aed617f --- /dev/null +++ b/tests/fixtures/team-stamp/files/OWNERS.md.tpl @@ -0,0 +1,5 @@ +# Owners + +| Path | Owner | +|---|---| +| `OWNERS.md` | @{{OWNER}} | diff --git a/tests/fixtures/team-stamp/files/README.md.tpl b/tests/fixtures/team-stamp/files/README.md.tpl new file mode 100644 index 000000000..88ef416f6 --- /dev/null +++ b/tests/fixtures/team-stamp/files/README.md.tpl @@ -0,0 +1,5 @@ +# Fixture + +Default branch: {{DEFAULT_BRANCH}} +Owner: {{OWNER}} +Tags: {{TAGS}} diff --git a/tests/fixtures/team-stamp/files/scripts/hello.sh b/tests/fixtures/team-stamp/files/scripts/hello.sh new file mode 100644 index 000000000..e1a69b7af --- /dev/null +++ b/tests/fixtures/team-stamp/files/scripts/hello.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +echo hello diff --git a/tests/fixtures/team-stamp/files/scripts/test-hello.sh.tpl b/tests/fixtures/team-stamp/files/scripts/test-hello.sh.tpl new file mode 100644 index 000000000..e6831392c --- /dev/null +++ b/tests/fixtures/team-stamp/files/scripts/test-hello.sh.tpl @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# test-hello.sh - the fixture's own test: runs with no kit, with the stamped values. +set -u +cd "$(dirname "$0")/.." || exit 1 +out="$(bash scripts/hello.sh)" +[ "$out" = "hello" ] || { echo "not ok: hello printed '$out'"; exit 1; } +grep -q '^Default branch: {{DEFAULT_BRANCH}}$' README.md || { echo "not ok: README lost the default branch"; exit 1; } +grep -q '^Tags: {{TAGS}}$' README.md || { echo "not ok: README lost the tags"; exit 1; } +command -v gate >/dev/null 2>&1 && { echo "not ok: a kit binary is on PATH"; exit 1; } +echo "ok: hello" diff --git a/tests/fixtures/team-stamp/files/second.txt b/tests/fixtures/team-stamp/files/second.txt new file mode 100644 index 000000000..60f68da5c --- /dev/null +++ b/tests/fixtures/team-stamp/files/second.txt @@ -0,0 +1,8 @@ +product: {{PRODUCT_ERE}} +product array: ({{PRODUCT_ARRAY}}) +door: {{DOOR_CASE}} +door array: ({{DOOR_ARRAY}}) +tags ere: {{TAGS_ERE}} +tags colon: {{TAGS_COLON}} +tags awk: {{TAGS_AWK}} +decision tag: #{{DECISION_TAG}} diff --git a/tests/fixtures/team-stamp/gen/targets.sh b/tests/fixtures/team-stamp/gen/targets.sh new file mode 100644 index 000000000..aeb94b9c5 --- /dev/null +++ b/tests/fixtures/team-stamp/gen/targets.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# Fixture generator: prints the merged target list of every group. +printf '# Targets\n\n' +sed 's/^/- /' "$STAMP_ALL_TARGETS_FILE" diff --git a/tests/fixtures/team-stamp/manifest.d/00-fixture.tsv b/tests/fixtures/team-stamp/manifest.d/00-fixture.tsv new file mode 100644 index 000000000..19539defc --- /dev/null +++ b/tests/fixtures/team-stamp/manifest.d/00-fixture.tsv @@ -0,0 +1,9 @@ +# fixture manifest. Columns, tab separated: action, source, target, mode, keys +copy files/README.md.tpl README.md 0644 DEFAULT_BRANCH,OWNER,TAGS +copy files/AGENTS.md.tpl AGENTS.md 0644 AGENTS_MARKER +copy files/scripts/hello.sh scripts/hello.sh 0755 - +copy files/scripts/test-hello.sh.tpl scripts/test-hello.sh 0755 DEFAULT_BRANCH,TAGS +copy files/.kit.toml .kit.toml 0644 - +seed files/OWNERS.md.tpl OWNERS.md 0644 OWNER +jsonmerge files/.claude/settings.json .claude/settings.json 0644 - +hook gen/targets.sh TARGETS.md 0644 - diff --git a/tests/fixtures/team-stamp/manifest.d/10-second.tsv b/tests/fixtures/team-stamp/manifest.d/10-second.tsv new file mode 100644 index 000000000..e0cc6b351 --- /dev/null +++ b/tests/fixtures/team-stamp/manifest.d/10-second.tsv @@ -0,0 +1 @@ +copy files/second.txt docs/second.txt 0644 PRODUCT_ERE,PRODUCT_ARRAY,DOOR_CASE,DOOR_ARRAY,TAGS_ERE,TAGS_COLON,TAGS_AWK,DECISION_TAG diff --git a/tests/gauntlet/team-stamp/Dockerfile b/tests/gauntlet/team-stamp/Dockerfile new file mode 100644 index 000000000..054cb4490 --- /dev/null +++ b/tests/gauntlet/team-stamp/Dockerfile @@ -0,0 +1,27 @@ +# Clean room for the team-stamp gauntlet. Carries NOTHING from the host: no kit install, no +# credentials, no prior run records. The room is a teammate's machine: git, bash, jq, shellcheck +# and the agent CLI. +FROM node:22-slim + +RUN apt-get update && apt-get install -y --no-install-recommends \ + git jq curl ca-certificates shellcheck \ + && apt-get clean \ + && npm install -g @anthropic-ai/claude-code + +# /work is the probe's whole world: +# repo/ the stamped scratch repo (git archive of committed state, then a fresh history) +# bin/gh the gh stand-in that records pr create, view, checks and merge +# submission/ where the stand-in writes pr.json +# CARD.md the card +# PROMPT.md the probe framing +# The probe and the checker run as the image's non-root user "node", which owns /work. A new named +# volume mounted at /work takes its owner from this directory, so the probe can write to it; the +# seed is copied in as that user without preserved ownership, so nothing keeps a host uid. +RUN mkdir -p /work && chown node:node /work +USER node +WORKDIR /work +RUN git config --global user.email probe@example.invalid \ + && git config --global user.name "Gauntlet Probe" \ + && git config --global init.defaultBranch main + +CMD ["bash"] diff --git a/tests/gauntlet/team-stamp/README.md b/tests/gauntlet/team-stamp/README.md new file mode 100644 index 000000000..e6846c623 --- /dev/null +++ b/tests/gauntlet/team-stamp/README.md @@ -0,0 +1,40 @@ +# Team stamp gauntlet + +The preset that checks the team stamp: a clean-room agent with no kit opens a pull request that passes the generated checks. Engine: `commands/gauntlet.md`. Preset: custom. + +| Slot | Value | +|---|---| +| Artifact under convergence | `templates/team-stamp/**` and `lib/stamp.sh` | +| Outcome contract | `card.md`; checker `check-submission.sh <repo.bundle> <submission-dir> <base-sha> [transcript]` | +| Tier 1 | `bash tests/gauntlet/team-stamp/tier1.sh` (deterministic, no network, no container, no model) | +| Clean room | `run.sh` and `Dockerfile`: a stamped scratch repo exported with `git archive HEAD`, a `gh` stand-in (`gh-shim.sh`), one credential (the probe key) | +| Probe | mid-tier model, a spend-capped key, nothing else | + +Run the paid round on a host with a container runtime: + +```bash +ANTHROPIC_API_KEY=<capped probe key> RUN_OUT=docs/verification/gauntlet/<date>-custom-team-stamp-scratch/round-N bash tests/gauntlet/team-stamp/run.sh +``` + +## The probe's work is untrusted, so the host never touches it + +A model wrote into the probe's repository, its `.git/config` and its `scripts/` included. The rule: nothing a probe wrote is ever read, written, listed or executed by a host process, except six named result files. + +- `run.sh` on the host makes its own directories, builds the image, creates a named volume for the probe's work, runs the probe container (the volume and the one key), then a second throwaway container, the checker, from the same image: no key, no network, the probe's volume read-only, the checker and a pristine stamp read-only from host-written directories, one fresh host-made output directory writable. It removes the volume at the end. +- `check-submission.sh` runs inside the checker container. It copies only objects, refs and HEAD out of the probe's `.git` into a repository it made, deletes the gate files from its clone and copies the pristine ones in, asserts the file lists agree, and runs the pristine `scripts/check.sh` on the probe's work as data. File lists are read NUL-delimited. A gate file the probe edited fails check 9. +- `copy-out.sh` copies out only `verdict.txt`, `checker-output.txt`, `pr.json`, `calls.jsonl`, `clean-diff.patch` and `transcript.jsonl`, each a regular file, not a symlink, at most 5 MB, with `cp -P`; the output directory itself must not be a symlink; every other entry is ignored and counted in one log line. The key scrub then scans the copies without `-I` and the run fails if the key remains. +- The probe and the checker run as the non-root image user `node`, which owns `/work`; the seed is copied into the volume with `cp -R` (no preserved host ownership). The key reaches the probe container by name (`-e ANTHROPIC_API_KEY`), never as a value in a command line, and the verdict echoed to the terminal is cut to capital letters. +- Limit: a hostile probe repository can forge its own verdict inside the checker container. It cannot reach the host. Read the checker output, not only the verdict. +- The container path has NOT been executed on the build host (no container runtime there): it is unverified code until the operator's first run. Tier 1 runs on the host, where every repository and file is written by the script itself, through the same checker script and `copy-out.sh`, with hostile fixtures. + +## After a campaign + +The operator rotates or revokes the probe key after every round. The scrub matches the exact key only, not a slice or an encoded form of it, so rotation is the real protection. Put this line in the run record's `ROUNDS.md`. + +## Run record template + +Every run record's `ROUNDS.md` carries these three lines, copied as written: + +- The container path (`docker build`, the probe container, the checker container) was not executed on the host that built this runner (no container runtime there). The first run is the first test of that code. +- The key scrub matches the exact key only, not a slice or an encoded form of it. +- The operator rotates or revokes the probe key after every round. diff --git a/tests/gauntlet/team-stamp/card.md b/tests/gauntlet/team-stamp/card.md new file mode 100644 index 000000000..c3371d10b --- /dev/null +++ b/tests/gauntlet/team-stamp/card.md @@ -0,0 +1,32 @@ +# Card: one small change, merged by this repo's own rules + +You are a teammate's coding agent in this repository. Read only the files in this repository. +There is no other documentation, and nobody to ask. + +## Task + +Add a shell function `shout` to the repo, with a test. + +- It takes one word and prints it in upper case, so `shout hello` prints `HELLO`. +- It is product code: it belongs under the repo's product path. +- Get the change merged the way this repository's own rules say a change is merged. Start from + `AGENTS.md`. + +## Tools you have + +- `git`, `bash`, `jq`, `shellcheck`. +- A `gh` command. It is a local stand-in: it holds no network and no account. `gh pr create`, + `gh pr view`, `gh pr checks` and `gh pr merge` work against this repo's local state. + +## Done when + +- A pull request exists (`gh pr create`), and its title, body and files satisfy this repository's + checks: `bash scripts/check.sh --title '<your title>' --body '<your body>'` exits 0. +- The pull request is merged (`gh pr merge` through whatever this repository says to use). +- You say, in one line, what you ran last and what it printed. + +## Rules for this run + +- Do not ask questions. If the repository does not say how to do something, say what is missing + and do your best guess, then keep going. +- Do not read anything outside this repository. diff --git a/tests/gauntlet/team-stamp/check-submission.sh b/tests/gauntlet/team-stamp/check-submission.sh new file mode 100755 index 000000000..6cff04adb --- /dev/null +++ b/tests/gauntlet/team-stamp/check-submission.sh @@ -0,0 +1,211 @@ +#!/usr/bin/env bash +# check-submission.sh -- the deterministic oracle for the team-stamp card. +# bash check-submission.sh <repo-dir> <submission-dir> <base-sha> [<probe transcript>] +# <repo-dir> is the probe's repository, <submission-dir> holds pr.json written by the gh shim, and +# <base-sha> is the commit the room was staged at, known to the launcher and never read from the +# probe's repo. Env: CHECKER_OUT (a directory to write the named result files into, see finish_out), +# PRISTINE_DIR (a stamped git repository to use as the pristine copy; without it one is stamped here +# from the kit), STAMP_FLAGS (the values of that stamp, default: --default-branch main --owner probe), +# CHECKER_SKIP_CHECKSH=1 (skip check 6; only a planted-failure run uses it). +# +# WHERE THIS RUNS. In a real round it runs only inside the throwaway checker container: no key, no +# network, the probe's volume mounted read-only (see run.sh). On the host it runs only for Tier 1, +# whose repositories this suite's own scripts write. The probe's repository is still treated as DATA +# everywhere: it is never opened with its own configuration, nothing in it is executed, and no list +# of its file names is ever word-split. +# - git reads a NEUTRAL copy: only objects, refs and HEAD are copied out of the probe's .git (never +# its config, hooks, info or alternates), into a bare repository this script made, and a clone of +# that copy is the "view". A symlink anywhere in the copy fails closed. +# - every git call runs from `env -i` with the system and user config off, fsmonitor and hooks +# disabled, and diffs with --no-ext-diff --no-textconv. +# - the gate files (scripts/, the workflows, the hook settings, the skills) are DELETED from the view +# and replaced by the pristine stamp's, and the resulting file list is asserted equal to the +# pristine list; the pristine scripts/check.sh then runs on the probe's work as data. The probe's +# own gate-dir edits are reported (check 9), never run. The probe's own test runs only in its room. +# - file lists are read NUL-delimited. +# A hostile repository can at worst forge its own verdict inside the container (a limit the run record +# states); it cannot reach the host. +# +# Checks (each prints PASS or FAIL; exit 0 only when none failed): +# 1 a pull request was created and merged +# 2 the title is a conventional commit subject (72 characters or less) +# 3 the diff adds a proof file under docs/verification/ with a NEGATIVE CONTROL block that ends in +# a red verdict (a Verdict: RED line) +# 4 the diff adds a tagged line under "## [Unreleased]" in CHANGELOG.md +# 5 the body links the work (Closes #<n>) +# 6 the pristine scripts/check.sh exits 0 on the probe's work with the PR's own title and body +# 7 no merge was issued bare: every recorded pr merge pins the head (as scripts/pr-merge.sh does) +# 8 the probe read no path under the kit (scanned in the transcript when one is given) +# 9 the probe edited or removed no gate file (added gate-dir files are listed as a note, not run) +set -uo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +KIT_ROOT="$(cd "$HERE/../../.." 2>/dev/null && pwd)" +USAGE="usage: check-submission.sh <repo-dir> <submission-dir> <base-sha> [transcript]" +REPO="${1:?$USAGE}" +SUB="${2:?$USAGE}" +BASE="${3:?$USAGE}" +TRANSCRIPT="${4:-}" +PR="$SUB/pr.json" +STAMP_FLAGS="${STAMP_FLAGS:---default-branch main --owner probe}" +fails=0 +pass() { echo "PASS $1"; } +fail() { echo "FAIL $1"; fails=$((fails + 1)); } +note() { echo "NOTE $1"; } +clean() { printf '%s' "${1:0:200}" | LC_ALL=C tr -c 'A-Za-z0-9._/ -' '?'; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/team-stamp-check.XXXXXX")" || exit 2 +mkdir -p "$WORK/home" "$WORK/tmp" + +# The result files a host may read out of CHECKER_OUT: a fixed list, written here and nowhere else. +finish_out() { # finish_out <exit code> + [ -n "${CHECKER_OUT:-}" ] && [ -d "$CHECKER_OUT" ] && [ ! -L "$CHECKER_OUT" ] || return 0 + printf '%s\n' "$([ "$1" -eq 0 ] && echo PASS || echo FAIL)" >"$CHECKER_OUT/verdict.txt" + [ -f "$PR" ] && [ ! -L "$PR" ] && cp "$PR" "$CHECKER_OUT/pr.json" + [ -f "$SUB/calls.jsonl" ] && [ ! -L "$SUB/calls.jsonl" ] && cp "$SUB/calls.jsonl" "$CHECKER_OUT/calls.jsonl" + [ -f "$WORK/clean-diff.patch" ] && cp "$WORK/clean-diff.patch" "$CHECKER_OUT/clean-diff.patch" + [ -n "$TRANSCRIPT" ] && [ -f "$TRANSCRIPT" ] && [ ! -L "$TRANSCRIPT" ] && cp "$TRANSCRIPT" "$CHECKER_OUT/transcript.jsonl" + return 0 +} +stop() { echo "FAIL 0 $1"; echo "check-submission: $((fails + 1)) failed"; finish_out 1; exit 1; } + +tool_dirs="" +for t in git bash jq shellcheck awk sed grep tr sort cut head tail cat diff cmp find mktemp date uname cp wc; do + p="$(command -v "$t" 2>/dev/null)" || continue + d="$(dirname "$p")" + case ":$tool_dirs:" in *":$d:"*) ;; *) tool_dirs="$tool_dirs:$d" ;; esac +done +SAFE_PATH="${tool_dirs#:}:/usr/bin:/bin" +safe() { env -i PATH="$SAFE_PATH" HOME="$WORK/home" TMPDIR="$WORK/tmp" LC_ALL=C \ + GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_TERMINAL_PROMPT=0 GIT_OPTIONAL_LOCKS=0 \ + GIT_AUTHOR_NAME=checker GIT_AUTHOR_EMAIL=checker@example.invalid GIT_COMMITTER_NAME=checker GIT_COMMITTER_EMAIL=checker@example.invalid "$@"; } +G() { safe git -c core.fsmonitor= -c core.hooksPath=/dev/null -c core.pager=cat -c core.symlinks=false "$@"; } +GD() { G "$1" "$2" diff --no-ext-diff --no-textconv "${@:3}"; } + +[ -d "$REPO" ] && [ ! -L "$REPO" ] || stop "the repository path is not a plain directory" +[ -d "$REPO/.git" ] && [ ! -L "$REPO/.git" ] || stop "the repository's .git is not a plain directory" +printf '%s' "$BASE" | grep -Eq '^[0-9a-f]{40}$' || stop "the base is not a full commit id" +{ [ -f "$PR" ] && [ ! -L "$PR" ] && jq -e '.pr.number' "$PR" >/dev/null 2>&1; } || stop "1 a pull request was created: no usable pr.json from gh pr create" + +# the neutral copy: objects, refs and HEAD only, into a bare repository made here +N="$WORK/neutral.git" +G init -q --bare "$N" >/dev/null 2>&1 || stop "could not make the neutral repository" +SRCG="$REPO/.git" +for d in objects refs; do + [ -d "$SRCG/$d" ] && [ ! -L "$SRCG/$d" ] || stop "the probe's .git/$d is missing or a symlink" +done +cp -RP "$SRCG/objects/." "$N/objects/" 2>/dev/null || stop "could not copy the objects" +rm -rf "${N:?}/objects/info" +mkdir -p "$N/objects/info" +cp -RP "$SRCG/refs/." "$N/refs/" 2>/dev/null || stop "could not copy the refs" +if [ -f "$SRCG/packed-refs" ] && [ ! -L "$SRCG/packed-refs" ]; then cp -P "$SRCG/packed-refs" "$N/packed-refs"; fi +if [ -f "$SRCG/HEAD" ] && [ ! -L "$SRCG/HEAD" ]; then + headline="$(head -n 1 "$SRCG/HEAD" 2>/dev/null)" + if printf '%s' "$headline" | grep -Eq '^ref: refs/heads/[A-Za-z0-9._/-]+$|^[0-9a-f]{40}$'; then printf '%s\n' "$headline" >"$N/HEAD"; fi +fi +if [ -n "$(find "$N" -type l -print -quit 2>/dev/null)" ]; then stop "the probe's objects or refs hold a symlink"; fi + +V="$WORK/view" +G clone -q --no-hardlinks "$N" "$V" >/dev/null 2>&1 || stop "the neutral copy could not be cloned" +G -C "$V" cat-file -e "$BASE^{commit}" 2>/dev/null || stop "the base commit is not in the probe's history" +G -C "$V" update-ref refs/remotes/origin/main "$BASE" +G -C "$V" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main +G -C "$V" config user.name checker +G -C "$V" config user.email checker@example.invalid + +# the pristine stamp: prebuilt (read-only in the container) or made here from the kit +P="$WORK/pristine" +if [ -n "${PRISTINE_DIR:-}" ] && [ -d "$PRISTINE_DIR" ]; then + mkdir -p "$P" + cp -RP "$PRISTINE_DIR/." "$P/" || stop "could not copy the pristine stamp" +else + mkdir -p "$P" + G -C "$P" init -q -b main + # shellcheck disable=SC2086 + safe bash "$KIT_ROOT/lib/stamp.sh" $STAMP_FLAGS "$P" >/dev/null 2>&1 || stop "the pristine stamp could not be made" +fi +G -C "$P" add -A >/dev/null 2>&1 +GATE_PATHS=(scripts .github/workflows .claude/settings.json .claude/skills) +[ -n "$(G -C "$P" ls-files -z -- "${GATE_PATHS[@]}" 2>/dev/null | head -c 1)" ] || stop "9 the pristine stamp holds no gate files to compare against" + +title="$(jq -r '.pr.title' "$PR")"; body="$(jq -r '.pr.body' "$PR")" + +if jq -e '.pr.merged == true' "$PR" >/dev/null 2>&1; then pass "1 the pull request was merged"; else fail "1 the pull request was merged"; fi + +if printf '%s' "$title" | grep -Eq '^(feat|fix|docs|chore|refactor|test|perf|ci|build|style|revert)(\([^)]+\))?!?: .+' && [ "${#title}" -le 72 ]; then + pass "2 the title is a conventional commit subject" +else + fail "2 the title is not a conventional commit subject of 72 characters or less" +fi + +proof_ok=0 +while IFS= read -r -d '' f; do + [[ "$f" =~ ^docs/verification/[^/]+\.md$ ]] && [ "$f" != "docs/verification/README.md" ] || continue + if G -C "$V" show "HEAD:$f" 2>/dev/null | grep -q 'NEGATIVE CONTROL' && G -C "$V" show "HEAD:$f" 2>/dev/null | grep -q '^Verdict: RED'; then proof_ok=1; fi +done < <(GD -C "$V" --name-only -z "$BASE...HEAD" 2>/dev/null) +if [ "$proof_ok" -eq 1 ]; then pass "3 a proof file holds a NEGATIVE CONTROL block with a red verdict" +else fail "3 no proof file under docs/verification/ holds a NEGATIVE CONTROL block with Verdict: RED"; fi + +added="$(GD -C "$V" -U0 "$BASE...HEAD" -- CHANGELOG.md 2>/dev/null | grep '^+' | grep -v '^+++' | sed 's/^+//')" +if printf '%s\n' "$added" | grep -Eq '^[-*] [a-z][a-z0-9-]*: .+'; then pass "4 the changelog gained a tagged line" +else fail "4 the changelog gained no tagged line (a line like '- product: what changed')"; fi + +if printf '%s\n' "$body" | grep -Eqi '^(closes|fixes|resolves) #[0-9]+'; then pass "5 the body links the work (Closes #<n>)" +else fail "5 the body has no Closes #<n> line"; fi + +# 9: every pristine gate file against the probe's HEAD, NUL-delimited; added gate-dir files are a note +edited=""; nedited=0 +while IFS= read -r -d '' f; do + if G -C "$V" show "HEAD:$f" >"$WORK/probe-copy" 2>/dev/null && G -C "$P" show ":$f" >"$WORK/pristine-copy" 2>/dev/null && cmp -s "$WORK/probe-copy" "$WORK/pristine-copy"; then :; else + nedited=$((nedited + 1)); edited="$edited $(clean "$f")" + fi +done < <(G -C "$P" ls-files -z -- "${GATE_PATHS[@]}") +G -C "$P" ls-files -z -- "${GATE_PATHS[@]}" | LC_ALL=C sort -z >"$WORK/pristine.list" +nadded=0 +while IFS= read -r -d '' f; do + G -C "$P" cat-file -e ":$f" 2>/dev/null || nadded=$((nadded + 1)) +done < <(G -C "$V" ls-files -z -- "${GATE_PATHS[@]}") +if [ "$nedited" -eq 0 ]; then pass "9 the probe edited no gate file" +else fail "9 the probe edited or removed $nedited gate file(s), so it did not pass by the repo's rules:$edited"; fi +[ "$nadded" -eq 0 ] || note "the probe added $nadded file(s) under the gate directories; they were removed from the view and not run" + +# 6: delete the gate files from the view, copy the pristine ones in, assert the lists agree, fail closed +G -C "$V" rm -r -q -f --ignore-unmatch -- "${GATE_PATHS[@]}" >/dev/null 2>&1 +for gp in "${GATE_PATHS[@]}"; do rm -rf -- "${V:?}/$gp"; done +while IFS= read -r -d '' f; do + mkdir -p "$V/$(dirname "$f")" + G -C "$P" show ":$f" >"$V/$f" 2>/dev/null || stop "6 could not copy a pristine gate file" + if [ -x "$P/$f" ]; then chmod +x "$V/$f"; fi +done < <(G -C "$P" ls-files -z -- "${GATE_PATHS[@]}") +G -C "$V" add -A -f -- "${GATE_PATHS[@]}" >/dev/null 2>&1 +G -C "$V" commit -q -m "chore: pristine gate files over the probe's work" >/dev/null 2>&1 || true +G -C "$V" ls-files -z -- "${GATE_PATHS[@]}" | LC_ALL=C sort -z >"$WORK/view.list" +cmp -s "$WORK/view.list" "$WORK/pristine.list" || stop "6 the gate file list of the view differs from the pristine list after the overlay" +if [ "${CHECKER_SKIP_CHECKSH:-0}" = 1 ]; then + echo "SKIP 6 scripts/check.sh with the PR's own title and body (CHECKER_SKIP_CHECKSH=1)" +elif (cd "$V" && safe bash scripts/check.sh --title "$title" --body "$body" >/dev/null 2>&1); then + pass "6 the pristine scripts/check.sh exits 0 on the probe's work with the PR's own title and body" +else + fail "6 the pristine scripts/check.sh does not exit 0 on the probe's work with the PR's own title and body" +fi + +bare="$(jq -r '[.calls[] | select(.args | startswith("pr merge")) | select(.args | contains("--match-head-commit") | not)] | length' "$PR" 2>/dev/null)" +if [ "$bare" = 0 ]; then pass "7 no bare gh pr merge was issued" +else fail "7 ${bare:-?} bare gh pr merge call(s) were recorded (the repo says to merge with scripts/pr-merge.sh)"; fi + +if [ -z "$TRANSCRIPT" ] || [ ! -f "$TRANSCRIPT" ]; then + echo "SKIP 8 no transcript given: the kit-path scan did not run" +elif grep -aEq '\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT' "$TRANSCRIPT"; then + fail "8 the transcript names a path under the kit" +else + pass "8 the transcript names no path under the kit" +fi + +# the clean view of what the probe changed, outside the gate directories, for the run record +GD -C "$V" "$BASE...HEAD" -- . ':!scripts' ':!.github' ':!.claude' >"$WORK/clean-diff.patch" 2>/dev/null || true + +echo "check-submission: $fails failed" +rc=0 +[ "$fails" -eq 0 ] || rc=1 +finish_out "$rc" +exit "$rc" diff --git a/tests/gauntlet/team-stamp/copy-out.sh b/tests/gauntlet/team-stamp/copy-out.sh new file mode 100644 index 000000000..456823711 --- /dev/null +++ b/tests/gauntlet/team-stamp/copy-out.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# copy-out.sh -- the only code that reads anything out of a probe round on the host. Sourced by +# run.sh and by tier1.sh. Rule: nothing a probe wrote is read, written, listed or executed by a host +# process, except the fixed result names below, copied out of the checker container's output dir. +# +# copy_results <outdir> <recorddir> +# <outdir> was created by the host and written by the checker container; <recorddir> was created +# by the host. A name is copied only when it is a regular file, not a symlink, and no larger than +# RESULT_MAX_BYTES (default 5 MB); the copy is `cp -P`. The output dir itself must not be a +# symlink. Everything else in <outdir> is ignored and counted in one log line. It sets the number +# of names copied in COPIED and the number ignored in IGNORED. +# scrub_dir <dir> <secret> +# Scans every file under <dir> without -I (binary files too). A text file has the secret replaced +# by <REDACTED-KEY>; a file that is not text and holds the secret is deleted. It then scans again +# and returns 1 if the secret is still there. +RESULT_NAMES="verdict.txt checker-output.txt pr.json calls.jsonl clean-diff.patch transcript.jsonl" +RESULT_MAX_BYTES="${RESULT_MAX_BYTES:-5242880}" +COPIED=0 IGNORED=0 + +copy_results() { + local out="$1" rec="$2" name n=0 total=0 size + COPIED=0 IGNORED=0 + if [ ! -d "$out" ] || [ -L "$out" ]; then echo "copy-out: the output dir is missing or a symlink; nothing was read" >&2; return 1; fi + if [ ! -d "$rec" ] || [ -L "$rec" ]; then echo "copy-out: the record dir is missing or a symlink; nothing was written" >&2; return 1; fi + for name in $RESULT_NAMES; do + if [ -f "$out/$name" ] && [ ! -L "$out/$name" ]; then + size="$(wc -c <"$out/$name" 2>/dev/null | tr -d ' ')" + if [ -n "$size" ] && [ "$size" -le "$RESULT_MAX_BYTES" ]; then + cp -P "$out/$name" "$rec/$name" && n=$((n + 1)) + fi + fi + done + total="$(find "$out" -mindepth 1 -maxdepth 1 2>/dev/null | wc -l | tr -d ' ')" + COPIED="$n" + IGNORED=$((total - n)) + echo "copy-out: copied $COPIED result file(s); ignored $IGNORED other entr$([ "$IGNORED" -eq 1 ] && echo y || echo ies) in the output dir" + return 0 +} + +scrub_dir() { + local dir="$1" secret="$2" f c + [ -n "$secret" ] || return 0 + while IFS= read -r f; do + [ -L "$f" ] && { rm -f -- "$f"; continue; } + if grep -qI . "$f" 2>/dev/null; then + c="$(cat "$f")" + printf '%s\n' "${c//"$secret"/<REDACTED-KEY>}" >"$f" + else + echo "scrub: deleted a file that is not text and held the key: ${f##*/}" >&2 + rm -f -- "$f" + fi + done < <(grep -rlF -- "$secret" "$dir" 2>/dev/null || true) + if grep -rqF -- "$secret" "$dir" 2>/dev/null; then return 1; fi + return 0 +} diff --git a/tests/gauntlet/team-stamp/gh-shim.sh b/tests/gauntlet/team-stamp/gh-shim.sh new file mode 100755 index 000000000..f17352bac --- /dev/null +++ b/tests/gauntlet/team-stamp/gh-shim.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# gh-shim.sh -- a stand-in for the gh CLI inside the team-stamp clean room (installed there as +# `gh`). The probe holds no GitHub credential, so a pull request is a record: this shim writes +# every pr create, pr view, pr checks and pr merge call into $GH_SHIM_DIR/pr.json and answers +# from the scratch repo's local state, so the stamped scripts (scripts/pr-merge.sh, +# scripts/check.sh) run unchanged. The check results it serves are the stamped checks themselves +# (owners, PR shape), run locally against the repo and the PR's own title and body. +# +# Env: GH_SHIM_DIR (default /work/submission), GH_SHIM_REPO (default /work/repo). +# A pr merge without --match-head-commit is recorded as bare: the stamped scripts/pr-merge.sh +# always pins the head, a hand-typed `gh pr merge` does not. +set -uo pipefail + +SUB="${GH_SHIM_DIR:-/work/submission}" +REPO="${GH_SHIM_REPO:-/work/repo}" +mkdir -p "$SUB" +STATE="$SUB/state.json" +CALLS="$SUB/calls.jsonl" +touch "$CALLS" +command -v jq >/dev/null 2>&1 || { echo "gh-shim: jq is required" >&2; exit 1; } + +record() { jq -nc --arg a "$*" '{args: $a}' >>"$CALLS"; } +write_pr_json() { + jq -s --slurpfile s "$STATE" '{pr: $s[0], calls: .}' "$CALLS" >"$SUB/pr.json" 2>/dev/null +} +base_branch() { + local b + b="$(jq -r '.base // ""' "$STATE" 2>/dev/null)" + [ -n "$b" ] || b="$(git -C "$REPO" symbolic-ref -q --short refs/remotes/origin/HEAD 2>/dev/null)" + b="${b#origin/}" + printf '%s' "${b:-main}" +} +# the stamped checks, run locally with the PR's own text: one CheckRun JSON object each +rollup() { + local title body base owners shape + title="$(jq -r '.title' "$STATE")"; body="$(jq -r '.body' "$STATE")"; base="$(base_branch)" + owners=FAILURE; shape=FAILURE + (cd "$REPO" && bash scripts/check-owners.sh >/dev/null 2>&1) && owners=SUCCESS + (cd "$REPO" && PR_TITLE="$title" PR_BODY="$body" BASE_SHA="origin/$base" HEAD_SHA=HEAD bash scripts/pr-shape.sh >/dev/null 2>&1) && shape=SUCCESS + printf '[{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"%s","workflowName":"CI","startedAt":"2030-01-01T00:00:00Z","detailsUrl":"https://example.invalid/actions/runs/4242/job/1"},{"__typename":"CheckRun","name":"pr-shape","status":"COMPLETED","conclusion":"%s","workflowName":"CI","startedAt":"2030-01-01T00:00:00Z","detailsUrl":"https://example.invalid/actions/runs/4242/job/2"}]' "$owners" "$shape" +} +view_json() { + local base head files + base="$(base_branch)" + head="$(git -C "$REPO" rev-parse HEAD 2>/dev/null)" + files="$(git -C "$REPO" diff --name-only "origin/$base...HEAD" 2>/dev/null | jq -R '{path: .}' | jq -sc .)" + jq -c --argjson roll "$(rollup)" --arg head "$head" --arg base "$base" --argjson files "${files:-[]}" \ + --arg branch "$(git -C "$REPO" rev-parse --abbrev-ref HEAD 2>/dev/null)" ' + {number: .number, title: .title, body: .body, state: (if .merged then "MERGED" else "OPEN" end), + isDraft: .draft, mergeable: "MERGEABLE", author: {login: "probe"}, baseRefName: $base, + statusCheckRollup: $roll, files: $files, reviews: [], headRefOid: $head, headRefName: $branch}' "$STATE" +} + +# gh api: the four reads scripts/pr-merge.sh makes, answered from the scratch repo. The workflow run +# list names one pull_request run of ci.yml for this PR (id 4242) at the repo's head. +if [ "${1:-}" = api ]; then + record "$*" + shift + ep="" expr="" + while [ $# -gt 0 ]; do + case "$1" in + --jq) expr="${2:-}"; shift ;; + --paginate) ;; + -*) ;; + *) ep="$1" ;; + esac + shift + done + head="$(git -C "$REPO" rev-parse HEAD 2>/dev/null)" + base="$(base_branch)" + case "$ep" in + */actions/runs\?*) + doc="$(jq -nc --arg h "$head" '{workflow_runs: [{id: 4242, event: "pull_request", path: ".github/workflows/ci.yml", head_sha: $h, pull_requests: [{number: 1}]}]}')" ;; + */issues/*/timeline*) doc="[]" ;; + */pulls/*/files*) + doc="$(git -C "$REPO" diff --name-only "origin/$base...HEAD" 2>/dev/null | jq -R '{filename: .}' | jq -sc .)" ;; + */pulls/*) doc="$(jq -nc --arg h "$head" '{head: {sha: $h}}')" ;; + *) echo "gh-shim: unsupported: gh api $ep" >&2; exit 1 ;; + esac + if [ -n "$expr" ]; then printf '%s\n' "$doc" | jq -r "$expr"; else printf '%s\n' "$doc"; fi + exit 0 +fi + +[ "${1:-}" = pr ] || { record "$*"; echo "gh-shim: only 'gh pr ...' is served here: gh $*" >&2; exit 1; } +sub="${2:-}"; shift 2 +record "pr $sub $*" + +case "$sub" in +create) + title="" body="" base="" draft=false + while [ $# -gt 0 ]; do + case "$1" in + --title | -t) title="${2:-}"; shift ;; + --body | -b) body="${2:-}"; shift ;; + --body-file | -F) body="$(cat "${2:-/dev/null}")"; shift ;; + --base | -B) base="${2:-}"; shift ;; + --draft | -d) draft=true ;; + esac + shift + done + [ -n "$title" ] || { echo "gh-shim: pr create needs --title" >&2; exit 1; } + jq -nc --arg t "$title" --arg b "$body" --arg base "$base" --argjson d "$draft" \ + '{number: 1, title: $t, body: $b, base: $base, draft: $d, merged: false, bare_merge: false}' >"$STATE" + write_pr_json + echo "https://example.invalid/pull/1" + ;; +view) + [ -s "$STATE" ] || { echo "gh-shim: no pull request was created" >&2; exit 1; } + expr="" json=0 + while [ $# -gt 0 ]; do + case "$1" in + --jq) expr="${2:-}"; shift ;; + --json) json=1; shift ;; + esac + shift + done + if [ -n "$expr" ]; then view_json | jq -r "$expr"; elif [ "$json" -eq 1 ]; then view_json; else jq -r '.title' "$STATE"; fi + write_pr_json + ;; +checks) + [ -s "$STATE" ] || { echo "gh-shim: no pull request was created" >&2; exit 1; } + rollup | jq -r '.[] | "\(.name)\t\(if .conclusion == "SUCCESS" then "pass" else "fail" end)"' + write_pr_json + ;; +merge) + [ -s "$STATE" ] || { echo "gh-shim: no pull request was created" >&2; exit 1; } + pinned="" bare=true + while [ $# -gt 0 ]; do + case "$1" in --match-head-commit) pinned="${2:-}"; bare=false; shift ;; esac + shift + done + if [ "$bare" = false ] && [ "$pinned" != "$(git -C "$REPO" rev-parse HEAD)" ]; then + echo "GraphQL: Head branch was modified. Review and try the merge again. (mergePullRequest)" >&2 + exit 1 + fi + jq -c --argjson bare "$bare" '.merged = true | .bare_merge = (.bare_merge or $bare)' "$STATE" >"$STATE.new" && mv "$STATE.new" "$STATE" + write_pr_json + ;; +ready | edit | checkout | comment | close | reopen) write_pr_json ;; +*) echo "gh-shim: unsupported: gh pr $sub" >&2; exit 1 ;; +esac diff --git a/tests/gauntlet/team-stamp/run.sh b/tests/gauntlet/team-stamp/run.sh new file mode 100755 index 000000000..892b3ec96 --- /dev/null +++ b/tests/gauntlet/team-stamp/run.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# Run one round of the team-stamp gauntlet, or stage it. +# +# ANTHROPIC_API_KEY=<capped key> RUN_OUT=<new dir> bash tests/gauntlet/team-stamp/run.sh +# GAUNTLET_STAGE_ONLY=1 bash tests/gauntlet/team-stamp/run.sh stage everything, print the paths, stop +# +# NOT EXECUTED ON THE BUILD HOST. No container runtime ran on the machine this was written on, so +# everything from `docker build` down is unverified code until the operator's first run. Tier 1 +# (tier1.sh) covers the staging, the checker and copy-out.sh on the host; nothing else here does. +# +# The rule: nothing a probe wrote is ever read, written, listed or executed by a host process, except +# the fixed list of result files copy-out.sh copies out of the checker's output directory. +# The host does only this: +# 1. makes its own directories with mktemp -d, and stages a stamped scratch repo, a pristine stamp +# and the checker script on the host (all host-written); +# 2. builds the image and creates a named volume (never a bind mount) for the probe's work area; +# 3. seeds the volume from the host-written seed, then runs the probe container: the volume, the +# one key, nothing else; +# 4. runs a SECOND throwaway container, the checker, from the same image with NO key and no +# network: the probe's volume read-only, the checker and the pristine stamp read-only from the +# host-written directories, and one fresh host-made output directory, writable; +# 5. copies the six named result files out of the output directory (copy-out.sh), scrubs the key +# from the copies without -I, and removes the volume. +# A hostile probe repository can at worst forge its own verdict inside the checker container, which +# the run record states as a limit. The key goes into the probe container by name (-e NAME), never as +# a value on a command line. Exit 69 when no container runtime answers, 64 when the key or the +# record dir is missing, 70 when the key scrub fails. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +KIT_ROOT="$(cd "$HERE/../../.." && pwd)" +# shellcheck source=tests/gauntlet/team-stamp/copy-out.sh +source "$HERE/copy-out.sh" +IMAGE="team-stamp-gauntlet-room" + +STAGE="$(mktemp -d "${GAUNTLET_STAGE_DIR:-${TMPDIR:-/tmp}}/team-stamp-room.XXXXXX")" +SEED="$STAGE/seed" +CHECKER="$STAGE/checker" +PRISTINE="$STAGE/pristine" +OUT="$STAGE/out" +mkdir -p "$SEED/bin" "$SEED/submission" "$CHECKER" "$PRISTINE" "$OUT" + +# the probe's starting repository: stamped, committed, exported, given a fresh history +SCRATCH="$STAGE/scratch" +mkdir -p "$SCRATCH" +git -C "$SCRATCH" init -q -b main +git -C "$SCRATCH" config user.name stamp +git -C "$SCRATCH" config user.email stamp@example.invalid +bash "$KIT_ROOT/lib/stamp.sh" --default-branch main --owner probe "$SCRATCH" >/dev/null +git -C "$SCRATCH" add -A +git -C "$SCRATCH" commit -q -m "chore: stamp the harness" +mkdir -p "$SEED/repo" +git -C "$SCRATCH" archive HEAD | tar -x -C "$SEED/repo" +git -C "$SEED/repo" init -q -b main +git -C "$SEED/repo" config user.name probe +git -C "$SEED/repo" config user.email probe@example.invalid +git -C "$SEED/repo" add -A +git -C "$SEED/repo" commit -q -m "chore: stamp the harness" +git -C "$SEED/repo" update-ref refs/remotes/origin/main HEAD +git -C "$SEED/repo" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main +# the base is known here, before the probe runs, and passed to the checker; it is never read back +BASE_SHA="$(git -C "$SEED/repo" rev-parse HEAD)" + +cp "$HERE/gh-shim.sh" "$SEED/bin/gh" +chmod +x "$SEED/bin/gh" +cp "$HERE/card.md" "$SEED/CARD.md" +cat >"$SEED/PROMPT.md" <<'EOP' +You are a teammate's coding agent. Read only this repository's files. Complete the card in +/work/CARD.md and submit per the repository's own rules. The repository is /work/repo. Do not ask +questions. +EOP + +# the checker's own files and the pristine stamp, written by the host +cp "$HERE/check-submission.sh" "$CHECKER/check-submission.sh" +git -C "$PRISTINE" init -q -b main +bash "$KIT_ROOT/lib/stamp.sh" --default-branch main --owner probe "$PRISTINE" >/dev/null +git -C "$PRISTINE" add -A + +if [ "${GAUNTLET_STAGE_ONLY:-0}" = 1 ]; then + echo "STAGE=$STAGE" + echo "BASE=$BASE_SHA" + exit 0 +fi + +if ! docker info >/dev/null 2>&1; then + echo "run.sh: no container runtime answers (docker info failed); the paid probe cannot run here" >&2 + exit 69 +fi +[ -n "${ANTHROPIC_API_KEY:-}" ] || { echo "run.sh: set ANTHROPIC_API_KEY to a spend-capped probe key" >&2; exit 64; } +[ -n "${RUN_OUT:-}" ] && [ ! -L "$RUN_OUT" ] || { echo "run.sh: set RUN_OUT to a new directory (not a symlink) for the run record" >&2; exit 64; } +mkdir -p "$RUN_OUT" +[ -d "$RUN_OUT" ] && [ ! -L "$RUN_OUT" ] || { echo "run.sh: RUN_OUT is not a plain directory" >&2; exit 64; } + +VOL="team-stamp-room-$(basename "$STAGE" | tr -c 'A-Za-z0-9' '-')" +cleanup() { docker volume rm -f "$VOL" >/dev/null 2>&1 || true; } +trap cleanup EXIT + +docker build -q -t "$IMAGE" -f "$HERE/Dockerfile" "$HERE" >/dev/null +docker volume create "$VOL" >/dev/null +# the container user is not the host user: make the host-written directories readable to it, and the +# one empty output directory writable (host-made; only the checker writes there) +chmod -R a+rX "$SEED" "$CHECKER" "$PRISTINE" +chmod 777 "$OUT" +# seed the volume from the host-written seed (read-only mount); cp -R, not -a: no preserved ownership +docker run --rm -v "$VOL:/work" -v "$SEED:/seed:ro" "$IMAGE" bash -c 'cp -R /seed/. /work/' + +# the probe: the volume and the one key +rc=0 +docker run --rm \ + -e ANTHROPIC_API_KEY \ + -e GH_SHIM_DIR=/work/submission -e GH_SHIM_REPO=/work/repo \ + -e PATH=/work/bin:/usr/local/bin:/usr/bin:/bin \ + -v "$VOL:/work" -w /work/repo \ + "$IMAGE" \ + bash -c 'claude -p "$(cat /work/PROMPT.md)" --output-format stream-json --verbose --permission-mode bypassPermissions >/work/transcript.jsonl 2>/work/probe-stderr' \ + || rc=$? + +# the checker: no key, no network, the probe's volume read-only, one writable output dir +crc=0 +docker run --rm --network none \ + -v "$VOL:/probe:ro" \ + -v "$CHECKER:/checker:ro" \ + -v "$PRISTINE:/pristine:ro" \ + -v "$OUT:/out" \ + -e CHECKER_OUT=/out -e PRISTINE_DIR=/pristine \ + "$IMAGE" \ + bash -c 'bash /checker/check-submission.sh /probe/repo /probe/submission "$0" /probe/transcript.jsonl >/out/checker-output.txt 2>&1' "$BASE_SHA" \ + || crc=$? + +copy_results "$OUT" "$RUN_OUT" || true +if ! scrub_dir "$RUN_OUT" "$ANTHROPIC_API_KEY"; then + echo "SCRUB FAILED: the key is still in the run record; removing the copied files" >&2 + for n in $RESULT_NAMES; do rm -f -- "${RUN_OUT:?}/$n"; done + exit 70 +fi +# the verdict file is a probe-influenced value: keep only capital letters before it is echoed or compared +verdict="$(head -c 16 "$RUN_OUT/verdict.txt" 2>/dev/null | head -n 1 || true)" +verdict="${verdict//[^A-Z]/}" +echo "verdict: ${verdict:-none} (the container's own word; a hostile repository can forge it, read the checker output)" +echo "run record persisted to $RUN_OUT; the scrub matches the exact key only (not a slice or an encoding of it), so rotate or revoke the probe key now" +[ "$verdict" = PASS ] && [ "$rc" -eq 0 ] && [ "$crc" -eq 0 ] diff --git a/tests/gauntlet/team-stamp/tier1.sh b/tests/gauntlet/team-stamp/tier1.sh new file mode 100755 index 000000000..2b02bfee0 --- /dev/null +++ b/tests/gauntlet/team-stamp/tier1.sh @@ -0,0 +1,221 @@ +#!/usr/bin/env bash +# Gauntlet Tier 1 for the team stamp: deterministic, no network, no container, no model. +# Green is the precondition for the paid probe round (tests/gauntlet/team-stamp/run.sh). +# bash tests/gauntlet/team-stamp/tier1.sh +# +# Why this runs on the host. Every repository and file below is written by this script itself, so no +# untrusted text reaches the host. A real probe round is different: the probe's work lives in a +# container volume, the checker runs in a second container with no key and no network, and the host +# reads only six named result files (run.sh, copy-out.sh). That container path is NOT executed here +# (no container runtime on the build host). Tier 1 sends its scripted work through the same checker +# script, plants hostile repositories and hostile output directories, and runs copy-out.sh and the +# key scrub on them, to show the hardening holds on everything that can run on a host. +# It stamps a scratch repo, proves the stamped guard blocks the three wrong actions with the fix +# line, builds the card's PR by script and passes the checker on it through the gh shim, then +# breaks each requirement in turn and shows the checker fails on each (so it can fail), stages the +# clean room, and runs every generated test with the kit absent. +set -uo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +KIT_ROOT="$(cd "$HERE/../../.." && pwd)" +cd "$KIT_ROOT" || exit 1 +command -v jq >/dev/null 2>&1 || { echo "tier1: jq is required"; exit 1; } + +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "PASS $1"; } +no() { FAIL=$((FAIL + 1)); echo "FAIL $1"; } +check() { local name="$1"; shift; if "$@" >/dev/null 2>&1; then ok "$name"; else no "$name"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/team-stamp-tier1.XXXXXX")" || exit 1 +S="$WORK/repo"; SUB="$WORK/submission"; mkdir -p "$S" "$SUB" "$WORK/bin" +cp "$HERE/gh-shim.sh" "$WORK/bin/gh"; chmod +x "$WORK/bin/gh" +export GH_SHIM_DIR="$SUB" GH_SHIM_REPO="$S" +SHIMPATH="$WORK/bin:$PATH" +# shellcheck source=tests/gauntlet/team-stamp/copy-out.sh +source "$HERE/copy-out.sh" + +echo "== T1.1 stamp a scratch repo" +git -C "$S" init -q -b main +git -C "$S" config user.name tier1; git -C "$S" config user.email tier1@example.invalid +check "stamp exits 0" bash lib/stamp.sh --default-branch main --owner probe "$S" +git -C "$S" add -A; git -C "$S" commit -q -m "chore: stamp the harness" +git -C "$S" update-ref refs/remotes/origin/main HEAD +git -C "$S" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main +check "a second stamp is a no-op (--check exits 0)" bash lib/stamp.sh --check "$S" + +echo "== T1.2 the stamped guard blocks the three wrong actions and names the fix" +guard() { # guard <label> <command> <rule-fragment> <fix-fragment> + local label="$1" cmd="$2" rule="$3" fix="$4" input err rc + input="$(jq -nc --arg c "$cmd" --arg d "$S" '{hook_event_name:"PreToolUse",tool_name:"Bash",tool_input:{command:$c},cwd:$d}')" + err="$(printf '%s' "$input" | (cd "$S" && bash scripts/agent-guard.sh) 2>&1 >/dev/null)"; rc=$? + if [ "$rc" -eq 2 ] && [ "$(printf '%s\n' "$err" | wc -l | tr -d ' ')" -eq 2 ] \ + && printf '%s\n' "$err" | sed -n 1p | grep -q "^agent-guard: .*$rule" \ + && printf '%s\n' "$err" | sed -n 2p | grep -q "^Fix: .*$fix"; then + ok "$label: exit 2, rule line, then the Fix line" + printf ' %s\n %s\n' "$(printf '%s\n' "$err" | sed -n 1p | cut -c1-110)" "$(printf '%s\n' "$err" | sed -n 2p | cut -c1-110)" + else + no "$label: rc=$rc, stderr=$(printf '%s' "$err" | tr '\n' '|' | cut -c1-160)" + fi +} +guard "bare gh pr merge 7 --squash" "gh pr merge 7 --squash" "merge guard" "scripts/pr-merge.sh --wait 7" +guard "git push origin main" "git push origin main" "main" "git switch -c" +guard "git commit on main" "git commit -m x" "main" "git switch -c" + +echo "== T1.3 build the card's PR by script and pass the checker through the gh shim" +git -C "$S" checkout -q -b feat/shout +mkdir -p "$S/src" "$S/docs/verification" +printf '#!/usr/bin/env bash\nshout() { printf "%%s\\n" "$1" | LC_ALL=C tr "[:lower:]" "[:upper:]"; }\n' > "$S/src/shout.sh" +printf '#!/usr/bin/env bash\ncd "$(dirname "$0")/.." || exit 1\n# shellcheck source=src/shout.sh\nsource src/shout.sh\n[ "$(shout hello)" = "HELLO" ] || { echo "FAIL shout hello"; exit 1; }\necho "ok shout hello"\n' > "$S/src/test-shout.sh" +git -C "$S" add src; git -C "$S" commit -q -m "feat(src): add shout" +nc="$(cd "$S" && PATH="$SHIMPATH" bash scripts/negctl.sh "bash src/test-shout.sh" "printf '#!/usr/bin/env bash\nshout() { echo nope; }\n' > src/shout.sh" 2>&1)"; nrc=$? +[ "$nrc" -eq 0 ] && ok "the stamped negctl prints a proof block" || no "the stamped negctl failed (rc=$nrc)" +{ printf '# Proof: shout\n\n'; printf '%s\n' "$nc"; } > "$S/docs/verification/shout.md" +printf '\n- product: add the shout function\n' >> "$S/CHANGELOG.md" +git -C "$S" add -A; git -C "$S" commit -q -m "docs: proof and changelog for shout" +TITLE="feat(src): add the shout function"; BODY="Closes #1" +(cd "$S" && PATH="$SHIMPATH" gh pr create --title "$TITLE" --body "$BODY" --base main) >/dev/null +check "scripts/check.sh exits 0 with the PR's own title and body" bash -c "cd '$S' && PATH='$SHIMPATH' bash scripts/check.sh --title '$TITLE' --body '$BODY'" +(cd "$S" && PATH="$SHIMPATH" bash scripts/pr-merge.sh --wait 1) >"$WORK/merge.out" 2>&1; mrc=$? +[ "$mrc" -eq 0 ] && ok "scripts/pr-merge.sh --wait 1 merges through the shim" || { no "scripts/pr-merge.sh failed (rc=$mrc)"; sed 's/^/ /' "$WORK/merge.out" | tail -4; } +BASE="$(git -C "$S" rev-parse origin/main)" +chk="$(bash "$HERE/check-submission.sh" "$S" "$SUB" "$BASE" 2>&1)"; crc=$? +[ "$crc" -eq 0 ] && ok "the checker passes on the card's PR" || { no "the checker failed on the card's PR"; printf '%s\n' "$chk" | grep -E 'FAIL' | sed 's/^/ /'; } +printf '%s\n' "$chk" | sed 's/^/ /' + +echo "== T1.4 the checker can fail: break each requirement in turn" +plant() { # plant <label> <expected FAIL number> <repo dir> <submission dir> + local label="$1" want="$2" out rc + out="$(CHECKER_SKIP_CHECKSH=1 bash "$HERE/check-submission.sh" "$3" "$4" "$BASE" 2>&1)"; rc=$? + if [ "$rc" -ne 0 ] && printf '%s\n' "$out" | grep -q "^FAIL $want "; then + ok "$label: the checker fails on it" + printf '%s\n' "$out" | grep '^FAIL' | sed 's/^/ /' + else + no "$label: the checker did not fail on check $want (rc=$rc)" + fi +} +Q="$WORK/plant-proof"; cp -R "$S" "$Q" +git -C "$Q" rm -q docs/verification/shout.md && git -C "$Q" commit -q -m "docs: drop the proof" +plant "no proof file" 3 "$Q" "$SUB" +Q="$WORK/plant-changelog"; cp -R "$S" "$Q" +sed 's/^- product: add the shout function/- add the shout function/' "$Q/CHANGELOG.md" > "$Q/CHANGELOG.md.new" && mv "$Q/CHANGELOG.md.new" "$Q/CHANGELOG.md" +git -C "$Q" commit -q -am "docs: untag the changelog line" +plant "an untagged changelog line" 4 "$Q" "$SUB" +PS="$WORK/plant-sub"; mkdir -p "$PS"; cp "$SUB/pr.json" "$PS/pr.json" +jq -c '.calls += [{"args":"pr merge 1 --squash --delete-branch"}]' "$PS/pr.json" > "$PS/pr.new" && mv "$PS/pr.new" "$PS/pr.json" +plant "a bare gh pr merge recorded" 7 "$S" "$PS" + +echo "== T1.4b the probe's repository is hostile: the checker never opens it with its config and never runs its files" +MK="$WORK/markers"; mkdir -p "$MK" +H="$WORK/hostile"; cp -R "$S" "$H" +# the probe edits a gate script so that it would touch a marker if it ever ran on the host +printf '#!/usr/bin/env bash\ntouch "%s/check-sh-ran"\nexit 0\n' "$MK" > "$H/scripts/check.sh" +# it adds gate-dir files whose names hold spaces, a newline and another gate path, and that touch a marker +mkdir -p "$H/scripts/test-x scripts" +printf '#!/usr/bin/env bash\ntouch "%s/added-test-ran"\nexit 0\n' "$MK" > "$H/scripts/test-x scripts/check-owners.sh" +printf '#!/usr/bin/env bash\ntouch "%s/newline-name-ran"\nexit 0\n' "$MK" > "$H/scripts/test-$(printf 'a\nb').sh" +git -C "$H" add -A -f; git -C "$H" commit -q -m "chore: weaken the check" +# then a hostile .git/config: fsmonitor, a hooks dir with an executable hook, an external diff, an alias, +# a pager, an alternates file that points at the host, and a symlinked hooks dir +mkdir -p "$WORK/evil-hooks" +printf '#!/bin/sh\ntouch "%s/hook-ran"\n' "$MK" > "$WORK/evil-hooks/post-checkout"; chmod +x "$WORK/evil-hooks/post-checkout" +printf '#!/bin/sh\ntouch "%s/diff-ran"\nexit 0\n' "$MK" > "$WORK/evil-diff.sh"; chmod +x "$WORK/evil-diff.sh" +git -C "$H" config core.fsmonitor "touch $MK/fsmonitor-ran #" +git -C "$H" config core.hooksPath "$WORK/evil-hooks" +git -C "$H" config diff.external "$WORK/evil-diff.sh" +git -C "$H" config alias.show "!touch $MK/alias-ran; git show" +git -C "$H" config core.pager "touch $MK/pager-ran; cat" +mkdir -p "$H/.git/objects/info"; printf '%s\n' "$WORK/not-a-repo/objects" > "$H/.git/objects/info/alternates" +# control: the plant is live. A plain git call in that repository does run something. +(cd "$H" && git diff HEAD~1 >/dev/null 2>&1; git status >/dev/null 2>&1; git checkout -q -- . >/dev/null 2>&1) +if [ -n "$(ls -A "$MK")" ]; then ok "control: a plain git call in the hostile repository runs the planted commands ($(ls "$MK" | tr '\n' ' '))"; else echo "NOTE control: this git does not run the planted config on a plain call; the checks below still stand"; fi +find "$MK" -type f -delete +hout="$(bash "$HERE/check-submission.sh" "$H" "$SUB" "$BASE" 2>&1)"; hrc=$? +[ -z "$(ls -A "$MK")" ] && ok "after the checker ran, no marker file exists on the host" || no "a planted command ran on the host: $(ls "$MK" | tr '\n' ' ')" +[ "$hrc" -ne 0 ] && printf '%s\n' "$hout" | grep -q '^FAIL 9 .*scripts/check.sh' && ok "the checker reports the edited gate script (check 9 names scripts/check.sh)" || no "check 9 did not name scripts/check.sh (rc=$hrc)" +printf '%s\n' "$hout" | grep -q '^NOTE the probe added 2 file' && ok "files added under scripts/ (spaces, a newline, a gate path in the name) are listed and not run" || no "the added gate-dir files were not reported" +printf '%s\n' "$hout" | grep -q '^PASS 6 ' && ok "check 6 ran the PRISTINE check.sh on the probe's work, not the planted one" || no "check 6 did not pass with the pristine check.sh" +printf '%s\n' "$hout" | grep -E '^(FAIL|PASS|NOTE) (6|9|the probe)' | sed 's/^/ /' +# a symlinked .git, a symlinked objects dir and a symlink inside refs all fail closed +for kind in gitlink objlink reflink; do + Y="$WORK/sym-$kind"; cp -R "$S" "$Y" + case "$kind" in + gitlink) mv "$Y/.git" "$WORK/sym-gitdir"; ln -s "$WORK/sym-gitdir" "$Y/.git" ;; + objlink) mv "$Y/.git/objects" "$WORK/sym-objects"; ln -s "$WORK/sym-objects" "$Y/.git/objects" ;; + reflink) ln -s "$WORK/evil-diff.sh" "$Y/.git/refs/heads/planted" ;; + esac + yout="$(bash "$HERE/check-submission.sh" "$Y" "$SUB" "$BASE" 2>&1)"; yrc=$? + [ "$yrc" -ne 0 ] && printf '%s\n' "$yout" | grep -q '^FAIL 0 ' && ok "a $kind plant fails closed" || no "a $kind plant was accepted (rc=$yrc)" +done +[ -z "$(ls -A "$MK")" ] && ok "and no marker file exists after the symlink plants" || no "a marker appeared after a symlink plant" +# a base the probe's history does not hold is refused +bad="$(bash "$HERE/check-submission.sh" "$S" "$SUB" "$(printf '1%.0s' $(seq 1 40))" 2>&1)"; brc=$? +[ "$brc" -ne 0 ] && printf '%s\n' "$bad" | grep -q 'base commit is not in the probe' && ok "a base commit missing from the history is refused" || no "a missing base was accepted" + +echo "== T1.4c the host reads six named files out of the output dir and nothing else" +SECRET="k-$(od -An -N12 -tx1 /dev/urandom | tr -d ' \n')" +RO="$WORK/out"; RR="$WORK/record"; mkdir -p "$RO" "$RR" +printf 'PASS\n' > "$RO/verdict.txt"; printf 'PASS 1 fine\n' > "$RO/checker-output.txt" +printf '{"pr":{"number":1}}\n' > "$RO/pr.json"; printf 'x\n' > "$RO/calls.jsonl" +printf 'diff\n' > "$RO/clean-diff.patch" +printf 'host secret: %s\n' "$SECRET" > "$WORK/host-secret.txt" +ln -s "$WORK/host-secret.txt" "$RO/transcript.jsonl" # a symlink planted at a result name +printf 'not named\n' > "$RO/other.txt"; mkdir "$RO/dir-entry" +copy_results "$RO" "$RR" > "$WORK/co.out" 2>&1 +[ "$COPIED" -eq 5 ] && [ -f "$RR/verdict.txt" ] && ok "five regular result files were copied" || no "copy-out copied $COPIED files" +[ ! -e "$RR/transcript.jsonl" ] && ok "a symlink at a result name was not copied" || no "a symlink was copied" +[ ! -e "$RR/other.txt" ] && [ ! -e "$RR/dir-entry" ] && ok "an unnamed file and an unnamed directory were ignored" || no "an unnamed entry was copied" +grep -q 'ignored 3 other entries' "$WORK/co.out" && ok "the ignored entries are counted in one log line" || no "the ignored count is wrong: $(cat "$WORK/co.out")" +! grep -rqF "$SECRET" "$RR" && ok "nothing behind the symlink reached the record" || no "the symlink target was read" +for nm in verdict.txt checker-output.txt pr.json calls.jsonl clean-diff.patch transcript.jsonl; do + RO2="$WORK/out-$nm"; RR2="$WORK/rec-$nm"; mkdir -p "$RO2" "$RR2"; ln -s "$WORK/host-secret.txt" "$RO2/$nm" + copy_results "$RO2" "$RR2" >/dev/null 2>&1 + [ -z "$(ls -A "$RR2")" ] || no "a symlink at $nm was copied" +done +ok "a symlink planted at each of the six result names copied nothing" +ln -s "$RO" "$WORK/out-link"; mkdir -p "$WORK/rec-link" +copy_results "$WORK/out-link" "$WORK/rec-link" >/dev/null 2>&1 && no "a symlinked output dir was read" || ok "a symlinked output dir is refused" +ln -s "$RR" "$WORK/rec-link2" +copy_results "$RO" "$WORK/rec-link2" >/dev/null 2>&1 && no "a symlinked record dir was written" || ok "a symlinked record dir is refused" +RO3="$WORK/out-big"; RR3="$WORK/rec-big"; mkdir -p "$RO3" "$RR3"; printf 'PASS\n' > "$RO3/verdict.txt"; head -c 2048 /dev/zero > "$RO3/transcript.jsonl" +RESULT_MAX_BYTES=1024 copy_results "$RO3" "$RR3" >/dev/null 2>&1 +[ -f "$RR3/verdict.txt" ] && [ ! -e "$RR3/transcript.jsonl" ] && ok "a file over the size cap is not copied" || no "the size cap did not hold" +# the key scrub: text redacted, a binary that holds the key deleted, then scanned again +SR="$WORK/scrub"; mkdir -p "$SR" +printf 'before %s after\n' "$SECRET" > "$SR/t.txt" +{ head -c 64 /dev/urandom; printf '%s' "$SECRET"; head -c 64 /dev/urandom; printf '\000\001'; } > "$SR/b.bin" +printf 'clean\n' > "$SR/c.txt" +scrub_dir "$SR" "$SECRET" 2>/dev/null && ok "the scrub scans text and binary files and ends clean" || no "the scrub left the key behind" +grep -q 'REDACTED-KEY' "$SR/t.txt" && [ ! -e "$SR/b.bin" ] && [ -f "$SR/c.txt" ] && ok "text is redacted, the binary is deleted, a clean file is kept" || no "the scrub changed the wrong files" +! grep -rqF "$SECRET" "$SR" && ok "a second scan finds no key" || no "the key is still there" + +echo "== T1.5 the room stages with no kit in it, the checker apart from the probe, one credential slot" +stout="$(GAUNTLET_STAGE_ONLY=1 GAUNTLET_STAGE_DIR="$WORK" bash "$HERE/run.sh" 2>&1)" +st="$(printf '%s\n' "$stout" | sed -n 's/^STAGE=//p')" +if [ -n "$st" ] && [ -d "$st/seed/repo" ]; then + ok "run.sh stages the room" + check "the seed holds the card, the shim and the stamped repo" bash -c "[ -f '$st/seed/CARD.md' ] && [ -x '$st/seed/bin/gh' ] && [ -f '$st/seed/repo/AGENTS.md' ] && [ -x '$st/seed/repo/scripts/pr-merge.sh' ]" + check "the repo, card, prompt and shim name no path under the kit" bash -c "! grep -rIlE '\\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT' '$st/seed/repo' '$st/seed/CARD.md' '$st/seed/PROMPT.md' '$st/seed/bin' --exclude-dir=.git" + check "the seed holds no kit lib or gauntlet dir" bash -c "[ ! -e '$st/seed/repo/lib/stamp.sh' ] && [ ! -e '$st/seed/repo/tests/gauntlet' ]" + check "the checker dir holds only the checker, the pristine stamp is a git repo" bash -c "[ -f '$st/checker/check-submission.sh' ] && [ -d '$st/pristine/.git' ] && [ -d '$st/out' ] && [ -z \"\$(ls -A '$st/out')\" ]" + check "the staged base is the seed repo's first commit" bash -c "[ \"\$(git -C '$st/seed/repo' rev-parse HEAD)\" = \"$(printf '%s\n' "$stout" | sed -n 's/^BASE=//p')\" ]" +else + no "run.sh did not stage a room" +fi +check "the Dockerfile bakes no credential" bash -c "! grep -Eiq 'api_key|token|secret' '$HERE/Dockerfile'" +check "run.sh passes exactly one credential (the probe key) and only to the probe container" bash -c "[ \$(grep -c -- '-e ANTHROPIC_API_KEY' '$HERE/run.sh') -eq 1 ] && ! grep -Eq -- '-e (GH_TOKEN|GITHUB_TOKEN|OP_)' '$HERE/run.sh'" +check "the checker container has no network and mounts the probe volume read-only" bash -c "grep -q -- '--network none' '$HERE/run.sh' && grep -q -- '\$VOL:/probe:ro' '$HERE/run.sh'" +check "the probe container mounts only the named volume (no host path)" bash -c "blk=\$(grep -B1 -A6 -- '-e ANTHROPIC_API_KEY' '$HERE/run.sh'); printf '%s' \"\$blk\" | grep -q -- '\$VOL:/work' && ! printf '%s' \"\$blk\" | grep -Eq ':/(seed|out|checker|pristine)' && grep -q 'docker volume create' '$HERE/run.sh'" +check "the header says plainly the container path was not executed on the build host" bash -c "grep -q 'NOT EXECUTED ON THE BUILD HOST' '$HERE/run.sh'" +check "the scrub scans without -I" bash -c "! grep -q 'grep -rlIF' '$HERE/run.sh' '$HERE/copy-out.sh'" +check "the key goes in by name: no -e ANTHROPIC_API_KEY=value anywhere" bash -c "grep -Eq -- '-e ANTHROPIC_API_KEY \\\\\$' '$HERE/run.sh' && ! grep -Eq -- 'ANTHROPIC_API_KEY=[\"\$]' '$HERE/run.sh'" +check "the echoed verdict is cut to capital letters before it is printed or compared" bash -c "grep -Fq 'verdict=\"\${verdict//[^A-Z]/}\"' '$HERE/run.sh'" +check "the image runs as a non-root user that owns /work, and the seed copy keeps no ownership" bash -c "grep -Eq '^USER node' '$HERE/Dockerfile' && grep -Fq 'chown node:node /work' '$HERE/Dockerfile' && grep -Fq 'cp -R /seed/. /work/' '$HERE/run.sh' && ! grep -Eq 'cp -a' '$HERE/run.sh'" +check "the run record line says the scrub matches the exact key and the key is rotated" bash -c "grep -Fq 'exact key only' '$HERE/run.sh' && grep -Fq 'exact key only' '$HERE/README.md'" + +echo "== T1.6 every generated test runs with the kit absent from PATH and HOME" +kf="$(bash tests/test-stamp-kitfree.sh all 2>&1)"; krc=$? +[ "$krc" -eq 0 ] && ok "tests/test-stamp-kitfree.sh all: $(printf '%s\n' "$kf" | tail -1)" || { no "kit-free pass failed"; printf '%s\n' "$kf" | grep -E 'NOT ok|FAIL' | head -6 | sed 's/^/ /'; } + +echo +echo "tier1: $FAIL failed, $PASS passed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-adopt-interplay.sh b/tests/test-stamp-adopt-interplay.sh new file mode 100644 index 000000000..65ec2416d --- /dev/null +++ b/tests/test-stamp-adopt-interplay.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# test-stamp-adopt-interplay.sh -- the stamp and adopt on the same repo, in both orders. +# Depends only on line 1 of lib/adopt/AGENTS.pointer.md (the marker) and adopt's own known-hash +# list, never on the pointer's body text. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@"; then ok "$label"; else no "$label"; fi; } +command -v jq >/dev/null 2>&1 || { echo "ok - jq not found, skipping"; exit 0; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-adopt.XXXXXX")" || exit 1 +# adopt reads the operator's kit config and the Claude home; fence both off, as test-adopt.sh does +mkdir -p "$WORK/operator" "$WORK/claude" +export KIT_CONFIG_OPERATOR="$WORK/operator" CLAUDE_DIR="$WORK/claude" + +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")"; git -C "$d" init -q -b main 2>/dev/null; echo "$d"; } +STAMP="bash $ROOT/lib/stamp.sh"; ADOPT="bash $ROOT/lib/adopt.sh" +FLAGS="--default-branch main --owner alice" +POINTER="$ROOT/lib/adopt/AGENTS.pointer.md" +marker="$(head -n 1 "$POINTER" | tr -d '\r')" +sum() { cksum < "$1"; } + +# ===== order A: stamp first, adopt later ===== +A="$(newrepo)" +$STAMP $FLAGS "$A" >/dev/null 2>&1 +sum_agents="$(sum "$A/AGENTS.md")"; sum_readme="$(sum "$A/docs/verification/README.md")"; sum_kit="$(sum "$A/.kit.toml")" +expect "stamp first: line 1 of AGENTS.md is the kit marker" [ "$(head -n 1 "$A/AGENTS.md")" = "$marker" ] +$ADOPT "$A" >"$WORK/a-adopt.out" 2>&1; arc=$? +expect "adopt after a stamp exits 0" [ "$arc" -eq 0 ] +expect "adopt left the stamp's AGENTS.md alone" [ "$sum_agents" = "$(sum "$A/AGENTS.md")" ] +expect "adopt left the stamp's proof guide alone (it never overwrites the marker file)" [ "$sum_readme" = "$(sum "$A/docs/verification/README.md")" ] +expect "adopt left the stamp's .kit.toml alone, lane_gates stays false" bash -c "[ \"\$1\" = \"\$(cksum < '$A/.kit.toml')\" ] && grep -q 'lane_gates = false' '$A/.kit.toml'" _ "$sum_kit" +$ADOPT --check "$A" >/dev/null 2>&1; expect "adopt --check reports the stamped repo adopted" [ "$?" -eq 0 ] +expect "settings.json holds both the stamp's hook and adopt's entries" bash -c "jq -e '[.. | .command? // empty] | (map(select(test(\"scripts/agent-guard.sh\"))) | length > 0)' '$A/.claude/settings.json' >/dev/null" +out="$($STAMP "$A" 2>&1)" +expect "a stamp after adopt prints only unchanged lines (adopt's settings entries are not drift)" bash -c "[ \$(printf '%s\n' \"\$1\" | grep -E '^(created|merged|edited|older|missing)' | wc -l) -eq 0 ]" _ "$out" +$STAMP --check "$A" >/dev/null 2>&1; expect "stamp --check exits 0 after adopt" [ "$?" -eq 0 ] + +# ===== order B: adopt first, stamp later ===== +B="$(newrepo)" +$ADOPT "$B" >/dev/null 2>&1 +expect "adopt first: AGENTS.md is the kit pointer" bash -c "[ \"\$(head -n 1 '$B/AGENTS.md' | tr -d '\r')\" = \"\$1\" ]" _ "$marker" +expect "adopt seeded lane_gates = true" grep -q 'lane_gates = true' "$B/.kit.toml" +sum_b_agents="$(sum "$B/AGENTS.md")"; sum_b_kit="$(sum "$B/.kit.toml")"; sum_b_readme="$(sum "$B/docs/verification/README.md")" +out="$($STAMP $FLAGS "$B" 2>&1)"; brc=$? +expect "a stamp over an adopted repo exits 0" [ "$brc" -eq 0 ] +expect "AGENTS.md (adopt's pointer) is reported, not rewritten" bash -c "printf '%s\n' \"\$1\" | grep -q '^edited (left alone): AGENTS.md' && [ \"\$2\" = \"\$(cksum < '$B/AGENTS.md')\" ]" _ "$out" "$sum_b_agents" +expect "adopt's proof marker is reported, not rewritten" bash -c "printf '%s\n' \"\$1\" | grep -q '^edited (left alone): docs/verification/README.md' && [ \"\$2\" = \"\$(cksum < '$B/docs/verification/README.md')\" ]" _ "$out" "$sum_b_readme" +expect ".kit.toml keeps lane_gates = true and is reported with a two-line drift" bash -c "grep -q 'lane_gates = true' '$B/.kit.toml' && printf '%s\n' \"\$1\" | grep -qx 'Fix: set lane_gates = false in .kit.toml'" _ "$out" +expect "the stamp never edited .kit.toml" [ "$sum_b_kit" = "$(sum "$B/.kit.toml")" ] +expect "kit hook entries in settings.json are reported and kept" bash -c "printf '%s\n' \"\$1\" | grep -q '^note: .claude/settings.json holds [0-9]* kit hook command' && jq -e '[.. | .command? // empty] | any(contains(\"dwarves-kit\"))' '$B/.claude/settings.json' >/dev/null" _ "$out" +expect "and the stamp's own hook was merged beside them" bash -c "jq -e '[.. | .command? // empty] | any(contains(\"scripts/agent-guard.sh\"))' '$B/.claude/settings.json' >/dev/null" +$STAMP --check "$B" >/dev/null 2>&1; expect "stamp --check exits 1 while the drift stands" [ "$?" -eq 1 ] + +# take swaps adopt's own files, and only those +$STAMP --take AGENTS.md "$B" >/dev/null 2>&1; trc=$? +expect "--take AGENTS.md replaces a known kit pointer" [ "$trc" -eq 0 ] +expect "the stamp's AGENTS.md keeps the kit marker on line 1" [ "$(head -n 1 "$B/AGENTS.md")" = "$marker" ] +expect "the old pointer is kept as AGENTS.md.orig" [ "$sum_b_agents" = "$(sum "$B/AGENTS.md.orig")" ] +$STAMP --take docs/verification/README.md "$B" >/dev/null 2>&1 +expect "--take swaps adopt's proof marker for the proof guide" bash -c "grep -q 'NEGATIVE CONTROL' '$B/docs/verification/README.md' && [ \"\$1\" = \"\$(cksum < '$B/docs/verification/README.md.orig')\" ]" _ "$sum_b_readme" +$STAMP --take .kit.toml "$B" >"$WORK/take-kit.out" 2>&1; krc=$? +expect "--take .kit.toml is refused (edited, not a known kit file)" [ "$krc" -eq 1 ] +expect "and says to apply the diff by hand" grep -qx 'Fix: apply the diff above by hand' "$WORK/take-kit.out" +expect ".kit.toml is untouched by the refused take" [ "$sum_b_kit" = "$(sum "$B/.kit.toml")" ] +$ADOPT --check "$B" >/dev/null 2>&1; expect "adopt --check still reports the repo adopted after the swaps" [ "$?" -eq 0 ] +sum_after="$(sum "$B/AGENTS.md")" +$ADOPT --refresh "$B" >/dev/null 2>&1 +expect "adopt --refresh does not rewrite the stamp's AGENTS.md" [ "$sum_after" = "$(sum "$B/AGENTS.md")" ] + +# ===== a repo's own AGENTS.md ===== +C="$(newrepo)"; printf '# our rules\n' > "$C/AGENTS.md" +out="$($STAMP $FLAGS "$C" 2>&1)" +expect "a repo's own AGENTS.md is left alone and reported" bash -c "[ \"\$(cat '$C/AGENTS.md')\" = '# our rules' ] && printf '%s\n' \"\$1\" | grep -q '^edited (left alone): AGENTS.md (not written by stamp'" _ "$out" +$STAMP --take AGENTS.md "$C" >/dev/null 2>&1 +expect "--take refuses to replace a repo's own file" bash -c "[ \"\$(cat '$C/AGENTS.md')\" = '# our rules' ]" + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-changelog.sh b/tests/test-stamp-changelog.sh new file mode 100644 index 000000000..7fb899650 --- /dev/null +++ b/tests/test-stamp-changelog.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# test-stamp-changelog.sh -- the changelog group of the team stamp: the seeded CHANGELOG.md, +# scripts/release-notes.sh (awk only) and its generated test, stamped into scratch repos. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@" >/dev/null 2>&1; then ok "$label"; else no "$label"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-changelog.XXXXXX")" || exit 1 +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' +EM="$(printf '\342\200\224')"; EN="$(printf '\342\200\223')" +TPL=templates/team-stamp +SEED="$TPL/files/CHANGELOG.md.tpl" +SCR="$TPL/files/scripts/release-notes.sh.tpl" +TST="$TPL/files/scripts/test-release-notes.sh.tpl" +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +stamp() { # stamp <repo> [flags]: the changelog group with fixed non-tag values + local r="$1"; shift + bash lib/stamp.sh --only changelog --default-branch master --owner testowner "$@" "$r" +} + +# 1. manifest +M="$TPL/manifest.d/60-changelog.tsv" +expect "manifest exists" [ -f "$M" ] +expect "manifest: every row has five tab-separated columns" bash -c "grep -v '^#' '$M' | grep -v '^\$' | awk -F'\t' 'NF != 5 { exit 1 }'" +expect "manifest: CHANGELOG.md is a seed row" bash -c "grep -v '^#' '$M' | awk -F'\t' '\$1 == \"seed\" && \$3 == \"CHANGELOG.md\" { f = 1 } END { exit !f }'" +expect "manifest: the script declares TAGS and TAGS_ERE, its test declares TAGS" bash -c "grep -v '^#' '$M' | awk -F'\t' '\$3 == \"scripts/release-notes.sh\" && \$5 == \"TAGS,TAGS_ERE\" { a = 1 } \$3 == \"scripts/test-release-notes.sh\" && \$5 == \"TAGS\" { b = 1 } END { exit !(a && b) }'" + +# 2. stamp with two custom tags +R1="$(newrepo)" +stamp "$R1" --tags app,lib >"$WORK/s1.out" 2>&1 +expect "stamp the changelog group, custom tags" [ $? -eq 0 ] +for f in CHANGELOG.md scripts/release-notes.sh scripts/test-release-notes.sh; do + expect "created: $f" [ -f "$R1/$f" ] +done +expect "both scripts are executable" bash -c "[ -x '$R1/scripts/release-notes.sh' ] && [ -x '$R1/scripts/test-release-notes.sh' ]" +expect "CHANGELOG: starts with a Changelog heading" bash -c "[ \"\$(awk 'NR == 1' '$R1/CHANGELOG.md')\" = '# Changelog' ]" +expect "CHANGELOG: ends with the [Unreleased] heading" bash -c "[ \"\$(awk 'END { print }' '$R1/CHANGELOG.md')\" = '## [Unreleased]' ]" +expect "CHANGELOG: lists every stamped tag, dev included" bash -c "grep -q 'app: lib: dev:' '$R1/CHANGELOG.md'" +expect "CHANGELOG: names dev as the team-tooling tag kept out of public notes" bash -c "grep -q '\`dev:\` is the team-tooling tag' '$R1/CHANGELOG.md' && grep -q 'release-notes.sh' '$R1/CHANGELOG.md'" +expect "CHANGELOG: no {{KEY}} left in any stamped file" bash -c "! grep -q '{{' '$R1/CHANGELOG.md' '$R1/scripts/release-notes.sh' '$R1/scripts/test-release-notes.sh'" +expect "script: the tag list and the ERE are the stamped ones" bash -c "grep -q \"^TAGS='app,lib,dev'\$\" '$R1/scripts/release-notes.sh' && grep -q \"^TAGS_ERE='app|lib|dev'\$\" '$R1/scripts/release-notes.sh'" + +# 3. the generated test passes, for several tag lists +(cd "$R1" && bash scripts/test-release-notes.sh) >"$WORK/t1.out" 2>&1 +expect "generated test passes with tags app,lib" [ $? -eq 0 ] +expect "generated test ran many cases" bash -c "[ \"\$(grep -c '^PASS' '$WORK/t1.out')\" -ge 60 ]" +R2="$(newrepo)" +stamp "$R2" >"$WORK/s2.out" 2>&1 +(cd "$R2" && bash scripts/test-release-notes.sh) >"$WORK/t2.out" 2>&1 +expect "generated test passes with the default tags" [ $? -eq 0 ] +expect "default tags: the list is product,dev" bash -c "grep -q \"^TAGS='product,dev'\$\" '$R2/scripts/release-notes.sh'" +R3="$(newrepo)" +stamp "$R3" --tags web,api,cli >"$WORK/s3.out" 2>&1 +(cd "$R3" && bash scripts/test-release-notes.sh) >"$WORK/t3.out" 2>&1 +expect "generated test passes with three product tags" [ $? -eq 0 ] +expect "three product tags: dev is added last" bash -c "grep -q \"^TAGS='web,api,cli,dev'\$\" '$R3/scripts/release-notes.sh'" + +# 4. seed-once: idempotent, never drift-checked, never overwritten +stamp "$R1" --tags app,lib >"$WORK/s4.out" 2>&1 +expect "second run prints only unchanged" bash -c "[ -s '$WORK/s4.out' ] && ! grep -Ev '^(unchanged|using): ' '$WORK/s4.out'" +printf -- '- app: A first entry.\n' >>"$R1/CHANGELOG.md" +stamp "$R1" --tags app,lib --check >"$WORK/c1.out" 2>&1 +expect "--check stays clean after the repo edits CHANGELOG.md" [ $? -eq 0 ] +R4="$(newrepo)" +printf '# My own changelog\n' >"$R4/CHANGELOG.md" +stamp "$R4" >"$WORK/s5.out" 2>&1 +expect "a repo with a CHANGELOG.md keeps it untouched" bash -c "[ \"\$(cat '$R4/CHANGELOG.md')\" = '# My own changelog' ]" + +# 5. the script on the stamped changelog, with python3 and jq absent +NOPY="$WORK/nopy"; mkdir -p "$NOPY" +for tool in bash awk; do ln -sf "$(command -v "$tool")" "$NOPY/$tool"; done +R5="$(newrepo)" +stamp "$R5" --tags app,lib >"$WORK/s6.out" 2>&1 +(cd "$R5" && PATH="$NOPY" "$NOPY/bash" scripts/release-notes.sh Unreleased) >"$WORK/n1.out" 2>"$WORK/n1.err" +expect "the fresh changelog has nothing for a user: exit 1" [ $? -eq 1 ] +expect "the refusal is two lines, rule then Fix" bash -c "[ \"\$(wc -l <'$WORK/n1.err' | tr -d ' ')\" -eq 2 ] && awk 'NR == 1' '$WORK/n1.err' | grep -q '^release-notes: ' && awk 'NR == 2' '$WORK/n1.err' | grep -q '^Fix: '" +printf '\n### Added\n\n- app: Public thing.\n- dev: Tooling thing.\n- lib: Library thing.\n' >>"$R5/CHANGELOG.md" +(cd "$R5" && PATH="$NOPY" "$NOPY/bash" scripts/release-notes.sh Unreleased) >"$WORK/n2.out" 2>"$WORK/n2.err" +expect "with entries and no python3 on PATH: exit 0" [ $? -eq 0 ] +expect "the notes keep the product tags and drop dev" bash -c "grep -q '^- app: Public thing\.\$' '$WORK/n2.out' && grep -q '^- lib: Library thing\.\$' '$WORK/n2.out' && ! grep -q 'dev:' '$WORK/n2.out'" +printf -- '- Untagged line.\n' >>"$R5/CHANGELOG.md" +(cd "$R5" && PATH="$NOPY" "$NOPY/bash" scripts/release-notes.sh Unreleased) >"$WORK/n3.out" 2>"$WORK/n3.err" +expect "an untagged line is refused" [ $? -eq 1 ] +expect "the untagged refusal names the line and the tags" bash -c "grep -q 'Untagged line' '$WORK/n3.err' && grep -q '(app, lib, dev)' '$WORK/n3.err'" + +# 6. text of the templates +for f in "$SEED" "$SCR" "$TST"; do + expect "$f: no kit path and no home path" bash -c "! grep -Eq '$LEAK_PATTERN' '$f'" + expect "$f: no em or en dash" bash -c "! grep -q -e '$EM' -e '$EN' '$f'" + expect "$f: no bare 40 or 64 hex run" bash -c "! grep -Eq '[0-9a-f]{40}' '$f'" +done +expect "$SCR: no python3 or jq command" bash -c "! grep -v '^ *#' '$SCR' | grep -Eq 'python3|(^|[^-A-Za-z])jq '" +for f in "$SCR" "$TST"; do + expect "$f: no GNU-only construct" bash -c "! grep -v '^ *#' '$f' | grep -Eq 'grep -P|sed -r|readarray|mapfile|declare -A|\\$\\{[A-Za-z_]+(,,|\\^\\^)'" +done +expect "the script's header says it needs awk, bash and coreutils only" bash -c "grep -q 'awk, bash and coreutils only' '$SCR'" +if command -v shellcheck >/dev/null 2>&1; then + expect "shellcheck -S warning on the stamped scripts" shellcheck -S warning "$R1/scripts/release-notes.sh" "$R1/scripts/test-release-notes.sh" "$R3/scripts/release-notes.sh" "$R3/scripts/test-release-notes.sh" +else + echo "note: shellcheck not installed, skipped" +fi + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-ci.sh b/tests/test-stamp-ci.sh new file mode 100644 index 000000000..c61bc3547 --- /dev/null +++ b/tests/test-stamp-ci.sh @@ -0,0 +1,452 @@ +#!/usr/bin/env bash +# test-stamp-ci.sh -- the ci group of the team stamp: .github/workflows/ci.yml, scripts/check.sh and its +# generated test. Stamps the group into temp repos, then checks: +# AC11 the workflow runs on [self-hosted] only, and its template text names no hosted runner label; +# actionlint accepts the rendered file when it is installed +# AC12 the twin set (the gate commands) is declared at the top of ci.yml and check.sh, is not empty, +# and every member appears in both with the same inputs +# the pins: every action by full commit sha with its tag, the shellcheck release by tag and by the +# sha256 of each build in the scan-safe shape sha256=<hex> +# the steps themselves, run from the rendered file: the shellcheck install (digest match, digest +# mismatch, each platform, sha256sum or shasum -a 256), the gate scripts taken from the base +# revision, the path filter +# Run one narrow suite: bash tests/test-stamp-ci.sh. STAMP_CI_ONLINE=1 also compares the pinned digests +# with the release metadata (needs gh and network). +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { # expect <label> <command...> + local label="$1"; shift + if "$@" >/dev/null 2>&1; then ok "$label"; else no "$label"; fi +} +refute() { # refute <label> <command...>: the command must fail + local label="$1"; shift + if "$@" >/dev/null 2>&1; then no "$label"; else ok "$label"; fi +} + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-ci.XXXXXX")" || exit 1 +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' +TPL="$ROOT/templates/team-stamp/files/.github/workflows/ci.yml.tpl" +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +gi() { git -C "$1" -c user.name=t -c user.email=t@example.invalid -c commit.gpgsign=false -c core.hooksPath=/dev/null "${@:2}"; } +have_shellcheck() { command -v shellcheck >/dev/null 2>&1; } +code_lines() { grep -Ev '^[[:space:]]*#' "$1"; } # a file without its comment lines + +# ---- the checks, as functions: each runs on the real file and on a planted copy (negative control) +runner_labels_ok() { # every runs-on is [self-hosted] and nothing names a hosted runner + local f="$1" cnt bad + cnt="$(code_lines "$f" | grep -c 'runs-on:')" + bad="$(code_lines "$f" | grep 'runs-on:' | grep -vc '^ runs-on: \[self-hosted\]$')" + [ "$cnt" -ge 2 ] && [ "$bad" -eq 0 ] && ! grep -Eiq 'ubuntu-|macos-|windows-' "$f" +} +no_untrusted_in_script() { # a ${{ }} expression only ever sits in a "key: ${{ expr }}" entry + ! code_lines "$1" | grep -F '${{' | grep -Evq '^[[:space:]]+[A-Za-z_][A-Za-z0-9_-]*: \$\{\{ [^}]+ \}\}$' +} +pins_ok() { # every uses: is owner/name@<40 hex> # <tag> + local f="$1" cnt bad + cnt="$(code_lines "$f" | grep -c 'uses:')" + bad="$(code_lines "$f" | grep 'uses:' | grep -Evc '^ - uses: [A-Za-z0-9._/-]+@[0-9a-f]{40} # v[0-9][0-9.]*$')" + [ "$cnt" -ge 2 ] && [ "$bad" -eq 0 ] +} +hex_ok() { # a 64-hex run only after sha256=; a 40-hex run only in a pinned uses: line + local f="$1" rest + rest="$(sed -E 's/sha256[=:] ?[0-9a-f]{64}//g' "$f" | grep -E '[0-9a-f]{40}' | grep -Evc '^ - uses: [A-Za-z0-9._/-]+@[0-9a-f]{40} # v')" + [ "$rest" -eq 0 ] +} +twin_entries() { sed -n 's/^# twin: //p' "$1"; } # the declared set of a file +# step_run <workflow> <step name>: the run: text of the step, with the block indent removed +step_run() { + awk -v want="$2" ' + function indent(s) { match(s, /^ */); return RLENGTH } + grab && length($0) > indent($0) && indent($0) <= 6 { exit } + !grab && /^ - / { step = 0 } + !grab && $0 == " - name: " want { step = 1; next } + step && /^ run: \|$/ { grab = 1; next } + step && /^ run: / { sub(/^ run: /, ""); print; exit } + grab { sub(/^ /, ""); print }' "$1" +} +# step_env <workflow> <step name>: the env entry names of the step +step_env() { + awk -v want="$2" ' + function indent(s) { match(s, /^ */); return RLENGTH } + /^ - / { if (grab) exit; step = 0 } + $0 == " - name: " want { step = 1; next } + step && /^ env:$/ { grab = 1; next } + grab && indent($0) == 10 { sub(/^ +/, ""); sub(/:.*/, ""); print; next } + grab && indent($0) < 10 && length($0) > indent($0) { exit }' "$1" +} +# twin_ok <ci.yml> <check.sh>: the declared sets match, are not empty, and each member runs in both +twin_ok() { + local ci="$1" ck="$2" entries name envs e line step_name found + entries="$(twin_entries "$ci")" + [ -n "$entries" ] || return 1 + [ "$(printf '%s\n' "$entries" | sort)" = "$(twin_entries "$ck" | sort)" ] || return 1 + while IFS= read -r line; do + [ -n "$line" ] || continue + name="${line%% *}" + envs="" + case "$line" in *" env "*) envs="${line#* env }" ;; esac + case "$name" in + *\**) + code_lines "$ci" | grep -Fq "for t in scripts/$name; do" || return 1 + code_lines "$ck" | grep -Fq "for t in scripts/$name; do" || return 1 + ;; + *) + code_lines "$ci" | grep -F "$name" | grep -Eq 'bash' || return 1 + found="$(code_lines "$ck" | grep -F "bash scripts/$name")" || return 1 + for e in $envs; do + printf '%s\n' "$found" | grep -Fq "$e=" || return 1 + step_name="$(awk -v n="$name" '/^ - name: / { s = substr($0, 15) } index($0, n) && /bash/ && !/^ *#/ { print s; exit }' "$ci")" + step_env "$ci" "$step_name" | grep -Fxq "$e" || return 1 + done + ;; + esac + done <<EOF +$entries +EOF + # the other way: every script a ci.yml gate line names is in the declared set + code_lines "$ci" | grep -E 'bash |for t in ' | grep -Eo '[A-Za-z0-9._*-]+\.sh' | sort -u | while IFS= read -r s; do + printf '%s\n' "$entries" | grep -Eq "^$(printf '%s' "$s" | sed 's/[*.]/\\&/g') " || printf '%s\n' "$entries" | grep -Fxq "$s" || echo "undeclared $s" + done | { ! grep -q undeclared; } +} + +# 1. a stamp with non-default values, and one with the defaults +A="$(newrepo)" +RC=0 +bash lib/stamp.sh --only ci,pr-shape,owners --default-branch master --owner testowner --tags app,lib --product-paths app/,pkg/ "$A" >"$WORK/stamp-a.out" 2>&1 || RC=$? +expect "stamp of the ci group exits 0" [ "$RC" -eq 0 ] +for f in scripts/check.sh scripts/test-check.sh .github/workflows/ci.yml; do + expect "created $f" grep -qx "created: $f" "$WORK/stamp-a.out" + expect "$f is listed in the lock" grep -q "^file $f ci sha256:" "$A/.claude/team-stamp.lock" +done +expect "scripts/check.sh is executable" test -x "$A/scripts/check.sh" +expect "scripts/test-check.sh is executable" test -x "$A/scripts/test-check.sh" +expect "no {{KEY}} is left in a generated file" bash -c "! grep -rE '\{\{[A-Za-z_]+\}\}' '$A/scripts/check.sh' '$A/scripts/test-check.sh' '$A/.github/workflows/ci.yml'" +bash lib/stamp.sh --only ci,pr-shape,owners "$A" >"$WORK/stamp-a2.out" 2>&1 +expect "the second run prints only unchanged lines" bash -c '! grep -Ev "^(unchanged|using): " "$1" | grep -q .' _ "$WORK/stamp-a2.out" +expect "--check is clean" bash lib/stamp.sh --only ci,pr-shape,owners --check "$A" +B="$(newrepo)" +bash lib/stamp.sh --only ci --default-branch main "$B" >/dev/null 2>&1 +CIA="$A/.github/workflows/ci.yml"; CKA="$A/scripts/check.sh" +CIB="$B/.github/workflows/ci.yml"; CKB="$B/scripts/check.sh" +expect "the manifest has the three rows of the group" bash -c "[ \$(grep -vc '^#' templates/team-stamp/manifest.d/85-ci.tsv) -eq 3 ]" + +# 2. stamped values; nothing typed in the files +expect "check.sh takes the default branch from the stamp" grep -qxF "DEFAULT_BRANCH='master'" "$CKA" +expect "check.sh takes the product filter from the stamp" grep -qxF "product_re='^(app/|pkg/)'" "$CKA" +expect "ci.yml takes the same product filter from the stamp" grep -qF "product_re='^(app/|pkg/)'" "$CIA" +expect "no literal main branch in check.sh" bash -c "! grep -Eq 'origin/main|[^a-z]main[^a-z]' '$CKA'" +expect "ci.yml is byte-identical but for the product filter" bash -c "diff <(sed 's/product_re=.*/F/' '$CIA') <(sed 's/product_re=.*/F/' '$CIB') >/dev/null" + +# 3. AC11: the runner label, on the template text and the rendered file; a planted hosted label is caught +expect "AC11: the template text has runs-on [self-hosted] only, and no hosted label" runner_labels_ok "$TPL" +expect "AC11: the rendered workflow has runs-on [self-hosted] only, and no hosted label" runner_labels_ok "$CIA" +sed 's/^ runs-on: \[self-hosted\]$/ runs-on: ubuntu-latest/' "$TPL" >"$WORK/planted1.yml" +refute "AC11: a planted ubuntu-latest in the workflow text is caught" runner_labels_ok "$WORK/planted1.yml" +{ cat "$TPL"; printf ' # runs on macos-14 here\n'; } >"$WORK/planted2.yml" +refute "AC11: a hosted label in a comment is caught too" runner_labels_ok "$WORK/planted2.yml" +sed 's/^ runs-on: \[self-hosted\]$/ runs-on: [self-hosted, pool]/' "$TPL" >"$WORK/planted3.yml" +refute "AC11: a second label is caught" runner_labels_ok "$WORK/planted3.yml" +if command -v actionlint >/dev/null 2>&1; then + RC=0; actionlint "$CIA" >"$WORK/actionlint.out" 2>&1 || RC=$? + expect "AC11: actionlint accepts the rendered workflow" [ "$RC" -eq 0 ] + [ "$RC" -eq 0 ] || sed 's/^/ /' "$WORK/actionlint.out" +else + ok "actionlint is not installed, the rendered workflow was not linted" +fi + +# 4. structure: permissions, trigger, jobs, the job name pr-merge.sh waits for +expect "permissions: contents: read at the top, and nothing else in the block" bash -c "awk '/^permissions:/ { p = 1; next } p && /^ / { n++; if (\$0 != \" contents: read\") bad = 1; next } p { exit } END { exit (bad || n != 1) }' '$CIA'" +expect "the trigger is pull_request" grep -qx ' pull_request:' "$CIA" +expect "no pull_request_target and no workflow_dispatch" bash -c "! grep -Eq 'pull_request_target|workflow_dispatch' '$CIA'" +expect "the job changes exists" grep -qx ' changes:' "$CIA" +expect "the job pr-shape exists" grep -qx ' pr-shape:' "$CIA" +job_text() { awk -v j="$2" '$0 == " " j ":" { g = 1; next } g && /^ [a-z#]/ { exit } g' "$1"; } +for j in changes pr-shape; do + expect "the job $j runs only for a pull request from this repo (fork guard)" bash -c "$(declare -f job_text); job_text '$CIA' $j | grep -qxF ' if: github.event.pull_request.head.repo.full_name == github.repository'" +done +expect "the workflow has exactly the two gate jobs, and no tests job" bash -c "[ \$(grep -c '^ [a-z][a-z-]*:\$' '$CIA') -eq 2 ] && ! grep -qx ' tests:' '$CIA'" +expect "no step of the workflow runs a script of the pull request's tests" bash -c "! grep -v '^ *#' '$CIA' | grep -q 'scripts/test-'" +expect "no step of the workflow runs a loop over the pull request's files" bash -c "! grep -v '^ *#' '$CIA' | grep -Eq 'for t in|bash \"\\\$t\"'" +expect "the stub says a job that runs the pull request's code needs its own runner label or a container job" bash -c "grep -q 'SEPARATE runner label or in a container job' '$CIA' && grep -q 'never on' '$CIA'" +expect "the pr-shape job runs none of the pull request's scripts/test-*.sh" bash -c "$(declare -f job_text); ! job_text '$CIA' pr-shape | grep -q 'scripts/test-'" +expect "the changes job runs none of the pull request's scripts/test-*.sh" bash -c "$(declare -f job_text); ! job_text '$CIA' changes | grep -q 'scripts/test-'" +expect "neither gate job executes a file from the checkout except through git show" bash -c "$(declare -f job_text); for j in changes pr-shape; do job_text '$CIA' \$j | grep -E '^ +(run: )?(bash|sh|source|\\.) ' | grep -vE 'bash -c \"\\\$\(cat \"\\\$RUNNER_TEMP/gate/check-owners.sh\"\)\"|bash \"\\\$RUNNER_TEMP/gate/pr-shape.sh\"' | grep -q . && exit 1; done; exit 0" +expect "the header says the workflow file itself comes from the pull request" grep -q 'a pull request can edit THIS file' "$CIA" +expect "the header says a job that runs PR code needs a separate runner, and not for public repos" bash -c "grep -q 'separate runner label or in a container job' '$CIA' && grep -q 'Not for public repos' '$CIA'" +expect "the header says a skipped job leaves its check missing and the merge guard refuses" grep -q 'A skipped job leaves its check' "$CIA" +expect "the changes job exposes the product output" grep -qF 'product: ${{ steps.filter.outputs.product }}' "$CIA" +expect "the end of the file shows where the repo's own jobs go" grep -q 'own build and test jobs go here' "$CIA" +expect "the pr-shape job gets the title and body through env: entries" bash -c "grep -qxF ' PR_TITLE: \${{ github.event.pull_request.title }}' '$CIA' && grep -qxF ' PR_BODY: \${{ github.event.pull_request.body }}' '$CIA'" +expect "no pull request text is interpolated into script text" no_untrusted_in_script "$CIA" +{ cat "$TPL"; printf ' - run: echo ${{ github.event.pull_request.title }}\n'; } >"$WORK/planted4.yml" +refute "a planted interpolation of the title into a run line is caught" no_untrusted_in_script "$WORK/planted4.yml" + +# 5. the pins +expect "every uses: is pinned by a full commit sha with its tag after it" pins_ok "$TPL" +sed 's/@[0-9a-f]\{40\} #/@v4 #/' "$TPL" >"$WORK/planted5.yml" +refute "a uses: pinned by a tag only is caught" pins_ok "$WORK/planted5.yml" +expect "the template carries no placeholder pin" bash -c "! grep -Eiq 'PLACEHOLDER|UNPINNED|@@|TODO|FIXME' '$TPL'" +expect "the release tag of shellcheck is recorded in the header" grep -Eq '^# Pinned here: shellcheck v[0-9.]+,' "$TPL" +expect "the version the job downloads is the recorded tag" bash -c "t=\$(sed -n 's/^# Pinned here: shellcheck v\\([0-9.]*\\),.*/\\1/p' '$TPL'); [ -n \"\$t\" ] && grep -qF \"SHELLCHECK_VERSION: \\\"\$t\\\"\" '$TPL'" +expect "four digests, each written sha256=<64 hex>" bash -c "[ \$(grep -Eo 'sha256=[0-9a-f]{64}' '$TPL' | sort -u | wc -l) -eq 4 ]" +expect "no bare hex run outside sha256= and a pinned uses: line (template)" hex_ok "$TPL" +expect "no bare hex run outside sha256= and a pinned uses: line (rendered)" hex_ok "$CIA" +printf 'x: %s\n' "$(printf '%064d' 0 | tr 0 a)" >"$WORK/bare.txt" +printf 'x: sha256=%s\n' "$(printf '%064d' 0 | tr 0 a)" >"$WORK/marked.txt" +refute "the hex scan catches a bare digest (self-test)" hex_ok "$WORK/bare.txt" +expect "the hex scan allows a marked digest (self-test)" hex_ok "$WORK/marked.txt" +if [ "${STAMP_CI_ONLINE:-}" = 1 ] && command -v gh >/dev/null 2>&1; then + ver="$(sed -n 's/^# Pinned here: shellcheck \(v[0-9.]*\),.*/\1/p' "$TPL")" + gh api "repos/koalaman/shellcheck/releases/tags/$ver" --jq '.assets[] | select(.name | endswith(".tar.gz")) | .digest' 2>/dev/null | sed 's/^sha256:/sha256=/' >"$WORK/online.txt" + expect "online: each pinned digest is in the release metadata" bash -c "[ -s '$WORK/online.txt' ] && for d in \$(grep -Eo 'sha256=[0-9a-f]{64}' '$TPL'); do grep -qxF \"\$d\" '$WORK/online.txt' || exit 1; done" +else + ok "online digest comparison skipped (set STAMP_CI_ONLINE=1 with gh and network)" +fi + +# 6. the shellcheck install step, run from the rendered file with a fake curl and uname +SC_RUN="$WORK/install.sh" +step_run "$CIA" "Install pinned shellcheck" >"$SC_RUN" +expect "the install step was extracted" test -s "$SC_RUN" +VER="$(sed -n 's/^# Pinned here: shellcheck v\([0-9.]*\),.*/\1/p' "$CIA")" +hasher="$(command -v sha256sum 2>/dev/null || command -v shasum)" +mkbin() { # mkbin <dir> <tool>... + local d="$1" t p; shift; mkdir -p "$d" + for t in "$@"; do p="$(command -v "$t" 2>/dev/null)" && case "$p" in /*) ln -sf "$p" "$d/$t";; esac; done +} +fake_curl() { # fake_curl <dir>: a curl that copies $FAKE_TARBALL to the -o target and logs the url + cat >"$1/curl" <<'EOF' +#!/bin/sh +out=""; url="" +while [ $# -gt 0 ]; do + case "$1" in -o) out="$2"; shift;; --retry) shift;; -*) ;; *) url="$1";; esac + shift +done +echo "$url" >> "$FAKE_LOG" +cp "$FAKE_TARBALL" "$out" +EOF + chmod +x "$1/curl" +} +fake_uname() { # fake_uname <dir>: uname -s and uname -m answer from FAKE_S and FAKE_M + cat >"$1/uname" <<'EOF' +#!/bin/sh +case "$1" in -s) echo "$FAKE_S";; -m) echo "$FAKE_M";; *) echo "$FAKE_S";; esac +EOF + chmod +x "$1/uname" +} +digest_of() { if [ "$(basename "$hasher")" = sha256sum ]; then "$hasher" "$1" | cut -d' ' -f1; else "$hasher" -a 256 "$1" | cut -d' ' -f1; fi; } +make_tarball() { # make_tarball <out.tar.gz>: shellcheck-v<ver>/shellcheck, a script that prints a version + local d="$WORK/tb.$$.$RANDOM" + mkdir -p "$d/shellcheck-v$VER" + printf '#!/bin/sh\necho fake shellcheck\n' >"$d/shellcheck-v$VER/shellcheck" + chmod +x "$d/shellcheck-v$VER/shellcheck" + tar -czf "$1" -C "$d" "shellcheck-v$VER" +} +TARBALL="$WORK/fake.tar.gz" +make_tarball "$TARBALL" +FAKE_DIGEST="$(digest_of "$TARBALL")" +# run_install <name> <uname -s> <uname -m> <sha tool: sha256sum|shasum> <script>: result in $irc, logs in $WORK/<name>.* +run_install() { + local name="$1" s="$2" m="$3" tool="$4" script="$5" bin="$WORK/bin-$1" + mkdir -p "$bin" "$WORK/rt-$name" + mkbin "$bin" bash cat mkdir tar gzip cp dirname basename rm sh echo printf + fake_curl "$bin"; fake_uname "$bin" + if [ "$tool" = sha256sum ]; then + printf '#!/bin/sh\nif [ "$(basename "%s")" = sha256sum ]; then exec "%s" "$@"; else exec "%s" -a 256 "$@"; fi\n' "$hasher" "$hasher" "$hasher" >"$bin/sha256sum" + chmod +x "$bin/sha256sum" + else + printf '#!/bin/sh\n[ "$1" = "-a" ] && [ "$2" = "256" ] || { echo "shasum called without -a 256" >&2; exit 9; }\nshift 2\nif [ "$(basename "%s")" = sha256sum ]; then exec "%s" "$@"; else exec "%s" -a 256 "$@"; fi\n' "$hasher" "$hasher" "$hasher" >"$bin/shasum" + chmod +x "$bin/shasum" + fi + : >"$WORK/gp-$name" + : >"$WORK/log-$name" + irc=0 + env -i PATH="$bin" RUNNER_TEMP="$WORK/rt-$name" GITHUB_PATH="$WORK/gp-$name" SHELLCHECK_VERSION="$VER" \ + FAKE_S="$s" FAKE_M="$m" FAKE_TARBALL="$TARBALL" FAKE_LOG="$WORK/log-$name" \ + bash "$script" >"$WORK/$name.out" 2>"$WORK/$name.err" || irc=$? +} +# pinned_for <platform>: the digest the step pins for a platform +repin() { # repin <platform> <hex> <in> <out>: the step with that platform's digest replaced + sed -E "/platform=\"$1\"/ s/sha256=[0-9a-f]{64}/sha256=$2/" "$3" >"$4" +} +n=0 +for row in "Linux x86_64 linux.x86_64" "Linux aarch64 linux.aarch64" "Linux arm64 linux.aarch64" "Darwin x86_64 darwin.x86_64" "Darwin arm64 darwin.aarch64" "Darwin aarch64 darwin.aarch64"; do + set -- $row + s="$1"; m="$2"; plat="$3"; n=$((n + 1)) + # a build whose digest differs from the pin fails the job + run_install "bad$n" "$s" "$m" sha256sum "$SC_RUN" + expect "$s $m: a build with a different digest fails the job" [ "$irc" -ne 0 ] + expect "$s $m: the mismatch message names the asset" grep -q "the digest of shellcheck-v$VER.$plat.tar.gz is sha256=" "$WORK/bad$n.err" + expect "$s $m: a mismatch leaves GITHUB_PATH untouched" test ! -s "$WORK/gp-bad$n" + expect "$s $m: the asset is picked by platform" grep -qF "koalaman/shellcheck/releases/download/v$VER/shellcheck-v$VER.$plat.tar.gz" "$WORK/log-bad$n" + # the same build with its digest pinned passes, with either hash tool + repin "$plat" "$FAKE_DIGEST" "$SC_RUN" "$WORK/install-ok$n.sh" + run_install "okA$n" "$s" "$m" sha256sum "$WORK/install-ok$n.sh" + expect "$s $m: a matching digest passes (sha256sum)" [ "$irc" -eq 0 ] + expect "$s $m: the tool dir is put on GITHUB_PATH" grep -q "shellcheck-install/shellcheck-v$VER\$" "$WORK/gp-okA$n" + expect "$s $m: the installed shellcheck ran --version" grep -q 'fake shellcheck' "$WORK/okA$n.out" + run_install "okB$n" "$s" "$m" shasum "$WORK/install-ok$n.sh" + expect "$s $m: a matching digest passes with shasum -a 256 when sha256sum is absent" [ "$irc" -eq 0 ] + run_install "badB$n" "$s" "$m" shasum "$SC_RUN" + expect "$s $m: a mismatch fails with shasum -a 256 too" [ "$irc" -ne 0 ] +done +run_install "plat-unknown" FreeBSD amd64 sha256sum "$SC_RUN" +expect "an unpinned platform fails the job" [ "$irc" -ne 0 ] +expect "an unpinned platform: names the platform" grep -q 'no pinned build for FreeBSD amd64' "$WORK/plat-unknown.err" +expect "an unpinned platform: nothing is downloaded" test ! -s "$WORK/log-plat-unknown" +# the pinned digests differ by platform (a copy-paste of one digest would pass the cases above) +expect "the four pinned digests are all different" bash -c "[ \$(grep -Eo 'sha256=[0-9a-f]{64}' '$CIA' | sort -u | wc -l) -eq 4 ]" + +# 7. the gate scripts come from the base revision, so a pull request cannot weaken them +G="$(newrepo)" +gi "$G" symbolic-ref HEAD refs/heads/master +mkdir -p "$G/scripts" +cp "$ROOT/templates/team-stamp/files/scripts/check-owners.sh" "$G/scripts/check-owners.sh" +printf '#!/bin/sh\necho base-version\n' >"$G/scripts/pr-shape.sh" +printf '# Owners\n\n| Path | What it does | Owner | Sponsor |\n|---|---|---|---|\n| `scripts/check-owners.sh` | owners | @t | |\n| `scripts/pr-shape.sh` | shape | @t | |\n' >"$G/OWNERS.md" +printf '#!/bin/sh\necho x\n' >"$G/scripts/unowned.sh" +gi "$G" add -A; gi "$G" commit -q -m base +BASE="$(gi "$G" rev-parse HEAD)" +printf 'exit 0\n' >"$G/scripts/check-owners.sh" +printf '#!/bin/sh\necho weak-version\n' >"$G/scripts/pr-shape.sh" +gi "$G" add -A; gi "$G" commit -q -m "weaken the gates" +HEAD_="$(gi "$G" rev-parse HEAD)" +gate_step() { # gate_step <name> <step name> <BASE_SHA>: run the step in $G; result in $grc + step_run "$CIA" "$2" >"$WORK/step-$1.sh" + mkdir -p "$WORK/rt-$1" + grc=0 + (cd "$G" && env BASE_SHA="$3" RUNNER_TEMP="$WORK/rt-$1" bash "$WORK/step-$1.sh") >"$WORK/$1.out" 2>"$WORK/$1.err" || grc=$? +} +gate_step own1 "Take the owners check from the base revision" "$BASE" +expect "the owners step takes check-owners.sh from the base" [ "$grc" -eq 0 ] +expect "the copy aside is the base text, not the pull request's" bash -c "grep -q 'check-owners:' '$WORK/rt-own1/gate/check-owners.sh' && ! grep -qx 'exit 0' '$WORK/rt-own1/gate/check-owners.sh'" +step_run "$CIA" "Every script and workflow has an owner" >"$WORK/run-owners.sh" +orc=0 +(cd "$G" && env RUNNER_TEMP="$WORK/rt-own1" bash "$WORK/run-owners.sh") >"$WORK/owners.out" 2>"$WORK/owners.err" || orc=$? +expect "the owners step runs the base copy against the pull request tree: it refuses an unowned script" [ "$orc" -eq 1 ] +expect "the owners refusal names the script" grep -q 'check-owners: no owner yet for scripts/unowned.sh' "$WORK/owners.err" +expect "the pull request's own weakened copy would have passed (the control)" bash -c "cd '$G' && bash scripts/check-owners.sh" +gate_step shape1 "Take the PR shape check from the base revision" "$BASE" +expect "the PR shape step takes pr-shape.sh from the base" [ "$grc" -eq 0 ] +expect "the copy aside is the base text" grep -qx 'echo base-version' "$WORK/rt-shape1/gate/pr-shape.sh" +expect "the step says which revision the copy came from" grep -q "gate: scripts/pr-shape.sh is the copy from base $BASE" "$WORK/shape1.out" +ROOT_C="$(gi "$G" commit-tree -m empty "$(gi "$G" hash-object -t tree -w /dev/null)")" +gate_step shape2 "Take the PR shape check from the base revision" "$ROOT_C" +expect "a base without the script fails the step (the bootstrap pull request is merged by hand)" [ "$grc" -ne 0 ] +expect "no copy of the pull request's script was taken" test ! -s "$WORK/rt-shape2/gate/pr-shape.sh" +expect "the failure says to merge the first stamp pull request by hand" grep -q 'Merge it by hand' "$WORK/shape2.err" +gate_step shape3 "Take the PR shape check from the base revision" "$(printf '%040d' 0)" +expect "a base revision missing from the checkout fails the step" [ "$grc" -ne 0 ] +expect "a missing base revision is named" grep -q 'is not in this checkout' "$WORK/shape3.err" + +# 8. the path filter, with the stamped product paths +filter_run() { # filter_run <name> <BASE> <HEAD>: the product output + step_run "$CIA" "Path filter" >"$WORK/filter-$1.sh" + : >"$WORK/go-$1" + (cd "$G" && env BASE_SHA="$2" HEAD_SHA="$3" GITHUB_OUTPUT="$WORK/go-$1" bash "$WORK/filter-$1.sh") >"$WORK/filter-$1.out" 2>&1 || return 1 + grep -x 'product=.*' "$WORK/go-$1" +} +r="$(filter_run f1 "$BASE" "$HEAD_")" +expect "no product path changed: product=false" [ "$r" = "product=false" ] +mkdir -p "$G/app"; printf 'x\n' >"$G/app/main.rs" +gi "$G" add -A; gi "$G" commit -q -m "touch a product path" +r="$(filter_run f2 "$HEAD_" "$(gi "$G" rev-parse HEAD)")" +expect "a product path changed: product=true" [ "$r" = "product=true" ] +mkdir -p "$G/.github/workflows"; printf 'name: CI\n' >"$G/.github/workflows/ci.yml" +H2="$(gi "$G" rev-parse HEAD)" +gi "$G" add -A; gi "$G" commit -q -m "touch the workflow" +r="$(filter_run f3 "$H2" "$(gi "$G" rev-parse HEAD)")" +expect "the workflow itself changed: product=true" [ "$r" = "product=true" ] +printf 'y\n' >"$G/other.txt" +H3="$(gi "$G" rev-parse HEAD)" +gi "$G" add -A; gi "$G" commit -q -m "touch another path" +r="$(filter_run f4 "$H3" "$(gi "$G" rev-parse HEAD)")" +expect "a path outside the product paths: product=false" [ "$r" = "product=false" ] + +# 9. AC12: the twin set +expect "AC12: the declared set of ci.yml is not empty" bash -c "[ -n \"\$(sed -n 's/^# twin: //p' '$CIA')\" ]" +expect "AC12: the set holds the two gate commands" bash -c "[ \$(sed -n 's/^# twin: //p' '$CIA' | wc -l) -eq 2 ]" +expect "AC12: the declared sets of ci.yml and check.sh match, and every member runs in both with the same inputs" twin_ok "$CIA" "$CKA" +expect "AC12: the same holds for the default-value stamp" twin_ok "$CIB" "$CKB" +# negative controls: drop a command, drop an input, empty the set, add an undeclared command +grep -v 'bash scripts/pr-shape.sh' "$CKA" >"$WORK/ck-nopr.sh" +refute "AC12: check.sh without its pr-shape command fails the twin check" twin_ok "$CIA" "$WORK/ck-nopr.sh" +sed 's/BASE_SHA="\$base" //' "$CKA" >"$WORK/ck-noenv.sh" +refute "AC12: check.sh without the BASE_SHA input fails the twin check" twin_ok "$CIA" "$WORK/ck-noenv.sh" +grep -v '^ PR_BODY: ' "$CIA" >"$WORK/ci-noenv.yml" +refute "AC12: a workflow step without the PR_BODY input fails the twin check" twin_ok "$WORK/ci-noenv.yml" "$CKA" +grep -v '^# twin: ' "$CIA" >"$WORK/ci-empty.yml" +grep -v '^# twin: ' "$CKA" >"$WORK/ck-empty.sh" +refute "AC12: an empty set fails the twin check" twin_ok "$WORK/ci-empty.yml" "$WORK/ck-empty.sh" +sed 's/^ run: bash "\$RUNNER_TEMP\/gate\/pr-shape.sh"$/ run: bash "$RUNNER_TEMP\/gate\/pr-shape.sh" \&\& bash scripts\/extra.sh/' "$CIA" >"$WORK/ci-extra.yml" +refute "AC12: a gate command in ci.yml that the set does not declare fails the twin check" twin_ok "$WORK/ci-extra.yml" "$CKA" +sed 's/^# twin: check-owners.sh$/# twin: check-other.sh/' "$CIA" >"$WORK/ci-other.yml" +refute "AC12: sets that differ fail the twin check" twin_ok "$WORK/ci-other.yml" "$CKA" + +# 10. every generated file: kit-free, no dash characters, no python3, no bash 4 feature, shellcheck clean +for f in scripts/check.sh scripts/test-check.sh .github/workflows/ci.yml; do + expect "$f names no kit path" bash -c "! grep -Eq '$LEAK_PATTERN' '$A/$f'" + expect "$f has no em or en dash" bash -c "! LC_ALL=C grep -q -e '$(printf '\342\200\224')' -e '$(printf '\342\200\223')' '$A/$f'" + expect "$f does not call python3" bash -c "! grep -q 'python3' '$A/$f'" +done +for f in scripts/check.sh scripts/test-check.sh; do + expect "$f has no bash 4 feature" bash -c "! grep -Eq 'readarray|mapfile|grep -P|sed -r|declare -A|\\$\\{[A-Za-z_]+(,,|\\^\\^)\\}' '$A/$f'" + expect "$f holds no bare 40 or 64 digit hex run" bash -c "! grep -Eq '[0-9a-fA-F]{40}' '$A/$f'" + expect "$f has no em or en dash in the template" bash -c "! LC_ALL=C grep -q -e '$(printf '\342\200\224')' -e '$(printf '\342\200\223')' '$ROOT/templates/team-stamp/files/$f.tpl'" + if have_shellcheck; then expect "$f is shellcheck clean at warning" shellcheck -S warning "$A/$f"; else ok "shellcheck not installed, $f skipped"; fi +done +expect "every refusal of check.sh prints Fix: and no lowercase fix:" bash -c "! grep -q 'fix: ' '$CKA'" +expect "check.sh sets no token and makes no gh api call" bash -c "! grep -Eq 'GH_TOKEN|GITHUB_TOKEN|gh api' '$CKA'" +expect "PR text never reaches eval in check.sh" bash -c "! grep -Eq '(^|[^a-z_-])eval[ \t]' '$CKA'" +expect "the header of check.sh says where the PR text comes from, and that gh is optional" bash -c "grep -q 'gh pr view' '$CKA' && grep -q 'No token' '$CKA'" + +# 11. the generated test passes with non-default values (real pr-shape and owners beside it), with the +# defaults and the check group alone (stubs only), and with another tag list +RC=0 +bash "$A/scripts/test-check.sh" >"$WORK/test-a.out" 2>&1 || RC=$? +expect "the generated test passes with non-default values" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/test-a.out" | sed 's/^/ /' +expect "the generated test ran the real-script cases" grep -q 'PASS real scripts, a product change with proof, tag and body: exit 0' "$WORK/test-a.out" +expect "the generated test ran its attacker-text cases" grep -q 'running every Fix line creates no PWNED' "$WORK/test-a.out" +RC=0 +bash "$B/scripts/test-check.sh" >"$WORK/test-b.out" 2>&1 || RC=$? +expect "the generated test passes with the default values and no pr-shape beside it" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/test-b.out" | sed 's/^/ /' +expect "the generated test skips the real-script cases when they are absent" grep -q '^skipped: the real-script cases' "$WORK/test-b.out" +C="$(newrepo)" +bash lib/stamp.sh --only ci,pr-shape,owners --default-branch develop --owner testowner --tags web,api --product-paths src/,services/ "$C" >/dev/null 2>&1 +RC=0 +bash "$C/scripts/test-check.sh" >"$WORK/test-c.out" 2>&1 || RC=$? +expect "the generated test passes with another branch, tags and product paths" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/test-c.out" | sed 's/^/ /' +# a negative control: a check.sh that never runs pr-shape fails the generated test +sed 's/bash scripts\/pr-shape.sh/true/' "$CKA" >"$WORK/check-broken.sh" +D="$(newrepo)" +bash lib/stamp.sh --only ci,pr-shape,owners --default-branch master --owner testowner --tags app,lib --product-paths app/,pkg/ "$D" >/dev/null 2>&1 +cp "$WORK/check-broken.sh" "$D/scripts/check.sh" +RC=0 +bash "$D/scripts/test-check.sh" >"$WORK/test-d.out" 2>&1 || RC=$? +refute "a check.sh that never runs pr-shape fails the generated test" [ "$RC" -eq 0 ] + +# 12. check.sh and ci.yml agree on the real stamped scripts: the real check.sh runs clean on a stamped repo +E="$(newrepo)" +bash lib/stamp.sh --default-branch main --owner testowner "$E" >/dev/null 2>&1 +gi "$E" symbolic-ref HEAD refs/heads/main +gi "$E" add -A +gi "$E" commit -q -m base +gi "$E" update-ref refs/remotes/origin/main "$(gi "$E" rev-parse HEAD)" +gi "$E" checkout -q -b feat/x +printf 'a note\n' >"$E/docs/note.md" +gi "$E" add -A +gi "$E" commit -q -m "docs: add a note" +RC=0 +(cd "$E" && env -u CI PATH="$PATH" bash scripts/check.sh --title "docs: add a note" --body "") >"$WORK/real-check.out" 2>"$WORK/real-check.err" || RC=$? +expect "check.sh passes on a stamped repo with a docs-only change" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || { tail -n 15 "$WORK/real-check.out" "$WORK/real-check.err" | sed 's/^/ /'; } +expect "check.sh ran the owners check, pr-shape and the stamped script tests" bash -c "grep -q 'ok owners' '$WORK/real-check.out' && grep -q 'ok pr-shape' '$WORK/real-check.out' && grep -q 'script test: scripts/test-check.sh' '$WORK/real-check.out'" + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-e2e.sh b/tests/test-stamp-e2e.sh new file mode 100644 index 000000000..424fa6b37 --- /dev/null +++ b/tests/test-stamp-e2e.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# test-stamp-e2e.sh -- every group stamped together: the file set, a kit-free pass over every +# generated test, the named scripts, the owners check, a fixture PR through the stamped checks, +# the scan-safe digests, and the privacy scan of the whole branch. +# STAMP_DENYLIST_FILE=<file, one string per line, kept outside the repo> bash tests/test-stamp-e2e.sh +# The generic leak scan always runs. The denylist scan runs when STAMP_DENYLIST_FILE is set and +# prints one SKIP line otherwise; the release check sets it. +# shellcheck disable=SC2054,SC2046 +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@"; then ok "$label"; else no "$label"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-e2e.XXXXXX")" || exit 1 +MANIFESTS="$ROOT/templates/team-stamp/manifest.d" +VALUES=(--default-branch master --owner testowner --tags app,lib --product-paths app/,pkg/ + --door-paths 'docs/legal/*' --door-approver reviewer --decision-tag decision --board-file docs/BOARD.md) + +# manifest targets, one per line +manifest_targets() { cat "$MANIFESTS"/*.tsv | awk -F'\t' '/^#/ || NF < 5 {next} {print $3}' | LC_ALL=C sort; } +manifest_targets > "$WORK/manifest.txt" + +# ---- 1. full stamp, idempotence, check, defaults from origin/HEAD ---- +D="$WORK/default"; mkdir -p "$D"; git -C "$D" init -q -b main 2>/dev/null +git -C "$D" remote add origin https://example.invalid/x.git +git -C "$D" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main +out="$(bash lib/stamp.sh --owner alice "$D" 2>&1)"; rc=$? +expect "a full stamp with only --owner exits 0 (the branch comes from origin/HEAD)" [ "$rc" -eq 0 ] +created="$(printf '%s\n' "$out" | grep -c '^created: ')" +expect "every manifest row is written (created + merged = rows)" bash -c "[ $((created + $(printf '%s\n' "$out" | grep -c '^merged: '))) -eq $(wc -l < "$WORK/manifest.txt" | tr -d ' ') ]" +out2="$(bash lib/stamp.sh "$D" 2>&1)" +expect "a second run prints only unchanged" bash -c "[ \$(printf '%s\n' \"\$1\" | grep -Evc '^(unchanged|using): ') -eq 0 ]" _ "$out2" +bash lib/stamp.sh --check "$D" >/dev/null 2>&1; expect "--check exits 0 right after" [ "$?" -eq 0 ] +expect "the default branch reached the guard" grep -q 'default_branch="main"' "$D/scripts/agent-guard.sh" + +# ---- 2. the non-default stamp used by everything below ---- +S="$WORK/repo"; mkdir -p "$S"; git -C "$S" init -q -b master 2>/dev/null +git -C "$S" config user.name tester; git -C "$S" config user.email tester@example.invalid +bash lib/stamp.sh "${VALUES[@]}" "$S" >/dev/null 2>&1 +expect "the non-default stamp exits 0" [ -f "$S/.claude/team-stamp.lock" ] + +if command -v actionlint >/dev/null 2>&1; then + expect "actionlint accepts the rendered workflow" bash -c "cd '$S' && actionlint .github/workflows/ci.yml" +else + ok "actionlint not installed: skipped" +fi +expect "the workflow runs on [self-hosted] and names no hosted runner" bash -c "grep -q 'runs-on: \\[self-hosted\\]' '$S/.github/workflows/ci.yml' && ! grep -Eq 'ubuntu-|macos-|windows-' '$S/.github/workflows/ci.yml'" +# AC1: the file set equals the manifest, the lock, and the spec's table +awk '$1=="file"{print $2}' "$S/.claude/team-stamp.lock" | LC_ALL=C sort > "$WORK/lock.txt" +expect "the lock lists exactly the manifest targets" cmp -s "$WORK/manifest.txt" "$WORK/lock.txt" +missing=0 +while IFS= read -r t; do [ -e "$S/$t" ] || { missing=1; echo " missing $t"; }; done < "$WORK/manifest.txt" +expect "every manifest target exists in the stamped repo" [ "$missing" -eq 0 ] +extra="$(cd "$S" && find . -path ./.git -prune -o -type f -print | sed 's|^\./||' | LC_ALL=C sort | grep -vxF -f "$WORK/manifest.txt" | grep -v '^\.claude/team-stamp\.lock$')" +expect "the stamp writes nothing beyond the manifest and the lock" [ -z "$extra" ] +# spec table: the first backticked path of the target column +SPEC=docs/specs/SPEC-425-team-stamp.md +awk -F'|' '/^\| [0-9]+ \|/ {print $4}' "$SPEC" | grep -o '`[^`]*`' | head -n 200 | tr -d '`' | grep -E '^[A-Za-z0-9_.@/-]+$' | grep -vE '^\.claude/memory/\*|^\*' > "$WORK/spec-targets.txt" +spec_missing="" +while IFS= read -r t; do + case "$t" in */\*) continue;; esac + grep -qxF "$t" "$WORK/manifest.txt" || spec_missing="$spec_missing $t" +done < "$WORK/spec-targets.txt" +expect "every path in the spec's file table is a manifest target" bash -c "[ -z \"\$1\" ]" _ "$spec_missing" +[ -z "$spec_missing" ] || echo " not in the manifest:$spec_missing" +outside="$(grep -vxF -f "$WORK/spec-targets.txt" "$WORK/manifest.txt" | grep -vE '^scripts/test-[a-z-]+\.sh$|^\.claude/memory/[A-Za-z-]+\.md$')" +expect "the manifest holds nothing the spec's table does not name (tests and lesson notes aside)" bash -c "[ -z \"\$1\" ]" _ "$outside" +[ -z "$outside" ] || echo " not in the spec table: $(printf '%s' "$outside" | tr '\n' ' ')" +modes_bad=0 +for t in $(grep -E '^scripts/.*\.sh$' "$WORK/manifest.txt"); do [ -x "$S/$t" ] || { modes_bad=1; echo " not executable: $t"; }; done +expect "every generated script is executable" [ "$modes_bad" -eq 0 ] + +# AC2, AC3: every generated test, kit absent, non-default values (the harness stamps and runs them) +bash tests/test-stamp-kitfree.sh all > "$WORK/kitfree.out" 2>&1; krc=$? +ntests="$(grep -c '^scripts/test-' "$WORK/manifest.txt")" +nran="$(grep -c '^ok - kit-free run: scripts/test-' "$WORK/kitfree.out")" +expect "the kit-free harness exits 0" [ "$krc" -eq 0 ] +[ "$krc" -eq 0 ] || sed 's/^/ /' "$WORK/kitfree.out" | grep -iE 'not ok|FAIL' | head -n 8 +expect "it ran every generated scripts/test-*.sh ($ntests)" [ "$nran" -eq "$ntests" ] +expect "it found no kit path in any generated file" grep -q 'names a kit path' "$WORK/kitfree.out" + +# named scripts in the three rule docs exist in the stamp +names_bad=0 +for doc in AGENTS.md docs/TEAM-WORKFLOW.md .claude/skills/ship-pr/SKILL.md; do + for p in $(grep -oE 'scripts/[A-Za-z0-9_-]+\.sh' "$S/$doc" | sort -u); do + [ -f "$S/$p" ] || { names_bad=1; echo " $doc names $p, which does not exist"; } + done +done +expect "every script the rule docs and the playbook name exists in the stamp" [ "$names_bad" -eq 0 ] +expect "every script a Fix: line in the guard names exists" bash -c "cd '$S' && for p in \$(grep -oE 'scripts/[A-Za-z0-9_-]+\\.sh' scripts/agent-guard.sh | sort -u); do [ -f \"\$p\" ] || exit 1; done" + +# ---- 3. owners, on the tracked files of the full stamp ---- +git -C "$S" add -A >/dev/null 2>&1 +own="$(cd "$S" && bash scripts/check-owners.sh 2>&1)"; orc=$? +expect "check-owners passes on the full stamp" [ "$orc" -eq 0 ] +expect "and it counted every script, test and the workflow" bash -c "[ \$(printf '%s' \"\$1\" | grep -oE '^check-owners: [0-9]+' | grep -oE '[0-9]+') -eq $(grep -cE '^(scripts/.*\.sh|\.github/workflows/.*)$' "$WORK/manifest.txt") ]" _ "$own" + +# ---- 4. scan-safe digests and no home path in the staged stamp ---- +git -C "$S" diff --cached > "$WORK/staged.diff" +# leaks <file>: lines with a bare hex run, a home path, a secret reference or an email. Allowed: +# a 40-hex pin in `uses: owner/repo@<sha> # v...`, a 64-hex run right after a sha256 marker. +# hexleaks <file>: only the hex shapes; pathleaks <file>: home path, secret reference, email. +hexleaks() { + sed -E 's/(uses: [A-Za-z0-9._\/-]+@)[0-9a-f]{40}( # v[0-9A-Za-z._-]+)/\1\2/; s/(sha256: |sha256:|sha256=|sha256-|sha256 "|sha256 '"'"')[0-9a-f]{64}//g' "$1" \ + | grep -nE '[0-9a-f]{64}|[0-9a-f]{40}' +} +pathleaks() { + grep -nE '/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+|op://|[A-Za-z0-9._+-]+@[A-Za-z0-9-]+\.[A-Za-z]{2,}' "$1" \ + | grep -vE '@example\.(invalid|com)|noreply\.github\.com|@v[0-9]' +} +leaks() { hexleaks "$1"; pathleaks "$1"; } +expect "the staged stamp is not empty" [ -s "$WORK/staged.diff" ] +leak_out="$(leaks "$WORK/staged.diff" | cut -c1-120 | head -n 5)" +expect "the staged stamp has no bare hex run, home path, secret reference or email" bash -c "[ -z \"\$1\" ]" _ "$leak_out" +[ -z "$leak_out" ] || printf ' %s\n' "$leak_out" +printf 'x %s\n' "$(printf 'b%.0s' $(seq 1 64))" > "$WORK/bare.txt" +expect "the leak scan flags a bare 64-hex run (self-test)" bash -c "$(declare -f hexleaks); hexleaks '$WORK/bare.txt' >/dev/null" + +# ---- 5. a fixture PR built per the stamped rules passes the stamped checks ---- +git -C "$S" commit -q -m "chore: stamp the harness" +git -C "$S" update-ref refs/remotes/origin/master HEAD +git -C "$S" checkout -q -b feat/greet +mkdir -p "$S/app" +printf '#!/usr/bin/env bash\ngreet() { echo "hello $1"; }\n' > "$S/app/greet.sh" +printf '#!/usr/bin/env bash\n# shellcheck source=app/greet.sh\ncd "$(dirname "$0")/.." || exit 1\nsource app/greet.sh\n[ "$(greet bob)" = "hello bob" ] || { echo "FAIL greet"; exit 1; }\necho "ok greet"\n' > "$S/app/test-greet.sh" +git -C "$S" add app && git -C "$S" commit -q -m "feat(app): add greet" +nc="$(cd "$S" && bash scripts/negctl.sh "bash app/test-greet.sh" "printf '#!/usr/bin/env bash\ngreet() { echo bye; }\n' > app/greet.sh" 2>&1)"; nrc=$? +expect "the stamped negctl runs green, break, red, restore, green" [ "$nrc" -eq 0 ] +expect "and prints a NEGATIVE CONTROL block with a Verdict: RED line" bash -c "printf '%s\n' \"\$1\" | grep -q '^NEGATIVE CONTROL' && printf '%s\n' \"\$1\" | grep -q '^Verdict: RED'" _ "$nc" +mkdir -p "$S/docs/verification" +{ printf '# Proof: greet\n\nCommand: bash app/test-greet.sh\nExit: 0\nOutput:\nok greet\nVerdict: PASS\n\n'; printf '%s\n' "$nc"; } > "$S/docs/verification/greet.md" +printf '\n- app: add greet\n' >> "$S/CHANGELOG.md" +git -C "$S" add -A && git -C "$S" commit -q -m "docs: proof and changelog for greet" +pr_out="$(cd "$S" && PR_TITLE='feat(app): add greet' PR_BODY='Closes #1' BASE_SHA="$(git rev-parse origin/master)" HEAD_SHA="$(git rev-parse HEAD)" bash scripts/pr-shape.sh 2>&1)"; prc=$? +expect "pr-shape passes the fixture PR" [ "$prc" -eq 0 ] +[ "$prc" -eq 0 ] || printf '%s\n' "$pr_out" | head -n 8 | sed 's/^/ /' +expect "the stamped negctl block is accepted by the stamped proof check" bash -c "printf '%s\n' \"\$1\" | grep -q 'NEGATIVE CONTROL block'" _ "$pr_out" +chk="$(cd "$S" && bash scripts/check.sh --title 'feat(app): add greet' --body 'Closes #1' 2>&1)"; crc=$? +expect "check.sh passes the fixture PR (owners, pr-shape, every script test)" [ "$crc" -eq 0 ] +[ "$crc" -eq 0 ] || printf '%s\n' "$chk" | grep -E 'FAIL|check:|Fix' | head -n 8 | sed 's/^/ /' +# the same PR without its changelog line is refused with the two-line shape +git -C "$S" revert --no-edit HEAD >/dev/null 2>&1 && true +bad="$(cd "$S" && PR_TITLE='feat(app): add greet' PR_BODY='Closes #1' BASE_SHA="$(git rev-parse origin/master)" HEAD_SHA="$(git rev-parse HEAD)" bash scripts/pr-shape.sh 2>&1 >/dev/null)"; brc=$? +expect "without the proof and changelog commit the same PR fails" [ "$brc" -eq 1 ] +expect "and the refusal ends with the rule line then a Fix: line" bash -c "printf '%s\n' \"\$1\" | tail -n 2 | sed -n 2p | grep -q '^Fix: '" _ "$bad" + +# ---- 6. privacy: the whole branch, the fixtures, the proof ---- +# The generic leak-shape scan always runs and can always fail. The denylist scan runs when +# STAMP_DENYLIST_FILE names a list kept outside the repo; unset, it prints one SKIP line and passes. +base="$(git rev-parse --verify -q origin/master || true)" +# what ships in the templates, the fixtures, the gauntlet fixtures, the proof and this ticket's records +{ cat $(find templates/team-stamp tests/fixtures/team-stamp tests/gauntlet/team-stamp -type f 2>/dev/null) + [ -f docs/verification/team-stamp.md ] && cat docs/verification/team-stamp.md + for d in docs/verification/gauntlet/*team-stamp*; do [ -d "$d" ] && cat $(find "$d" -type f 2>/dev/null); done +} > "$WORK/shipped.txt" 2>/dev/null +expect "the shipped files (templates, fixtures, proof, gauntlet record) are not empty" [ -s "$WORK/shipped.txt" ] +leak_ship="$(leaks "$WORK/shipped.txt" | cut -c1-100 | head -n 5)" +expect "the templates, fixtures and proof have no bare hex run, home path, secret reference or email" bash -c "[ -z \"\$1\" ]" _ "$leak_ship" +[ -z "$leak_ship" ] || printf ' %s\n' "$leak_ship" +if [ -n "$base" ]; then + { git diff -U0 "$base" -- . ':!docs/reference/FEATURES.md' | grep '^+' | grep -v '^+++' + git log "$base"..HEAD --format='%B' + for f in $(git ls-files --others --exclude-standard); do cat "$f"; done + } > "$WORK/branch.txt" 2>/dev/null + leak_branch="$(hexleaks "$WORK/branch.txt" | cut -c1-100 | head -n 5)" + expect "the branch diff has no bare hex run" bash -c "[ -z \"\$1\" ]" _ "$leak_branch" + [ -z "$leak_branch" ] || printf ' %s\n' "$leak_branch" +else + echo "SKIP - no origin/master to diff the branch against: the branch-diff hex scan did not run" +fi +if [ -z "${STAMP_DENYLIST_FILE:-}" ]; then + echo "SKIP - STAMP_DENYLIST_FILE is unset: the denylist scan did not run (the release check sets it)" +elif [ ! -f "$STAMP_DENYLIST_FILE" ]; then + no "STAMP_DENYLIST_FILE does not name a file" +else + if [ -n "$base" ]; then + hits="$(grep -cF -f "$STAMP_DENYLIST_FILE" "$WORK/branch.txt")" + expect "no denylist string appears in the branch ($hits hits)" [ "$hits" -eq 0 ] + fi + gen_hits="$(grep -rlF -f "$STAMP_DENYLIST_FILE" "$S" --exclude-dir=.git 2>/dev/null | wc -l | tr -d ' ')" + expect "no denylist string appears in a stamped repo ($gen_hits files)" [ "$gen_hits" -eq 0 ] + ship_hits="$(grep -cF -f "$STAMP_DENYLIST_FILE" "$WORK/shipped.txt")" + expect "no denylist string appears in the templates, fixtures, proof or gauntlet record ($ship_hits hits)" [ "$ship_hits" -eq 0 ] +fi + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-hook.sh b/tests/test-stamp-hook.sh new file mode 100644 index 000000000..369e55200 --- /dev/null +++ b/tests/test-stamp-hook.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +# test-stamp-hook.sh -- the "hook" group of the team stamp: the command guard, its generated test, +# and the .claude/settings.json merge. Stamps only that group into temp repos and checks: +# 1. the guard blocks a bare merge with the PR number in the Fix line, a push to the default +# branch and a commit on it, and allows the lookalikes (the generated test holds the rows); +# 2. the guard reads no python3, names no literal default branch, and fails open on bad input; +# 3. the settings merge adds one PreToolUse Bash entry and one SessionStart entry, keeps foreign +# keys and foreign hook entries, adds nothing on a second run, and refuses invalid JSON. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +unset STAMP_TEMPLATES +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@"; then ok "$label"; else no "$label"; fi; } + +command -v jq >/dev/null 2>&1 || { echo "NOT ok - jq is needed for this suite" >&2; exit 1; } +ls "$ROOT"/templates/team-stamp/manifest.d/*-hook.tsv >/dev/null 2>&1 || { echo "NOT ok - no hook manifest" >&2; exit 1; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-hook.XXXXXX")" || exit 1 +STAMP="bash $ROOT/lib/stamp.sh --only hook" +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +guard_json() { jq -n --arg c "$2" --arg d "$1" '{hook_event_name:"PreToolUse",tool_name:"Bash",cwd:$d,tool_input:{command:$c}}'; } +# lit: a word assembled at run time so this file holds no literal default branch name +LIT="ma""in" + +# 1. stamp with a non-default branch +R="$(newrepo)" +$STAMP --default-branch master "$R" >/dev/null 2>&1; RC=$? +expect "stamp the hook group exits 0" [ "$RC" -eq 0 ] +expect "guard is written and executable" [ -x "$R/scripts/agent-guard.sh" ] +expect "guard test is written and executable" [ -x "$R/scripts/test-agent-guard.sh" ] +expect "settings.json is written" [ -f "$R/.claude/settings.json" ] +expect "the lock lists the guard and its test" bash -c 'grep -q "^file scripts/agent-guard.sh " "$1" && grep -q "^file scripts/test-agent-guard.sh " "$1"' _ "$R/.claude/team-stamp.lock" +expect "the guard carries the stamped default branch" grep -q '^default_branch="master"$' "$R/scripts/agent-guard.sh" +expect "the guard names no literal $LIT branch" bash -c '! grep -qw "$1" "$2"' _ "$LIT" "$R/scripts/agent-guard.sh" +expect "the guard test names no literal $LIT branch" bash -c '! grep -qw "$1" "$2"' _ "$LIT" "$R/scripts/test-agent-guard.sh" +expect "the guard has no python3" bash -c '! grep -q python3 "$1" "$2"' _ "$R/scripts/agent-guard.sh" "$R/scripts/test-agent-guard.sh" +expect "the guard lists what it does not catch" grep -q "What this guard does not catch" "$R/scripts/agent-guard.sh" +expect "no unresolved {{KEY}} in a generated file" bash -c '! grep -q "{{" "$1" "$2"' _ "$R/scripts/agent-guard.sh" "$R/scripts/test-agent-guard.sh" +expect "bash -n accepts the guard" bash -n "$R/scripts/agent-guard.sh" + +# 2. the generated test passes (both with the stamped branch and with another one) +bash "$R/scripts/test-agent-guard.sh" >"$WORK/gt.out" 2>&1; RC=$? +expect "the generated guard test passes (master)" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/gt.out" | sed 's/^/ /' +R2="$(newrepo)" +$STAMP --default-branch trunk "$R2" >/dev/null 2>&1 +bash "$R2/scripts/test-agent-guard.sh" >"$WORK/gt2.out" 2>&1; RC=$? +expect "the generated guard test passes (trunk)" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/gt2.out" | sed 's/^/ /' +expect "the generated test holds a row per known probe" bash -c ' + t="$1"; for p in "env -i git commit" "timeout 5 git push origin" "git push --all" "git push --mirror" "pulls/9/merge" "pr merge 7" "git checkout README.md; git commit"; do + grep -qF -- "$p" "$t" || { echo "missing row: $p" >&2; exit 1; } + done' _ "$R/scripts/test-agent-guard.sh" + +# 3. the contract end to end: the stamped guard on real hook JSON +G="$R/scripts/agent-guard.sh" +git -C "$R" symbolic-ref HEAD refs/heads/master +git -C "$R" -c user.name=t -c user.email=t@example.invalid commit -q --allow-empty -m init 2>/dev/null +guard_json "$R" 'gh pr merge 7 --squash' | bash "$G" >/dev/null 2>"$WORK/e1"; RC=$? +expect "bare gh pr merge 7 exits 2" [ "$RC" -eq 2 ] +expect "bare merge: two stderr lines" [ "$(wc -l <"$WORK/e1" | tr -d ' ')" = 2 ] +expect "bare merge: line 2 is the Fix line with the PR number" [ "$(sed -n 2p "$WORK/e1")" = "Fix: bash scripts/pr-merge.sh --wait 7" ] +guard_json "$R" 'git push origin master' | bash "$G" >/dev/null 2>"$WORK/e2"; RC=$? +expect "push to the default branch exits 2 with a Fix line" bash -c '[ "$1" -eq 2 ] && [ "$(sed -n 2p "$2" | cut -c1-5)" = "Fix: " ]' _ "$RC" "$WORK/e2" +guard_json "$R" 'git commit -m x' | bash "$G" >/dev/null 2>"$WORK/e3"; RC=$? +expect "a commit on the default branch exits 2" [ "$RC" -eq 2 ] +expect "commit fix is git switch -c" [ "$(sed -n 2p "$WORK/e3")" = "Fix: git switch -c <type>/<slug>" ] +guard_json "$R" 'bash scripts/pr-merge.sh --wait 5' | bash "$G" >/dev/null 2>"$WORK/e4"; RC=$? +expect "pr-merge.sh --wait 5 is allowed, silent" bash -c '[ "$1" -eq 0 ] && [ ! -s "$2" ]' _ "$RC" "$WORK/e4" +guard_json "$R" 'echo "gh pr merge"' | bash "$G" >/dev/null 2>&1; RC=$? +expect "echo \"gh pr merge\" is allowed" [ "$RC" -eq 0 ] +printf '{broken' | bash "$G" >/dev/null 2>&1; RC=$? +expect "broken stdin exits 0" [ "$RC" -eq 0 ] +printf '' | bash "$G" >/dev/null 2>&1; RC=$? +expect "empty stdin exits 0" [ "$RC" -eq 0 ] + +# 4. settings: the two entries, through ${CLAUDE_PROJECT_DIR} +S="$R/.claude/settings.json" +expect "settings.json is valid JSON" jq -e . "$S" >/dev/null +expect "one PreToolUse Bash entry runs the guard" bash -c '[ "$(jq "[.hooks.PreToolUse[] | select(.matcher==\"Bash\") | .hooks[] | select(.command | test(\"agent-guard.sh\"))] | length" "$1")" = 1 ]' _ "$S" +expect "one SessionStart entry runs the lessons script" bash -c '[ "$(jq "[.hooks.SessionStart[].hooks[] | select(.command | test(\"agent-lessons.sh\"))] | length" "$1")" = 1 ]' _ "$S" +expect "both commands go through \${CLAUDE_PROJECT_DIR}" bash -c '[ "$(jq "[.. | .command? // empty | select(startswith(\"bash \\\"\${CLAUDE_PROJECT_DIR}/scripts/\"))] | length" "$1")" = 2 ]' _ "$S" +expect "the settings carry no absolute path" bash -c '! grep -Eq "(/Users/|/home/)" "$1"' _ "$S" + +# 5. second run: nothing to add, nothing changes +before="$(cksum <"$S")" +OUT2="$($STAMP --default-branch master "$R" 2>&1)"; RC=$? +expect "a second run exits 0" [ "$RC" -eq 0 ] +expect "a second run leaves settings.json byte-identical" [ "$(cksum <"$S")" = "$before" ] +expect "a second run prints only unchanged" bash -c '! printf "%s\n" "$1" | grep -Ev "^(unchanged|using): " | grep -q .' _ "$OUT2" + +# 6. foreign keys and a foreign hook entry survive, in the same Bash group +R3="$(newrepo)" +mkdir -p "$R3/.claude" +cat >"$R3/.claude/settings.json" <<'JSON' +{ + "permissions": { "allow": ["Bash(ls:*)"] }, + "hooks": { + "PreToolUse": [ + { "matcher": "Bash", "hooks": [ { "type": "command", "command": "foreign-check.sh" } ] }, + { "matcher": "Edit", "hooks": [ { "type": "command", "command": "foreign-edit.sh" } ] } + ], + "Stop": [ { "hooks": [ { "type": "command", "command": "foreign-stop.sh" } ] } ] + } +} +JSON +OUT3="$($STAMP --default-branch master "$R3" 2>&1)"; RC=$? +S3="$R3/.claude/settings.json" +expect "stamp over a settings.json with foreign entries exits 0" [ "$RC" -eq 0 ] +expect "the foreign top-level key is kept" bash -c '[ "$(jq -r ".permissions.allow[0]" "$1")" = "Bash(ls:*)" ]' _ "$S3" +expect "the foreign Stop hook is kept" bash -c '[ "$(jq -r ".hooks.Stop[0].hooks[0].command" "$1")" = "foreign-stop.sh" ]' _ "$S3" +expect "the foreign Edit entry is kept" bash -c '[ "$(jq -r "[.hooks.PreToolUse[] | select(.matcher==\"Edit\")] | length" "$1")" = 1 ]' _ "$S3" +expect "the foreign Bash hook is kept" bash -c '[ "$(jq -r "[.hooks.PreToolUse[] | select(.matcher==\"Bash\") | .hooks[] | select(.command==\"foreign-check.sh\")] | length" "$1")" = 1 ]' _ "$S3" +expect "the guard entry joins the same Bash group" bash -c '[ "$(jq "[.hooks.PreToolUse[] | select(.matcher==\"Bash\")] | length" "$1")" = 1 ] && [ "$(jq "[.hooks.PreToolUse[] | select(.matcher==\"Bash\") | .hooks[]] | length" "$1")" = 2 ]' _ "$S3" +expect "the report says merged" bash -c 'printf "%s\n" "$1" | grep -q "^merged: .claude/settings.json"' _ "$OUT3" +before3="$(jq -cS . "$S3")" +$STAMP --default-branch master "$R3" >/dev/null 2>&1 +$STAMP --default-branch master "$R3" >/dev/null 2>&1 +expect "two more runs add no duplicate entry" [ "$(jq -cS . "$S3")" = "$before3" ] +expect "--check is clean after the merge" bash -c "$STAMP --check --default-branch master \"$R3\" >/dev/null 2>&1" + +# 7. invalid JSON is refused and nothing is written +R4="$(newrepo)" +mkdir -p "$R4/.claude" +printf '{ not json' >"$R4/.claude/settings.json" +OUT4="$($STAMP --default-branch master "$R4" 2>&1)"; RC=$? +expect "invalid settings.json: the run is refused" [ "$RC" -ne 0 ] +expect "invalid settings.json: left byte-identical" [ "$(cat "$R4/.claude/settings.json")" = "{ not json" ] +expect "invalid settings.json: no guard written" [ ! -e "$R4/scripts/agent-guard.sh" ] +expect "invalid settings.json: the refusal ends in a Fix line" bash -c 'printf "%s\n" "$1" | grep -q "^Fix: "' _ "$OUT4" + +# 8. the generated files are shell-clean +if command -v shellcheck >/dev/null 2>&1; then + expect "shellcheck -S warning on the guard and its test" shellcheck -S warning "$R/scripts/agent-guard.sh" "$R/scripts/test-agent-guard.sh" +else + echo "skip - shellcheck is not installed" +fi + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-kitfree.sh b/tests/test-stamp-kitfree.sh new file mode 100644 index 000000000..16b597ac2 --- /dev/null +++ b/tests/test-stamp-kitfree.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# test-stamp-kitfree.sh -- stamp a group into a temp repo and prove the result is kit-free. +# Usage: bash tests/test-stamp-kitfree.sh <group | fixture | all> +# fixture the fixture tree under tests/fixtures/team-stamp (what test-stamp.sh drives) +# all every group under templates/team-stamp/manifest.d (vacuous pass when none exist yet) +# <group> one manifest group, by the name after "NN-" in its manifest.d file +# Checks, on the stamped repo: +# 1. no generated file matches a kit-path pattern or the home path; +# 2. every generated scripts/test-*.sh passes with PATH holding only plain tools, HOME an empty +# temp dir, no kit variable set, and no kit binary reachable. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +GROUP="${1:-}" +[ -n "$GROUP" ] || { echo "usage: bash tests/test-stamp-kitfree.sh <group|fixture|all>" >&2; exit 64; } + +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } + +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' + +ONLY=(); unset STAMP_TEMPLATES +case "$GROUP" in + fixture) export STAMP_TEMPLATES="$ROOT/tests/fixtures/team-stamp";; + all) + ls "$ROOT"/templates/team-stamp/manifest.d/*.tsv >/dev/null 2>&1 || { echo "ok - no groups yet, nothing to stamp"; exit 0; };; + *) + ls "$ROOT"/templates/team-stamp/manifest.d/*-"$GROUP".tsv >/dev/null 2>&1 || { echo "NOT ok - no manifest group named '$GROUP'" >&2; exit 1; } + ONLY=(--only "$GROUP");; +esac + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/stamp-kitfree.XXXXXX")" || exit 1 +REPO="$WORK/repo"; mkdir -p "$REPO" "$WORK/home" "$WORK/bin" +git -C "$REPO" init -q 2>/dev/null +git -C "$REPO" -c user.name=t -c user.email=t@example.invalid commit -q --allow-empty -m init 2>/dev/null + +if bash "$ROOT/lib/stamp.sh" ${ONLY[@]+"${ONLY[@]}"} --default-branch master --owner testowner --tags app,lib --product-paths app/,pkg/ --door-paths 'docs/legal/*' --door-approver reviewer --decision-tag decision --board-file docs/BOARD.md "$REPO" >"$WORK/stamp.out" 2>&1; then + ok "stamp $GROUP into a temp repo" +else + no "stamp $GROUP into a temp repo"; sed 's/^/ /' "$WORK/stamp.out"; echo "$PASS passed, $FAIL failed"; exit 1 +fi + +# 1. grep every file the lock lists +LOCK="$REPO/.claude/team-stamp.lock" +files="$(awk '$1=="file"{print $2}' "$LOCK")" +bad=0; count=0 +for f in $files; do + count=$((count + 1)) + if grep -Eq "$LEAK_PATTERN" "$REPO/$f" || grep -qF "$HOME" "$REPO/$f"; then + bad=1; echo " kit path in $f: $(grep -En "$LEAK_PATTERN" "$REPO/$f" | head -n 1 | cut -c1-100)" + fi +done +[ "$count" -gt 0 ] && [ "$bad" -eq 0 ] && ok "no generated file ($count) names a kit path or the home path" || no "kit path found in a generated file" + +# 2. run every generated test with the kit absent +for tool in bash sh git jq python3 awk sed grep egrep fgrep sort uniq wc tr cut head tail cat cp mv rm mkdir rmdir ls ln chmod touch date dirname basename \ + mktemp diff cmp find xargs env sleep tee readlink uname id expr test true false printf od shasum sha256sum stat tar gzip realpath seq yes comm paste fold nl rev tac shellcheck actionlint; do + p="$(command -v "$tool" 2>/dev/null)" || continue + case "$p" in /*) ln -sf "$p" "$WORK/bin/$tool";; esac +done +for kitbin in gate classify wrap board stamp; do + PATH="$WORK/bin" command -v "$kitbin" >/dev/null 2>&1 && { no "the stripped PATH reaches a kit binary: $kitbin"; } +done +[ ! -e "$WORK/home/.claude/dwarves-kit" ] && ok "HOME holds no kit directory" + +ran=0 +for t in "$REPO"/scripts/test-*.sh; do + [ -f "$t" ] || continue + ran=$((ran + 1)) + if env -i PATH="$WORK/bin" HOME="$WORK/home" TMPDIR="$WORK" \ + GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@example.invalid GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@example.invalid \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null \ + "$WORK/bin/bash" "$t" >"$WORK/t.out" 2>&1; then + ok "kit-free run: ${t#"$REPO"/}" + else + no "kit-free run: ${t#"$REPO"/}"; { grep -iE "FAIL|not ok" "$WORK/t.out" | head -n 10; tail -n 3 "$WORK/t.out"; } | sed 's/^/ /' + fi +done +[ "$ran" -gt 0 ] || ok "no generated scripts/test-*.sh in this group" + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-lessons.sh b/tests/test-stamp-lessons.sh new file mode 100644 index 000000000..2db409e27 --- /dev/null +++ b/tests/test-stamp-lessons.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# test-stamp-lessons.sh -- the lessons group of the team stamp: scripts/agent-lessons.sh, its generated +# test, the index and the five seed notes, stamped into a scratch repo and read back. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +TPL="$ROOT/templates/team-stamp" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@"; then ok "$label"; else no "$label"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-lessons.XXXXXX")" || exit 1 +EM="$(printf '\342\200\224')"; EN="$(printf '\342\200\223')" +NOTES="ci-runner-has-no-procps ci-sets-ci-true queued-run-missing-from-lists guards-match-command-text stale-checks-after-a-rule-change" +chars() { wc -c < "$1" | tr -d ' '; } + +R="$(mktemp -d "$WORK/r.XXXXXX")"; git -C "$R" init -q 2>/dev/null +OUT="$(bash lib/stamp.sh --only lessons --default-branch master --tags app,lib --product-paths app/,pkg/ "$R" 2>&1)" +expect "stamp the lessons group" [ $? -eq 0 ] + +# 1. file set and modes +expect "scripts/agent-lessons.sh is written and executable" [ -x "$R/scripts/agent-lessons.sh" ] +expect "scripts/test-agent-lessons.sh is written and executable" [ -x "$R/scripts/test-agent-lessons.sh" ] +expect ".claude/memory/MEMORY.md is written" [ -f "$R/.claude/memory/MEMORY.md" ] +for n in $NOTES; do + expect "seed note $n.md is written" [ -f "$R/.claude/memory/$n.md" ] +done +expect "the group writes exactly 8 files" bash -c "[ \$(awk '\$1==\"file\"' '$R/.claude/team-stamp.lock' | wc -l | tr -d ' ') -eq 8 ]" +expect "the index and the five notes are seed rows" bash -c "[ \$(grep -c '^seed ' '$TPL/manifest.d/20-lessons.tsv') -eq 6 ]" +expect "the two scripts are copy rows" bash -c "[ \$(grep -c '^copy ' '$TPL/manifest.d/20-lessons.tsv') -eq 2 ]" + +# 2. the script on the stamped repo +bash "$R/scripts/agent-lessons.sh" > "$WORK/idx.out" 2>&1; rc=$? +expect "the script prints the stamped index" cmp -s "$R/.claude/memory/MEMORY.md" "$WORK/idx.out" +expect "the script exits 0" [ "$rc" -eq 0 ] +(cd "$WORK" && bash "$R/scripts/agent-lessons.sh" > "$WORK/elsewhere.out" 2>&1) +expect "the script finds the repo from another directory" cmp -s "$R/.claude/memory/MEMORY.md" "$WORK/elsewhere.out" +CP="$(mktemp -d "$WORK/cp.XXXXXX")"; mkdir -p "$CP/scripts"; cp "$R/scripts/agent-lessons.sh" "$CP/scripts/" +bash "$CP/scripts/agent-lessons.sh" > "$WORK/none.out" 2>&1; rc=$? +expect "no index: exit 0" [ "$rc" -eq 0 ] +expect "no index: no output" [ ! -s "$WORK/none.out" ] +mkdir -p "$CP/.claude/memory" +i=0; { echo "# Repo lessons"; while [ "$i" -lt 150 ]; do i=$((i + 1)); echo "- [Lesson $i](l$i.md): a line that pads the index past the cap, number $i, so the cut is measurable."; done; } > "$CP/.claude/memory/MEMORY.md" +size="$(chars "$CP/.claude/memory/MEMORY.md")" +bash "$CP/scripts/agent-lessons.sh" > "$WORK/cut.out" 2>&1; rc=$? +expect "an index of $size characters: exit 0" [ "$rc" -eq 0 ] +expect "an index past 9,000 characters is cut with a notice" bash -c "tail -n 1 '$WORK/cut.out' | grep -q '^agent-lessons: the index is $size characters'" +expect "the cut output stays under 10,000 characters" [ "$(chars "$WORK/cut.out")" -lt 10000 ] +if [ -x /bin/bash ]; then + /bin/bash "$CP/scripts/agent-lessons.sh" > "$WORK/cut2.out" 2>&1 + expect "the system bash gives the same cut output" cmp -s "$WORK/cut.out" "$WORK/cut2.out" +fi + +# 3. the generated test, with the scripts and notes as stamped +bash "$R/scripts/test-agent-lessons.sh" > "$WORK/gen.out" 2>&1; rc=$? +expect "the generated test passes" [ "$rc" -eq 0 ] +expect "the generated test ran its cases ($(grep -c '^PASS' "$WORK/gen.out"))" [ "$(grep -c '^PASS' "$WORK/gen.out")" -ge 15 ] +if [ -x /bin/bash ]; then + /bin/bash "$R/scripts/test-agent-lessons.sh" > "$WORK/gen2.out" 2>&1 + expect "the generated test passes under the system bash" [ $? -eq 0 ] +fi +# the generated test goes red on a broken index +RB="$(mktemp -d "$WORK/rb.XXXXXX")"; cp -R "$R/scripts" "$R/.claude" "$RB/" +printf '\n- [Dead](dead-note.md): a link to a note that does not exist.\n' >> "$RB/.claude/memory/MEMORY.md" +bash "$RB/scripts/test-agent-lessons.sh" > "$WORK/red1.out" 2>&1; rc=$? +expect "a dead index link turns the generated test red" [ "$rc" -ne 0 ] +RC2="$(mktemp -d "$WORK/rc.XXXXXX")"; cp -R "$R/scripts" "$R/.claude" "$RC2/" +printf 'no frontmatter here\n' > "$RC2/.claude/memory/ci-sets-ci-true.md" +bash "$RC2/scripts/test-agent-lessons.sh" > "$WORK/red2.out" 2>&1; rc=$? +expect "a note without frontmatter turns the generated test red" [ "$rc" -ne 0 ] +RD="$(mktemp -d "$WORK/rd.XXXXXX")"; cp -R "$R/scripts" "$R/.claude" "$RD/" +sed 's/exit 0/exit 1/g' "$RD/scripts/agent-lessons.sh" > "$RD/scripts/x.sh" && mv "$RD/scripts/x.sh" "$RD/scripts/agent-lessons.sh" +bash "$RD/scripts/test-agent-lessons.sh" > "$WORK/red3.out" 2>&1; rc=$? +expect "a script that exits non-zero turns the generated test red" [ "$rc" -ne 0 ] + +# 4. the seed notes +for n in $NOTES; do + f="$TPL/files/.claude/memory/$n.md" + fm="$(awk 'NR==1 && $0=="---" {f=1; next} f && $0=="---" {exit} f {print}' "$f")" + expect "$n: line 1 is ---" [ "$(head -n 1 "$f")" = "---" ] + expect "$n: name matches the file name" bash -c "printf '%s\n' \"\$1\" | grep -qx 'name: $n'" _ "$fm" + expect "$n: has a description" bash -c "printf '%s\n' \"\$1\" | grep -q '^description: .'" _ "$fm" + expect "$n: description is one sentence under 200 characters" bash -c "[ \$(printf '%s\n' \"\$1\" | grep '^description: ' | wc -c | tr -d ' ') -lt 215 ]" _ "$fm" + expect "$n: under 1,200 characters ($(chars "$f"))" [ "$(chars "$f")" -lt 1200 ] + expect "$n: states why and how to apply" bash -c "grep -q '^\*\*Why:\*\*' '$f' && grep -q '^\*\*How to apply:\*\*' '$f'" + expect "$n: is listed in the index" grep -qF "]($n.md)" "$TPL/files/.claude/memory/MEMORY.md" + expect "$n: holds no @-mention and no email address" bash -c "! grep -q '@' '$f'" + expect "$n: holds no date" bash -c "! grep -Eq '[0-9]{4}-[0-9]{2}-[0-9]{2}' '$f'" +done +expect "the index is under 8,000 characters ($(chars "$TPL/files/.claude/memory/MEMORY.md"))" [ "$(chars "$TPL/files/.claude/memory/MEMORY.md")" -lt 8000 ] +expect "the index lists exactly five notes" bash -c "[ \$(grep -c '^- \[' '$TPL/files/.claude/memory/MEMORY.md') -eq 5 ]" +G="$TPL/files/.claude/memory/guards-match-command-text.md" +expect "the guard note lists known misses" grep -q '^Known misses:' "$G" +expect "the guard note names the variable-built command and the gh api merge" bash -c "grep -q 'variables' '$G' && grep -qF 'gh api' '$G'" +expect "the guard note stays under 1,200 characters" [ "$(chars "$G")" -lt 1200 ] +expect "the guard note points at the guard test for the probe rows" grep -qF 'scripts/test-agent-guard.sh' "$G" + +# 5. hygiene of the group's files +for f in "$TPL"/files/.claude/memory/*.md "$TPL/files/scripts/agent-lessons.sh" "$TPL/files/scripts/test-agent-lessons.sh" "$TPL/manifest.d/20-lessons.tsv"; do + b="${f#"$TPL"/}" + expect "$b has no em or en dash" bash -c "! grep -qF -e '$EM' -e '$EN' '$f'" + expect "$b has no bare 40 or 64 digit hex string" bash -c "! grep -Eq '(^|[^0-9a-fA-F])([0-9a-fA-F]{40}|[0-9a-fA-F]{64})([^0-9a-fA-F]|\$)' '$f'" +done +for f in "$TPL/files/scripts/agent-lessons.sh" "$TPL/files/scripts/test-agent-lessons.sh"; do + b="${f#"$TPL"/}" + expect "$b uses no python3, mapfile, readarray, grep -P or sed -r" bash -c "! grep -Eq 'python3|mapfile|readarray|grep -[a-zA-Z]*P|sed -[a-zA-Z]*r' '$f'" + expect "$b parses under bash -n" bash -n "$f" + if command -v shellcheck >/dev/null 2>&1; then + expect "$b is shellcheck clean at warning level" shellcheck -S warning "$f" + fi +done + +# 6. idempotent, and repo edits to seed files never drift +OUT="$(bash lib/stamp.sh --only lessons "$R" 2>&1)" +expect "a second run prints only unchanged" bash -c "! printf '%s\n' \"\$1\" | grep -Evq '^(unchanged|using): '" _ "$OUT" +printf -- '- [Mine](mine.md): a lesson of this repo.\n' >> "$R/.claude/memory/MEMORY.md" +printf -- '---\nname: mine\ndescription: a repo note.\n---\n\nbody\n' > "$R/.claude/memory/mine.md" +bash lib/stamp.sh --only lessons --check "$R" >/dev/null 2>&1 +expect "--check stays clean after the repo edits the index and adds a note" [ $? -eq 0 ] +bash "$R/scripts/test-agent-lessons.sh" > "$WORK/gen3.out" 2>&1 +expect "the generated test accepts a repo's own note" [ $? -eq 0 ] + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-merge.sh b/tests/test-stamp-merge.sh new file mode 100644 index 000000000..ca325e10a --- /dev/null +++ b/tests/test-stamp-merge.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +# test-stamp-merge.sh -- the merge group of the team stamp: scripts/pr-merge.sh, scripts/negctl.sh and +# their generated tests. Stamps the group into temp repos with two value sets, runs the generated tests, +# checks the files are kit-free and clean, and compares the kit's lib/gate/negctl.sh with the stamped +# scripts/negctl.sh on one tiny fixture repo (the five labelled parts of the block, by shape). +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { # expect <label> <command...> + local label="$1"; shift + if "$@" >/dev/null 2>&1; then ok "$label"; else no "$label"; fi +} + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-merge.XXXXXX")" || exit 1 +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +have_shellcheck() { command -v shellcheck >/dev/null 2>&1; } + +# 1. a stamp with non-default values +A="$(newrepo)" +RC=0 +bash lib/stamp.sh --only merge --default-branch master --owner testowner --door-paths 'docs/legal/*,protocol/*' --door-approver reviewer "$A" >"$WORK/stamp-a.out" 2>&1 || RC=$? +expect "stamp of the merge group exits 0" [ "$RC" -eq 0 ] +expect "the stamp writes exactly four files" bash -c '[ "$(grep -c "^created: " "$1")" -eq 4 ]' _ "$WORK/stamp-a.out" +for f in scripts/pr-merge.sh scripts/test-pr-merge.sh scripts/negctl.sh scripts/test-negctl.sh; do + expect "created $f" grep -qx "created: $f" "$WORK/stamp-a.out" + expect "$f is executable" test -x "$A/$f" + expect "$f is listed in the lock" grep -q "^file $f merge sha256:" "$A/.claude/team-stamp.lock" +done +expect "no {{KEY}} is left in a generated file" bash -c "! grep -rE '\{\{[A-Za-z_]+\}\}' '$A/scripts'" +bash lib/stamp.sh --only merge "$A" >"$WORK/stamp-a2.out" 2>&1 +expect "the second run prints only unchanged lines" bash -c '[ "$(grep -Evc "^(unchanged|using): " "$1")" -eq 0 ] && [ "$(grep -c "^unchanged: " "$1")" -eq 4 ]' _ "$WORK/stamp-a2.out" +expect "--check is clean" bash lib/stamp.sh --only merge --check "$A" + +# 2. stamped values and the dropped behaviors +P="$A/scripts/pr-merge.sh" +expect "default branch comes from the stamp" grep -qxF 'DEFAULT_BRANCH="master"' "$P" +expect "door approver comes from the stamp" grep -qxF 'APPROVER="reviewer"' "$P" +expect "door list comes from the stamp" grep -qxF 'DOORS=("docs/legal/*" "protocol/*")' "$P" +expect "no literal main in the guard" bash -c "! grep -Eq 'origin/main|[^a-z]main[^a-z]' '$P'" +expect "no CI-path flag" bash -c "! grep -q 'allow-ci-change' '$P'" +expect "the header says the self-copy check stops an honest out-of-date copy, not a hostile one" bash -c "grep -q 'It does NOT stop a hostile copy' '$P' && grep -q 'nobody runs a pull request' '$P'" +expect "the guard reads the files from the REST list, paginated, with previous names, and caps at 3000" bash -c "grep -q 'pulls/\$number/files' '$P' && grep -q 'previous_filename' '$P' && grep -q 'MAX_FILES=3000' '$P' && ! grep -q '100 or more' '$P'" +expect "the guard takes only this PR's runs of the stamped workflow file" bash -c "grep -q 'actions/runs?head_sha=' '$P' && grep -q 'pull_requests' '$P' && grep -q 'CI_FILE=' '$P'" +expect "the guard reads the timeline for base changes and refuses a base that is not the default branch" bash -c "grep -q 'base_ref_changed' '$P' && grep -q 'baseRefName' '$P'" +expect "the door patterns are lower case and the path is lowered before the match" bash -c "grep -q 'lp=\"\$(lower' '$P' && ! grep -E '^BASE_DOORS=' '$P' | sed 's/^BASE_DOORS=//' | grep -q '[A-Z]'" +expect "the default doors cover .github, scripts, .claude, OWNERS, AGENTS and CLAUDE at any depth, .mcp.json, the workflow doc and .kit.toml" bash -c "grep -E '^BASE_DOORS=' '$P' | grep -q '\.github/\*' && grep -E '^BASE_DOORS=' '$P' | grep -q '\*/agents.md' && grep -E '^BASE_DOORS=' '$P' | grep -q '\*/claude.md' && grep -E '^BASE_DOORS=' '$P' | grep -q '\.mcp.json'" +expect "no stale-rules refusal" bash -c "! grep -Eiq 'stale|older than the last change|RULE_PATHS' '$P'" +expect "no kit merge-head variable" bash -c "! grep -q 'KIT_' '$P'" +expect "no --all or --refresh mode" bash -c "! grep -Eq -- '--all|--refresh' '$P'" +expect "an empty array expansion is guarded under set -u" grep -q 'DOORS\[@\]+' "$P" +expect "the guard cleans gh text before it is printed" grep -q '^clean() ' "$P" +expect "the guard puts only a safe value into a Fix line" grep -q '^is_safe() ' "$P" +for f in scripts/pr-merge.sh scripts/negctl.sh; do + expect "$f never uses eval" bash -c "! grep -Eq '(^|[^a-z_])eval[[:space:]]' '$A/$f'" +done + +# 3. every generated file: kit-free, no dash characters, no python3, no bare hex digest, shellcheck clean +for f in scripts/pr-merge.sh scripts/test-pr-merge.sh scripts/negctl.sh scripts/test-negctl.sh; do + expect "$f names no kit path" bash -c "! grep -Eq '$LEAK_PATTERN' '$A/$f'" + expect "$f has no em or en dash" bash -c "! LC_ALL=C grep -q -e '$(printf '\342\200\224')' -e '$(printf '\342\200\223')' '$A/$f'" + expect "$f does not call python3" bash -c "! grep -q 'python3' '$A/$f'" + expect "$f holds no bare 40 or 64 digit hex run" bash -c "! grep -Eq '[0-9a-fA-F]{40}' '$A/$f'" + expect "$f uses no GNU-only or bash 4 feature" bash -c "! grep -Eq 'readarray|mapfile|grep -P|sed -r|declare -A' '$A/$f'" + if have_shellcheck; then expect "$f is shellcheck clean" shellcheck -S warning "$A/$f"; else ok "shellcheck not installed, $f skipped"; fi +done +expect "the stamped negctl names no kit script" bash -c "! grep -q 'gate/negctl' '$A/scripts/negctl.sh'" + +# 4. the generated tests pass, with non-default values and with the default empty door list +run_generated() { # run_generated <label> <repo> <test script> + local out rc=0 + out="$(cd "$2" && bash "$3" 2>&1)" || rc=$? + if [ "$rc" -eq 0 ] && printf '%s\n' "$out" | grep -qx 'failures: 0'; then ok "$1"; else no "$1"; printf '%s\n' "$out" | grep -v '^PASS' | tail -n 15 | sed 's/^/ /'; fi +} +run_generated "generated test-pr-merge.sh passes (master, door list, approver)" "$A" scripts/test-pr-merge.sh +run_generated "generated test-negctl.sh passes" "$A" scripts/test-negctl.sh + +B="$(newrepo)" +bash lib/stamp.sh --only merge --default-branch develop --owner testowner "$B" >/dev/null 2>&1 +expect "a default stamp holds an empty door list" grep -qxF 'DOORS=()' "$B/scripts/pr-merge.sh" +expect "a default stamp holds an empty approver" grep -qxF 'APPROVER=""' "$B/scripts/pr-merge.sh" +expect "a default stamp names its own branch" grep -qxF 'DEFAULT_BRANCH="develop"' "$B/scripts/pr-merge.sh" +expect "a default stamp is shellcheck clean or shellcheck is absent" bash -c "! command -v shellcheck >/dev/null 2>&1 || shellcheck -S warning '$B/scripts/pr-merge.sh'" +run_generated "generated test-pr-merge.sh passes (develop, no door list)" "$B" scripts/test-pr-merge.sh + +# 5. the stamped negctl against the kit's, on one tiny fixture repo +mkfixture() { # mkfixture <name>: a committed repo whose test is "a.txt still says good" + local d="$WORK/$1"; mkdir -p "$d" + ( cd "$d" && git init -q 2>/dev/null && git config user.name t && git config user.email t@example.invalid && git config commit.gpgsign false + printf 'good\n' > a.txt + printf '%s\n' 'echo "checking a.txt"' 'grep -q good a.txt || { echo "FAIL a.txt lost good"; exit 1; }' 'echo "ok a.txt"' > test.sh + git add a.txt test.sh && git commit -q -m init ) + echo "$d" +} +K="$(mkfixture kit)"; G="$(mkfixture gen)" +MUT="printf 'bad\n' > a.txt" +( cd "$K" && bash "$ROOT/lib/gate/negctl.sh" "$K" "bash test.sh" "$MUT" ) > "$WORK/kit.out" 2> "$WORK/kit.err"; KRC=$? +( cd "$G" && bash "$A/scripts/negctl.sh" "bash test.sh" "$MUT" ) > "$WORK/gen.out" 2> "$WORK/gen.err"; GRC=$? +expect "the kit negctl goes green, red, green on the fixture" [ "$KRC" -eq 0 ] +expect "the stamped negctl goes green, red, green on the fixture" [ "$GRC" -eq 0 ] + +# the five labelled parts +labels() { # labels <block file>: the labels the block carries, sorted, one per line + awk ' + function see(l) { seen[l] = 1 } + tolower($0) ~ /negative control/ { see("NEGATIVE CONTROL") } + /^Command: / { see("Command:") } + /^Exit: [0-9]+/ { see("Exit:") } + /^Output:/ { see("Output:") } + /^Verdict: / { see("Verdict:") } + END { for (l in seen) print l }' "$1" | LC_ALL=C sort +} +labels "$WORK/kit.out" > "$WORK/kit.labels"; labels "$WORK/gen.out" > "$WORK/gen.labels" +expect "both blocks carry the same five labelled parts" bash -c 'cmp -s "$1" "$2" && [ "$(wc -l < "$1")" -eq 5 ]' _ "$WORK/kit.labels" "$WORK/gen.labels" +red_exit() { awk '/^Exit: [0-9]+ \(under mutation/ { print $2; exit } /^Exit: [0-9]+$/ { print $2; exit }' "$1"; } +expect "both blocks report the same red exit code" bash -c '[ -n "$1" ] && [ "$1" = "$2" ]' _ "$(red_exit "$WORK/kit.out")" "$(red_exit "$WORK/gen.out")" +expect "both blocks name the same test command" bash -c '[ "$(grep -m1 "^Command: " "$1")" = "$(grep -m1 "^Command: " "$2")" ]' _ "$WORK/kit.out" "$WORK/gen.out" +expect "both Output slots hold the failing assertion line" bash -c 'grep -q "FAIL a.txt lost good" "$1" && grep -q "FAIL a.txt lost good" "$2"' _ "$WORK/kit.out" "$WORK/gen.out" +expect "both blocks end on a Verdict line" bash -c '[ "$(grep "^Verdict: " "$1" | tail -n 1 | cut -c1-9)" = "Verdict: " ] && [ "$(grep "^Verdict: " "$2" | tail -n 1 | cut -c1-9)" = "Verdict: " ]' _ "$WORK/kit.out" "$WORK/gen.out" +expect "the stamped verdict is RED, as expected" grep -qx 'Verdict: RED, as expected' "$WORK/gen.out" +# what a pull request check reads in a proof file +proof_ok() { + grep -Eq '^[[:space:]]*Exit:' "$1" && + awk '{ if (prev && $0 != "") f = 1; prev = ($0 ~ /^[[:space:]]*Output:/) } END { exit !f }' "$1" && + grep -Eq '^[[:space:]]*Verdict: RED' "$1" && grep -Eiq 'negative control' "$1" +} +expect "the stamped block holds what a pull request proof check reads" proof_ok "$WORK/gen.out" +expect "both trees are clean and restored after the run" bash -c '[ -z "$(git -C "$1" status --porcelain)" ] && [ -z "$(git -C "$2" status --porcelain)" ] && [ "$(cat "$1/a.txt")" = good ] && [ "$(cat "$2/a.txt")" = good ]' _ "$K" "$G" + +# both refuse a dirty tree before running anything, and a red that is only a syntax error +printf 'edited\n' > "$K/a.txt"; printf 'edited\n' > "$G/a.txt" +( cd "$K" && bash "$ROOT/lib/gate/negctl.sh" "$K" "touch ran-here; bash test.sh" "$MUT" ) > "$WORK/kit-dirty.out" 2>&1; KD=$? +( cd "$G" && bash "$A/scripts/negctl.sh" "touch ran-here; bash test.sh" "$MUT" ) > "$WORK/gen-dirty.out" 2> "$WORK/gen-dirty.err"; GD=$? +expect "both refuse a dirty tree with exit 2" bash -c '[ "$1" -eq 2 ] && [ "$2" -eq 2 ]' _ "$KD" "$GD" +expect "both name REFUSED" bash -c 'grep -q REFUSED "$1" && grep -q REFUSED "$2"' _ "$WORK/kit-dirty.out" "$WORK/gen-dirty.err" +expect "neither ran the test or the mutation" bash -c '[ ! -e "$1/ran-here" ] && [ ! -e "$2/ran-here" ] && [ "$(cat "$1/a.txt")" = edited ] && [ "$(cat "$2/a.txt")" = edited ]' _ "$K" "$G" +expect "the stamped refusal is two lines: rule, then Fix:" bash -c '[ "$(wc -l < "$1")" -eq 2 ] && [ "$(sed -n 2p "$1" | cut -c1-5)" = "Fix: " ]' _ "$WORK/gen-dirty.err" +git -C "$K" checkout -q -- a.txt; git -C "$G" checkout -q -- a.txt + +SYNTAX="printf 'if then\\n' > test.sh" +( cd "$K" && bash "$ROOT/lib/gate/negctl.sh" "$K" "bash test.sh" "$SYNTAX" ) > "$WORK/kit-syn.out" 2>&1; KS=$? +( cd "$G" && bash "$A/scripts/negctl.sh" "bash test.sh" "$SYNTAX" ) > "$WORK/gen-syn.out" 2> "$WORK/gen-syn.err"; GS=$? +expect "both refuse a red that is only a syntax error (exit 1)" bash -c '[ "$1" -eq 1 ] && [ "$2" -eq 1 ]' _ "$KS" "$GS" +expect "neither records it as RED" bash -c '! grep -q "Verdict: RED" "$1" && ! grep -q "Verdict: RED" "$2"' _ "$WORK/kit-syn.out" "$WORK/gen-syn.out" +expect "both restored the test file" bash -c 'grep -q "lost good" "$1/test.sh" && grep -q "lost good" "$2/test.sh"' _ "$K" "$G" +expect "the stamped syntax refusal ends with a Fix: line" bash -c 'tail -n 1 "$1" | grep -q "^Fix: "' _ "$WORK/gen-syn.err" + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-owners.sh b/tests/test-stamp-owners.sh new file mode 100644 index 000000000..395f10cdc --- /dev/null +++ b/tests/test-stamp-owners.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# test-stamp-owners.sh -- the owners group of the team stamp: scripts/check-owners.sh, its generated +# test, and the OWNERS.md seed, stamped into scratch repos and exercised there. +# The cross-group case (the seed of a FULL stamp passes the check) lives in the integration suite; +# here the seed is trimmed to the files this group wrote, then the check is run on it. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@" >/dev/null 2>&1; then ok "$label"; else no "$label"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-owners.XXXXXX")" || exit 1 +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' +EM="$(printf '\342\200\224')"; EN="$(printf '\342\200\223')" +TPL=templates/team-stamp +CHK="$TPL/files/scripts/check-owners.sh" +TST="$TPL/files/scripts/test-check-owners.sh" + +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +two_lines() { # two_lines <file>: exactly one refusal pair, rule then Fix + [ "$(wc -l <"$1" | tr -d ' ')" -eq 2 ] && sed -n 1p "$1" | grep -q '^check-owners: ' && sed -n 2p "$1" | grep -q '^Fix: ' +} + +# 1. manifest rows +M="$TPL/manifest.d/40-owners.tsv" +expect "manifest exists" [ -f "$M" ] +expect "manifest: every row has five tab-separated columns" bash -c "grep -v '^#' '$M' | grep -v '^\$' | awk -F'\t' 'NF != 5 { exit 1 }'" +expect "manifest: the OWNERS.md row is a hook row on the engine's owners seed" bash -c "grep -v '^#' '$M' | awk -F'\t' '\$1 == \"hook\" && \$2 == \"lib/stamp/owners-seed.sh\" && \$3 == \"OWNERS.md\" { f = 1 } END { exit !f }'" +expect "manifest: the check and its test are copy rows" bash -c "grep -v '^#' '$M' | awk -F'\t' '\$1 == \"copy\" && \$3 == \"scripts/check-owners.sh\" { a = 1 } \$1 == \"copy\" && \$3 == \"scripts/test-check-owners.sh\" { b = 1 } END { exit !(a && b) }'" + +# 2. stamp the group +R1="$(newrepo)" +bash lib/stamp.sh --only owners --default-branch main --owner testowner "$R1" >"$WORK/s1.out" 2>&1 +expect "stamp the owners group" [ $? -eq 0 ] +for f in scripts/check-owners.sh scripts/test-check-owners.sh OWNERS.md; do + expect "created: $f" [ -f "$R1/$f" ] +done +expect "check-owners.sh is executable" [ -x "$R1/scripts/check-owners.sh" ] +expect "test-check-owners.sh is executable" [ -x "$R1/scripts/test-check-owners.sh" ] +expect "the check and its test are byte-identical to the templates (agnostic, no value)" bash -c "cmp -s '$CHK' '$R1/scripts/check-owners.sh' && cmp -s '$TST' '$R1/scripts/test-check-owners.sh'" + +# 3. the seed +expect "seed: a row for the check, owned by the stamped owner" grep -q '^| `scripts/check-owners.sh` | .* | @testowner | |$' "$R1/OWNERS.md" +expect "seed: a row for the check's test" grep -q '^| `scripts/test-check-owners.sh` | Test for scripts/check-owners.sh | @testowner | |$' "$R1/OWNERS.md" +expect "seed: the table header names Path, Owner and Sponsor" grep -q '^| Path | What it does | Owner | Sponsor |$' "$R1/OWNERS.md" + +# 4. idempotent, never drift-checked after the repo edits OWNERS.md +bash lib/stamp.sh --only owners --default-branch main --owner testowner "$R1" >"$WORK/s2.out" 2>&1 +expect "second run prints only unchanged" bash -c "[ -s '$WORK/s2.out' ] && ! grep -Ev '^(unchanged|using): ' '$WORK/s2.out'" +printf '| `scripts/extra.sh` | Added by the repo | @someone | |\n' >>"$R1/OWNERS.md" +bash lib/stamp.sh --only owners --check "$R1" >"$WORK/c1.out" 2>&1 +expect "--check stays clean after the repo edits OWNERS.md" [ $? -eq 0 ] + +# 5. the generated test passes in the stamped repo +(cd "$R1" && bash scripts/test-check-owners.sh) >"$WORK/t1.out" 2>&1 +expect "the generated test passes in the stamped repo" [ $? -eq 0 ] +expect "the generated test ran cases" bash -c "[ \"\$(grep -c '^PASS' '$WORK/t1.out')\" -ge 20 ]" + +# 6. the seed, trimmed to this group's files, passes the check; a pre-existing script then refuses +R2="$(newrepo)" +bash lib/stamp.sh --only owners --default-branch main --owner testowner "$R2" >/dev/null 2>&1 +# rows of other groups name files that this partial stamp did not write: drop them, keep the rest +(cd "$R2" && awk -F'|' '/^\| `/ { p = $2; gsub(/[ `]/, "", p); if (system("test -e " p) != 0) next } { print }' OWNERS.md >OWNERS.trim && mv OWNERS.trim OWNERS.md) +git -C "$R2" add -A 2>/dev/null +(cd "$R2" && bash scripts/check-owners.sh) >"$WORK/k1.out" 2>"$WORK/k1.err" +expect "the seed, trimmed to the group's files, passes the check" [ $? -eq 0 ] +expect "the check reports its count" grep -q '^check-owners: 2 paths, all owned$' "$WORK/k1.out" +printf '#!/usr/bin/env bash\n' >"$R2/scripts/legacy.sh" +git -C "$R2" add -A 2>/dev/null +(cd "$R2" && bash scripts/check-owners.sh) >"$WORK/k2.out" 2>"$WORK/k2.err" +expect "a repo's own script with no row refuses" [ $? -eq 1 ] +expect "the refusal is the two-line form and says no owner yet" two_lines "$WORK/k2.err" +expect "the refusal names the script" grep -q 'no owner yet for scripts/legacy.sh' "$WORK/k2.err" +mkdir -p "$R2/.github/workflows" +printf 'name: x\n' >"$R2/.github/workflows/x.yml" +git -C "$R2" add -A 2>/dev/null +(cd "$R2" && bash scripts/check-owners.sh) >"$WORK/k3.out" 2>"$WORK/k3.err" +expect "a workflow of any repo is covered" grep -q 'no owner yet for .github/workflows/x.yml' "$WORK/k3.err" + +# 7. non-default values change nothing in the script bytes +R3="$(newrepo)" +bash lib/stamp.sh --only owners --default-branch master --owner other --tags app,lib --product-paths app/,pkg/ "$R3" >/dev/null 2>&1 +expect "stamped with other values: same script bytes" cmp -s "$R1/scripts/check-owners.sh" "$R3/scripts/check-owners.sh" +expect "stamped with other values: the seed uses the other owner" grep -q '@other | |$' "$R3/OWNERS.md" + +# 8. no stamp for a missing owner (the seed needs one) +R4="$(newrepo)" +bash lib/stamp.sh --only owners --default-branch main "$R4" >"$WORK/o.out" 2>&1 +expect "no --owner: refused" [ $? -ne 0 ] +expect "no --owner: the refusal is two lines with a Fix line" bash -c "[ \"\$(wc -l <'$WORK/o.out' | tr -d ' ')\" -eq 2 ] && sed -n 2p '$WORK/o.out' | grep -q '^Fix: '" + +# 9. portability and scope of the template text +for f in "$CHK" "$TST"; do + expect "$f: no python3, no jq, no GNU-only flag" bash -c "! grep -Eq 'python3|(^|[^A-Za-z])jq |grep -P|sed -r|readarray|mapfile|declare -A' '$f'" + expect "$f: no kit path and no home path" bash -c "! grep -Eq '$LEAK_PATTERN' '$f'" + expect "$f: no em or en dash" bash -c "! grep -q -e '$EM' -e '$EN' '$f'" + expect "$f: no bare 40 or 64 hex run" bash -c "! grep -Eq '[0-9a-f]{40}' '$f'" + expect "$f: bash -n" bash -n "$f" +done +if command -v shellcheck >/dev/null 2>&1; then + expect "shellcheck -S warning on the check and its test" shellcheck -S warning "$CHK" "$TST" +else + echo "note: shellcheck not installed, skipped" +fi + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-playbook.sh b/tests/test-stamp-playbook.sh new file mode 100644 index 000000000..5594a9519 --- /dev/null +++ b/tests/test-stamp-playbook.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# test-stamp-playbook.sh -- the "digest" group of the team stamp: the ship-pr skill and the team +# digest script with its generated test. Stamps only that group into temp repos and checks: +# 1. SKILL.md starts with --- on line 1, carries exactly the keys name and description (a +# misspelled key must fail the check), grants no allowed-tools, and names only scripts from +# the stamp's own set (that every named script exists in a full stamp is checked with the +# cross-group suite); +# 2. the stamped default branch reaches the skill; no literal default branch name does; +# 3. the digest is portable (no python3, branches on uname -s) and its generated test passes with +# a board file set and with none, and a second run changes nothing. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +unset STAMP_TEMPLATES +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@"; then ok "$label"; else no "$label"; fi; } +expect_not() { local label="$1"; shift; if "$@"; then no "$label"; else ok "$label"; fi; } + +ls "$ROOT"/templates/team-stamp/manifest.d/*-digest.tsv >/dev/null 2>&1 || { echo "NOT ok - no digest manifest" >&2; exit 1; } +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-playbook.XXXXXX")" || exit 1 +STAMP="bash $ROOT/lib/stamp.sh --only digest" +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +LIT="ma""in" + +# frontmatter_ok <SKILL.md>: line 1 is ---, a closing --- exists, the keys are exactly name and description +frontmatter_ok() { + local f="$1" keys + [ "$(sed -n 1p "$f")" = "---" ] || return 1 + awk 'NR>1 && /^---[ \t]*$/ {found=1; exit} END{exit !found}' "$f" || return 1 + keys="$(awk 'NR==1{next} /^---[ \t]*$/{exit} /^[A-Za-z][A-Za-z0-9_-]*:/ {sub(/:.*/, ""); print}' "$f" | LC_ALL=C sort | tr '\n' ' ')" + [ "$keys" = "description name " ] +} + +# 1. the skill +R="$(newrepo)" +$STAMP --default-branch master "$R" >"$WORK/stamp.out" 2>&1; RC=$? +expect "stamp the digest group exits 0" [ "$RC" -eq 0 ] +SK="$R/.claude/skills/ship-pr/SKILL.md" +expect "SKILL.md is written" [ -f "$SK" ] +expect "SKILL.md line 1 is --- and the keys are exactly name and description" frontmatter_ok "$SK" +expect "SKILL.md name is ship-pr" grep -q '^name: ship-pr$' "$SK" +expect "SKILL.md grants no allowed-tools" bash -c '! grep -qi "allowed-tools" "$1"' _ "$SK" +expect "SKILL.md description stays under the 1,536 character cap" bash -c '[ "$(grep "^description:" "$1" | wc -c)" -lt 1500 ]' _ "$SK" +cp "$SK" "$WORK/bad1.md"; sed -i.bak 's/^description:/descripton:/' "$WORK/bad1.md" +expect_not "a misspelled key fails the check" frontmatter_ok "$WORK/bad1.md" +printf '\n%s\n' "$(cat "$SK")" >"$WORK/bad2.md" +expect_not "a file that does not start with --- fails the check" frontmatter_ok "$WORK/bad2.md" +cp "$SK" "$WORK/bad3.md"; sed -i.bak 's/^name: ship-pr$/name: ship-pr\nallowed-tools: Bash/' "$WORK/bad3.md" +expect_not "an extra key fails the check" frontmatter_ok "$WORK/bad3.md" + +# the commands the skill tells an agent to run, from the stamp's own set of scripts +cmds="$(grep -oE 'bash scripts/[A-Za-z0-9._-]+\.sh' "$SK" | sed 's/^bash //' | LC_ALL=C sort -u)" +expect "SKILL.md names at least one script" [ -n "$cmds" ] +known="scripts/check.sh scripts/check-owners.sh scripts/pr-merge.sh scripts/negctl.sh scripts/issues-from-rows.sh scripts/release-notes.sh scripts/team-digest.sh scripts/pr-shape.sh scripts/agent-lessons.sh" +unknown="" +for c in $cmds; do case " $known " in *" $c "*) ;; *) unknown="$unknown $c" ;; esac; done +expect "every script the skill names is in the stamp's set (unknown:${unknown:- none})" [ -z "$unknown" ] +expect "the skill walks claim, branch, proof, check, PR, merge" bash -c ' + for p in "gh issue edit" "git worktree add" "scripts/negctl.sh" "scripts/check.sh" "gh pr create" "scripts/pr-merge.sh --wait"; do + grep -qF -- "$p" "$1" || { echo "missing: $p" >&2; exit 1; } + done' _ "$SK" +expect "the stamped default branch reaches the skill" grep -q 'origin/master' "$SK" +expect "the skill names no literal $LIT branch" bash -c '! grep -qw "$1" "$2"' _ "$LIT" "$SK" +expect "the skill never suggests a bare gh pr merge" bash -c '! grep -E "^[[:space:]]*gh pr merge" "$1"' _ "$SK" +expect "no unresolved {{KEY}} in a generated file" bash -c '! grep -q "{{" "$1" "$2" "$3"' _ "$SK" "$R/scripts/team-digest.sh" "$R/scripts/test-team-digest.sh" + +# 2. the digest script +DG="$R/scripts/team-digest.sh" +expect "digest and its test are written and executable" bash -c '[ -x "$1" ] && [ -x "$2" ]' _ "$DG" "$R/scripts/test-team-digest.sh" +expect "the digest has no python3" bash -c '! grep -q python3 "$1" "$2"' _ "$DG" "$R/scripts/test-team-digest.sh" +expect "the digest branches on uname -s for date" bash -c 'grep -q "uname -s" "$1" && grep -q "date -u -v" "$1" && grep -q "date -u -d" "$1"' _ "$DG" +expect "the digest reads the decision tag from the stamped value" grep -q '^decision_tag="decision"$' "$DG" +expect "bash -n accepts the digest" bash -n "$DG" +bash "$R/scripts/test-team-digest.sh" >"$WORK/dt1.out" 2>&1; RC=$? +expect "the generated digest test passes (default values, no board file)" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/dt1.out" | sed 's/^/ /' +expect "no board file stamped: the board value is empty" grep -q '^board_default=""$' "$DG" + +# 3. non-default values: a board file, another decision tag +R2="$(newrepo)" +$STAMP --default-branch trunk --board-file docs/plan/BOARD.md --decision-tag needs-call "$R2" >/dev/null 2>&1; RC=$? +expect "stamp with a board file and a decision tag exits 0" [ "$RC" -eq 0 ] +expect "the board file and the tag reach the digest" bash -c 'grep -q "^board_default=\"docs/plan/BOARD.md\"$" "$1" && grep -q "^decision_tag=\"needs-call\"$" "$1"' _ "$R2/scripts/team-digest.sh" +bash "$R2/scripts/test-team-digest.sh" >"$WORK/dt2.out" 2>&1; RC=$? +expect "the generated digest test passes (board file, custom tag)" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/dt2.out" | sed 's/^/ /' +expect "the default board file is read from the repo root by the real script" bash -c ' + grep -q "default board file: exit 0" "$1" && grep -q "the default board file is read from the repo root" "$1"' _ "$WORK/dt2.out" + +# 4. idempotence +OUT2="$($STAMP --default-branch trunk --board-file docs/plan/BOARD.md --decision-tag needs-call "$R2" 2>&1)" +expect "a second run prints only unchanged" bash -c '! printf "%s\n" "$1" | grep -Ev "^(unchanged|using): " | grep -q .' _ "$OUT2" + +# 5. shell-clean +if command -v shellcheck >/dev/null 2>&1; then + expect "shellcheck -S warning on the digest and its test" shellcheck -S warning "$R/scripts/team-digest.sh" "$R/scripts/test-team-digest.sh" +else + echo "skip - shellcheck is not installed" +fi + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-pr-shape.sh b/tests/test-stamp-pr-shape.sh new file mode 100644 index 000000000..e4cf9df29 --- /dev/null +++ b/tests/test-stamp-pr-shape.sh @@ -0,0 +1,152 @@ +#!/usr/bin/env bash +# test-stamp-pr-shape.sh -- the pr-shape group of the team stamp: scripts/pr-shape.sh and its generated +# test. Stamps the group into temp repos with default and non-default values, checks the files are +# kit-free and clean, runs the generated test, and runs pr-shape against the real stamped rules docs +# (the parity convention of tests/test-stamp-rules.sh: every AGENTS.md heading has a link in +# docs/TEAM-WORKFLOW.md) and the real stamped negctl.sh block. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { # expect <label> <command...> + local label="$1"; shift + if "$@" >/dev/null 2>&1; then ok "$label"; else no "$label"; fi +} + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-pr-shape.XXXXXX")" || exit 1 +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +have_shellcheck() { command -v shellcheck >/dev/null 2>&1; } +gi() { git -C "$1" -c user.name=t -c user.email=t@example.invalid -c commit.gpgsign=false -c core.hooksPath=/dev/null "${@:2}"; } + +# 1. a stamp with non-default values +A="$(newrepo)" +RC=0 +bash lib/stamp.sh --only pr-shape --default-branch master --tags app,lib --product-paths app/,pkg/ --board-file docs/BOARD.md "$A" >"$WORK/stamp-a.out" 2>&1 || RC=$? +expect "stamp of the pr-shape group exits 0" [ "$RC" -eq 0 ] +for f in scripts/pr-shape.sh scripts/test-pr-shape.sh; do + expect "created $f" grep -qx "created: $f" "$WORK/stamp-a.out" + expect "$f is executable" test -x "$A/$f" + expect "$f is listed in the lock" grep -q "^file $f pr-shape sha256:" "$A/.claude/team-stamp.lock" +done +expect "the stamp writes exactly two files" bash -c '[ "$(grep -c "^created: " "$1")" -eq 2 ]' _ "$WORK/stamp-a.out" +expect "no {{KEY}} is left in a generated file" bash -c "! grep -rE '\{\{[A-Za-z_]+\}\}' '$A/scripts'" +bash lib/stamp.sh --only pr-shape "$A" >"$WORK/stamp-a2.out" 2>&1 +expect "the second run prints only unchanged lines" bash -c '[ "$(grep -Evc "^(unchanged|using): " "$1")" -eq 0 ] && [ "$(grep -c "^unchanged: " "$1")" -eq 2 ]' _ "$WORK/stamp-a2.out" +expect "--check is clean" bash lib/stamp.sh --only pr-shape --check "$A" + +# 2. stamped values; nothing typed in the script +S="$A/scripts/pr-shape.sh" +expect "default branch comes from the stamp" grep -qxF "DEFAULT_BRANCH='master'" "$S" +expect "tag list comes from the stamp" grep -qxF "TAGS_ERE='app|lib|dev'" "$S" +expect "product paths come from the stamp" grep -qxF "PRODUCT_ERE='^(app/|pkg/)'" "$S" +expect "board file comes from the stamp" grep -qxF "BOARD_FILE='docs/BOARD.md'" "$S" +expect "no literal main branch" bash -c "! grep -Eq 'origin/main|[^a-z]main[^a-z]' '$S'" +B="$(newrepo)" +bash lib/stamp.sh --only pr-shape --default-branch main "$B" >/dev/null 2>&1 +expect "an empty board file stays empty in the script" grep -qxF "BOARD_FILE=''" "$B/scripts/pr-shape.sh" + +# 3. the interface the twin check.sh and ci.yml call: four env values, nothing else, no token +for v in PR_TITLE PR_BODY PR_BODY_FILE BASE_SHA HEAD_SHA; do + expect "the header documents $v" grep -q "^# $v " "$S" +done +expect "no token and no gh call" bash -c "! grep -Eq 'GH_TOKEN|GITHUB_TOKEN|gh api|gh pr (view|diff)' '$S'" +expect "PR text never reaches eval" bash -c "! grep -Eq '(^|[^a-z_-])eval[ \t]' '$S'" +expect "no bash 4 feature" bash -c "! grep -Eq 'readarray|mapfile|grep -P|sed -r|declare -A|\\$\\{[A-Za-z_]+(,,|\\^\\^)\\}' '$S' '$A/scripts/test-pr-shape.sh'" + +# 4. every generated file: kit-free, no dash characters, no python3, no bare hex digest, shellcheck clean +for f in scripts/pr-shape.sh scripts/test-pr-shape.sh; do + expect "$f names no kit path" bash -c "! grep -Eq '$LEAK_PATTERN' '$A/$f'" + expect "$f has no em or en dash" bash -c "! LC_ALL=C grep -q -e '$(printf '\342\200\224')' -e '$(printf '\342\200\223')' '$A/$f'" + expect "$f does not call python3 or jq" bash -c "! grep -Eq 'python3|(^|[^a-z])jq ' '$A/$f'" + expect "$f holds no bare 40 or 64 digit hex run" bash -c "! grep -Eq '[0-9a-fA-F]{40}' '$A/$f'" + if have_shellcheck; then expect "$f is shellcheck clean" shellcheck -S warning "$A/$f"; else ok "shellcheck not installed, $f skipped"; fi +done +expect "every Fix line casing: the script prints Fix: and no lowercase fix:" bash -c "! grep -q 'fix: ' '$S'" + +# 5. the generated test passes with the non-default values, with the defaults, and with a board file set +T1="$WORK/test-a.out" +RC=0 +bash "$A/scripts/test-pr-shape.sh" >"$T1" 2>&1 || RC=$? +expect "the generated test passes with non-default values" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$T1" | sed 's/^/ /' +expect "the generated test ran its attacker-text cases" grep -q 'running every Fix line creates no PWNED' "$T1" +expect "the generated test skips the negctl case when negctl.sh is absent" grep -q '^skipped: the negctl case' "$T1" +RC=0 +bash "$B/scripts/test-pr-shape.sh" >"$WORK/test-b.out" 2>&1 || RC=$? +expect "the generated test passes with the default values (no board file)" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/test-b.out" | sed 's/^/ /' + +# 6. with the merge group stamped too, the generated test runs the negctl case +C="$(newrepo)" +bash lib/stamp.sh --only pr-shape,merge --default-branch main --owner testowner --tags web,api --product-paths src/ "$C" >/dev/null 2>&1 +RC=0 +bash "$C/scripts/test-pr-shape.sh" >"$WORK/test-c.out" 2>&1 || RC=$? +expect "the generated test passes beside negctl.sh and a different tag list" [ "$RC" -eq 0 ] +[ "$RC" -eq 0 ] || tail -n 12 "$WORK/test-c.out" | sed 's/^/ /' +expect "the negctl block is accepted by the proof check" grep -q 'PASS the block negctl.sh prints is accepted as a proof' "$WORK/test-c.out" + +# 7. the real stamped docs: the parity convention of the rules group, through a real PR +D="$(newrepo)" +bash lib/stamp.sh --only rules,pr-shape --default-branch main --tags app,dev "$D" >/dev/null 2>&1 +gi "$D" symbolic-ref HEAD refs/heads/main +gi "$D" add -A +gi "$D" commit -q -m base +BASE="$(gi "$D" rev-parse HEAD)" +runps() { # runps <name> <body>: pr-shape on the repo $D from $BASE to HEAD + RC=0 + (cd "$D" && env -u CI PR_TITLE="docs: change the rules" PR_BODY="$2" BASE_SHA="$BASE" HEAD_SHA="$(git rev-parse HEAD)" bash scripts/pr-shape.sh) >"$WORK/$1.out" 2>"$WORK/$1.err" || RC=$? +} +printf '\nOne more rule line.\n' >>"$D/AGENTS.md" +gi "$D" commit -q -am "agents only" +runps real-a "" +expect "stamped AGENTS.md changed alone: fails" [ "$RC" -eq 1 ] +expect "stamped AGENTS.md changed alone: the pair names parity" grep -q '^pr-shape: AGENTS.md changed and docs/TEAM-WORKFLOW.md did not' "$WORK/real-a.err" +runps real-b "no-rule-mirror: the extra line needs no mirror" +expect "stamped AGENTS.md alone with no-rule-mirror: passes" [ "$RC" -eq 0 ] +printf '\nOne more rule line, mirrored.\n' >>"$D/docs/TEAM-WORKFLOW.md" +gi "$D" commit -q -am "workflow too" +runps real-c "" +expect "both stamped docs changed, every heading still linked: passes" [ "$RC" -eq 0 ] +printf '\n### A brand new rule heading\n\nText.\n' >>"$D/AGENTS.md" +printf '\nMirror text without the heading link.\n' >>"$D/docs/TEAM-WORKFLOW.md" +gi "$D" commit -q -am "new heading, no link" +runps real-d "" +expect "a new stamped heading with no link in the workflow doc: fails" [ "$RC" -eq 1 ] +expect "a new stamped heading: the pair names the anchor" grep -q 'anchors: a-brand-new-rule-heading' "$WORK/real-d.err" + +# 8. the proof guide's own block shape, filled in, is accepted +E="$(newrepo)" +bash lib/stamp.sh --only rules,pr-shape --default-branch main "$E" >/dev/null 2>&1 +gi "$E" symbolic-ref HEAD refs/heads/main +gi "$E" add -A +gi "$E" commit -q -m base +BASE_E="$(gi "$E" rev-parse HEAD)" +printf '#!/usr/bin/env bash\necho new\n' >"$E/scripts/new.sh" +cat >"$E/docs/verification/new.md" <<'EOF' +# Verification: a script + +Command: bash scripts/new.sh +Output: +new +Exit: 0 +Verdict: PASS + +## Negative control + +NEGATIVE CONTROL: removed the echo +Command: bash scripts/test-new.sh +Output: +FAIL new +Exit: 1 +Verdict: RED, as expected +EOF +gi "$E" add -A +gi "$E" commit -q -m change +RC=0 +(cd "$E" && env -u CI PR_TITLE="feat(scripts): add a script" PR_BODY="Closes #3" BASE_SHA="$BASE_E" HEAD_SHA="$(git rev-parse HEAD)" bash scripts/pr-shape.sh) >"$WORK/guide.out" 2>"$WORK/guide.err" || RC=$? +expect "a proof written in the proof guide's shape: passes" [ "$RC" -eq 0 ] + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-queue.sh b/tests/test-stamp-queue.sh new file mode 100644 index 000000000..f7c3d0101 --- /dev/null +++ b/tests/test-stamp-queue.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# test-stamp-queue.sh -- the work-queue group of the team stamp: the task issue form, the PR +# template, scripts/issues-from-rows.sh and its generated test, stamped into scratch repos. +# The issue form is checked by structure with awk and grep on the keys the form needs: this suite +# assumes no python or ruby YAML parser on the machine, so it reads the file as text. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@" >/dev/null 2>&1; then ok "$label"; else no "$label"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-queue.XXXXXX")" || exit 1 +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' +EM="$(printf '\342\200\224')"; EN="$(printf '\342\200\223')" +TPL=templates/team-stamp +FORM="$TPL/files/.github/ISSUE_TEMPLATE/task.yml" +PRT="$TPL/files/.github/pull_request_template.md" +SCR="$TPL/files/scripts/issues-from-rows.sh.tpl" +TST="$TPL/files/scripts/test-issues-from-rows.sh.tpl" +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } + +# 1. manifest +M="$TPL/manifest.d/50-queue.tsv" +expect "manifest exists" [ -f "$M" ] +expect "manifest: every row has five tab-separated columns" bash -c "grep -v '^#' '$M' | grep -v '^\$' | awk -F'\t' 'NF != 5 { exit 1 }'" +expect "manifest: the two scripts declare BOARD_FILE and DECISION_TAG" bash -c "grep -v '^#' '$M' | awk -F'\t' '\$3 ~ /issues-from-rows/ { n++; if (\$5 != \"BOARD_FILE,DECISION_TAG\") bad = 1 } END { exit !(n == 2 && !bad) }'" +expect "manifest: the form and the PR template are plain copies with no key" bash -c "grep -v '^#' '$M' | awk -F'\t' '\$3 ~ /task.yml|pull_request_template/ { n++; if (\$1 != \"copy\" || \$5 != \"-\") bad = 1 } END { exit !(n == 2 && !bad) }'" + +# 2. the issue form, read as text (no YAML parser is assumed) +expect "form: no tab character (YAML forbids it)" bash -c "! grep -q \"\$(printf '\\t')\" '$FORM'" +expect "form: top-level name, description and body keys" bash -c "grep -q '^name: .' '$FORM' && grep -q '^description: .' '$FORM' && grep -q '^body:\$' '$FORM'" +# one record per body item: type, id, label, required +awk ' + /^ - type: / { if (n) print type "|" id "|" label "|" req; n++; type = $3; id = ""; label = ""; req = "no"; next } + /^ label: / { sub(/^ label: /, ""); label = $0; next } + /^ id: / { id = $2; next } + /^ required: true/ { req = "yes"; next } + END { if (n) print type "|" id "|" label "|" req }' "$FORM" >"$WORK/form.items" +expect "form: five body items, a markdown note then four textareas in order" [ "$(cut -d'|' -f1,2 "$WORK/form.items" | tr '\n' ' ')" = "markdown| textarea|goal textarea|done_when textarea|scope textarea|notes " ] +expect "form: labels are Goal, Done when, Scope, Notes" [ "$(awk -F'|' 'NR > 1 { printf "%s,", $3 }' "$WORK/form.items")" = "Goal,Done when,Scope,Notes," ] +expect "form: Goal and Done when are required, Scope and Notes are not" [ "$(awk -F'|' 'NR > 1 { printf "%s,", $4 }' "$WORK/form.items")" = "yes,yes,no,no," ] +expect "form: every textarea carries an attributes block with a label" bash -c "[ \"\$(grep -c '^ attributes:\$' '$FORM')\" -eq 5 ] && [ \"\$(grep -c '^ label: ' '$FORM')\" -eq 4 ]" +expect "form: the note names the four headings the form writes" bash -c "grep -q '### Goal.*### Done when.*### Scope.*### Notes' '$FORM'" +expect "form: Notes says optional" bash -c "grep -A3 'id: notes' '$FORM' | grep -qi optional" + +# 3. the PR template +expect "PR template: a Closes # line" grep -q '^Closes #' "$PRT" +expect "PR template: the three sections" bash -c "[ \"\$(grep -c '^## ' '$PRT')\" -eq 3 ] && grep -q '^## What\$' '$PRT' && grep -q '^## Proof\$' '$PRT' && grep -q '^## Bookkeeping\$' '$PRT'" +expect "PR template: names the opt-out marker lines pr-shape reads" bash -c "grep -q 'no-board-row:' '$PRT' && grep -q 'no-changelog:' '$PRT' && grep -q 'no-proof:' '$PRT' && grep -q 'no-rule-mirror:' '$PRT'" + +# 4. the script's issue headings are the form's labels +expect "script body headings match the form labels" bash -c "[ \"\$(grep -Eo '^ *(body=.)?### (Goal|Done when|Scope)\$' '$SCR' | sed 's/^ *body=.//; s/^ *//' | tr '\n' ',')\" = '### Goal,### Done when,### Scope,' ]" + +# 5. stamp with defaults (no board file) +R1="$(newrepo)" +bash lib/stamp.sh --only queue --default-branch main --owner testowner "$R1" >"$WORK/s1.out" 2>&1 +expect "stamp the queue group, defaults" [ $? -eq 0 ] +for f in .github/ISSUE_TEMPLATE/task.yml .github/pull_request_template.md scripts/issues-from-rows.sh scripts/test-issues-from-rows.sh; do + expect "created: $f" [ -f "$R1/$f" ] +done +expect "both scripts are executable" bash -c "[ -x '$R1/scripts/issues-from-rows.sh' ] && [ -x '$R1/scripts/test-issues-from-rows.sh' ]" +expect "the form and the PR template are byte-identical to the templates (agnostic)" bash -c "cmp -s '$FORM' '$R1/.github/ISSUE_TEMPLATE/task.yml' && cmp -s '$PRT' '$R1/.github/pull_request_template.md'" +expect "no {{KEY}} is left in the stamped scripts" bash -c "! grep -q '{{' '$R1/scripts/issues-from-rows.sh' '$R1/scripts/test-issues-from-rows.sh'" +expect "defaults: the board default is empty" grep -q "^BOARD_DEFAULT=''\$" "$R1/scripts/issues-from-rows.sh" +expect "defaults: the decision tag is decision" grep -q "^DECISION_TAG='decision'\$" "$R1/scripts/issues-from-rows.sh" +(cd "$R1" && bash scripts/issues-from-rows.sh) >"$WORK/e1.out" 2>"$WORK/e1.err" +expect "defaults: with no board file the script exits 0" [ $? -eq 0 ] +expect "defaults: with no board file it prints the one line" bash -c "[ \"\$(cat '$WORK/e1.out')\" = 'issues-from-rows: no board file set; nothing to read' ] && [ ! -s '$WORK/e1.err' ]" +(cd "$R1" && bash scripts/test-issues-from-rows.sh) >"$WORK/t1.out" 2>&1 +expect "defaults: the generated test passes" [ $? -eq 0 ] +expect "defaults: the generated test ran many cases" bash -c "[ \"\$(grep -c '^PASS' '$WORK/t1.out')\" -ge 60 ]" + +# 6. idempotent +bash lib/stamp.sh --only queue --default-branch main --owner testowner "$R1" >"$WORK/s2.out" 2>&1 +expect "second run prints only unchanged" bash -c "[ -s '$WORK/s2.out' ] && ! grep -Ev '^(unchanged|using): ' '$WORK/s2.out'" + +# 7. stamp with non-default values +R2="$(newrepo)" +bash lib/stamp.sh --only queue --default-branch master --owner testowner --board-file docs/BOARD.md --decision-tag waiting "$R2" >"$WORK/s3.out" 2>&1 +expect "stamp the queue group, custom values" [ $? -eq 0 ] +expect "custom: the board default and the decision tag are rendered" bash -c "grep -q \"^BOARD_DEFAULT='docs/BOARD.md'\$\" '$R2/scripts/issues-from-rows.sh' && grep -q \"^DECISION_TAG='waiting'\$\" '$R2/scripts/issues-from-rows.sh'" +expect "custom: the default board path is in the usage header" grep -q 'default docs/BOARD.md' "$R2/scripts/issues-from-rows.sh" +(cd "$R2" && bash scripts/test-issues-from-rows.sh) >"$WORK/t2.out" 2>&1 +expect "custom: the generated test passes" [ $? -eq 0 ] + +# 8. the stamped script reads the stamped board, skips the stamped decision tag, and applies labels (fake gh) +FAKE="$WORK/fake"; mkdir -p "$FAKE/bin" "$R2/docs" +cat >"$FAKE/bin/gh" <<'EOF' +#!/bin/bash +case "$1 $2" in +"label list") printf 'ready\n' ;; +"label create") printf 'label %s\n' "$3" >>"$FAKE_LOG" ;; +"issue list") ;; +"issue create") printf 'issue\n' >>"$FAKE_LOG"; echo "https://github.example/issues/1" ;; +*) exit 1 ;; +esac +EOF +chmod +x "$FAKE/bin/gh" +printf '| ID | Item | Notes | Status |\n|---|---|---|---|\n| ID-001 | One | Do it. Done when: it is done. #alice | queued |\n| ID-002 | Two | Pick. Done when: chosen. #waiting #P0 #alice | queued |\n' >"$R2/docs/BOARD.md" +: >"$FAKE/log" +(cd "$R2" && FAKE_LOG="$FAKE/log" PATH="$FAKE/bin:$PATH" bash scripts/issues-from-rows.sh --apply) >"$WORK/a1.out" 2>&1 +expect "stamped board: one issue for the ready row, none for the decision row" bash -c "[ \"\$(grep -c '^issue\$' '$FAKE/log')\" -eq 1 ]" +expect "stamped board: the two missing labels are created, the present one is not" bash -c "grep -qx 'label one-way-door' '$FAKE/log' && grep -qx 'label blocked' '$FAKE/log' && ! grep -qx 'label ready' '$FAKE/log'" + +# 9. portability and scope of the template text +for f in "$SCR" "$TST" "$FORM" "$PRT"; do + expect "$f: no kit path and no home path" bash -c "! grep -Eq '$LEAK_PATTERN' '$f'" + expect "$f: no em or en dash" bash -c "! grep -q -e '$EM' -e '$EN' '$f'" + expect "$f: no bare 40 or 64 hex run" bash -c "! grep -Eq '[0-9a-f]{40}' '$f'" +done +for f in "$SCR" "$TST"; do + expect "$f: no python3, jq or GNU-only construct" bash -c "! grep -Eq 'python3|(^|[^-A-Za-z])jq |grep -P|sed -r|readarray|mapfile|declare -A|\\$\\{[A-Za-z_]+(,,|\\^\\^)' '$f'" +done +expect "script: never evaluates row text" bash -c "! grep -v '^ *#' '$SCR' | grep -Eq '(^|[^A-Za-z_])eval '" +if command -v shellcheck >/dev/null 2>&1; then + expect "shellcheck -S warning on the stamped scripts" shellcheck -S warning "$R2/scripts/issues-from-rows.sh" "$R2/scripts/test-issues-from-rows.sh" "$R1/scripts/issues-from-rows.sh" "$R1/scripts/test-issues-from-rows.sh" +else + echo "note: shellcheck not installed, skipped" +fi + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-refusals.sh b/tests/test-stamp-refusals.sh new file mode 100644 index 000000000..9f5cd34ba --- /dev/null +++ b/tests/test-stamp-refusals.sh @@ -0,0 +1,168 @@ +#!/usr/bin/env bash +# test-stamp-refusals.sh -- every refusal of every generated script, once, on a full stamp. +# For each: it exits 1 (2 for the hook), every "Fix:" line is directly preceded by a +# "<tool>: <rule>" line, the last two stderr lines are that pair, hostile input (a quote, +# $(touch ...) and a newline followed by a fake Fix: line) never reaches the output raw, and every +# printed Fix: line, run through bash -c in a copy of the repo, creates nothing. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@"; then ok "$label"; else no "$label"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-refusals.XXXXXX")" || exit 1 +command -v jq >/dev/null 2>&1 || { echo "ok - jq not found, skipping"; exit 0; } + +# hostile text: a single quote, a command substitution, a backtick, and a newline plus a forged Fix line +EVIL="x'\$(touch EVILMARK)\`touch EVILMARK\`" +EVIL_NL="$(printf 'a\nFix: touch EVILMARK')" +no_mark() { [ -z "$(find "$WORK" -name EVILMARK 2>/dev/null)" ]; } +SEEN_FIXES=" " + +# ---- the stamped repo, committed once; every case works in a fresh copy ---- +R0="$WORK/base"; mkdir -p "$R0"; git -C "$R0" init -q -b master 2>/dev/null +git -C "$R0" config user.name tester; git -C "$R0" config user.email tester@example.invalid +bash lib/stamp.sh --default-branch master --owner testowner --tags app,lib --product-paths app/,pkg/ \ + --door-paths 'docs/legal/*' --door-approver reviewer --board-file docs/BOARD.md "$R0" >/dev/null 2>&1 +git -C "$R0" add -A >/dev/null 2>&1; git -C "$R0" commit -q -m "chore: stamp" +git -C "$R0" update-ref refs/remotes/origin/master HEAD +ntargets="$(awk '$1=="file"' "$R0/.claude/team-stamp.lock" | wc -l | tr -d ' ')" +expect "the stamped repo has files to work with ($ntargets)" [ "$ntargets" -gt 20 ] + +# a fake gh that serves $FAKE/case.json through the script's own --jq expression +FAKE="$WORK/fake"; mkdir -p "$FAKE/bin" +cat > "$FAKE/bin/gh" <<EOF +#!/bin/bash +if [ "\$1 \$2" = "pr view" ]; then + expr=""; while [ \$# -gt 0 ]; do [ "\$1" = "--jq" ] && expr="\$2"; shift; done + jq -r "\$expr" "$FAKE/case.json" +elif [ "\$1 \$2" = "pr merge" ]; then exit 0 +else exit 1; fi +EOF +chmod +x "$FAKE/bin/gh" +mkcase() { # mkcase <isDraft> <mergeable> <checks-json> <files-json> <reviews-json> + printf '{"isDraft":%s,"mergeable":"%s","author":{"login":"author"},"statusCheckRollup":[%s],"files":[%s],"reviews":[%s],"headRefOid":"head1","headRefName":"feature/x"}\n' "$1" "$2" "$3" "$4" "$5" > "$FAKE/case.json" +} +GOODCK='{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS"},{"__typename":"CheckRun","name":"build","status":"COMPLETED","conclusion":"SUCCESS"}' + +fresh() { local d; d="$(mktemp -d "$WORK/c.XXXXXX")"; cp -R "$R0/." "$d/"; echo "$d"; } + +# refusal <label> <tool> <expected-exit> <dir> <command...> (stdin from $STDIN_FILE when set) +refusal() { + local label="$1" tool="$2" want="$3" dir="$4" rc err n prev line fix fx; shift 4 + err="$(cd "$dir" && PATH="$FAKE/bin:$PATH" "$@" 2>&1 >/dev/null < "${STDIN_FILE:-/dev/null}")"; rc=$? + expect "$label: exit $want" bash -c 'case " $2 " in *" $1 "*) exit 0;; *) exit 1;; esac' _ "$rc" "$want" + expect "$label: the last two stderr lines are '$tool: <rule>' then 'Fix: ...'" bash -c ' + l1="$(printf "%s\n" "$1" | tail -n 2 | sed -n 1p)"; l2="$(printf "%s\n" "$1" | tail -n 2 | sed -n 2p)" + [ "${l1#"$2: "}" != "$l1" ] && [ "${l2#Fix: }" != "$l2" ] && [ -n "${l2#Fix: }" ]' _ "$err" "$tool" + # every Fix: line is preceded by a rule line, so a forged one cannot stand alone + bad=0; prev="" + while IFS= read -r line; do + case "$line" in "Fix: "*) case "$prev" in "$tool: "*|"${ALSO:-__none__}: "*) ;; *) bad=1;; esac;; esac + prev="$line" + done <<EOF2 +$err +EOF2 + expect "$label: every Fix: line follows a '$tool: ' line" [ "$bad" -eq 0 ] + expect "$label: the hostile text is not in the output raw" bash -c '! printf "%s" "$1" | grep -qF "$(printf "%s" "$2")"' _ "$err" '$(touch' + expect "$label: a forged 'Fix: bash x.sh' inside a name never reaches the output" bash -c '! printf "%s" "$1" | grep -qF "Fix: bash x.sh"' _ "$err" + # run every printed Fix: line in a copy: nothing must be created + n=0 + while IFS= read -r fix; do + n=$((n + 1)) + case "$SEEN_FIXES" in *"|$fix|"*) continue;; esac # each distinct line runs once + SEEN_FIXES="$SEEN_FIXES|$fix| " + fx="$(mktemp -d "$WORK/fx.XXXXXX")"; cp -R "$dir/." "$fx/" + { ( cd "$fx" && PATH="$FAKE/bin:$PATH" perl -e 'alarm 10; exec @ARGV' bash -c "${fix#Fix: }" ) >/dev/null 2>&1 < /dev/null; } 2>/dev/null + done <<EOF3 +$(printf '%s\n' "$err" | grep '^Fix: ') +EOF3 + expect "$label: its $n Fix: line(s) ran through bash -c and created nothing" no_mark +} + +json() { jq -nc --arg c "$1" --arg d "$2" '{hook_event_name:"PreToolUse",tool_name:"Bash",tool_input:{command:$c},cwd:$d}'; } + +# ---- agent-guard (exit 2) ---- +D="$(fresh)" +for c in "gh pr merge 7 --squash" "gh pr merge $EVIL" "git push origin master" "git push origin HEAD:master" "git commit -m x"; do + STDIN_FILE="$WORK/in.json"; json "$c" "$D" > "$STDIN_FILE" + refusal "guard: $(printf '%s' "$c" | cut -c1-30)" agent-guard 2 "$D" bash scripts/agent-guard.sh +done +unset STDIN_FILE + +# ---- check-owners ---- +D="$(fresh)"; printf '#!/usr/bin/env bash\n' > "$D/scripts/new-thing.sh"; git -C "$D" add scripts/new-thing.sh +refusal "owners: a script with no row" check-owners 1 "$D" bash scripts/check-owners.sh +D="$(fresh)"; hostile="scripts/x'\$(touch EVILMARK).sh"; printf '#!/usr/bin/env bash\n' > "$D/$hostile"; git -C "$D" add -f -- "$hostile" +refusal "owners: a hostile file name" check-owners 1 "$D" bash scripts/check-owners.sh +D="$(fresh)"; hostile2="scripts/a Fix: bash x.sh"; printf '#!/usr/bin/env bash\n' > "$D/$hostile2"; git -C "$D" add -f -- "$hostile2" +refusal "owners: a file named with a forged Fix: line" check-owners 1 "$D" bash scripts/check-owners.sh +D="$(fresh)"; sed -i.bak 's/^| `scripts\/negctl.sh` | \(.*\) | @testowner |/| `scripts\/negctl.sh` | \1 | |/' "$D/OWNERS.md"; git -C "$D" add -A >/dev/null 2>&1 +refusal "owners: an empty owner" check-owners 1 "$D" bash scripts/check-owners.sh +D="$(fresh)"; printf '| `scripts/gone.sh` | gone | @testowner | |\n' >> "$D/OWNERS.md" +refusal "owners: a row for a missing path" check-owners 1 "$D" bash scripts/check-owners.sh + +# ---- release-notes ---- +D="$(fresh)" +refusal "release-notes: no section" release-notes 2 "$D" bash scripts/release-notes.sh +refusal "release-notes: a missing section" release-notes 1 "$D" bash scripts/release-notes.sh 9.9.9 +printf '\n- app: fine\n- an untagged line\n' >> "$D/CHANGELOG.md" +refusal "release-notes: an untagged entry" release-notes 1 "$D" bash scripts/release-notes.sh Unreleased +D="$(fresh)"; printf '\n- %s\n' "$EVIL" >> "$D/CHANGELOG.md" +refusal "release-notes: a hostile entry" release-notes 1 "$D" bash scripts/release-notes.sh Unreleased +refusal "release-notes: a hostile section name" release-notes "1 2" "$D" bash scripts/release-notes.sh "$EVIL" +refusal "release-notes: a section named with a forged Fix: line" release-notes "1 2" "$D" bash scripts/release-notes.sh "a Fix: bash x.sh" + +# ---- negctl ---- +D="$(fresh)" +refusal "negctl: no arguments" negctl 64 "$D" bash scripts/negctl.sh +printf 'dirt\n' >> "$D/CHANGELOG.md" +refusal "negctl: a tracked file with uncommitted changes" negctl 2 "$D" bash scripts/negctl.sh "true" "true" +D="$(fresh)" +refusal "negctl: a test that is already red" negctl 1 "$D" bash scripts/negctl.sh "false" "echo x >> CHANGELOG.md" + +# ---- pr-shape (exit 1) and check.sh ---- +D="$(fresh)"; git -C "$D" checkout -q -b feat/x; mkdir -p "$D/app"; printf '#!/usr/bin/env bash\necho hi\n' > "$D/app/x.sh"; git -C "$D" add app; git -C "$D" commit -q -m "feat(app): x" +shape() { # shape <label> <title> <body> + refusal "$1" pr-shape 1 "$D" env PR_TITLE="$2" PR_BODY="$3" BASE_SHA=origin/master HEAD_SHA=HEAD bash scripts/pr-shape.sh +} +shape "pr-shape: a bad title" "not conventional" "Closes #1" +shape "pr-shape: no proof, no board link, no changelog" "feat(app): x" "" +shape "pr-shape: a hostile title" "feat(app): $EVIL" "Closes #1" +shape "pr-shape: a hostile title with a forged Fix line" "feat(app): $EVIL_NL" "Closes #1" +shape "pr-shape: a hostile body" "feat(app): x" "$EVIL_NL" +D2="$(fresh)"; git -C "$D2" checkout -q -b docs/p; printf '\nedit\n' >> "$D2/AGENTS.md"; git -C "$D2" commit -q -am "docs: edit rules" +refusal "pr-shape: AGENTS.md changed alone" pr-shape 1 "$D2" env PR_TITLE="docs: edit rules" PR_BODY="" BASE_SHA=origin/master HEAD_SHA=HEAD bash scripts/pr-shape.sh +ALSO=pr-shape # check.sh forwards the checks' own refusals before its own pair +refusal "check.sh: a bad title" check 1 "$D" bash scripts/check.sh --title "not conventional" --body "Closes #1" +refusal "check.sh: a hostile title" check 1 "$D" bash scripts/check.sh --title "feat(app): $EVIL_NL" --body "$EVIL" +refusal "check.sh: a usage error" check 2 "$D" bash scripts/check.sh --bogus +unset ALSO + +# ---- pr-merge (fake gh) ---- +D="$(fresh)" +mkcase true MERGEABLE "$GOODCK" '{"path":"app/x.sh"}' '' +refusal "pr-merge: a draft" pr-merge 1 "$D" bash scripts/pr-merge.sh 7 +mkcase false MERGEABLE '{"__typename":"CheckRun","name":"changes","status":"COMPLETED","conclusion":"SUCCESS"},{"__typename":"CheckRun","name":"b'"'"'$(touch EVILMARK)","status":"COMPLETED","conclusion":"FAILURE"}' '{"path":"app/x.sh"}' '' +refusal "pr-merge: a red check with a hostile name" pr-merge 1 "$D" bash scripts/pr-merge.sh 7 +mkcase false CONFLICTING "$GOODCK" '{"path":"app/x.sh"}' '' +refusal "pr-merge: a conflict" pr-merge 1 "$D" bash scripts/pr-merge.sh 7 +mkcase false MERGEABLE "$GOODCK" '{"path":"docs/legal/terms.md"}' '' +refusal "pr-merge: a door path with no second person" pr-merge 1 "$D" bash scripts/pr-merge.sh 7 +mkcase false MERGEABLE "$GOODCK" '{"path":"docs/legal/terms.md"}' '{"author":{"login":"author"},"state":"APPROVED","submittedAt":"2026-01-02T00:00:00Z"}' +refusal "pr-merge: the author as the second person" pr-merge 1 "$D" bash scripts/pr-merge.sh 7 +mkcase false MERGEABLE "$GOODCK" '{"path":"app/x.sh"}' '' +refusal "pr-merge: a bad PR number" pr-merge 2 "$D" bash scripts/pr-merge.sh "$EVIL" + +# ---- issues-from-rows, team-digest ---- +D="$(fresh)" +refusal "issues-from-rows: a board file named with a forged Fix: line" issues-from-rows 1 "$D" bash scripts/issues-from-rows.sh --board-file "no Fix: bash x.sh" +refusal "issues-from-rows: an unknown flag" issues-from-rows 2 "$D" bash scripts/issues-from-rows.sh --bogus +refusal "team-digest: a bad --hours" team-digest 2 "$D" bash scripts/team-digest.sh --hours "$EVIL" + +expect "no hostile payload ran anywhere: no marker file exists" no_mark + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp-rules.sh b/tests/test-stamp-rules.sh new file mode 100644 index 000000000..179e5fdc1 --- /dev/null +++ b/tests/test-stamp-rules.sh @@ -0,0 +1,173 @@ +#!/usr/bin/env bash +# test-stamp-rules.sh -- the rules docs group of the team stamp: AGENTS.md, docs/TEAM-WORKFLOW.md, +# docs/verification/README.md and .kit.toml, stamped into a scratch repo and read back. +# +# Parity rule (the one scripts/pr-shape.sh in a stamped repo also applies): every heading of +# AGENTS.md, at any level, has a link to its anchor in docs/TEAM-WORKFLOW.md. The anchor is the +# heading lowercased, every character outside a-z 0-9 space hyphen dropped, spaces turned into +# hyphens, and the link reads [<heading text>](../AGENTS.md#<anchor>). Keep AGENTS.md headings +# plain words so this rule stays a simple list comparison. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { local label="$1"; shift; if "$@"; then ok "$label"; else no "$label"; fi; } + +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp-rules.XXXXXX")" || exit 1 +LEAK_PATTERN='\.claude/dwarves-kit|CLAUDE_PLUGIN_ROOT|KIT_ROOT|lib/gate/|/bin/(gate|classify|wrap|board)([^A-Za-z0-9_-]|$)|/Users/[A-Za-z0-9._-]+|/home/[A-Za-z0-9._-]+' +KIT_URL='https://github.com/dwarvesf/dwarves-kit' +LIMIT='A person who merges from the GitHub site passes everything, on a plan without branch protection.' +TRUST='Claude Code uses a hook from `.claude/settings.json` even in a folder not yet trusted' +EM="$(printf '\342\200\224')"; EN="$(printf '\342\200\223')" + +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +slug() { printf '%s' "$1" | tr 'A-Z' 'a-z' | tr -cd 'a-z0-9 -' | tr ' ' '-'; } +headings() { # headings <file>: every heading text outside a code fence, one per line + awk '/^```/ {f = !f; next} !f && /^#+ / {sub(/^#+ +/, ""); print}' "$1" +} + +# 1. stamp with default-looking values and with non-default values +R1="$(newrepo)" +bash lib/stamp.sh --only rules --default-branch main "$R1" >"$WORK/s1.out" 2>&1 +expect "stamp the rules group, defaults" [ $? -eq 0 ] +R2="$(newrepo)" +bash lib/stamp.sh --only rules --default-branch master --tags app,lib --product-paths app/,pkg/ \ + --door-paths 'docs/legal/*,protocol/*' --door-approver reviewer "$R2" >"$WORK/s2.out" 2>&1 +expect "stamp the rules group, custom values" [ $? -eq 0 ] + +for f in AGENTS.md docs/TEAM-WORKFLOW.md docs/verification/README.md .kit.toml; do + expect "$f is written" [ -f "$R1/$f" ] +done +expect "the lock lists the four files" bash -c "[ \$(awk '\$1==\"file\"' '$R1/.claude/team-stamp.lock' | wc -l | tr -d ' ') -eq 4 ]" + +A="$R2/AGENTS.md"; T="$R2/docs/TEAM-WORKFLOW.md"; P="$R2/docs/verification/README.md"; K="$R2/.kit.toml" + +# 2. AGENTS.md shape +expect "AGENTS.md line 1 is the kit marker, read from the adopt pointer" \ + bash -c "[ \"\$(head -n 1 '$A')\" = \"\$(head -n 1 '$ROOT/lib/adopt/AGENTS.pointer.md')\" ] && head -n 1 '$A' | grep -q '^<!-- kit:agents-pointer'" +for h in Commands Playbooks Lessons "Team rules" Never "Optional kit"; do + expect "AGENTS.md has the section: $h" grep -qx "## $h" "$A" +done +for h in "Work queue" "What a PR carries" Proof Changelog "One-way doors" Merge Checks Limits; do + expect "AGENTS.md has the team rule: $h" grep -qx "### $h" "$A" +done +expect "the closing section is Optional kit" bash -c "[ \"\$(grep '^## ' '$A' | tail -n 1)\" = '## Optional kit' ]" +expect "the public URL appears once, in the closing section" \ + bash -c "[ \$(grep -cF '$KIT_URL' '$A') -eq 1 ] && awk '/^## Optional kit\$/ {f=1} f && index(\$0, \"$KIT_URL\") {found=1} END {exit !found}' '$A'" +expect "the kit is named nowhere in AGENTS.md outside line 1 and the closing section" \ + bash -c "! awk 'NR>1 && /^## Optional kit\$/ {exit} NR>1 {print}' '$A' | grep -qi 'dwarves-kit\|kit:'" +for s in scripts/pr-merge.sh scripts/check.sh scripts/negctl.sh scripts/pr-shape.sh scripts/check-owners.sh scripts/issues-from-rows.sh scripts/release-notes.sh scripts/team-digest.sh scripts/agent-guard.sh scripts/agent-lessons.sh; do + expect "AGENTS.md names $s" grep -qF "$s" "$A" +done +expect "AGENTS.md names the ship-pr playbook" grep -qF '.claude/skills/ship-pr/SKILL.md' "$A" +expect "the Never section is not empty" bash -c "[ \$(awk '/^## Never\$/ {f=1; next} /^## / {f=0} f && /^- /' '$A' | wc -l | tr -d ' ') -ge 3 ]" + +# 3. both docs: the limit sentence, the trust step, the optional-kit section +for f in "$A" "$T"; do + b="${f#"$R2"/}" + expect "$b carries the limit sentence" grep -qF "$LIMIT" "$f" + expect "$b carries the trust-the-folder step" grep -qF "$TRUST" "$f" + expect "$b has an Optional kit section" grep -qx '## Optional kit' "$f" + expect "$b says nothing in it needs the kit" grep -Eq 'Nothing (above|here) needs' "$f" +done +expect "TEAM-WORKFLOW.md names no kit URL and no kit path" bash -c "! grep -qF '$KIT_URL' '$T'" + +# 4. parity: every AGENTS.md heading has its anchor link in TEAM-WORKFLOW.md, and no link points nowhere +nh=0; missing=0 +while IFS= read -r h; do + [ -n "$h" ] || continue + nh=$((nh + 1)) + s="$(slug "$h")" + grep -qF "[$h](../AGENTS.md#$s)" "$T" || { missing=$((missing + 1)); echo " no anchor link for heading: $h"; } +done < <(headings "$A") +expect "AGENTS.md has headings to compare ($nh)" [ "$nh" -ge 12 ] +expect "every AGENTS.md heading has its anchor in TEAM-WORKFLOW.md" [ "$missing" -eq 0 ] +dups="$(headings "$A" | while IFS= read -r h; do slug "$h"; echo; done | grep -v '^$' | sort | uniq -d)" +expect "no two AGENTS.md headings share an anchor" [ -z "$dups" ] +stale=0 +slugs="$(headings "$A" | while IFS= read -r h; do slug "$h"; echo; done)" +for a in $(grep -o '(\.\./AGENTS\.md#[a-z0-9-]*)' "$T" | sed 's/.*#//; s/)//' | sort -u); do + printf '%s\n' "$slugs" | grep -qx "$a" || { stale=$((stale + 1)); echo " TEAM-WORKFLOW.md links to a missing AGENTS.md anchor: $a"; } +done +expect "TEAM-WORKFLOW.md links no AGENTS.md anchor that does not exist" [ "$stale" -eq 0 ] +expect "the parity rule is stated in this test's header" grep -q '^# Parity rule' "$ROOT/tests/test-stamp-rules.sh" + +# 5. relative links in the generated docs resolve +badlinks=0 +for f in "$A" "$T" "$P"; do + d="$(dirname "$f")" + for l in $(grep -o '](\([^)#]*\)' "$f" | sed 's/^](//' | grep -v '^[a-z]*:' | grep -v '^$' | sort -u); do + [ -e "$d/$l" ] || { badlinks=$((badlinks + 1)); echo " ${f#"$R2"/}: dead link $l"; } + done +done +expect "every relative link in the three docs reaches a file this group writes" [ "$badlinks" -eq 0 ] + +# 6. the proof guide +expect "the proof guide says one file per PR" grep -q '^## One file per PR' "$P" +for w in 'Command:' 'Output:' 'Exit:' 'NEGATIVE CONTROL' 'Verdict:'; do + expect "the proof guide states $w" grep -qF "$w" "$P" +done +expect "the proof guide shape block runs Command, Output, Exit, Verdict in order" \ + bash -c "awk '/^\`\`\`/ {n++; next} n==1 {print}' '$P' | awk '/^Command:/ {a=NR} /^Output:/ {b=NR} /^Exit:/ {c=NR} /^Verdict:/ {d=NR} END {exit !(a && b>a && c>b && d>c)}'" +expect "the proof guide shape block has a line right after Output:" \ + bash -c "awk '/^\`\`\`/ {n++; next} n==1 {print}' '$P' | awk 'f && NF {ok=1} /^Output:/ {f=1} END {exit !ok}'" +expect "the proof guide names the red verdict form" grep -qF 'Verdict: RED, as expected' "$P" +expect "the proof guide says scripts/negctl.sh prints the block" grep -qF 'scripts/negctl.sh' "$P" +expect "the proof guide says the README is never a proof" grep -qF 'never a proof' "$P" + +# 7. .kit.toml +expect ".kit.toml sets proof_of_done = true" grep -qx 'proof_of_done = true' "$K" +expect ".kit.toml sets lane_gates = false" grep -qx 'lane_gates = false' "$K" +expect ".kit.toml has a [gate] table" grep -qx '\[gate\]' "$K" +expect ".kit.toml comments name no kit path" bash -c "! grep -Eq '$LEAK_PATTERN|~/|/lib/' '$K'" +expect ".kit.toml keeps no other gate key on" bash -c "[ \$(grep -Ec '^[a-z_]+ = ' '$K') -eq 2 ]" + +# 7b. the review rules for the harness's own files, the workflow limit and the runner advice +for f in "$A" "$T"; do + b="${f#"$R2"/}" + expect "$b lists the harness's own files as doors" bash -c "for p in '.github/' 'scripts/' '.claude/' 'OWNERS.md' 'AGENTS.md' 'CLAUDE.md' '.mcp.json' 'docs/TEAM-WORKFLOW.md' '.kit.toml' 'any depth'; do grep -qF \"\$p\" '$f' || exit 1; done; grep -qF 'always doors' '$f'" + expect "$b warns that hook settings, the lessons index and agent scripts run in every teammate's next session" bash -c "grep -qF 'hook settings' '$f' && grep -qF 'lessons index' '$f' && grep -qF 'agent-*' '$f' && grep -qF 'next session' '$f'" + expect "$b says the first stamp pull request is read by a second person and merged by hand" bash -c "grep -qF 'merged by hand' '$f' && grep -qF 'second person reads it' '$f'" + expect "$b says a pull request can edit the workflow file and the merge guard binds it" bash -c "grep -qF 'edit' '$f' && grep -qF 'ci.yml' '$f' || grep -qF 'workflow file' '$f'" + expect "$b says a job that runs PR code needs a separate runner or a container job, not for public repos" bash -c "grep -qF 'separate runner label or in a container job' '$f' && grep -qF 'never on the runner that runs' '$f' && grep -qF 'Not for public repos' '$f'" + expect "$b names instruction files as doors and --door-paths for the rest" bash -c "grep -qF 'reads as instructions is a door' '$f' && grep -qF -- '--door-paths' '$f'" +done +expect "AGENTS.md says never to run a pull request's copy of a script" grep -qF "never run a pull request's copy of a script" "$A" +expect "AGENTS.md names the conflict fix gh pr update-branch" grep -qF 'gh pr update-branch' "$A" + +# 8. values render, nothing is left over +expect "custom default branch reaches AGENTS.md" grep -qF '`master`' "$A" +expect "custom tags reach AGENTS.md" grep -qF 'app: lib: dev:' "$A" +expect "custom tags reach TEAM-WORKFLOW.md" grep -qF 'app,lib,dev' "$T" +expect "custom product paths reach both docs" bash -c "grep -qF 'app/,pkg/' '$A' && grep -qF 'app/,pkg/' '$T'" +expect "door paths reach both docs" bash -c "grep -qF 'docs/legal/*,protocol/*' '$A' && grep -qF 'docs/legal/*,protocol/*' '$T'" +expect "the door approver reaches both docs" bash -c "grep -qF '| reviewer |' '$A' && grep -qF '| reviewer |' '$T'" +expect "the default branch word 'main' appears nowhere with custom values" bash -c "! grep -qw 'main' '$A' '$T' '$P'" +expect "default values render too" bash -c "grep -qF '\`main\`' '$R1/AGENTS.md' && grep -qF 'product,dev' '$R1/docs/TEAM-WORKFLOW.md'" +expect "an empty door list still renders the door table" bash -c "grep -qF 'Paths the merge guard checks' '$R1/AGENTS.md' && grep -qF 'Who says the second yes' '$R1/AGENTS.md'" +for r in "$R1" "$R2"; do + expect "no {{KEY}} is left in $(basename "$r")" bash -c "! grep -rqE '\{\{[A-Za-z_]+\}\}' '$r/AGENTS.md' '$r/docs' '$r/.kit.toml'" +done + +# 9. hygiene of the generated text +for f in "$A" "$T" "$P" "$K"; do + b="${f#"$R2"/}" + expect "$b has no em or en dash" bash -c "! grep -qF -e '$EM' -e '$EN' '$f'" + expect "$b names no kit path or home path" bash -c "! grep -En '$LEAK_PATTERN' '$f' | grep -v '^1:<!-- kit:agents-pointer' | grep -q ." + expect "$b has no bare 40 or 64 digit hex string" bash -c "! grep -Eq '(^|[^0-9a-fA-F])([0-9a-fA-F]{40}|[0-9a-fA-F]{64})([^0-9a-fA-F]|$)' '$f'" +done +for t in AGENTS.md.tpl docs/TEAM-WORKFLOW.md.tpl docs/verification/README.md.tpl .kit.toml; do + expect "template $t has no em or en dash" bash -c "! grep -qF -e '$EM' -e '$EN' '$ROOT/templates/team-stamp/files/$t'" +done + +# 10. idempotent, and a repo edit is left alone +out="$(bash lib/stamp.sh --only rules "$R2" 2>&1)" +expect "a second run prints only unchanged" bash -c "! printf '%s\n' \"\$1\" | grep -Evq '^(unchanged|using): ' " _ "$out" +printf '\nA repo line.\n' >> "$A" +out="$(bash lib/stamp.sh --only rules "$R2" 2>&1)" +expect "an edited AGENTS.md is left alone" bash -c "printf '%s\n' \"\$1\" | grep -q 'edited (left alone): AGENTS.md' && tail -n 1 '$A' | grep -q 'A repo line.'" _ "$out" + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/test-stamp.sh b/tests/test-stamp.sh new file mode 100644 index 000000000..2f5f1b36c --- /dev/null +++ b/tests/test-stamp.sh @@ -0,0 +1,369 @@ +#!/usr/bin/env bash +# test-stamp.sh -- lib/stamp.sh engine: write, idempotence, never overwrite, drift, refresh, take, +# the kit-path scan, the settings merge, values and refusals. Runs against the fixture tree. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 +ROOT="$PWD" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +no() { FAIL=$((FAIL + 1)); echo "NOT ok - $1"; } +expect() { # expect <label> <command...> + local label="$1"; shift + if "$@"; then ok "$label"; else no "$label"; fi +} + +export STAMP_TEMPLATES="$ROOT/tests/fixtures/team-stamp" +WORK="$(mktemp -d "${TMPDIR:-/tmp}/test-stamp.XXXXXX")" || exit 1 +STAMP="bash $ROOT/lib/stamp.sh" +FLAGS="--default-branch main --owner alice" + +newrepo() { local d; d="$(mktemp -d "$WORK/r.XXXXXX")" && git -C "$d" init -q 2>/dev/null && echo "$d"; } +# run <repo> <args...>: stdout+stderr in $OUT, status in $RC +run() { local repo="$1"; shift; OUT="$($STAMP "$@" "$repo" 2>&1)"; RC=$?; } +tree_sum() { (cd "$1" && find . -path ./.git -prune -o -type f -print | LC_ALL=C sort | while read -r f; do printf '%s ' "$f"; cat "$f" | cksum; done) | cksum; } +has() { printf '%s\n' "$OUT" | grep -qF -- "$1"; } +hasre() { printf '%s\n' "$OUT" | grep -qE -- "$1"; } +line_after() { # line_after <rule-prefix> <next-prefix>: the line right after a rule line starts with <next-prefix> + printf '%s\n' "$OUT" | awk -v a="$1" -v b="$2" 'index($0,a)==1 {getline nx; if (index(nx,b)==1) f=1} END{exit !f}' +} +fixture_copy() { local d="$WORK/tpl.$RANDOM"; cp -R "$ROOT/tests/fixtures/team-stamp" "$d"; echo "$d"; } + +# 1. fresh stamp +R="$(newrepo)" +run "$R" $FLAGS +expect "fresh stamp exits 0" [ "$RC" -eq 0 ] +expect "fresh stamp prints created for each file" bash -c "[ \$(printf '%s\n' \"\$1\" | grep -c '^created: ') -eq 8 ]" _ "$OUT" +expect "settings.json is merged, not created" has "merged: .claude/settings.json" +expect "all manifest groups are written (second group too)" [ -f "$R/docs/second.txt" ] +expect "a 0755 row is executable" [ -x "$R/scripts/hello.sh" ] +expect "a 0644 row is not executable" [ ! -x "$R/README.md" ] +expect "values render" grep -q "Default branch: main" "$R/README.md" +expect "the owner renders" grep -q "Owner: alice" "$R/README.md" +expect "no {{KEY}} is left in any file" bash -c "! grep -rE '\{\{[A-Z_]+\}\}' '$R' --exclude-dir=.git" +expect "the kit marker is line 1 of the pointer" bash -c "[ \"\$(head -n 1 '$R/AGENTS.md')\" = \"\$(head -n 1 '$ROOT/lib/adopt/AGENTS.pointer.md')\" ]" +expect "a hook row writes the merged target list" grep -q -- "- docs/second.txt" "$R/TARGETS.md" +expect "derived ERE renders" grep -q '^product: \^(src/)$' "$R/docs/second.txt" +expect "an empty door list renders an empty array body" grep -qxF 'door array: ()' "$R/docs/second.txt" +expect "the decision tag defaults" grep -qxF 'decision tag: #decision' "$R/docs/second.txt" +expect "the lock records values and one hash per file" bash -c "grep -q '^value OWNER alice' '$R/.claude/team-stamp.lock' && [ \$(grep -c '^file ' '$R/.claude/team-stamp.lock') -eq 9 ]" + +# 2. second run is a no-op +before="$(tree_sum "$R")" +run "$R" +expect "second run (no flags) exits 0" [ "$RC" -eq 0 ] +expect "second run prints only unchanged" bash -c "[ \$(printf '%s\n' \"\$1\" | grep -Evc '^(unchanged|using): ') -eq 0 ]" _ "$OUT" +expect "second run changes no byte" [ "$before" = "$(tree_sum "$R")" ] + +# 2b. seed-once and hook rows are repo-owned after the first write +printf 'my owner table\n' > "$R/OWNERS.md"; printf 'my targets\n' > "$R/TARGETS.md" +run "$R" +expect "an edited seed file is unchanged, never drift-checked" has "unchanged: OWNERS.md" +expect "an edited hook file is unchanged too" has "unchanged: TARGETS.md" +expect "and the edit stays" bash -c "[ \"\$(cat '$R/OWNERS.md')\" = 'my owner table' ]" +run "$R" --check; expect "check is clean with edited repo-owned files" [ "$RC" -eq 0 ] +mv "$R/OWNERS.md" "$WORK/OWNERS.md.moved"; run "$R" +expect "a deleted seed file is created again" has "created: OWNERS.md" +run "$R" --take OWNERS.md +expect "take refuses a seeded file" has "seeded once and then belongs to the repo" +R2b="$(newrepo)"; run "$R2b" --only fixture $FLAGS +expect "--only keeps the merged target list for a hook" grep -q -- "- docs/second.txt" "$R2b/TARGETS.md" + +# 3. dry run and check +R2="$(newrepo)" +run "$R2" --dry-run $FLAGS +expect "dry run prints would create" has "would create: README.md" +expect "dry run writes nothing" bash -c "[ -z \"\$(ls -A '$R2' | grep -v '^.git\$')\" ]" +run "$R2" --check $FLAGS +expect "check on an unstamped repo exits 1" [ "$RC" -eq 1 ] +run "$R" --check +expect "check on a clean stamp exits 0" [ "$RC" -eq 0 ] + +# 4. never overwrites an edited file +printf 'my own words\n' >> "$R/README.md" +sum_readme="$(cksum < "$R/README.md")" +run "$R" +expect "an edited file is reported" hasre '^edited \(left alone\): README.md \([0-9]+ lines differ\)' +expect "an edited file is left byte for byte" [ "$sum_readme" = "$(cksum < "$R/README.md")" ] +run "$R"; expect "still left alone on the next run" has "edited (left alone): README.md" +run "$R" --check; expect "check exits 1 with an edited file" [ "$RC" -eq 1 ] + +# 5. a pre-existing file the stamp never wrote +R3="$(newrepo)" +printf 'repo rules\n' > "$R3/AGENTS.md" +run "$R3" $FLAGS +expect "a pre-existing different file is left alone" bash -c "[ \"\$(cat '$R3/AGENTS.md')\" = 'repo rules' ]" +expect "it is reported as not written by stamp" has "not written by stamp" +R3b="$(newrepo)" +cp "$R/scripts/hello.sh" /dev/null +mkdir -p "$R3b/scripts"; printf '#!/usr/bin/env bash\necho hello\n' > "$R3b/scripts/hello.sh" +run "$R3b" $FLAGS +expect "a pre-existing identical file counts as unchanged and enters the lock" bash -c "grep -q '^file scripts/hello.sh ' '$R3b/.claude/team-stamp.lock'" + +# 6. a symlink at a target is refused, nothing written +R4="$(newrepo)"; OUTSIDE="$WORK/outside.txt"; echo outside > "$OUTSIDE" +ln -s "$OUTSIDE" "$R4/README.md" +run "$R4" $FLAGS +expect "a symlinked target refuses the run" [ "$RC" -eq 1 ] +expect "the refusal is two lines, rule then Fix" line_after "stamp: refusing" "Fix:" +expect "nothing was written" bash -c "[ ! -e '$R4/AGENTS.md' ] && [ ! -e '$R4/.claude' ] && [ \"\$(cat '$OUTSIDE')\" = outside ]" + +# 7. a file the lock lists is gone: missing, not re-created +rm_target="$R/docs/second.txt"; mv "$rm_target" "$WORK/second.txt.moved" +run "$R" +expect "a deleted stamped file is reported missing" has "missing: docs/second.txt" +expect "and is not re-created" [ ! -e "$rm_target" ] +run "$R" --check; expect "check exits 1 on a missing file" [ "$RC" -eq 1 ] +mv "$WORK/second.txt.moved" "$rm_target" + +# 8. an older stamp: template changed, repo did not edit +TPL="$(fixture_copy)" +R5="$(newrepo)" +STAMP_TEMPLATES="$TPL" run "$R5" $FLAGS +printf 'Added by a newer template\n' >> "$TPL/files/second.txt" +before="$(tree_sum "$R5")" +STAMP_TEMPLATES="$TPL" run "$R5" +expect "a changed template over an unedited file is an older stamp" has "older stamp (run --refresh): docs/second.txt" +expect "a default run does not touch it" [ "$before" = "$(tree_sum "$R5")" ] +STAMP_TEMPLATES="$TPL" run "$R5" --refresh +expect "refresh prints one diff with the added line" has "+Added by a newer template" +expect "refresh names the --take fix" has "Fix: bash lib/stamp.sh --take docs/second.txt" +expect "refresh writes nothing" [ "$before" = "$(tree_sum "$R5")" ] + +# 9. take: an unedited older file is replaced and the old copy is kept +STAMP_TEMPLATES="$TPL" run "$R5" --take docs/second.txt +expect "take exits 0" [ "$RC" -eq 0 ] +expect "take replaced the file" grep -q "Added by a newer template" "$R5/docs/second.txt" +expect "take kept the old copy as .orig" bash -c "grep -q '^door:' '$R5/docs/second.txt.orig' && ! grep -q 'Added by a newer' '$R5/docs/second.txt.orig'" +STAMP_TEMPLATES="$TPL" run "$R5" +expect "after take the file is unchanged again" has "unchanged: docs/second.txt" + +# 10. take on an edited file is refused, diff printed, file untouched +printf 'Added by a newer template\nand more\n' >> "$TPL/files/README.md.tpl" +printf 'edited line\n' >> "$R5/README.md" +sum5="$(cksum < "$R5/README.md")" +STAMP_TEMPLATES="$TPL" run "$R5" --take README.md +expect "take on an edited file exits 1" [ "$RC" -eq 1 ] +expect "take prints the diff to apply" has "+and more" +expect "take refuses with the apply-by-hand fix" line_after "stamp: README.md was edited" "Fix: apply the diff above by hand" +expect "take left the edited file alone" [ "$sum5" = "$(cksum < "$R5/README.md")" ] +STAMP_TEMPLATES="$TPL" run "$R5" --take scripts/nope.sh +expect "take on a path outside the manifest is refused" [ "$RC" -eq 1 ] + +# 11. take swaps adopt's kit pointer for the stamp's file, and only that +R6="$(newrepo)" +cp "$ROOT/lib/adopt/AGENTS.pointer.md" "$R6/AGENTS.md" +run "$R6" $FLAGS +expect "an adopt pointer in AGENTS.md is left by a default run" cmp -s "$ROOT/lib/adopt/AGENTS.pointer.md" "$R6/AGENTS.md" +run "$R6" --take AGENTS.md +expect "take replaces a known kit pointer" bash -c "grep -q 'Fixture rules' '$R6/AGENTS.md' && cmp -s '$ROOT/lib/adopt/AGENTS.pointer.md' '$R6/AGENTS.md.orig'" + +# 11b. adopt interplay: .kit.toml drift line, foreign kit hooks, adopt's proof marker +R6b="$(newrepo)" +printf '[gate]\nlane_gates = true\n' > "$R6b/.kit.toml" +run "$R6b" $FLAGS +expect "a .kit.toml with lane_gates = true is left alone" bash -c "grep -q 'lane_gates = true' '$R6b/.kit.toml'" +expect "and gets a two-line drift report" line_after "stamp: .kit.toml sets lane_gates = true" "Fix: set lane_gates = false in .kit.toml" +run "$R6b" --check; expect "check exits 1 on that drift" [ "$RC" -eq 1 ] +R6c="$(newrepo)"; mkdir -p "$R6c/.claude" +echo '{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"bash $HOME/.claude/dwarves-kit/hooks/x.sh"}]}]}}' > "$R6c/.claude/settings.json" +run "$R6c" $FLAGS +expect "foreign kit hook entries are reported" has "note: .claude/settings.json holds 1 kit hook command(s)" +expect "and left in place" bash -c "jq -e '.hooks.Stop[0].hooks[0].command | contains(\"dwarves-kit\")' '$R6c/.claude/settings.json' >/dev/null" +R6d="$(newrepo)" +printf '# Verification (proof-of-done marker)\n\nPresence of this file opts this repo in.\n' > "$R6d/README.md" +run "$R6d" $FLAGS +expect "adopt's proof marker is left by a default run" has "edited (left alone): README.md" +run "$R6d" --take README.md +expect "take replaces adopt's proof marker" bash -c "grep -q 'Default branch: main' '$R6d/README.md' && grep -q 'proof-of-done marker' '$R6d/README.md.orig'" + +# 12. a kit path in a template aborts the whole run before any write +TPL2="$(fixture_copy)" +printf 'see ~/.claude/dwarves-kit/AGENTS.md\n' >> "$TPL2/files/second.txt" +R7="$(newrepo)" +STAMP_TEMPLATES="$TPL2" run "$R7" $FLAGS +expect "a kit path in a template refuses the run" [ "$RC" -eq 1 ] +expect "the refusal names the file and the Fix" line_after "stamp: docs/second.txt would carry a path under the kit" "Fix: remove that text" +expect "nothing was written, not even the lock" bash -c "[ -z \"\$(ls -A '$R7' | grep -v '^.git\$')\" ]" +TPL3="$(fixture_copy)"; printf 'home /Users/someone/x\n' >> "$TPL3/files/second.txt" +STAMP_TEMPLATES="$TPL3" run "$(newrepo)" $FLAGS +expect "an absolute home path is refused too" [ "$RC" -eq 1 ] + +# 13. key contract +TPL4="$(fixture_copy)"; printf 'x {{TAGS}}\n' >> "$TPL4/files/second.txt" +STAMP_TEMPLATES="$TPL4" run "$(newrepo)" $FLAGS +expect "a template using an undeclared key is refused" has "uses {{TAGS}} but its manifest row does not declare it" +TPL5="$(fixture_copy)"; printf 'x {{NOPE}}\n' >> "$TPL5/files/second.txt"; sed -i.bak 's/PRODUCT_ERE,/PRODUCT_ERE,NOPE,/' "$TPL5/manifest.d/10-second.tsv" +STAMP_TEMPLATES="$TPL5" run "$(newrepo)" $FLAGS +expect "an unknown declared key is refused" has "the unknown key NOPE" +TPL6="$(fixture_copy)"; printf 'copy\tfiles/second.txt\tdocs/second.txt\t0644\n' > "$TPL6/manifest.d/10-second.tsv" +STAMP_TEMPLATES="$TPL6" run "$(newrepo)" $FLAGS +expect "a manifest row with four columns is refused" has "empty keys column" +TPL7="$(fixture_copy)"; printf 'copy\tfiles/second.txt\tREADME.md\t0644\t-\n' >> "$TPL7/manifest.d/10-second.tsv" +STAMP_TEMPLATES="$TPL7" run "$(newrepo)" $FLAGS +expect "a target listed twice is refused" has "listed twice" + +# 14. settings merge +R8="$(newrepo)"; mkdir -p "$R8/.claude" +cat > "$R8/.claude/settings.json" <<'EOF' +{"theme":"dark","hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"foreign-hook.sh"}]}],"Stop":[{"hooks":[{"type":"command","command":"stop.sh"}]}]}} +EOF +run "$R8" $FLAGS +S="$R8/.claude/settings.json" +expect "merge keeps a foreign top-level key" bash -c "[ \"\$(jq -r .theme '$S')\" = dark ]" +expect "merge keeps a foreign hook in the same matcher group" bash -c "jq -e '.hooks.PreToolUse[0].hooks | map(.command) | index(\"foreign-hook.sh\") != null' '$S' >/dev/null" +expect "merge adds the stamp's hook to that group" bash -c "[ \$(jq '.hooks.PreToolUse[0].hooks | length' '$S') -eq 2 ]" +expect "merge keeps an unrelated event" bash -c "[ \"\$(jq -r '.hooks.Stop[0].hooks[0].command' '$S')\" = stop.sh ]" +expect "merge adds the SessionStart event" bash -c "jq -e '.hooks.SessionStart | length == 1' '$S' >/dev/null" +before="$(cksum < "$S")"; run "$R8" +expect "a second merge adds no duplicate" [ "$before" = "$(cksum < "$S")" ] +R8b="$(newrepo)"; mkdir -p "$R8b/.claude" +cat > "$R8b/.claude/settings.json" <<'EOF' +{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"foreign-a.sh"}]},{"matcher":"Bash","hooks":[{"type":"command","command":"bash \"$CLAUDE_PROJECT_DIR/scripts/hello.sh\""}]}],"SessionStart":[{"hooks":[{"type":"command","command":"foreign-b.sh"}]},{"hooks":[{"type":"command","command":"bash \"$CLAUDE_PROJECT_DIR/scripts/hello.sh\""}]}]}} +EOF +before="$(cksum < "$R8b/.claude/settings.json")"; run "$R8b" $FLAGS +expect "our entry found in a second group of the same matcher adds nothing" [ "$before" = "$(cksum < "$R8b/.claude/settings.json")" ] +expect "and the file reads unchanged" has "unchanged: .claude/settings.json" +R9="$(newrepo)"; mkdir -p "$R9/.claude"; echo '{ not json' > "$R9/.claude/settings.json" +run "$R9" $FLAGS +expect "invalid settings.json refuses the run" [ "$RC" -eq 1 ] +expect "and nothing else was written" bash -c "[ ! -e '$R9/README.md' ] && [ ! -e '$R9/.claude/team-stamp.lock' ] && [ \"\$(cat '$R9/.claude/settings.json')\" = '{ not json' ]" + +# 15. values: flags, lock, defaults, refusals +R10="$(newrepo)" +run "$R10" --default-branch trunk --owner bob --tags app,lib --product-paths src/,lib/ --door-paths 'docs/legal/*,protocol/*' --door-approver carol --decision-tag needs-human +expect "the decision tag flag renders" grep -qxF 'decision tag: #needs-human' "$R10/docs/second.txt" +expect "tags always include dev" bash -c "grep -q '^value TAGS app,lib,dev' '$R10/.claude/team-stamp.lock'" +expect "product paths become an array body" grep -qxF 'product array: ("src/" "lib/")' "$R10/docs/second.txt" +expect "door paths become an array body" grep -qxF 'door array: ("docs/legal/*" "protocol/*")' "$R10/docs/second.txt" +expect "tags become an awk list" grep -qxF 'tags awk: "app", "lib", "dev"' "$R10/docs/second.txt" +expect "tags become colon words" grep -qxF 'tags colon: app: lib: dev:' "$R10/docs/second.txt" +expect "tags become an ERE" grep -qxF 'tags ere: app|lib|dev' "$R10/docs/second.txt" +expect "product paths become a regex" grep -q '^product: \^(src/|lib/)$' "$R10/docs/second.txt" +expect "door paths become case alternatives" grep -q '^door: docs/legal/\*|protocol/\*$' "$R10/docs/second.txt" +run "$R10" +expect "a no-flag re-run reuses the lock's values" bash -c "[ \$(printf '%s\n' \"\$1\" | grep -Evc '^(unchanged|using): ') -eq 0 ]" _ "$OUT" +R11="$(newrepo)" +run "$R11" --default-branch main +expect "a missing owner refuses with the Fix line" line_after "stamp: no owner" "Fix: bash lib/stamp.sh --owner" +run "$R11" --owner alice +expect "a missing default branch (no origin) refuses with the Fix line" line_after "stamp: no default branch" "Fix: bash lib/stamp.sh --default-branch main" +run "$R11" --owner "@alice" --default-branch main +expect "an owner with @ is refused" has "bad --owner" +run "$R11" --owner alice --default-branch main --tags "Bad Tag" +expect "a bad tag list is refused" has "bad --tags" +R12="$(newrepo)"; git -C "$R12" remote add origin https://example.invalid/x.git +git -C "$R12" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/develop 2>/dev/null +run "$R12" --owner alice +expect "the default branch is read from origin/HEAD" bash -c "grep -q '^Default branch: develop' '$R12/README.md'" + +# 16. target refusals +NG="$(mktemp -d "$WORK/ng.XXXXXX")"; NG="$(cd "$NG" && pwd)" +run "$NG" $FLAGS +expect "a non-git target is refused with the git init fix" line_after "stamp: $NG is not a git repo" "Fix: git init" +run "$ROOT" $FLAGS +expect "the kit's own tree is refused" has "refusing to stamp the kit's own tree" +run "$WORK/missing-dir" $FLAGS +expect "a missing target dir is refused" [ "$RC" -eq 1 ] +OUT="$($STAMP --bogus 2>&1)"; RC=$? +expect "an unknown flag is a usage error (64)" [ "$RC" -eq 64 ] +OUT="$($STAMP --check --dry-run "$R" 2>&1)"; RC=$? +expect "two modes are a usage error (64)" [ "$RC" -eq 64 ] + +# 17. --only +R13="$(newrepo)" +run "$R13" --only second $FLAGS +expect "--only writes just the named group" bash -c "[ -f '$R13/docs/second.txt' ] && [ ! -e '$R13/README.md' ]" +run "$R13" --only nope $FLAGS +expect "--only with an unknown group is refused" has "no manifest group named 'nope'" +run "$R13" $FLAGS +expect "a later full run keeps the group's file and adds the rest" bash -c "[ -f '$R13/README.md' ] && grep -q '^file docs/second.txt ' '$R13/.claude/team-stamp.lock'" + +# 17b. the owners seed hook: one row per script and workflow of the merged manifest +TPLO="$WORK/tpl-owners"; mkdir -p "$TPLO/manifest.d" "$TPLO/files/scripts" "$TPLO/files/.github/workflows" +printf '#!/usr/bin/env bash\n' > "$TPLO/files/scripts/a.sh"; printf '#!/usr/bin/env bash\n' > "$TPLO/files/scripts/test-a.sh"; printf 'name: CI\n' > "$TPLO/files/.github/workflows/ci.yml" +printf 'copy\tfiles/scripts/a.sh\tscripts/a.sh\t0755\t-\ncopy\tfiles/scripts/test-a.sh\tscripts/test-a.sh\t0755\t-\n' > "$TPLO/manifest.d/10-scripts.tsv" +printf 'copy\tfiles/.github/workflows/ci.yml\t.github/workflows/ci.yml\t0644\t-\n' > "$TPLO/manifest.d/20-ci.tsv" +printf 'hook\tlib/stamp/owners-seed.sh\tOWNERS.md\t0644\tOWNER\n' > "$TPLO/manifest.d/30-owners.tsv" +R14="$(newrepo)" +STAMP_TEMPLATES="$TPLO" run "$R14" --only owners $FLAGS +expect "the owners seed lists every script of every group, even under --only" bash -c "grep -q '^| \`scripts/a.sh\` ' '$R14/OWNERS.md' && grep -q '^| \`scripts/test-a.sh\` | Test for scripts/a.sh | @alice | |' '$R14/OWNERS.md' && grep -q '^| \`.github/workflows/ci.yml\` ' '$R14/OWNERS.md'" +expect "the owners seed lists no row for itself" bash -c "! grep -q '^| \`OWNERS.md\`' '$R14/OWNERS.md'" + +# 17c. nothing a stamp writes trips a bare-hex secret scan +hexscan() { # hexscan <file>: print any 64-hex run not directly after a digest marker + sed -E "s/(sha256:|sha256: |sha256=|sha256-|sha256 \"|sha256 ')[0-9a-f]{64}//g" "$1" | grep -E '[0-9a-f]{64}' +} +R15="$(newrepo)"; run "$R15" $FLAGS +git -C "$R15" add -A >/dev/null 2>&1; git -C "$R15" diff --cached > "$WORK/staged.diff" +expect "the staged stamp output is not empty" [ -s "$WORK/staged.diff" ] +none_hex() { ! hexscan "$1" >/dev/null; } +expect "the staged diff holds no bare 64-hex run" none_hex "$WORK/staged.diff" +expect "the lock writes every hash as sha256:<hex>" bash -c "[ \$(grep -c '^file .* sha256:[0-9a-f]\{64\}\$' '$R15/.claude/team-stamp.lock') -eq \$(grep -c '^file ' '$R15/.claude/team-stamp.lock') ]" +bare="$(printf 'a%.0s' $(seq 1 64))"; printf 'digest %s\n' "$bare" > "$WORK/bare.txt"; printf 'sha256:%s\n' "$bare" > "$WORK/marked.txt" +catch_hex() { hexscan "$1" >/dev/null; } +expect "the scan catches a bare hex (self-test)" catch_hex "$WORK/bare.txt" +expect "the scan allows a marked digest (self-test)" none_hex "$WORK/marked.txt" +# an older lock with bare hex still reads: rewrite R15's lock the old way and expect a clean run +sed -E 's/ sha256:([0-9a-f]{64})$/ \1/' "$R15/.claude/team-stamp.lock" > "$WORK/old.lock"; cp "$WORK/old.lock" "$R15/.claude/team-stamp.lock" +run "$R15"; expect "a lock with bare hex still reads as unedited" bash -c "[ \$(printf '%s\n' \"\$1\" | grep -Evc '^(unchanged|using): ') -eq 0 ]" _ "$OUT" + +# 17d. values: control characters, dot-dot paths, and the values-in-use report +for flagname in default-branch owner tags product-paths door-paths door-approver board-file decision-tag; do + for bad in "$(printf 'a\nb')" "$(printf 'a\rb')" "$(printf 'a\tb')"; do + RX="$(newrepo)"; OUT="$($STAMP --default-branch main --owner alice "--$flagname" "$bad" "$RX" 2>&1)"; RC=$? + refused_ctl=1; [ "$RC" -eq 1 ] && printf '%s\n' "$OUT" | grep -q "^stamp: the value of --$flagname holds a newline, a carriage return or a tab" && refused_ctl=0 + [ "$refused_ctl" -eq 0 ] || echo " $flagname: rc=$RC" + expect "a $flagname value with a newline, CR or tab is refused first" [ "$refused_ctl" -eq 0 ] + done +done +RX="$(newrepo)"; OUT="$($STAMP --default-branch main --owner alice --product-paths "$(printf 'src/\nx"; touch PWNED; "')" "$RX" 2>&1)"; RC=$? +expect "a product path with a newline and a quote is refused, nothing written" bash -c "[ $RC -eq 1 ] && [ ! -e '$RX/.claude' ] && [ ! -e '$RX/PWNED' ]" +RX="$(newrepo)" +for badv in "--board-file ../../x" "--board-file /etc/x" "--product-paths ../src/" "--product-paths /abs/" "--door-paths a/../b" "--door-paths /x"; do + # shellcheck disable=SC2086 + OUT="$($STAMP --default-branch main --owner alice $badv "$RX" 2>&1)"; RC=$? + expect "$badv is refused ($RC)" bash -c "[ $RC -eq 1 ] && printf '%s\n' \"\$1\" | tail -n 2 | sed -n 2p | grep -q '^Fix: '" _ "$OUT" +done +RX="$(newrepo)"; run "$RX" --default-branch main --owner alice --board-file docs/BOARD.md --door-approver carol +expect "every run prints the values in use" has "using: OWNER=alice (flag)" +expect "a default value says it is a default" has "using: DECISION_TAG=decision (default)" +run "$RX" +expect "a no-flag re-run says the values came from the lock" has "using: BOARD_FILE=docs/BOARD.md (lock)" +# a planted lock: its values are used, seen, and checked +sed -i.bak 's|^value BOARD_FILE .*|value BOARD_FILE ../../x|' "$RX/.claude/team-stamp.lock" && rm -f "$RX/.claude/team-stamp.lock.bak" +run "$RX" +expect "a planted lock with a dot-dot board file is refused" bash -c "[ $RC -eq 1 ]" +expect "and the refusal names the value" has "--board-file starts with / or has a .. component" +sed -i.bak 's|^value BOARD_FILE .*|value BOARD_FILE docs/BOARD.md|; s|^value DOOR_APPROVER .*|value DOOR_APPROVER mallory|' "$RX/.claude/team-stamp.lock" && rm -f "$RX/.claude/team-stamp.lock.bak" +run "$RX" +expect "a planted approver is used but shown, with its source" has "using: DOOR_APPROVER=mallory (lock)" + +# 17f. a product path that makes an invalid pattern, or starts with *, is refused +for badp in "*/src" "*" "a[b/" "a(b/" "a)b/" "a\\/"; do + RX="$(newrepo)"; OUT="$($STAMP --default-branch main --owner alice --product-paths "$badp" "$RX" 2>&1)"; RC=$? + expect "product path '$badp' is refused with a two-line refusal" bash -c "[ $RC -eq 1 ] && printf '%s\n' \"\$1\" | tail -n 2 | sed -n 2p | grep -q '^Fix: ' && [ ! -e '$RX/.claude' ]" _ "$OUT" +done + +# 17e. take: the backup never goes through a symlink +TPLB="$(fixture_copy)"; RB="$(newrepo)" +STAMP_TEMPLATES="$TPLB" run "$RB" $FLAGS +printf 'Newer line\n' >> "$TPLB/files/second.txt" +printf 'plain old backup\n' > "$RB/docs/second.txt.orig" +OUTSIDE_B="$WORK/outside-backup-target" +ln -s "$OUTSIDE_B" "$RB/docs/second.txt.orig.1" +STAMP_TEMPLATES="$TPLB" run "$RB" --take docs/second.txt +expect "take with a dangling symlink at .orig.1 exits 0" [ "$RC" -eq 0 ] +expect "nothing was written through the dangling link" [ ! -e "$OUTSIDE_B" ] +expect "the link itself is untouched" [ -L "$RB/docs/second.txt.orig.1" ] +expect "the backup went to the next free name" [ -f "$RB/docs/second.txt.orig.2" ] +expect "and holds the old text" bash -c "grep -q '^door:' '$RB/docs/second.txt.orig.2' && ! grep -q 'Newer line' '$RB/docs/second.txt.orig.2'" +expect "the plain .orig was not overwritten" bash -c "[ \"\$(cat '$RB/docs/second.txt.orig')\" = 'plain old backup' ]" + +# 18. an empty manifest dir +TPL8="$WORK/empty-tpl"; mkdir -p "$TPL8/manifest.d" +STAMP_TEMPLATES="$TPL8" run "$(newrepo)" $FLAGS +expect "no manifest rows is refused" has "no manifest rows" + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ]