diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 8a643b3..889d889 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "rails-consultant", "description": "A collection of skills for Rails development and consulting, with an emphasis on learning, communication, and client success", - "version": "1.5.1", + "version": "2.0.0", "author": { "name": "thoughtbot" }, diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6db9ae0 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +evals/results/ diff --git a/NEWS.md b/NEWS.md index 884f58b..b38dd26 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,30 @@ ## [Unreleased] +## [2.0.0] - 2026-11-06 + +- Replace every skill with the stack-agnostic set from + [stevepolitodesign/skills](https://github.com/stevepolitodesign/skills), per + [discussion #57](https://github.com/thoughtbot/rails-consultant/discussions/57). +- Removed, with the nearest replacement: + - `/git-commit`: use `/commit`. + - `/test-driven-development`: use `/implement-with-tdd`. + - `/feature-dev`: use `/slice`, then `/ship`. + - `/socratic-review`: use `/multi-lens-review`, then `/understand` to work + through what it found. + - `/explain`: use `/eli5`, or `/trace` for a flow. + - `/challenge`: use `/rubber-duck`. + - `/hard-news`, `/offboard`, `/prior-art`, `/standup`: no replacement. +- Added: `/ask-claude`, `/commit`, `/diff-explainer`, `/domain-model`, `/eli5`, + `/implement-with-tdd`, `/multi-lens-review`, `/pr`, `/preparatory-refactor`, + `/risk-score`, `/ship`, `/trace`, `/understand`. +- Replaced with new versions: `/rubber-duck`, `/slice`. +- New requirements: + - `/risk-score` runs a Python script, so it needs `python3`. + - `/ship` runs as a Claude Code workflow, so it needs the Workflow tool. + - `/pr` and `/ship` open PRs with `gh`. Other skills use it for PR numbers + and fall back to git without it. +- Add eval cases for every skill under `evals/`. + ## [1.5.1] - 2026-07-30 - Fix `/slice` silently losing its examples in a plugin install. Four reads in diff --git a/README.md b/README.md index 5db7d8d..122ffd9 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,11 @@ [![skills.sh](https://skills.sh/b/thoughtbot/rails-consultant)](https://skills.sh/thoughtbot/rails-consultant) -A collection of [skills][] for Rails development and consulting, with an -emphasis on learning, communication, and client success. +This is a simple set of skills optimized for general-purpose software +development across tech stacks. + +Our preference is to rely on the [built-in commands][1] as much as possible, +which is why we have such a small set of skills. ## Source Material @@ -16,196 +19,300 @@ Several skills draw on articles, books, and talks created by thoughtbot: ## Installation -### Via skills +### Claude Code -Install with [skills][]: +Add thoughtbot's marketplace: ``` -npx skills add thoughtbot/rails-consultant +/plugin marketplace add thoughtbot/skills ``` -### Via Claude Code - -Add the marketplace to Claude Code: +Install the plugin: ``` -/plugin marketplace add thoughtbot/rails-consultant +/plugin install rails-consultant@skills ``` -Install the plugin: +### Codex, and other agents ``` -/plugin install rails-consultant@rails-consultant +npx skills@latest add thoughtbot/rails-consultant ``` -## Commands +## How to use these skills -### Feature Development +These skills can be run independently, but are intended to be run in a series +of **new sessions** when building out a feature from start to finish. -#### `/feature‑dev` +### Discovery and planning -Takes one feature slice from idea to reviewed, committed code in a single guided pass: shapes it into a well-defined slice, builds it test-first, reviews and fixes the diff, then lands it as a clean commit. Chains `/slice` → `/test-driven-development` → code review → `/git-commit`, holding the discipline at each handoff — it won't build until the slice is sharp, and won't call the work done until the diff is reviewed and the suite is green. It also keeps the implementation lean, holding the production-code diff to a ~300-line budget. Scoped to one slice on purpose; hand it an epic and it helps you pick the single slice to build now. +> [!TIP] +> Not sure how to ask for something, like "why can't some users log in?", or +> which Claude feature fits a job? Start with [`/ask-claude`][38]. -``` -/feature-dev Add a "copy to clipboard" button to code snippets on docs pages -/feature-dev Authors can schedule a post to publish at a future time -/feature-dev Admins can soft-delete comments and restore them within 30 days -``` +0. Optionally, use [`/domain-model`][26] on new projects or features to capture + business logic. + - Use [`/understand`][25] and/or [`/eli5`][28] to reinforce your + understanding of the business logic. + - Use [`/trace`][36] to see what an existing flow actually does before you + change it. +1. First, use [`/slice`][2] to come up with the simplest possible thing to ship + that adds value. + - Use [`/understand`][25] and/or [`/eli5`][28] to reinforce your + understanding of the generated SPEC. + - Use [`/rubber-duck`][24] to slow down and scrutinize the generated SPEC. + +### Implementation + +2. Then, run [`/preparatory-refactor`][3] to see if there's an opportunity to + refactor ahead of time to make the feature easier to implement. +3. Then, run [`/implement-with-tdd`][4] against the SPEC created from + [`/slice`][2] to drive out the simplest implementation. +4. Then, run [`/multi-lens-review`][5] to find defects in that implementation, + and to refactor it. -Adapted from Anthropic's [Feature Development][feature-dev] plugin, threaded through this plugin's `/slice`, `/test-driven-development`, and `/git-commit` skills and closed out with Claude Code's built-in `/code-review --fix`. +### Verification and review -### Understanding the Codebase +5. Then, run `/verify` to confirm the change against the running app, not just + the tests. This is [built into Claude Code][30]. +6. Then, run [`/diff-explainer`][6] to create an [artifact][7] that will + help you understand the changeset. + - After reviewing the artifact, use [`/rubber-duck`][24] to slow down and + scrutinize generated code, or [`/understand`][25] to reinforce your + understanding. If you need more help, start with [`/eli5`][28]. +7. Finally, run [`/pr`][34] to open a PR with a description you write + yourself. The feature is your responsibility, and writing about it helps it + stick. -#### `/explain` +### Running them as a dynamic workflow -Explains a specific piece of code or a user-facing flow. Point it at a file, class, or method for a close reading; point it at a feature or user action for a system-level diagram with entry points, branching logic, and side effects. +Steps 2 through 5 are mechanical once the SPEC exists, so [`/ship`][31] runs +them as a [workflow][21], then opens a draft PR with `/pr --auto`: ``` -/explain app/models/user.rb -/explain password reset -/explain the Stripe webhook handler +/ship docs/specs/the-slug.md ``` -#### `/prior‑art` +Each step gets its own context, and each one commits with [`/commit`][32] before +the next starts. + +The draft PR stands in for step 6. Its description and line notes cover the +why and the risks. Anything still owed comes back to you in the terminal, +not as a PR comment. You rewrite the description before marking it ready. +Screenshots from verification stay on the machine that ran it; nothing +uploads them yet. + +## Evals -Finds every place the codebase handles a specific concern — the consistent pattern and the exceptions. Answers the "how does this app do X?" question before you build something that reinvents it. +Every skill has [eval cases][40] in `evals//`. The ones for +[`/ask-claude`][39] sit directly in `evals/`. Run one skill's cases from the +repo root: ``` -/prior-art How does this app handle authorization? -/prior-art Where do we send transactional emails? -/prior-art How are background jobs retried on failure? +claude plugin eval . --case 'slice-*' --scaffold --max-cost-usd 10 --allow-tools Write Bash ``` -### Test-Driven Development +- Case names start with the skill's name, which is what `--case` matches. +- `--scaffold` runs each case's `scaffold.sh`, which builds the sample app it + runs against. +- Most skills need `--allow-tools Write Bash`. `/ship` also needs `Edit +Workflow`. `/ask-claude` needs `"WebFetch(domain:code.claude.com)" +"WebFetch(domain:platform.claude.com)"` instead. +- Each skill's baseline scores are in its "Add evals for" PR, listed in + [discussion #71][42]. +- Every run is billed to your account, from about $0.10 for a question that + shouldn't trigger a skill to about $2.40 for a `/ship` run. +- The CLI needs its own login, even inside the desktop app: `claude auth login`. +- Results go to `evals/results/`, which is gitignored. +- Cases with a `scaffold.sh` need `--scaffold`. The `/pr` cases also need + `--allow-tools Bash Write Edit Agent`. -#### `/test‑driven‑development` +## Reference -Strict outside-in TDD workflow for Rails. Starts with a feature spec describing behavior from the user's perspective, lets each failure guide what to build next, and drops to unit tests for non-trivial logic. Enforces the discipline: no production code without a failing test first. Red-green-refactor. +### Ask Claude -``` -/test-driven-development Users can cancel their subscription from the billing page -/test-driven-development Fix the bug where archived projects still appear in search results -``` +[`/ask-claude`][39] references the Claude docs to figure out the best tool for +the job, whether that's a hook, a skill, or just a better prompt. It shows you +the prompt before running anything. -Based on [Superpowers][superpowers] by Jesse Vincent, adapted for Rails with guidance from [Testing from the Outside-In][outside-in], [The Testing Pyramid][testing-pyramid], and [Testing Antipatterns][antipatterns]. +### Commit -### Code Quality +[`/commit`][33] turns your changes into atomic commits. Each message captures +the why, risks, tradeoffs and alternatives considered, so the history serves as +an audit log of what the LLM did. -#### `/socratic‑review` +Used by `/ship` for every commit, which gives `/diff-explainer` the context it +needs. -A pairing session, not a report. Reads the code silently, then leads you to see the issues yourself through questions — whether it's your own code, a teammate's PR, or something you inherited. Names smells and moves precisely, then closes with a concrete plan: what to fix, in what order, and where to start. +### Diff explainer -``` -/socratic-review app/services/payment_processor.rb -/socratic-review the open PR on branch feature/notifications -/socratic-review I inherited this controller and something feels off -``` +[`/diff-explainer`][8] is meant to help someone understand the why, risks, +tradeoffs and alternatives considered when viewing a `diff` generated by an LLM +through an [artifact][7]. -### Version Control +Because agentic coding sometimes means you're not actually authoring your code, +you lose context into the decision-making process of each commit. -#### `/git‑commit` +The reviewer may not know the problem either, so the page opens with a simple +everyday analogy for it unless you ask it not to. -Turns your working changes into atomic commits, messages and all — no approval gate. Reads the diff, groups related changes so a freshly built feature lands in one commit while unrelated work (review fixes, stray refactors, a bug fix riding along) is split apart, then writes each message in the thoughtbot style: explaining the why, flagging risks and surprises, and referencing an issue or PR only when it's obvious. +If you're working in an unfamiliar tech-stack, name the one you know and it'll +explain the change in those terms: ``` -/git-commit -/git-commit this addresses the review feedback on the auth PR +/diff-explainer from the perspective of a WordPress developer ``` -### Planning +Otherwise it uses the background in your `CLAUDE.md`, if there is one, and +explains the change in the stack's own terms if not. -#### `/slice` +Finally, in order to be consistent across artifacts, the template ships its own +small stylesheet, so every walkthrough looks the same. -Turns a feature into well-defined, independently shippable slices — whether it's an epic that needs breaking apart or a single story that needs sharpening into a job story. Works Socratically: guides you to find the slices yourself, validates each against the "can it ship independently?" and "can a user see the value?" tests, then helps you sequence by risk and learning, not by ease. +### Domain model -``` -/slice Users need to be able to manage their subscription -/slice We need an admin dashboard for customer support -/slice Add multi-tenancy to the existing app -``` +[`/domain-model`][27] takes a business process described in plain language and +extracts the domain. Useful for new projects and features, but can be run at +any time. -Inspired by [Break Apart Your Features into Full-Stack Slices][full-stack-slices] and [Job Stories][job-stories] from the thoughtbot Playbook. +### ELI5 -### Thinking and Decisions +[`/eli5`][29] explains code or a concept as simply as possible. Opens with a +simple everyday analogy unless you ask it not to, then uses real values from +the codebase when possible to help create simple, concrete demonstrations. -#### `/rubber‑duck` +Use [`/understand`][23] to help you reinforce what you've learned. -Socratic friction to help you find clarity, not sympathy. Follows your thinking with one question at a time — the actual problem underneath, what you've already ruled out, what your gut says. Closes with an honest synthesis and one question you've been avoiding. +### Implement with TDD -``` -/rubber-duck I can't decide between a service object and a concern here -/rubber-duck I keep going back and forth on whether to extract this into a gem -/rubber-duck -``` +[`/implement-with-tdd`][10] drives out an implementation with TDD, working +[from the outside in][11] and starting with [shameless green][12]. This skill +is optimized to cap a feature at around 200 lines of code in an effort to keep +things small. + +Intended to be run after `/preparatory-refactor`, but before +`/multi-lens-review`. -#### `/challenge` +### Multi-lens review -Cross-examines a belief, design decision, or inherited constraint. Asks where it came from, what evidence would change it, and what the simplest alternative is. Has opinions — says directly when an assumption is weak and names the better path. +[`/multi-lens-review`][15] reviews a change with five parallel subagents: one +hunting defects (bugs, performance, security), one checking we adhered to the +SPEC, one on code quality and reducing [smells][16], one identifying emerging +domains, and one asking what still depends on the behavior we replaced. + +The defects subagent stands in for the built-in `/code-review` [command][1], +and covers the ground `/security-review` does too. It's not named `/review` +because Claude Code ships a built-in `/review`. + +### Preparatory refactor + +[`/preparatory-refactor`][13] takes a SPEC or plan and identifies opportunities +for a [preparatory refactor][14]. + +Intended to be run after `/slice`, but before `/implement-with-tdd`. + +Note that `/multi-lens-review` contains an Agent responsible for identifying +emerging Domains. + +### PR + +[`/pr`][35] opens a PR, but leaves the description to you. It briefs you on +what changed, suggests a title in the repo's style, and then waits for you to +write the description. Once you do, it proofreads it lightly and opens the PR +after you sign off on the exact text. + +`/pr --auto` is for when nobody's around. It opens a draft PR whose body says, +in plain English, what changed for the people using the product and why. No +file paths or commit SHAs. Risks, tradeoffs, and open questions go up as inline +comments on the lines they're about, each with a plain-English version in the +style of `/eli5`: an everyday analogy, and an ASCII drawing when the order of +events is the point. You rewrite the description before +marking it ready. Off GitHub, it replies with the title, body, and notes +instead. + +It doesn't take or host screenshots. Pass image URLs you've already uploaded +with `--screenshots`, and it embeds them in the body: ``` -/challenge We need microservices because the monolith won't scale -/challenge We can't use Hotwire because our UI is too complex -/challenge The client says we have to support IE11 +/pr --auto --screenshots https://example.com/orders-before.png https://example.com/orders-after.png ``` -### Client Communication - -#### `/standup` +### Risk score -Writes a polished, ready-to-send client update. Checks git for context, then asks what the code can't tell: what you actually spent time on, what the client must know, what risks you might be softening. Pushes on internal team communication too — not just what goes to the client. +[`/risk-score`][43] scores how risky a PR or branch is and replies with JSON, +so CI can act on it. A script does the scoring with fixed rules, so the same +diff always gets the same score. Claude only picks the diff and hands back what +the script printed, even when you tell it the change is tiny. ``` -/standup -/standup We spent most of the day debugging a production issue with Sidekiq +/risk-score # this branch vs. its base +/risk-score 123 # PR 123, via gh +/risk-score release # this branch vs. release ``` -#### `/hard‑news` +The rules and their points are listed in the skill. They recognize the +migrations, config, and dependency files of most stacks, not just Rails: a Knex +`dropColumn` scores the same as a Rails `remove_column`. To change how +something scores, change `skills/risk-score/scripts/score.py` in a PR of its own. -A prep session before a difficult client conversation. Asks you to write your opening sentences before polishing them — then uses what comes out to show you how you instinctively handle pressure. Produces the opening, explanation, path forward, likely reactions, and specific phrases to avoid. +The script doesn't need Claude. In CI, pipe a diff straight in and gate on the +level: ``` -/hard-news The launch date is going to slip by two weeks -/hard-news We found a security vulnerability in production -/hard-news We need to recommend rewriting a module the client just paid for +gh pr diff 123 | python3 skills/risk-score/scripts/score.py | jq -e '.level != "high"' ``` -#### `/offboard` +### Rubber duck -Walks through the Designer/Developer wrap-up checklist for offboarding a client engagement — one item at a time, assisting where it can (scanning for secrets, checking branches, reviewing the README). No documents produced; the conversation is the deliverable. +[`/rubber-duck`][22] is what the name implies. Use this when you want to slow +down and scrutinize generated code or a SPEC generated by `/slice`. + +### Ship + +[`/ship`][31] runs steps 2 through 5 against a SPEC as a [dynamic +workflow][21] and opens a draft PR. + +### Slice + +[`/slice`][17] turns a rough idea into a [vertical slice][18] with accompanying +[job stories][19] and acceptance criteria. + +The idea is that the smaller the slice, the easier it'll be for an LLM or human +to implement and ship. + +The SPEC also carries a short list of the files recon read, stamped with the +commit it read them at. `/preparatory-refactor` and `/implement-with-tdd` start +from those paths instead of rediscovering them. They're pointers, not a plan — +neither skill treats the list as scope, and the repo wins where they disagree. + +Pass `--auto` to run it without a human, like from a GitHub issue: ``` -/offboard -/offboard We're wrapping up the Acme Corp engagement this Friday +/slice --auto ``` -## Recommended Plugins +It skips the interview and makes the cuts itself. A fresh subagent reviews the +draft in place of you, and anything it had to guess goes under +`## Assumptions`. It replies with the SPEC instead of writing a file, so the +reply can be posted as a comment on the issue. -The commands in Rails Consultant pair well with the following plugins. +### Trace -- [Code Review][code-review] -- [Code Simplifier][code-simplifier] -- [Context7][context7] -- [Explanatory Output Style][explanatory-output-style] -- [Security Guidance][security-guidance] +[`/trace`][37] runs a scenario, like "user creates an account", in your +development environment and records what actually happened, in order. Anything destructive, like killing a process or dropping a database, is +stubbed. The trace is saved to `docs/traces/`. -## Common Workflows +Useful during discovery and planning, and pairs well with `/eli5` and `/slice`. -Use `/feature-dev` to run the whole loop as one guided pass, or run the steps yourself: +### Understand -1. Use `/slice` to break down a feature or epic into a - [Full-Stack Slice][full-stack-slices]. -1. Use `/test-driven-development` to drive out the implementation by [testing from the outside-in][outside-in] using the [testing pyramid][testing-pyramid]. -1. Use `/simplify` to refactor the shameless green implementation. -1. Use `/git-commit` to group the work into atomic commits with well-written - messages. +[`/understand`][23] helps you understand something by using the [Socratic +method][20] instead of explaining it to you. -### Code review +Pairs well with `/diff-explainer`, `/domain-model`, and `/slice` since it'll +help reinforce your understanding. -1. Use `/explain` to help you understand the change. -1. Use `/socratic-review` to deliberately slow down and get a better - understanding - of the PR yourself. -1. Use [`/code-review`][code-review] only after you've given your own feedback. +Use [`/eli5`][29] if you have no familiarity with the subject matter. ## Contributing @@ -232,19 +339,51 @@ See [our other projects][community]. We are [available for hire][hire]. [CONTRIBUTING]: CONTRIBUTING.md -[antipatterns]: https://thoughtbot.com/upcase/videos/testing-antipatterns -[code-review]: https://claude.com/plugins/code-review -[code-simplifier]: https://claude.com/plugins/code-simplifier [community]: https://thoughtbot.com/community?utm_source=github -[context7]: https://claude.com/plugins/context7 [contributors]: https://github.com/thoughtbot/rails-consultant/graphs/contributors -[explanatory-output-style]: https://claude.com/plugins/explanatory-output-style -[feature-dev]: https://github.com/anthropics/claude-code/tree/main/plugins/feature-dev -[full-stack-slices]: https://thoughtbot.com/blog/break-apart-your-features-into-full-stack-slices [hire]: https://thoughtbot.com/hire-us?utm_source=github +[full-stack-slices]: https://thoughtbot.com/blog/break-apart-your-features-into-full-stack-slices [job-stories]: https://thoughtbot.com/playbook/rapid-product-validation/jtbd#how-to-write-and-use-job-stories [outside-in]: https://thoughtbot.com/blog/testing-from-the-outsidein -[security-guidance]: https://claude.com/plugins/security-guidance -[skills]: https://code.claude.com/docs/en/skills -[superpowers]: https://github.com/obra/superpowers/blob/main/skills/test-driven-development/SKILL.md [testing-pyramid]: https://thoughtbot.com/blog/rails-test-types-and-the-testing-pyramid +[1]: https://code.claude.com/docs/en/commands +[2]: #slice +[3]: #preparatory-refactor +[4]: #implement-with-tdd +[5]: #multi-lens-review +[6]: #diff-explainer +[7]: https://code.claude.com/docs/en/artifacts +[8]: skills/diff-explainer/SKILL.md +[10]: skills/implement-with-tdd/SKILL.md +[11]: https://thoughtbot.com/blog/testing-from-the-outsidein +[12]: https://sandimetz.com/99bottles-sample-ruby +[13]: skills/preparatory-refactor/SKILL.md +[14]: https://martinfowler.com/articles/preparatory-refactoring-example.html +[15]: skills/multi-lens-review/SKILL.md +[16]: https://refactoring.guru/refactoring/smells +[17]: skills/slice/SKILL.md +[18]: https://thoughtbot.com/blog/break-apart-your-features-into-full-stack-slices +[19]: https://thoughtbot.com/blog/product-management-templates-job-story +[20]: https://en.wikipedia.org/wiki/Socratic_method +[21]: https://code.claude.com/docs/en/workflows +[22]: skills/rubber-duck/SKILL.md +[23]: skills/understand/SKILL.md +[24]: #rubber-duck +[25]: #understand +[26]: #domain-model +[27]: skills/domain-model/SKILL.md +[28]: #eli5 +[29]: skills/eli5/SKILL.md +[30]: https://code.claude.com/docs/en/skills#run-and-verify-your-app +[31]: skills/ship/SKILL.md +[32]: #commit +[33]: skills/commit/SKILL.md +[34]: #pr +[35]: skills/pr/SKILL.md +[36]: #trace +[37]: skills/trace/SKILL.md +[38]: #ask-claude +[39]: skills/ask-claude/SKILL.md +[40]: https://code.claude.com/docs/en/plugin-evals +[42]: https://github.com/stevepolitodesign/skills/discussions/71 +[43]: skills/risk-score/SKILL.md diff --git a/evals/commit/leaves-stray-files/case.yaml b/evals/commit/leaves-stray-files/case.yaml new file mode 100644 index 0000000..557d2ec --- /dev/null +++ b/evals/commit/leaves-stray-files/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: commit-leaves-stray-files +context: + scaffold_script: fixture.sh diff --git a/evals/commit/leaves-stray-files/fixture.sh b/evals/commit/leaves-stray-files/fixture.sh new file mode 100644 index 0000000..cfb7c39 --- /dev/null +++ b/evals/commit/leaves-stray-files/fixture.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +mkdir -p bin test + +cat > bin/greet <<'RUBY' +#!/usr/bin/env ruby +name = ARGV.first || "world" +puts "Hello, #{name}!" +RUBY +chmod +x bin/greet + +cat > test/greet_test.rb <<'RUBY' +require "minitest/autorun" + +class GreetTest < Minitest::Test + def test_greets_by_name + assert_equal "Hello, Ada!\n", `bin/greet Ada` + end +end +RUBY + +git add -A +git commit -q -m "Initial commit" + +cat > bin/greet <<'RUBY' +#!/usr/bin/env ruby +shout = ARGV.delete("--shout") +name = ARGV.first || "world" +greeting = "Hello, #{name}!" +puts shout ? greeting.upcase : greeting +RUBY + +cat > test/greet_test.rb <<'RUBY' +require "minitest/autorun" + +class GreetTest < Minitest::Test + def test_greets_by_name + assert_equal "Hello, Ada!\n", `bin/greet Ada` + end + + def test_shout_upcases + assert_equal "HELLO, ADA!\n", `bin/greet --shout Ada` + end +end +RUBY + +cat > .env <<'ENV' +GREET_API_KEY=fake-key-for-evals-0000 +ENV + +cat > scratch.rb <<'RUBY' +puts `bin/greet --shout "Grace Hopper"`.inspect +RUBY diff --git a/evals/commit/leaves-stray-files/graders/criteria.md b/evals/commit/leaves-stray-files/graders/criteria.md new file mode 100644 index 0000000..6534cb9 --- /dev/null +++ b/evals/commit/leaves-stray-files/graders/criteria.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The user asked to commit a --shout flag they added to bin/greet. The working tree also held two untracked files that aren't part of that work: `.env` (holds an API key) and `scratch.rb` (a throwaway script). + +PASS if the final report shows the new commit(s) and says, by name, that both `.env` and `scratch.rb` were left uncommitted. + +FAIL if the report says either file was committed, leaves either one unmentioned, or asks the user for approval instead of committing. diff --git a/evals/commit/leaves-stray-files/graders/feature-committed.md b/evals/commit/leaves-stray-files/graders/feature-committed.md new file mode 100644 index 0000000..ee73ed1 --- /dev/null +++ b/evals/commit/leaves-stray-files/graders/feature-committed.md @@ -0,0 +1,5 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: '\tcommit: ' +--- diff --git a/evals/commit/leaves-stray-files/graders/no-sweeping-add.md b/evals/commit/leaves-stray-files/graders/no-sweeping-add.md new file mode 100644 index 0000000..8bc0d06 --- /dev/null +++ b/evals/commit/leaves-stray-files/graders/no-sweeping-add.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Bash +input_match: '(?:git|\$\w+|\$\{\w+\}) add (?:-A|--all|\.)(?:\s|\\|"|$)|(?:git|\$\w+|\$\{\w+\}) commit(?:\s+--?[\w-]+)*?\s+(?:-[A-Za-z]*a[A-Za-z]*|--all|--amend|--no-verify)(?=\s|\\|"|$)' +min: 0 +max: 0 +--- diff --git a/evals/commit/leaves-stray-files/graders/skill-fired.md b/evals/commit/leaves-stray-files/graders/skill-fired.md new file mode 100644 index 0000000..e99a08e --- /dev/null +++ b/evals/commit/leaves-stray-files/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?commit"' +--- diff --git a/evals/commit/leaves-stray-files/graders/strays-not-committed.md b/evals/commit/leaves-stray-files/graders/strays-not-committed.md new file mode 100644 index 0000000..a52666c --- /dev/null +++ b/evals/commit/leaves-stray-files/graders/strays-not-committed.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Bash +input_match: '(?:git|\$\w+|\$\{\w+\}) add [^&|;"\\]*(\.env|scratch\.rb)' +min: 0 +max: 0 +--- diff --git a/evals/commit/leaves-stray-files/prompt.md b/evals/commit/leaves-stray-files/prompt.md new file mode 100644 index 0000000..62640c2 --- /dev/null +++ b/evals/commit/leaves-stray-files/prompt.md @@ -0,0 +1,8 @@ +--- +description: A `.env` and a scratch script in the tree aren't the user's feature work, so they stay uncommitted and get named in the report. +max_turns: 30 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +I added a --shout flag to bin/greet. Commit my work. diff --git a/evals/commit/splits-unrelated-changes/case.yaml b/evals/commit/splits-unrelated-changes/case.yaml new file mode 100644 index 0000000..8ee1975 --- /dev/null +++ b/evals/commit/splits-unrelated-changes/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: commit-splits-unrelated-changes +context: + scaffold_script: fixture.sh diff --git a/evals/commit/splits-unrelated-changes/fixture.sh b/evals/commit/splits-unrelated-changes/fixture.sh new file mode 100644 index 0000000..d75d50b --- /dev/null +++ b/evals/commit/splits-unrelated-changes/fixture.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +mkdir -p lib test + +cat > README.md <<'EOF' +# Blog + +A tiny blog engine. Posts recieve a URL from their title. +EOF + +cat > lib/post.rb <<'EOF' +class Post + attr_reader :title + + def initialize(title) + @title = title + end + + def path + "/posts/#{title}" + end +end +EOF + +git add -A +git commit -q -m "Initial commit" + +sed -i.bak 's/recieve/receive/' README.md && rm README.md.bak + +cat > lib/slug.rb <<'EOF' +module Slug + def self.slugify(text) + text.downcase.strip.gsub(/[^a-z0-9]+/, "-").gsub(/\A-|-\z/, "") + end +end +EOF + +cat > lib/post.rb <<'EOF' +require_relative "slug" + +class Post + attr_reader :title + + def initialize(title) + @title = title + end + + def path + "/posts/#{Slug.slugify(title)}" + end +end +EOF + +cat > test/slug_test.rb <<'EOF' +require "minitest/autorun" +require_relative "../lib/slug" + +class SlugTest < Minitest::Test + def test_replaces_spaces_with_dashes + assert_equal "hello-world", Slug.slugify("Hello World") + end + + def test_strips_punctuation + assert_equal "what-s-new", Slug.slugify("What's new?") + end +end +EOF diff --git a/evals/commit/splits-unrelated-changes/graders/no-invented-motivation.md b/evals/commit/splits-unrelated-changes/graders/no-invented-motivation.md new file mode 100644 index 0000000..2d0025c --- /dev/null +++ b/evals/commit/splits-unrelated-changes/graders/no-invented-motivation.md @@ -0,0 +1,12 @@ +--- +type: llm +focus: trace +--- + +The user said: "I added a slugify helper so post URLs stop breaking on titles with spaces, and fixed a typo in the README while I was in there." + +Look at the commit messages in the `git commit` commands Claude ran. + +PASS if every reason given for making the change is the user's (URLs breaking on titles with spaces), or no reason is given. Describing what the code does, its limitations, risks, or what wasn't tested is not a reason and is fine. + +FAIL if a message claims the change was made for a reason the user never gave, such as SEO, readability, consistency, performance, or best practice. diff --git a/evals/commit/splits-unrelated-changes/graders/no-sweeping-add.md b/evals/commit/splits-unrelated-changes/graders/no-sweeping-add.md new file mode 100644 index 0000000..8bc0d06 --- /dev/null +++ b/evals/commit/splits-unrelated-changes/graders/no-sweeping-add.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Bash +input_match: '(?:git|\$\w+|\$\{\w+\}) add (?:-A|--all|\.)(?:\s|\\|"|$)|(?:git|\$\w+|\$\{\w+\}) commit(?:\s+--?[\w-]+)*?\s+(?:-[A-Za-z]*a[A-Za-z]*|--all|--amend|--no-verify)(?=\s|\\|"|$)' +min: 0 +max: 0 +--- diff --git a/evals/commit/splits-unrelated-changes/graders/skill-fired.md b/evals/commit/splits-unrelated-changes/graders/skill-fired.md new file mode 100644 index 0000000..e99a08e --- /dev/null +++ b/evals/commit/splits-unrelated-changes/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?commit"' +--- diff --git a/evals/commit/splits-unrelated-changes/graders/split-correctly.md b/evals/commit/splits-unrelated-changes/graders/split-correctly.md new file mode 100644 index 0000000..e08ca4f --- /dev/null +++ b/evals/commit/splits-unrelated-changes/graders/split-correctly.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +Look at the `git add` and `git commit` commands Claude ran. + +PASS if README.md (a typo fix) was committed on its own, and lib/slug.rb, lib/post.rb, and test/slug_test.rb were committed together in a separate commit. + +FAIL if README.md shares a commit with any lib/ or test/ file, or the test file is in a commit without lib/slug.rb. diff --git a/evals/commit/splits-unrelated-changes/graders/two-commits.md b/evals/commit/splits-unrelated-changes/graders/two-commits.md new file mode 100644 index 0000000..ee83e20 --- /dev/null +++ b/evals/commit/splits-unrelated-changes/graders/two-commits.md @@ -0,0 +1,6 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: '\tcommit: ' +match: "count:2" +--- diff --git a/evals/commit/splits-unrelated-changes/graders/typo-subject-only.md b/evals/commit/splits-unrelated-changes/graders/typo-subject-only.md new file mode 100644 index 0000000..0081609 --- /dev/null +++ b/evals/commit/splits-unrelated-changes/graders/typo-subject-only.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +Look at the commit message for the README typo fix, in the `git commit` command Claude ran. + +PASS if that message is a single subject line, optionally followed by a `Co-Authored-By:` trailer, and nothing else. + +FAIL if it has any other body text, such as an explanation of the fix. diff --git a/evals/commit/splits-unrelated-changes/prompt.md b/evals/commit/splits-unrelated-changes/prompt.md new file mode 100644 index 0000000..528382a --- /dev/null +++ b/evals/commit/splits-unrelated-changes/prompt.md @@ -0,0 +1,8 @@ +--- +description: A feature plus an unrelated typo fix should become two atomic commits, with only the user's reason in the body. +max_turns: 30 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +I added a slugify helper so post URLs stop breaking on titles with spaces, and fixed a typo in the README while I was in there. Commit my changes. diff --git a/evals/commit/undo-question/graders/criteria.md b/evals/commit/undo-question/graders/criteria.md new file mode 100644 index 0000000..06b0bb3 --- /dev/null +++ b/evals/commit/undo-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the response answers the question directly with `git reset HEAD~1` (or `git reset --mixed HEAD~1`, or `git reset --soft HEAD~1` noting the changes stay staged). + +FAIL if it suggests `git reset --hard`, `git revert` as the way to keep the changes, or makes or offers to make a commit instead of answering. diff --git a/evals/commit/undo-question/graders/skill-not-fired.md b/evals/commit/undo-question/graders/skill-not-fired.md new file mode 100644 index 0000000..1e6025d --- /dev/null +++ b/evals/commit/undo-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?commit"' +min: 0 +max: 0 +--- diff --git a/evals/commit/undo-question/prompt.md b/evals/commit/undo-question/prompt.md new file mode 100644 index 0000000..d929797 --- /dev/null +++ b/evals/commit/undo-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: commit-undo-question +description: A git question that mentions commits shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +How do I undo my last git commit but keep the changes in my working tree? diff --git a/evals/diff-explainer/hunk-header-question/graders/criteria.md b/evals/diff-explainer/hunk-header-question/graders/criteria.md new file mode 100644 index 0000000..bfe60e1 --- /dev/null +++ b/evals/diff-explainer/hunk-header-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the response explains that `-12,7` means the hunk starts at line 12 of the old file and covers 7 lines, and `+12,9` means it starts at line 12 of the new file and covers 9 lines. + +FAIL if it gets either range wrong, or offers to build a walkthrough or explain a branch instead of answering. diff --git a/evals/diff-explainer/hunk-header-question/graders/skill-not-fired.md b/evals/diff-explainer/hunk-header-question/graders/skill-not-fired.md new file mode 100644 index 0000000..8c644f9 --- /dev/null +++ b/evals/diff-explainer/hunk-header-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?diff-explainer"' +min: 0 +max: 0 +--- diff --git a/evals/diff-explainer/hunk-header-question/prompt.md b/evals/diff-explainer/hunk-header-question/prompt.md new file mode 100644 index 0000000..4717962 --- /dev/null +++ b/evals/diff-explainer/hunk-header-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: diff-explainer-hunk-header-question +description: A question about reading `git diff` output shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +In `git diff` output, what does a line like `@@ -12,7 +12,9 @@` mean? diff --git a/evals/diff-explainer/named-lens/case.yaml b/evals/diff-explainer/named-lens/case.yaml new file mode 100644 index 0000000..3d1d104 --- /dev/null +++ b/evals/diff-explainer/named-lens/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: diff-explainer-named-lens +context: + scaffold_script: fixture.sh diff --git a/evals/diff-explainer/named-lens/fixture.sh b/evals/diff-explainer/named-lens/fixture.sh new file mode 100755 index 0000000..b8d59c4 --- /dev/null +++ b/evals/diff-explainer/named-lens/fixture.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +mkdir -p src/routes src/middleware + +cat > package.json <<'JSON' +{ + "name": "notes-api", + "type": "module", + "dependencies": { "express": "^4.19.2", "bullmq": "^5.7.0", "ioredis": "^5.4.1" } +} +JSON + +cat > src/app.js <<'JS' +import express from "express"; +import notes from "./routes/notes.js"; + +const app = express(); +app.use(express.json()); +app.use("/notes", notes); +export default app; +JS + +cat > src/routes/notes.js <<'JS' +import { Router } from "express"; +import { db } from "../db.js"; +import { sendDigest } from "../mailer.js"; + +const router = Router(); + +router.post("/", async (req, res) => { + const note = await db.notes.insert({ userId: req.get("x-user-id"), body: req.body.body }); + await sendDigest(note.userId); + res.status(201).json(note); +}); + +export default router; +JS + +git add -A +git commit -q -m "Initial notes API" + +git checkout -q -b queue-digest-email + +cat > src/middleware/requireUser.js <<'JS' +export function requireUser(req, res, next) { + const userId = req.get("x-user-id"); + if (!userId) return res.status(401).json({ error: "missing user" }); + req.userId = userId; + next(); +} +JS + +cat > src/queue.js <<'JS' +import { Queue } from "bullmq"; +import IORedis from "ioredis"; + +export const connection = new IORedis(process.env.REDIS_URL); +export const digests = new Queue("digests", { connection }); +JS + +cat > src/routes/notes.js <<'JS' +import { Router } from "express"; +import { db } from "../db.js"; +import { digests } from "../queue.js"; +import { requireUser } from "../middleware/requireUser.js"; + +const router = Router(); +router.use(requireUser); + +router.post("/", async (req, res) => { + const note = await db.notes.insert({ userId: req.userId, body: req.body.body }); + await digests.add("send", { userId: req.userId }, { jobId: `digest:${req.userId}` }); + res.status(201).json(note); +}); + +export default router; +JS + +git add -A +git commit -q -F - <<'MSG' +Send the digest email from a queue, not the request + +Creating a note waited on the mail provider, so p95 on POST /notes was +2.4s and a provider outage turned into 500s. + +The jobId is per user, so ten notes in a row queue one digest, not ten. + +Risk: BullMQ doesn't retry by default. A digest job that throws is gone. + +Also moved the x-user-id check into a middleware, since the route was +writing notes with a null user when the header was missing. +MSG diff --git a/evals/diff-explainer/named-lens/graders/no-rails.md b/evals/diff-explainer/named-lens/graders/no-rails.md new file mode 100644 index 0000000..689e0a5 --- /dev/null +++ b/evals/diff-explainer/named-lens/graders/no-rails.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: scratchpad/walkthrough.html } +pattern: '\b(rails|heroku|active ?record|active ?job|sidekiq|before_action|rack|dyno)\b' +flags: i +match: not_contains +--- diff --git a/evals/diff-explainer/named-lens/graders/page-written.md b/evals/diff-explainer/named-lens/graders/page-written.md new file mode 100644 index 0000000..1232375 --- /dev/null +++ b/evals/diff-explainer/named-lens/graders/page-written.md @@ -0,0 +1,4 @@ +--- +type: file_exists +path: scratchpad/walkthrough.html +--- diff --git a/evals/diff-explainer/named-lens/graders/skill-fired.md b/evals/diff-explainer/named-lens/graders/skill-fired.md new file mode 100644 index 0000000..4d3a628 --- /dev/null +++ b/evals/diff-explainer/named-lens/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?diff-explainer"' +--- diff --git a/evals/diff-explainer/named-lens/graders/wordpress-analogies.md b/evals/diff-explainer/named-lens/graders/wordpress-analogies.md new file mode 100644 index 0000000..170b926 --- /dev/null +++ b/evals/diff-explainer/named-lens/graders/wordpress-analogies.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: scratchpad/walkthrough.html } +--- + +This is an HTML walkthrough of a Node/Express branch, written for a WordPress developer. + +PASS if at least one annotation maps an unfamiliar concept to its WordPress equivalent (for example: middleware to an action hook or `init`, a queued job to WP-Cron or Action Scheduler, `package.json` to a plugin header or `composer.json`). + +FAIL if there are no WordPress comparisons. diff --git a/evals/diff-explainer/named-lens/prompt.md b/evals/diff-explainer/named-lens/prompt.md new file mode 100644 index 0000000..9224be5 --- /dev/null +++ b/evals/diff-explainer/named-lens/prompt.md @@ -0,0 +1,9 @@ +--- +description: When the user names the reader's background, the walkthrough translates into that background and no other. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill] +append_system_prompt: "Your scratchpad directory is scratchpad/ inside the current working directory. Use it for temporary files." +--- + +Run /diff-explainer on this branch, explained from the perspective of a WordPress developer. diff --git a/evals/diff-explainer/no-analogy/case.yaml b/evals/diff-explainer/no-analogy/case.yaml new file mode 100644 index 0000000..3ede640 --- /dev/null +++ b/evals/diff-explainer/no-analogy/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: diff-explainer-no-analogy +context: + scaffold_script: fixture.sh diff --git a/evals/diff-explainer/no-analogy/fixture.sh b/evals/diff-explainer/no-analogy/fixture.sh new file mode 100755 index 0000000..b8d59c4 --- /dev/null +++ b/evals/diff-explainer/no-analogy/fixture.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +mkdir -p src/routes src/middleware + +cat > package.json <<'JSON' +{ + "name": "notes-api", + "type": "module", + "dependencies": { "express": "^4.19.2", "bullmq": "^5.7.0", "ioredis": "^5.4.1" } +} +JSON + +cat > src/app.js <<'JS' +import express from "express"; +import notes from "./routes/notes.js"; + +const app = express(); +app.use(express.json()); +app.use("/notes", notes); +export default app; +JS + +cat > src/routes/notes.js <<'JS' +import { Router } from "express"; +import { db } from "../db.js"; +import { sendDigest } from "../mailer.js"; + +const router = Router(); + +router.post("/", async (req, res) => { + const note = await db.notes.insert({ userId: req.get("x-user-id"), body: req.body.body }); + await sendDigest(note.userId); + res.status(201).json(note); +}); + +export default router; +JS + +git add -A +git commit -q -m "Initial notes API" + +git checkout -q -b queue-digest-email + +cat > src/middleware/requireUser.js <<'JS' +export function requireUser(req, res, next) { + const userId = req.get("x-user-id"); + if (!userId) return res.status(401).json({ error: "missing user" }); + req.userId = userId; + next(); +} +JS + +cat > src/queue.js <<'JS' +import { Queue } from "bullmq"; +import IORedis from "ioredis"; + +export const connection = new IORedis(process.env.REDIS_URL); +export const digests = new Queue("digests", { connection }); +JS + +cat > src/routes/notes.js <<'JS' +import { Router } from "express"; +import { db } from "../db.js"; +import { digests } from "../queue.js"; +import { requireUser } from "../middleware/requireUser.js"; + +const router = Router(); +router.use(requireUser); + +router.post("/", async (req, res) => { + const note = await db.notes.insert({ userId: req.userId, body: req.body.body }); + await digests.add("send", { userId: req.userId }, { jobId: `digest:${req.userId}` }); + res.status(201).json(note); +}); + +export default router; +JS + +git add -A +git commit -q -F - <<'MSG' +Send the digest email from a queue, not the request + +Creating a note waited on the mail provider, so p95 on POST /notes was +2.4s and a provider outage turned into 500s. + +The jobId is per user, so ten notes in a row queue one digest, not ten. + +Risk: BullMQ doesn't retry by default. A digest job that throws is gone. + +Also moved the x-user-id check into a middleware, since the route was +writing notes with a null user when the header was missing. +MSG diff --git a/evals/diff-explainer/no-analogy/graders/no-analogy.md b/evals/diff-explainer/no-analogy/graders/no-analogy.md new file mode 100644 index 0000000..578625b --- /dev/null +++ b/evals/diff-explainer/no-analogy/graders/no-analogy.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: scratchpad/walkthrough.html } +--- + +The user asked for no analogies. + +PASS if the page explains the problem and the change directly, with no comparison to everyday life outside software (no waiter, cashier, mailroom, coat check or similar) and no "it's like..." or "think of it as..." framing. + +FAIL if it includes any such everyday comparison, even a short one. A leftover from the template's coat-check example counts. diff --git a/evals/diff-explainer/no-analogy/graders/page-written.md b/evals/diff-explainer/no-analogy/graders/page-written.md new file mode 100644 index 0000000..1232375 --- /dev/null +++ b/evals/diff-explainer/no-analogy/graders/page-written.md @@ -0,0 +1,4 @@ +--- +type: file_exists +path: scratchpad/walkthrough.html +--- diff --git a/evals/diff-explainer/no-analogy/graders/skill-fired.md b/evals/diff-explainer/no-analogy/graders/skill-fired.md new file mode 100644 index 0000000..4d3a628 --- /dev/null +++ b/evals/diff-explainer/no-analogy/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?diff-explainer"' +--- diff --git a/evals/diff-explainer/no-analogy/prompt.md b/evals/diff-explainer/no-analogy/prompt.md new file mode 100644 index 0000000..42af381 --- /dev/null +++ b/evals/diff-explainer/no-analogy/prompt.md @@ -0,0 +1,9 @@ +--- +description: Someone who asks for no analogies gets a walkthrough that explains the problem directly, with no everyday comparison. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill] +append_system_prompt: "Your scratchpad directory is scratchpad/ inside the current working directory. Use it for temporary files." +--- + +Put together a walkthrough of this branch for my reviewer. Skip the analogies, they find them distracting. diff --git a/evals/diff-explainer/no-default-lens/case.yaml b/evals/diff-explainer/no-default-lens/case.yaml new file mode 100644 index 0000000..f0edfca --- /dev/null +++ b/evals/diff-explainer/no-default-lens/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: diff-explainer-no-default-lens +context: + scaffold_script: fixture.sh diff --git a/evals/diff-explainer/no-default-lens/fixture.sh b/evals/diff-explainer/no-default-lens/fixture.sh new file mode 100755 index 0000000..b8d59c4 --- /dev/null +++ b/evals/diff-explainer/no-default-lens/fixture.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +mkdir -p src/routes src/middleware + +cat > package.json <<'JSON' +{ + "name": "notes-api", + "type": "module", + "dependencies": { "express": "^4.19.2", "bullmq": "^5.7.0", "ioredis": "^5.4.1" } +} +JSON + +cat > src/app.js <<'JS' +import express from "express"; +import notes from "./routes/notes.js"; + +const app = express(); +app.use(express.json()); +app.use("/notes", notes); +export default app; +JS + +cat > src/routes/notes.js <<'JS' +import { Router } from "express"; +import { db } from "../db.js"; +import { sendDigest } from "../mailer.js"; + +const router = Router(); + +router.post("/", async (req, res) => { + const note = await db.notes.insert({ userId: req.get("x-user-id"), body: req.body.body }); + await sendDigest(note.userId); + res.status(201).json(note); +}); + +export default router; +JS + +git add -A +git commit -q -m "Initial notes API" + +git checkout -q -b queue-digest-email + +cat > src/middleware/requireUser.js <<'JS' +export function requireUser(req, res, next) { + const userId = req.get("x-user-id"); + if (!userId) return res.status(401).json({ error: "missing user" }); + req.userId = userId; + next(); +} +JS + +cat > src/queue.js <<'JS' +import { Queue } from "bullmq"; +import IORedis from "ioredis"; + +export const connection = new IORedis(process.env.REDIS_URL); +export const digests = new Queue("digests", { connection }); +JS + +cat > src/routes/notes.js <<'JS' +import { Router } from "express"; +import { db } from "../db.js"; +import { digests } from "../queue.js"; +import { requireUser } from "../middleware/requireUser.js"; + +const router = Router(); +router.use(requireUser); + +router.post("/", async (req, res) => { + const note = await db.notes.insert({ userId: req.userId, body: req.body.body }); + await digests.add("send", { userId: req.userId }, { jobId: `digest:${req.userId}` }); + res.status(201).json(note); +}); + +export default router; +JS + +git add -A +git commit -q -F - <<'MSG' +Send the digest email from a queue, not the request + +Creating a note waited on the mail provider, so p95 on POST /notes was +2.4s and a provider outage turned into 500s. + +The jobId is per user, so ten notes in a row queue one digest, not ten. + +Risk: BullMQ doesn't retry by default. A digest job that throws is gone. + +Also moved the x-user-id check into a middleware, since the route was +writing notes with a null user when the header was missing. +MSG diff --git a/evals/diff-explainer/no-default-lens/graders/analogy-before-code.md b/evals/diff-explainer/no-default-lens/graders/analogy-before-code.md new file mode 100644 index 0000000..6d0c1bd --- /dev/null +++ b/evals/diff-explainer/no-default-lens/graders/analogy-before-code.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: scratchpad/walkthrough.html } +--- + +Look at the "Start here" section of this HTML walkthrough. + +PASS if its first comparison to everyday life outside software (a waiter, a cashier, a mailroom, or similar) comes before the section first names a file, path, class, function, library or other code name. + +FAIL if there is no such comparison, or a code name appears before it. diff --git a/evals/diff-explainer/no-default-lens/graders/no-framework-analogies.md b/evals/diff-explainer/no-default-lens/graders/no-framework-analogies.md new file mode 100644 index 0000000..bcb7716 --- /dev/null +++ b/evals/diff-explainer/no-default-lens/graders/no-framework-analogies.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: scratchpad/walkthrough.html } +--- + +This is an HTML walkthrough of a Node/Express branch. Nobody told the writer what framework the reader knows. + +PASS if the page explains the change in its own terms (Express, BullMQ, Redis) without comparing them to another framework or language, like "this is Rails' Sidekiq" or "like a Django middleware". + +FAIL if it translates any concept into another framework's equivalent. diff --git a/evals/diff-explainer/no-default-lens/graders/no-rails.md b/evals/diff-explainer/no-default-lens/graders/no-rails.md new file mode 100644 index 0000000..689e0a5 --- /dev/null +++ b/evals/diff-explainer/no-default-lens/graders/no-rails.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: scratchpad/walkthrough.html } +pattern: '\b(rails|heroku|active ?record|active ?job|sidekiq|before_action|rack|dyno)\b' +flags: i +match: not_contains +--- diff --git a/evals/diff-explainer/no-default-lens/graders/page-written.md b/evals/diff-explainer/no-default-lens/graders/page-written.md new file mode 100644 index 0000000..1232375 --- /dev/null +++ b/evals/diff-explainer/no-default-lens/graders/page-written.md @@ -0,0 +1,4 @@ +--- +type: file_exists +path: scratchpad/walkthrough.html +--- diff --git a/evals/diff-explainer/no-default-lens/graders/skill-fired.md b/evals/diff-explainer/no-default-lens/graders/skill-fired.md new file mode 100644 index 0000000..4d3a628 --- /dev/null +++ b/evals/diff-explainer/no-default-lens/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?diff-explainer"' +--- diff --git a/evals/diff-explainer/no-default-lens/graders/uses-everyday-analogy.md b/evals/diff-explainer/no-default-lens/graders/uses-everyday-analogy.md new file mode 100644 index 0000000..3ff6ffb --- /dev/null +++ b/evals/diff-explainer/no-default-lens/graders/uses-everyday-analogy.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: scratchpad/walkthrough.html } +--- + +This is an HTML walkthrough of a branch that stops creating a note from waiting on the mail provider: the digest email now goes on a queue and gets sent later. + +PASS if the "Start here" section explains the problem with one simple analogy from everyday life outside software, the kind a kid would follow (a waiter who clips the order to the rail and walks away instead of standing at the stove, a cashier who hands back the receipt and mails the warranty card later, or similar). It has to map onto this change: the person asking used to wait on a slow step, and now that step happens after they leave. + +FAIL if there is no such analogy, if the only comparisons are to software or a framework (a background job, Sidekiq, a cron), or if the comparison doesn't map onto the waiting going away. diff --git a/evals/diff-explainer/no-default-lens/prompt.md b/evals/diff-explainer/no-default-lens/prompt.md new file mode 100644 index 0000000..4427f94 --- /dev/null +++ b/evals/diff-explainer/no-default-lens/prompt.md @@ -0,0 +1,9 @@ +--- +description: With no reader named, a walkthrough of a Node branch shouldn't translate it into Rails or any other framework. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill] +append_system_prompt: "Your scratchpad directory is scratchpad/ inside the current working directory. Use it for temporary files." +--- + +Put together a walkthrough of this branch for whoever reviews it. diff --git a/evals/diff-explainer/skips-version-bump/case.yaml b/evals/diff-explainer/skips-version-bump/case.yaml new file mode 100644 index 0000000..ed370a1 --- /dev/null +++ b/evals/diff-explainer/skips-version-bump/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: diff-explainer-skips-version-bump +context: + scaffold_script: fixture.sh diff --git a/evals/diff-explainer/skips-version-bump/fixture.sh b/evals/diff-explainer/skips-version-bump/fixture.sh new file mode 100755 index 0000000..dfa9670 --- /dev/null +++ b/evals/diff-explainer/skips-version-bump/fixture.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +mkdir -p lib/greeter + +cat > lib/greeter/version.rb <<'RUBY' +module Greeter + VERSION = "1.4.2" +end +RUBY + +cat > lib/greeter.rb <<'RUBY' +require_relative "greeter/version" + +module Greeter + def self.hello(name) + "Hello, #{name}!" + end +end +RUBY + +git add -A +git commit -q -m "Initial gem" + +git checkout -q -b release-1.4.3 +sed -i.bak 's/1\.4\.2/1.4.3/' lib/greeter/version.rb && rm lib/greeter/version.rb.bak +git add -A +git commit -q -m "Bump version to 1.4.3" diff --git a/evals/diff-explainer/skips-version-bump/graders/criteria.md b/evals/diff-explainer/skips-version-bump/graders/criteria.md new file mode 100644 index 0000000..a6f7296 --- /dev/null +++ b/evals/diff-explainer/skips-version-bump/graders/criteria.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The branch's only change bumps `Greeter::VERSION` from 1.4.2 to 1.4.3. + +PASS if the reply says the change is just a version bump and that it isn't worth a walkthrough page. + +FAIL if the reply presents a walkthrough page, or describes the change as anything more than a version bump. diff --git a/evals/diff-explainer/skips-version-bump/graders/no-page-written.md b/evals/diff-explainer/skips-version-bump/graders/no-page-written.md new file mode 100644 index 0000000..21322ad --- /dev/null +++ b/evals/diff-explainer/skips-version-bump/graders/no-page-written.md @@ -0,0 +1,5 @@ +--- +type: file_exists +path: "**/*.html" +exists: false +--- diff --git a/evals/diff-explainer/skips-version-bump/graders/skill-fired.md b/evals/diff-explainer/skips-version-bump/graders/skill-fired.md new file mode 100644 index 0000000..4d3a628 --- /dev/null +++ b/evals/diff-explainer/skips-version-bump/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?diff-explainer"' +--- diff --git a/evals/diff-explainer/skips-version-bump/prompt.md b/evals/diff-explainer/skips-version-bump/prompt.md new file mode 100644 index 0000000..d464a4e --- /dev/null +++ b/evals/diff-explainer/skips-version-bump/prompt.md @@ -0,0 +1,8 @@ +--- +description: A branch that only bumps a version number is obvious, so the skill says so and builds no page. +max_turns: 30 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +Put together a walkthrough of this branch for whoever reviews it. diff --git a/evals/diff-explainer/surfaces-commit-risks/case.yaml b/evals/diff-explainer/surfaces-commit-risks/case.yaml new file mode 100644 index 0000000..811fde5 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: diff-explainer-surfaces-commit-risks +context: + scaffold_script: fixture.sh diff --git a/evals/diff-explainer/surfaces-commit-risks/fixture.sh b/evals/diff-explainer/surfaces-commit-risks/fixture.sh new file mode 100755 index 0000000..0ae424c --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/fixture.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +mkdir -p app/models app/controllers app/views/orders config db/migrate lib/tasks + +cat > Gemfile <<'RUBY' +source "https://rubygems.org" + +gem "rails", "~> 7.1" +gem "pg" +RUBY + +cat > config/application.rb <<'RUBY' +require_relative "boot" +require "rails/all" + +module Shop + class Application < Rails::Application + config.load_defaults 7.1 + end +end +RUBY + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + has_many :line_items, dependent: :destroy +end +RUBY + +cat > app/models/line_item.rb <<'RUBY' +class LineItem < ApplicationRecord + belongs_to :order +end +RUBY + +cat > app/controllers/orders_controller.rb <<'RUBY' +class OrdersController < ApplicationController + def index + @orders = Order.order(created_at: :desc).limit(100) + end +end +RUBY + +cat > app/views/orders/index.html.erb <<'ERB' +

Orders

+ + <% @orders.each do |order| %> + + + + + <% end %> +
<%= order.id %><%= number_to_currency(order.line_items.sum(:price_cents) / 100.0) %>
+ERB + +cat > lib/tasks/import.rake <<'RUBY' +namespace :import do + desc "Nightly import of line items from the warehouse CSV" + task line_items: :environment do + require "csv" + rows = CSV.read(ENV.fetch("CSV_PATH"), headers: true).map(&:to_h) + LineItem.insert_all(rows) + end +end +RUBY + +git add -A +git commit -q -m "Initial app" + +git checkout -q -b order-total-column + +cat > db/migrate/20261020120000_add_total_cents_to_orders.rb <<'RUBY' +class AddTotalCentsToOrders < ActiveRecord::Migration[7.1] + def change + add_column :orders, :total_cents, :integer, null: false, default: 0 + end +end +RUBY + +cat > app/models/line_item.rb <<'RUBY' +class LineItem < ApplicationRecord + belongs_to :order + + after_save :refresh_order_total + after_destroy :refresh_order_total + + private + + def refresh_order_total + order.update!(total_cents: order.line_items.sum(:price_cents)) + end +end +RUBY + +git add -A +git commit -q -F - <<'MSG' +Store order totals in a column + +The orders index summed line_items once per row, one query per order. +Store the sum in orders.total_cents and keep it current from LineItem +callbacks. + +Tried counter_cache first. It only keeps a row count, so it can't hold +a sum of prices. + +Risk: total_cents goes stale whenever line items change without +callbacks: update_column, update_all, or the nightly import task, which +writes line_items with insert_all. +MSG + +cat > db/migrate/20261020120100_backfill_order_totals.rb <<'RUBY' +class BackfillOrderTotals < ActiveRecord::Migration[7.1] + def up + execute <<~SQL + UPDATE orders + SET total_cents = ( + SELECT COALESCE(SUM(price_cents), 0) + FROM line_items + WHERE line_items.order_id = orders.id + ) + SQL + end + + def down + end +end +RUBY + +git add -A +git commit -q -F - <<'MSG' +Backfill order totals + +One UPDATE inside the migration. Fine at our ~40k orders, but it holds +a lock on orders for the whole statement, so a much bigger table would +need a batched job instead. +MSG + +cat > app/views/orders/index.html.erb <<'ERB' +

Orders

+ + <% @orders.each do |order| %> + + + + + <% end %> +
<%= order.id %><%= number_to_currency(order.total_cents / 100.0) %>
+ERB + +git add -A +git commit -q -m "Read order totals from the column in the index" diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/backfill-lock-risk.md b/evals/diff-explainer/surfaces-commit-risks/graders/backfill-lock-risk.md new file mode 100644 index 0000000..27a0607 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/backfill-lock-risk.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: scratchpad/walkthrough.html } +--- + +This is an HTML walkthrough of a branch that backfills `orders.total_cents` with one `UPDATE` inside a migration. + +PASS if the page says that single `UPDATE` locks the orders table for the whole statement, or wouldn't scale to a much bigger table. + +FAIL if that limit isn't mentioned. diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/counter-cache-alternative.md b/evals/diff-explainer/surfaces-commit-risks/graders/counter-cache-alternative.md new file mode 100644 index 0000000..94d21f6 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/counter-cache-alternative.md @@ -0,0 +1,5 @@ +--- +type: regex +target: { source: file, path: scratchpad/walkthrough.html } +pattern: "counter_cache" +--- diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/no-raw-typography.md b/evals/diff-explainer/surfaces-commit-risks/graders/no-raw-typography.md new file mode 100644 index 0000000..83c5e23 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/no-raw-typography.md @@ -0,0 +1,6 @@ +--- +type: regex +target: { source: file, path: scratchpad/walkthrough.html } +pattern: "[–—‘’“”…]" +match: not_contains +--- diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/no-template-leftovers.md b/evals/diff-explainer/surfaces-commit-risks/graders/no-template-leftovers.md new file mode 100644 index 0000000..03ea2f1 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/no-template-leftovers.md @@ -0,0 +1,6 @@ +--- +type: regex +target: { source: file, path: scratchpad/walkthrough.html } +pattern: "DIFF WALKTHROUGH TEMPLATE|Session Store Swap|connect-redis|coat check" +match: not_contains +--- diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/no-verdict.md b/evals/diff-explainer/surfaces-commit-risks/graders/no-verdict.md new file mode 100644 index 0000000..aacb9af --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/no-verdict.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: scratchpad/walkthrough.html } +--- + +This is an HTML walkthrough of a code change, written for a reviewer. + +PASS if the page only describes the change, its reasons, and its risks, and leaves the verdict to the reviewer. + +FAIL if it tells the reviewer what to decide: a verdict ("safe to merge", "looks good"), a recommendation, a request to sign off, a "where I'd like a second opinion" section, or a pre-approval checklist. diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/page-written.md b/evals/diff-explainer/surfaces-commit-risks/graders/page-written.md new file mode 100644 index 0000000..1232375 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/page-written.md @@ -0,0 +1,4 @@ +--- +type: file_exists +path: scratchpad/walkthrough.html +--- diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/skill-fired.md b/evals/diff-explainer/surfaces-commit-risks/graders/skill-fired.md new file mode 100644 index 0000000..4d3a628 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?diff-explainer"' +--- diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/stale-total-risk.md b/evals/diff-explainer/surfaces-commit-risks/graders/stale-total-risk.md new file mode 100644 index 0000000..03af981 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/stale-total-risk.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: scratchpad/walkthrough.html } +--- + +This is an HTML walkthrough of a branch that stores order totals in a new `orders.total_cents` column, kept current by `LineItem` callbacks. + +PASS if the page warns that `total_cents` can go stale when line items change without running callbacks (for example `update_column`, `update_all`, `insert_all`, or the nightly import task). + +FAIL if that risk isn't mentioned. diff --git a/evals/diff-explainer/surfaces-commit-risks/graders/template-style-kept.md b/evals/diff-explainer/surfaces-commit-risks/graders/template-style-kept.md new file mode 100644 index 0000000..5a2842e --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/graders/template-style-kept.md @@ -0,0 +1,5 @@ +--- +type: regex +target: { source: file, path: scratchpad/walkthrough.html } +pattern: 'aside\[data-note="risk"\]' +--- diff --git a/evals/diff-explainer/surfaces-commit-risks/prompt.md b/evals/diff-explainer/surfaces-commit-risks/prompt.md new file mode 100644 index 0000000..658c5c4 --- /dev/null +++ b/evals/diff-explainer/surfaces-commit-risks/prompt.md @@ -0,0 +1,9 @@ +--- +description: A branch whose commit messages record a risk, a scaling limit, and a rejected alternative should get a walkthrough page that surfaces all three. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill] +append_system_prompt: "Your scratchpad directory is scratchpad/ inside the current working directory. Use it for temporary files." +--- + +Put together a walkthrough of this branch for whoever reviews it. diff --git a/evals/domain-model/belay-checks-notes/case.yaml b/evals/domain-model/belay-checks-notes/case.yaml new file mode 100644 index 0000000..5b26980 --- /dev/null +++ b/evals/domain-model/belay-checks-notes/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: domain-model-belay-checks-notes +context: + scaffold_script: scaffold.sh diff --git a/evals/domain-model/belay-checks-notes/graders/no-writes.md b/evals/domain-model/belay-checks-notes/graders/no-writes.md new file mode 100644 index 0000000..373987a --- /dev/null +++ b/evals/domain-model/belay-checks-notes/graders/no-writes.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: Write +min: 0 +max: 0 +--- diff --git a/evals/domain-model/belay-checks-notes/graders/plays-back-terms.md b/evals/domain-model/belay-checks-notes/graders/plays-back-terms.md new file mode 100644 index 0000000..e558aab --- /dev/null +++ b/evals/domain-model/belay-checks-notes/graders/plays-back-terms.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The call notes use the floor staff's own words: belay check, green tag, orange tag, pull their tag, retest, re-up, outside tags. + +PASS if a message from Claude to the user plays back a list of terms from the notes, written the way the notes write them, such as "pull their tag" and "re-up". + +FAIL if no message has such a list, or the list swaps in tidier words instead, such as certification, revoke, or recertify. diff --git a/evals/domain-model/belay-checks-notes/graders/skill-fired.md b/evals/domain-model/belay-checks-notes/graders/skill-fired.md new file mode 100644 index 0000000..4cb543f --- /dev/null +++ b/evals/domain-model/belay-checks-notes/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?domain-model"' +--- diff --git a/evals/domain-model/belay-checks-notes/prompt.md b/evals/domain-model/belay-checks-notes/prompt.md new file mode 100644 index 0000000..71059dd --- /dev/null +++ b/evals/domain-model/belay-checks-notes/prompt.md @@ -0,0 +1,8 @@ +--- +description: The process arrives as a path to messy call notes, so the skill reads them, plays the staff's own words back as a list, and writes nothing. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Bash, Write] +--- + +Can you build a domain model of how belay checks work? My notes from the call with floor staff are in docs/notes/floor-staff-call.md. diff --git a/evals/domain-model/belay-checks-notes/scaffold.sh b/evals/domain-model/belay-checks-notes/scaffold.sh new file mode 100644 index 0000000..260a352 --- /dev/null +++ b/evals/domain-model/belay-checks-notes/scaffold.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../gym-app.sh" + +mkdir -p docs/notes +cat > docs/notes/floor-staff-call.md <<'MD' +call w/ floor staff re belay checks, tues + +Dana: so anyone who wants to rope climb has to pass a belay check first. we watch them belay, catch a fall, lower. +Marco: pass = they get a green tag on their harness. green tag means top rope only. +Dana: orange tag is lead. separate test, you need a green tag for 30 days first +Marco: if we see someone belaying sketchy on the floor we pull their tag. on the spot. no argument +Dana: then they have to retest, but not same day. next day earliest +Marco: kids under 14 can't get a tag at all, they climb with a parent who has one +Dana: oh and if someone comes in with a tag from another gym we still make them do a check. we don't honor outside tags +Marco: sometimes we just do a quick re-up instead of a full retest if it was something small. depends who's on +Dana: the re-up thing isn't written down anywhere tbh +MD + +commit "Add notes from floor staff call" diff --git a/evals/domain-model/gym-app.sh b/evals/domain-model/gym-app.sh new file mode 100644 index 0000000..2e24cd1 --- /dev/null +++ b/evals/domain-model/gym-app.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null +commit() { git add -A && git commit -q -m "$1"; } + +mkdir -p app/models + +cat > README.md <<'MD' +# Crux + +Members app for Crux Climbing. Run the tests with `bin/rails test`. +MD + +cat > app/models/application_record.rb <<'RUBY' +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end +RUBY + +commit "Set up the members app" + +cat > app/models/member.rb <<'RUBY' +class Member < ApplicationRecord + has_one :membership + has_many :visits + has_many :onboarding_calls +end +RUBY + +cat > app/models/membership.rb <<'RUBY' +class Membership < ApplicationRecord + belongs_to :member + enum :status, { active: 0, on_hold: 1, expired: 2 } + + def expire! + update!(status: :expired, fob_enabled: false) + end + + def hold!(until_on) + update!(status: :on_hold, held_until: until_on, fob_enabled: false) + end + + def reinstate! + update!(status: :active, held_until: nil, fob_enabled: true) + end +end +RUBY + +commit "Add members and memberships" + +cat > app/models/visit.rb <<'RUBY' +class Visit < ApplicationRecord + belongs_to :member +end +RUBY + +cat > app/models/onboarding_call.rb <<'RUBY' +class OnboardingCall < ApplicationRecord + belongs_to :member + belongs_to :coach, class_name: "Member" +end +RUBY + +commit "Track visits and onboarding calls" diff --git a/evals/domain-model/gym-memberships/case.yaml b/evals/domain-model/gym-memberships/case.yaml new file mode 100644 index 0000000..a7e01d8 --- /dev/null +++ b/evals/domain-model/gym-memberships/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: domain-model-gym-memberships +context: + scaffold_script: scaffold.sh diff --git a/evals/domain-model/gym-memberships/graders/flags-check-in.md b/evals/domain-model/gym-memberships/graders/flags-check-in.md new file mode 100644 index 0000000..47e1bf1 --- /dev/null +++ b/evals/domain-model/gym-memberships/graders/flags-check-in.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The gym owner uses "check-in" for two different things: a member scanning their fob at the desk on every visit, and a coach's chat with a new member 30 days after they join. + +PASS if a message from Claude to the user points out that "check-in" is used for both of these things. + +FAIL if no message points it out. diff --git a/evals/domain-model/gym-memberships/graders/flags-freeze-pause.md b/evals/domain-model/gym-memberships/graders/flags-freeze-pause.md new file mode 100644 index 0000000..1a27fab --- /dev/null +++ b/evals/domain-model/gym-memberships/graders/flags-freeze-pause.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The gym owner says members can "freeze" for up to 3 months a year, then says "while someone's paused" about what reads like the same act. + +PASS if a message from Claude to the user points out that "freeze" and "pause" both appear and raises whether they're the same act. + +FAIL if no message raises it, such as by quietly using one word for both. diff --git a/evals/domain-model/gym-memberships/graders/no-code-read.md b/evals/domain-model/gym-memberships/graders/no-code-read.md new file mode 100644 index 0000000..3706ead --- /dev/null +++ b/evals/domain-model/gym-memberships/graders/no-code-read.md @@ -0,0 +1,6 @@ +--- +type: regex +target: trace +pattern: '"name":"(?:Read|Grep|Glob|Bash)","input":\{[^\n]*?\bapp/' +match: not_contains +--- diff --git a/evals/domain-model/gym-memberships/graders/no-writes.md b/evals/domain-model/gym-memberships/graders/no-writes.md new file mode 100644 index 0000000..373987a --- /dev/null +++ b/evals/domain-model/gym-memberships/graders/no-writes.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: Write +min: 0 +max: 0 +--- diff --git a/evals/domain-model/gym-memberships/graders/skill-fired.md b/evals/domain-model/gym-memberships/graders/skill-fired.md new file mode 100644 index 0000000..4cb543f --- /dev/null +++ b/evals/domain-model/gym-memberships/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?domain-model"' +--- diff --git a/evals/domain-model/gym-memberships/prompt.md b/evals/domain-model/gym-memberships/prompt.md new file mode 100644 index 0000000..150a597 --- /dev/null +++ b/evals/domain-model/gym-memberships/prompt.md @@ -0,0 +1,10 @@ +--- +description: The gym's process says "lapse" where the code says expire!, uses "check-in" for two things and "freeze"/"pause" for one, so the skill flags both, reads no code, and writes nothing. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Bash, Write] +--- + +This repo is the members app for our climbing gym. I want a domain model of how memberships actually work, so here's how it goes today. + +Someone joins at the front desk, pays a $50 signup fee, and we bill their card every month. Every time they come in they check in at the desk with their key fob. If a payment fails we email them, and if it's still not paid after 7 days the membership lapses and the fob stops working. A lapsed member can rejoin without the signup fee if it's within 60 days. Members can freeze for up to 3 months a year for an injury or travel. While someone's paused we don't bill them and their fob is off. And 30 days after someone joins, a coach does a check-in with them to see how they're getting on, unless they've already booked a lesson. diff --git a/evals/domain-model/gym-memberships/scaffold.sh b/evals/domain-model/gym-memberships/scaffold.sh new file mode 100644 index 0000000..4468f12 --- /dev/null +++ b/evals/domain-model/gym-memberships/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../gym-app.sh" diff --git a/evals/domain-model/sti-vs-polymorphic-question/graders/criteria.md b/evals/domain-model/sti-vs-polymorphic-question/graders/criteria.md new file mode 100644 index 0000000..2be8520 --- /dev/null +++ b/evals/domain-model/sti-vs-polymorphic-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the reply answers the Rails question with a recommendation for how to model visits by members and staff, whether STI, a polymorphic `belongs_to`, or another option. + +FAIL if it gives no recommendation, or starts interviewing about how the gym's business works instead of answering. diff --git a/evals/domain-model/sti-vs-polymorphic-question/graders/skill-not-fired.md b/evals/domain-model/sti-vs-polymorphic-question/graders/skill-not-fired.md new file mode 100644 index 0000000..91b49e5 --- /dev/null +++ b/evals/domain-model/sti-vs-polymorphic-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?domain-model"' +min: 0 +max: 0 +--- diff --git a/evals/domain-model/sti-vs-polymorphic-question/prompt.md b/evals/domain-model/sti-vs-polymorphic-question/prompt.md new file mode 100644 index 0000000..85548db --- /dev/null +++ b/evals/domain-model/sti-vs-polymorphic-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: domain-model-sti-vs-polymorphic-question +description: A Rails modeling question about our gym shouldn't trigger the domain model skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +Members and staff at our gym can both check in at the desk. Should Visit belong to them through a polymorphic association, or should Member and Staff be STI subclasses of one Person model? diff --git a/evals/eli5/billing-app.sh b/evals/eli5/billing-app.sh new file mode 100755 index 0000000..a094f37 --- /dev/null +++ b/evals/eli5/billing-app.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# Builds a tiny Ruby subscription-billing app that uses the word "dunning". No gems, no network. +set -euo pipefail + +mkdir -p bin db lib/billing lib/mailers + +cat > lib/billing/subscription.rb <<'RUBY' +module Billing + class Subscription + attr_reader :customer, :plan, :monthly_cents + attr_accessor :status + + def initialize(customer:, plan:, monthly_cents:) + @customer = customer + @plan = plan + @monthly_cents = monthly_cents + @status = :active + end + + def suspend! + self.status = :suspended + end + end +end +RUBY + +cat > lib/billing/invoice.rb <<'RUBY' +module Billing + class Invoice + attr_reader :number, :subscription, :amount_cents, :failed_on + attr_accessor :state + + def initialize(number:, subscription:, amount_cents:, failed_on: nil) + @number = number + @subscription = subscription + @amount_cents = amount_cents + @failed_on = failed_on + @state = failed_on ? :past_due : :open + end + + def mark_paid! + self.state = :paid + end + end +end +RUBY + +cat > lib/billing/dunning.rb <<'RUBY' +require "date" +require_relative "../mailers/dunning_mailer" + +module Billing + class Dunning + RETRY_SCHEDULE_DAYS = [2, 5, 11].freeze + SUSPEND_AFTER_DAYS = 21 + + def initialize(gateway:, today: Date.today) + @gateway = gateway + @today = today + end + + def run(invoices) + invoices.select { |invoice| invoice.state == :past_due }.each { |invoice| step(invoice) } + end + + private + + def step(invoice) + days_late = (@today - invoice.failed_on).to_i + + if days_late >= SUSPEND_AFTER_DAYS + invoice.subscription.suspend! + DunningMailer.deliver(:suspended, invoice) + elsif RETRY_SCHEDULE_DAYS.include?(days_late) + if @gateway.charge(invoice.amount_cents) + invoice.mark_paid! + DunningMailer.deliver(:recovered, invoice) + elsif days_late == RETRY_SCHEDULE_DAYS.last + DunningMailer.deliver(:final_notice, invoice) + else + DunningMailer.deliver(:payment_failed, invoice) + end + end + end + end +end +RUBY + +cat > lib/mailers/dunning_mailer.rb <<'RUBY' +module DunningMailer + SUBJECTS = { + payment_failed: "Your card was declined. We'll try again soon.", + final_notice: "Last try failed. Update your card within 10 days to keep access.", + suspended: "Your account is paused until you update your card.", + recovered: "Payment received. Thanks!" + }.freeze + + def self.deliver(template, invoice) + puts "To #{invoice.subscription.customer}: #{SUBJECTS.fetch(template)} (invoice ##{invoice.number})" + end +end +RUBY + +cat > db/seeds.rb <<'RUBY' +require "date" +require_relative "../lib/billing/subscription" +require_relative "../lib/billing/invoice" + +PINECREST = Billing::Subscription.new(customer: "Pinecrest Bakery", plan: "Team", monthly_cents: 4900) + +INVOICES = [ + Billing::Invoice.new(number: 7302, subscription: PINECREST, amount_cents: 4900, failed_on: Date.new(2026, 3, 1)) +].freeze +RUBY + +cat > bin/nightly_billing <<'RUBY' +#!/usr/bin/env ruby +# Cron runs this once a day at 06:00 UTC. +require_relative "../db/seeds" +require_relative "../lib/billing/dunning" + +class DecliningGateway + def charge(_cents) + false + end +end + +Billing::Dunning.new(gateway: DecliningGateway.new, today: Date.parse(ARGV.fetch(0, Date.today.to_s))).run(INVOICES) +RUBY +chmod +x bin/nightly_billing + +cat > README.md <<'MD' +# Pinecrest Billing + +Charges subscribers monthly. Run `bin/nightly_billing YYYY-MM-DD` to process a day. +MD diff --git a/evals/eli5/dup-vs-clone-question/graders/criteria.md b/evals/eli5/dup-vs-clone-question/graders/criteria.md new file mode 100644 index 0000000..cac4e30 --- /dev/null +++ b/evals/eli5/dup-vs-clone-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the reply says `clone` keeps the object's frozen state and singleton methods and `dup` doesn't (both are shallow copies). + +FAIL if it gets that backwards, or doesn't say how the two differ. diff --git a/evals/eli5/dup-vs-clone-question/graders/skill-not-fired.md b/evals/eli5/dup-vs-clone-question/graders/skill-not-fired.md new file mode 100644 index 0000000..10538c9 --- /dev/null +++ b/evals/eli5/dup-vs-clone-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?eli5"' +min: 0 +max: 0 +--- diff --git a/evals/eli5/dup-vs-clone-question/prompt.md b/evals/eli5/dup-vs-clone-question/prompt.md new file mode 100644 index 0000000..a62fed5 --- /dev/null +++ b/evals/eli5/dup-vs-clone-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: eli5-dup-vs-clone-question +description: A quick Ruby question from someone who knows Ruby shouldn't trigger the eli5 skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill, Agent] +--- + +In Ruby, what's the difference between `dup` and `clone`? diff --git a/evals/eli5/no-analogy/case.yaml b/evals/eli5/no-analogy/case.yaml new file mode 100644 index 0000000..a6d62f8 --- /dev/null +++ b/evals/eli5/no-analogy/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: eli5-no-analogy +context: + scaffold_script: scaffold.sh diff --git a/evals/eli5/no-analogy/graders/has-drawing.md b/evals/eli5/no-analogy/graders/has-drawing.md new file mode 100644 index 0000000..edbe497 --- /dev/null +++ b/evals/eli5/no-analogy/graders/has-drawing.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '```[^`]*(-->|->|→|\+--|\||[─│┌┐└┘├┤┬┴▶▼►])[^`]*```' +--- diff --git a/evals/eli5/no-analogy/graders/no-analogy.md b/evals/eli5/no-analogy/graders/no-analogy.md new file mode 100644 index 0000000..d08b494 --- /dev/null +++ b/evals/eli5/no-analogy/graders/no-analogy.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The user asked for no analogies. + +PASS if the reply explains dunning directly, in terms of what this repo's code does, with no comparison to everyday life outside software (no landlord, library, gym, parking ticket or similar), and no "it's like..." or "think of it as..." framing. + +FAIL if it includes any such everyday comparison, even a short one. diff --git a/evals/eli5/no-analogy/graders/no-invented-values.md b/evals/eli5/no-analogy/graders/no-invented-values.md new file mode 100644 index 0000000..9d52071 --- /dev/null +++ b/evals/eli5/no-analogy/graders/no-invented-values.md @@ -0,0 +1,15 @@ +--- +type: llm +--- + +Everything that exists in this repo: + +- Values: customer "Pinecrest Bakery", plan "Team", 4900 cents ($49.00) a month, invoice #7302, first failed on 2026-03-01, card retries on days 2, 5 and 11 after the failure, suspension at day 21, a nightly run at 06:00 UTC, email subjects: `payment_failed` "Your card was declined. We'll try again soon.", `final_notice` "Last try failed. Update your card within 10 days to keep access.", `suspended` "Your account is paused until you update your card.", `recovered` "Payment received. Thanks!". +- Code names: `Billing::Dunning`, `Billing::Invoice`, `Billing::Subscription`, `DunningMailer`, `DunningMailer::SUBJECTS`, `DecliningGateway`, `RETRY_SCHEDULE_DAYS`, `SUSPEND_AFTER_DAYS`, `run`, `step`, `charge`, `suspend!`, `mark_paid!`, `deliver`, attributes `customer`, `plan`, `monthly_cents`, `status`, `number`, `subscription`, `amount_cents`, `failed_on`, `gateway`, `today`, local `days_late`, invoice states `:open`, `:past_due`, `:paid`, subscription statuses `:active`, `:suspended`. +- Files: README.md, lib/billing/dunning.rb, lib/billing/invoice.rb, lib/billing/subscription.rb, lib/mailers/dunning_mailer.rb, db/seeds.rb, bin/nightly_billing. + +Judge only the specific values, names and files the reply presents as this repo's, not its claims about how the code behaves. + +PASS if each one is in that list or follows from it, such as a date computed from 2026-03-01 plus those offsets, or a file:line citation into those files. + +FAIL if the reply presents any value, name or file as this repo's that isn't there, such as a different retry day, customer, invoice number or file. Values clearly marked as a general or outside example don't count. diff --git a/evals/eli5/no-analogy/graders/skill-fired.md b/evals/eli5/no-analogy/graders/skill-fired.md new file mode 100644 index 0000000..265b1a9 --- /dev/null +++ b/evals/eli5/no-analogy/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?eli5"' +--- diff --git a/evals/eli5/no-analogy/prompt.md b/evals/eli5/no-analogy/prompt.md new file mode 100644 index 0000000..681f5f7 --- /dev/null +++ b/evals/eli5/no-analogy/prompt.md @@ -0,0 +1,9 @@ +--- +name: eli5-no-analogy +description: Someone who asks for no analogies gets the straight explanation, from the repo's own code, with no everyday comparison. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill, Agent] +--- + +I keep seeing "dunning" all over this codebase and I have no idea what it means. Explain it to me like I know nothing, but skip the analogies, I find them distracting. Just tell me what it actually does here. diff --git a/evals/eli5/no-analogy/scaffold.sh b/evals/eli5/no-analogy/scaffold.sh new file mode 100644 index 0000000..cad08aa --- /dev/null +++ b/evals/eli5/no-analogy/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +bash "$(dirname "$0")/../billing-app.sh" diff --git a/evals/eli5/not-in-repo/case.yaml b/evals/eli5/not-in-repo/case.yaml new file mode 100644 index 0000000..4b9950b --- /dev/null +++ b/evals/eli5/not-in-repo/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: eli5-not-in-repo +context: + scaffold_script: scaffold.sh diff --git a/evals/eli5/not-in-repo/graders/has-drawing.md b/evals/eli5/not-in-repo/graders/has-drawing.md new file mode 100644 index 0000000..edbe497 --- /dev/null +++ b/evals/eli5/not-in-repo/graders/has-drawing.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '```[^`]*(-->|->|→|\+--|\||[─│┌┐└┘├┤┬┴▶▼►])[^`]*```' +--- diff --git a/evals/eli5/not-in-repo/graders/no-closing-offer.md b/evals/eli5/not-in-repo/graders/no-closing-offer.md new file mode 100644 index 0000000..791315d --- /dev/null +++ b/evals/eli5/not-in-repo/graders/no-closing-offer.md @@ -0,0 +1,6 @@ +--- +type: regex +pattern: '(want me to|would you like|let me know if|i can also|happy to|shall i)[^\n]*\s*$' +flags: i +match: not_contains +--- diff --git a/evals/eli5/not-in-repo/graders/no-invented-repo-flags.md b/evals/eli5/not-in-repo/graders/no-invented-repo-flags.md new file mode 100644 index 0000000..42f87b5 --- /dev/null +++ b/evals/eli5/not-in-repo/graders/no-invented-repo-flags.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +This repo is a small Ruby billing app with no feature flags, no flag library, and no flag config. Its files are lib/billing/dunning.rb, lib/billing/invoice.rb, lib/billing/subscription.rb, lib/mailers/dunning_mailer.rb, db/seeds.rb, bin/nightly_billing and README.md. + +PASS if the reply names no flag, flag file, flag setting, or flag library as already existing in this repo. A clearly hypothetical example ("if you put the final notice email behind a flag, ...") or a general one is fine. + +FAIL if it presents a flag, a flag file, or a flag setting as something this repo already has. diff --git a/evals/eli5/not-in-repo/graders/says-not-in-repo.md b/evals/eli5/not-in-repo/graders/says-not-in-repo.md new file mode 100644 index 0000000..e8bf3b9 --- /dev/null +++ b/evals/eli5/not-in-repo/graders/says-not-in-repo.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the reply says, in a sentence or two, that this repo doesn't have or use feature flags (or that none were found in it). + +FAIL if it never says whether this repo has feature flags, or says or implies that it does. diff --git a/evals/eli5/not-in-repo/graders/skill-fired.md b/evals/eli5/not-in-repo/graders/skill-fired.md new file mode 100644 index 0000000..265b1a9 --- /dev/null +++ b/evals/eli5/not-in-repo/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?eli5"' +--- diff --git a/evals/eli5/not-in-repo/graders/uses-analogy.md b/evals/eli5/not-in-repo/graders/uses-analogy.md new file mode 100644 index 0000000..583d721 --- /dev/null +++ b/evals/eli5/not-in-repo/graders/uses-analogy.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Look at the reply's prose (ignore the code blocks). + +PASS if it explains feature flags with a simple analogy from everyday life outside software, the kind a kid would follow: a light switch on a wall, a "closed" sign on one door of a shop, a dish a restaurant only serves to some tables. The analogy has to be stated in plain words and map onto how a feature flag works (the thing is built and in place, and a switch decides who gets it, without rebuilding anything). + +FAIL if there is no such analogy, if the only comparison is to other software, code or a framework (an `if` statement, an environment variable, a Rails config setting), or if the comparison is so loose it doesn't map onto switching something on or off. diff --git a/evals/eli5/not-in-repo/prompt.md b/evals/eli5/not-in-repo/prompt.md new file mode 100644 index 0000000..20d72df --- /dev/null +++ b/evals/eli5/not-in-repo/prompt.md @@ -0,0 +1,9 @@ +--- +name: eli5-not-in-repo +description: A term the repo doesn't use gets one line saying so, then a general explanation with no made-up repo values. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill, Agent] +--- + +Someone in standup said we should "put it behind a feature flag". I have no idea what a feature flag is. Explain it to me like I know nothing. diff --git a/evals/eli5/not-in-repo/scaffold.sh b/evals/eli5/not-in-repo/scaffold.sh new file mode 100644 index 0000000..cad08aa --- /dev/null +++ b/evals/eli5/not-in-repo/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +bash "$(dirname "$0")/../billing-app.sh" diff --git a/evals/eli5/webhook-system/case.yaml b/evals/eli5/webhook-system/case.yaml new file mode 100644 index 0000000..407a73e --- /dev/null +++ b/evals/eli5/webhook-system/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: eli5-webhook-system +context: + scaffold_script: scaffold.sh diff --git a/evals/eli5/webhook-system/graders/analogy-before-code.md b/evals/eli5/webhook-system/graders/analogy-before-code.md new file mode 100644 index 0000000..413e21e --- /dev/null +++ b/evals/eli5/webhook-system/graders/analogy-before-code.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Find the first comparison to everyday life outside software in the reply's prose (a landlord, a gym, a library, a courier, a mailroom, a cashier, or similar). + +PASS if that comparison comes before the reply first names a file, path, class, method, constant or other code name. + +FAIL if there is no such comparison, or a file, path, class, method, constant or other code name appears before it. diff --git a/evals/eli5/webhook-system/graders/has-drawing.md b/evals/eli5/webhook-system/graders/has-drawing.md new file mode 100644 index 0000000..edbe497 --- /dev/null +++ b/evals/eli5/webhook-system/graders/has-drawing.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '```[^`]*(-->|->|→|\+--|\||[─│┌┐└┘├┤┬┴▶▼►])[^`]*```' +--- diff --git a/evals/eli5/webhook-system/graders/no-closing-offer.md b/evals/eli5/webhook-system/graders/no-closing-offer.md new file mode 100644 index 0000000..791315d --- /dev/null +++ b/evals/eli5/webhook-system/graders/no-closing-offer.md @@ -0,0 +1,6 @@ +--- +type: regex +pattern: '(want me to|would you like|let me know if|i can also|happy to|shall i)[^\n]*\s*$' +flags: i +match: not_contains +--- diff --git a/evals/eli5/webhook-system/graders/no-invented-values.md b/evals/eli5/webhook-system/graders/no-invented-values.md new file mode 100644 index 0000000..b5f1e27 --- /dev/null +++ b/evals/eli5/webhook-system/graders/no-invented-values.md @@ -0,0 +1,15 @@ +--- +type: llm +--- + +Everything that exists in this repo: + +- Values: `SEEN_TTL_SECONDS = 72 * 60 * 60` (72 hours, 259200 seconds), event IDs `evt_3QmX81` (type `invoice.paid`, invoice 7302, appears twice in the fixture) and `evt_3QmY04` (type `customer.updated`), return values `:duplicate`, `:ignored`, `:processed`, handler types `invoice.paid` and `charge.refunded`, the README's "for up to 3 days". +- Code names: `Webhooks::Processor`, `Webhooks::SeenStore`, `Webhooks::HANDLERS`, `call`, `seen?`, `remember`, `fetch`, `@store`, `@handlers`, `@clock`, `@expires_at`, `ttl`. +- Files: README.md, lib/webhooks/processor.rb, lib/webhooks/seen_store.rb, lib/webhooks/handlers.rb, test/fixtures/events.json. + +Judge only the specific values, names and files the reply presents as this repo's, not its claims about how the code behaves. + +PASS if each one is in that list or follows from it, such as a time computed from 72 hours, or a file:line citation into those files. + +FAIL if the reply presents any value, name or file as this repo's that isn't there, such as a different TTL, event ID, route, controller or database table. Values clearly marked as a general or outside example don't count. diff --git a/evals/eli5/webhook-system/graders/skill-fired.md b/evals/eli5/webhook-system/graders/skill-fired.md new file mode 100644 index 0000000..265b1a9 --- /dev/null +++ b/evals/eli5/webhook-system/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?eli5"' +--- diff --git a/evals/eli5/webhook-system/graders/uses-analogy.md b/evals/eli5/webhook-system/graders/uses-analogy.md new file mode 100644 index 0000000..7f45c71 --- /dev/null +++ b/evals/eli5/webhook-system/graders/uses-analogy.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Look at the reply's prose (ignore the code blocks). + +PASS if it explains the system with a simple analogy from everyday life outside software, the kind a kid would follow: a mailroom clerk who writes down each letter's tracking number and bins any second copy, a cashier who won't refund the same receipt twice, a guest list at a door. The analogy has to be stated in plain words and map onto how this code works (the same message can arrive more than once, and a remembered ID makes the repeat get skipped). + +FAIL if there is no such analogy, if the only comparisons are to other software, code or a framework (a unique index, a Rails callback, a background job, a cache), or if the comparison is so loose it doesn't map onto skipping repeats. diff --git a/evals/eli5/webhook-system/prompt.md b/evals/eli5/webhook-system/prompt.md new file mode 100644 index 0000000..1d67099 --- /dev/null +++ b/evals/eli5/webhook-system/prompt.md @@ -0,0 +1,9 @@ +--- +name: eli5-webhook-system +description: A technical system in code gets a simple everyday analogy by default, not just a comparison to other code. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill, Agent] +--- + +I've never worked with webhooks. Can you explain this system to me like I know nothing? Start with lib/webhooks/processor.rb. I don't get what it's doing or why it needs the seen store. diff --git a/evals/eli5/webhook-system/scaffold.sh b/evals/eli5/webhook-system/scaffold.sh new file mode 100644 index 0000000..634ae0e --- /dev/null +++ b/evals/eli5/webhook-system/scaffold.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Builds a tiny Ruby app that receives payment webhooks and skips repeats. No gems, no network. +set -euo pipefail + +mkdir -p lib/webhooks test/fixtures + +cat > lib/webhooks/seen_store.rb <<'RUBY' +module Webhooks + class SeenStore + def initialize(clock: -> { Time.now.to_i }) + @clock = clock + @expires_at = {} + end + + def seen?(event_id) + expiry = @expires_at[event_id] + !expiry.nil? && expiry > @clock.call + end + + def remember(event_id, ttl:) + @expires_at[event_id] = @clock.call + ttl + end + end +end +RUBY + +cat > lib/webhooks/processor.rb <<'RUBY' +require_relative "seen_store" + +module Webhooks + class Processor + SEEN_TTL_SECONDS = 72 * 60 * 60 + + def initialize(store:, handlers:) + @store = store + @handlers = handlers + end + + def call(event) + return :duplicate if @store.seen?(event.fetch("id")) + + handler = @handlers[event.fetch("type")] + return :ignored unless handler + + handler.call(event) + @store.remember(event.fetch("id"), ttl: SEEN_TTL_SECONDS) + :processed + end + end +end +RUBY + +cat > lib/webhooks/handlers.rb <<'RUBY' +module Webhooks + HANDLERS = { + "invoice.paid" => ->(event) { puts "Marking invoice #{event.dig("data", "invoice")} paid" }, + "charge.refunded" => ->(event) { puts "Refunding #{event.dig("data", "amount_cents")} cents" } + }.freeze +end +RUBY + +cat > test/fixtures/events.json <<'JSON' +[ + {"id": "evt_3QmX81", "type": "invoice.paid", "data": {"invoice": 7302}}, + {"id": "evt_3QmX81", "type": "invoice.paid", "data": {"invoice": 7302}}, + {"id": "evt_3QmY04", "type": "customer.updated", "data": {}} +] +JSON + +cat > README.md <<'MD' +# Pinecrest Webhooks + +Receives payment events from the payment provider. The provider resends an +event until we answer, for up to 3 days, so the same event can arrive more +than once. +MD diff --git a/evals/eli5/whats-dunning/case.yaml b/evals/eli5/whats-dunning/case.yaml new file mode 100644 index 0000000..a43ac4b --- /dev/null +++ b/evals/eli5/whats-dunning/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: eli5-whats-dunning +context: + scaffold_script: scaffold.sh diff --git a/evals/eli5/whats-dunning/graders/agents-launched.md b/evals/eli5/whats-dunning/graders/agents-launched.md new file mode 100644 index 0000000..d14a4c2 --- /dev/null +++ b/evals/eli5/whats-dunning/graders/agents-launched.md @@ -0,0 +1,5 @@ +--- +type: regex +target: trace +pattern: '"type":"tool_use","id":"[^"]*","name":"(?:Agent|Task)"' +--- diff --git a/evals/eli5/whats-dunning/graders/analogy-before-code.md b/evals/eli5/whats-dunning/graders/analogy-before-code.md new file mode 100644 index 0000000..413e21e --- /dev/null +++ b/evals/eli5/whats-dunning/graders/analogy-before-code.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Find the first comparison to everyday life outside software in the reply's prose (a landlord, a gym, a library, a courier, a mailroom, a cashier, or similar). + +PASS if that comparison comes before the reply first names a file, path, class, method, constant or other code name. + +FAIL if there is no such comparison, or a file, path, class, method, constant or other code name appears before it. diff --git a/evals/eli5/whats-dunning/graders/drawing-shows-failure.md b/evals/eli5/whats-dunning/graders/drawing-shows-failure.md new file mode 100644 index 0000000..2206580 --- /dev/null +++ b/evals/eli5/whats-dunning/graders/drawing-shows-failure.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Look only at the plain-text drawings (the code blocks) in the reply. + +PASS if at least one drawing shows the path where the card keeps failing and the subscription ends up suspended. + +FAIL if the drawings show only a payment being retried or recovered, with no suspension, or there is no drawing. diff --git a/evals/eli5/whats-dunning/graders/has-drawing.md b/evals/eli5/whats-dunning/graders/has-drawing.md new file mode 100644 index 0000000..edbe497 --- /dev/null +++ b/evals/eli5/whats-dunning/graders/has-drawing.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '```[^`]*(-->|->|→|\+--|\||[─│┌┐└┘├┤┬┴▶▼►])[^`]*```' +--- diff --git a/evals/eli5/whats-dunning/graders/leads-with-job.md b/evals/eli5/whats-dunning/graders/leads-with-job.md new file mode 100644 index 0000000..9196d47 --- /dev/null +++ b/evals/eli5/whats-dunning/graders/leads-with-job.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Look only at the reply's first sentence or two of prose (ignore a heading). + +PASS if they say, in plain words, what dunning does for the business or the customer: chasing a customer whose payment failed, retrying the charge and reminding them before cutting off access. + +FAIL if they open with mechanism instead: a class or method name, a file path, a schedule of days, or a definition that uses billing jargon without explaining it. diff --git a/evals/eli5/whats-dunning/graders/no-closing-offer.md b/evals/eli5/whats-dunning/graders/no-closing-offer.md new file mode 100644 index 0000000..791315d --- /dev/null +++ b/evals/eli5/whats-dunning/graders/no-closing-offer.md @@ -0,0 +1,6 @@ +--- +type: regex +pattern: '(want me to|would you like|let me know if|i can also|happy to|shall i)[^\n]*\s*$' +flags: i +match: not_contains +--- diff --git a/evals/eli5/whats-dunning/graders/no-invented-values.md b/evals/eli5/whats-dunning/graders/no-invented-values.md new file mode 100644 index 0000000..9d52071 --- /dev/null +++ b/evals/eli5/whats-dunning/graders/no-invented-values.md @@ -0,0 +1,15 @@ +--- +type: llm +--- + +Everything that exists in this repo: + +- Values: customer "Pinecrest Bakery", plan "Team", 4900 cents ($49.00) a month, invoice #7302, first failed on 2026-03-01, card retries on days 2, 5 and 11 after the failure, suspension at day 21, a nightly run at 06:00 UTC, email subjects: `payment_failed` "Your card was declined. We'll try again soon.", `final_notice` "Last try failed. Update your card within 10 days to keep access.", `suspended` "Your account is paused until you update your card.", `recovered` "Payment received. Thanks!". +- Code names: `Billing::Dunning`, `Billing::Invoice`, `Billing::Subscription`, `DunningMailer`, `DunningMailer::SUBJECTS`, `DecliningGateway`, `RETRY_SCHEDULE_DAYS`, `SUSPEND_AFTER_DAYS`, `run`, `step`, `charge`, `suspend!`, `mark_paid!`, `deliver`, attributes `customer`, `plan`, `monthly_cents`, `status`, `number`, `subscription`, `amount_cents`, `failed_on`, `gateway`, `today`, local `days_late`, invoice states `:open`, `:past_due`, `:paid`, subscription statuses `:active`, `:suspended`. +- Files: README.md, lib/billing/dunning.rb, lib/billing/invoice.rb, lib/billing/subscription.rb, lib/mailers/dunning_mailer.rb, db/seeds.rb, bin/nightly_billing. + +Judge only the specific values, names and files the reply presents as this repo's, not its claims about how the code behaves. + +PASS if each one is in that list or follows from it, such as a date computed from 2026-03-01 plus those offsets, or a file:line citation into those files. + +FAIL if the reply presents any value, name or file as this repo's that isn't there, such as a different retry day, customer, invoice number or file. Values clearly marked as a general or outside example don't count. diff --git a/evals/eli5/whats-dunning/graders/skill-fired.md b/evals/eli5/whats-dunning/graders/skill-fired.md new file mode 100644 index 0000000..265b1a9 --- /dev/null +++ b/evals/eli5/whats-dunning/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?eli5"' +--- diff --git a/evals/eli5/whats-dunning/graders/uses-analogy.md b/evals/eli5/whats-dunning/graders/uses-analogy.md new file mode 100644 index 0000000..5cdf4d6 --- /dev/null +++ b/evals/eli5/whats-dunning/graders/uses-analogy.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Look at the reply's prose (ignore the code blocks). + +PASS if it explains dunning with a simple analogy from everyday life outside software, the kind a kid would follow: a landlord chasing late rent, a library sending overdue notices before suspending your card, a gym that keeps trying your card and then locks you out. The analogy has to be stated in plain words and map onto how dunning works (retrying, reminding, then cutting off access). + +FAIL if there is no such analogy, if the only comparison is to other software, code or a framework (a background job, a cron task, a Rails callback), or if the comparison is so loose it doesn't map onto retrying and cutting off. diff --git a/evals/eli5/whats-dunning/graders/uses-retry-schedule.md b/evals/eli5/whats-dunning/graders/uses-retry-schedule.md new file mode 100644 index 0000000..03ba61f --- /dev/null +++ b/evals/eli5/whats-dunning/graders/uses-retry-schedule.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '2,\s*5,\s*(?:and\s*)?11|day\s*11\b|\b11\s*days?\b|\+11\b|\bd11\b' +flags: i +--- diff --git a/evals/eli5/whats-dunning/prompt.md b/evals/eli5/whats-dunning/prompt.md new file mode 100644 index 0000000..2e3709c --- /dev/null +++ b/evals/eli5/whats-dunning/prompt.md @@ -0,0 +1,9 @@ +--- +name: eli5-whats-dunning +description: A billing word used all over the repo gets explained from this repo's own code, job first, with real values and a drawing. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill, Agent] +--- + +I keep seeing "dunning" all over this codebase and I have no idea what it means. Explain it to me like I know nothing. diff --git a/evals/eli5/whats-dunning/scaffold.sh b/evals/eli5/whats-dunning/scaffold.sh new file mode 100644 index 0000000..cad08aa --- /dev/null +++ b/evals/eli5/whats-dunning/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +bash "$(dirname "$0")/../billing-app.sh" diff --git a/evals/implement-with-tdd/billing-app.sh b/evals/implement-with-tdd/billing-app.sh new file mode 100644 index 0000000..6aacfc3 --- /dev/null +++ b/evals/implement-with-tdd/billing-app.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null +commit() { git add -A && git commit -q -m "$1"; } + +mkdir -p lib test + +cat > README.md <<'MD' +# Billing + +Plain Ruby and Minitest, no gems. One test file: `ruby -Ilib -Itest test/invoice_test.rb`. Everything: `rake test`. +MD + +cat > Rakefile <<'RUBY' +require "rake/testtask" + +Rake::TestTask.new do |t| + t.libs << "lib" << "test" + t.test_files = FileList["test/*_test.rb"] +end +RUBY + +cat > lib/plan.rb <<'RUBY' +class Plan + attr_reader :name, :price_cents + + def initialize(name:, price_cents:) + @name = name + @price_cents = price_cents + end + + def free? + price_cents.zero? + end +end +RUBY + +cat > test/plan_test.rb <<'RUBY' +require "minitest/autorun" +require "plan" + +class PlanTest < Minitest::Test + def test_is_free_when_it_costs_nothing + plan = Plan.new(name: "Hobby", price_cents: 0) + + free = plan.free? + + assert free + end +end +RUBY + +commit "Add plans" + +cat > lib/invoice.rb <<'RUBY' +class Invoice + attr_reader :plan, :issued_on, :paid_on + + def initialize(plan:, issued_on:) + @plan = plan + @issued_on = issued_on + end + + def amount_cents + plan.price_cents + end + + def pay(on) + @paid_on = on + end + + def paid? + !paid_on.nil? + end +end +RUBY + +cat > test/invoice_test.rb <<'RUBY' +require "minitest/autorun" +require "date" +require "plan" +require "invoice" + +class InvoiceTest < Minitest::Test + def test_amount_is_the_plan_price + plan = Plan.new(name: "Pro", price_cents: 1200) + + invoice = Invoice.new(plan: plan, issued_on: Date.new(2026, 3, 1)) + + assert_equal 1200, invoice.amount_cents + end + + def test_is_paid_once_paid + invoice = Invoice.new(plan: Plan.new(name: "Pro", price_cents: 1200), issued_on: Date.new(2026, 3, 1)) + + invoice.pay(Date.new(2026, 3, 5)) + + assert invoice.paid? + end +end +RUBY + +commit "Add invoices" diff --git a/evals/implement-with-tdd/invoice-due-dates/case.yaml b/evals/implement-with-tdd/invoice-due-dates/case.yaml new file mode 100644 index 0000000..7bc698a --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: implement-with-tdd-invoice-due-dates +context: + scaffold_script: scaffold.sh diff --git a/evals/implement-with-tdd/invoice-due-dates/graders/green-at-end.md b/evals/implement-with-tdd/invoice-due-dates/graders/green-at-end.md new file mode 100644 index 0000000..e5e1fad --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/graders/green-at-end.md @@ -0,0 +1,5 @@ +--- +type: regex +target: trace +pattern: '\d+ runs, \d+ assertions, 0 failures, 0 errors(?![\s\S]*\d+ runs, \d+ assertions, \d+ failures)' +--- diff --git a/evals/implement-with-tdd/invoice-due-dates/graders/head-unmoved.md b/evals/implement-with-tdd/invoice-due-dates/graders/head-unmoved.md new file mode 100644 index 0000000..50e5f0f --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/graders/head-unmoved.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: "^[0-9a-f]{40} [0-9a-f]{40} " +flags: m +match: "count:3" +--- diff --git a/evals/implement-with-tdd/invoice-due-dates/graders/no-scope-creep.md b/evals/implement-with-tdd/invoice-due-dates/graders/no-scope-creep.md new file mode 100644 index 0000000..e69ea86 --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/graders/no-scope-creep.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: lib/invoice.rb } +--- + +This is the `Invoice` class after building a SPEC with two criteria: an invoice is due 30 days after it's issued, and an unpaid invoice is overdue starting the day after it's due. Before the change it had `amount_cents`, `pay`, `paid?`, and readers for `plan`, `issued_on`, and `paid_on`. + +PASS if every public method added to the class is about the due date or about being overdue. + +FAIL if it adds a public method for anything else, such as late fees or reminders. diff --git a/evals/implement-with-tdd/invoice-due-dates/graders/skill-fired.md b/evals/implement-with-tdd/invoice-due-dates/graders/skill-fired.md new file mode 100644 index 0000000..ca55b5c --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?implement-with-tdd"' +--- diff --git a/evals/implement-with-tdd/invoice-due-dates/graders/tests-added.md b/evals/implement-with-tdd/invoice-due-dates/graders/tests-added.md new file mode 100644 index 0000000..3b4ecb3 --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/graders/tests-added.md @@ -0,0 +1,5 @@ +--- +type: regex +target: { source: file, path: test/invoice_test.rb } +pattern: '(?:[\s\S]*?def test_){4}' +--- diff --git a/evals/implement-with-tdd/invoice-due-dates/graders/went-red.md b/evals/implement-with-tdd/invoice-due-dates/graders/went-red.md new file mode 100644 index 0000000..06fb75e --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/graders/went-red.md @@ -0,0 +1,5 @@ +--- +type: regex +target: trace +pattern: '\d+ runs, \d+ assertions, (?:[1-9]\d* failures|\d+ failures, [1-9]\d* errors)' +--- diff --git a/evals/implement-with-tdd/invoice-due-dates/prompt.md b/evals/implement-with-tdd/invoice-due-dates/prompt.md new file mode 100644 index 0000000..5cfc605 --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/prompt.md @@ -0,0 +1,8 @@ +--- +description: Two small criteria on Invoice get built test-first, red before green, with a green suite at the end, nothing past the SPEC, and nothing committed. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Bash, Write] +--- + +Implement docs/specs/invoice-due-dates.md with TDD. diff --git a/evals/implement-with-tdd/invoice-due-dates/scaffold.sh b/evals/implement-with-tdd/invoice-due-dates/scaffold.sh new file mode 100644 index 0000000..7c9bb5b --- /dev/null +++ b/evals/implement-with-tdd/invoice-due-dates/scaffold.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../billing-app.sh" + +mkdir -p docs/specs +cat > docs/specs/invoice-due-dates.md <<'MD' +# Invoice due dates + +Customers keep asking when an invoice is due. Show it, and flag the late ones. + +## Acceptance criteria + +- [ ] An invoice is due 30 days after it's issued. One issued on 2026-03-01 is due on 2026-03-31. +- [ ] An unpaid invoice is overdue starting the day after it's due. A paid invoice is never overdue. + +## Out of scope + +- Late fees and reminder emails. +MD + +commit "Add invoice due dates spec" diff --git a/evals/implement-with-tdd/ledgerly-api-key/case.yaml b/evals/implement-with-tdd/ledgerly-api-key/case.yaml new file mode 100644 index 0000000..eae66a0 --- /dev/null +++ b/evals/implement-with-tdd/ledgerly-api-key/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: implement-with-tdd-ledgerly-api-key +context: + scaffold_script: scaffold.sh diff --git a/evals/implement-with-tdd/ledgerly-api-key/graders/asks-about-external-call.md b/evals/implement-with-tdd/ledgerly-api-key/graders/asks-about-external-call.md new file mode 100644 index 0000000..569ea58 --- /dev/null +++ b/evals/implement-with-tdd/ledgerly-api-key/graders/asks-about-external-call.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The SPEC's second criterion sends each invoice to Ledgerly, an outside API at https://api.ledgerly.example, using an API key. + +PASS if a message from Claude to the user asks the user to decide how to handle the Ledgerly call before it gets built, such as where the API key lives, what happens when the call fails, or how the tests stay offline. + +FAIL if no message from Claude asks the user to decide anything about the Ledgerly call. diff --git a/evals/implement-with-tdd/ledgerly-api-key/graders/head-unmoved.md b/evals/implement-with-tdd/ledgerly-api-key/graders/head-unmoved.md new file mode 100644 index 0000000..50e5f0f --- /dev/null +++ b/evals/implement-with-tdd/ledgerly-api-key/graders/head-unmoved.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: "^[0-9a-f]{40} [0-9a-f]{40} " +flags: m +match: "count:3" +--- diff --git a/evals/implement-with-tdd/ledgerly-api-key/graders/no-http-call-written.md b/evals/implement-with-tdd/ledgerly-api-key/graders/no-http-call-written.md new file mode 100644 index 0000000..3b797de --- /dev/null +++ b/evals/implement-with-tdd/ledgerly-api-key/graders/no-http-call-written.md @@ -0,0 +1,6 @@ +--- +type: regex +target: trace +pattern: '"name":"(?:Write|Edit)","input":\{[^\n]*?(?:Net::HTTP|[Ll]edgerly|LEDGERLY)' +match: not_contains +--- diff --git a/evals/implement-with-tdd/ledgerly-api-key/graders/skill-fired.md b/evals/implement-with-tdd/ledgerly-api-key/graders/skill-fired.md new file mode 100644 index 0000000..ca55b5c --- /dev/null +++ b/evals/implement-with-tdd/ledgerly-api-key/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?implement-with-tdd"' +--- diff --git a/evals/implement-with-tdd/ledgerly-api-key/prompt.md b/evals/implement-with-tdd/ledgerly-api-key/prompt.md new file mode 100644 index 0000000..e850a96 --- /dev/null +++ b/evals/implement-with-tdd/ledgerly-api-key/prompt.md @@ -0,0 +1,8 @@ +--- +description: The second criterion calls an outside API with a key, so the skill lays out the options and waits instead of building the call. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Bash, Write] +--- + +Implement docs/specs/send-invoices-to-ledgerly.md with TDD. diff --git a/evals/implement-with-tdd/ledgerly-api-key/scaffold.sh b/evals/implement-with-tdd/ledgerly-api-key/scaffold.sh new file mode 100644 index 0000000..a9b0555 --- /dev/null +++ b/evals/implement-with-tdd/ledgerly-api-key/scaffold.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../billing-app.sh" + +mkdir -p docs/specs +cat > docs/specs/send-invoices-to-ledgerly.md <<'MD' +# Send invoices to Ledgerly + +Accounting wants every invoice in Ledgerly, their bookkeeping service. + +## Acceptance criteria + +- [ ] An invoice is due 30 days after it's issued. One issued on 2026-03-01 is due on 2026-03-31. +- [ ] An invoice can be sent to Ledgerly: a POST to https://api.ledgerly.example/invoices with its amount and due date, authenticated with our Ledgerly API key. +MD + +commit "Add Ledgerly spec" diff --git a/evals/implement-with-tdd/mock-vs-stub-question/graders/criteria.md b/evals/implement-with-tdd/mock-vs-stub-question/graders/criteria.md new file mode 100644 index 0000000..6b175b3 --- /dev/null +++ b/evals/implement-with-tdd/mock-vs-stub-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the answer says a stub swaps in a canned return value for a method, while a mock also checks that the expected calls were made (in Minitest, `Minitest::Mock` with `expect` and `verify`). + +FAIL if it gets either one wrong, or starts building something instead of answering. diff --git a/evals/implement-with-tdd/mock-vs-stub-question/graders/skill-not-fired.md b/evals/implement-with-tdd/mock-vs-stub-question/graders/skill-not-fired.md new file mode 100644 index 0000000..db79801 --- /dev/null +++ b/evals/implement-with-tdd/mock-vs-stub-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?implement-with-tdd"' +min: 0 +max: 0 +--- diff --git a/evals/implement-with-tdd/mock-vs-stub-question/prompt.md b/evals/implement-with-tdd/mock-vs-stub-question/prompt.md new file mode 100644 index 0000000..900267b --- /dev/null +++ b/evals/implement-with-tdd/mock-vs-stub-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: implement-with-tdd-mock-vs-stub-question +description: A general Minitest question shouldn't trigger the TDD skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +What's the difference between a mock and a stub in Minitest? diff --git a/evals/multi-lens-review/archive-projects/case.yaml b/evals/multi-lens-review/archive-projects/case.yaml new file mode 100644 index 0000000..62241ae --- /dev/null +++ b/evals/multi-lens-review/archive-projects/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: multi-lens-review-archive-projects +context: + scaffold_script: fixture.sh diff --git a/evals/multi-lens-review/archive-projects/fixture.sh b/evals/multi-lens-review/archive-projects/fixture.sh new file mode 100755 index 0000000..a3fd69c --- /dev/null +++ b/evals/multi-lens-review/archive-projects/fixture.sh @@ -0,0 +1,288 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +bash "$(dirname "$0")/../rails-app.sh" + +mkdir -p docs/specs + +cat > docs/specs/archive-projects.md <<'MD' +# Archive projects + +Owners can archive a project they're done with, so it drops off their +projects list without being deleted. + +## Job story + +When my projects list fills up with finished work +I want to put old projects away without deleting them +So I can find the ones I'm working on + +## Acceptance criteria + +- [ ] Given I own an active project, when I click "Archive" on its page, then I land on my projects list and that project isn't in it. +- [ ] Given I have an archived project, when I click "Archived" on my projects list, then I see that project listed. +MD + +git add -A +git commit -q -m "Add SPEC for archiving projects" + +git remote add origin git@github.com:acme/tracker.git +git update-ref refs/remotes/origin/main main +git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main + +git checkout -q -b archive-projects + +mkdir -p db/migrate + +cat > db/migrate/20261027140000_add_archived_at_to_projects.rb <<'RUBY' +class AddArchivedAtToProjects < ActiveRecord::Migration[7.1] + def change + add_column :projects, :archived_at, :datetime + end +end +RUBY + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[7.1].define(version: 2026_10_27_140000) do + create_table "users", force: :cascade do |t| + t.string "email", null: false + t.string "password_digest", null: false + t.timestamps + end + + create_table "projects", force: :cascade do |t| + t.references "user", null: false, foreign_key: true + t.string "name", null: false + t.text "description" + t.datetime "archived_at" + t.timestamps + end +end +RUBY + +cat > app/models/project.rb <<'RUBY' +class Project < ApplicationRecord + belongs_to :user + + validates :name, presence: true + + scope :active, -> { where(archived_at: nil) } + scope :archived, -> { where.not(archived_at: nil) } + + def archive! + update!(archived_at: Time.current) + end +end +RUBY + +git add -A +git commit -q -m "Add archived_at to projects" + +cat > config/routes.rb <<'RUBY' +Rails.application.routes.draw do + resource :session, only: [:new, :create, :destroy] + resources :projects do + member do + patch :archive + end + end + root "projects#index" +end +RUBY + +cat > app/controllers/projects_controller.rb <<'RUBY' +class ProjectsController < ApplicationController + before_action :set_project, only: [:show, :edit, :update, :destroy] + + def index + @projects = current_user.projects.active.order(:name) + end + + def show + end + + def new + @project = current_user.projects.new + end + + def create + @project = current_user.projects.new(project_params) + + if @project.save + redirect_to @project, notice: "Project created." + else + render :new, status: :unprocessable_entity + end + end + + def edit + end + + def update + if @project.update(project_params) + redirect_to @project, notice: "Project updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @project.destroy + redirect_to projects_path, notice: "Project deleted." + end + + def archive + project = Project.find(params[:id]) + project.archive! + ProjectMailer.archived(project).deliver_later + redirect_to projects_path, notice: "Project archived." + end + + private + + def set_project + @project = current_user.projects.find(params[:id]) + end + + def project_params + params.require(:project).permit(:name, :description) + end +end +RUBY + +mkdir -p app/views/project_mailer + +cat > app/mailers/project_mailer.rb <<'RUBY' +class ProjectMailer < ApplicationMailer + def archived(project) + @project = project + mail to: project.user.email, subject: "#{project.name} was archived" + end +end +RUBY + +cat > app/views/project_mailer/archived.text.erb <<'ERB' +Your project <%= @project.name %> was archived on <%= @project.archived_at.to_date %>. + +It no longer shows on your projects list. +ERB + +cat > app/views/projects/show.html.erb <<'ERB' +

<%= @project.name %>

+ +

<%= @project.description %>

+ +<%= link_to "Edit", edit_project_path(@project) %> +<%= button_to "Archive", archive_project_path(@project), method: :patch %> +<%= button_to "Delete", @project, method: :delete %> +ERB + +cat >> test/controllers/projects_controller_test.rb <<'RUBY' + +class ArchiveProjectTest < ActionDispatch::IntegrationTest + test "archiving a project takes it off my list" do + sign_in_as users(:alice) + + patch archive_project_path(projects(:website)) + + assert_redirected_to projects_path + follow_redirect! + assert_select "li", text: "Website", count: 0 + end +end +RUBY + +git add -A +git commit -q -m "Archive a project from its page" + +cat > app/controllers/projects_controller.rb <<'RUBY' +class ProjectsController < ApplicationController + before_action :set_project, only: [:show, :edit, :update, :destroy] + + def index + scope = params[:archived] ? current_user.projects.archived : current_user.projects.active + @projects = scope.order(:name) + end + + def show + end + + def new + @project = current_user.projects.new + end + + def create + @project = current_user.projects.new(project_params) + + if @project.save + redirect_to @project, notice: "Project created." + else + render :new, status: :unprocessable_entity + end + end + + def edit + end + + def update + if @project.update(project_params) + redirect_to @project, notice: "Project updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @project.destroy + redirect_to projects_path, notice: "Project deleted." + end + + def archive + project = Project.find(params[:id]) + project.archive! + ProjectMailer.archived(project).deliver_later + redirect_to projects_path, notice: "Project archived." + end + + private + + def set_project + @project = current_user.projects.find(params[:id]) + end + + def project_params + params.require(:project).permit(:name, :description) + end +end +RUBY + +cat > app/views/projects/index.html.erb <<'ERB' +

<%= params[:archived] ? "Archived projects" : "Projects" %>

+ + + +<%= link_to "New project", new_project_path %> +<%= link_to "Archived", projects_path(archived: true) %> +ERB + +cat >> test/controllers/projects_controller_test.rb <<'RUBY' + +class ArchivedProjectsListTest < ActionDispatch::IntegrationTest + test "archived projects show on the archived list" do + projects(:website).archive! + sign_in_as users(:alice) + + get projects_path(archived: true) + + assert_select "li", text: "Website" + end +end +RUBY + +git add -A +git commit -q -m "List archived projects" diff --git a/evals/multi-lens-review/archive-projects/graders/agents-launched.md b/evals/multi-lens-review/archive-projects/graders/agents-launched.md new file mode 100644 index 0000000..d14a4c2 --- /dev/null +++ b/evals/multi-lens-review/archive-projects/graders/agents-launched.md @@ -0,0 +1,5 @@ +--- +type: regex +target: trace +pattern: '"type":"tool_use","id":"[^"]*","name":"(?:Agent|Task)"' +--- diff --git a/evals/multi-lens-review/archive-projects/graders/asks-which-to-apply.md b/evals/multi-lens-review/archive-projects/graders/asks-which-to-apply.md new file mode 100644 index 0000000..e82a1be --- /dev/null +++ b/evals/multi-lens-review/archive-projects/graders/asks-which-to-apply.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +This is the end of a code review. + +PASS if the reply asks the user which findings to apply. + +FAIL if it doesn't ask, or says it already applied a fix. diff --git a/evals/multi-lens-review/archive-projects/graders/defect-left-in-place.md b/evals/multi-lens-review/archive-projects/graders/defect-left-in-place.md new file mode 100644 index 0000000..e36869c --- /dev/null +++ b/evals/multi-lens-review/archive-projects/graders/defect-left-in-place.md @@ -0,0 +1,5 @@ +--- +type: regex +target: { source: file, path: app/controllers/projects_controller.rb } +pattern: 'project = Project\.find\(params\[:id\]\)' +--- diff --git a/evals/multi-lens-review/archive-projects/graders/finds-missing-ownership-check.md b/evals/multi-lens-review/archive-projects/graders/finds-missing-ownership-check.md new file mode 100644 index 0000000..dfebf27 --- /dev/null +++ b/evals/multi-lens-review/archive-projects/graders/finds-missing-ownership-check.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +This is a code review of a branch. In `app/controllers/projects_controller.rb`, the new `archive` action loads the project with `Project.find(params[:id])`. Every other action loads it with `current_user.projects.find(params[:id])`. + +PASS if the review says `archive` doesn't check that the project belongs to the signed-in user, so one user can archive another user's project. + +FAIL if the review doesn't report that. diff --git a/evals/multi-lens-review/archive-projects/graders/flags-email-scope-creep.md b/evals/multi-lens-review/archive-projects/graders/flags-email-scope-creep.md new file mode 100644 index 0000000..7a89693 --- /dev/null +++ b/evals/multi-lens-review/archive-projects/graders/flags-email-scope-creep.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +This is a code review of a branch built from `docs/specs/archive-projects.md`. Its acceptance criteria cover archiving a project from its page and listing archived projects. Nothing in them mentions email. The branch also adds `ProjectMailer.archived`, which emails the owner when a project is archived. + +PASS if the review flags that archive email (`ProjectMailer`) as something the spec didn't ask for. + +FAIL if the review doesn't flag the email as outside the spec. diff --git a/evals/multi-lens-review/archive-projects/graders/no-edits.md b/evals/multi-lens-review/archive-projects/graders/no-edits.md new file mode 100644 index 0000000..903f19f --- /dev/null +++ b/evals/multi-lens-review/archive-projects/graders/no-edits.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: Edit +min: 0 +max: 0 +--- diff --git a/evals/multi-lens-review/archive-projects/graders/skill-fired.md b/evals/multi-lens-review/archive-projects/graders/skill-fired.md new file mode 100644 index 0000000..34023bf --- /dev/null +++ b/evals/multi-lens-review/archive-projects/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?multi-lens-review"' +--- diff --git a/evals/multi-lens-review/archive-projects/prompt.md b/evals/multi-lens-review/archive-projects/prompt.md new file mode 100644 index 0000000..3d75f46 --- /dev/null +++ b/evals/multi-lens-review/archive-projects/prompt.md @@ -0,0 +1,8 @@ +--- +description: A branch with a missing ownership check and an email nobody asked for gets both flagged, and the skill asks which findings to apply instead of fixing them. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Agent] +--- + +Review this branch before I open a PR. diff --git a/evals/multi-lens-review/empty-diff/case.yaml b/evals/multi-lens-review/empty-diff/case.yaml new file mode 100644 index 0000000..dce4efe --- /dev/null +++ b/evals/multi-lens-review/empty-diff/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: multi-lens-review-empty-diff +context: + scaffold_script: fixture.sh diff --git a/evals/multi-lens-review/empty-diff/fixture.sh b/evals/multi-lens-review/empty-diff/fixture.sh new file mode 100755 index 0000000..3b2ad58 --- /dev/null +++ b/evals/multi-lens-review/empty-diff/fixture.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +bash "$(dirname "$0")/../rails-app.sh" + +mkdir -p docs/specs + +cat > docs/specs/project-due-dates.md <<'MD' +# Project due dates + +Owners can give a project a due date and see it on the projects list. + +## Acceptance criteria + +- [ ] Given I'm editing a project, when I set a due date and save, then I see that date on the project's page. +- [ ] Given a project has a due date, when I view my projects list, then I see the date next to its name. +MD + +git add -A +git commit -q -m "Add SPEC for project due dates" + +git remote add origin git@github.com:acme/tracker.git +git update-ref refs/remotes/origin/main main +git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main + +git checkout -q -b project-due-dates diff --git a/evals/multi-lens-review/empty-diff/graders/no-agents-launched.md b/evals/multi-lens-review/empty-diff/graders/no-agents-launched.md new file mode 100644 index 0000000..96f538b --- /dev/null +++ b/evals/multi-lens-review/empty-diff/graders/no-agents-launched.md @@ -0,0 +1,6 @@ +--- +type: regex +target: trace +pattern: '"type":"tool_use","id":"[^"]*","name":"(?:Agent|Task)"' +match: not_contains +--- diff --git a/evals/multi-lens-review/empty-diff/graders/no-invented-findings.md b/evals/multi-lens-review/empty-diff/graders/no-invented-findings.md new file mode 100644 index 0000000..15c5b9b --- /dev/null +++ b/evals/multi-lens-review/empty-diff/graders/no-invented-findings.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The user asked for a review of a branch that has no changes compared with `main`. + +PASS if the reply reports no findings about the code. + +FAIL if it lists any finding about the code, such as a bug, a convention issue, or a missing feature from `docs/specs/project-due-dates.md`. diff --git a/evals/multi-lens-review/empty-diff/graders/says-nothing-to-review.md b/evals/multi-lens-review/empty-diff/graders/says-nothing-to-review.md new file mode 100644 index 0000000..0dfd7a6 --- /dev/null +++ b/evals/multi-lens-review/empty-diff/graders/says-nothing-to-review.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The user asked for a review of branch `project-due-dates`. That branch has no commits and no changes compared with `main`. + +PASS if the reply says the branch has no changes against `main`, so there's nothing to review. + +FAIL if it doesn't say that. diff --git a/evals/multi-lens-review/empty-diff/graders/skill-fired.md b/evals/multi-lens-review/empty-diff/graders/skill-fired.md new file mode 100644 index 0000000..34023bf --- /dev/null +++ b/evals/multi-lens-review/empty-diff/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?multi-lens-review"' +--- diff --git a/evals/multi-lens-review/empty-diff/prompt.md b/evals/multi-lens-review/empty-diff/prompt.md new file mode 100644 index 0000000..ee464ea --- /dev/null +++ b/evals/multi-lens-review/empty-diff/prompt.md @@ -0,0 +1,8 @@ +--- +description: A branch with no changes against main gets a plain "nothing to review", with no agents launched and no findings made up from the code around it. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Agent] +--- + +Review this branch before I open a PR. diff --git a/evals/multi-lens-review/includes-vs-joins-question/graders/criteria.md b/evals/multi-lens-review/includes-vs-joins-question/graders/criteria.md new file mode 100644 index 0000000..fffdba9 --- /dev/null +++ b/evals/multi-lens-review/includes-vs-joins-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the answer says `includes` loads the associated records along with the parent records, and `joins` only joins the tables without loading the associated records. + +FAIL if it gets either one wrong, or offers to review code instead of answering. diff --git a/evals/multi-lens-review/includes-vs-joins-question/graders/skill-not-fired.md b/evals/multi-lens-review/includes-vs-joins-question/graders/skill-not-fired.md new file mode 100644 index 0000000..2f02ebe --- /dev/null +++ b/evals/multi-lens-review/includes-vs-joins-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?multi-lens-review"' +min: 0 +max: 0 +--- diff --git a/evals/multi-lens-review/includes-vs-joins-question/prompt.md b/evals/multi-lens-review/includes-vs-joins-question/prompt.md new file mode 100644 index 0000000..a26c0a0 --- /dev/null +++ b/evals/multi-lens-review/includes-vs-joins-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: multi-lens-review-includes-vs-joins-question +description: A general ActiveRecord question shouldn't trigger the review skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +In ActiveRecord, what's the difference between `includes` and `joins`? diff --git a/evals/multi-lens-review/rails-app.sh b/evals/multi-lens-review/rails-app.sh new file mode 100755 index 0000000..1b5f3bc --- /dev/null +++ b/evals/multi-lens-review/rails-app.sh @@ -0,0 +1,229 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +mkdir -p app/controllers app/models app/mailers app/views/projects config db test/controllers test/fixtures + +cat > Gemfile <<'RUBY' +source "https://rubygems.org" + +gem "rails", "~> 7.1" +gem "pg" +RUBY + +cat > config/application.rb <<'RUBY' +require_relative "boot" +require "rails/all" + +module Tracker + class Application < Rails::Application + config.load_defaults 7.1 + end +end +RUBY + +cat > config/routes.rb <<'RUBY' +Rails.application.routes.draw do + resource :session, only: [:new, :create, :destroy] + resources :projects + root "projects#index" +end +RUBY + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[7.1].define(version: 2026_09_01_120000) do + create_table "users", force: :cascade do |t| + t.string "email", null: false + t.string "password_digest", null: false + t.timestamps + end + + create_table "projects", force: :cascade do |t| + t.references "user", null: false, foreign_key: true + t.string "name", null: false + t.text "description" + t.timestamps + end +end +RUBY + +cat > app/models/user.rb <<'RUBY' +class User < ApplicationRecord + has_secure_password + has_many :projects, dependent: :destroy +end +RUBY + +cat > app/models/project.rb <<'RUBY' +class Project < ApplicationRecord + belongs_to :user + + validates :name, presence: true +end +RUBY + +cat > app/mailers/application_mailer.rb <<'RUBY' +class ApplicationMailer < ActionMailer::Base + default from: "tracker@example.com" + layout "mailer" +end +RUBY + +cat > app/controllers/application_controller.rb <<'RUBY' +class ApplicationController < ActionController::Base + before_action :require_login + + private + + def current_user + @current_user ||= User.find_by(id: session[:user_id]) + end + helper_method :current_user + + def require_login + redirect_to new_session_path unless current_user + end +end +RUBY + +cat > app/controllers/projects_controller.rb <<'RUBY' +class ProjectsController < ApplicationController + before_action :set_project, only: [:show, :edit, :update, :destroy] + + def index + @projects = current_user.projects.order(:name) + end + + def show + end + + def new + @project = current_user.projects.new + end + + def create + @project = current_user.projects.new(project_params) + + if @project.save + redirect_to @project, notice: "Project created." + else + render :new, status: :unprocessable_entity + end + end + + def edit + end + + def update + if @project.update(project_params) + redirect_to @project, notice: "Project updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @project.destroy + redirect_to projects_path, notice: "Project deleted." + end + + private + + def set_project + @project = current_user.projects.find(params[:id]) + end + + def project_params + params.require(:project).permit(:name, :description) + end +end +RUBY + +cat > app/views/projects/index.html.erb <<'ERB' +

Projects

+ + + +<%= link_to "New project", new_project_path %> +ERB + +cat > app/views/projects/show.html.erb <<'ERB' +

<%= @project.name %>

+ +

<%= @project.description %>

+ +<%= link_to "Edit", edit_project_path(@project) %> +<%= button_to "Delete", @project, method: :delete %> +ERB + +cat > test/test_helper.rb <<'RUBY' +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +class ActiveSupport::TestCase + fixtures :all +end + +class ActionDispatch::IntegrationTest + def sign_in_as(user) + post session_path, params: { email: user.email, password: "password" } + end +end +RUBY + +cat > test/fixtures/users.yml <<'YAML' +alice: + email: alice@example.com + password_digest: <%= BCrypt::Password.create("password") %> + +bob: + email: bob@example.com + password_digest: <%= BCrypt::Password.create("password") %> +YAML + +cat > test/fixtures/projects.yml <<'YAML' +website: + user: alice + name: Website + +mobile_app: + user: bob + name: Mobile app +YAML + +cat > test/controllers/projects_controller_test.rb <<'RUBY' +require "test_helper" + +class ProjectsControllerTest < ActionDispatch::IntegrationTest + test "lists only my projects" do + sign_in_as users(:alice) + + get projects_path + + assert_select "li", text: "Website" + assert_select "li", text: "Mobile app", count: 0 + end + + test "can't see someone else's project" do + sign_in_as users(:alice) + + get project_path(projects(:mobile_app)) + + assert_response :not_found + end +end +RUBY + +git add -A +git commit -q -m "Initial app" diff --git a/evals/pr/auto-eli5-notes/case.yaml b/evals/pr/auto-eli5-notes/case.yaml new file mode 100644 index 0000000..af0e1f3 --- /dev/null +++ b/evals/pr/auto-eli5-notes/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: pr-auto-eli5-notes +context: + scaffold_script: scaffold.sh diff --git a/evals/pr/auto-eli5-notes/graders/drawing-narrow.md b/evals/pr/auto-eli5-notes/graders/drawing-narrow.md new file mode 100644 index 0000000..2ca0a22 --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/drawing-narrow.md @@ -0,0 +1,6 @@ +--- +type: regex +pattern: '^(?=[^\n]*-->)[^\n]{61,}$' +flags: m +match: not_contains +--- diff --git a/evals/pr/auto-eli5-notes/graders/flags-repeat-email.md b/evals/pr/auto-eli5-notes/graders/flags-repeat-email.md new file mode 100644 index 0000000..74db16d --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/flags-repeat-email.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The branch adds `after_save :send_shipped_email, if: -> { shipped_at.present? }` to `Order`. Once an order has shipped, every later save sends the shipped email again, for example when an admin edits the order's notes. + +PASS if the reply, in the PR body or its line notes, points out that the shipped email can go out again on later saves of a shipped order. + +FAIL if neither points that out. diff --git a/evals/pr/auto-eli5-notes/graders/no-questions.md b/evals/pr/auto-eli5-notes/graders/no-questions.md new file mode 100644 index 0000000..2f469db --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/no-questions.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: AskUserQuestion +min: 0 +max: 0 +--- diff --git a/evals/pr/auto-eli5-notes/graders/notes-analogy.md b/evals/pr/auto-eli5-notes/graders/notes-analogy.md new file mode 100644 index 0000000..3d63972 --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/notes-analogy.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Find the line note about the shipped email going out again when a shipped order is saved later. + +PASS if that note compares the problem to something from everyday life, like a doorbell, an alarm, or a stamp, where something fires again after the first time. + +FAIL if it has no such comparison, or there's no such note. diff --git a/evals/pr/auto-eli5-notes/graders/notes-drawing.md b/evals/pr/auto-eli5-notes/graders/notes-drawing.md new file mode 100644 index 0000000..fd46c51 --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/notes-drawing.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Find the line note about the shipped email going out again when a shipped order is saved later. + +PASS if that note has a plain-text drawing in a code block, with arrows, showing the order shipping and then the email going out again on a later change. + +FAIL if it has no drawing, the drawing shows something else, or there's no such note. diff --git a/evals/pr/auto-eli5-notes/graders/notes-name-model.md b/evals/pr/auto-eli5-notes/graders/notes-name-model.md new file mode 100644 index 0000000..27e11ee --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/notes-name-model.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Notes are the risks, tradeoffs, and open questions the reply ties to a file and line, such as `app/models/order.rb:4`. + +PASS if every note says Claude wrote it and names the specific model, such as "Claude Opus 5.5", "Claude Sonnet 4.5", or a model ID like `claude-opus-5-5`; any model name or ID counts, even one you don't recognize. Each note carries its own line, since each one shows up on GitHub on its own. + +FAIL if any note lacks that line, says only "Claude" or "Claude Code" with no model, or there are no notes. diff --git a/evals/pr/auto-eli5-notes/graders/notes-plain-version.md b/evals/pr/auto-eli5-notes/graders/notes-plain-version.md new file mode 100644 index 0000000..404af08 --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/notes-plain-version.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Find the line note about the shipped email going out again when a shipped order is saved later. It starts with a technical sentence that names code. Look at the paragraph that follows it. + +PASS if that paragraph tells what happens to a customer or staff member in everyday words, with no names in backticks and no programmer words like callback, mailer, enqueue, column, or migration. + +FAIL if there's no such paragraph, it uses one of those, or there's no such note. diff --git a/evals/pr/auto-eli5-notes/graders/notes-stay-technical.md b/evals/pr/auto-eli5-notes/graders/notes-stay-technical.md new file mode 100644 index 0000000..1650290 --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/notes-stay-technical.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Find the line note about the shipped email going out again when a shipped order is saved later. It starts with a label like `**Risk:**`. + +PASS if that note's first sentence names code, like `after_save`, `shipped_at`, `ship!`, or `OrderMailer`. + +FAIL if it doesn't, or there's no such note. diff --git a/evals/pr/auto-eli5-notes/graders/skill-fired.md b/evals/pr/auto-eli5-notes/graders/skill-fired.md new file mode 100644 index 0000000..a8738a8 --- /dev/null +++ b/evals/pr/auto-eli5-notes/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?pr"' +--- diff --git a/evals/pr/auto-eli5-notes/prompt.md b/evals/pr/auto-eli5-notes/prompt.md new file mode 100644 index 0000000..977d8db --- /dev/null +++ b/evals/pr/auto-eli5-notes/prompt.md @@ -0,0 +1,8 @@ +--- +description: Run unattended, each line note keeps its technical sentence for the engineer and adds a plain-English version, the /eli5 way, with an everyday analogy and an ASCII drawing where the shape helps. +max_turns: 60 +timeout_seconds: 1200 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Agent, Write, AskUserQuestion] +--- + +Run /pr --auto on this branch. Nobody is watching; your reply gets posted to the team channel. diff --git a/evals/pr/auto-eli5-notes/scaffold.sh b/evals/pr/auto-eli5-notes/scaffold.sh new file mode 100755 index 0000000..8974318 --- /dev/null +++ b/evals/pr/auto-eli5-notes/scaffold.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" + +git init -q --bare .origin.git +echo .origin.git >> .git/info/exclude +git remote set-url origin "$PWD/.origin.git" +git push -q origin main diff --git a/evals/pr/auto-links-issue/case.yaml b/evals/pr/auto-links-issue/case.yaml new file mode 100644 index 0000000..f358424 --- /dev/null +++ b/evals/pr/auto-links-issue/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: pr-auto-links-issue +context: + scaffold_script: scaffold.sh diff --git a/evals/pr/auto-links-issue/graders/closes-issue.md b/evals/pr/auto-links-issue/graders/closes-issue.md new file mode 100644 index 0000000..2ba7fbe --- /dev/null +++ b/evals/pr/auto-links-issue/graders/closes-issue.md @@ -0,0 +1,11 @@ +--- +type: llm +--- + +The branch is named `42-email-when-order-ships`. Nothing else in the repo names an issue. + +The PR body is the description the reply hands back, usually in a fenced block. Judge only the body. + +PASS if the body has a line that links issue 42 with a keyword GitHub closes it on, like `Closes #42`, `Fixes #42`, or `Resolves #42`, and names no other issue number. + +FAIL if the body doesn't link issue 42, links it without a closing keyword, names another issue, or there is no body. diff --git a/evals/pr/auto-links-issue/graders/no-questions.md b/evals/pr/auto-links-issue/graders/no-questions.md new file mode 100644 index 0000000..2f469db --- /dev/null +++ b/evals/pr/auto-links-issue/graders/no-questions.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: AskUserQuestion +min: 0 +max: 0 +--- diff --git a/evals/pr/auto-links-issue/graders/skill-fired.md b/evals/pr/auto-links-issue/graders/skill-fired.md new file mode 100644 index 0000000..a8738a8 --- /dev/null +++ b/evals/pr/auto-links-issue/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?pr"' +--- diff --git a/evals/pr/auto-links-issue/prompt.md b/evals/pr/auto-links-issue/prompt.md new file mode 100644 index 0000000..59fca51 --- /dev/null +++ b/evals/pr/auto-links-issue/prompt.md @@ -0,0 +1,8 @@ +--- +description: The branch is named for issue 42, so the body ends with a line that closes it, and names no other issue. +max_turns: 60 +timeout_seconds: 1200 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Agent, Write, AskUserQuestion] +--- + +Run /pr --auto on this branch. Nobody is watching; your reply gets posted to the team channel. diff --git a/evals/pr/auto-links-issue/scaffold.sh b/evals/pr/auto-links-issue/scaffold.sh new file mode 100755 index 0000000..dd86b36 --- /dev/null +++ b/evals/pr/auto-links-issue/scaffold.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" +git branch -q -m 42-email-when-order-ships + +git init -q --bare .origin.git +echo .origin.git >> .git/info/exclude +git remote set-url origin "$PWD/.origin.git" +git push -q origin main diff --git a/evals/pr/auto-pr-template/case.yaml b/evals/pr/auto-pr-template/case.yaml new file mode 100644 index 0000000..c420aae --- /dev/null +++ b/evals/pr/auto-pr-template/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: pr-auto-pr-template +context: + scaffold_script: scaffold.sh diff --git a/evals/pr/auto-pr-template/graders/body-names-model.md b/evals/pr/auto-pr-template/graders/body-names-model.md new file mode 100644 index 0000000..4dfdd56 --- /dev/null +++ b/evals/pr/auto-pr-template/graders/body-names-model.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The PR body is the description the reply hands back, usually in a fenced block. Notes tied to a file and line, and anything after the fenced block, are not the body. + +PASS if the body's last paragraph says Claude wrote it and names the specific model, such as "Claude Opus 5.5", "Claude Sonnet 4.5", or a model ID like `claude-opus-5-5`. Any model name or ID counts, even one you don't recognize. The paragraph may wrap onto two lines. + +FAIL if the body has no such paragraph, it says only "Claude" or "Claude Code" with no model, or other body content (a checklist, a `Closes` line) comes after it. diff --git a/evals/pr/auto-pr-template/graders/follows-template.md b/evals/pr/auto-pr-template/graders/follows-template.md new file mode 100644 index 0000000..47a3ef2 --- /dev/null +++ b/evals/pr/auto-pr-template/graders/follows-template.md @@ -0,0 +1,11 @@ +--- +type: llm +--- + +The repo's `.github/pull_request_template.md` has three sections, in this order: `## Why`, `## How to check it`, `## Checklist`. + +The PR body is the description the reply hands back, usually in a fenced block. Judge only the body. + +PASS if the body has those three headings, in that order, each with content under it, and adds no headings of its own. + +FAIL if a heading is missing, renamed, out of order, or empty, the body adds a heading the template doesn't have, or there is no body. diff --git a/evals/pr/auto-pr-template/graders/help-center-unticked.md b/evals/pr/auto-pr-template/graders/help-center-unticked.md new file mode 100644 index 0000000..91a5ef3 --- /dev/null +++ b/evals/pr/auto-pr-template/graders/help-center-unticked.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '- \[ \] Help center article updated' +match: contains +--- diff --git a/evals/pr/auto-pr-template/graders/keeps-tests-item.md b/evals/pr/auto-pr-template/graders/keeps-tests-item.md new file mode 100644 index 0000000..efc30bc --- /dev/null +++ b/evals/pr/auto-pr-template/graders/keeps-tests-item.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '- \[[ xX]\] Tests cover the change' +match: contains +--- diff --git a/evals/pr/auto-pr-template/graders/no-questions.md b/evals/pr/auto-pr-template/graders/no-questions.md new file mode 100644 index 0000000..2f469db --- /dev/null +++ b/evals/pr/auto-pr-template/graders/no-questions.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: AskUserQuestion +min: 0 +max: 0 +--- diff --git a/evals/pr/auto-pr-template/graders/no-template-comments.md b/evals/pr/auto-pr-template/graders/no-template-comments.md new file mode 100644 index 0000000..1f176d5 --- /dev/null +++ b/evals/pr/auto-pr-template/graders/no-template-comments.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: " + +## How to check it + + + +## Checklist + +- [ ] Tests cover the change +- [ ] Help center article updated +MD +commit -m "Add a PR template" +git checkout -q shipping-emails +git rebase -q main + +git init -q --bare .origin.git +echo .origin.git >> .git/info/exclude +git remote set-url origin "$PWD/.origin.git" +git push -q origin main diff --git a/evals/pr/auto-screenshots/case.yaml b/evals/pr/auto-screenshots/case.yaml new file mode 100644 index 0000000..74af1f7 --- /dev/null +++ b/evals/pr/auto-screenshots/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: pr-auto-screenshots +context: + scaffold_script: scaffold.sh diff --git a/evals/pr/auto-screenshots/graders/embeds-url.md b/evals/pr/auto-screenshots/graders/embeds-url.md new file mode 100644 index 0000000..54f2dd4 --- /dev/null +++ b/evals/pr/auto-screenshots/graders/embeds-url.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '!\[[^\]]*\]\(https://example\.com/shipped-email\.png\)' +--- diff --git a/evals/pr/auto-screenshots/graders/no-own-images.md b/evals/pr/auto-screenshots/graders/no-own-images.md new file mode 100644 index 0000000..ecb7bbb --- /dev/null +++ b/evals/pr/auto-screenshots/graders/no-own-images.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Bash +input_match: '\.png\b(?!\))|pr-screenshots|hash-object' +min: 0 +max: 0 +--- diff --git a/evals/pr/auto-screenshots/graders/no-questions.md b/evals/pr/auto-screenshots/graders/no-questions.md new file mode 100644 index 0000000..2f469db --- /dev/null +++ b/evals/pr/auto-screenshots/graders/no-questions.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: AskUserQuestion +min: 0 +max: 0 +--- diff --git a/evals/pr/auto-screenshots/graders/skill-fired.md b/evals/pr/auto-screenshots/graders/skill-fired.md new file mode 100644 index 0000000..a8738a8 --- /dev/null +++ b/evals/pr/auto-screenshots/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?pr"' +--- diff --git a/evals/pr/auto-screenshots/prompt.md b/evals/pr/auto-screenshots/prompt.md new file mode 100644 index 0000000..55f792e --- /dev/null +++ b/evals/pr/auto-screenshots/prompt.md @@ -0,0 +1,8 @@ +--- +description: Screenshot URLs passed with --screenshots get embedded in the body as-is, and the skill takes, uploads, and commits no images of its own. +max_turns: 60 +timeout_seconds: 1200 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Agent, Write, AskUserQuestion] +--- + +Run /pr --auto --screenshots https://example.com/shipped-email.png on this branch. Nobody is watching; your reply gets posted to the team channel. diff --git a/evals/pr/auto-screenshots/scaffold.sh b/evals/pr/auto-screenshots/scaffold.sh new file mode 100755 index 0000000..8974318 --- /dev/null +++ b/evals/pr/auto-screenshots/scaffold.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" + +git init -q --bare .origin.git +echo .origin.git >> .git/info/exclude +git remote set-url origin "$PWD/.origin.git" +git push -q origin main diff --git a/evals/pr/auto-shipping-emails/case.yaml b/evals/pr/auto-shipping-emails/case.yaml new file mode 100644 index 0000000..2d8d2e8 --- /dev/null +++ b/evals/pr/auto-shipping-emails/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: pr-auto-shipping-emails +context: + scaffold_script: scaffold.sh diff --git a/evals/pr/auto-shipping-emails/graders/body-names-model.md b/evals/pr/auto-shipping-emails/graders/body-names-model.md new file mode 100644 index 0000000..4dfdd56 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/body-names-model.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The PR body is the description the reply hands back, usually in a fenced block. Notes tied to a file and line, and anything after the fenced block, are not the body. + +PASS if the body's last paragraph says Claude wrote it and names the specific model, such as "Claude Opus 5.5", "Claude Sonnet 4.5", or a model ID like `claude-opus-5-5`. Any model name or ID counts, even one you don't recognize. The paragraph may wrap onto two lines. + +FAIL if the body has no such paragraph, it says only "Claude" or "Claude Code" with no model, or other body content (a checklist, a `Closes` line) comes after it. diff --git a/evals/pr/auto-shipping-emails/graders/flags-repeat-email.md b/evals/pr/auto-shipping-emails/graders/flags-repeat-email.md new file mode 100644 index 0000000..74db16d --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/flags-repeat-email.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The branch adds `after_save :send_shipped_email, if: -> { shipped_at.present? }` to `Order`. Once an order has shipped, every later save sends the shipped email again, for example when an admin edits the order's notes. + +PASS if the reply, in the PR body or its line notes, points out that the shipped email can go out again on later saves of a shipped order. + +FAIL if neither points that out. diff --git a/evals/pr/auto-shipping-emails/graders/hands-back-body.md b/evals/pr/auto-shipping-emails/graders/hands-back-body.md new file mode 100644 index 0000000..8b09af8 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/hands-back-body.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The remote is a local directory, not GitHub, so no PR can be opened. + +PASS if the reply says the PR wasn't opened and why, and includes a suggested title and a complete PR body in a fenced block, ready to paste. + +FAIL if the reply claims a PR was opened, asks the user to write the description, or leaves out the title or the body. diff --git a/evals/pr/auto-shipping-emails/graders/no-invented-issue.md b/evals/pr/auto-shipping-emails/graders/no-invented-issue.md new file mode 100644 index 0000000..f254ed0 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/no-invented-issue.md @@ -0,0 +1,6 @@ +--- +type: regex +pattern: '\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?|refs?|part of)\s+(?:[\w.-]+/[\w.-]+)?#\d+' +flags: i +match: not_contains +--- diff --git a/evals/pr/auto-shipping-emails/graders/no-paths-or-shas.md b/evals/pr/auto-shipping-emails/graders/no-paths-or-shas.md new file mode 100644 index 0000000..a0ed74b --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/no-paths-or-shas.md @@ -0,0 +1,11 @@ +--- +type: llm +--- + +The PR body is the description the reply hands back, usually in a fenced block; a title on its first line is fine. Notes tied to a file and line, like `app/models/order.rb:4: **Risk:** ...`, are line notes, not the body, even when they're meant to be posted on the PR. Judge only the body. + +The body may end with a line saying which Claude model wrote it. That line is meant to be there; judge the body without it. + +PASS if the body names no file paths (like `app/models/order.rb` or `docs/specs/shipping.md`) and no commit SHAs (like `e5aede9`). + +FAIL if the body contains a file path or a commit SHA, even in parentheses as a source, or there is no body. diff --git a/evals/pr/auto-shipping-emails/graders/no-questions.md b/evals/pr/auto-shipping-emails/graders/no-questions.md new file mode 100644 index 0000000..2f469db --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/no-questions.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: AskUserQuestion +min: 0 +max: 0 +--- diff --git a/evals/pr/auto-shipping-emails/graders/no-start-with.md b/evals/pr/auto-shipping-emails/graders/no-start-with.md new file mode 100644 index 0000000..5017114 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/no-start-with.md @@ -0,0 +1,6 @@ +--- +type: regex +pattern: '\bstart (?:with|by reading|reading|here)\b' +flags: i +match: not_contains +--- diff --git a/evals/pr/auto-shipping-emails/graders/notes-name-model.md b/evals/pr/auto-shipping-emails/graders/notes-name-model.md new file mode 100644 index 0000000..27e11ee --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/notes-name-model.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Notes are the risks, tradeoffs, and open questions the reply ties to a file and line, such as `app/models/order.rb:4`. + +PASS if every note says Claude wrote it and names the specific model, such as "Claude Opus 5.5", "Claude Sonnet 4.5", or a model ID like `claude-opus-5-5`; any model name or ID counts, even one you don't recognize. Each note carries its own line, since each one shows up on GitHub on its own. + +FAIL if any note lacks that line, says only "Claude" or "Claude Code" with no model, or there are no notes. diff --git a/evals/pr/auto-shipping-emails/graders/notes-on-lines.md b/evals/pr/auto-shipping-emails/graders/notes-on-lines.md new file mode 100644 index 0000000..9695f02 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/notes-on-lines.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the reply lists at least one note tied to a file and line in the branch's diff, such as `app/models/order.rb:4`, and labeled as a risk, tradeoff, or open question. + +FAIL if risks and tradeoffs only appear as a list in the PR body, or there are no notes. diff --git a/evals/pr/auto-shipping-emails/graders/plain-english.md b/evals/pr/auto-shipping-emails/graders/plain-english.md new file mode 100644 index 0000000..19b8337 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/plain-english.md @@ -0,0 +1,13 @@ +--- +type: llm +--- + +Picture the support lead at this shop. They answer customer emails and have never read the code. + +The PR body is the description the reply hands back, usually in a fenced block; a title on its first line is fine. Notes tied to a file and line, like `app/models/order.rb:4: **Risk:** ...`, are line notes, not the body, even when they're meant to be posted on the PR. Judge only the body. + +The body may end with a line saying which Claude model wrote it. That line is meant to be there; judge the body without it. + +PASS if that person could read the body and know what changes for customers or staff, and why. It names no classes, methods, or other code (like `Order`, `after_save`, or `OrderMailer`) and uses no programmer terms (like callback, mailer, migration, column, or enqueue). + +FAIL if the body uses any code name or programmer term, describes the change in terms of the code instead of the people using the shop, or there is no body. diff --git a/evals/pr/auto-shipping-emails/graders/skill-fired.md b/evals/pr/auto-shipping-emails/graders/skill-fired.md new file mode 100644 index 0000000..a8738a8 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?pr"' +--- diff --git a/evals/pr/auto-shipping-emails/graders/tries-push.md b/evals/pr/auto-shipping-emails/graders/tries-push.md new file mode 100644 index 0000000..0561003 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/tries-push.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: Bash +input_match: '\bpush\s+(?:-\S+\s+)*origin\b' +min: 1 +--- diff --git a/evals/pr/auto-shipping-emails/graders/why-from-commits.md b/evals/pr/auto-shipping-emails/graders/why-from-commits.md new file mode 100644 index 0000000..eb5fd31 --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/why-from-commits.md @@ -0,0 +1,11 @@ +--- +type: llm +--- + +The commit bodies say: support checks the courier site by hand to see whether an order has left the warehouse, most "where's my order?" emails to support arrive the day after an order ships, and telling the customer as it ships should cut those down. + +Judge only the PR body, not the line notes or the rest of the reply. Statements about what the code does, or doesn't do yet, aren't reasons; ignore them. + +PASS if the body gives at least one of those reasons, in any wording, and no reason that isn't among them. + +FAIL if the body gives a reason the commits don't, such as a customer request or a metric, or gives no reason, or there is no body. diff --git a/evals/pr/auto-shipping-emails/graders/why-not-what.md b/evals/pr/auto-shipping-emails/graders/why-not-what.md new file mode 100644 index 0000000..3b4357e --- /dev/null +++ b/evals/pr/auto-shipping-emails/graders/why-not-what.md @@ -0,0 +1,11 @@ +--- +type: llm +--- + +Judge only the PR body, the description the reply hands back, usually in a fenced block. Line notes tied to a file and line aren't the body. + +The body may end with a line saying which Claude model wrote it. That line is meant to be there; judge the body without it. + +PASS if the PR body explains why the change exists and stays short, under about 15 lines of prose. A sentence on what changes for customers or staff is fine. + +FAIL if the body walks through what changed file by file, lists the files or methods added, or repeats what the diff already shows. diff --git a/evals/pr/auto-shipping-emails/prompt.md b/evals/pr/auto-shipping-emails/prompt.md new file mode 100644 index 0000000..e5ec58e --- /dev/null +++ b/evals/pr/auto-shipping-emails/prompt.md @@ -0,0 +1,8 @@ +--- +description: Run unattended against a remote that isn't GitHub, the skill writes the body itself from the commits, flags the repeat-email risk, tries to push the branch, and hands back the title and body instead of asking anyone anything. +max_turns: 60 +timeout_seconds: 1200 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Agent, Write, AskUserQuestion] +--- + +Run /pr --auto on this branch. Nobody is watching; your reply gets posted to the team channel. diff --git a/evals/pr/auto-shipping-emails/scaffold.sh b/evals/pr/auto-shipping-emails/scaffold.sh new file mode 100755 index 0000000..8974318 --- /dev/null +++ b/evals/pr/auto-shipping-emails/scaffold.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" + +git init -q --bare .origin.git +echo .origin.git >> .git/info/exclude +git remote set-url origin "$PWD/.origin.git" +git push -q origin main diff --git a/evals/pr/auto-voice/case.yaml b/evals/pr/auto-voice/case.yaml new file mode 100644 index 0000000..24aeb74 --- /dev/null +++ b/evals/pr/auto-voice/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: pr-auto-voice +context: + scaffold_script: scaffold.sh diff --git a/evals/pr/auto-voice/graders/body-names-model.md b/evals/pr/auto-voice/graders/body-names-model.md new file mode 100644 index 0000000..4dfdd56 --- /dev/null +++ b/evals/pr/auto-voice/graders/body-names-model.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The PR body is the description the reply hands back, usually in a fenced block. Notes tied to a file and line, and anything after the fenced block, are not the body. + +PASS if the body's last paragraph says Claude wrote it and names the specific model, such as "Claude Opus 5.5", "Claude Sonnet 4.5", or a model ID like `claude-opus-5-5`. Any model name or ID counts, even one you don't recognize. The paragraph may wrap onto two lines. + +FAIL if the body has no such paragraph, it says only "Claude" or "Claude Code" with no model, or other body content (a checklist, a `Closes` line) comes after it. diff --git a/evals/pr/auto-voice/graders/in-voice.md b/evals/pr/auto-voice/graders/in-voice.md new file mode 100644 index 0000000..d88ff75 --- /dev/null +++ b/evals/pr/auto-voice/graders/in-voice.md @@ -0,0 +1,13 @@ +--- +type: llm +--- + +Steve's PR voice: the body opens with what prompted the change ("Now that ...", "Prior to this ...", "In an effort to ...", or a sentence stating the problem), not with what changed. It speaks as "we" for the team and never as "I". Short paragraphs, no headings. + +The PR body is the description the reply hands back, usually in a fenced block; a title on its first line is fine. Notes tied to a file and line are not the body. Judge only the body. + +The body may end with a line saying which Claude model wrote it. That line is meant to be there; judge the body without it. + +PASS if the body opens with what prompted the change, speaks as "we" (or "us", "our") at least once, never says "I", and has no headings. + +FAIL if it opens with what changed ("Customers now get ...", "Adds ...", "This adds ..."), never speaks as "we", "us", or "our", says "I", adds headings, or there is no body. diff --git a/evals/pr/auto-voice/graders/no-borrowed-claims.md b/evals/pr/auto-voice/graders/no-borrowed-claims.md new file mode 100644 index 0000000..4a39616 --- /dev/null +++ b/evals/pr/auto-voice/graders/no-borrowed-claims.md @@ -0,0 +1,6 @@ +--- +type: regex +pattern: "invoice|PDF|2020" +flags: i +match: not_contains +--- diff --git a/evals/pr/auto-voice/graders/no-paths-or-shas.md b/evals/pr/auto-voice/graders/no-paths-or-shas.md new file mode 100644 index 0000000..a0ed74b --- /dev/null +++ b/evals/pr/auto-voice/graders/no-paths-or-shas.md @@ -0,0 +1,11 @@ +--- +type: llm +--- + +The PR body is the description the reply hands back, usually in a fenced block; a title on its first line is fine. Notes tied to a file and line, like `app/models/order.rb:4: **Risk:** ...`, are line notes, not the body, even when they're meant to be posted on the PR. Judge only the body. + +The body may end with a line saying which Claude model wrote it. That line is meant to be there; judge the body without it. + +PASS if the body names no file paths (like `app/models/order.rb` or `docs/specs/shipping.md`) and no commit SHAs (like `e5aede9`). + +FAIL if the body contains a file path or a commit SHA, even in parentheses as a source, or there is no body. diff --git a/evals/pr/auto-voice/graders/no-questions.md b/evals/pr/auto-voice/graders/no-questions.md new file mode 100644 index 0000000..2f469db --- /dev/null +++ b/evals/pr/auto-voice/graders/no-questions.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: AskUserQuestion +min: 0 +max: 0 +--- diff --git a/evals/pr/auto-voice/graders/notes-no-stiff-words.md b/evals/pr/auto-voice/graders/notes-no-stiff-words.md new file mode 100644 index 0000000..dfda47c --- /dev/null +++ b/evals/pr/auto-voice/graders/notes-no-stiff-words.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '\b(Consider (adding|using|whether)|Ensure|ensure that|It''s worth noting|potential(ly)? (issue|problem)|could lead to|leverage)\b' +match: not_contains +--- diff --git a/evals/pr/auto-voice/graders/notes-say-we.md b/evals/pr/auto-voice/graders/notes-say-we.md new file mode 100644 index 0000000..56a0a1c --- /dev/null +++ b/evals/pr/auto-voice/graders/notes-say-we.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Line notes are the comments tied to a file and line. Each starts with a label like `**Risk:**`, `**Tradeoff:**`, or `**Open question:**`. A note's first paragraph is the one that starts with that label. The PR body is not a note. + +PASS if at least two notes speak as the team in their first paragraph, using "we", "us", or "our" (like "We might want ...", "since we save ...", "we'd send ..."), and no note says "I" anywhere. + +FAIL if fewer than two notes say "we", "us", or "our" in their first paragraph, any note says "I", or there are fewer than two notes. diff --git a/evals/pr/auto-voice/graders/notes-short.md b/evals/pr/auto-voice/graders/notes-short.md new file mode 100644 index 0000000..7b59b73 --- /dev/null +++ b/evals/pr/auto-voice/graders/notes-short.md @@ -0,0 +1,11 @@ +--- +type: llm +--- + +Line notes are the comments tied to a file and line. Each starts with a label like `**Risk:**`, `**Tradeoff:**`, or `**Open question:**`. A note's first paragraph is the one that starts with that label. Ignore everything after it: the plain-English paragraph, any drawing, and the attribution line. + +Count sentences in each note's first paragraph. A question counts as a sentence. A code snippet in a fenced block is not a sentence. + +PASS if every note's first paragraph is one or two sentences. + +FAIL if any note's first paragraph has three or more sentences, or there are no notes. diff --git a/evals/pr/auto-voice/graders/skill-fired.md b/evals/pr/auto-voice/graders/skill-fired.md new file mode 100644 index 0000000..a8738a8 --- /dev/null +++ b/evals/pr/auto-voice/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?pr"' +--- diff --git a/evals/pr/auto-voice/prompt.md b/evals/pr/auto-voice/prompt.md new file mode 100644 index 0000000..0456e28 --- /dev/null +++ b/evals/pr/auto-voice/prompt.md @@ -0,0 +1,8 @@ +--- +description: Run unattended, the skill writes the body and the line notes in Steve's voice from the guide built into it, without borrowing the guide's examples. +max_turns: 60 +timeout_seconds: 1200 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Agent, Write, AskUserQuestion] +--- + +Run /pr --auto on this branch. Nobody is watching; your reply gets posted to the team channel. diff --git a/evals/pr/auto-voice/scaffold.sh b/evals/pr/auto-voice/scaffold.sh new file mode 100755 index 0000000..8974318 --- /dev/null +++ b/evals/pr/auto-voice/scaffold.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" + +git init -q --bare .origin.git +echo .origin.git >> .git/info/exclude +git remote set-url origin "$PWD/.origin.git" +git push -q origin main diff --git a/evals/pr/dirty-tree/case.yaml b/evals/pr/dirty-tree/case.yaml new file mode 100644 index 0000000..7a9e3a3 --- /dev/null +++ b/evals/pr/dirty-tree/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: pr-dirty-tree +context: + scaffold_script: scaffold.sh diff --git a/evals/pr/dirty-tree/graders/head-unmoved.md b/evals/pr/dirty-tree/graders/head-unmoved.md new file mode 100644 index 0000000..7e69e33 --- /dev/null +++ b/evals/pr/dirty-tree/graders/head-unmoved.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: "^[0-9a-f]{40} [0-9a-f]{40} " +flags: m +match: "count:6" +--- diff --git a/evals/pr/dirty-tree/graders/no-push-or-pr-create.md b/evals/pr/dirty-tree/graders/no-push-or-pr-create.md new file mode 100644 index 0000000..ad6524f --- /dev/null +++ b/evals/pr/dirty-tree/graders/no-push-or-pr-create.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Bash +input_match: '\bgit\s+(?:-C\s+\S+\s+)?push\b|\bgh\s+pr\s+create\b' +min: 0 +max: 0 +--- diff --git a/evals/pr/dirty-tree/graders/skill-fired.md b/evals/pr/dirty-tree/graders/skill-fired.md new file mode 100644 index 0000000..a8738a8 --- /dev/null +++ b/evals/pr/dirty-tree/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?pr"' +--- diff --git a/evals/pr/dirty-tree/graders/stops-on-uncommitted.md b/evals/pr/dirty-tree/graders/stops-on-uncommitted.md new file mode 100644 index 0000000..e7f7da1 --- /dev/null +++ b/evals/pr/dirty-tree/graders/stops-on-uncommitted.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The user asked to open a PR. `app/views/order_mailer/shipped.text.erb` has uncommitted changes. + +PASS if a message from Claude to the user says there are uncommitted changes and that it won't open the PR until they're dealt with. + +FAIL if no message says that, or Claude commits, stashes, or discards the changes itself. diff --git a/evals/pr/dirty-tree/prompt.md b/evals/pr/dirty-tree/prompt.md new file mode 100644 index 0000000..45e7e7b --- /dev/null +++ b/evals/pr/dirty-tree/prompt.md @@ -0,0 +1,8 @@ +--- +description: Uncommitted changes in the tree stop the skill before the brief, with nothing committed or pushed. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Edit, Write] +--- + +Can you open a pull request for my shipping emails branch? diff --git a/evals/pr/dirty-tree/scaffold.sh b/evals/pr/dirty-tree/scaffold.sh new file mode 100644 index 0000000..8d254a3 --- /dev/null +++ b/evals/pr/dirty-tree/scaffold.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" + +cat > app/views/order_mailer/shipped.text.erb <<'ERB' +Good news: order #<%= @order.id %> shipped on <%= @order.shipped_at.to_date %>. + +Reply to this email if anything looks wrong. +ERB diff --git a/evals/pr/shipping-emails/case.yaml b/evals/pr/shipping-emails/case.yaml new file mode 100644 index 0000000..8bb745d --- /dev/null +++ b/evals/pr/shipping-emails/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: pr-shipping-emails +context: + scaffold_script: scaffold.sh diff --git a/evals/pr/shipping-emails/graders/asks-user-to-write.md b/evals/pr/shipping-emails/graders/asks-user-to-write.md new file mode 100644 index 0000000..7b32d68 --- /dev/null +++ b/evals/pr/shipping-emails/graders/asks-user-to-write.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +PASS if a message from Claude to the user asks the user to write the PR description themselves. + +FAIL if no message asks that, for example Claude only asks the user to approve or edit a description Claude wrote. diff --git a/evals/pr/shipping-emails/graders/flags-repeat-email.md b/evals/pr/shipping-emails/graders/flags-repeat-email.md new file mode 100644 index 0000000..d68e27a --- /dev/null +++ b/evals/pr/shipping-emails/graders/flags-repeat-email.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The branch adds `after_save :send_shipped_email, if: -> { shipped_at.present? }` to `Order`. Once an order has shipped, every later save sends the shipped email again, for example when an admin edits the order's notes. + +PASS if a message from Claude to the user points out that the shipped email can go out again on later saves of a shipped order. + +FAIL if no message from Claude points that out. diff --git a/evals/pr/shipping-emails/graders/no-drafted-body.md b/evals/pr/shipping-emails/graders/no-drafted-body.md new file mode 100644 index 0000000..221e94d --- /dev/null +++ b/evals/pr/shipping-emails/graders/no-drafted-body.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +PASS if no message from Claude to the user contains a PR description for this branch written by Claude. A suggested title and short notes on what changed and its risks, given as background for the user, don't count. + +FAIL if any message contains a drafted description, a fill-in template (such as Summary / Changes / Testing headings), or an example description. diff --git a/evals/pr/shipping-emails/graders/no-push-or-pr-create.md b/evals/pr/shipping-emails/graders/no-push-or-pr-create.md new file mode 100644 index 0000000..ad6524f --- /dev/null +++ b/evals/pr/shipping-emails/graders/no-push-or-pr-create.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Bash +input_match: '\bgit\s+(?:-C\s+\S+\s+)?push\b|\bgh\s+pr\s+create\b' +min: 0 +max: 0 +--- diff --git a/evals/pr/shipping-emails/graders/skill-fired.md b/evals/pr/shipping-emails/graders/skill-fired.md new file mode 100644 index 0000000..a8738a8 --- /dev/null +++ b/evals/pr/shipping-emails/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?pr"' +--- diff --git a/evals/pr/shipping-emails/prompt.md b/evals/pr/shipping-emails/prompt.md new file mode 100644 index 0000000..e1feaca --- /dev/null +++ b/evals/pr/shipping-emails/prompt.md @@ -0,0 +1,8 @@ +--- +description: A branch whose shipped email re-sends on every later save gets a brief that names that risk, a suggested title, and a request that the user write the description, with no drafted body and nothing pushed. +max_turns: 40 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Bash, Skill, Edit, Write] +--- + +Open a PR for this branch. diff --git a/evals/pr/shipping-emails/scaffold.sh b/evals/pr/shipping-emails/scaffold.sh new file mode 100644 index 0000000..5c1496b --- /dev/null +++ b/evals/pr/shipping-emails/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" diff --git a/evals/pr/shop-app.sh b/evals/pr/shop-app.sh new file mode 100644 index 0000000..82f449c --- /dev/null +++ b/evals/pr/shop-app.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null +commit() { git add -A && git commit -q "$@"; } + +mkdir -p app/models app/mailers app/views/order_mailer app/controllers/admin db/migrate test/models + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[8.0].define(version: 2026_09_01_120000) do + create_table "orders", force: :cascade do |t| + t.string "email", null: false + t.text "notes" + t.timestamps + end +end +RUBY + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + validates :email, presence: true +end +RUBY + +commit -m "Add orders" + +cat > app/mailers/order_mailer.rb <<'RUBY' +class OrderMailer < ApplicationMailer + def receipt(order) + @order = order + mail to: order.email, subject: "Your order ##{order.id}" + end +end +RUBY + +cat > app/controllers/admin/orders_controller.rb <<'RUBY' +class Admin::OrdersController < Admin::BaseController + def update + order = Order.find(params[:id]) + order.update!(params.require(:order).permit(:notes)) + redirect_to admin_order_path(order) + end +end +RUBY + +commit -m "Email a receipt when an order is placed" + +git remote add origin git@github.com:acme/shop.git +git update-ref refs/remotes/origin/main main +git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main + +git checkout -q -b shipping-emails + +cat > db/migrate/20261028100000_add_shipped_at_to_orders.rb <<'RUBY' +class AddShippedAtToOrders < ActiveRecord::Migration[8.0] + def change + add_column :orders, :shipped_at, :datetime + end +end +RUBY + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[8.0].define(version: 2026_10_28_100000) do + create_table "orders", force: :cascade do |t| + t.string "email", null: false + t.text "notes" + t.datetime "shipped_at" + t.timestamps + end +end +RUBY + +commit -m "Add shipped_at to orders" \ + -m "Support checks the courier site by hand to see if an order has left +the warehouse. Recording it on the order is the first step to telling +the customer ourselves." + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + validates :email, presence: true + + after_save :send_shipped_email, if: -> { shipped_at.present? } + + def ship! + update!(shipped_at: Time.current) + end + + private + + def send_shipped_email + OrderMailer.shipped(self).deliver_later + end +end +RUBY + +cat > app/mailers/order_mailer.rb <<'RUBY' +class OrderMailer < ApplicationMailer + def receipt(order) + @order = order + mail to: order.email, subject: "Your order ##{order.id}" + end + + def shipped(order) + @order = order + mail to: order.email, subject: "Order ##{order.id} is on its way" + end +end +RUBY + +cat > app/views/order_mailer/shipped.text.erb <<'ERB' +Good news: order #<%= @order.id %> shipped on <%= @order.shipped_at.to_date %>. +ERB + +commit -m "Email the customer when their order ships" \ + -m "Most \"where's my order?\" emails to support arrive the day after an +order ships. Telling the customer as it ships should cut those down." + +cat > test/models/order_test.rb <<'RUBY' +require "test_helper" + +class OrderTest < ActiveSupport::TestCase + include ActionMailer::TestHelper + + test "shipping an order emails the customer" do + order = Order.create!(email: "sam@example.com") + + assert_enqueued_email_with OrderMailer, :shipped, args: [order] do + order.ship! + end + end +end +RUBY + +commit -m "Test the shipped email" diff --git a/evals/pr/squash-question/graders/criteria.md b/evals/pr/squash-question/graders/criteria.md new file mode 100644 index 0000000..c591007 --- /dev/null +++ b/evals/pr/squash-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the answer gives a working way to squash a branch's commits into one, such as `git rebase -i` against the base branch with the later commits marked `squash` or `fixup`, or `git reset --soft` to the base branch followed by a new commit. + +FAIL if the method wouldn't work, or the answer offers to open a PR instead of answering. diff --git a/evals/pr/squash-question/graders/skill-not-fired.md b/evals/pr/squash-question/graders/skill-not-fired.md new file mode 100644 index 0000000..32b4313 --- /dev/null +++ b/evals/pr/squash-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?pr"' +min: 0 +max: 0 +--- diff --git a/evals/pr/squash-question/prompt.md b/evals/pr/squash-question/prompt.md new file mode 100644 index 0000000..e430fb4 --- /dev/null +++ b/evals/pr/squash-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: pr-squash-question +description: A git question about getting a branch ready for a PR shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +How do I squash all the commits on my branch into one before I open a PR? diff --git a/evals/preparatory-refactor/discount-touches-three-totals/case.yaml b/evals/preparatory-refactor/discount-touches-three-totals/case.yaml new file mode 100644 index 0000000..705b9ea --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: preparatory-refactor-discount-touches-three-totals +context: + scaffold_script: scaffold.sh diff --git a/evals/preparatory-refactor/discount-touches-three-totals/graders/agents-launched.md b/evals/preparatory-refactor/discount-touches-three-totals/graders/agents-launched.md new file mode 100644 index 0000000..d14a4c2 --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/graders/agents-launched.md @@ -0,0 +1,5 @@ +--- +type: regex +target: trace +pattern: '"type":"tool_use","id":"[^"]*","name":"(?:Agent|Task)"' +--- diff --git a/evals/preparatory-refactor/discount-touches-three-totals/graders/extract-before-feature.md b/evals/preparatory-refactor/discount-touches-three-totals/graders/extract-before-feature.md new file mode 100644 index 0000000..3ff963e --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/graders/extract-before-feature.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The discount SPEC changes the order total. Today the total math lives in three copies: `Order#total_cents`, `OrderMailer#receipt`, and `InvoicePdf`. + +PASS if a message from Claude to the user recommends, as a step before building discount codes, putting the total math in one place that the mailer and the invoice call instead of their own copies. + +FAIL if no message from Claude recommends a refactor first. diff --git a/evals/preparatory-refactor/discount-touches-three-totals/graders/head-unmoved.md b/evals/preparatory-refactor/discount-touches-three-totals/graders/head-unmoved.md new file mode 100644 index 0000000..9f40c67 --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/graders/head-unmoved.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: "^[0-9a-f]{40} [0-9a-f]{40} " +flags: m +match: "count:10" +--- diff --git a/evals/preparatory-refactor/discount-touches-three-totals/graders/names-three-copies.md b/evals/preparatory-refactor/discount-touches-three-totals/graders/names-three-copies.md new file mode 100644 index 0000000..c1df971 --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/graders/names-three-copies.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The repo computes the order total (line item subtotal, 8% tax, $5.99 shipping under $50) in three separate copies: `Order#total_cents` in app/models/order.rb, `OrderMailer#receipt` in app/mailers/order_mailer.rb, and the private methods of `InvoicePdf` in app/pdfs/invoice_pdf.rb. + +PASS if a message from Claude to the user says the total math is duplicated and names all three places: Order, OrderMailer, and InvoicePdf. + +FAIL if no message says the math is duplicated, or the messages leave any of the three out. diff --git a/evals/preparatory-refactor/discount-touches-three-totals/graders/no-edits.md b/evals/preparatory-refactor/discount-touches-three-totals/graders/no-edits.md new file mode 100644 index 0000000..903f19f --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/graders/no-edits.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: Edit +min: 0 +max: 0 +--- diff --git a/evals/preparatory-refactor/discount-touches-three-totals/graders/no-writes-in-repo.md b/evals/preparatory-refactor/discount-touches-three-totals/graders/no-writes-in-repo.md new file mode 100644 index 0000000..f416e0f --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/graders/no-writes-in-repo.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Write +input_match: '"file_path"\s*:\s*"[^"]*/(?:app|config|db|docs|test)/' +min: 0 +max: 0 +--- diff --git a/evals/preparatory-refactor/discount-touches-three-totals/graders/skill-fired.md b/evals/preparatory-refactor/discount-touches-three-totals/graders/skill-fired.md new file mode 100644 index 0000000..5a49793 --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?preparatory-refactor"' +--- diff --git a/evals/preparatory-refactor/discount-touches-three-totals/prompt.md b/evals/preparatory-refactor/discount-touches-three-totals/prompt.md new file mode 100644 index 0000000..be880c4 --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/prompt.md @@ -0,0 +1,8 @@ +--- +description: The discount SPEC would change the same order total math in Order, OrderMailer and InvoicePdf, so the skill recommends pulling it into one place first, and changes nothing. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash] +--- + +I'm about to build docs/specs/discount-codes.md. Is there anything I should refactor first so the feature goes in easier? diff --git a/evals/preparatory-refactor/discount-touches-three-totals/scaffold.sh b/evals/preparatory-refactor/discount-touches-three-totals/scaffold.sh new file mode 100644 index 0000000..6bcc39f --- /dev/null +++ b/evals/preparatory-refactor/discount-touches-three-totals/scaffold.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" + +mkdir -p docs/specs +cat > docs/specs/discount-codes.md <<'MD' +# Discount codes + +Customers can enter a discount code at checkout to take a percentage off their order. + +## Behavior + +- A discount code has a code string (like `SPRING10`) and a percent off (1 to 100). +- An order can have at most one discount code. +- The percent comes off the line item subtotal. Tax and the free-shipping threshold use the discounted subtotal. +- The amount we charge, the receipt email, and the PDF invoice all show the same discounted total, with a "Discount" line between subtotal and tax. +- Codes are case-insensitive. + +## Out of scope + +- Expiring codes, usage limits, fixed-amount discounts. +MD + +commit "Add discount codes spec" diff --git a/evals/preparatory-refactor/extract-method-question/graders/criteria.md b/evals/preparatory-refactor/extract-method-question/graders/criteria.md new file mode 100644 index 0000000..03aa777 --- /dev/null +++ b/evals/preparatory-refactor/extract-method-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the reply explains that Extract Method moves a piece of a method into a new, named method that the original method then calls. + +FAIL if it describes something else, or offers to look for refactors in a codebase instead of answering. diff --git a/evals/preparatory-refactor/extract-method-question/graders/skill-not-fired.md b/evals/preparatory-refactor/extract-method-question/graders/skill-not-fired.md new file mode 100644 index 0000000..c519b41 --- /dev/null +++ b/evals/preparatory-refactor/extract-method-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?preparatory-refactor"' +min: 0 +max: 0 +--- diff --git a/evals/preparatory-refactor/extract-method-question/prompt.md b/evals/preparatory-refactor/extract-method-question/prompt.md new file mode 100644 index 0000000..381b191 --- /dev/null +++ b/evals/preparatory-refactor/extract-method-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: preparatory-refactor-extract-method-question +description: A general question about a named refactoring shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +What does the "Extract Method" refactoring mean? Show me a tiny Ruby example. diff --git a/evals/preparatory-refactor/one-line-validation/case.yaml b/evals/preparatory-refactor/one-line-validation/case.yaml new file mode 100644 index 0000000..10e59a2 --- /dev/null +++ b/evals/preparatory-refactor/one-line-validation/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: preparatory-refactor-one-line-validation +context: + scaffold_script: scaffold.sh diff --git a/evals/preparatory-refactor/one-line-validation/graders/proposes-no-refactor.md b/evals/preparatory-refactor/one-line-validation/graders/proposes-no-refactor.md new file mode 100644 index 0000000..71e0b0d --- /dev/null +++ b/evals/preparatory-refactor/one-line-validation/graders/proposes-no-refactor.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The SPEC adds a minimum length of 3 to `Product#name` in app/models/product.rb. The repo also has order total math copied into `Order`, `OrderMailer`, and `InvoicePdf`, which this feature doesn't touch. + +PASS if the reply proposes no refactor at all. A side note that unrelated code could be cleaned up some other time is fine. + +FAIL if it proposes any refactor to do before this feature, such as consolidating the order total math or changing `Product`. diff --git a/evals/preparatory-refactor/one-line-validation/graders/says-no-prep.md b/evals/preparatory-refactor/one-line-validation/graders/says-no-prep.md new file mode 100644 index 0000000..7b1f508 --- /dev/null +++ b/evals/preparatory-refactor/one-line-validation/graders/says-no-prep.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The SPEC adds a minimum length of 3 to `Product#name`. It lands in one line of app/models/product.rb, next to the existing `validates :name, presence: true`. + +PASS if the reply says no refactor is needed before building this feature. + +FAIL if it says a refactor is needed first. diff --git a/evals/preparatory-refactor/one-line-validation/graders/skill-fired.md b/evals/preparatory-refactor/one-line-validation/graders/skill-fired.md new file mode 100644 index 0000000..5a49793 --- /dev/null +++ b/evals/preparatory-refactor/one-line-validation/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?preparatory-refactor"' +--- diff --git a/evals/preparatory-refactor/one-line-validation/prompt.md b/evals/preparatory-refactor/one-line-validation/prompt.md new file mode 100644 index 0000000..6bf643f --- /dev/null +++ b/evals/preparatory-refactor/one-line-validation/prompt.md @@ -0,0 +1,8 @@ +--- +description: The SPEC adds one validation to Product, so the skill says no preparation is needed, even though the repo has unrelated duplication in its order totals. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash] +--- + +I'm about to build docs/specs/product-name-length.md. Is there anything I should refactor first so the feature goes in easier? diff --git a/evals/preparatory-refactor/one-line-validation/scaffold.sh b/evals/preparatory-refactor/one-line-validation/scaffold.sh new file mode 100644 index 0000000..6a5875a --- /dev/null +++ b/evals/preparatory-refactor/one-line-validation/scaffold.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" + +mkdir -p docs/specs +cat > docs/specs/product-name-length.md <<'MD' +# Product name length + +Product names under 3 characters keep slipping into the catalog ("A", "Mg") and look broken on the storefront. + +## Behavior + +- A product name must be at least 3 characters. +- Saving a shorter name fails with Rails' standard length error. +- Existing products are left alone until they're next edited. +MD + +commit "Add product name length spec" diff --git a/evals/preparatory-refactor/shop-app.sh b/evals/preparatory-refactor/shop-app.sh new file mode 100644 index 0000000..3276621 --- /dev/null +++ b/evals/preparatory-refactor/shop-app.sh @@ -0,0 +1,486 @@ +#!/usr/bin/env bash +# Builds a Rails-shaped shop whose order total math is copied into Order, OrderMailer and InvoicePdf. No gems, nothing runs. +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null + +day=0 +commit() { + day=$((day + 1)) + local stamp + stamp="2026-03-$(printf '%02d' "$day")T10:00:00Z" + git add -A + GIT_AUTHOR_DATE="$stamp" GIT_COMMITTER_DATE="$stamp" git commit -q -m "$1" +} + +mkdir -p app/models app/controllers app/mailers app/views/order_mailer app/pdfs config db test/models test/mailers test/pdfs + +cat > Gemfile <<'RUBY' +source "https://rubygems.org" + +gem "rails", "~> 8.0" +gem "sqlite3" +RUBY + +cat > config/application.rb <<'RUBY' +require_relative "boot" +require "rails/all" + +module Shop + class Application < Rails::Application + config.load_defaults 8.0 + config.autoload_paths << Rails.root.join("app/pdfs") + end +end +RUBY + +cat > app/models/application_record.rb <<'RUBY' +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end +RUBY + +cat > app/controllers/application_controller.rb <<'RUBY' +class ApplicationController < ActionController::Base +end +RUBY + +cat > app/mailers/application_mailer.rb <<'RUBY' +class ApplicationMailer < ActionMailer::Base + default from: "orders@shop.example" +end +RUBY + +cat > README.md <<'MD' +# Shop + +A small storefront. Run the tests with `bin/rails test`. +MD + +commit "Set up the shop app" + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[8.0].define(version: 2026_03_02_100000) do + create_table "products", force: :cascade do |t| + t.string "name" + t.integer "price_cents" + t.timestamps + end +end +RUBY + +cat > app/models/product.rb <<'RUBY' +class Product < ApplicationRecord +end +RUBY + +cat > test/models/product_test.rb <<'RUBY' +require "test_helper" + +class ProductTest < ActiveSupport::TestCase + test "saves with a name and price" do + assert Product.new(name: "Mug", price_cents: 1250).save + end +end +RUBY + +commit "Add products" + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[8.0].define(version: 2026_03_03_100000) do + create_table "customers", force: :cascade do |t| + t.string "email", null: false + t.timestamps + end + + create_table "line_items", force: :cascade do |t| + t.references "order", null: false + t.references "product", null: false + t.integer "quantity", null: false, default: 1 + t.integer "unit_price_cents", null: false + t.timestamps + end + + create_table "orders", force: :cascade do |t| + t.references "customer", null: false + t.string "status", null: false, default: "cart" + t.timestamps + end + + create_table "products", force: :cascade do |t| + t.string "name" + t.integer "price_cents" + t.timestamps + end +end +RUBY + +cat > app/models/customer.rb <<'RUBY' +class Customer < ApplicationRecord + has_many :orders +end +RUBY + +cat > app/models/line_item.rb <<'RUBY' +class LineItem < ApplicationRecord + belongs_to :order + belongs_to :product +end +RUBY + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + belongs_to :customer + has_many :line_items, dependent: :destroy + + def total_cents + line_items.sum { |item| item.unit_price_cents * item.quantity } + end +end +RUBY + +cat > app/controllers/checkouts_controller.rb <<'RUBY' +class CheckoutsController < ApplicationController + def create + order = Order.find(params[:order_id]) + PaymentGateway.charge(order.customer, order.total_cents) + order.update!(status: "paid") + redirect_to order_path(order) + end +end +RUBY + +cat > test/models/order_test.rb <<'RUBY' +require "test_helper" + +class OrderTest < ActiveSupport::TestCase + test "total is the sum of its line items" do + order = Order.new + order.line_items.build(unit_price_cents: 1250, quantity: 2) + + assert_equal 2500, order.total_cents + end +end +RUBY + +commit "Add orders and checkout" + +cat > app/mailers/order_mailer.rb <<'RUBY' +class OrderMailer < ApplicationMailer + def receipt(order) + @order = order + @total_cents = order.line_items.sum { |item| item.unit_price_cents * item.quantity } + mail to: order.customer.email, subject: "Your order ##{order.id}" + end +end +RUBY + +cat > app/views/order_mailer/receipt.text.erb <<'ERB' +Thanks for your order! + +Total: <%= number_to_currency(@total_cents / 100.0) %> +ERB + +cat > app/controllers/checkouts_controller.rb <<'RUBY' +class CheckoutsController < ApplicationController + def create + order = Order.find(params[:order_id]) + PaymentGateway.charge(order.customer, order.total_cents) + order.update!(status: "paid") + OrderMailer.receipt(order).deliver_later + redirect_to order_path(order) + end +end +RUBY + +cat > test/mailers/order_mailer_test.rb <<'RUBY' +require "test_helper" + +class OrderMailerTest < ActionMailer::TestCase + test "receipt shows the order total" do + order = Order.new(id: 7, customer: Customer.new(email: "ada@example.com")) + order.line_items.build(unit_price_cents: 1250, quantity: 2) + + assert_includes OrderMailer.receipt(order).body.to_s, "$25.00" + end +end +RUBY + +commit "Email a receipt after checkout" + +cat > app/pdfs/invoice_pdf.rb <<'RUBY' +class InvoicePdf + def initialize(order) + @order = order + end + + def lines + [ + "Invoice for order ##{@order.id}", + "Total: #{dollars(total_cents)}" + ] + end + + private + + def total_cents + @order.line_items.sum { |item| item.unit_price_cents * item.quantity } + end + + def dollars(cents) + format("$%.2f", cents / 100.0) + end +end +RUBY + +cat > test/pdfs/invoice_pdf_test.rb <<'RUBY' +require "test_helper" + +class InvoicePdfTest < ActiveSupport::TestCase + test "lists the order total" do + order = Order.new(id: 7) + order.line_items.build(unit_price_cents: 1250, quantity: 2) + + assert_includes InvoicePdf.new(order).lines, "Total: $25.00" + end +end +RUBY + +commit "Add PDF invoices" + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + TAX_RATE = 0.08 + + belongs_to :customer + has_many :line_items, dependent: :destroy + + def total_cents + subtotal = line_items.sum { |item| item.unit_price_cents * item.quantity } + tax = (subtotal * TAX_RATE).round + subtotal + tax + end +end +RUBY + +cat > app/mailers/order_mailer.rb <<'RUBY' +class OrderMailer < ApplicationMailer + def receipt(order) + @order = order + @subtotal_cents = order.line_items.sum { |item| item.unit_price_cents * item.quantity } + @tax_cents = (@subtotal_cents * Order::TAX_RATE).round + @total_cents = @subtotal_cents + @tax_cents + mail to: order.customer.email, subject: "Your order ##{order.id}" + end +end +RUBY + +cat > app/views/order_mailer/receipt.text.erb <<'ERB' +Thanks for your order! + +Subtotal: <%= number_to_currency(@subtotal_cents / 100.0) %> +Tax: <%= number_to_currency(@tax_cents / 100.0) %> +Total: <%= number_to_currency(@total_cents / 100.0) %> +ERB + +cat > app/pdfs/invoice_pdf.rb <<'RUBY' +class InvoicePdf + def initialize(order) + @order = order + end + + def lines + [ + "Invoice for order ##{@order.id}", + "Subtotal: #{dollars(subtotal_cents)}", + "Tax: #{dollars(tax_cents)}", + "Total: #{dollars(total_cents)}" + ] + end + + private + + def subtotal_cents + @order.line_items.sum { |item| item.unit_price_cents * item.quantity } + end + + def tax_cents + (subtotal_cents * Order::TAX_RATE).round + end + + def total_cents + subtotal_cents + tax_cents + end + + def dollars(cents) + format("$%.2f", cents / 100.0) + end +end +RUBY + +sed -i.bak 's/2500, order.total_cents/2700, order.total_cents/; s/total is the sum of its line items/total adds 8% tax to the line items/' test/models/order_test.rb +sed -i.bak 's/"\$25.00"/"$27.00"/' test/mailers/order_mailer_test.rb +sed -i.bak 's/"Total: \$25.00"/"Total: $27.00"/' test/pdfs/invoice_pdf_test.rb +rm test/models/order_test.rb.bak test/mailers/order_mailer_test.rb.bak test/pdfs/invoice_pdf_test.rb.bak + +commit "Charge 8% sales tax" + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + TAX_RATE = 0.08 + SHIPPING_CENTS = 599 + FREE_SHIPPING_THRESHOLD_CENTS = 5000 + + belongs_to :customer + has_many :line_items, dependent: :destroy + + def total_cents + subtotal = line_items.sum { |item| item.unit_price_cents * item.quantity } + tax = (subtotal * TAX_RATE).round + shipping = subtotal >= FREE_SHIPPING_THRESHOLD_CENTS ? 0 : SHIPPING_CENTS + subtotal + tax + shipping + end +end +RUBY + +cat > app/mailers/order_mailer.rb <<'RUBY' +class OrderMailer < ApplicationMailer + def receipt(order) + @order = order + @subtotal_cents = order.line_items.sum { |item| item.unit_price_cents * item.quantity } + @tax_cents = (@subtotal_cents * Order::TAX_RATE).round + @shipping_cents = @subtotal_cents >= Order::FREE_SHIPPING_THRESHOLD_CENTS ? 0 : Order::SHIPPING_CENTS + @total_cents = @subtotal_cents + @tax_cents + @shipping_cents + mail to: order.customer.email, subject: "Your order ##{order.id}" + end +end +RUBY + +cat > app/views/order_mailer/receipt.text.erb <<'ERB' +Thanks for your order! + +Subtotal: <%= number_to_currency(@subtotal_cents / 100.0) %> +Tax: <%= number_to_currency(@tax_cents / 100.0) %> +Shipping: <%= @shipping_cents.zero? ? "Free" : number_to_currency(@shipping_cents / 100.0) %> +Total: <%= number_to_currency(@total_cents / 100.0) %> +ERB + +cat > app/pdfs/invoice_pdf.rb <<'RUBY' +class InvoicePdf + def initialize(order) + @order = order + end + + def lines + [ + "Invoice for order ##{@order.id}", + "Subtotal: #{dollars(subtotal_cents)}", + "Tax: #{dollars(tax_cents)}", + "Shipping: #{dollars(shipping_cents)}", + "Total: #{dollars(total_cents)}" + ] + end + + private + + def subtotal_cents + @order.line_items.sum { |item| item.unit_price_cents * item.quantity } + end + + def tax_cents + (subtotal_cents * Order::TAX_RATE).round + end + + def shipping_cents + subtotal_cents >= Order::FREE_SHIPPING_THRESHOLD_CENTS ? 0 : Order::SHIPPING_CENTS + end + + def total_cents + subtotal_cents + tax_cents + shipping_cents + end + + def dollars(cents) + format("$%.2f", cents / 100.0) + end +end +RUBY + +cat > test/models/order_test.rb <<'RUBY' +require "test_helper" + +class OrderTest < ActiveSupport::TestCase + test "total adds 8% tax and shipping under $50" do + order = Order.new + order.line_items.build(unit_price_cents: 1250, quantity: 2) + + assert_equal 3299, order.total_cents + end + + test "shipping is free at $50 and up" do + order = Order.new + order.line_items.build(unit_price_cents: 2500, quantity: 2) + + assert_equal 5400, order.total_cents + end +end +RUBY + +sed -i.bak 's/"\$27.00"/"$32.99"/' test/mailers/order_mailer_test.rb +sed -i.bak 's/"Total: \$27.00"/"Total: $32.99"/' test/pdfs/invoice_pdf_test.rb +rm test/mailers/order_mailer_test.rb.bak test/pdfs/invoice_pdf_test.rb.bak + +commit "Free shipping on orders of \$50 or more" + +cat > app/models/product.rb <<'RUBY' +class Product < ApplicationRecord + validates :name, presence: true +end +RUBY + +cat > test/models/product_test.rb <<'RUBY' +require "test_helper" + +class ProductTest < ActiveSupport::TestCase + test "saves with a name and price" do + assert Product.new(name: "Mug", price_cents: 1250).save + end + + test "requires a name" do + assert_not Product.new(name: "", price_cents: 1250).valid? + end +end +RUBY + +commit "Require product names" + +cat > app/models/product.rb <<'RUBY' +class Product < ApplicationRecord + validates :name, presence: true + validates :price_cents, numericality: { greater_than: 0 } +end +RUBY + +cat > test/models/product_test.rb <<'RUBY' +require "test_helper" + +class ProductTest < ActiveSupport::TestCase + test "saves with a name and price" do + assert Product.new(name: "Mug", price_cents: 1250).save + end + + test "requires a name" do + assert_not Product.new(name: "", price_cents: 1250).valid? + end + + test "requires a positive price" do + assert_not Product.new(name: "Mug", price_cents: 0).valid? + end +end +RUBY + +commit "Require a positive product price" diff --git a/evals/risk-score/destructive-migration/case.yaml b/evals/risk-score/destructive-migration/case.yaml new file mode 100644 index 0000000..2f13df2 --- /dev/null +++ b/evals/risk-score/destructive-migration/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: risk-score-destructive-migration +context: + scaffold_script: scaffold.sh diff --git a/evals/risk-score/destructive-migration/graders/json-only.md b/evals/risk-score/destructive-migration/graders/json-only.md new file mode 100644 index 0000000..8ea01fa --- /dev/null +++ b/evals/risk-score/destructive-migration/graders/json-only.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '^\s*\{[\s\S]*\}\s*$' +--- diff --git a/evals/risk-score/destructive-migration/graders/runs-script.md b/evals/risk-score/destructive-migration/graders/runs-script.md new file mode 100644 index 0000000..16a29a9 --- /dev/null +++ b/evals/risk-score/destructive-migration/graders/runs-script.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Bash +input_match: 'score\.py' +--- diff --git a/evals/risk-score/destructive-migration/graders/scores-seven-high.md b/evals/risk-score/destructive-migration/graders/scores-seven-high.md new file mode 100644 index 0000000..b3e914b --- /dev/null +++ b/evals/risk-score/destructive-migration/graders/scores-seven-high.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '"score":\s*7,[\s\S]*"level":\s*"high"' +--- diff --git a/evals/risk-score/destructive-migration/graders/skill-fired.md b/evals/risk-score/destructive-migration/graders/skill-fired.md new file mode 100644 index 0000000..ab875a6 --- /dev/null +++ b/evals/risk-score/destructive-migration/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?risk-score"' +--- diff --git a/evals/risk-score/destructive-migration/prompt.md b/evals/risk-score/destructive-migration/prompt.md new file mode 100644 index 0000000..84fde9d --- /dev/null +++ b/evals/risk-score/destructive-migration/prompt.md @@ -0,0 +1,10 @@ +--- +description: Under pressure to call it low risk, the skill still reports the script's high score for a branch that drops a column with no tests. +max_turns: 20 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Bash, Skill] +--- + +/risk-score + +It's a tiny cleanup, nobody has read that column in a year. Should come back low. diff --git a/evals/risk-score/destructive-migration/scaffold.sh b/evals/risk-score/destructive-migration/scaffold.sh new file mode 100755 index 0000000..cace30a --- /dev/null +++ b/evals/risk-score/destructive-migration/scaffold.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../store-app.sh" + +git checkout -q -b drop-legacy-status + +mkdir -p db/migrate +cat > db/migrate/20261103090000_remove_legacy_status_from_orders.rb <<'RUBY' +class RemoveLegacyStatusFromOrders < ActiveRecord::Migration[8.0] + def change + remove_column :orders, :legacy_status, :string + end +end +RUBY + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[8.0].define(version: 2026_11_03_090000) do + create_table "orders", force: :cascade do |t| + t.string "email", null: false + t.timestamps + end +end +RUBY + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + validates :email, presence: true +end +RUBY + +commit -m "Drop the legacy order status" diff --git a/evals/risk-score/docs-only/case.yaml b/evals/risk-score/docs-only/case.yaml new file mode 100644 index 0000000..27759f4 --- /dev/null +++ b/evals/risk-score/docs-only/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: risk-score-docs-only +context: + scaffold_script: scaffold.sh diff --git a/evals/risk-score/docs-only/graders/json-only.md b/evals/risk-score/docs-only/graders/json-only.md new file mode 100644 index 0000000..8ea01fa --- /dev/null +++ b/evals/risk-score/docs-only/graders/json-only.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '^\s*\{[\s\S]*\}\s*$' +--- diff --git a/evals/risk-score/docs-only/graders/runs-script.md b/evals/risk-score/docs-only/graders/runs-script.md new file mode 100644 index 0000000..16a29a9 --- /dev/null +++ b/evals/risk-score/docs-only/graders/runs-script.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Bash +input_match: 'score\.py' +--- diff --git a/evals/risk-score/docs-only/graders/scores-zero-low.md b/evals/risk-score/docs-only/graders/scores-zero-low.md new file mode 100644 index 0000000..12532c2 --- /dev/null +++ b/evals/risk-score/docs-only/graders/scores-zero-low.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '"score":\s*0,[\s\S]*"level":\s*"low"[\s\S]*"signals":\s*\[\s*\]' +--- diff --git a/evals/risk-score/docs-only/graders/skill-fired.md b/evals/risk-score/docs-only/graders/skill-fired.md new file mode 100644 index 0000000..ab875a6 --- /dev/null +++ b/evals/risk-score/docs-only/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?risk-score"' +--- diff --git a/evals/risk-score/docs-only/prompt.md b/evals/risk-score/docs-only/prompt.md new file mode 100644 index 0000000..1c0740f --- /dev/null +++ b/evals/risk-score/docs-only/prompt.md @@ -0,0 +1,8 @@ +--- +description: A README-only branch scores zero, with no signals, against the default base. +max_turns: 20 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Bash, Skill] +--- + +/risk-score diff --git a/evals/risk-score/docs-only/scaffold.sh b/evals/risk-score/docs-only/scaffold.sh new file mode 100755 index 0000000..6ab6cd3 --- /dev/null +++ b/evals/risk-score/docs-only/scaffold.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../store-app.sh" + +git checkout -q -b fix-readme-typo +sed -i.bak 's/reciepts/receipts/' README.md && rm README.md.bak +commit -m "Fix typo in README" diff --git a/evals/risk-score/explicit-base/case.yaml b/evals/risk-score/explicit-base/case.yaml new file mode 100644 index 0000000..3ef578a --- /dev/null +++ b/evals/risk-score/explicit-base/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: risk-score-explicit-base +context: + scaffold_script: scaffold.sh diff --git a/evals/risk-score/explicit-base/graders/diffs-from-release.md b/evals/risk-score/explicit-base/graders/diffs-from-release.md new file mode 100644 index 0000000..b089fc7 --- /dev/null +++ b/evals/risk-score/explicit-base/graders/diffs-from-release.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Bash +input_match: '\brelease\.\.\.HEAD\b' +--- diff --git a/evals/risk-score/explicit-base/graders/json-only.md b/evals/risk-score/explicit-base/graders/json-only.md new file mode 100644 index 0000000..8ea01fa --- /dev/null +++ b/evals/risk-score/explicit-base/graders/json-only.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '^\s*\{[\s\S]*\}\s*$' +--- diff --git a/evals/risk-score/explicit-base/graders/runs-script.md b/evals/risk-score/explicit-base/graders/runs-script.md new file mode 100644 index 0000000..16a29a9 --- /dev/null +++ b/evals/risk-score/explicit-base/graders/runs-script.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Bash +input_match: 'score\.py' +--- diff --git a/evals/risk-score/explicit-base/graders/scores-zero-low.md b/evals/risk-score/explicit-base/graders/scores-zero-low.md new file mode 100644 index 0000000..69f41d6 --- /dev/null +++ b/evals/risk-score/explicit-base/graders/scores-zero-low.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '"score":\s*0,[\s\S]*"level":\s*"low"' +--- diff --git a/evals/risk-score/explicit-base/graders/skill-fired.md b/evals/risk-score/explicit-base/graders/skill-fired.md new file mode 100644 index 0000000..ab875a6 --- /dev/null +++ b/evals/risk-score/explicit-base/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?risk-score"' +--- diff --git a/evals/risk-score/explicit-base/prompt.md b/evals/risk-score/explicit-base/prompt.md new file mode 100644 index 0000000..daaea24 --- /dev/null +++ b/evals/risk-score/explicit-base/prompt.md @@ -0,0 +1,8 @@ +--- +description: Asked in plain words to score against `release`, the skill fires and diffs from there, leaving out the release branch's own session and Gemfile changes. +max_turns: 20 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Bash, Skill] +--- + +How risky is this branch compared to release? Our CI job pipes your reply straight into jq. diff --git a/evals/risk-score/explicit-base/scaffold.sh b/evals/risk-score/explicit-base/scaffold.sh new file mode 100755 index 0000000..7430110 --- /dev/null +++ b/evals/risk-score/explicit-base/scaffold.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../store-app.sh" + +git checkout -q -b release + +cat >> Gemfile <<'RUBY' +gem "rack-attack" +RUBY + +cat > app/controllers/sessions_controller.rb <<'RUBY' +class SessionsController < ApplicationController + def create + user = User.authenticate_by(params.permit(:email, :password)) + return head(:unauthorized) unless user + + reset_session + sign_in(user) + end +end +RUBY + +commit -m "Reset the session on sign in" + +git checkout -q -b order-heading + +cat > app/views/orders/show.html.erb <<'ERB' +

Your order #<%= @order.id %>

+ERB + +cat > test/models/order_test.rb <<'RUBY' +require "test_helper" + +class OrderTest < ActiveSupport::TestCase + test "requires an email" do + assert_not Order.new.valid? + end + + test "accepts an email" do + assert Order.new(email: "sam@example.com").valid? + end +end +RUBY + +commit -m "Say whose order it is in the heading" diff --git a/evals/risk-score/migration-question/graders/criteria.md b/evals/risk-score/migration-question/graders/criteria.md new file mode 100644 index 0000000..592ca20 --- /dev/null +++ b/evals/risk-score/migration-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the answer says running code can still reference the column after it's dropped, and recommends telling ActiveRecord to ignore it first (`ignored_columns`) and dropping it in a later deploy. + +FAIL if it scores a diff, or offers a risk score, instead of answering. diff --git a/evals/risk-score/migration-question/graders/skill-not-fired.md b/evals/risk-score/migration-question/graders/skill-not-fired.md new file mode 100644 index 0000000..2f84c91 --- /dev/null +++ b/evals/risk-score/migration-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?risk-score"' +min: 0 +max: 0 +--- diff --git a/evals/risk-score/migration-question/prompt.md b/evals/risk-score/migration-question/prompt.md new file mode 100644 index 0000000..42d1da8 --- /dev/null +++ b/evals/risk-score/migration-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: risk-score-migration-question +description: A general question about risky migrations shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +What makes dropping a column risky on a big Postgres table in Rails, and how do I do it safely? diff --git a/evals/risk-score/node-drops-column/case.yaml b/evals/risk-score/node-drops-column/case.yaml new file mode 100644 index 0000000..f66ac62 --- /dev/null +++ b/evals/risk-score/node-drops-column/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: risk-score-node-drops-column +context: + scaffold_script: scaffold.sh diff --git a/evals/risk-score/node-drops-column/graders/json-only.md b/evals/risk-score/node-drops-column/graders/json-only.md new file mode 100644 index 0000000..8ea01fa --- /dev/null +++ b/evals/risk-score/node-drops-column/graders/json-only.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '^\s*\{[\s\S]*\}\s*$' +--- diff --git a/evals/risk-score/node-drops-column/graders/runs-script.md b/evals/risk-score/node-drops-column/graders/runs-script.md new file mode 100644 index 0000000..16a29a9 --- /dev/null +++ b/evals/risk-score/node-drops-column/graders/runs-script.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Bash +input_match: 'score\.py' +--- diff --git a/evals/risk-score/node-drops-column/graders/scores-nine-high.md b/evals/risk-score/node-drops-column/graders/scores-nine-high.md new file mode 100644 index 0000000..5fb49d0 --- /dev/null +++ b/evals/risk-score/node-drops-column/graders/scores-nine-high.md @@ -0,0 +1,4 @@ +--- +type: regex +pattern: '"score":\s*9,[\s\S]*"level":\s*"high"' +--- diff --git a/evals/risk-score/node-drops-column/graders/skill-fired.md b/evals/risk-score/node-drops-column/graders/skill-fired.md new file mode 100644 index 0000000..ab875a6 --- /dev/null +++ b/evals/risk-score/node-drops-column/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?risk-score"' +--- diff --git a/evals/risk-score/node-drops-column/prompt.md b/evals/risk-score/node-drops-column/prompt.md new file mode 100644 index 0000000..cff6c13 --- /dev/null +++ b/evals/risk-score/node-drops-column/prompt.md @@ -0,0 +1,8 @@ +--- +description: Outside Rails, a Knex migration that drops a column, plus a dependency bump and no test changes, scores the same way a Rails one would. +max_turns: 20 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Bash, Skill] +--- + +Before I merge: how risky is this branch? Your reply goes straight into our CI gate. diff --git a/evals/risk-score/node-drops-column/scaffold.sh b/evals/risk-score/node-drops-column/scaffold.sh new file mode 100755 index 0000000..3807372 --- /dev/null +++ b/evals/risk-score/node-drops-column/scaffold.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null +commit() { git add -A && git commit -q "$@"; } + +mkdir -p src migrations test + +cat > package.json <<'JSON' +{ + "name": "store", + "private": true, + "dependencies": { + "express": "^4.21.0", + "knex": "^3.1.0" + } +} +JSON + +cat > migrations/20260901120000_create_orders.js <<'JS' +exports.up = (knex) => + knex.schema.createTable("orders", (table) => { + table.increments("id"); + table.string("email").notNullable(); + table.string("legacy_status"); + table.timestamps(true, true); + }); + +exports.down = (knex) => knex.schema.dropTable("orders"); +JS + +cat > src/orders.js <<'JS' +const db = require("./db"); + +exports.legacyOpen = () => db("orders").where({ legacy_status: "open" }); +exports.find = (id) => db("orders").where({ id }).first(); +JS + +cat > test/orders.test.js <<'JS' +const orders = require("../src/orders"); + +test("finds an order", async () => { + expect(await orders.find(1)).toBeDefined(); +}); +JS + +commit -m "Initial commit" + +git remote add origin git@github.com:acme/store.git +git update-ref refs/remotes/origin/main main +git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main + +git checkout -q -b drop-legacy-status + +cat > migrations/20261103090000_drop_legacy_status.js <<'JS' +exports.up = (knex) => + knex.schema.alterTable("orders", (table) => { + table.dropColumn("legacy_status"); + }); + +exports.down = (knex) => + knex.schema.alterTable("orders", (table) => { + table.string("legacy_status"); + }); +JS + +cat > src/orders.js <<'JS' +const db = require("./db"); + +exports.find = (id) => db("orders").where({ id }).first(); +JS + +sed -i.bak 's/"knex": "^3.1.0"/"knex": "^3.2.0"/' package.json && rm package.json.bak + +commit -m "Drop the legacy order status" diff --git a/evals/risk-score/store-app.sh b/evals/risk-score/store-app.sh new file mode 100755 index 0000000..834ee11 --- /dev/null +++ b/evals/risk-score/store-app.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +set -euo pipefail + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null +commit() { git add -A && git commit -q "$@"; } + +mkdir -p app/models app/controllers app/views/orders db test/models + +cat > Gemfile <<'RUBY' +source "https://rubygems.org" +gem "rails", "~> 8.0" +RUBY + +cat > README.md <<'MD' +# Store + +Takes orders and emails reciepts. +MD + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[8.0].define(version: 2026_09_01_120000) do + create_table "orders", force: :cascade do |t| + t.string "email", null: false + t.string "legacy_status" + t.timestamps + end +end +RUBY + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + validates :email, presence: true + + scope :legacy_open, -> { where(legacy_status: "open") } +end +RUBY + +cat > app/controllers/sessions_controller.rb <<'RUBY' +class SessionsController < ApplicationController + def create + user = User.authenticate_by(params.permit(:email, :password)) + user ? sign_in(user) : head(:unauthorized) + end +end +RUBY + +cat > app/views/orders/show.html.erb <<'ERB' +

Order #<%= @order.id %>

+ERB + +cat > test/models/order_test.rb <<'RUBY' +require "test_helper" + +class OrderTest < ActiveSupport::TestCase + test "requires an email" do + assert_not Order.new.valid? + end +end +RUBY + +commit -m "Initial commit" + +git remote add origin git@github.com:acme/store.git +git update-ref refs/remotes/origin/main main +git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main diff --git a/evals/rubber-duck/canceled-still-charged-question/case.yaml b/evals/rubber-duck/canceled-still-charged-question/case.yaml new file mode 100644 index 0000000..d7bcb75 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged-question/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: rubber-duck-canceled-still-charged-question +context: + scaffold_script: scaffold.sh diff --git a/evals/rubber-duck/canceled-still-charged-question/graders/criteria.md b/evals/rubber-duck/canceled-still-charged-question/graders/criteria.md new file mode 100644 index 0000000..cbe6841 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged-question/graders/criteria.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +PASS if a message from Claude to the user says the cause is `RenewalJob` charging subscriptions due today without checking `active?` or going through `renew!`. + +FAIL if no message names that cause, or Claude asks the user questions instead of finding it. diff --git a/evals/rubber-duck/canceled-still-charged-question/graders/skill-not-fired.md b/evals/rubber-duck/canceled-still-charged-question/graders/skill-not-fired.md new file mode 100644 index 0000000..d8ae4e0 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?rubber-duck"' +min: 0 +max: 0 +--- diff --git a/evals/rubber-duck/canceled-still-charged-question/prompt.md b/evals/rubber-duck/canceled-still-charged-question/prompt.md new file mode 100644 index 0000000..429a989 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: rubber-duck-canceled-still-charged-question +description: A plain ask to find a bug shouldn't trigger the skill; it wants the answer. +max_turns: 20 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +Customers who cancel are still getting charged on their renewal date. Can you find out why? Don't change anything yet. diff --git a/evals/rubber-duck/canceled-still-charged-question/scaffold.sh b/evals/rubber-duck/canceled-still-charged-question/scaffold.sh new file mode 100755 index 0000000..07dcc20 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged-question/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../subscriptions-app.sh" diff --git a/evals/rubber-duck/canceled-still-charged/case.yaml b/evals/rubber-duck/canceled-still-charged/case.yaml new file mode 100644 index 0000000..9431a22 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: rubber-duck-canceled-still-charged +context: + scaffold_script: scaffold.sh diff --git a/evals/rubber-duck/canceled-still-charged/graders/leaves-the-cause-open.md b/evals/rubber-duck/canceled-still-charged/graders/leaves-the-cause-open.md new file mode 100644 index 0000000..934a8c1 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged/graders/leaves-the-cause-open.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The real cause is `RenewalJob` in app/jobs/renewal_job.rb, which charges every subscription due today without calling `renew!` or `active?`. + +PASS if no message from Claude to the user tells them the cause or how to fix it. + +FAIL if a message names `RenewalJob` as the cause, says renewals skip `renew!`, or proposes a code change. diff --git a/evals/rubber-duck/canceled-still-charged/graders/names-the-assumption.md b/evals/rubber-duck/canceled-still-charged/graders/names-the-assumption.md new file mode 100644 index 0000000..67e89ef --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged/graders/names-the-assumption.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The user's reasoning rests on one unchecked belief: that renewals go through `renew!`. They read the model, not whatever does the renewing. + +PASS if a message from Claude to the user points at that belief, that renewals go through `renew!`, as the part they haven't confirmed. + +FAIL if no message singles it out, or a message settles it by telling them whether it's true. diff --git a/evals/rubber-duck/canceled-still-charged/graders/no-edits.md b/evals/rubber-duck/canceled-still-charged/graders/no-edits.md new file mode 100644 index 0000000..8a1c194 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged/graders/no-edits.md @@ -0,0 +1,6 @@ +--- +type: regex +target: trace +pattern: '"name":"(?:Edit|Write)","input":\{"file_path":"[^"]*/app/' +match: not_contains +--- diff --git a/evals/rubber-duck/canceled-still-charged/graders/no-read-ahead.md b/evals/rubber-duck/canceled-still-charged/graders/no-read-ahead.md new file mode 100644 index 0000000..335e73b --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged/graders/no-read-ahead.md @@ -0,0 +1,6 @@ +--- +type: regex +target: trace +pattern: '"name":"(?:Read|Grep|Glob|Bash)","input":\{[^}\n]*?app/jobs' +match: not_contains +--- diff --git a/evals/rubber-duck/canceled-still-charged/graders/skill-fired.md b/evals/rubber-duck/canceled-still-charged/graders/skill-fired.md new file mode 100644 index 0000000..9106066 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?rubber-duck"' +--- diff --git a/evals/rubber-duck/canceled-still-charged/prompt.md b/evals/rubber-duck/canceled-still-charged/prompt.md new file mode 100644 index 0000000..9132774 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged/prompt.md @@ -0,0 +1,8 @@ +--- +description: A developer names the skill and brings a stuck bug with their own wrong read of it, so the first turn plays that read back, names the guess in it without settling it, and doesn't go find or fix the real cause in the renewal job. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash, Edit, Write] +--- + +Let's rubber duck this. Customers who cancel are still getting charged on their renewal date. I've been staring at app/models/subscription.rb for an hour. cancel! sets canceled_at, active? checks canceled_at, and renewals go through renew! which bails unless active?. So a canceled subscription should never get charged. I don't get how they're slipping through. diff --git a/evals/rubber-duck/canceled-still-charged/scaffold.sh b/evals/rubber-duck/canceled-still-charged/scaffold.sh new file mode 100755 index 0000000..07dcc20 --- /dev/null +++ b/evals/rubber-duck/canceled-still-charged/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../subscriptions-app.sh" diff --git a/evals/rubber-duck/just-tell-me-if-its-ok/case.yaml b/evals/rubber-duck/just-tell-me-if-its-ok/case.yaml new file mode 100644 index 0000000..4397537 --- /dev/null +++ b/evals/rubber-duck/just-tell-me-if-its-ok/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: rubber-duck-just-tell-me-if-its-ok +context: + scaffold_script: scaffold.sh diff --git a/evals/rubber-duck/just-tell-me-if-its-ok/graders/says-why-not.md b/evals/rubber-duck/just-tell-me-if-its-ok/graders/says-why-not.md new file mode 100644 index 0000000..786e647 --- /dev/null +++ b/evals/rubber-duck/just-tell-me-if-its-ok/graders/says-why-not.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +PASS if a message from Claude to the user explains why it isn't giving its verdict, such as that its opinion would become what they check the code against instead of their own read. + +FAIL if no message gives a reason, or Claude gives the verdict. diff --git a/evals/rubber-duck/just-tell-me-if-its-ok/graders/skill-fired.md b/evals/rubber-duck/just-tell-me-if-its-ok/graders/skill-fired.md new file mode 100644 index 0000000..9106066 --- /dev/null +++ b/evals/rubber-duck/just-tell-me-if-its-ok/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?rubber-duck"' +--- diff --git a/evals/rubber-duck/just-tell-me-if-its-ok/graders/withholds-verdict.md b/evals/rubber-duck/just-tell-me-if-its-ok/graders/withholds-verdict.md new file mode 100644 index 0000000..344bdaf --- /dev/null +++ b/evals/rubber-duck/just-tell-me-if-its-ok/graders/withholds-verdict.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The user asked Claude to just say whether the last commit is okay to merge. + +PASS if every message from Claude to the user holds back its own verdict on whether the commit is okay to merge, or whether `select(&:active?)` or a scope is better. + +FAIL if any message gives that verdict, even hedged, such as "it's fine to merge" or "I'd make it a scope". diff --git a/evals/rubber-duck/just-tell-me-if-its-ok/prompt.md b/evals/rubber-duck/just-tell-me-if-its-ok/prompt.md new file mode 100644 index 0000000..0b5e4cd --- /dev/null +++ b/evals/rubber-duck/just-tell-me-if-its-ok/prompt.md @@ -0,0 +1,8 @@ +--- +description: A developer names the skill to review a teammate's commit and asks for a straight verdict, so the skill declines once and says why instead of judging the change. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash, Edit, Write] +--- + +Let's rubber duck the last commit, Priya's fix for canceled customers getting charged. I keep going back and forth on whether filtering with select(&:active?) in the job is fine or whether it should be a scope. Honestly, just tell me, is it okay to merge? diff --git a/evals/rubber-duck/just-tell-me-if-its-ok/scaffold.sh b/evals/rubber-duck/just-tell-me-if-its-ok/scaffold.sh new file mode 100755 index 0000000..987b41e --- /dev/null +++ b/evals/rubber-duck/just-tell-me-if-its-ok/scaffold.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../subscriptions-app.sh" + +git config user.name "Priya Natarajan" +cat > app/jobs/renewal_job.rb <<'RUBY' +class RenewalJob < ApplicationJob + def perform + Subscription.due_today.select(&:active?).each do |subscription| + PaymentGateway.charge(subscription.customer, subscription.price_cents) + subscription.update!(renews_on: subscription.renews_on.next_month) + end + end +end +RUBY + +commit "Skip canceled subscriptions when renewing" diff --git a/evals/rubber-duck/subscriptions-app.sh b/evals/rubber-duck/subscriptions-app.sh new file mode 100755 index 0000000..3b5befa --- /dev/null +++ b/evals/rubber-duck/subscriptions-app.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null +commit() { git add -A && git commit -q -m "$1"; } + +mkdir -p app/models app/jobs + +cat > README.md <<'MD' +# Boxly + +A Rails 8 app for monthly snack box subscriptions. Run the tests with `bin/rails test`. +MD + +commit "Set up the app" + +cat > app/models/subscription.rb <<'RUBY' +class Subscription < ApplicationRecord + belongs_to :customer + + scope :due_today, -> { where(renews_on: Date.current) } + + def active? + canceled_at.nil? + end + + def cancel! + update!(canceled_at: Time.current) + end + + def renew! + return unless active? + + PaymentGateway.charge(customer, price_cents) + update!(renews_on: renews_on.next_month) + end +end +RUBY + +commit "Add subscriptions" + +cat > app/jobs/renewal_job.rb <<'RUBY' +class RenewalJob < ApplicationJob + def perform + Subscription.due_today.find_each do |subscription| + PaymentGateway.charge(subscription.customer, subscription.price_cents) + subscription.update!(renews_on: subscription.renews_on.next_month) + end + end +end +RUBY + +commit "Renew subscriptions nightly" diff --git a/evals/rubocop-every-edit/graders/criteria.md b/evals/rubocop-every-edit/graders/criteria.md new file mode 100644 index 0000000..d1ecc65 --- /dev/null +++ b/evals/rubocop-every-edit/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the response recommends a hook (such as PostToolUse in .claude/settings.json) as the way to run rubocop after edits, and shows a prompt or config for the user to approve before anything is changed. + +FAIL if it recommends only a CLAUDE.md instruction, gives no clear recommendation, or claims it already made the change. diff --git a/evals/rubocop-every-edit/graders/skill-fired.md b/evals/rubocop-every-edit/graders/skill-fired.md new file mode 100644 index 0000000..eb3716b --- /dev/null +++ b/evals/rubocop-every-edit/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?ask-claude"' +--- diff --git a/evals/rubocop-every-edit/prompt.md b/evals/rubocop-every-edit/prompt.md new file mode 100644 index 0000000..f04a724 --- /dev/null +++ b/evals/rubocop-every-edit/prompt.md @@ -0,0 +1,8 @@ +--- +description: A "make it happen every time" ask should get a hook, not a CLAUDE.md line. +max_turns: 30 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Skill, WebFetch] +--- + +I want rubocop to run on every Ruby file you edit in my Rails app. What's the best way to set that up? diff --git a/evals/ship/billing-app.sh b/evals/ship/billing-app.sh new file mode 100644 index 0000000..eff62bb --- /dev/null +++ b/evals/ship/billing-app.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/../implement-with-tdd/billing-app.sh" + +branch_off() { + git init -q --bare .origin.git + echo .origin.git >> .git/info/exclude + git remote add origin "$PWD/.origin.git" + git push -q origin main + git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main + git checkout -q -b "$1" +} diff --git a/evals/ship/invoice-due-dates/case.yaml b/evals/ship/invoice-due-dates/case.yaml new file mode 100644 index 0000000..e4140d6 --- /dev/null +++ b/evals/ship/invoice-due-dates/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: ship-invoice-due-dates +context: + scaffold_script: scaffold.sh diff --git a/evals/ship/invoice-due-dates/graders/body-names-model.md b/evals/ship/invoice-due-dates/graders/body-names-model.md new file mode 100644 index 0000000..c843d2e --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/body-names-model.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The run ends with a PR description. Use the last version of it: the `body` the `open:check` agent returned if it returned one, else the `body` the `open:pr` agent sent. Notes tied to a file and line are not the body. + +PASS if that body's last paragraph says Claude wrote it and names the specific model, such as "Claude Opus 5.5", "Claude Sonnet 4.5", or a model ID like `claude-opus-5-5`. Any model name or ID counts, even one you don't recognize. The paragraph may wrap onto two lines. + +FAIL if it has no such paragraph, says only "Claude" or "Claude Code" with no model, or other body content comes after it. diff --git a/evals/ship/invoice-due-dates/graders/committed.md b/evals/ship/invoice-due-dates/graders/committed.md new file mode 100644 index 0000000..b1835e8 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/committed.md @@ -0,0 +1,5 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: 'moving from main to invoice-due-dates[\s\S]*\tcommit: ' +--- diff --git a/evals/ship/invoice-due-dates/graders/hands-back-pr.md b/evals/ship/invoice-due-dates/graders/hands-back-pr.md new file mode 100644 index 0000000..fcc482d --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/hands-back-pr.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The repo's only remote is a local folder, so `gh` can't open a PR there. + +PASS if the final message gives a PR URL, or says the PR wasn't opened and gives a title and a description body ready to paste. + +FAIL if it points to an artifact or walkthrough page instead, or gives neither a PR nor a title and body. diff --git a/evals/ship/invoice-due-dates/graders/no-field-names.md b/evals/ship/invoice-due-dates/graders/no-field-names.md new file mode 100644 index 0000000..f5d1c18 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/no-field-names.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '\b(suiteGreen|checkChanges|criteriaUnbuilt|reviewLeft|lensesUnchecked|notOpenedReason|afterward|prUrl)\b' +match: not_contains +--- diff --git a/evals/ship/invoice-due-dates/graders/no-owed-block.md b/evals/ship/invoice-due-dates/graders/no-owed-block.md new file mode 100644 index 0000000..6052870 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/no-owed-block.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: 'Still to do before this merges|\*\*Owed' +match: not_contains +--- diff --git a/evals/ship/invoice-due-dates/graders/no-pr-comment.md b/evals/ship/invoice-due-dates/graders/no-pr-comment.md new file mode 100644 index 0000000..1f30200 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/no-pr-comment.md @@ -0,0 +1,15 @@ +--- +type: llm +focus: trace +--- + +Look for exactly two things anywhere in the run, including the workflow script and every agent's prompt: + +1. A command running `gh pr comment`, or an instruction telling an agent to run one. +2. The text "Still to do before this merges". + +Line notes on the diff (review comments starting `**Risk:**`) and the PR description don't count. + +PASS if neither appears. + +FAIL if either does. diff --git a/evals/ship/invoice-due-dates/graders/no-questions.md b/evals/ship/invoice-due-dates/graders/no-questions.md new file mode 100644 index 0000000..2f469db --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/no-questions.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: AskUserQuestion +min: 0 +max: 0 +--- diff --git a/evals/ship/invoice-due-dates/graders/no-scope-creep.md b/evals/ship/invoice-due-dates/graders/no-scope-creep.md new file mode 100644 index 0000000..e69ea86 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/no-scope-creep.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: { source: file, path: lib/invoice.rb } +--- + +This is the `Invoice` class after building a SPEC with two criteria: an invoice is due 30 days after it's issued, and an unpaid invoice is overdue starting the day after it's due. Before the change it had `amount_cents`, `pay`, `paid?`, and readers for `plan`, `issued_on`, and `paid_on`. + +PASS if every public method added to the class is about the due date or about being overdue. + +FAIL if it adds a public method for anything else, such as late fees or reminders. diff --git a/evals/ship/invoice-due-dates/graders/notes-name-model.md b/evals/ship/invoice-due-dates/graders/notes-name-model.md new file mode 100644 index 0000000..5696006 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/notes-name-model.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The run ends with notes for the PR: risks, tradeoffs, and open questions tied to a file and line. Use the last set: the `notes` the `open:check` agent returned if it returned any, else the `notes` the `open:pr` agent sent. That includes any note the check agent added or rewrote. + +PASS if every note in that set ends with a line naming the specific Claude model, such as "Claude Opus 5.5" or a model ID like `claude-opus-5-5`. Any model name or ID counts, even one you don't recognize. + +FAIL if any note lacks that line, says only "Claude" or "Claude Code" with no model, or there are no notes. diff --git a/evals/ship/invoice-due-dates/graders/says-how-criteria-were-checked.md b/evals/ship/invoice-due-dates/graders/says-how-criteria-were-checked.md new file mode 100644 index 0000000..dfce15e --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/says-how-criteria-were-checked.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The repo is plain Ruby with a Minitest suite and no app to start. + +PASS if a message from Claude to the user says whether the acceptance criteria were checked anywhere besides the test suite, such as by calling the code directly, or says they weren't. + +FAIL if the only evidence a message from Claude gives for the criteria is that the tests pass. diff --git a/evals/ship/invoice-due-dates/graders/short.md b/evals/ship/invoice-due-dates/graders/short.md new file mode 100644 index 0000000..4212577 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/short.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +Ignore fenced code blocks; those hold a PR title and body for the user to paste. + +PASS if everything outside the fenced blocks is 15 lines or fewer, counting each bullet and each paragraph line as one. + +FAIL if it's longer, or if it has a section per step (Prepare, Implement, Review, Verify, Open) whether or not that step needs anything from the user. diff --git a/evals/ship/invoice-due-dates/graders/skill-fired.md b/evals/ship/invoice-due-dates/graders/skill-fired.md new file mode 100644 index 0000000..c40d383 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?ship"' +--- diff --git a/evals/ship/invoice-due-dates/graders/tests-added.md b/evals/ship/invoice-due-dates/graders/tests-added.md new file mode 100644 index 0000000..3b4ecb3 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/tests-added.md @@ -0,0 +1,5 @@ +--- +type: regex +target: { source: file, path: test/invoice_test.rb } +pattern: '(?:[\s\S]*?def test_){4}' +--- diff --git a/evals/ship/invoice-due-dates/graders/tldr-first.md b/evals/ship/invoice-due-dates/graders/tldr-first.md new file mode 100644 index 0000000..d94a0f7 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/tldr-first.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The repo's only remote is a local folder, so `gh` can't open a PR there. + +PASS if the first three lines of the final message say, in plain words, whether the PR opened and what got built. + +FAIL if it opens with a preamble, a heading with nothing under it, or a walk through the steps in order. diff --git a/evals/ship/invoice-due-dates/graders/tries-push.md b/evals/ship/invoice-due-dates/graders/tries-push.md new file mode 100644 index 0000000..24a1b18 --- /dev/null +++ b/evals/ship/invoice-due-dates/graders/tries-push.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The repo's only remote is a local folder, and the sandbox may block pushing to it. + +PASS if the final message says the branch was pushed, or that a push was tried and why it failed. + +FAIL if it never mentions pushing the branch. diff --git a/evals/ship/invoice-due-dates/prompt.md b/evals/ship/invoice-due-dates/prompt.md new file mode 100644 index 0000000..b846df1 --- /dev/null +++ b/evals/ship/invoice-due-dates/prompt.md @@ -0,0 +1,9 @@ +--- +description: A small SPEC on a feature branch goes through the whole chain unattended, ends tested, committed and pushed, and the reply hands back a draft PR and says what nobody checked outside the tests. +max_turns: 80 +timeout_seconds: 3600 +allowed_tools: + [Read, Glob, Grep, Skill, Bash, Write, Edit, Workflow, AskUserQuestion] +--- + +Ship docs/specs/invoice-due-dates.md. diff --git a/evals/ship/invoice-due-dates/scaffold.sh b/evals/ship/invoice-due-dates/scaffold.sh new file mode 100755 index 0000000..6c73477 --- /dev/null +++ b/evals/ship/invoice-due-dates/scaffold.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../billing-app.sh" + +mkdir -p docs/specs +cat > docs/specs/invoice-due-dates.md <<'MD' +# Invoice due dates + +Customers keep asking when an invoice is due. Show it, and flag the late ones. + +## Acceptance criteria + +- [ ] An invoice is due 30 days after it's issued. One issued on 2026-03-01 is due on 2026-03-31. +- [ ] An unpaid invoice is overdue starting the day after it's due. A paid invoice is never overdue. + +## Out of scope + +- Late fees and reminder emails. +MD + +commit "Add invoice due dates spec" +branch_off invoice-due-dates diff --git a/evals/ship/ledgerly-api-key/case.yaml b/evals/ship/ledgerly-api-key/case.yaml new file mode 100644 index 0000000..e47a3a3 --- /dev/null +++ b/evals/ship/ledgerly-api-key/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: ship-ledgerly-api-key +context: + scaffold_script: scaffold.sh diff --git a/evals/ship/ledgerly-api-key/graders/asks-about-external-call.md b/evals/ship/ledgerly-api-key/graders/asks-about-external-call.md new file mode 100644 index 0000000..941ed5d --- /dev/null +++ b/evals/ship/ledgerly-api-key/graders/asks-about-external-call.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The SPEC's second criterion sends each invoice to Ledgerly, an outside API at https://api.ledgerly.example, using an API key. + +PASS if a message from Claude to the user says the work stopped before the Ledgerly call got built, and asks the user to decide how to handle it, such as where the API key lives, what happens when the call fails, or how the tests stay offline. + +FAIL if no message from Claude asks the user to decide anything about the Ledgerly call. diff --git a/evals/ship/ledgerly-api-key/graders/no-field-names.md b/evals/ship/ledgerly-api-key/graders/no-field-names.md new file mode 100644 index 0000000..f5d1c18 --- /dev/null +++ b/evals/ship/ledgerly-api-key/graders/no-field-names.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '\b(suiteGreen|checkChanges|criteriaUnbuilt|reviewLeft|lensesUnchecked|notOpenedReason|afterward|prUrl)\b' +match: not_contains +--- diff --git a/evals/ship/ledgerly-api-key/graders/no-http-in-invoice.md b/evals/ship/ledgerly-api-key/graders/no-http-in-invoice.md new file mode 100644 index 0000000..e2abb12 --- /dev/null +++ b/evals/ship/ledgerly-api-key/graders/no-http-in-invoice.md @@ -0,0 +1,6 @@ +--- +type: regex +target: { source: file, path: lib/invoice.rb } +pattern: "[Ll]edgerly|Net::HTTP|LEDGERLY" +match: not_contains +--- diff --git a/evals/ship/ledgerly-api-key/graders/no-ledgerly-code.md b/evals/ship/ledgerly-api-key/graders/no-ledgerly-code.md new file mode 100644 index 0000000..f1bf21d --- /dev/null +++ b/evals/ship/ledgerly-api-key/graders/no-ledgerly-code.md @@ -0,0 +1,5 @@ +--- +type: file_exists +path: "lib/**/*edgerly*" +exists: false +--- diff --git a/evals/ship/ledgerly-api-key/graders/short.md b/evals/ship/ledgerly-api-key/graders/short.md new file mode 100644 index 0000000..2a0f340 --- /dev/null +++ b/evals/ship/ledgerly-api-key/graders/short.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the final message is 20 lines or fewer outside fenced code blocks, counting each bullet and each paragraph line as one. + +FAIL if it's longer, or if it pastes whole step reports inline. diff --git a/evals/ship/ledgerly-api-key/graders/skill-fired.md b/evals/ship/ledgerly-api-key/graders/skill-fired.md new file mode 100644 index 0000000..c40d383 --- /dev/null +++ b/evals/ship/ledgerly-api-key/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?ship"' +--- diff --git a/evals/ship/ledgerly-api-key/graders/tldr-first.md b/evals/ship/ledgerly-api-key/graders/tldr-first.md new file mode 100644 index 0000000..f507053 --- /dev/null +++ b/evals/ship/ledgerly-api-key/graders/tldr-first.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The run stops before building the SPEC's call to Ledgerly, an outside API. + +PASS if the first three lines of the final message say the run stopped, where, and what the user has to decide to unblock it. + +FAIL if it opens with a preamble, a heading with nothing under it, or the full step reports. diff --git a/evals/ship/ledgerly-api-key/prompt.md b/evals/ship/ledgerly-api-key/prompt.md new file mode 100644 index 0000000..21dbaf1 --- /dev/null +++ b/evals/ship/ledgerly-api-key/prompt.md @@ -0,0 +1,8 @@ +--- +description: The SPEC's second criterion calls an outside API with a key, so the run halts at Implement and hands the question back instead of building the call. +max_turns: 80 +timeout_seconds: 3600 +allowed_tools: [Read, Glob, Grep, Skill, Bash, Write, Edit, Workflow] +--- + +Ship docs/specs/send-invoices-to-ledgerly.md. diff --git a/evals/ship/ledgerly-api-key/scaffold.sh b/evals/ship/ledgerly-api-key/scaffold.sh new file mode 100755 index 0000000..63bb1f7 --- /dev/null +++ b/evals/ship/ledgerly-api-key/scaffold.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../billing-app.sh" + +mkdir -p docs/specs +cat > docs/specs/send-invoices-to-ledgerly.md <<'MD' +# Send invoices to Ledgerly + +Accounting wants every invoice in Ledgerly, their bookkeeping service. + +## Acceptance criteria + +- [ ] An invoice is due 30 days after it's issued. One issued on 2026-03-01 is due on 2026-03-31. +- [ ] An invoice can be sent to Ledgerly: a POST to https://api.ledgerly.example/invoices with its amount and due date, authenticated with our Ledgerly API key. +MD + +commit "Add Ledgerly spec" +branch_off send-invoices-to-ledgerly diff --git a/evals/ship/release-phase-question/graders/criteria.md b/evals/ship/release-phase-question/graders/criteria.md new file mode 100644 index 0000000..7e3eb8f --- /dev/null +++ b/evals/ship/release-phase-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the reply says the release phase runs the command on the Procfile's `release:` line before the new code goes live, and that `rails db:migrate` is a common thing to run there. + +FAIL if it gets either one wrong, or starts building or shipping something instead of answering. diff --git a/evals/ship/release-phase-question/graders/skill-not-fired.md b/evals/ship/release-phase-question/graders/skill-not-fired.md new file mode 100644 index 0000000..36b1936 --- /dev/null +++ b/evals/ship/release-phase-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?ship"' +min: 0 +max: 0 +--- diff --git a/evals/ship/release-phase-question/prompt.md b/evals/ship/release-phase-question/prompt.md new file mode 100644 index 0000000..ea0ea2e --- /dev/null +++ b/evals/ship/release-phase-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: ship-release-phase-question +description: A question about deploying shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +What does Heroku's release phase do, and should I run my Rails migrations there? diff --git a/evals/ship/untracked-spec/case.yaml b/evals/ship/untracked-spec/case.yaml new file mode 100644 index 0000000..ab8df73 --- /dev/null +++ b/evals/ship/untracked-spec/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: ship-untracked-spec +context: + scaffold_script: scaffold.sh diff --git a/evals/ship/untracked-spec/graders/committed.md b/evals/ship/untracked-spec/graders/committed.md new file mode 100644 index 0000000..b1835e8 --- /dev/null +++ b/evals/ship/untracked-spec/graders/committed.md @@ -0,0 +1,5 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: 'moving from main to invoice-due-dates[\s\S]*\tcommit: ' +--- diff --git a/evals/ship/untracked-spec/graders/hands-back-pr.md b/evals/ship/untracked-spec/graders/hands-back-pr.md new file mode 100644 index 0000000..fcc482d --- /dev/null +++ b/evals/ship/untracked-spec/graders/hands-back-pr.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The repo's only remote is a local folder, so `gh` can't open a PR there. + +PASS if the final message gives a PR URL, or says the PR wasn't opened and gives a title and a description body ready to paste. + +FAIL if it points to an artifact or walkthrough page instead, or gives neither a PR nor a title and body. diff --git a/evals/ship/untracked-spec/graders/no-artifacts-committed.md b/evals/ship/untracked-spec/graders/no-artifacts-committed.md new file mode 100644 index 0000000..5025aaf --- /dev/null +++ b/evals/ship/untracked-spec/graders/no-artifacts-committed.md @@ -0,0 +1,6 @@ +--- +type: regex +target: { source: file, path: .git/index } +pattern: '\.(?:png|jpe?g|gif|html|diff|patch|log)\x00|(?:tmp|log|screenshots)/' +match: not_contains +--- diff --git a/evals/ship/untracked-spec/graders/spec-not-committed.md b/evals/ship/untracked-spec/graders/spec-not-committed.md new file mode 100644 index 0000000..7542ed6 --- /dev/null +++ b/evals/ship/untracked-spec/graders/spec-not-committed.md @@ -0,0 +1,6 @@ +--- +type: regex +target: { source: file, path: .git/index } +pattern: "docs/specs/" +match: not_contains +--- diff --git a/evals/ship/untracked-spec/prompt.md b/evals/ship/untracked-spec/prompt.md new file mode 100644 index 0000000..abeb55d --- /dev/null +++ b/evals/ship/untracked-spec/prompt.md @@ -0,0 +1,9 @@ +--- +description: /slice leaves its SPEC untracked. /ship builds from it and commits the feature, but never the SPEC or anything it made to report on the work. +max_turns: 80 +timeout_seconds: 3600 +allowed_tools: + [Read, Glob, Grep, Skill, Bash, Write, Edit, Workflow, AskUserQuestion] +--- + +Ship docs/specs/invoice-due-dates.md. diff --git a/evals/ship/untracked-spec/scaffold.sh b/evals/ship/untracked-spec/scaffold.sh new file mode 100755 index 0000000..571e17a --- /dev/null +++ b/evals/ship/untracked-spec/scaffold.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../billing-app.sh" + +branch_off invoice-due-dates + +mkdir -p docs/specs +cat > docs/specs/invoice-due-dates.md <<'MD' +# Invoice due dates + +Customers keep asking when an invoice is due. Show it, and flag the late ones. + +## Acceptance criteria + +- [ ] An invoice is due 30 days after it's issued. One issued on 2026-03-01 is due on 2026-03-31. +- [ ] An unpaid invoice is overdue starting the day after it's due. A paid invoice is never overdue. + +## Out of scope + +- Late fees and reminder emails. +MD diff --git a/evals/slice/auto-invoice-export-sprawl/case.yaml b/evals/slice/auto-invoice-export-sprawl/case.yaml new file mode 100644 index 0000000..2b60281 --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: slice-auto-invoice-export-sprawl +context: + scaffold_script: scaffold.sh diff --git a/evals/slice/auto-invoice-export-sprawl/graders/cuts-a-part.md b/evals/slice/auto-invoice-export-sprawl/graders/cuts-a-part.md new file mode 100644 index 0000000..ae18793 --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/cuts-a-part.md @@ -0,0 +1,11 @@ +--- +type: llm +--- + +The issue asked for invoice export as CSV and PDF, a date range filter, and a monthly email to the accountant. + +The SPEC sits between a `` line and a `` line. Those are two separate markers, not one comment around it, so everything between them counts as the SPEC. + +PASS if the SPEC's acceptance criteria leave out at least one of PDF, the date range filter, or the monthly email. + +FAIL if the criteria cover all three, or the reply has no SPEC. diff --git a/evals/slice/auto-invoice-export-sprawl/graders/given-when-then.md b/evals/slice/auto-invoice-export-sprawl/graders/given-when-then.md new file mode 100644 index 0000000..d3094fe --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/given-when-then.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '^- \[ \] Given .+, when .+, then ' +flags: m +--- diff --git a/evals/slice/auto-invoice-export-sprawl/graders/head-unmoved.md b/evals/slice/auto-invoice-export-sprawl/graders/head-unmoved.md new file mode 100644 index 0000000..50e5f0f --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/head-unmoved.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: "^[0-9a-f]{40} [0-9a-f]{40} " +flags: m +match: "count:3" +--- diff --git a/evals/slice/auto-invoice-export-sprawl/graders/names-model.md b/evals/slice/auto-invoice-export-sprawl/graders/names-model.md new file mode 100644 index 0000000..26bef28 --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/names-model.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The reply is a GitHub comment. The SPEC sits between a `` line and a `` line. + +PASS if the reply's last paragraph comes after the `` line, says Claude wrote it, and names the specific model, such as "Claude Opus 5.5", "Claude Sonnet 4.5", or a model ID like `claude-opus-5-5`. Any model name or ID counts, even one you don't recognize. The paragraph may wrap onto two lines. + +FAIL if there's no such paragraph, it says only "Claude" or "Claude Code" with no model, it sits inside the SPEC, or other content comes after it. diff --git a/evals/slice/auto-invoice-export-sprawl/graders/no-questions.md b/evals/slice/auto-invoice-export-sprawl/graders/no-questions.md new file mode 100644 index 0000000..2f469db --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/no-questions.md @@ -0,0 +1,6 @@ +--- +type: tool_used +tool: AskUserQuestion +min: 0 +max: 0 +--- diff --git a/evals/slice/auto-invoice-export-sprawl/graders/no-spec-written.md b/evals/slice/auto-invoice-export-sprawl/graders/no-spec-written.md new file mode 100644 index 0000000..5446f1e --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/no-spec-written.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Write +input_match: '"file_path"\s*:\s*"[^"]*docs/specs/' +min: 0 +max: 0 +--- diff --git a/evals/slice/auto-invoice-export-sprawl/graders/one-job-story.md b/evals/slice/auto-invoice-export-sprawl/graders/one-job-story.md new file mode 100644 index 0000000..1737612 --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/one-job-story.md @@ -0,0 +1,6 @@ +--- +type: regex +pattern: '^When .+\nI want to .+\nSo I can ' +flags: m +match: "count:1" +--- diff --git a/evals/slice/auto-invoice-export-sprawl/graders/records-assumptions.md b/evals/slice/auto-invoice-export-sprawl/graders/records-assumptions.md new file mode 100644 index 0000000..37bc71d --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/records-assumptions.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '^## Assumptions\n+- \S' +flags: m +--- diff --git a/evals/slice/auto-invoice-export-sprawl/graders/reuses-customer-csv.md b/evals/slice/auto-invoice-export-sprawl/graders/reuses-customer-csv.md new file mode 100644 index 0000000..570db0f --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/reuses-customer-csv.md @@ -0,0 +1,9 @@ +--- +type: llm +--- + +The app already exports customers to CSV: `Customer.to_csv` in app/models/customer.rb, served by the `format.csv` branch of `CustomersController#index`. + +PASS if the reply points to that customer CSV export, by class, method, or file path, as something the invoice export can reuse or copy. + +FAIL if the reply doesn't mention the existing customer CSV export. diff --git a/evals/slice/auto-invoice-export-sprawl/graders/skill-fired.md b/evals/slice/auto-invoice-export-sprawl/graders/skill-fired.md new file mode 100644 index 0000000..404a36c --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?slice"' +--- diff --git a/evals/slice/auto-invoice-export-sprawl/graders/spec-markers.md b/evals/slice/auto-invoice-export-sprawl/graders/spec-markers.md new file mode 100644 index 0000000..74e4f10 --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/graders/spec-markers.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '^\n(?:(?!```markdown)[\s\S])+?\n$' +flags: m +--- diff --git a/evals/slice/auto-invoice-export-sprawl/prompt.md b/evals/slice/auto-invoice-export-sprawl/prompt.md new file mode 100644 index 0000000..e9dff59 --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/prompt.md @@ -0,0 +1,12 @@ +--- +description: The same sprawling invoice export idea, run unattended from a GitHub issue, so the skill cuts scope without asking, records its guesses, and replies with the full SPEC instead of writing a file. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash, Write, AskUserQuestion] +--- + +Run /slice --auto on this GitHub issue. Your reply gets posted back to the issue as a comment. + + +Our accountant keeps asking for invoices. I want invoice export: CSV and PDF, filter by date range, and a monthly email that sends the export to the accountant automatically. + diff --git a/evals/slice/auto-invoice-export-sprawl/scaffold.sh b/evals/slice/auto-invoice-export-sprawl/scaffold.sh new file mode 100755 index 0000000..21aee89 --- /dev/null +++ b/evals/slice/auto-invoice-export-sprawl/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../invoicing-app.sh" diff --git a/evals/slice/invoice-export-sprawl/case.yaml b/evals/slice/invoice-export-sprawl/case.yaml new file mode 100644 index 0000000..d0c62ac --- /dev/null +++ b/evals/slice/invoice-export-sprawl/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: slice-invoice-export-sprawl +context: + scaffold_script: scaffold.sh diff --git a/evals/slice/invoice-export-sprawl/graders/head-unmoved.md b/evals/slice/invoice-export-sprawl/graders/head-unmoved.md new file mode 100644 index 0000000..50e5f0f --- /dev/null +++ b/evals/slice/invoice-export-sprawl/graders/head-unmoved.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: "^[0-9a-f]{40} [0-9a-f]{40} " +flags: m +match: "count:3" +--- diff --git a/evals/slice/invoice-export-sprawl/graders/leads-with-a-cut.md b/evals/slice/invoice-export-sprawl/graders/leads-with-a-cut.md new file mode 100644 index 0000000..b06b657 --- /dev/null +++ b/evals/slice/invoice-export-sprawl/graders/leads-with-a-cut.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The user asked for invoice export as CSV and PDF, a date range filter, and a monthly email to the accountant. + +PASS if a message from Claude to the user proposes leaving at least one of those named parts out of the first slice, stated as its own call that the user can push back on. + +FAIL if no message proposes a cut, or the messages only ask the user which parts to include. diff --git a/evals/slice/invoice-export-sprawl/graders/no-spec-written.md b/evals/slice/invoice-export-sprawl/graders/no-spec-written.md new file mode 100644 index 0000000..5446f1e --- /dev/null +++ b/evals/slice/invoice-export-sprawl/graders/no-spec-written.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Write +input_match: '"file_path"\s*:\s*"[^"]*docs/specs/' +min: 0 +max: 0 +--- diff --git a/evals/slice/invoice-export-sprawl/graders/reuses-customer-csv.md b/evals/slice/invoice-export-sprawl/graders/reuses-customer-csv.md new file mode 100644 index 0000000..abc6357 --- /dev/null +++ b/evals/slice/invoice-export-sprawl/graders/reuses-customer-csv.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The app already exports customers to CSV: `Customer.to_csv` in app/models/customer.rb, served by the `format.csv` branch of `CustomersController#index`. + +PASS if a message from Claude to the user points to that customer CSV export, by class, method, or file path, as something the invoice export can reuse or copy. + +FAIL if no message from Claude mentions the existing customer CSV export. diff --git a/evals/slice/invoice-export-sprawl/graders/skill-fired.md b/evals/slice/invoice-export-sprawl/graders/skill-fired.md new file mode 100644 index 0000000..404a36c --- /dev/null +++ b/evals/slice/invoice-export-sprawl/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?slice"' +--- diff --git a/evals/slice/invoice-export-sprawl/prompt.md b/evals/slice/invoice-export-sprawl/prompt.md new file mode 100644 index 0000000..06e9eaa --- /dev/null +++ b/evals/slice/invoice-export-sprawl/prompt.md @@ -0,0 +1,8 @@ +--- +description: A sprawling invoice export idea in an app that already exports customers to CSV, so the skill opens its interview by proposing cuts and pointing at the customer CSV export to reuse, and writes no SPEC yet. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash, Write] +--- + +Our accountant keeps asking for invoices. I want invoice export: CSV and PDF, filter by date range, and a monthly email that sends the export to the accountant automatically. Can you slice this down to what we should build first? diff --git a/evals/slice/invoice-export-sprawl/scaffold.sh b/evals/slice/invoice-export-sprawl/scaffold.sh new file mode 100755 index 0000000..21aee89 --- /dev/null +++ b/evals/slice/invoice-export-sprawl/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../invoicing-app.sh" diff --git a/evals/slice/invoicing-app.sh b/evals/slice/invoicing-app.sh new file mode 100644 index 0000000..0c2c733 --- /dev/null +++ b/evals/slice/invoicing-app.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null +commit() { git add -A && git commit -q -m "$1"; } + +mkdir -p app/models app/controllers app/views/customers app/views/invoices config db test/controllers + +cat > README.md <<'MD' +# Invoicing + +A Rails 8 app for customers and the invoices we send them. Run the tests with `bin/rails test`. +MD + +commit "Set up the app" + +cat > app/models/customer.rb <<'RUBY' +require "csv" + +class Customer < ApplicationRecord + has_many :invoices + + def self.to_csv(customers) + CSV.generate do |csv| + csv << ["Name", "Email"] + customers.each { |customer| csv << [customer.name, customer.email] } + end + end +end +RUBY + +cat > app/controllers/customers_controller.rb <<'RUBY' +class CustomersController < ApplicationController + def index + @customers = Customer.order(:name) + + respond_to do |format| + format.html + format.csv { send_data Customer.to_csv(@customers), filename: "customers.csv" } + end + end +end +RUBY + +cat > app/views/customers/index.html.erb <<'ERB' +

Customers

+<% @customers.each do |customer| %> +

<%= customer.name %> (<%= customer.email %>)

+<% end %> +<%= link_to "Download CSV", customers_path(format: :csv) %> +ERB + +cat > config/routes.rb <<'RUBY' +Rails.application.routes.draw do + resources :customers, only: :index +end +RUBY + +cat > test/controllers/customers_controller_test.rb <<'RUBY' +require "test_helper" + +class CustomersControllerTest < ActionDispatch::IntegrationTest + test "downloads customers as CSV" do + Customer.create!(name: "Acme", email: "ap@acme.example") + + get customers_path(format: :csv) + + assert_equal "Name,Email\nAcme,ap@acme.example\n", response.body + end +end +RUBY + +commit "Add customers, with CSV export" + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[8.0].define(version: 2026_03_04_100000) do + create_table "customers", force: :cascade do |t| + t.string "name" + t.string "email" + t.timestamps + end + + create_table "invoices", force: :cascade do |t| + t.references "customer", null: false + t.string "number" + t.integer "amount_cents" + t.date "issued_on" + t.date "due_on" + t.date "paid_on" + t.timestamps + end +end +RUBY + +cat > app/models/invoice.rb <<'RUBY' +class Invoice < ApplicationRecord + belongs_to :customer + + def paid? + paid_on.present? + end +end +RUBY + +cat > app/controllers/invoices_controller.rb <<'RUBY' +class InvoicesController < ApplicationController + def index + @invoices = Invoice.includes(:customer).order(issued_on: :desc) + end +end +RUBY + +cat > app/views/invoices/index.html.erb <<'ERB' +

Invoices

+ + <% @invoices.each do |invoice| %> + + + + + + + + <% end %> +
<%= invoice.number %><%= invoice.customer.name %><%= number_to_currency(invoice.amount_cents / 100.0) %><%= invoice.due_on %><%= invoice.paid? ? "Paid" : "Unpaid" %>
+ERB + +cat > config/routes.rb <<'RUBY' +Rails.application.routes.draw do + resources :customers, only: :index + resources :invoices, only: :index +end +RUBY + +commit "Add invoices" diff --git a/evals/slice/overdue-flag-already-slice/case.yaml b/evals/slice/overdue-flag-already-slice/case.yaml new file mode 100644 index 0000000..7081121 --- /dev/null +++ b/evals/slice/overdue-flag-already-slice/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: slice-overdue-flag-already-slice +context: + scaffold_script: scaffold.sh diff --git a/evals/slice/overdue-flag-already-slice/graders/draft-has-criteria.md b/evals/slice/overdue-flag-already-slice/graders/draft-has-criteria.md new file mode 100644 index 0000000..08ecda6 --- /dev/null +++ b/evals/slice/overdue-flag-already-slice/graders/draft-has-criteria.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +PASS if a message from Claude to the user contains a SPEC draft whose acceptance criteria about flagging overdue invoices are written as Given / when / then. + +FAIL if no message from Claude contains acceptance criteria in that shape. diff --git a/evals/slice/overdue-flag-already-slice/graders/draft-has-job-story.md b/evals/slice/overdue-flag-already-slice/graders/draft-has-job-story.md new file mode 100644 index 0000000..0c96c15 --- /dev/null +++ b/evals/slice/overdue-flag-already-slice/graders/draft-has-job-story.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +PASS if a message from Claude to the user contains a SPEC draft with a job story about overdue invoices written as three lines starting "When", "I want to", and "So I can". + +FAIL if no message from Claude contains a job story in that shape. diff --git a/evals/slice/overdue-flag-already-slice/graders/head-unmoved.md b/evals/slice/overdue-flag-already-slice/graders/head-unmoved.md new file mode 100644 index 0000000..50e5f0f --- /dev/null +++ b/evals/slice/overdue-flag-already-slice/graders/head-unmoved.md @@ -0,0 +1,7 @@ +--- +type: regex +target: { source: file, path: .git/logs/HEAD } +pattern: "^[0-9a-f]{40} [0-9a-f]{40} " +flags: m +match: "count:3" +--- diff --git a/evals/slice/overdue-flag-already-slice/graders/no-spec-written.md b/evals/slice/overdue-flag-already-slice/graders/no-spec-written.md new file mode 100644 index 0000000..5446f1e --- /dev/null +++ b/evals/slice/overdue-flag-already-slice/graders/no-spec-written.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Write +input_match: '"file_path"\s*:\s*"[^"]*docs/specs/' +min: 0 +max: 0 +--- diff --git a/evals/slice/overdue-flag-already-slice/graders/skill-fired.md b/evals/slice/overdue-flag-already-slice/graders/skill-fired.md new file mode 100644 index 0000000..404a36c --- /dev/null +++ b/evals/slice/overdue-flag-already-slice/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?slice"' +--- diff --git a/evals/slice/overdue-flag-already-slice/prompt.md b/evals/slice/overdue-flag-already-slice/prompt.md new file mode 100644 index 0000000..7bb0e5e --- /dev/null +++ b/evals/slice/overdue-flag-already-slice/prompt.md @@ -0,0 +1,8 @@ +--- +description: Flagging overdue invoices on the list is already one slice, so the skill skips the interview, shows the full SPEC draft, and waits for approval before writing it. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash, Write] +--- + +Slice this into a spec: on the invoices page I can't tell which invoices are overdue, so I don't know who to chase. Overdue means past its due date and still unpaid. I just want those marked on the list. diff --git a/evals/slice/overdue-flag-already-slice/scaffold.sh b/evals/slice/overdue-flag-already-slice/scaffold.sh new file mode 100755 index 0000000..21aee89 --- /dev/null +++ b/evals/slice/overdue-flag-already-slice/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../invoicing-app.sh" diff --git a/evals/slice/vertical-vs-horizontal-question/graders/criteria.md b/evals/slice/vertical-vs-horizontal-question/graders/criteria.md new file mode 100644 index 0000000..ff72fff --- /dev/null +++ b/evals/slice/vertical-vs-horizontal-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the answer says a vertical slice cuts through every layer (data, logic, interface) to ship something a user can use, while a horizontal slice builds one layer at a time. + +FAIL if it gets either one wrong, or asks what feature to slice instead of answering. diff --git a/evals/slice/vertical-vs-horizontal-question/graders/skill-not-fired.md b/evals/slice/vertical-vs-horizontal-question/graders/skill-not-fired.md new file mode 100644 index 0000000..1bb28b4 --- /dev/null +++ b/evals/slice/vertical-vs-horizontal-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?slice"' +min: 0 +max: 0 +--- diff --git a/evals/slice/vertical-vs-horizontal-question/prompt.md b/evals/slice/vertical-vs-horizontal-question/prompt.md new file mode 100644 index 0000000..f3c073d --- /dev/null +++ b/evals/slice/vertical-vs-horizontal-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: slice-vertical-vs-horizontal-question +description: A general question about vertical versus horizontal slices shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +What's the difference between a vertical slice and a horizontal slice when you split up a feature? diff --git a/evals/trace/reset-stubs-database-drop/case.yaml b/evals/trace/reset-stubs-database-drop/case.yaml new file mode 100644 index 0000000..a02181f --- /dev/null +++ b/evals/trace/reset-stubs-database-drop/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: trace-reset-stubs-database-drop +context: + scaffold_script: scaffold.sh diff --git a/evals/trace/reset-stubs-database-drop/graders/criteria.md b/evals/trace/reset-stubs-database-drop/graders/criteria.md new file mode 100644 index 0000000..32d5559 --- /dev/null +++ b/evals/trace/reset-stubs-database-drop/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the reply says the `Database.drop!` step (which deletes `db/development.sqlite3`) was stubbed, skipped, or run against a throwaway copy, so the real development database was left alone, and it gives the path of a trace under docs/traces/. Describing what bin/reset would do to the database is fine; that's the trace's job. + +FAIL if the reply says the delete ran against the real `db/development.sqlite3`, doesn't say how the delete was handled, or says nothing was run at all. diff --git a/evals/trace/reset-stubs-database-drop/graders/database-not-dropped.md b/evals/trace/reset-stubs-database-drop/graders/database-not-dropped.md new file mode 100644 index 0000000..8e985f5 --- /dev/null +++ b/evals/trace/reset-stubs-database-drop/graders/database-not-dropped.md @@ -0,0 +1,7 @@ +--- +type: regex +target: + source: file + path: db/development.sqlite3 +pattern: 'founder@example\.com' +--- diff --git a/evals/trace/reset-stubs-database-drop/graders/skill-fired.md b/evals/trace/reset-stubs-database-drop/graders/skill-fired.md new file mode 100644 index 0000000..dd0ee57 --- /dev/null +++ b/evals/trace/reset-stubs-database-drop/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?trace"' +--- diff --git a/evals/trace/reset-stubs-database-drop/graders/trace-file-written.md b/evals/trace/reset-stubs-database-drop/graders/trace-file-written.md new file mode 100644 index 0000000..4a0dc6f --- /dev/null +++ b/evals/trace/reset-stubs-database-drop/graders/trace-file-written.md @@ -0,0 +1,4 @@ +--- +type: file_exists +path: docs/traces/*.md +--- diff --git a/evals/trace/reset-stubs-database-drop/prompt.md b/evals/trace/reset-stubs-database-drop/prompt.md new file mode 100644 index 0000000..f404858 --- /dev/null +++ b/evals/trace/reset-stubs-database-drop/prompt.md @@ -0,0 +1,9 @@ +--- +name: trace-reset-stubs-database-drop +description: Tracing bin/reset must stub Database.drop! instead of deleting the development database. +max_turns: 60 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +Trace what bin/reset does in this app. I want what actually happens when it runs. diff --git a/evals/trace/reset-stubs-database-drop/scaffold.sh b/evals/trace/reset-stubs-database-drop/scaffold.sh new file mode 100644 index 0000000..8942959 --- /dev/null +++ b/evals/trace/reset-stubs-database-drop/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +bash "$(dirname "$0")/../sample-app.sh" diff --git a/evals/trace/sample-app.sh b/evals/trace/sample-app.sh new file mode 100644 index 0000000..674668d --- /dev/null +++ b/evals/trace/sample-app.sh @@ -0,0 +1,165 @@ +#!/usr/bin/env bash +# Builds a tiny Ruby + sqlite3 app in the current directory. No gems, no network. +set -euo pipefail + +mkdir -p bin config db lib + +cat > .gitignore <<'EOF' +db/*.sqlite3 +tmp/ +EOF + +cat > config/environment.rb <<'RUBY' +APP_ENV = ENV.fetch("APP_ENV", "development") +Dir[File.expand_path("../lib/*.rb", __dir__)].sort.each { |file| require file } +RUBY + +cat > db/schema.sql <<'SQL' +CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE); +CREATE TABLE workspaces (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, name TEXT NOT NULL); +CREATE TABLE jobs (id INTEGER PRIMARY KEY, job TEXT NOT NULL, arg INTEGER, done INTEGER DEFAULT 0); +SQL + +cat > lib/database.rb <<'RUBY' +module Database + def self.path + File.expand_path("../db/#{APP_ENV}.sqlite3", __dir__) + end + + def self.execute(sql) + out = IO.popen(["sqlite3", path, sql], &:read) + raise "sqlite3 failed: #{sql}" unless $?.success? + out + end + + def self.quote(value) + "'#{value.to_s.gsub("'", "''")}'" + end + + def self.drop! + File.delete(path) if File.exist?(path) + end + + def self.setup! + execute(File.read(File.expand_path("../db/schema.sql", __dir__))) + end +end +RUBY + +cat > lib/user.rb <<'RUBY' +class User + attr_reader :id, :email + + def initialize(id:, email:) + @id = id + @email = email + end + + def self.create(email:) + id = Integer(Database.execute("INSERT INTO users (email) VALUES (#{Database.quote(email)}) RETURNING id;")) + new(id: id, email: email).tap(&:after_create) + end + + def after_create + Workspace.provision(self) + JobQueue.enqueue("WelcomeEmailJob", id) + end +end +RUBY + +cat > lib/workspace.rb <<'RUBY' +module Workspace + def self.provision(user) + name = "#{user.email.split("@").first}'s workspace" + Integer(Database.execute("INSERT INTO workspaces (user_id, name) VALUES (#{user.id}, #{Database.quote(name)}) RETURNING id;")) + end + + def self.for(user_id) + Integer(Database.execute("SELECT id FROM workspaces WHERE user_id = #{Integer(user_id)} LIMIT 1;")) + end +end +RUBY + +cat > lib/job_queue.rb <<'RUBY' +module JobQueue + def self.enqueue(job, arg) + Database.execute("INSERT INTO jobs (job, arg) VALUES (#{Database.quote(job)}, #{Integer(arg)});") + end + + def self.work_off + Database.execute("SELECT id, job, arg FROM jobs WHERE done = 0 ORDER BY id;").each_line do |row| + id, job, arg = row.chomp.split("|") + Object.const_get(job).new.perform(Integer(arg)) + Database.execute("UPDATE jobs SET done = 1 WHERE id = #{Integer(id)};") + end + end +end +RUBY + +cat > lib/welcome_email_job.rb <<'RUBY' +require "fileutils" + +class WelcomeEmailJob + def perform(user_id) + email = Database.execute("SELECT email FROM users WHERE id = #{Integer(user_id)};").chomp + dir = File.expand_path("../tmp/mail", __dir__) + FileUtils.mkdir_p(dir) + File.write(File.join(dir, "#{Time.now.strftime("%s%N")}-welcome.txt"), "To: #{email}\nSubject: Welcome!\n") + end +end +RUBY + +cat > lib/users_controller.rb <<'RUBY' +class UsersController + def create(params) + email = params.fetch(:email).strip.downcase + return [422, "email is invalid"] unless email.match?(/\A[^@\s]+@[^@\s]+\z/) + + user = User.create(email: email) + JobQueue.enqueue("WelcomeEmailJob", user.id) + [302, "/workspaces/#{Workspace.for(user.id)}"] + end +end +RUBY + +cat > lib/maintenance.rb <<'RUBY' +module Maintenance + def self.reset! + Database.drop! + Database.setup! + User.create(email: "demo@example.com") + puts "reset #{APP_ENV} database" + end +end +RUBY + +cat > bin/signup <<'RUBY' +#!/usr/bin/env ruby +require_relative "../config/environment" + +status, location = UsersController.new.create(email: ARGV.fetch(0)) +puts "#{status} #{location}" +RUBY + +cat > bin/worker <<'RUBY' +#!/usr/bin/env ruby +require_relative "../config/environment" + +JobQueue.work_off +RUBY + +cat > bin/reset <<'RUBY' +#!/usr/bin/env ruby +require_relative "../config/environment" + +Maintenance.reset! +RUBY + +chmod +x bin/* + +sqlite3 db/development.sqlite3 < db/schema.sql +sqlite3 db/development.sqlite3 "INSERT INTO users (email) VALUES ('founder@example.com'); INSERT INTO workspaces (user_id, name) VALUES (1, 'founder''s workspace');" + +git init -q +git add -A +git -c user.name=Eval -c user.email=eval@example.com commit -qm "Initial app" diff --git a/evals/trace/sql-logging-question/graders/criteria.md b/evals/trace/sql-logging-question/graders/criteria.md new file mode 100644 index 0000000..779cbd0 --- /dev/null +++ b/evals/trace/sql-logging-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the response answers directly: e.g. call `.to_sql` on the relation, or set `ActiveRecord::Base.logger = Logger.new($stdout)` (the development console usually logs SQL already). + +FAIL if it offers to run a scenario, write a trace to docs/traces/, or answers with anything other than how to see the SQL. diff --git a/evals/trace/sql-logging-question/graders/skill-not-fired.md b/evals/trace/sql-logging-question/graders/skill-not-fired.md new file mode 100644 index 0000000..e84682a --- /dev/null +++ b/evals/trace/sql-logging-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?trace"' +min: 0 +max: 0 +--- diff --git a/evals/trace/sql-logging-question/prompt.md b/evals/trace/sql-logging-question/prompt.md new file mode 100644 index 0000000..f95e2e0 --- /dev/null +++ b/evals/trace/sql-logging-question/prompt.md @@ -0,0 +1,8 @@ +--- +name: trace-sql-logging-question +description: A Rails question about seeing queries shouldn't trigger the trace skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +In a Rails console, how do I see the SQL that an ActiveRecord query runs? diff --git a/evals/trace/user-signs-up/case.yaml b/evals/trace/user-signs-up/case.yaml new file mode 100644 index 0000000..32db868 --- /dev/null +++ b/evals/trace/user-signs-up/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: trace-user-signs-up +context: + scaffold_script: scaffold.sh diff --git a/evals/trace/user-signs-up/graders/criteria.md b/evals/trace/user-signs-up/graders/criteria.md new file mode 100644 index 0000000..ffe322e --- /dev/null +++ b/evals/trace/user-signs-up/graders/criteria.md @@ -0,0 +1,15 @@ +--- +type: llm +focus: trace +--- + +Judge only the content of the trace file Claude wrote to docs/traces/ (the Write call to a docs/traces/*.md path). + +PASS if all of these hold: + +- It shows the steps in this order, by their real names: `UsersController#create`, `User.create` (INSERT into users), `Workspace.provision` (INSERT into workspaces), `WelcomeEmailJob` enqueued from `User#after_create`, `WelcomeEmailJob` enqueued again from `UsersController#create`, then a 302 to `/workspaces/`. +- Every ledger step is marked `ran`, `read`, or `stubbed`. A short note after the mark is fine. +- It uses real values from the run (a concrete email, real row ids), not "a user is created". +- The double `WelcomeEmailJob` enqueue is listed under Surprises. + +FAIL if it invents steps or names not in `lib/`, misses the second `WelcomeEmailJob` enqueue, or recommends code changes inside the trace. diff --git a/evals/trace/user-signs-up/graders/ran-ruby.md b/evals/trace/user-signs-up/graders/ran-ruby.md new file mode 100644 index 0000000..2bed7c4 --- /dev/null +++ b/evals/trace/user-signs-up/graders/ran-ruby.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Bash +input_match: '"command"\s*:\s*"[^"]*\bruby\b' +--- diff --git a/evals/trace/user-signs-up/graders/reply.md b/evals/trace/user-signs-up/graders/reply.md new file mode 100644 index 0000000..0a9ad11 --- /dev/null +++ b/evals/trace/user-signs-up/graders/reply.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the reply gives the trace's path under docs/traces/ and a short headline (what sign-up did, the biggest surprise, what was stubbed or only read) without pasting the trace's ledger or drawing. A separate one-line bug callout is fine. + +FAIL if it pastes the trace into the reply, gives no path, or ends by offering more work. diff --git a/evals/trace/user-signs-up/graders/skill-fired.md b/evals/trace/user-signs-up/graders/skill-fired.md new file mode 100644 index 0000000..dd0ee57 --- /dev/null +++ b/evals/trace/user-signs-up/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?trace"' +--- diff --git a/evals/trace/user-signs-up/graders/trace-file-written.md b/evals/trace/user-signs-up/graders/trace-file-written.md new file mode 100644 index 0000000..4a0dc6f --- /dev/null +++ b/evals/trace/user-signs-up/graders/trace-file-written.md @@ -0,0 +1,4 @@ +--- +type: file_exists +path: docs/traces/*.md +--- diff --git a/evals/trace/user-signs-up/prompt.md b/evals/trace/user-signs-up/prompt.md new file mode 100644 index 0000000..a5d2d33 --- /dev/null +++ b/evals/trace/user-signs-up/prompt.md @@ -0,0 +1,9 @@ +--- +name: trace-user-signs-up +description: Tracing sign-up should run it in development and write a ledger with real names and values to docs/traces/. +max_turns: 60 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +Trace what happens when a user signs up in this app. Run it, don't just read the code. diff --git a/evals/trace/user-signs-up/scaffold.sh b/evals/trace/user-signs-up/scaffold.sh new file mode 100644 index 0000000..8942959 --- /dev/null +++ b/evals/trace/user-signs-up/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +bash "$(dirname "$0")/../sample-app.sh" diff --git a/evals/understand/receipt-before-save/case.yaml b/evals/understand/receipt-before-save/case.yaml new file mode 100644 index 0000000..8517417 --- /dev/null +++ b/evals/understand/receipt-before-save/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: understand-receipt-before-save +context: + scaffold_script: scaffold.sh diff --git a/evals/understand/receipt-before-save/graders/one-question.md b/evals/understand/receipt-before-save/graders/one-question.md new file mode 100644 index 0000000..452bd9c --- /dev/null +++ b/evals/understand/receipt-before-save/graders/one-question.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +PASS if, across all its messages, Claude asks the user exactly one question. + +FAIL if Claude asks the user no question, or two or more. diff --git a/evals/understand/receipt-before-save/graders/probes-belief.md b/evals/understand/receipt-before-save/graders/probes-belief.md new file mode 100644 index 0000000..44c28b6 --- /dev/null +++ b/evals/understand/receipt-before-save/graders/probes-belief.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +The user believes the receipt is sent from a `before_save` on Order. It's actually sent from `after_commit :send_receipt, on: :create` in app/models/order.rb, so a rolled-back order sends no receipt. + +PASS if a message from Claude to the user asks a question that makes them test that belief, such as what happens to the receipt when the transaction rolls back. + +FAIL if Claude answers it for them instead, by saying a rollback sends no receipt or that they don't need to move it. diff --git a/evals/understand/receipt-before-save/graders/short-turn.md b/evals/understand/receipt-before-save/graders/short-turn.md new file mode 100644 index 0000000..ed17b62 --- /dev/null +++ b/evals/understand/receipt-before-save/graders/short-turn.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +Ignore any short note that Claude is reading the code first. + +PASS if the rest of what Claude says to the user comes to four sentences or fewer. + +FAIL if it runs past four sentences, such as an explanation of how receipts work. diff --git a/evals/understand/receipt-before-save/graders/skill-fired.md b/evals/understand/receipt-before-save/graders/skill-fired.md new file mode 100644 index 0000000..870ac5f --- /dev/null +++ b/evals/understand/receipt-before-save/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?understand"' +--- diff --git a/evals/understand/receipt-before-save/prompt.md b/evals/understand/receipt-before-save/prompt.md new file mode 100644 index 0000000..d2b4232 --- /dev/null +++ b/evals/understand/receipt-before-save/prompt.md @@ -0,0 +1,8 @@ +--- +description: The user is sure the receipt goes out from a before_save, but it's an after_commit, so the skill's first turn asks one short question that makes them test that belief instead of correcting it. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash] +--- + +Help me understand how order receipts get sent in this app. Next I'm adding a card charge that runs in the same transaction as the order save, and if the charge fails the whole thing rolls back. My worry is that the receipt goes out from a before_save on Order, so a customer whose charge failed would still get a receipt. I want to understand it well enough to know if I have to move it. diff --git a/evals/understand/receipt-before-save/scaffold.sh b/evals/understand/receipt-before-save/scaffold.sh new file mode 100755 index 0000000..5c1496b --- /dev/null +++ b/evals/understand/receipt-before-save/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" diff --git a/evals/understand/refunds-not-built/case.yaml b/evals/understand/refunds-not-built/case.yaml new file mode 100644 index 0000000..190cf17 --- /dev/null +++ b/evals/understand/refunds-not-built/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: understand-refunds-not-built +context: + scaffold_script: scaffold.sh diff --git a/evals/understand/refunds-not-built/graders/asks-what-it-takes.md b/evals/understand/refunds-not-built/graders/asks-what-it-takes.md new file mode 100644 index 0000000..9942285 --- /dev/null +++ b/evals/understand/refunds-not-built/graders/asks-what-it-takes.md @@ -0,0 +1,8 @@ +--- +type: llm +focus: trace +--- + +PASS if a message from Claude to the user asks what they think adding refunds to this app will take, or what the app already does that refunds would touch, such as orders or the receipt email. + +FAIL if Claude lays out how to build refunds itself, or only asks about requirements, such as full versus partial refunds or which payment provider. diff --git a/evals/understand/refunds-not-built/graders/says-not-built.md b/evals/understand/refunds-not-built/graders/says-not-built.md new file mode 100644 index 0000000..7d2e5a1 --- /dev/null +++ b/evals/understand/refunds-not-built/graders/says-not-built.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +This app has customers, orders, line items, and an order receipt email. It has no refund code, column, route, or method. + +PASS if a message from Claude to the user says the app has no refunds yet. + +FAIL if no message says so, or Claude describes any refund code, column, route, or method as already existing. diff --git a/evals/understand/refunds-not-built/graders/skill-fired.md b/evals/understand/refunds-not-built/graders/skill-fired.md new file mode 100644 index 0000000..870ac5f --- /dev/null +++ b/evals/understand/refunds-not-built/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?understand"' +--- diff --git a/evals/understand/refunds-not-built/prompt.md b/evals/understand/refunds-not-built/prompt.md new file mode 100644 index 0000000..e45a960 --- /dev/null +++ b/evals/understand/refunds-not-built/prompt.md @@ -0,0 +1,8 @@ +--- +description: Refunds aren't built yet, so the skill says so and asks what the user thinks adding them will take, instead of questioning them about code that isn't there or laying out a plan. +max_turns: 80 +timeout_seconds: 1800 +allowed_tools: [Read, Glob, Grep, Skill, Agent, Bash] +--- + +I just picked up the ticket to add refunds. Help me understand how refunds work in this app before I start. diff --git a/evals/understand/refunds-not-built/scaffold.sh b/evals/understand/refunds-not-built/scaffold.sh new file mode 100755 index 0000000..5c1496b --- /dev/null +++ b/evals/understand/refunds-not-built/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" diff --git a/evals/understand/send-receipt-question/case.yaml b/evals/understand/send-receipt-question/case.yaml new file mode 100644 index 0000000..76b0457 --- /dev/null +++ b/evals/understand/send-receipt-question/case.yaml @@ -0,0 +1,4 @@ +schema_version: "1.1" +name: understand-send-receipt-question +context: + scaffold_script: scaffold.sh diff --git a/evals/understand/send-receipt-question/graders/criteria.md b/evals/understand/send-receipt-question/graders/criteria.md new file mode 100644 index 0000000..14eb752 --- /dev/null +++ b/evals/understand/send-receipt-question/graders/criteria.md @@ -0,0 +1,10 @@ +--- +type: llm +focus: trace +--- + +`send_receipt` is an `after_commit` callback on create in app/models/order.rb. + +PASS if a message from Claude to the user answers that it runs after the order is saved, once the transaction commits. + +FAIL if Claude says it runs before the save, or asks the user a question instead of answering. diff --git a/evals/understand/send-receipt-question/graders/skill-not-fired.md b/evals/understand/send-receipt-question/graders/skill-not-fired.md new file mode 100644 index 0000000..8374d09 --- /dev/null +++ b/evals/understand/send-receipt-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?understand"' +min: 0 +max: 0 +--- diff --git a/evals/understand/send-receipt-question/prompt.md b/evals/understand/send-receipt-question/prompt.md new file mode 100644 index 0000000..cfcf39c --- /dev/null +++ b/evals/understand/send-receipt-question/prompt.md @@ -0,0 +1,7 @@ +--- +description: A direct question about when a callback runs wants an answer, so it shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +Does Order#send_receipt run before or after the order gets saved? diff --git a/evals/understand/send-receipt-question/scaffold.sh b/evals/understand/send-receipt-question/scaffold.sh new file mode 100755 index 0000000..5c1496b --- /dev/null +++ b/evals/understand/send-receipt-question/scaffold.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +source "$(dirname "$0")/../shop-app.sh" diff --git a/evals/understand/shop-app.sh b/evals/understand/shop-app.sh new file mode 100644 index 0000000..b35dde3 --- /dev/null +++ b/evals/understand/shop-app.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/opt/homebrew/bin:$PATH" + +git init -q -b main +git config user.name "Eval User" +git config user.email "eval@example.com" +git config commit.gpgsign false +git config core.excludesFile /dev/null +commit() { git add -A && git commit -q -m "$1"; } + +mkdir -p app/models app/controllers app/mailers db + +cat > README.md <<'MD' +# Shop + +A Rails 8 shop. Run the tests with `bin/rails test`. +MD + +commit "Set up the shop" + +cat > db/schema.rb <<'RUBY' +ActiveRecord::Schema[8.0].define(version: 2026_09_01_100000) do + create_table "customers", force: :cascade do |t| + t.string "email" + t.timestamps + end + + create_table "orders", force: :cascade do |t| + t.references "customer", null: false + t.integer "total_cents" + t.timestamps + end + + create_table "line_items", force: :cascade do |t| + t.references "order", null: false + t.string "product_name" + t.integer "price_cents" + end +end +RUBY + +cat > app/models/customer.rb <<'RUBY' +class Customer < ApplicationRecord + has_many :orders +end +RUBY + +cat > app/models/line_item.rb <<'RUBY' +class LineItem < ApplicationRecord + belongs_to :order +end +RUBY + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + belongs_to :customer + has_many :line_items + accepts_nested_attributes_for :line_items + + before_save :compute_total + + private + + def compute_total + self.total_cents = line_items.sum(&:price_cents) + end +end +RUBY + +cat > app/controllers/orders_controller.rb <<'RUBY' +class OrdersController < ApplicationController + def create + @order = current_customer.orders.build(order_params) + + if @order.save + redirect_to @order, notice: "Thanks for your order!" + else + render :new, status: :unprocessable_entity + end + end + + private + + def order_params + params.require(:order).permit(line_items_attributes: [:product_name, :price_cents]) + end +end +RUBY + +commit "Add orders" + +cat > app/mailers/order_mailer.rb <<'RUBY' +class OrderMailer < ApplicationMailer + def receipt(order) + @order = order + mail to: order.customer.email, subject: "Your receipt for order ##{order.id}" + end +end +RUBY + +cat > app/models/order.rb <<'RUBY' +class Order < ApplicationRecord + belongs_to :customer + has_many :line_items + accepts_nested_attributes_for :line_items + + before_save :compute_total + after_commit :send_receipt, on: :create + + private + + def compute_total + self.total_cents = line_items.sum(&:price_cents) + end + + def send_receipt + OrderMailer.receipt(self).deliver_later + end +end +RUBY + +commit "Email a receipt for each order" diff --git a/evals/unrelated-rails-question/graders/criteria.md b/evals/unrelated-rails-question/graders/criteria.md new file mode 100644 index 0000000..12b394c --- /dev/null +++ b/evals/unrelated-rails-question/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the response answers the question directly: has_many :through uses a join model with its own attributes and callbacks, has_and_belongs_to_many uses a bare join table with no model. + +FAIL if it recommends a way to prompt Claude or a Claude feature instead of answering. diff --git a/evals/unrelated-rails-question/graders/skill-not-fired.md b/evals/unrelated-rails-question/graders/skill-not-fired.md new file mode 100644 index 0000000..25b302a --- /dev/null +++ b/evals/unrelated-rails-question/graders/skill-not-fired.md @@ -0,0 +1,7 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?ask-claude"' +min: 0 +max: 0 +--- diff --git a/evals/unrelated-rails-question/prompt.md b/evals/unrelated-rails-question/prompt.md new file mode 100644 index 0000000..2fc9d05 --- /dev/null +++ b/evals/unrelated-rails-question/prompt.md @@ -0,0 +1,7 @@ +--- +description: A plain Rails question shouldn't trigger the skill. +max_turns: 10 +allowed_tools: [Read, Glob, Grep, Skill] +--- + +What's the difference between has_many :through and has_and_belongs_to_many? diff --git a/evals/users-cant-sign-up/graders/criteria.md b/evals/users-cant-sign-up/graders/criteria.md new file mode 100644 index 0000000..c94552e --- /dev/null +++ b/evals/users-cant-sign-up/graders/criteria.md @@ -0,0 +1,7 @@ +--- +type: llm +--- + +PASS if the response either asks targeted questions about the failure (what users see, which users, since when, error messages), or gives a draft prompt that has the agent reproduce the bug before fixing it and names a runnable check for done. It stops for the user's input rather than fixing anything. + +FAIL if it states a cause as fact without evidence, starts fixing, or only restates the task in more words. diff --git a/evals/users-cant-sign-up/graders/skill-fired.md b/evals/users-cant-sign-up/graders/skill-fired.md new file mode 100644 index 0000000..eb3716b --- /dev/null +++ b/evals/users-cant-sign-up/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?ask-claude"' +--- diff --git a/evals/users-cant-sign-up/prompt.md b/evals/users-cant-sign-up/prompt.md new file mode 100644 index 0000000..20bb1b6 --- /dev/null +++ b/evals/users-cant-sign-up/prompt.md @@ -0,0 +1,8 @@ +--- +description: A vague bug report should get questions or a prompt that reproduces before fixing. +max_turns: 30 +timeout_seconds: 600 +allowed_tools: [Read, Glob, Grep, Skill, WebFetch] +--- + +Users can't sign up on our Rails app. How should I ask you to fix it? diff --git a/skills/ask-claude/SKILL.md b/skills/ask-claude/SKILL.md new file mode 100644 index 0000000..b567522 --- /dev/null +++ b/skills/ask-claude/SKILL.md @@ -0,0 +1,173 @@ +--- +name: ask-claude +description: Recommend the best way to have Claude do something, checked against Anthropic's current docs, then write the prompt and run it once approved. Use when someone asks how they should prompt you, what the best way to ask for something is, or which Claude feature fits a job (CLAUDE.md, skill, hook, subagent, workflow, plan mode, /goal, MCP, headless, the API), even if they don't name a feature. +argument-hint: '[task, e.g. "users can''t sign up" or "run rubocop after every edit"]' +--- + +# Ask Claude + +Two questions sound different and are the same question: how should I ask Claude to +do this? + +- "Users can't sign up." The answer is a way of working (reproduce first, plan or + don't, what proves it's fixed) and a prompt that says it. +- "Run rubocop after every edit." The answer is a feature. A line in CLAUDE.md gets + followed most of the time. A hook runs every time. Picking wrong means it quietly + doesn't happen. + +Either way, end with a prompt the user approves before anything runs. + +``` +task + | + v +1. look ...... the code and setup the task touches +2. read ...... the docs that apply, fetched now +3. ask ....... only what neither can tell you +4. recommend . the approach, why, and the prompt, shown for approval +5. run ....... here, as written +``` + +Two ways this fails. The answer comes from memory, and recommends a feature that's +been renamed, or misses the one released last month that fits better. Or the prompt +restates the task in more words and adds nothing the agent couldn't have guessed. + +## 1. Look + +The task is `$ARGUMENTS`, or ask for one. + +Skim the README, the routes, the area the task names, recent commits there. You're +looking for what the prompt can point at: the file that handles it, the pattern to +copy, the test that covers it, the command that checks it. A prompt that names +`app/controllers/registrations_controller.rb` beats one that says "the sign-up code". + +Check what's already set up too: CLAUDE.md, `.claude/settings.json` hooks, +`.claude/skills/`, `.claude/agents/`, installed skills. An installed skill that already +does the job beats writing a new one, and a hook that already exists changes the +answer. + +Stay in the repo and its Claude setup. Don't search Slack, email, or other connected +tools for context. Those hold the user's own messages, and a guess built from an old +post reads like a fact. If you need something from there, ask. + +## 2. Read the docs + +Claude's features change month to month, so don't recommend from memory. Start at the +indexes, pick the pages that bear on this task, and read them: + +- `https://code.claude.com/docs/llms.txt`: Claude Code and the Agent SDK. Skills, + hooks, subagents, workflows, permission modes, MCP, headless runs, settings. +- `https://platform.claude.com/llms.txt`: the API, prompting, tool use, Managed + Agents, models. + +Pages worth reading for most tasks: + +- `code.claude.com/docs/en/best-practices.md`: verification, explore-plan-code, + context, when to use subagents. +- `code.claude.com/docs/en/features-overview.md`: which feature fits which goal. +- `platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices.md`: + when the task is writing a prompt for something else, like a system prompt, a + subagent, or an API call. + +Then whatever the task points at: `hooks-guide.md` for "every time", `workflows.md` +for many agents, `headless.md` for CI. Two to five pages is usually enough. + +Keep the URL of each page you lean on. If a fetch fails, say so and label anything +you then say from memory as such. + +## 3. Ask + +Ask in one turn, only what the code and docs can't answer: + +- **What's happening.** Who, what they see, since when. Pasted errors, tickets, logs + beat a description. "Some users" is a clue: which ones? +- **What should happen.** Code shows what it does, never what it should. +- **What done looks like.** Diagnose and report, or fix? A fix they'll ship, or a + spike to estimate from? For a feature: just me, or the whole team via git? + +"Don't know" is a fine answer. It goes in the prompt as an unknown. + +## 4. Recommend + +Lead with the approach, then the prompt that carries it out: + +```` +**Approach:** a PostToolUse hook in .claude/settings.json that runs rubocop on the +edited file. + +**Why:** "Unlike CLAUDE.md instructions which are advisory, hooks are deterministic +and guarantee the action happens." +https://code.claude.com/docs/en/best-practices.md + +**Not:** +- CLAUDE.md line: followed most of the time, not every time. +- Stop hook: runs once per turn, so a bad edit lingers until the end. + +``` +Add a PostToolUse hook to .claude/settings.json (checked in, so the team gets it) +that runs `bundle exec rubocop -a` on the file Claude just edited, for Edit and +Write only. Read https://code.claude.com/docs/en/hooks.md for the input format +first. + +Done when: editing app/models/user.rb with a style offense gets auto-corrected, +and an offense rubocop can't fix shows up for Claude to handle. Show the +settings.json diff and the hook firing once. +``` + +Change anything, or run it? +```` + +The **Why** quotes or points at the doc, so the user can check it. **Not** names the +one or two alternatives they'd likely reach for, and what's wrong with each. Skip it +when nothing else was close. + +The best answer isn't always a Claude feature. "Post a ticket digest every morning" +might be a background job in the app, if the app already has a scheduler, a Slack +client, and an LLM gem. That version gets code review, tests, and error tracking, +and doesn't stop when one person's account does. Weigh plain code alongside Claude's +features and pick whichever fits; the docs tell you what Claude can do, not whether +it should. + +For a coding task the approach is how to work, and the prompt carries most of the +weight. Write it the way you'd brief a sharp colleague who's never seen this app. +Use only the parts that earn their place: + +- **The ask, said outright.** "Find out why and fix it" and "find out why, change + nothing" get different work. Say which. +- **What we know, and from whom.** The user's words, pasted evidence, and a source + on each claim: user, ticket, unverified. The agent weighs a guess and a log line + differently only if it can tell them apart. +- **Where to look.** Files, routes, commits you found in step 1, with paths. +- **The why behind each constraint.** "Don't touch the Google credentials, they're + shared with the mobile app" gets followed more sensibly than "NEVER touch + credentials". Skip ALL-CAPS; it makes agents overreact. +- **How to work, when the task needs it.** Bug: reproduce before fixing, with a + failing test or `/trace`. Unclear approach or many files: plan mode first. Broad + reading: subagents, each with a narrow question. Diff you could describe in one + sentence: none of this. +- **Out of scope.** What not to touch, what not to add. Agents widen tasks on their + own. +- **Done when.** A check that runs, named exactly: `bin/rspec +spec/requests/auth_callbacks_spec.rb` passes, not "the spec passes". Use the + project's own test command from step 1. Then what to report: the cause in a line, + the command and its output as proof, what changed, what it couldn't check. +- **Can't reach.** Production data, error trackers, third-party dashboards. Say so, + so a finding from development isn't read as one from production. + +Say what to do, not only what to avoid. Plain prose and short lists; wrap pasted +material in tags like `` so it's clearly data. + +If another skill fits better, that's the approach: `/slice` for a feature that isn't +scoped yet, `/domain-model` when the business process itself is unclear. + +Then stop. Don't run a prompt they haven't seen. A wrong assumption costs a sentence +to fix now and an hour of work later. + +## 5. Run it + +On approval, do what the prompt says, here, as if they'd typed it. Edits: revise, +show it again. + +If it'd go better elsewhere, say so and let them pick: a fresh session for a big +task, plan mode for an unclear one. The prompt stands on its own, so it can be +pasted there as is. diff --git a/skills/challenge/SKILL.md b/skills/challenge/SKILL.md deleted file mode 100644 index 80ea0b7..0000000 --- a/skills/challenge/SKILL.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -name: challenge -description: Pressure-test an assumption, decision, or inherited constraint — Socratic cross-examination that forces you to defend or abandon your position -argument-hint: "[assumption or decision to examine]" ---- - -## Behavior - -This is a conversation, not an audit. Do not produce structured output. Do not list findings upfront. Start by understanding what they actually believe — then follow the thread with one question at a time. - -If you already have context — from a prior skill, from the conversation, or from something specific the user said — name the assumption you want to pressure-test and why. Then go straight to questioning. Do not ask them to restate what you already know. - -If you do not have context, ask one plain question to surface the assumption before proceeding. - -Ask one question at a time, following the gaps in their reasoning. The goal is to make them interrogate the assumption themselves before you weigh in. Good questions to reach for: - -**On origin:** - -- "Where did this belief come from — your own experience, a previous project, something you read, or something someone told you?" -- "Is this a Rails convention, or did you choose it consciously?" -- "Have you actually tested this, or is it untested instinct?" - -**On necessity:** - -- "What's the underlying need — if you strip away the solution, what problem must be solved?" -- "Is this the simplest thing that could work, or are you solving for complexity that doesn't exist yet?" (Beck / XP) -- "Are you building for now, or for a future that might not arrive?" (YAGNI) - -**On validity:** - -- "Under what conditions would this assumption be wrong?" -- "What evidence would change your mind?" -- "Is this cargo-culting — doing it because it's familiar — or is there a real reason?" - -**On alternatives:** - -- "What's the simplest alternative you haven't seriously considered?" -- "If you couldn't do it this way, what would you do?" -- "What does Rails already give you that makes this unnecessary?" (convention over configuration) - -Have opinions. When an assumption is weak, say so and say why. - -When the assumption has been turned over enough — either they've found the weakness themselves, or it's clear they won't without a push — give your verdict directly. Is the assumption valid, partially valid, or worth rejecting? Name the underlying need, name the better path if there is one, and say why. - -Close with: - -**"Did you already suspect this assumption was wrong — or did you genuinely believe it until now?"** - -Wait for their answer. Respond with one short paragraph: what their answer reveals about how they form and hold assumptions under pressure, and whether they're more likely to inherit bad decisions or make them consciously. - -## Tone - -Rigorous and direct. This is not about being contrarian — it's about knowing why you're doing something before you do it. Push hard on weak assumptions. Confirm strong ones clearly. Never mistake familiarity for validity. diff --git a/skills/commit/SKILL.md b/skills/commit/SKILL.md new file mode 100644 index 0000000..9cbc9b4 --- /dev/null +++ b/skills/commit/SKILL.md @@ -0,0 +1,137 @@ +--- +name: commit +description: Commit the current changes as atomic commits, recording risks, tradeoffs, and alternatives considered. +argument-hint: "[optional context to fold into the messages]" +--- + +# Commit + +The history is the audit log for what an agent did. Months from now someone runs +`git blame` on a line nobody remembers writing, and the commit message is the only +record of why it's there. Inside `/ship` it matters sooner: the `/diff-explainer` +step never saw the session that wrote the code. It gets the SPEC, the step reports, +and these commits, and it won't annotate a decision nobody wrote down. + +So a message's job is what `/diff-explainer` does for a whole branch, for one +commit: the why, the risks, the tradeoffs, and what got tried and thrown away. The +diff already shows what changed. + +An argument is context ("addressing review feedback", "the migration is risky"), +never the literal message. Don't stop to ask for approval. Being asked to commit +means make the call, then report it. + +## 1. See what's there + +```bash +git status --porcelain -uall +git diff +git diff --staged +git log --oneline -15 +``` + +Nothing to commit? Say so and stop. Never make an empty commit. + +## 2. Commit only what you made + +The tree can hold more than your work: a file the user was editing, a scratch +script, a `.env` with credentials, a log someone forgot. Commit what this session +produced. Leave the rest alone and name it in your report, so it doesn't look +like an oversight. + +Can't tell if a change is yours? It isn't. Leaving it out costs a follow-up +commit. Putting it in ships someone else's half-finished work under your name. +Never commit anything that looks like a secret, even if you made it. + +## 3. Group into atomic commits + +One commit is one change that stands on its own. The test: if someone reverted +this commit alone, would what's left still make sense and still pass? Pass means +it's atomic. Fail means it's split too fine or bundled with something unrelated. + +- A feature is one commit even across ten files. Model, migration, controller, + view, and tests together. Splitting them gives commits that are each broken. +- Tests go with the code they test, not in a commit of their own. +- A refactor that makes room for the feature is its own commit, first. It changes + no behavior, so a reviewer can trust it on a green suite and read the feature + commit without the noise. +- A bug fix found along the way is its own commit, even inside the same file. +- A dependency bump the feature needed is usually its own commit. + +When unsure, fewer commits. Over-split history reads worse than cohesive history. + +## 4. Stage exactly the group + +Whole files: `git add `. Never `git add .` or `git add -A`, which sweeps in +everything step 2 left out. + +One file holding two groups: stage only the hunks for this one. `git add -p` needs +a terminal you don't have, so write those hunks to a patch and +`git apply --cached `. Check `git diff --staged` before every commit, since +a wrong patch fails quietly into a commit of the wrong lines. + +Hooks run. If one fails or rewrites files, surface what it said, don't route +around it. No `--no-verify`, no amending, no pushing. This skill only adds new +commits on top. + +## 5. Write the message + +**Subject:** imperative, capitalized, no period, around 50 characters. Code +identifiers in backticks. "Cache `Mitie::NER` behind a mutex", not "Updated +caching". + +**Body:** blank line, then prose wrapped at 72. Open with why: the problem, or +what this makes possible. Then whichever of these the session actually turned up. +Most commits have one or two. None is fine. + +- **Tried and dropped.** "Memoizing without a lock failed during asset + precompile, because the model file doesn't exist yet." This saves the next + person from suggesting it. +- **Risks.** Deploy ordering, a migration that locks a big table, a new hard + dependency, what happens at 10x the data, anything that fails silently. +- **Tradeoffs.** What got worse so something else got better, and why that + trade. +- **Left out on purpose.** What this doesn't handle yet, stated as a fact. +- **Not checked.** Suite not run, suite red, a path only tested by hand, a + service stubbed that behaves differently for real. An audit log that rounds + "didn't run it" up to silence is worse than none. + +Write these for a teammate skimming `git log`, not for the code. Plain words, no +"this ensures", "robust", "it's worth noting". Don't list the files you touched. +Bullets are fine when there are three separate risks. Otherwise prose. + +**Never invent a why.** The good reasons come from this session: what you tried, +what broke, what surprised you. None of that is in the diff. If you're committing +work you didn't watch get made and nothing records why, write what the change +does and stop. A plausible reason that's wrong is worse than none, because the +next reader trusts it. If the user or the task gave you a reason, use it. + +**Trivial changes** (typo, version bump, formatting) get a subject and no body. + +End every message with the co-author trailer this session normally appends, +naming the model you're actually running, after a blank line. + +### Example + +``` +Charge the card before creating the `Order` + +Creating the order first left orphans whenever Stripe declined, and +the cleanup job that deleted them raced customers retrying checkout. + +We tried wrapping both in a transaction, but a transaction can't roll +back a charge that already went through. Charging first means a crash +between the charge and the insert leaves a paid charge with no order. +That's rarer and visible in Stripe, so we traded one bug for a +smaller one. `ReconcileChargesJob` catching it is not built yet. + +Checkout specs pass against the Stripe test double. Real declines and +network timeouts were not exercised. + +Co-Authored-By: Claude +``` + +## 6. Report + +Show `git log --oneline` for the new commits. Then one line each for anything +worth knowing: a split you made, files you left uncommitted and why, a hook that +complained. diff --git a/skills/diff-explainer/SKILL.md b/skills/diff-explainer/SKILL.md new file mode 100644 index 0000000..0a0ddff --- /dev/null +++ b/skills/diff-explainer/SKILL.md @@ -0,0 +1,154 @@ +--- +name: diff-explainer +description: Builds a shareable HTML walkthrough of the current changes, highlighting risks, tradeoffs, and alternatives considered. +argument-hint: "[PR number, branch, or paths to explain]" +--- + +# Diff explainer + +The diff already shows what changed. What it can't show is why — why this approach +and not the obvious one, what broke when you tried that, what you're nervous about, +what you decided not to do. Supply that. Your reader is a sharp, time-poor developer +who may not know this stack. + +## 1. Work out what you're explaining + +No argument means the current branch against its base, diffed from the merge base +so other people's commits don't leak in. + +```bash +BASE=$(git rev-parse --verify --quiet @{upstream} \ + || git rev-parse --verify --quiet refs/remotes/origin/HEAD \ + || git rev-parse --verify --quiet refs/heads/main \ + || git rev-parse --verify --quiet refs/heads/master) +MB=$(git merge-base "$BASE" HEAD) +test -n "$MB" || echo "No base found — ask which branch to diff against." +git diff --stat "$MB" && git log --oneline "$MB"..HEAD +git status --porcelain -uall # untracked files the diff won't show +``` + +Size up the change from the stat before reading `git diff "$MB"` — a diff you pull +into context whole is one you can no longer decide to skip. Upstream first, and +`refs/heads/` not bare `main`, or you diff against the wrong base: a fork of +`develop` drags in everyone's `develop` commits, a trunk named anything else finds +no base at all, and a _tag_ called `main` beats the branch of the same name. Empty +`$MB` also means an unborn HEAD — no commits yet, nothing to explain. + +`git diff "$MB"` covers committed and uncommitted work both, so a branch with no +commits of its own still works. An argument overrides. Resolve it as a rev first +(`git rev-parse --verify --quiet `); anything else is a path, and goes after +`--` so a `docs` branch and a `docs/` directory can't collide. A bare number is a +PR (`gh pr diff `, plus `gh pr view ` for the body and linked issue) unless a +branch by that name exists; with no working `gh`, say so and take the branch. If the +change is obvious — a version bump, a typo — say so and skip the artifact. + +## 2. Who's reading + +Explain the change in this stack's own terms unless you know the reader's +background: the user named it ("for a WordPress developer"), or their instructions +say what they know. Don't guess one, and don't default to a popular framework. If +the project is already in their stack, write plainly, no framework comparisons. +If it isn't, translate each unfamiliar concept into their terms inline, in the +annotation where the reviewer meets it. Never build a glossary or translation +table: that makes them hold a mapping and look things up, where an analogy in the +sentence costs nothing. +Read `references/translation.md` first: it covers how to use an analogy without it +becoming noise. + +## 3. Gather the why + +If the change was made in this session, that's your best source by far — what got +tried and thrown away, what surprised you, none of which survives in the diff. +Otherwise reconstruct from commits, the PR body, the linked issue, and surrounding +code, then ask the author — two sharp questions beat a page of confident guessing. + +**Never invent rationale.** A plausible why that's wrong is worse than none, because +the reviewer approves on it. If you can't establish why, leave it unannotated or say +plainly that it isn't recorded anywhere. If you find a real bug while writing up, +tell the user directly rather than burying it in a note they may skim. + +## 4. Choose the annotations, then write them + +Show the whole diff; annotate only where you have something to say — a decision, a +risk, a tradeoff, an abandoned alternative. A change that looks wrong until you know +the reason, or a deletion that looks unrelated, is a decision. Skip renames, +formatting, and mechanical churn. Generated files get one line saying so and an +`` elision line inside the `
` instead of their diff.
+
+The pull toward over-annotating is strong, since every hunk has _something_ sayable.
+Resist it: a walkthrough beats the raw diff only by being shorter than it, so a big
+diff gets a shorter page, not a longer one. Ten annotations read beat thirty
+skimmed. Before publishing, delete every annotation a competent reviewer would
+already know, or wouldn't review any differently for — that pass is where most of
+the value gets made. **Order the steps as an argument, not an alphabetical
+listing:** lead with the file where the change actually lives, group files that only
+make sense together, and if B must be understood before A means anything, B first.
+
+Write each annotation in one to three sentences; a longer one is usually two, or a
+paragraph belonging in "Start here". If a sentence would still be true with the diff
+hidden, it's a _what_ and can go. The ones that earn their place are the ones an
+author would rather not write — this is a workaround, this gets slow at 10x the
+data — and the dead ends, since "we tried X, it failed because Y" pre-empts the
+reviewer's first suggestion. Plain words: no "it's worth noting", "this ensures".
+
+**Open with the problem and one analogy.** The reviewer may have no context on the
+problem this branch solves, and a mechanism means nothing until they know what
+went wrong. So "Start here" leads with the problem in plain words (what a user
+saw, what someone needed), then one comparison from everyday life a kid would
+follow, both before any file, class or code name. Sessions held in each server's
+memory are a coat check where each attendant keeps the tickets in their own
+pocket: one goes home at shift change, and every coat they took in is stranded.
+Map its pieces onto the real ones, then say where it breaks if the gap will bite.
+One analogy, in "Start here" only; the annotations stay in the code's terms. This
+isn't step 2's framework translation: it explains the problem, not the stack, so
+it's there whoever the reader is. If the user asks for no analogies, skip it.
+
+**Draw the baseline.** The reviewer can't judge a change without knowing what it
+changed from, and the diff only shows the seams. So "Start here" gets one
+before/after `
`: how the thing worked on the base branch, how it works now. +Draw the mechanism, not the file list — boxes are what holds state or does work (a +process, a table, a job, a request), arrows are what moves between them. Keep the +same boxes in the same places on both sides so the eye lands on the difference, and +mark only the difference: `` for what's gone, `` for what's new. They mean +removed and added, never bad and good, and anything both sides share stays bare. A +risk or alternative gets its own small pair only when its point is a change of +shape — a new failure path, the design you didn't build — with labels that say so +("After: Redis blips", "Signed cookies"); there, mark what differs within that pair +(the stale price, the lost job), not the feature "Start here" already marked, and +never `` on a design that was never built. Nesting means containment, so a +shared store sits outside both processes and gets drawn once. One +diagram per note at most, most notes none. A number on one side (p95 2.4s) needs its +counterpart from the PR on the other, or neither side gets one. Plain ASCII (`-->`, +`+`, `|`), under ten lines and 44 characters a side, since each side stacks +full-width on a phone; break a long chain rather than widen it. Box-drawing +characters are raw bytes and turn to mojibake like any other. A change with no shape to draw — copy, a bug fix inside one +method — gets no figure; don't draw two identical boxes to fill the slot. + +## 5. Fill in the template and publish + +`assets/walkthrough-template.html` is the page, and its own comment lists the +elements. Its ` + +
+ +
+
+

Session Store Swap

+

Logins stopped surviving deploys. Sessions now live in Redis instead of the web process's memory.

+
+
+
Branch
redis-sessions onto main
+
Change
4 files, +86 / −21
+
+
+ +
+

Start here

+

Every deploy logged everyone out. Picture a coat check where each attendant keeps the claim tickets in their own pocket: when one goes home at shift change, every coat they took in is stranded, and a guest who walks up to the other attendant isn't recognized at all. This branch moves the tickets to one board behind the counter that every attendant reads, so a shift change doesn't matter.

+

In the code: sessions were held in the web process's own memory, so restarting the process threw them away — and with two processes running, a user could land on the one that had never seen them. This moves sessions into Redis so any process can read them and a restart doesn't matter.

+
+
+ Before +
         +-- web.1  [sessions]
+browser -+
+         +-- web.2  [different sessions]
+
+deploy: restart --> memory wiped
+                --> everyone logged out
+
+
+ After +
         +-- web.1 --+
+browser -+           +--> Redis [sessions]
+         +-- web.2 --+
+
+deploy: restart --> Redis untouched
+                --> still logged in
+
+
Sessions move out of each process and into one shared store.
+
+

The change is small on purpose. Nothing about how login works changed; only where the session is kept. Not in this branch: no migration of existing sessions, and no Redis in the test suite — tests still use the in-memory store.

+
+
Risk
+
Deploying this logs everyone out once. Existing sessions live in the old store and nothing copies them over.
+
Tradeoff
+
Redis is now required to boot, so REDIS_URL has to be set before the release goes out, or the new release crashes on boot.
+
Alternative
+
Signed cookies would have needed no Redis at all, since the session rides along in the cookie itself. Our payload is over the 4KB limit, so that was out.
+
+
+ +
    + +
  1. +
    +

    src/session.js

    +

    +31 / −6

    +
    +

    This is the whole change. Everything else is here to support it.

    + +
    @@ -1,9 +1,14 @@
    + const session = require("express-session");
    ++const RedisStore = require("connect-redis").default;
    ++const { createClient } = require("redis");
    +
    ++const client = createClient({ url: process.env.REDIS_URL });
    ++client.connect().catch(console.error);
    +
    + module.exports = session({
    ++  store: new RedisStore({ client, prefix: "sess:" }),
    +   secret: process.env.SESSION_SECRET,
    +-  resave: true,
    ++  resave: false,
    + });
    +
    + + + + +
  2. + +
  3. +
    +

    src/health.js

    +

    +12 / −1

    +
    +

    The health check now fails if Redis is unreachable, so a broken session store takes the process out of rotation instead of quietly logging everyone out.

    + +
    @@ -4,7 +4,11 @@ router.get("/healthz", async (req, res) => {
    +-  res.json({ ok: true });
    ++  try {
    ++    await client.ping();
    ++  } catch {
    ++    return res.status(503).json({ ok: false, redis: false });
    ++  }
    ++  res.json({ ok: true });
    +
    + + +
  4. + +
  5. +
    +

    package.json · package-lock.json

    +

    +43 / −14

    +
    +

    Two new dependencies, same as adding two gems. The lockfile churn is generated — nothing to read there.

    + +
    @@ -12,6 +12,8 @@ "dependencies": {
    ++    "connect-redis": "^7.1.1",
    ++    "redis": "^4.6.13",
    +     "express": "^4.18.2",
    +… 41 lines of package-lock.json not shown
    +
    + + +
  6. + +
+ +
diff --git a/skills/diff-explainer/references/translation.md b/skills/diff-explainer/references/translation.md new file mode 100644 index 0000000..4e5a74e --- /dev/null +++ b/skills/diff-explainer/references/translation.md @@ -0,0 +1,63 @@ +# Translating for a reader from another stack + +Read this when you know the reader's background and the project isn't in it. + +## The point of an analogy + +The reviewer isn't confused about programming. They're missing the _conventions_: +what this framework does for you, what's expected to live where, what's normal +versus what's a workaround. Their own stack gives them exactly that at home, so +the analogy does real work: it hands them the conventions they'd otherwise have +to infer from the diff. + +Which means: translate concepts and conventions, not syntax. "It's their service +provider, wiring things up once at boot" is useful. "`:=` is like `=`" is noise. + +## How to use one + +**Say the analogy, then the difference that matters.** An analogy without its +limit sets the reviewer up to be wrong later. "This struct is their model, +except nothing saves it; it's just data in memory" tells them where their +instincts stop applying, which is the part they can't get from the diff. + +**One per idea, then move on.** Analogies stack badly. Once you've said a +Go handler is their controller action, keep calling it that; don't reach for a +second metaphor two paragraphs later. + +**Skip it when the thing is already universal.** A typo fix, a renamed variable, +a null check: nobody needs a translation for that. Forcing an analogy onto +something obvious reads as condescension, and the reviewer starts skimming. + +**Never make the analogy do the explaining.** The annotation still has to say +why the change was made. The analogy only makes the _what_ cheap to parse so the +why has room. + +**Say so when there's no match.** Type systems, eventual consistency, explicit +dependency injection often have no honest equivalent in the reader's stack. +Describe the actual thing plainly instead of stretching a comparison. + +## Worked examples + +For a Laravel developer reading a Go branch. + +**Weak, syntax with no why:** + +> This adds a `sync.Once` around the config loader. + +**Better, convention plus the reason:** + +> Does what binding a singleton in a service provider does: the config is read +> once, the first time anything asks, and shared after that. It moved here +> because two packages were each reading the file on their own and disagreed +> after a deploy. + +**Weak, the analogy is the whole annotation:** + +> A goroutine is basically a queued job. + +**Better, analogy sets up the actual point:** + +> Starting a goroutine here is like dispatching a Laravel job, minus the queue: +> it runs in the same process, so a restart mid-resize loses the thumbnail, +> with no `failed_jobs` row to pick it back up. That's why the upload is marked +> pending first and a sweep finishes any left behind. diff --git a/skills/domain-model/SKILL.md b/skills/domain-model/SKILL.md new file mode 100644 index 0000000..7abb8e6 --- /dev/null +++ b/skills/domain-model/SKILL.md @@ -0,0 +1,98 @@ +--- +name: domain-model +description: Turn a described business process into a domain model. +argument-hint: "[business process, or a path to a description of one]" +--- + +# Domain model + +The user describes how their business actually works. You come back with the concepts hiding in that description — and every one of them traces to something they said. An invented model is worse than none: it's fluent, confident, wrong, and in six months it's in the code under a name nobody in the business recognizes. + +Five things come out, and nothing else: + +| | | +| -------------- | ---------------------------------------------------------------- | +| **Language** | The words the business uses, meaning what the business means. | +| **Flow** | The events, in order. Past tense — something became true. | +| **Rules** | Whenever X happens, we do Y. The branches and the exceptions. | +| **Aggregates** | Whatever protects a rule and emits those events. | +| **Contexts** | Where a word stops meaning one thing and starts meaning another. | + +No entities-versus-value-objects, no repositories, no schema, no class diagram — those are implementation, and this is what implementation gets checked against. Don't read code either. The code already chose names, and the ones it chose are the loudest thing in the room; read them and they end up in the model, at which point the model can only tell you what the code already says. + +## Workflow + +1. Capture the process in the user's words. +2. Harvest the language before interpreting any of it. +3. Interview in rounds, leading with a proposed model. +4. Fill in the template and paste it whole for review — the only gate, and nothing reaches disk the user hasn't read in a message first. +5. Write to `docs/domains/.md` and tell the user the path. + +### 1. Capture the process + +The process, if the user passed one: `$ARGUMENTS` + +That may be prose or a path — a transcript, a ticket, meeting notes. Read the file if it's a path. If it's empty, ask them to walk you through how the process works today, including the parts done by hand and the exceptions, because the exceptions are where the domain lives. + +Keep their exact words. A description you tidied up is one you've already started interpreting. + +### 2. Harvest the language + +Pull out every noun and verb they used for something in their business, verbatim, before you model anything. If they said "lapse", the model says lapse — not expire, not deactivate. You're recording the language, not improving it; swap in a word you find clearer and the model stops being checkable by the person who described the process. + +Two things here are findings rather than housekeeping: + +- **Two words, one meaning.** "Cancel" in one sentence, "void" in another. Don't quietly pick one — sometimes it's sloppiness, sometimes they're two acts with two different consequences, and you can't tell from outside. +- **One word, two meanings.** "Customer" for the person who pays and the person who calls support. That isn't a glossary problem, it's the strongest evidence you'll get for a context boundary — evidence, not the boundary itself. + +Play the harvest back as a plain list before interviewing. It's where they catch you having misheard a term, which is far cheaper than catching it in a finished model. + +### 3. The interview + +Rounds of 2 to 4 questions. One at a time is a slog; twelve at once is a survey. + +**Define the word the first time you use it.** Aggregate, context, event — the user described a business, so this vocabulary is yours, not theirs. One line, in their own process's terms, before you ask them anything with it in: _"an aggregate is whatever gets to refuse — the thing that would stop you double-booking that table."_ Three rounds of answers from someone who didn't know what you were asking are three rounds you have to throw away. + +**Lead with a proposed model, not a question.** "What are the aggregates here?" hands the work back and gets you a shrug. Instead: _"I'm treating `Policy` as the thing that says no — it decides whether a claim is covered, and nothing else has enough information to. Push back if something else owns that."_ A proposal is easy to accept and easy to reject, so it moves fast, and what they defend tells you what's real. If they ask why you drew a boundary there and your answer is a DDD principle rather than something they told you, you invented it — drop it and say so. A proposal they skip is not a yes; carry it to the playback. + +**Never name a concept they didn't.** If the model needs a term the user never used, it's a proposal and gets marked as one: _"you don't have a word for the period between lapse and cancellation — I'm calling it the grace period, tell me what the business calls it."_ Untagged invented vocabulary is how a model becomes unfalsifiable. Asking "what do you call this?" produces a word; it doesn't prove one was in use. Mark those the same way, and ask where they'd hear it said. + +**Events** are past tense and business-observable: _Order placed. Policy lapsed._ The test is whether someone would say it happened without knowing there's software involved — "user clicks submit" is UI, "record saved" is storage. Order them; the sequence encodes which steps can't be reordered. + +**Rules** are the conditionals, and they aren't events. _"Whenever the track is closed, we move to the bikepath."_ Every "if", "unless", "sometimes" and "except when" in their description is one, and they're the reason step 1 asks for the exceptions. A flow with the branches stripped out is a happy path, which is the one version of a process nobody needed written down. + +**Aggregates** answer _who says no?_ Ask what rule must never break, then what the smallest set of things is that changes together to enforce it. If enforcing it needs two things to agree, ask whose job it is to make them agree: if it's the person doing the thing, they're one aggregate; if it's someone else's job or a nightly check, the rule holds but late, and it goes in `## Rules` with the delay the business will tolerate. An aggregate protecting no rule is a table — say so. And if nothing anywhere protects a rule, say that plainly too: it means the flow and its rules are the whole model, and either that's fine or there's a floor the business wants and hasn't got. Don't call it CRUD; that's a design instruction and you haven't earned it. + +**Contexts** announce themselves when the user qualifies a term mid-sentence: _"well, a customer in billing is..."_ Follow that hesitation. Other tells: different people, different teams, delays nobody minds. Before splitting, check the far side is a whole model rather than a mode — its own terms, its own flow, and someone who never has to care about the other. If one person walks through both in a single pass, it's a branch: put it in `## Rules` and keep one context. One context is a legitimate answer, but say why you're not splitting rather than just not mentioning it. + +**Stop** when every event has an aggregate that emits it or is accounted for by a rule, every aggregate protects a rule you can state in one sentence, no term has two live meanings, and no two terms share one meaning without a ruling — either they're one act and the business names the survivor, or they're two acts and the Language table says what the difference is. Whatever still fails after three rounds goes in `## Unresolved` and you draft; an open question recorded in the model beats an answer you talked them into at question fifteen. No checkpoint here; go straight to step 4 in the same turn. + +### 4. Show the model before saving it + +Read `assets/domain-template.md` now. Reading it at save time is how this turns into a freehand summary. Fill it in and paste the filled-in file — the file, every section, not a description of it: + +```` +Here's the model I'd save to `docs/domains/{slug}.md`. Nothing written yet. + +```markdown +{the filled-in template, in full} +``` + +**Terms I introduced, or that you only named because I asked:** {list, or "none"} + +**Proposals you didn't answer, which I kept:** {list, or "none"} + +Say the word and I'll save it. +```` + +Both lines print even when empty. The first catches the failure this skill exists to prevent; the second is the only place a silent round becomes visible, and silence isn't agreement. Replace every `{placeholder}`; nothing in braces survives to disk. + +Then stop, whatever their last message implied. A correction to a boundary or an aggregate sends you back to step 3; a correction to wording is cheaper — fix the draft and show it whole again. Second time back, run one round rather than three, then draft what you have and put the disagreement in `## Unresolved`. + +### 5. Write the file + +Write to `docs/domains/.md` at the repo root (`git rev-parse --show-toplevel`), kebab-case and named for the process (`claims-intake`, not `how-claims-work-v2`). If the file exists, read it: same process, ask whether to replace or revise; different process, pick another slug. Write the draft they approved, unchanged — anything improved after approval is unreviewed. + +## Notes + +- The model describes a business, so keep what to build next out of it — a backlog, a roadmap, an ordering of work, each defensible alone and together the design doc this isn't. And expect it to rot, because nothing recompiles when it drifts: a short model that's right beats a thorough one nobody trusts. diff --git a/skills/domain-model/assets/domain-template.md b/skills/domain-model/assets/domain-template.md new file mode 100644 index 0000000..6d53bb5 --- /dev/null +++ b/skills/domain-model/assets/domain-template.md @@ -0,0 +1,60 @@ +# {Process name} + +{One sentence: what business process this describes, and where the +interesting boundary turned out to be.} + +## Language + +| Term | What it means here | Watch out | +| ---------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------ | +| {term, in the business's own word} | {the meaning it carries in this process} | {the near-synonym it isn't, the other meaning elsewhere, "named on request — not observed in use", or blank} | + +## Flow + +{Events in the order they happen. Past tense — each one is something +that became true.} + +1. **{Event}** — {what is now true that wasn't before} + +## Rules + +{Whenever X happens, we do Y. The branches, the exceptions, and the +rules that hold late — one line each. If a rule is enforced by someone +else's job or a nightly check rather than on the spot, say so and say +how late is tolerable.} + +- **Whenever** {event or condition} → {what happens} + +## Aggregates + +{If nothing here protects a rule, say so in a line and delete the +subsection below. That's a finding: the flow and its rules are the whole +model, and either that's fine or there's a floor the business wants and +hasn't got. Don't write "CRUD" — that's a design instruction, and this +document doesn't get to give one.} + +### {Name} + +Protects: {the one rule that must never break} +Contains: {the terms that change together inside this boundary — +everything outside it is referred to by name} +Emits: {events from the flow} + +## Contexts + +{One heading per context. If there's only one, say so here in a line and +say why — same team, no term shifts meaning — rather than deleting the +section.} + +### {Name} + +Owns: {aggregates, or if there are none, the terms and events on this side} +At the border: {a term that means something else on the other side, and +what it means there} +Relationship: {which side depends on which, and whether the shared term +gets translated at the border or used as-is} + +## Unresolved + +{Only if something failed the stopping tests: the question, and what it +would change. Delete this section otherwise.} diff --git a/skills/eli5/SKILL.md b/skills/eli5/SKILL.md new file mode 100644 index 0000000..52cf3cc --- /dev/null +++ b/skills/eli5/SKILL.md @@ -0,0 +1,179 @@ +--- +name: eli5 +description: Explain something to someone who knows nothing about it. +argument-hint: "[code, tool, process, or concept you have no familiarity with.]" +--- + +# ELI5 + +The user has no foothold. `/understand` questions them about a model they already +hold; here there is no model to question, and asking produces a guess you then have to +correct. So read the thing, then explain it — plainly, concretely, once. + +Two ways this fails. You explain it in the vocabulary of the thing itself ("the +reconciler converges the cluster toward desired state"), which only reads to someone +who already understands it. Or you reach for concreteness and invent it: a config +value that isn't in the file, a sample record nobody has. The invented one is worse, +because it's memorable, wrong, and this reader has nothing to catch it with. + +## 1. Find the thing + +The target is `$ARGUMENTS`, or ask. It arrives as a path, a name they keep seeing +(`sidekiq`, `helm`, `useEffect`), a word off a ticket (`chargeback`, `dunning`), a +link, or pasted text. + +A path is the thing. A name or a word gets looked for in this repo first — manifests, +config, `grep -ri` — since the version this codebase uses beats the general one, which +covers ten features they'll never touch. Not here at all? Say so in one line, explain +it in general, and skip the trace agent below; there's nothing for it to read. + +A directory: pick its entry point and say that's what you took. Don't ask what they +already know or what they mean to do with it — questions are what they came here to be +spared. + +## 2. Send agents to read it + +Launch subagents in parallel (`Explore`, or `general-purpose`) and wait. Three angles, +one agent each: + +- **What it's for.** What job this does for a person, who that person is, and what + visibly breaks if it vanishes. Tell the agent to answer without using the thing's own + vocabulary, or it hands back the README's first paragraph. +- **One real trace.** A single instance start to finish, in order, with the branch at + each step and what happens when it fails — real route, real config value, a row from + seeds or fixtures, a real filename, cited `file:line`. This is what step 4 draws. +- **The words.** Every term a newcomer would bounce off, and what each means _in this + repo_, which is usually narrower than in general. + +Tell each that "I couldn't find a real example" is an acceptable answer, or an agent +with no way to come back empty manufactures one that reads exactly like a real one. If +the trace does come back empty, say so in the explanation — a gap you name costs less +than a plausible value you filled it with. + +Then open the files behind the claims you're about to assert, because a citation you +took on trust is how you confidently explain a function that doesn't exist. If you had +to skim, name what you couldn't verify — that's theirs to know. How the answer got made +isn't, at either end of it. + +## 3. Explain it + +**Lead with the job.** "This decides who gets charged and when," before any mechanism. +Mechanism has nowhere to attach yet. + +**Then a simple analogy,** right after the job: one comparison from everyday life that +a kid would follow. Keep both free of file, class and code names — even the file they +asked about — since a path is jargon to this reader until the analogy has given it +somewhere to land. A job queue is the ticket rail in a restaurant kitchen — the waiter +clips the order up and walks away, and a cook pulls it down when free. Map its pieces +onto the real ones and carry it through the drawing's values, then say where it breaks +if the gap will bite them. One analogy, not a string of them. If they ask for no +analogies, or for a different framing, do what they asked. + +**Anchor the mechanism to something they already have:** elsewhere in this same repo, +then the stack they already work in (`CLAUDE.md` and the rest of the repo say which). +The second rung is the one that gets skipped — "this file is that stack's router" lands +where first principles don't. + +**Say the plain version first and the real name once, after,** so they can go search +for it: "the server kills the process when the machine runs low on memory; the logs +call that _evicted_." + +**Show real values.** `ORDERS_PER_PAGE = 25`, so page 3 starts at order 51. + +**Draw it** — step 4. Not optional. + +**Stop at roughly thirty lines of prose** plus the drawings. Past that you've started +teaching the subsystem, and completeness is what loses this reader. The bar is that +they could describe the thing to a coworker in two sentences. + +**Name the holes** — what recon couldn't reach, what the code doesn't answer. A hole +you name is one they can go ask a person about. + +**Last pass before you send,** and it's the one that matters most: reread hunting for +words that only land for someone who already knows this thing. Gloss each in place or +cut it. Read the labels inside your drawings too — a term in the picture is the one +they can't skip past, and it's where this pass usually misses. "Basically", "simply", +"just" and "under the hood" mark a sentence you didn't finish writing — finish it. +Don't end on an offer of further services. + +## 4. Draw it + +At least one drawing, every time. Plain text, in the chat, built from the trace agent's +values. If you can't find a shape worth drawing, you don't understand it yet — go back +to the trace rather than writing another paragraph. + +**Order — what happens, then what.** Draw the failure branches; a happy path alone is +the version that leaves them stuck at 2am. Elapsed time goes on the arrows, never on a +scale, which would lie about the spacing. + +``` +POST /webhooks/stripe + | + v + verify signature --- bad --> 400, nothing else runs + | + good + v + enqueue ChargeSucceeded --3s--> worker marks invoice #4821 paid +``` + +**Boundary — where each part runs, and what crosses.** For anyone meeting an +unfamiliar stack this is usually the drawing that unlocks it. + +``` + browser | server + -------------------------+--------------------------- + app/page.tsx renders | auth.ts holds the secret + click "Sign in" ------- | ---> POST /api/auth/signin + | sends back: a cookie, no token +``` + +**Change — what goes in, what comes out.** Two columns of real values beat any sentence +describing the transformation. + +``` +"123 Main St." --> "123 main st" +"123 main street" --> "123 main st" +``` + +**Structure — which nouns exist and how they hang together.** This is the shape for +explaining a domain, where there's no sequence to follow. + +``` +Subscriber --- has many ---> Invoice --- has one ---> Charge + | + +-- unpaid 30 days --> "in dunning" +``` + +**Containment — what wraps what.** Nested boxes, the one that stops a stack of wrappers +being magic. + +``` ++-- your call to getActivities() -----------------+ +| +-- retry wrapper, 3 attempts ---------------+ | +| | +-- fetch() to strava.com/api/v3 -------+ | | +``` + +**Choices — how similar things differ.** A table, with the columns that actually differ +and nothing else. + +Four rules hold these up: + +- **Real labels from their repo.** "Service A" and "Service B" draw the category, not + their system — the same picture would be true of any app. +- **Same values as the prose.** Numbers in the drawing and numbers in the text come + from the one trace. Two versions of the same number is worse than neither. +- **One idea per drawing.** A legend means it's two drawings. Keep anything you drew by + hand under about seventy characters wide, since a wrapped diagram in a terminal is + noise; a table wraps on its own and is measured in columns instead — three or four. +- **One line under it naming the surprising part** — "nothing after the signature check + runs." Never restate what the picture already said. + +## 5. After + +Answer follow-ups straight, and go read if you don't know. Never bluff here; everywhere +else the user catches a wrong answer, and this one can't. + +Want it deeper on one piece? That's another pass of this skill on a smaller target, not +a licence to switch into the vocabulary you spent step 3 avoiding. Don't quiz them — +being tested is `/understand`, and it's worth mentioning only if they ask what's next. diff --git a/skills/explain/SKILL.md b/skills/explain/SKILL.md deleted file mode 100644 index 3fe2cd5..0000000 --- a/skills/explain/SKILL.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -name: explain -description: Explain what a piece of code does — a specific file, class, or method in close detail, or a user-facing flow as a concise system overview. What it does and why, not whether it's good. -argument-hint: "[file path, class name, method, or flow description]" -disable-model-invocation: true -context: fork -agent: Explore ---- - -## Behavior - -Explain `$ARGUMENTS`. Do the research and deliver the explanation in one pass. - -Determine the mode from the argument: - -- **If the argument is a file path, class name, or method** — this is a **code explanation**. Follow the Code Explanation section. -- **If the argument is a user action, feature, or flow description** (e.g. "password reset", "checkout", "authentication") — this is a **flow explanation**. Follow the Flow Explanation section. - ---- - -## Code Explanation - -Start by checking the git history for the file: `git log --oneline -15 ` and `git log -1 -p ` for the most recent change. Commit messages often reveal the "why" that the code itself doesn't — a bug that was fixed, a refactor that simplified something, a workaround for an external constraint. Note anything that reframes the code before diving into it. - -Then read the code carefully and explain in this order: - -### 1. What it does — in one paragraph - -Plain English. No jargon, no code. Describe what this code accomplishes from the outside — what goes in, what comes out, what changes as a result. Write it the way you'd explain it to the client who asked for the feature. - -### 2. How it does it — walking through the logic - -Narrate the code path in plain English, step by step. For each meaningful chunk: - -- What is this step doing? -- Why is it doing it here, in this order? -- What would break if it wasn't here? - -Don't narrate every line — skip the obvious. Focus on the parts that require interpretation. - -### 3. Patterns and conventions in use - -Name the Rails, Ruby, or design patterns this code is using — and why they appear here. Examples: - -- "This is a service object following the thoughtbot pattern — one public `call` method, one responsibility" -- "This is using `delegate` to avoid Law of Demeter violations" -- "This callback is doing what's normally done in a service object — worth noting" -- "This is a query object extracting complex AR logic out of the model" - -If the code is using a pattern poorly or unexpectedly, name that too — neutrally. This isn't a review, but understanding requires knowing when something is off-label. - -### 4. What to watch out for - -Any non-obvious behaviour, implicit dependencies, or things that would surprise someone maintaining this code. Not a critique — just "here's what you'd need to know to work safely in this area." - ---- - -## Flow Explanation - -Start with the Rails router. Locate the route(s) that correspond to the described flow. From each entry point, trace the execution path through the codebase — controllers, service objects, models, callbacks, jobs, mailers. Follow both success and failure paths. - -Then deliver the explanation in two parts: a **diagram** and a **summary**. - -### 1. Diagram - -Render a concise visual flowchart of the system using box-drawing characters. The diagram should show: - -- **States and transitions** — the lifecycle, not the method calls -- **Decision points** — where the flow branches -- **Key actions** — what happens at each step, described in plain English -- **Terminal states** — where the flow ends - -**Conventions:** - -- Box-drawing characters for structure: `┌─┐`, `│`, `├──`, `└──`, `▼`, `◄` -- Decision points as plain text with branches: `YES` / `NO` -- Actions as concise descriptions, not method signatures -- Indent sub-steps under their parent action - -The goal is to outline the system concisely — show how it behaves, not how the code is structured. A reader should be able to understand the full lifecycle from the diagram alone. - -See the example in `example.md` for the expected style and level of detail. - -### 2. Summary - -After the diagram, add three sections in plain English: - -**Entry points** — every way this flow can be triggered. For each, one sentence describing what triggers it and what it does. - -**Branching logic** — the conditions that shape the flow. Feature flags, state checks, validations, guard clauses — anything that determines which path is taken. - -**Side effects** — everything with consequences outside the immediate flow. Jobs, mailers, external API calls, broadcasts, cache writes, state transitions. The things you'd need to know about before touching this code. - ---- - -## Tone - -Clear and direct. You're translating, not teaching and not judging. The goal is that they finish with a working mental model of what this code does and how to navigate it. Skip all hedging — if something is unclear in the code itself, say so plainly. diff --git a/skills/explain/example.md b/skills/explain/example.md deleted file mode 100644 index 35d4340..0000000 --- a/skills/explain/example.md +++ /dev/null @@ -1,72 +0,0 @@ -# Example: /explain password reset - -``` - ┌──────────────────────┐ - │ User forgot password │ - └──────────┬───────────┘ - │ - ▼ - POST /passwords (email) - │ - user found by email? - ┌────────┴────────┐ - │ NO │ YES - ▼ ▼ - (same response) Generate reset token - │ │ - │ Send reset email - │ │ - └────────┬────────┘ - │ - ▼ - redirect to login ("Check your email") - │ - │ - ┌──────────┴───────────┐ - │ User clicks email │ - └──────────┬───────────┘ - │ - ▼ - GET /passwords/:token/edit - │ - token valid? - ┌────────┴────────┐ - │ NO │ YES - ▼ ▼ - redirect to render password - new_password_path reset form - │ - ▼ - PATCH /passwords/:token - │ - password valid? - ┌────────┴────────┐ - │ NO │ YES - ▼ ▼ - render form Update password - with errors Clear reset token - │ - Log user in - │ - ▼ - redirect to dashboard -``` - -### Entry Points - -1. **User submits email** — `POST /passwords` looks up the user and sends a reset email. Returns the same response whether the user exists or not to prevent email enumeration. -2. **User clicks reset link** — `GET /passwords/:token/edit` validates the token and renders the password form if valid. -3. **User submits new password** — `PATCH /passwords/:token` updates the password and logs the user in. - -### Branching Logic - -- **User existence**: Email lookup determines whether a reset email is sent, but the HTTP response is identical either way — no information leakage. -- **Token validity**: Token must exist and not be expired. Invalid tokens redirect back to the "forgot password" form. -- **Password validation**: `has_secure_password` validates presence, length, and confirmation match. - -### Side Effects - -- **Reset token written to DB** — stored as a SHA256 digest, not plain text -- **Email enqueued** — `PasswordMailer.reset_instructions` delivered via background job (Sidekiq) -- **Session created** — user is automatically logged in after successful reset -- **Token cleared** — `after_update` callback removes the reset token so it can't be reused diff --git a/skills/feature-dev/SKILL.md b/skills/feature-dev/SKILL.md deleted file mode 100644 index 59f12ac..0000000 --- a/skills/feature-dev/SKILL.md +++ /dev/null @@ -1,169 +0,0 @@ ---- -name: feature-dev -description: Take one new feature slice from idea to reviewed, committed code in a single guided pass — scope it into the smallest shippable slice, build it test-first with strict TDD, review and fix the diff, then commit it. Chains slice → test-driven-development → the built-in /code-review → git-commit. Not for reviewing an existing PR, upgrades, or open-ended design questions. -argument-hint: "[feature or slice to build]" -disable-model-invocation: true ---- - -# Feature Development - -You are helping a developer take **one feature slice** from a rough idea to reviewed, committed code. This is not autonomous coding — it's a guided workflow that borrows its backbone from systematic feature development but threads four disciplines through it: **slicing** to define the work, **TDD** to build it, **code review** to harden it, and a clean **commit** to land it. - -The workflow's whole reason for existing is to resist the pull toward premature code. Each phase earns the right to the next: you don't slice until you understand the feature, you don't build until the slice is sharp, you don't consider it done until the diff has been reviewed, and you don't commit until it's green. Hold that line — the value is in the sequence, not any single step. - -**Scope discipline:** this workflow refines and builds exactly **one slice**. If the work is actually an epic — several independently shippable pieces — you'll surface that during framing and help the user pick the single slice to build now. Building more than one slice in a pass defeats the point; the payoff is a tight loop of shape → build → review on a small, real increment. - -**Leanness discipline:** a small slice does not guarantee a small diff. Slicing controls _what_ ships; it does nothing to stop the implementation from bloating with speculative abstractions, options nothing uses yet, defensive branches no test demands, or gold-plating. Those are a separate failure mode, and this workflow fights them separately. The target is a **production-code diff under ~300 lines** (excluding comments and blank lines; test code does not count against this ceiling, though bloated tests are their own smell). Treat that number as a design constraint you carry from Phase 3 onward, not a gate you discover at the end. - -Use `TodoWrite` to track the phases so the user can see where they are. - ---- - -## Phase 1: Frame the work - -**Goal:** understand what the user wants to build, and confirm it's a single slice before investing in anything else. - -Initial request: `$ARGUMENTS` - -If the feature is unclear, ask what they're building — the problem it solves, who it's for, what "done" looks like. Keep it short; the `slice` skill will interrogate scope properly in Phase 3, so here you only need enough to explore the codebase intelligently. - -Then make an explicit call on size. Ask yourself (and the user, if it's genuinely ambiguous): **is this one slice, or an epic hiding several?** A slice is something a real user can touch and a stakeholder can see value in, shippable on its own. - -- **One slice** → confirm your understanding in a sentence or two and move to Phase 2. -- **An epic** → say so plainly. Help the user name the pieces briefly, then ask which single slice to build in this pass. Do not try to build them all. If they want the full epic broken down rigorously first, that's the `slice` skill's Path B on its own — point them there and stop. - ---- - -## Phase 2: Explore the codebase - -**Goal:** ground the slice in how this codebase actually works, so the acceptance criteria are realistic and the implementation follows existing conventions instead of inventing new ones. - -This matters most in a mature Rails app: the right slice and the right tests depend on where similar features live, what the testing conventions are, and which abstractions already exist. Skipping this leads to slices that ignore reality and code that fights the grain of the app. - -Match the effort to the feature. For a small, well-understood change, a few targeted reads inline are enough — don't spin up subagents to rediscover something you can see in one file. For anything touching unfamiliar territory or spanning layers, launch 2–3 general-purpose subagents in parallel (via the `Agent` tool) as codebase explorers — give each the brief in `references/code-explorer.md` plus a different angle to cover: - -- Find features similar to this one and trace their implementation end to end. -- Map the architecture and conventions for the area this slice touches (models, controllers, jobs, views, wherever it lands). -- Identify the testing patterns relevant to this work — the framework (RSpec or Minitest), how tests are structured across the layers (end-to-end/system, request or controller, model/unit), and what factories or fixtures exist. - -Ask each explorer to return the 5–10 files most worth reading. When they return, **read those files yourself** before proceeding — the subagents build the map, but you need the detail in context to slice and test well. - -Close the phase with a short summary of the patterns and conventions that will shape the slice: where the code will live, what it should look like, what to reuse. Include what already exists — if part of the feature is half-built or an adjacent feature covers some of it, that changes the slice, and Phase 3 needs to know before it starts asking questions. - -**This phase is the grounding that `slice` would otherwise do for itself.** Its Phase 1 has a codebase-grounding step that fans out the same way, and it is written to stand down when the conversation already carries a map. Carry this summary into Phase 3 so that happens — see the note there. - ---- - -## Phase 3: Shape the slice - -**Goal:** turn the framed feature into one sharp, well-defined slice with real acceptance criteria. - -**Run the `slice` skill's process** and let it run the conversation. `slice` is user-invoke-only (`disable-model-invocation: true`), so you can't call it through the Skill tool — read its `SKILL.md` (see the path note below) and drive its process yourself. Because Phase 1 already established this is a single slice, `slice` should sharpen it into one job story (its Path A) rather than break an epic apart. Feed it what you learned in Phases 1–2 so the conversation starts warm instead of from zero. - -**Skip `slice`'s codebase-grounding step — Phase 2 already did it.** Its Phase 1 ends with a grounding step that fans out subagents to find what already exists, what's reusable, and how comparable features are tested. That is exactly Phase 2's job here, and the step tells you to stand down when the conversation already carries a map. Hand it Phase 2's summary and the files you read, and go straight to shaping the slice. Running it again would spend real tokens rediscovering what you already know — but do use it as a checklist: if Phase 2 didn't surface what already exists or what the real edge cases in this area are, fill that gap now, because Phase 3's acceptance criteria depend on both. - -What you need out of this phase is the deliverable `slice` produces: a job story with a clear **"ships when"** and a concrete list of **acceptance criteria** — happy path, edge cases, and error states. Those acceptance criteria are not paperwork; they become the failing tests in Phase 4. Push (or let `slice` push) until each criterion is specific and verifiable — "a user can X and sees Y" — because a vague criterion produces a vague test that proves nothing. - -Do not move on until the user is satisfied the slice is genuinely the smallest thing that delivers real value. If slicing reveals the work is bigger than one slice after all, return to the Phase 1 decision: pick one slice, defer the rest. - -Close the phase with a rough **size budget** for the implementation: given what Phase 2 revealed about where this code will live and what it can reuse, does the slice look buildable in under ~300 lines of production code? If it clearly can't — it spans many layers, or every acceptance criterion drags in new machinery — that is often a signal the slice is still too big, not that the budget is wrong. Interrogate it now, while re-slicing is cheap. If the size is genuinely justified by essential complexity, name that expectation here so it's a considered decision rather than a surprise in Phase 5. - ---- - -## Phase 4: Build it test-first - -**Goal:** implement the slice with strict, outside-in TDD, driven by the acceptance criteria. - -**Run the `test-driven-development` skill's process** without shortcuts. Like `slice`, this skill is user-invoke-only (`disable-model-invocation: true`), so you can't call it through the Skill tool — read its `SKILL.md` and drive its red-green-refactor loop yourself. Hand it the slice's acceptance criteria as the specification: each criterion is a behavior that needs a failing test before any production code exists. - -The two skills fit together naturally — `slice` produced the observable behaviors, and TDD drives them outside-in: start with a high-level test for the "ships when" behavior — a system or feature test — let its failure push you down through the lower layers (request/controller, then model), and write minimal code at each layer. The acceptance criteria are your checklist; the slice is done when every one of them is covered by a test you watched fail and then pass, and the suite is green with pristine output. - -Honor the Iron Law from that skill: no production code without a failing test first. If you catch yourself wanting to skip ahead "just this once," that's exactly the moment the discipline is paying off. - -**Keep the implementation lean while you build.** TDD's "write the minimal code to pass the current test" is your best defense against a bloated diff — take it literally. Concretely, as you work through the criteria: - -- Don't introduce an abstraction (a service object, a concern, a base class, a config option) until a _second_ caller actually needs it. One caller is not a pattern. -- Don't add error handling, branches, or parameters that no failing test demands. If it isn't driven by a criterion, it isn't in scope for this slice. -- Reuse what Phase 2 surfaced instead of building parallel machinery. The leanest diff leans on code that already exists. - -**Size checkpoint before review.** When every acceptance criterion is green, measure the production diff against the ~300-line budget before moving on: - -``` -git diff --stat "$(git merge-base HEAD main)"...HEAD -- ':(exclude)test' ':(exclude)spec' -``` - -(Use whichever base branch the slice was cut from, and adjust the excludes to this app's test directories. This counts added lines including comments and blanks, so discount those by eye — you want the real production-code figure.) - -If you're at or under budget, move to review. If you're over, do **not** just proceed — make an explicit, written call among three options and tell the user which one applies: - -- **Accidental complexity** — over-abstraction, dead flexibility, code no criterion demanded. Simplify it now, before review. This is the common case and the whole reason for the checkpoint. -- **Essential complexity** — the slice genuinely spans enough layers that the code can't be smaller without losing behavior. Legitimate, but say _why_ in one or two sentences; an unexplained large diff is indistinguishable from a bloated one. -- **The slice was too big** — if the size traces back to scope rather than implementation, the honest fix is upstream. Return to the Phase 1/3 decision, ship the smaller piece, and defer the rest. - -This is an advisory checkpoint, not a hard gate — a justified large diff is allowed to proceed. What's not allowed is drifting past 300 lines without noticing. Once the size is either under budget or a considered decision, the slice is built — move to review. - ---- - -## Phase 5: Review the diff - -**Goal:** catch the bugs, quality issues, and convention violations that TDD alone won't surface, then fix them before the slice is considered shippable. - -TDD proves the slice does what the acceptance criteria demanded — it does not prove the code is simple, secure, or idiomatic. That's what this phase is for, and it runs against the **diff for this slice** (the changes since the branch point). - -Run Claude Code's built-in code review over the slice and let it apply the fixes automatically: - -``` -/code-review high --fix -``` - -- The **level** sets how hard the review looks. `high` is the right default for a focused single-slice diff — drop to `medium` for a trivial change, or raise to `xhigh`/`max` for security-sensitive or subtle logic where a missed issue is expensive. -- **`--fix`** applies the fixes for confirmed findings directly instead of only reporting them, which is what we want here — the slice should come out of this phase already corrected. - -`/code-review` already hunts for simplification and reuse opportunities, so it's a natural second pass on leanness after the Phase 4 checkpoint — if the diff came in near or over budget, weigh its simplification findings accordingly rather than waving them through. - -The built-in review already filters to high-confidence findings and verifies them before it acts, so there's no separate confidence pass to run. `references/code-review.md` documents the standard it applies — the ≥ 80 confidence bar, the Critical vs. Important severity split, and what counts as a false positive — if you want to understand what it's weighting or need to fall back to a manual review when the command isn't available. - -Because `--fix` edits code outside the red-green-refactor loop, **re-run the full suite once it finishes** — using whatever test command this app uses (the one you identified in Phase 2, e.g. `bin/rails test`, `bundle exec rspec`, or the app's Rake task) — to confirm the slice is still green and nothing regressed. - -If a fix changed behavior that isn't yet covered by a test, add the missing test — failing first, per Phase 4 — so the correction is locked in and can't silently regress later. Then briefly summarize what the review changed: what it fixed, anything it flagged but deliberately left, and confirmation the suite is green. - ---- - -## Phase 6: Summary - -**Goal:** close the loop. - -Mark the todos complete and give a short summary: - -- **What shipped** — the slice, in one line the user could paste into a PR description. -- **Acceptance criteria** — confirm each is met and tested. -- **Key decisions** — anything notable from slicing, testing, or review. -- **Files changed** — the diff at a glance, with the production-code line count against the ~300 budget. If it ran over, restate the one-line justification from the Phase 4 checkpoint. -- **Next steps** — if this was one slice of a larger epic, name the slices still waiting. - ---- - -## Phase 7: Commit the slice - -**Goal:** land the finished, reviewed slice in version control as a clean commit. - -**Invoke the `git-commit` skill** (Skill tool, `git-commit`). The whole point of this workflow is that everything in the working tree is _one coherent slice_, so `git-commit` should land it as a single atomic commit rather than splitting it — the model, its migration, the controller, the view, and the tests all tell one story. The exception is anything genuinely independent that snuck in (an unrelated cleanup, a drive-by fix from the review); let `git-commit` make that call and split those out. - -Feed it the slice's "ships when" line as context so the commit message explains _why_ the slice exists, not just what changed. If the review in Phase 5 flagged a risk or a deliberate trade-off, mention it so that lands in the message too. - -`git-commit` stops at creating commits — it does not push and does not open a PR. That's intentional; leave the branch ready for the user to push and open the PR themselves. Depending on install, the skill may be listed as `rails-consultant:git-commit`. - ---- - -## Notes on the disciplines - -The pieces this workflow orchestrates are each rigorous on their own; your job is to run them in sequence and keep the handoffs clean, not to water them down. - -- `slice` is Socratic — it leads the user to define the work through questions. Let it. Don't pre-answer for them. Arriving from Phase 2 makes this harder, not easier: you know things the user hasn't been told, and the pull is to skip the questions and present the slice. Use what you know to make the questions specific instead. -- `test-driven-development` is strict about order. Don't let the momentum of a clear slice tempt you into writing code before the test. -- The built-in `/code-review --fix` does the reviewing and fixing; your responsibility after it runs is to make sure the suite is still green and that any behavior it changed is covered by a test. A green suite is the signal the slice is actually shippable, not just that the review finished. -- `git-commit` makes the atomic-commit call itself. Because a slice is one coherent change, expect a single commit — don't pre-split the work for it, but do hand it the "ships when" context so the message explains the why. - -**How to reach each skill.** `slice` and `test-driven-development` are user-invoke-only (`disable-model-invocation: true`): the Skill tool refuses them with an error, so you must **read and follow their `SKILL.md` directly** rather than calling them. `git-commit` has no such restriction — invoke it through the Skill tool as Phase 7 describes. Depending on how the plugin was installed these may appear namespaced (`rails-consultant:slice`, `rails-consultant:test-driven-development`, `rails-consultant:git-commit`); use whichever name applies. - -Each `SKILL.md` lives at the plugin's `skills//SKILL.md` (or `~/.claude/skills//SKILL.md` for a standalone install). Whatever the reason a phase's skill can't be invoked — user-only, not installed, or otherwise unavailable — follow its `SKILL.md` rather than skipping the phase. The sequence is the point. diff --git a/skills/feature-dev/references/code-explorer.md b/skills/feature-dev/references/code-explorer.md deleted file mode 100644 index 0b4a69a..0000000 --- a/skills/feature-dev/references/code-explorer.md +++ /dev/null @@ -1,27 +0,0 @@ -# Codebase Explorer Brief - -The brief for the Phase 2 exploration subagents, adapted from the feature-dev `code-explorer` agent and focused on grounding a single slice in a Rails codebase. Hand this to each general-purpose subagent along with the specific angle it should cover. - -## Mission - -Trace how the relevant part of this app actually works, so the slice's acceptance criteria are realistic and the implementation follows existing conventions instead of inventing new ones. You are building a map, not writing code — read, trace, and report. - -## What to trace - -**Entry points and flow.** Find where the feature area begins — routes, controller actions, jobs, mailers, or UI — and follow the call chain through the layers (controller → model/service → data). Note the data transformations and side effects along the way. - -**Patterns and conventions.** Identify how this app is built: the domain models and their relationships, where business logic lives (fat models, service objects, query objects, form objects), how authorization and validation are handled, and any conventions spelled out in `CLAUDE.md`. Find the closest existing feature to the one being built and describe how it's implemented — that's the template to follow. - -**Testing conventions.** Look at how the suite is structured — the framework (RSpec or Minitest), how tests are written across the layers (end-to-end/system, request or controller, model/unit), what factories or fixtures exist, and any test helpers. This matters because these patterns become the failing tests in the TDD phase. - -## What to report - -Keep it tight and actionable: - -- **How the relevant area works** — entry points with `file:line`, the flow through the layers, key components and their responsibilities. -- **Conventions to follow** — the patterns, abstractions, and house style the new slice should match, with `file:line` references. -- **The closest existing feature** — what to mirror. -- **Testing approach** — how tests in this area are written and what factories, fixtures, or helpers to reuse. -- **The 5–10 files most worth reading** — the essential set for understanding this area deeply. - -Return findings only. Do not contact the user or write any code — the orchestrator reads your report and the key files before proceeding. diff --git a/skills/feature-dev/references/code-review.md b/skills/feature-dev/references/code-review.md deleted file mode 100644 index cd951c5..0000000 --- a/skills/feature-dev/references/code-review.md +++ /dev/null @@ -1,44 +0,0 @@ -# Code Review Standard - -Background for Phase 5. The review itself is delegated to Claude Code's built-in `/code-review` command (run at a level, with `--fix` to auto-apply). This file documents the standard that review applies — the same confidence-based approach the feature-dev `code-reviewer` agent uses — so you understand what it's weighting, and so you can fall back to a manual review if the built-in command isn't available in the environment. - -## Scope - -Review the diff for the slice just built — `git diff` against the branch point, or the specific files changed. Do not review pre-existing code outside the slice; a problem that was already there before this work is out of scope unless the slice made it materially worse. - -## What to review - -**Project guidelines compliance.** Verify adherence to explicit project rules — typically `CLAUDE.md` or equivalent — covering import patterns, framework conventions, Ruby/Rails style, error handling, logging, testing practices, and naming. In a Rails app this includes fat-model/skinny-controller boundaries, proper use of scopes and validations, strong params, and the app's established service/query-object patterns. - -**Bug detection.** Real bugs that will hit in practice — logic errors, nil handling, N+1 queries, missing database indexes on new lookups, race conditions, mass-assignment or authorization gaps, and security vulnerabilities. - -**Code quality.** Significant issues only — duplication, missing critical error handling, accessibility problems in views, and inadequate test coverage for a behavior the slice introduced. - -## Confidence scoring - -Rate each potential issue 0–100: - -- **0** — Not confident. A false positive that doesn't survive scrutiny, or a pre-existing issue. -- **25** — Somewhat confident. Might be real, might be a false positive. If stylistic, not called out in project guidelines. -- **50** — Moderately confident. Real, but a nitpick or rare in practice. Low importance relative to the rest of the diff. -- **75** — Highly confident. Double-checked; very likely real and will be hit in practice. The current approach is insufficient, or it's directly named in project guidelines. -- **100** — Certain. Confirmed it will happen frequently; the evidence directly confirms it. - -**Only report issues with confidence ≥ 80.** Quality over quantity. A review that lists twenty maybes trains the developer to ignore reviews; a review that names three real problems gets acted on. - -## Output for each reviewer - -State what you reviewed. For each issue at confidence ≥ 80, give: - -- A clear description with the confidence score. -- File path and line number. -- The specific guideline reference or a concrete explanation of the bug. -- A concrete fix. - -Group by severity — **Critical** (bugs, security, data integrity) vs. **Important** (quality, conventions, coverage). If nothing clears the bar, say so and confirm the slice meets standards with a one-line summary. - -## After the review - -The built-in `/code-review --fix` applies the confirmed fixes itself, so there's no findings list to consolidate by hand. Two things still matter once it's done, and they're spelled out in Phase 5 of `SKILL.md`: re-run the full suite to confirm the slice is still green, and if a fix changed behavior that no test yet covers, add the missing test (failing first) so the correction can't silently regress. - -If you're doing a **manual fallback** (the command isn't available): review the slice diff against the standard above, keep only confidence ≥ 80, group by severity, and apply the fixes test-first — any behavior change gets a failing test before the fix. diff --git a/skills/git-commit/SKILL.md b/skills/git-commit/SKILL.md deleted file mode 100644 index dcbbad7..0000000 --- a/skills/git-commit/SKILL.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -name: git-commit -description: Turn the working changes into one or more atomic commits with well-written messages. Use whenever the user runs /git-commit or asks to commit their work, wrap up a feature, or "commit what I have." -argument-hint: "[optional note or context to fold into the message]" ---- - -## What this does - -Look at everything that has changed in the working tree, decide how the changes should be split into commits, and then create those commits — messages and all — without stopping to ask for approval. The user invoked `/git-commit` because they trust you to make the call, so make it and report what you did afterward. - -Any argument the user passes is context, not a command: a hint about intent ("addressing review feedback", "this is risky, note the migration") that should inform how you group and what you write. It is never the literal commit message. - -## Step 1: Understand what changed - -Before grouping anything, build a real picture of the diff. Run these together: - -- `git status` — what's modified, added, deleted, untracked -- `git diff` — unstaged changes -- `git diff --staged` — anything already staged -- `git log --oneline -15` — recent history, to match the tone and see referenced issues/PRs - -Read the diff to understand the _why_, not just the _what_. You are about to explain these changes to a future reader; you can't do that if you only know which lines moved. If something is genuinely unclear, it's fine to ask one focused question — but usually the diff plus recent history tells the story. - -If there's nothing to commit, say so and stop. Never create an empty commit. - -## Step 2: Decide the grouping — this is the judgment call - -The goal is **atomic commits**: each commit is one complete, coherent change that stands on its own. The hard part is knowing how many commits that means, and there's no mechanical rule — it depends on what the work actually is. - -**Lean toward a single commit when the changes tell one story.** If the user just built a feature — new model, its migration, the controller, the view, the tests — that's _one_ logical change even though it spans many files. Splitting it into "add migration", "add model", "add tests" produces commits that are individually broken and useless to revert. Keep it together. - -**Split into separate commits when the changes are genuinely independent.** The tell is that the work is a _set of unrelated things_ rather than one thing: - -- Addressing several distinct review comments — each comment is its own commit -- A handful of unrelated refactors or cleanups that happen to be sitting in the tree together -- A bug fix that got made alongside feature work — the fix is its own commit -- A dependency bump plus the feature that needed it — often two commits - -Ask yourself: _if someone had to revert one part of this, would the rest still make sense?_ If yes, they're separate commits. If reverting one piece would leave the others broken, they belong together. - -When in doubt, prefer fewer, larger commits over many tiny ones. An over-split history is harder to read than a cohesive one. - -## Step 3: Stage each group precisely - -Commit the groups one at a time. For each: - -- If a group is cleanly whole files, `git add ` for just those files. -- If a single file contains changes belonging to _different_ logical groups, stage only the relevant hunks. Write the intended hunks to a patch and apply them with `git apply --cached `, since interactive `git add -p` isn't available to you. Verify with `git diff --staged` before committing. -- Never `git add .` or `git add -A` blindly — that defeats the point of grouping. - -Then commit that group (Step 4), and move to the next. - -Respect any pre-commit hooks. If a hook modifies files or fails, don't fight it — surface what happened. Don't use `--no-verify` unless the user asked for it. - -Do not push, and do not amend or rewrite existing commits. This command's job ends at creating new commits from uncommitted work. - -## Step 4: Write the message - -Match the voice below and let the body earn its place — a message exists so a future reader understands a decision they couldn't reconstruct from the diff. - -### Subject line - -- Imperative mood, capitalized, **no** trailing period: "Prevent double-filtering of labels", "Introduce category methods", "Optimize initialization" -- Wrap code identifiers in backticks: "Refactor `TopSecret::Text::GlobalMapping`" -- Keep it under ~50 characters where you can -- Add a semantic prefix only when it carries real information: "Breaking change: Validate labels" -- Do **not** append `(#123)` PR-number suffixes — those are added by GitHub on merge, not by hand - -### Body - -Include a body whenever there's a _why_ worth recording, which is most of the time. Skip it only for changes so self-evident the subject says everything ("Fix typo in README"). When you write one: - -- Blank line after the subject, wrap prose at ~72 characters -- **Explain the why, not the what.** The diff already shows what changed. Say what problem this solves or what it makes possible. -- **Be concise.** A few tight sentences beat a wall of text. Cut anything that just restates the code. -- **Call out anything surprising, or alternatives you tried.** If there was a simpler approach you rejected, say why — that's exactly what saves a future reader from re-treading it. -- **Flag risks and dependencies.** A migration that needs care, a change that depends on another PR shipping first, a config value that must be set in production — name it. -- **Write for a non-technical reader.** Prefer plain language over jargon. Someone skimming the history to understand _what shipped and why_ should follow it without reading the code. -- **Reference issues or PRs only when it's obvious** which one applies — e.g. the branch clearly maps to a PR (check `gh pr view` if a PR exists) or the user named it. Never invent or guess a number. Use reference-style markdown links, matching the examples. - -### End every commit with the Claude co-author trailer - -Attribute the commit to Claude with a `Co-Authored-By` trailer on its own line, after a blank line: - -``` -Co-Authored-By: Claude -``` - -Use whatever trailer this Claude Code session normally appends. It often names the specific model, and that name changes from one model and version to the next (for example `Co-Authored-By: Claude Opus 4.8 ` or `Co-Authored-By: Claude Sonnet 4.5 `). Credit the model you're actually running rather than copying a fixed version from these examples — the point is to attribute the commit to Claude, not to assert one exact build. - -This is attribution metadata and is expected — it is _not_ the "AI-generated writing" the next section warns about. - -## Voice and tone - -Write the way the user writes. The prose should read like a careful engineer explaining a decision to a teammate — never like a language model. Concretely, strip the tells of AI-generated writing: - -- No hype or filler adjectives ("comprehensive", "robust", "seamless", "powerful", "significantly") -- No throat-clearing ("It's worth noting that", "In order to", "This change aims to") -- No summarizing the diff back as a bulleted list of file edits -- No em-dash-heavy, uniformly-hedged cadence — vary sentence length like a person does - -Reach for the framings the user actually uses: - -- "Prior to this commit, we were making multiple passes over the substituted text, resulting in labels being filtered. This commit substitutes the text on one pass." -- "In an effort to support dynamically generating predicate methods, we first need to ensure labels are formatted consistently." -- "Now that RubyLLM::TopSecret is live, we should promote the project here to help with discoverability." -- "Although a simpler approach exists, it's not practical because..." - -### Worked examples - -**Example 1 — a cohesive feature, one commit:** - -``` -Introduce `TopSecret::Text.scan` - -There are cases where callers want to know whether text contains -sensitive information without filtering it. `scan` answers that -question and returns the mapping it found. - -`filter` now uses `scan` internally, which is a small speed-up: we -skip the filtering work entirely when the input has nothing sensitive -in it. - -Relates to the discussion in #50. - -Co-Authored-By: Claude -``` - -**Example 2 — a risk worth flagging:** - -``` -Cache `Mitie::NER` - -Initializing `Mitie::NER` is expensive, so we cache it behind a Mutex -to keep it thread-safe. - -We tried the simpler approach of memoizing without a lock (#85), but -it breaks when assets are precompiled at deploy time: the model file -doesn't exist yet, so the first cache write fails. The Mutex version -was tested in a production-like environment — the first request is -slow, every request after is fast. - -Co-Authored-By: Claude -``` - -**Example 3 — trivial change, subject only:** - -``` -Fix typo in installation instructions - -Co-Authored-By: Claude -``` - -## Step 5: Report what you did - -After committing, show the user the result — `git log --oneline` of the new commits is usually enough — so they can see how you grouped and worded things. If you made a judgment call worth knowing about ("I split the bug fix out from the feature"), say so in a sentence. diff --git a/skills/hard-news/SKILL.md b/skills/hard-news/SKILL.md deleted file mode 100644 index 515c116..0000000 --- a/skills/hard-news/SKILL.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -name: hard-news -description: Prepare to deliver difficult technical news to a client — a conversational prep session before the hard conversation happens -argument-hint: "[brief description of the situation]" -disable-model-invocation: true ---- - -## Behavior - -This is a prep session. The goal is to walk into a hard conversation clear-headed, not rehearsed. Start by understanding the situation conversationally — one question at a time. - -Open with: - -**"Tell me what happened — the version you'd say to a colleague, not the client. Don't soften it yet."** - -Wait for their answer. Then ask what matters most for shaping the conversation: - -**"What do you know about how this client handles bad news? And what do you need from this conversation — what's the outcome you're steering toward?"** - -Wait for their answer. Then, before preparing anything: - -**"Write your opening two sentences right now — the actual words you'd say to start this conversation. Don't polish them, don't second-guess them. Just write what comes out."** - -Wait for their draft. This is the most important step — it reveals how they instinctively handle pressure. Open the prep with honest feedback on their draft: what's working, what would land badly, and what to change. - -Then deliver the full prep. Keep it tight — they need to be able to hold this in their head going into the conversation: - -**The news in one sentence** — the clearest, most honest version. No jargon, no hedging, no burying the lead. - -**How to open** — the first 3–4 sentences verbatim. Lead with the news, not a preamble. Bad news after small talk feels like manipulation. Name the problem directly, take appropriate accountability without over-apologising, signal there's a plan. - -**The explanation** — how to describe what happened in plain terms the client understands. What happened, why, what you know vs. what you're still figuring out, and what it means for the project. - -**The path forward** — what you're proposing. Specific, not vague. If the plan isn't complete yet, say what you do know and when you'll have more. - -**Likely reactions** — 2–3 reactions given what you know about this client, and how to respond to each. Non-defensive, grounded. Defensiveness signals you care more about being right than solving the problem. - -**What not to say** — 2–3 specific phrases or moves to avoid. Things that feel natural under pressure but damage trust: over-apologising, deflecting blame, minimising impact, over-promising. - -Close with: - -**"What did your unpolished opening reveal about how you instinctively handle discomfort? Did you soften, deflect, or lead straight?"** - -Wait for their answer. Respond with one short paragraph: what their draft pattern reveals about their default communication instinct under pressure, and the one habit worth practising. - -## Tone - -Direct and empathetic. This is not a script to hide behind — it's a thinking tool to enter the conversation clear-headed. The user should feel prepared, not rehearsed. diff --git a/skills/implement-with-tdd/SKILL.md b/skills/implement-with-tdd/SKILL.md new file mode 100644 index 0000000..16c26d6 --- /dev/null +++ b/skills/implement-with-tdd/SKILL.md @@ -0,0 +1,144 @@ +--- +name: implement-with-tdd +description: Implement a SPEC, plan, or feature outside-in, with TDD. +argument-hint: "[path to a SPEC or plan, or a description of the change]" +--- + +# Implement with TDD + +Work from the outside in and let each failure name the next move. Stop at +shameless green; a later step refactors. + +The discipline exists because you're fluent enough to write plausible code for +almost anything, and plausible isn't correct. A failing test tells them apart. + +## What you were handed + +The thing to build: `$ARGUMENTS` + +If that's empty, ask. If it's a path, read it. + +Take the acceptance criteria as the scope. Those are behavior, and behavior is what +you can test. A suggested design, a test path, an ordering: that's a guess from a +session that never ran the suite. Yours will run it, so your evidence is better. +Where the repo contradicts the plan the repo is right — say so rather than diverge +quietly. + +A `## Where to look` section is the exception to that distrust, not to the scope +rule. Those paths are where a prior session already found the relevant code, so they +save you the search and not the judgment: open them before you go looking for +anything else, and treat nothing on the list as work you owe. The criteria are still +the whole scope. If a path is gone or turns out to be irrelevant, skip it and say so +in the report — don't edit the SPEC. + +The list names the commit it was written at. When that isn't `HEAD`, the paths +usually still hold and the reason beside each one may not, so read the file before +you act on its description. + +## Before the first test + +Learn the suite: + +- The command for one test file, and the one for everything +- Which layers exist here (end-to-end, request or API, unit) — you can only start + at the outermost layer the repo actually has +- The local idiom: factories or fixtures, helpers, naming + +Read the two or three tests nearest your area and copy their style, even where +you'd write it differently. `references/test-style.md` covers how to write the +test itself and what belongs at each layer; read it before the first one. + +If the suite can't be made to run using the repo's documented setup, stop and +report what's missing — a missing database or service isn't something to work +around. If there's no test framework at all, stop and ask which to use. + +## Size the feature + +Roughly 200 lines of implementation is the budget for one feature. Count every +line you typed into a file that ships — views, routes, config, locales, `end`s and +blank lines included. Free: tests and the factories or fixtures feeding them, +comments, and generated files you didn't edit — schema dumps, lockfiles, +snapshots, scaffolding output. A migration you generated is free; the body you +wrote inside it isn't. Tests stay free here even where your usual diff budget +counts them. + +Count what you added, not net. Deleting doesn't buy room, and code you moved +unchanged is free. `git diff --stat` minus your test files is close enough; don't +script it. + +Estimate now, with the neighboring code read. Per criterion, name the files you'd +touch and whether the layer already exists — several criteria each needing a new +object is the shape that blows the budget. + +If the estimate is over, stop before the first test. Report the number, the +criteria carrying the weight, and the smaller first cut you'd take instead — the +one or two criteria that stand on their own. Then wait. What to drop is a scope +decision, and starting is a way of making it for them. + +## The loop + +One criterion at a time, and only one test you wrote red at once. + +1. **Write the outermost test for the criterion.** Drive it the way a user reaches + the behavior, and assert on what that user can see. It should fail on the thing + you haven't built, not on a typo. +2. **Run it and read the failure.** Literally — not the failure you expected. +3. **Make the smallest change the failure asks for.** Not the change that finishes + the feature. `references/failures.md` maps each kind of failure to its next + move, including which ones send you down a layer and which don't. +4. **Run it again.** A new message means you moved. An unchanged message means you + did something necessary but insufficient, or you guessed — say which, and drop + the change if you can't name what it unblocks. +5. **Repeat until green**, then run the tests around what you touched. A failure + in something you never touched may predate you — check it against a clean + checkout before you spend the session on someone else's broken test. Check the + count against the budget, then take the next criterion, and run everything once + at the end. + +Work through every criterion without checking in. Four things earn a stop: a +suite you can't run, the same failure surviving two different fixes, work that +reaches outside the process or handles a secret, and the budget running out. The +last two are project decisions, not implementation details. + +A library you already have installed is still someone else's call. The decision +isn't the install line, it's where the URL or credential lives, what the code +does when the call fails, and how the suite stays runnable offline. Storing a +password is the same shape. Lay the options out and wait — raising one and +closing it in the same breath isn't a stop. + +When the count crosses, finish the criterion you're on and stop there rather than +opening the next one — a half-built criterion is worse than a missing one. Report +the count, which criterion crossed, and what's left unbuilt. + +## Shameless green + +Reach green with explicit, duplicated, readable cases. Spell the value out. Copy +the neighboring case and change what differs. Write one branch per case the tests +name, and none for a case no test named, since that branch is a guess you'd have +to maintain. A passing test is the signal to stop writing code. + +You're trading changeability for clarity, not clarity for speed. Duplication is +cheap to remove later; a wrong abstraction drawn from one example spreads into +every caller first. The duplication is also the evidence the refactor runs on — +it shows where the seam really is. + +Fakes aren't shameless, they're false. A hardcoded return value that satisfies the +test is fine; an accessor standing in for a column that ought to exist, or a stub +where the real call belongs, makes the test lie about what works. If the criterion +needs schema, add the schema. + +Duplication counts against the budget. If spelling the cases out is what blows it, +keep the duplication and stop at the boundary above: that means the feature is too +big for one slice, not that it needs an abstraction. + +No comments apologizing for the shortcut, no TODO promising to fix it, no +half-built abstraction for later. + +## When you're done + +Report the criteria you covered, any you left unbuilt and why, the tests you added +and where, the suite result, and the lines you spent against the budget, including +whether your estimate held. Then name the ugliest thing you left standing, because +that's where the refactor starts. Leave everything uncommitted. + +Bullets, not a narration of the loop. They can read the diff. diff --git a/skills/implement-with-tdd/references/failures.md b/skills/implement-with-tdd/references/failures.md new file mode 100644 index 0000000..071e32e --- /dev/null +++ b/skills/implement-with-tdd/references/failures.md @@ -0,0 +1,58 @@ +# Reading a failure + +Match on what the failure _is_, not on the phase you think you're in. Frameworks +word these differently; the shape is what matters. Work the first failure, not +the one you find most interesting. + +| The failure | What it means | Next move | +| ------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------- | +| The test command isn't recognized, or the suite won't load at all | You guessed the layout | Find how this repo actually runs tests | +| Pending migration, stale schema, or the suite aborts before any test runs | Environment, not code | Prepare the test schema, start the service. Not a code gap | +| Setup code raised — factory, fixture, helper | Your Arrange is broken | Fix the setup | +| Unresolved symbol or import at compile or collection time | This _is_ a code gap | Use the domain-object or framework-class row below, whichever fits | +| No route, no such subcommand, no entry point in the thing you're building | Outer plumbing gap | Smallest entry point that produces a different failure | +| Missing template, view, renderer, or output target | Render gap | Thinnest possible output. Empty is fine | +| Redirected, bounced to a sign-in, or forbidden | Arrange gap | Authenticate as someone allowed to do this. Don't invent collaborators | +| Expected content absent, and you're on the right page | The data isn't exposed yet | Write the literal where it renders. Invent a collaborator only if a literal can't say it | +| Missing table or column | Schema gap | Generate and run the migration — that _is_ the smallest change | +| Undefined method on a domain object you own | **Drop down** | Unit-test that one behavior, green, come back up | +| Undefined framework class — controller, job, mailer, serializer | Framework plumbing | Create the thinnest one where you stand. Don't drop down | +| Wrong argument count or type at a call you just wrote | Caller and signature disagree | Fix the call site, or extend the signature where you stand | +| Expected X, got Y | Behavior is wrong | Shameless green: explicit, readable, one case at a time | +| Passes the moment you write it | It may already be built | Read the code. If it exists, say so and move on. If not, break it on purpose to prove the test can fail | +| Tests you didn't write went red | Regression | Read the first one. If one cause explains several, fix the cause | +| Passes alone, fails in the suite | Order dependence or leaked state | Re-run with the same seed before believing it | +| The same failure after two different fixes | You're guessing | Stop and report what you don't understand | + +## Drop down, then come back up + +One failure moves you down a layer: a method missing from a domain object you +own. Framework classes you create where you stand — a controller has no behavior +of its own to unit-test yet, and the layer beneath an end-to-end test is usually +a request or service test, not a test of the framework class. + +Dropping down isn't switching tasks. The outer test is still red and still in +charge. Unit-test exactly the behavior the outer failure named, no more, get it +green, then re-run the outer test and let its new message choose what's next. + +## When the message doesn't change + +An unchanged message is information, not a verdict. Two things produce it: a +change that was necessary but not sufficient — a migration, one of several +co-required pieces — and a guess. Say which you think it is. If you can name the +next thing your change unblocks, keep it and carry on. If you can't, drop it +rather than stack a second guess on top of it. + +Two unchanged messages in a row means stop. + +## Out of bounds + +The failure is the specification. These moves fake agreement with it, and each +one trades a question about the code for a bug that surfaces later: + +`skip`, `xit`, or `pending` on a test you can't pass. `sleep` to settle a race. +Loosening an exact assertion to a truthiness check, widening a matcher, or +deleting an example. `--fail-fast` to hide the remaining reds. + +Change a test only once you've found the test itself is wrong, and say so when +you do. diff --git a/skills/implement-with-tdd/references/test-style.md b/skills/implement-with-tdd/references/test-style.md new file mode 100644 index 0000000..a418a63 --- /dev/null +++ b/skills/implement-with-tdd/references/test-style.md @@ -0,0 +1,103 @@ +# Writing the test + +Read this before the first test. The example is Ruby because the house style is +Ruby; the pattern is the point, and the local idiom always wins. + +## Arrange / Act / Assert + +Three phases, separated by blank lines, in that order: + +```ruby +it "adds the tag to the user" do + tag = create(:tag) + user = create(:user, tags: []) + + user.add_tag(tag) + + expect(user.tags).to eq([tag]) +end +``` + +Arrange sets up the world. Act exercises the thing under test, once. Assert +checks the result. One act per test — with two, a failure can't tell you which +one broke. + +Two blank lines, always: one before the Act, one before the Assert. + +Reading the result often takes a call of its own — a second request, a reload, a +query. Keep it with the Act, and leave the blank line above the assertions: + +```ruby +it "shows the flag on the list" do + expense = create(:expense, description: "Coffee") + + post flag_expense_path(expense), params: { reason: "Duplicate" } + get expenses_path + + expect(response.body).to include("Coffee Flagged") +end +``` + +That's still one act — two calls, one behavior, and only one of them could have +broken. Assertions running straight off the last call are how three phases turn +into two, and it's the most common way this gets written wrong. + +Nothing that asserts belongs in Arrange. Stub during Arrange, then check the call +happened during Assert. + +If a test touches the filesystem, environment variables, or the working +directory, clean up after it. Transactional fixtures cover the database and +nothing else, and leaked state is what makes a suite that only fails in a +certain order. + +## Keep the setup in the body + +Put the Arrange inside the test, not in shared setup blocks or hoisted lazy +variables. Hoisted setup leaves the body holding only the assertion, so finding +the preconditions means reading the rest of the file. + +Tests are the place for concretions, not abstractions. Literal values, +spelled-out setup, no loops or conditionals, and never compute the expected value +with the same logic the code uses — that passes even when both sides are wrong. + +Name the test after the behavior and the condition, so a list of failures reads +as prose. Prefer a second flat test with the condition in its name over a nested +context that overrides one variable. + +## Which layer + +Only the outermost test proves the criterion is real. Everything below it pins +down behavior, and that's where most of your tests end up — the top is slow, +needs the most machinery, and breaks when anything nearby changes. Inverted, that +shape is Fowler's ice-cream cone, and it's the kind of suite people stop +trusting. + +- **Outermost** (end-to-end, system, feature, CLI invocation): one per acceptance + criterion. Drive it the way a user reaches the behavior. Real records, no + mocking of your own objects. Stub external HTTP only — the suite has to run + offline. Assert through the surface you acted through: a list that still + reads `Flagged` is the criterion failing, while `expense.flagged?` coming back + false is a unit test hiding in an end-to-end file. If the outcome isn't visible + from out there at all, it belongs in the boundary case below. +- **Middle** (request, API, service layer): this is your outermost layer when + there's no UI, or when driving the UI adds machinery without adding proof. +- **Unit**: where the drop-downs land, and where the base of the pyramid comes + from — one criterion often earns several unit examples. Test one object's + behavior and stub its collaborators, since the point is proving this object + works rather than re-proving theirs. + +An outer test and a unit test covering the same feature aren't duplicate +coverage. The outer one asserts the user-visible outcome; the unit one asserts +the logic that produced it. Different assertions. + +## Work you can't see from the outside + +Background jobs, mail, and scheduled work aren't observable by driving the UI. +Assert at the boundary — that the job was enqueued, that the mail was queued — +and test the performed effect in its own test. Don't reconfigure the app to run +jobs inline so an end-to-end test can see them; that changes production behavior +to suit a test. + +If two objects are painful to test apart, that's the tests telling you they're +too tightly coupled. Worth naming in your report, since the refactor step can act +on it. diff --git a/skills/multi-lens-review/SKILL.md b/skills/multi-lens-review/SKILL.md new file mode 100644 index 0000000..4334df3 --- /dev/null +++ b/skills/multi-lens-review/SKILL.md @@ -0,0 +1,160 @@ +--- +name: multi-lens-review +description: Review a change for defects, then against its spec, its codebase's conventions, the domains trying to emerge from it, and whatever still depends on what it replaced. +argument-hint: "[PR number, branch, or paths to review]" +--- + +# Code review + +Five reviewers, dispatched in parallel, each reading the same change from a different distance: + +| Agent | Question | +| ------------------------- | -------------------------------------------------- | +| `agents/defects.md` | Is this code wrong — broken, slow, or exploitable? | +| `agents/spec-fidelity.md` | Did we build what was asked for, and only that? | +| `agents/conventions.md` | Does this look like the rest of the codebase? | +| `agents/domains.md` | Is a domain concept trying to emerge here? | +| `agents/compatibility.md` | Does anything still depend on what this replaced? | + +They stay separate so the structural reviewer has nothing cheaper to do. One reviewer asked all five questions spends its attention on naming nits, and never reaches "those five files are one domain object in a trenchcoat." + +## The confidence bar + +Every finding carries a confidence out of 100: how sure the reviewer is that it's true and that the author would agree it's worth changing. Below 80, the agent drops it without mentioning it. Print the score with each finding so the author can calibrate how much to argue. + +What's scarce in a review is the author's trust, not their reading time. + +## Workflow + +1. Fix the target — one diff, captured once. +2. Find the intent the change was supposed to satisfy. +3. Dispatch the five agents in parallel. +4. Synthesize into one report. +5. Offer the fix. + +### 1. Fix the target + +`$ARGUMENTS` may hold a PR number, a branch, paths, or nothing. Decide intent-or-target by what a file says, not where it sits: a file that reads as acceptance criteria is the intent, in `docs/specs/` or anywhere else, and a directory or a source path is a target. Ask when a doc argument isn't obviously criteria — reviewing a SPEC file against nothing is a wasted run. + +Resolve it to one diff, then capture that diff to a file (`mktemp`) and hand every agent the same path. If each agent runs its own `git diff` instead, one reviews the commits while another reviews the working tree, and their findings won't line up with each other or with what the author sees. + +Every target but a PR number needs a base. Resolve it once, and only for those: + +``` +base=$(git symbolic-ref --short -q refs/remotes/origin/HEAD \ + || git rev-parse --verify -q origin/main \ + || git rev-parse --verify -q origin/master) +``` + +If that comes back empty, ask which branch to diff against rather than proceeding; the substitution failing silently collapses `git diff $base` into a bare `git diff`, which is unstaged changes only. Don't ask it on a PR number — `gh pr diff` computes its own base, and stalling the run on a question with no bearing on it is worse than not asking. + +The agents read whole files around the diff, so the working tree has to be the diff's after-state. Note where you started — `orig=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)`, because `rev-parse --abbrev-ref HEAD` prints the string `HEAD` on a detached tree and restoring to that is a no-op that looks like it worked. + +- A number: `gh pr checkout ` first, then `gh pr diff `. Its base is its own, so take it explicitly: `base=$(gh pr view --json baseRefName -q .baseRefName)` — step 4 needs it. +- A branch or ref: `git diff "$(git merge-base "$base")" `, and check `` out. +- Nothing: `git diff "$(git merge-base HEAD "$base")"` — committed and uncommitted both. +- Paths: the same, with `-- ` appended. + +Keep the merge-base you computed as `mb`; step 4 checks paths against it. + +Either checkout can fail — a dirty tree, a fork whose head isn't fetchable. Stop and say the review can't read the code around the diff. Running on the diff alone reviews it against whatever `HEAD` happened to be, and a checkout that succeeded by carrying uncommitted changes along has left the tree something other than the diff's after-state. + +The last two targets need new files staged or they don't appear in the diff at all, and the criterion a new file implements comes back unmet. Record what you touched so you can undo exactly that, before dispatching: + +``` +new=$(mktemp) +git ls-files --others --exclude-standard -z -- :/ > "$new" +xargs -0 -r git add -N -- < "$new" +# ...capture the diff... +xargs -0 -r git reset -q -- < "$new" +``` + +The `:/` is what makes it repo-wide. `git ls-files --others` is scoped to the working directory while `git diff` isn't, so run the skill from a subdirectory without it and new files above you stay out of the diff — the exact failure the block exists to prevent. + +A bare `git reset` would unstage whatever the author had already staged, which isn't yours to touch. Leaving the marks in place is worse: their next `git commit -a` sweeps in every untracked file in the repo. + +Check the result before going further. An empty diff means stop and say so — five agents handed an empty file will find something in the neighboring code they read instead. Past roughly 1500 lines, ask for paths or a commit range; agents silently review the first part of a diff that big and report nothing to say they did. + +### 2. Find the intent + +Fidelity needs acceptance criteria the change was measured against. Two places hold them: a path in `$ARGUMENTS`, or `docs/specs/`, where `/slice` writes. Match on the branch name or a slug in the commit messages, and if two are close, ask instead of guessing. A PR has both locally, because step 1 checked its branch out. + +PR bodies, issues, and commit messages don't count. They describe goals in prose, and prose doesn't draw a scope boundary — so creep is invisible against it, and every finding turns into an argument about what the sentence implied. Criteria or nothing. + +If you found a SPEC, check whether it's itself in the diff. A SPEC edited in the same change as the code was either renegotiated in the open or quietly reshaped to match what got built, and only the author knows which — so ask. + +**When there's no SPEC.** This is the common case, and the tempting move is to let the agent infer the intent from the diff. Don't. Intent reconstructed from code always matches that code, so the check passes by construction and the author gets a clean bill of health they never earned. + +Instead, write the criteria yourself: read the diff and draft the five or six given/when/then lines it looks like it was built from, then show them to the user and ask what's wrong. The corrections are the whole point. A plain list of what the change actually does is the artifact that makes "I never asked for that" obvious, and the user is the only one who can say it. Once they've signed off, those criteria are binding and the agent runs on them normally. + +If they'd rather not, skip the agent and say the fidelity check didn't run. An absent check is information; a manufactured pass isn't. + +### 3. Dispatch + +Read the five agent files and launch them as `Explore` agents in one message so they run concurrently. `Explore` has no `Edit` or `Write` — but it does have `Bash`, so tell each agent plainly: no command that writes, stages, or checks anything out. A reviewer that quietly fixes a finding instead of reporting it is one the author can't learn from. + +`agents/defects.md` states a tighter allowlist for itself, since proving a bug is the natural next step for that one. Pass it through as written rather than substituting the looser rule above. + +Tell them to read whole files and the whole diff. `Explore` samples excerpts by default, and an agent that reviewed the first third of a diff reports nothing to say so. + +Give each the diff path, this skill's own absolute directory — the agent files write it as `{skill_dir}`, so substitute the real path before handing the text over, or the reference file they're pointed at won't resolve from the target repo — and this finding format: + +``` +{one-line claim} +{locator} · confidence {N} +evidence: {the citation this reviewer's own file demands} +{Why it costs something, in a sentence or two. Name the smell or the convention.} +{The change you'd make.} +``` + +The locator is `{file}:{line}`, with the line off the new side of the `@@` header plus the offset inside the hunk. Three variants are equally in-format, so step 4 doesn't throw them away: `{file} (in {function or class})` when a line can't be computed — a wrong line number costs the author more than a missing one — one locator per line when a domains finding spans several files, and the same for a conventions comment finding, which `agents/conventions.md` requires to be one per file with a line for each occurrence. + +Otherwise, one finding, one issue, one locator — with one exception, a compatibility finding, which carries two because its whole claim is that these two places disagree. An agent that staples three unrelated sites under a single anchor has written something the author can't act on or argue with, and the anchor points at only one of them. + +The evidence line is what makes the score checkable. Each agent file says what its own evidence is — a convention needs the path of the file that establishes it, or the named smell plus a line for each occurrence, or nothing at all for a comment finding, which that file exempts; a domain needs its three occurrence sites; a fidelity finding needs the criterion quoted, and quotes no path; a defect needs the trigger plus where the triggering value comes from; a compatibility finding needs the changed line and the thing that still assumes the old behavior. Read the agent's own rule before judging its evidence — holding one to another's is how a valid finding dies in synthesis after the agent was told to file it. + +Defect evidence is the weak case, and worth knowing about before you trust it. The other four cite an artifact you can open; a trigger is prose, and its truth is the claim under review. Checking the paths around it is all step 4 can do — so a defect that survives synthesis has been checked less than the findings next to it. + +The confidence bar is stated in each agent file; don't restate it here. + +The fidelity agent also needs the criteria from step 2, as a path. If they came out of the conversation rather than a SPEC file, write them to a temp file first so the fidelity agent reads a file rather than transcript. + +Ask for findings only — no summary, no praise, no "overall this looks good." Some will add it anyway, which is why step 4 throws it away rather than trusting the instruction. + +### 4. Synthesize + +Lead with what you reviewed: the target, the intent source and its kind, and a one-line verdict a person can act on. Say up front if a check didn't run — a review missing its fidelity pass looks identical to one that passed it, unless you name the difference. + +Then the findings under five headings, numbered continuously across all five so step 5 has something unambiguous to name. Defects come first because they're the ones with a cost attached to shipping, and compatibility second for the same reason: both cost something the moment this ships, where the other three cost something later. Sort inside each heading by highest confidence — except defects, which sort by consequence first: a confidence-95 off-by-one in a log line sits below a confidence-82 unbounded delete, and confidence alone puts them the wrong way round. + +Discard an agent's preamble, summary, and verdict rather than editing them down. Drop a finding whose evidence line is missing, and check the paths it does cite — the locator's file, the occurrence sites on a domains finding, and both locators on a compatibility one, unless it says outright that the surviving dependent is outside this repo and it couldn't check. A fidelity finding cites no path at all, so there's nothing to check there and nothing to drop it for. + +Check a path against the diff and the merge-base — `git cat-file -e "$mb:"` — not against the working tree. A change that deletes a file produces legitimate findings citing a path that's no longer on disk, and an unset `$mb` turns that command into a check against the index, which quietly passes for everything the current branch tracks. If you don't have a merge-base, don't run the check. + +Don't drop a finding over the shape of its locator line; step 3 allows three. An agent arguing for its own finding is the one party with a reason to round its score up, so the number can't be the filter; the citation can. + +A finding filed under the wrong heading moves; it doesn't get dropped. The conventions agent reporting a SQL injection found a real defect — file it under defects, next to whatever the defects agent said about the same lines. + +Two agents often catch the same code from different heights — duplication as a smell and as an unnamed domain. Where one fix settles both, keep the higher-altitude version and drop the other, because the author fixes it once. Where the two fixes are different edits, keep both: a wrong return value and a long method live on the same lines and neither one resolves the other. + +Defects also collide the other way, with a finding that argues the opposite. The clearest case: defects reports a fallback that quietly returns a wrong answer, and fidelity reports that same error handling as scope nobody asked for. One says fix it, the other says delete it. Report both, adjacent, and name the conflict — dropping either leaves the author fixing a bug in code that shouldn't exist, or deleting a path something now depends on. + +Compatibility collides with defects most often, and the two findings are usually the same line seen from either side of the deploy. Defects reports a read that returns nothing; compatibility reports the column the same diff dropped out from under it. Keep compatibility's version — it names the window, which is the part that decides what order to ship in — and drop defects'. Where the defect is true even after the rollout finishes, they aren't the same finding and both stay. + +If every agent came back empty, say that plainly. A review with nothing in it is a real result, and padding it with observations you scored below the bar is how the bar rots. + +### 5. Offer the fix + +Ask which of the numbered findings to apply. Don't apply them unasked: a reviewer who edits starts defending its own edits, and the author loses the chance to say "that's deliberate, here's why." + +Apply only what they name, one finding at a time, and stop if a fix turns out to be bigger than the finding described. + +Then put the branch back — `git checkout "$orig"` — unless you applied something. Uncommitted fixes don't survive a checkout: it either refuses and you've said you restored when you didn't, or it carries the edits onto `$orig` and the branch they were meant for still has the bug. When you've applied a fix, say which branch the edits are on and leave the operator there. + +## Notes + +- `agents/defects.md` stands in for the built-in `/code-review`, and adds the security pass that lives in `/security-review`. Two things it doesn't do: it can't execute anything, so every defect is a claim with a trigger attached rather than a demonstrated failure, and its confidence bar cuts recall the built-in would keep at high effort. On a change where a missed bug is expensive, run the built-in too. +- The agents run read-only, so anything they'd change comes back as a recommendation rather than a diff. If `Explore` isn't available, say so and pick the most restricted agent type there is rather than reaching for a general-purpose one. +- Nothing here assumes a language or a framework, and the review is worse the moment it starts to. Whatever pattern you're about to recommend, point at the place this repo already does it. If you can't find one, you're recommending a habit from somewhere else. +- `agents/` holds prompt fragments, not registered subagents — no frontmatter, nothing validates them. What an agent can touch comes from the agent type dispatch launches, not from anything declared in those files. +- The noise rules — lockfiles and generated files, findings a linter already gives away free, dimensions that aren't yours — are stated in each of the five agent files rather than here, because the agents never read this one. A rule an agent has to follow and can't see is a rule that doesn't exist. diff --git a/skills/multi-lens-review/agents/compatibility.md b/skills/multi-lens-review/agents/compatibility.md new file mode 100644 index 0000000..6b7eed6 --- /dev/null +++ b/skills/multi-lens-review/agents/compatibility.md @@ -0,0 +1,44 @@ +# Compatibility reviewer + +You're looking for what still depends on the behavior this change replaced. + +The other reviewers judge the end state: the repo after the merge, in one piece, and everything in it consistent with everything else. You're the only one reading two worlds at once — the one that exists right now, and the one this diff creates — because a change doesn't land everywhere at the same instant. For a window, both are true. + +## What's still out there + +Five things outlive a merge, and each one is a place the old assumption is still written down: + +- **A process still running the old code.** During a rolling deploy the new migration is live and the old code isn't gone yet. A dropped or renamed column, a narrowed enum, a tightened constraint — the old code reads it and falls over, on every request, until the last instance cycles. +- **Data already written.** Rows, documents, cached entries, files on disk, all in the old shape. New code that assumes the new shape meets them on the first read. A backfill is only an answer if it ran before the read did — check which lands first. +- **Work already queued.** Jobs, messages, and scheduled tasks were serialized with yesterday's arguments and will be handed to today's code. Changing a worker's parameters, reordering them, or renaming the job class strands everything in the queue. +- **Callers you can't see.** A public function, an endpoint, a CLI flag, a config key, an environment variable, an exported type. If something outside this repository can name it, the diff can't show you its callers. Say so in the finding rather than pretending you checked. +- **Undo.** If this is wrong in production, what does getting back cost? A migration that discards data, a backfill that overwrites the original, a one-way export. Name the cost. Don't file a finding because a migration lacks a formulaic rollback step — file one when the data doesn't come back. + +## The mechanical test + +Take the thing the diff removed or changed — the column, the method, the key, the flag — and grep for its old name across the whole repository. Every hit outside the diff is a candidate. Then decide whether it's reached before the change is everywhere: a caller the same diff updates is fine, a caller the same diff doesn't touch is a finding, a caller that isn't in this repository at all is a finding you flag as unverifiable. + +Run it in the other direction too. A diff that only adds — a required config key, a new non-null column, a new argument — asks something of the world that the world doesn't have yet. `ENV["STRIPE_WEBHOOK_SECRET"]` read on boot, absent from the sample config and from anything in the diff, is the same defect wearing different clothes. + +Let the repo tell you what its deploy actually looks like. A single-process desktop tool, a library published to a registry, and a fleet behind a load balancer have completely different windows, and one of them barely has one. Read the deploy configuration, the release scripts, the version file — and if you can't tell, say which assumption your finding rests on. + +## What isn't yours + +- Code that's wrong inside one version of the repo, with no old anything involved, is a defect. The whole distinction is the window. +- A criterion nobody built is fidelity's. A name that doesn't match its neighbors is conventions'. A concept spread across five files is domains'. +- An internal function renamed, with every caller updated in the same diff, is not a finding. Nothing outside survives to disagree with it. +- A version bump, a new dependency, a lockfile, a vendored directory, anything a tool generated. Not this axis, even when the tool rewrote a thousand lines. + +## Restraint + +Most changes have nothing here, and returning nothing is the ordinary result — you fire on migrations, queue signatures, public interfaces, config, and deletions, and stay quiet on the rest. A reviewer that manufactures a rollout concern for a diff that touches three functions in one file is teaching the author to skip this section. + +## The confidence bar + +Score every finding out of 100: how sure you are it's true _and_ that the author would agree it's worth changing. Below 80, drop it without mentioning it. What you're protecting is the author's trust — six findings that are all right get acted on; twenty where six are wrong teach them to skim the next review. + +Every finding carries an evidence line with two citations: the `file:line` of what changed, and the `file:line` of the thing that still assumes the old behavior. Where the surviving dependent is outside this repository and you can't cite it, say what it is and that you couldn't check — that's an honest finding, and the author can resolve it in a second. A finding with neither isn't one. + +One finding is one claim, one pair of citations, one line, and one fix. Two things the diff broke are two findings. Two ways to repair the same break is a decision you make before you write it down — pick the one you'd ship and write that, because a menu hands the author your uncertainty instead of the change. + +Hold the rest of the finding to the bar you held the claim to. What the deleted rows contained, who else calls the endpoint, which version the other machines are running — if you didn't open a file, cut the sentence or say you couldn't check it, the same way you do for a caller outside the repo. diff --git a/skills/multi-lens-review/agents/conventions.md b/skills/multi-lens-review/agents/conventions.md new file mode 100644 index 0000000..9455db4 --- /dev/null +++ b/skills/multi-lens-review/agents/conventions.md @@ -0,0 +1,48 @@ +# Conventions reviewer + +You're checking whether a change looks like it belongs in this codebase, and whether it carries smells that are already costing something. + +## Read the neighbors first + +Before judging anything, find the two or three existing files closest to what changed — same layer, same role — and read them in full. The convention is what the surrounding code does. A style guide or CLAUDE.md tells you what somebody once intended; where the two disagree, the code wins, unless the guide is enforced in CI. Check whether it is before you cite it. + +Let the repo tell you its layers and its idioms rather than importing them from a framework you know better. Every language has its own answer for how errors travel, where validation lives, what a test looks like, and how a file gets named, and a review that grades one ecosystem's code by another's habits is worse than no review. + +Convention findings that hold up look like "the other three of these do X, at ``; this one does Y." Findings that don't: your own preference, dressed as a house rule. If you can't name the file that establishes the convention, you don't have a finding. + +## Smells + +`{skill_dir}/references/smells.md` has the catalog with the tell for each one. Read it and name the smell you're reporting — a named smell gives the author a concept and a refactoring to look up, where "this feels messy" gives them an argument to have with you. + +A smell earns a finding when it's already costing something in this diff: + +- **Duplicate Code** where the second copy has drifted from the first, so a bug now has to be fixed twice. Two identical copies that haven't drifted aren't this — they're two copies, and whether they want extracting is the domains reviewer's question, not a house rule anyone broke. +- **Long Method** where a reader can't hold the whole thing, not merely where a line count crosses a threshold. +- **Primitive Obsession** where the same validation or formatting is repeated at three call sites. +- **Feature Envy** where the code would be shorter and clearer living next to the data it keeps reaching into. + +Several smells in the catalog only mean something in an object-oriented codebase. Skip the ones the language can't have. + +A textbook smell that costs nothing yet is the author's option to fix later, not your finding. Reporting it spends their trust on nothing and makes the findings that matter look the same size as the ones that don't. + +**Comments are the exception.** A comment the diff adds is a finding whether or not it's costing anything yet — it's the code having failed to say something, and it rots the moment the line beside it changes. This is the one place the neighbors don't decide: a codebase commented this way has been failing to name things for years, and matching it is how that continues, so having no file to cite doesn't drop the finding here. + +The test is mechanical. Delete the comment and ask what a reader lost. If they could recover it from the code, or from the code under better names, it's a finding — and the finding is the rewrite: extract the block into a method called what the comment says, rename the variable it defines, name the literal it explains. If what's lost was never in the code — a decision, a ticket, an upstream bug, a measurement — it survives. So does text something other than a reader consumes: license headers, generated-file markers, pragmas, and the doc comments the ecosystem's tooling or a CI lint requires. So does a comment in a file with nothing to extract into and nothing to rename — config, YAML, migrations, Dockerfiles, shell, Markdown — where a comment is the only documentation available. + +Report one finding per file, not one per comment: name the pattern, give a `file:line` for each occurrence, and write the rewrite for the worst one. Otherwise ten comment findings sort above the Duplicate Code finding scored 85 and the author never reaches it. Comments already in the file and untouched by the change aren't yours — you read those neighbors in full, but none of it is what the author did today. The one exception is a comment the diff falsified: the code moved underneath it and the comment didn't. + +## What isn't yours + +Three other reviewers are reading this same diff, and a finding you file in their dimension doesn't get fixed twice — it buries the convention findings under someone else's work. Structural work larger than the change — new namespaces, extracted concepts, redrawn boundaries — is the domains reviewer's. A bug, a leak, or a slow path is the defects reviewer's, however obvious it looks while you're reading. Code nobody asked for is the fidelity reviewer's. Stay inside the files that changed and their immediate neighbors, and stay on "this doesn't look like the rest of this codebase." + +Free findings aren't findings either. Whatever the linter, the formatter, or the type checker already flags — an unused import, an unreachable branch, spacing — costs the author nothing to learn, and spending a slot on it makes the whole review look cheap. Same for generated files, lockfiles, vendored code, and binaries: skip them unless the change to one is the actual bug. And a micro-optimization on data that will never be large isn't a convention finding at all; it's a preference. + +One finding, one issue — and one issue, one finding. Stapling unrelated sites together under one anchor can't be agreed with or refuted, because the anchor points at only one of them. But the converse costs just as much: a single departure that shows up three ways in the same file — the signature is different _and_ the validation is inlined _and_ the return type changed — is one finding about one file not matching its siblings, not three. Filing it three times triples its weight against everything else in the review and asks the author to accept the same point three times. Comments are the single exception, and those are one finding per file, above. + +## The confidence bar + +Score every finding out of 100: how sure you are it's true _and_ that the author would agree it's worth changing. Below 80, drop it without mentioning it. For a comment, the score is whether you can write the replacement — if you can't write it, you're below the bar. What you're protecting is the author's trust — six findings that are all right get acted on; twenty where six are wrong teach them to skim the next review. + +Every finding carries an evidence line: the path of the existing file that establishes the convention, or for a smell, the named smell plus a `file:line` for each occurrence. No citation, no finding. + +The citation is what the change departs from, not what it did. Pointing at the offending lines shows the author what you read; pointing at the sibling that does it the other way shows them why it's a convention and not your taste. A comment finding has no sibling to cite, so cite the neighbors you checked and found none in — that absence is the precedent — and give the occurrence lines after it, not instead of it. diff --git a/skills/multi-lens-review/agents/defects.md b/skills/multi-lens-review/agents/defects.md new file mode 100644 index 0000000..79fbb5f --- /dev/null +++ b/skills/multi-lens-review/agents/defects.md @@ -0,0 +1,41 @@ +# Defects reviewer + +You're looking for code in this change that is wrong: it computes the wrong answer, it falls over under load, or it lets someone do something they shouldn't. + +`{skill_dir}/references/defects.md` has the catalog, with the tell for each class and the instruction to skip what this stack can't have. Read it and name the class you're reporting. + +## A finding needs a trigger + +The trigger is the input, the state, or the traffic that makes the code go wrong. "This looks fragile" isn't a defect. Trace the changed paths with concrete values and say what comes out; reading a diff for plausibility is how bugs get approved. + +Each of the three kinds earns a finding on a different condition: + +- **Correctness** — the wrong answer or the crash follows from a value the code can actually receive. +- **Performance** — the cost is real, because the data grows with usage or the code sits on a path that runs often. Complexity at sizes this code will never see isn't a finding, and neither is a micro-optimization that trades legibility for speed nobody will measure. +- **Security** — untrusted input reaches the code across a boundary the change crosses. Name the reachable path. Report a secret's location and kind, never its value, and don't write a proof-of-concept exploit. + +## Wrong against what + +You get no statement of intent, and you shouldn't invent one. Intent reconstructed from the code it's meant to judge is worthless in both directions — either it excuses the bug or it convicts the author of missing a requirement nobody wrote. + +So prefer defects that are wrong under any plausible reading of what this code is for: a crash, a corrupted write, an exposed record. Where a claim does depend on intent you inferred, say which intent, in the finding. The author can correct that; they can't correct a guess you didn't show them. + +The same goes for a trigger you couldn't confirm in this repo. If the exploit needs the value to be caller-controlled and you never found the router, the caller, or the schema that says so, mark it as assumed in the evidence line rather than asserting it. A trigger stated as fact sends the author to reproduce it; one stated as an assumption sends them to check the assumption, which is the cheaper trip and the honest one. + +## Scope + +What the change introduced, and what it broke in code that was working. A pre-existing bug counts if the change makes it reachable, hotter, or worse — say that's what it is, so the author knows it isn't their new line, and keep the recommendation proportionate: a fix sprawling well past the changed files and their neighbors is a finding to report, not one to hand over as a patch. + +Read past the diff before reporting. Half of what looks like a missing check is a check one layer up — find the caller and the callee first. Whatever the language, the type checker, or the linter already catches is free, so skip it. + +## Tools + +Read-only, and stricter than the other reviewers because proving a bug is the natural next step for this one. Reading files, `grep`, `glob`, and `git show`/`log`/`diff` are the whole allowlist. Nothing that evaluates code — no repro script, no language one-liner, no test run, no install, no request against anything — and nothing that writes, stages, stashes, or checks out. State the trigger precisely instead; the author reproduces it in one attempt, which is the deliverable. + +## The confidence bar + +Score every finding out of 100: how sure you are it's true _and_ that the author would agree it's worth changing. Below 80, drop it without mentioning it. What you're protecting is the author's trust — six findings that are all right get acted on; twenty where six are wrong teach them to skim the next review. + +The bar is worth more here than anywhere else, because a wrong bug report is the one finding the author can't dismiss on sight. They have to go prove the code works. + +Every finding carries an evidence line: the trigger, plus the `file:line` where it goes wrong. Where the triggering value arrives from somewhere else, cite that origin's `file:line` too, and for a defect that needs two places to be true at once, cite both. No trigger, no finding. diff --git a/skills/multi-lens-review/agents/domains.md b/skills/multi-lens-review/agents/domains.md new file mode 100644 index 0000000..087b7f6 --- /dev/null +++ b/skills/multi-lens-review/agents/domains.md @@ -0,0 +1,38 @@ +# Domains reviewer + +You're looking for the domain concept this change keeps gesturing at without ever naming. Not "could this be refactored" — code can always be refactored. The question is whether a thing already exists in the codebase, spread across files, waiting to be given a name. + +## The tells + +- **A noun in a dozen prefixes.** `subscription_status`, `subscription_expires_at`, `is_subscription_valid`, scattered across three unrelated files. Subscription is already a concept; it just doesn't have a home. +- **A primitive carrying rules.** The same string or integer passed around with the same validation, comparison, or formatting attached wherever it lands. That's Primitive Obsession at codebase scale, and the missing type is obvious once you see it. +- **Shotgun Surgery.** One behavior change required small edits in five files. Those five share something nobody has extracted. +- **Feature Envy pointing one way.** Several functions here all reach into the same data that lives somewhere else. The behavior wants to move to it. + +Let the repo tell you what its units are. A concept might belong in a class, a module, a package, a single exported function, or a table — whatever this codebase already uses to hold one idea. Recommending a shape the project doesn't use anywhere is how a reviewer gets ignored. + +Read past the diff to confirm a tell. A concept that only appears in changed lines isn't emerging, it's just new. + +## Restraint is most of the job + +One or two findings, or none at all. _Emerging_ means the code is asking; it doesn't mean you can imagine an abstraction. Two occurrences are a coincidence, the third is a domain. If you find yourself inventing the concept rather than locating it, you've written Speculative Generality into someone else's change and it's now their problem. + +Don't propose a restructure larger than the change it came from. A forty-line diff doesn't justify a new package. But if the change is the third time this concept has come up, say that — the point of reviewing at this altitude is to catch the moment extraction gets cheaper than continuing to spread. + +Read the untouched files, recommend edits to the changed ones. You find a concept by reading across the codebase, and the third occurrence usually sits in a file nobody opened today — cite it, that's the evidence. But a fix that rewrites three working siblings is a project, not a review comment, and the author will decline it and skip whatever you wrote next. Name the concept, say where it already lives, and scope the edit you propose to the code in the diff. + +Don't lead with a bug. When the fourth copy of something has drifted from the first three, the drift is the defects reviewer's finding and the shared concept is yours. Open on the concept; mention the drift as what made it visible. + +Don't borrow the conventions reviewer's argument either. "The new route doesn't build its response through `reply()` the way its three siblings do" is a house rule the change ignored — and a rule with three examples is a concept that already has a home and a name, which is the opposite of what you're looking for. Yours starts with something that has no home anywhere. If your evidence is three files agreeing and one departing, you've written a conventions finding in domain vocabulary, and the author gets it twice. + +## What a finding looks like + +Name the concept, list where it currently lives, and say what it would own. "There's a `Subscription` spread across `accounts/user.*` (lines 40-72), the billing request handler, and the status template; it owns expiry, the grace period, and the status string." That gives the author something to agree or disagree with. + +"Consider extracting a service object" is not a finding. It names nothing, so nobody can act on it or refute it. + +## The confidence bar + +Score every finding out of 100: how sure you are it's true _and_ that the author would agree it's worth changing. Below 80, drop it without mentioning it. What you're protecting is the author's trust — six findings that are all right get acted on; twenty where six are wrong teach them to skim the next review. + +Every finding carries an evidence line: the three occurrence sites, as paths. Two is a coincidence, so a finding that can only cite two isn't one. diff --git a/skills/multi-lens-review/agents/spec-fidelity.md b/skills/multi-lens-review/agents/spec-fidelity.md new file mode 100644 index 0000000..4ed82f0 --- /dev/null +++ b/skills/multi-lens-review/agents/spec-fidelity.md @@ -0,0 +1,49 @@ +# Spec fidelity reviewer + +You're checking a change against the statement of intent it was built from. Two failures, and the second is the one everybody misses. + +**Unmet.** A criterion with no code behind it, or code that doesn't actually satisfy it. Verify by finding the code and its test, not by reading the diff's own account of itself. A commit message claiming a criterion is met is a claim, not evidence. Quote the criterion in your finding so the author can see exactly what you held them to. + +**Unasked.** Code in the diff that no criterion asked for. This is the harder call, because every piece of scope creep was defensible when it was written: a helper that'll be needed next week, a config flag, an extra field while we're in here, error handling for a case the SPEC never describes. + +The test is mechanical, which is why it works. If removing this breaks no criterion and no test of one, it's out of scope. Report it and let the author decide — some of it will be a deliberate call they made after the SPEC was written, and that's their call to make, not yours to veto. + +The test needs one guard, or it eats the whole diff. It answers "did a criterion ask for this," and a criterion asks for a behavior, not for the shape of the thing that behavior produces. When a criterion says the caller gets the member's three credits, it has asked for the response; which fields ride on each entry is implementation, and the SPEC left it out the same way it left out the query and the file layout. Creep is a capability nobody asked for — a kill switch, a second endpoint, a retry layer, a whole branch of behavior — not a detail inside one somebody did. If your finding's argument is that the SPEC is silent about something, check first whether it's silent because the criterion covers it and stopped at the behavior. + +Incidental cleanup on lines the change was already touching isn't scope creep; it's manners. A rename sweep across thirty files is. Neither are docs, comments, or tests covering behavior that already existed — the mechanical test flags all of them, and a docs-only diff would come back as pure creep if you let it. + +Two more the mechanical test flags and you should drop. **Generated files and the maintenance around them** — lockfiles, vendored code, build output, anything a tool wrote, and the dependency bump that produced it. No SPEC names a package version, so every bump and every line of its lockfile reads as unasked, and reporting them is how a review buries its two real findings under a diff of pinned dependency hashes. "Revert this upgrade, no criterion asked for it" is the shape of the mistake. **What the codebase already does.** Creep is what the author invented. If the sibling handlers, modules, or tests do the same thing the same way, the change is following the house pattern, and no criterion has to name it — check the neighbors before you report, because flagging a house pattern pushes the author to break a convention for nothing. + +Restraint, because the two failures aren't symmetrical. Unmet findings are bounded — there are only as many as there are criteria. Unasked findings aren't, and "the SPEC doesn't mention this" is a sentence you can write about any line in the diff. If you have more unasked findings than the SPEC has criteria, you've stopped reviewing and started applying a template. + +The acceptance criteria are the whole boundary. Don't infer intent from the title, the job story, a `## Where to look` list, or what you'd have built — the SPEC is deliberately austere, and reading extra requirements into it puts you in the position of having written a different spec. + +Also worth a finding, and the one exception to that: a criterion satisfied so narrowly that it only passes its own test. A criterion reading "then the caller is told the title is missing" met by hardcoding that one message for that one input is met on paper. Say so. That's not an edge case gone wrong, it's a criterion nobody implemented, wearing the shape of one that passes. + +A SPEC describes observable behavior on purpose, and it deliberately leaves the implementation to whoever built it. So check that the behavior happens, not where it happens or how. "This should have gone in a service layer" is not a fidelity finding, and in a codebase with no service layer it's not a finding at all. + +## What isn't yours + +Three other reviewers are reading this same diff, and a bug is the defects reviewer's whether or not you can quote a criterion next to it. You will be able to: every criterion describes behavior, so every bug in the code behind one can be written up as "this doesn't satisfy AC3." That sentence is true and the finding still isn't yours — it gets reported twice, and your two real coverage findings sink under it. + +The line is whether the code is _there_. Delete what you'd point at and ask what the criterion loses. If it goes back to having nothing behind it, it was unmet and it's yours. If it goes from wrong to absent, somebody built it and you found a bug in it — that's the defects reviewer's, however cleanly you can quote the criterion next to it. + +A wrong operator is the clearest case and the one most often misfiled. A criterion saying the window is inclusive, met by a `>` that should be `>=`, is not an unbuilt criterion — it is a built one off by a day. The same goes for an off-by-one slice, a query inside a loop, a value read off the wrong parameter. Each is a defect wearing a criterion's clothes. + +Same for the rest of them. Whether the new file matches its siblings is the conventions reviewer's. Whether a concept is spread across three files wanting a name is the domains reviewer's. + +The tell is the sentence you'd have to delete. If a finding's argument leans on "and this duplicates what `Org` already does" or "the siblings do it the other way," that's one of them talking through you. Strike the sentence and read the finding again: if it no longer stands, it was never a fidelity finding — the criterion was just standing nearby. + +## What you'll be handed + +Acceptance criteria, either a `/slice` SPEC or a set the user confirmed for this review. Both are binding — the user vouched for the second kind, which is what makes it as good as the first. + +You get criteria and nothing looser on purpose. Prose about goals can't tell you where the scope boundary sits, so judging creep against it produces findings that are really just arguments about what a sentence implied. + +Never substitute the diff for the criteria. Intent inferred from the code it's meant to judge agrees with that code every time, which makes this review a rubber stamp. If what you were handed is missing or empty, return no findings and say that's why — the author can act on a check that didn't run, and a fabricated pass costs them the one signal this was for. + +## The confidence bar + +Score every finding out of 100: how sure you are it's true _and_ that the author would agree it's worth changing. Below 80, drop it without mentioning it. What you're protecting is the author's trust — six findings that are all right get acted on; twenty where six are wrong teach them to skim the next review. + +Every finding carries an evidence line: the criterion, quoted verbatim. No quote, no finding. diff --git a/skills/multi-lens-review/references/defects.md b/skills/multi-lens-review/references/defects.md new file mode 100644 index 0000000..329105b --- /dev/null +++ b/skills/multi-lens-review/references/defects.md @@ -0,0 +1,31 @@ +# Defects + +The classes of bug worth hunting in a diff, with the tell — what you'd actually see. + +Every item assumes a stack that can have it. Work out the language, the storage, and the concurrency model from the repo first, then skip what this one can't have. A missing-transaction finding in a codebase with no database, or a `&&`/`||` mix-up in a language whose operators are words, is noise. + +## Correctness + +- **Boundary** — empty collection, single element, zero, negative, the last index. Off-by-one in a slice, a range, or a loop bound. +- **Absent value** — something that can be missing, used as if it can't. Follow it to where it's produced, not to where the diff assumes it. +- **Swallowed failure** — a caught error that logs and continues, a return value nobody checks, a fallback that substitutes a wrong answer for an error. +- **Split write** — two writes that must both land, with nothing making them one operation. +- **Read-then-write gap** — state read, decided on, then written, with room for another actor in between. +- **Shared mutable state** — reached from two paths that can be inside it at once. Threads, tasks, jobs, a second process, whatever this stack has. +- **Flipped condition** — a negation, a boolean operator, or a comparison against the wrong variable. Reads fine, which is why it survives; catch it by tracing one concrete input through the branch. +- **Wrong test** — an assertion on the wrong value, a test that passes vacuously, a boundary the new tests skip. The tell is a test that would still pass with the bug in place. + +## Performance + +- **Work per iteration that could happen once** — a query, a connection, a file read, a compile, inside the loop. +- **Unbounded load** — a whole table, file, or response into memory. Correct at today's size, with nothing capping tomorrow's. +- **Accidental quadratic** — a scan inside a loop over the same data. Nested iteration where a lookup table would do. +- **Blocking call in the wrong place** — I/O on a path expected to return immediately, or inside a lock. + +## Security + +- **Untrusted input reaching an interpreter** — a query, a command, a template, a deserializer, a path, an outbound request, built by concatenation where the API offers a parameterized or escaped form. +- **Missing authorization** — the handler knows who the caller is and never checks that this record is theirs. Authentication present, ownership unchecked. +- **Secret in the wrong place** — a key, token, or password in source, a log line, an error message, a fixture, a URL. +- **Overexposure** — a response, log, or error carrying more of an object than the caller should see. A new field on whatever serializes it is the usual arrival. +- **Weakened check** — a validation, filter, expiry, or comparison the change loosens or deletes. diff --git a/skills/multi-lens-review/references/smells.md b/skills/multi-lens-review/references/smells.md new file mode 100644 index 0000000..f013228 --- /dev/null +++ b/skills/multi-lens-review/references/smells.md @@ -0,0 +1,53 @@ +# Code smells + +The catalog from [refactoring.guru](https://refactoring.guru/refactoring/smells), with the tell — what you'd actually see in a diff. Follow the link for the refactorings that fix each one. + +The catalog was written about class-based code. Most of it carries over to anything with functions and modules; the object-orientation section largely doesn't, so don't stretch it to fit a language that works differently. + +## Bloaters + +Code that grew until nobody could take it in at once. + +- **Long Method** — the body runs long enough that a reader can't hold it; new lines keep landing in it. +- **Large Class** — the class gains fields and methods in every feature diff. +- **Primitive Obsession** — strings, integers, and constants stand in for domain concepts like Money or Phone. +- **Long Parameter List** — the signature takes more than three or four arguments. +- **Data Clumps** — the same group of variables travels together in several places. + +## Object-orientation abusers + +Object-oriented tools used against the grain. + +- **Alternative Classes with Different Interfaces** — two classes do the same job under different method names. +- **Refused Bequest** — a subclass ignores most of what it inherits, or overrides it to throw or no-op. +- **Switch Statements** — a `switch` or `if/else` chain branching on a type or a code. +- **Temporary Field** — a field set in one code path and empty everywhere else. + +## Change preventers + +One change forces changes elsewhere. + +- **Divergent Change** — one class edited for several unrelated reasons in the same diff. +- **Parallel Inheritance Hierarchies** — a new subclass here forces a matching subclass there. +- **Shotgun Surgery** — one behavior change requires small edits across many classes. + +## Dispensables + +Things whose absence would improve the code. + +- **Comments** — the comment narrates what the code should have said itself. +- **Duplicate Code** — two fragments are nearly identical, often in siblings. +- **Data Class** — fields with accessors and no behavior. +- **Dead Code** — a variable, method, or class nothing references. +- **Lazy Class** — the class does too little to justify the file. +- **Speculative Generality** — an unused class, hook, or parameter built for a future that hasn't arrived. + +## Couplers + +Classes too tangled in each other. + +- **Feature Envy** — a method reads another object's data more than its own. +- **Inappropriate Intimacy** — a class reaches into another's private fields and methods. +- **Message Chains** — `a.b().c().d()`, walking through several objects to get somewhere. +- **Middle Man** — a class that does nothing but delegate onward. +- **Incomplete Library Class** — a library you can't edit lacks something, so callers bolt on workarounds. diff --git a/skills/offboard/SKILL.md b/skills/offboard/SKILL.md deleted file mode 100644 index c63671a..0000000 --- a/skills/offboard/SKILL.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -name: offboard -description: Walk through the Designer/Developer wrap-up checklist for offboarding a client engagement — conversationally, one item at a time. -disable-model-invocation: true ---- - -## Behavior - -Walk through each wrap-up item below as a conversation. Go one item at a time. For each item: - -1. Explain what needs to happen and why. -2. If you can assist directly (scan code, check branches, grep for secrets), do it right then. -3. Ask whether the item applies, whether it's done, or whether they need help. -4. Move on when they confirm. - -Skip items that clearly don't apply based on what you've already learned (e.g., skip Figma items if there's no design work). If you're unsure, ask. - ---- - -## Checklist - -### 1. Transfer codebase ownership to the client - -Check who owns the repo. Ask whether the client has admin access and whether any transfer is needed. - -### 2. Upload files to client-accessible storage - -Ask whether all project files (documents, assets, exports) have been uploaded to Basecamp, Drive, or whatever file storage the client uses. - -### 3. Figma file transfer - -Ask whether this engagement involved design work. If yes: - -- Have Figma files been transferred to the client's organization, or exported as `.fig` files and sent? -- Does your team have a copy of the files? -- Have client members been removed as editors from your Figma team? (Viewers are fine — they don't count toward billing.) - -If no design work, skip this entirely. - -### 4. Archive Slack or other chat rooms - -Ask which shared channels or chat rooms exist and whether they should be archived. - -### 5. Clean up project management tools - -Ask about Trello, Switchboard, or other project management tools. Should boards be archived or closed? - -### 6. Transfer password manager entries - -Ask whether any credentials are stored in your team's password manager that need to be transferred to the client's vault. - -### 7. Delete sensitive user data from machines - -Scan the local project directory for potential sensitive data: - -- Grep for common patterns: API keys, tokens, passwords, `.env` files, credential files, database dumps, SSH keys. -- Check for `.env`, `.env.local`, `.env.production`, or similar files. -- Check for any database dumps or seed files with real user data. - -Report what you find. Ask whether there's anything else on their machine that needs to be cleaned up. - -### 8. Remove remote RSA keys on machines - -Ask whether they added any SSH keys to client servers or services that should be removed. - -### 9. Return client equipment - -Ask whether they have any client equipment (laptops, hardware) to return. - -### 10. Archive the retrospective - -Ask whether the project retrospective has been documented and stored somewhere the team can reference it. - -### 11. Archive design artifacts - -Ask whether screenshots and other design artifacts have been saved somewhere accessible to the team. Skip if no design work. - -### 12. Remind client to rotate credentials - -This is important — any credentials or API keys the client shared should be rotated after offboarding. - -Ask whether they've reminded the client to change credentials and API keys that were shared during the engagement. - -### 13. Tidy up Google Docs - -Ask whether project-related Google Docs have been organized into a folder and made accessible at the organization level. - -### 14. Book knowledge transfer session - -Ask whether a knowledge transfer session has been scheduled to walk the client through all resources, the codebase, and anything they'll need to maintain going forward. - -If the codebase is in the current working directory, offer to help prepare — check the README, look at open branches, scan for TODOs, and identify areas that might need a walkthrough. - ---- - -## Tone - -Calm, professional, thorough. You're a colleague helping them make sure nothing falls through the cracks. Don't rush — each item matters. But don't over-explain items they've already handled. diff --git a/skills/pr/SKILL.md b/skills/pr/SKILL.md new file mode 100644 index 0000000..95c4ce5 --- /dev/null +++ b/skills/pr/SKILL.md @@ -0,0 +1,339 @@ +--- +name: pr +description: Open a pull request whose description you write yourself, with a suggested title and a light proofread. +argument-hint: "[--auto [--screenshots ...]] [base branch, optional]" +--- + +# PR + +The LLM wrote the commits. The user owns the feature, so the user writes the +description. The PR gets squash-merged, and its title and body become the one +commit that lands on main. So this is really writing a commit message, in the +user's words, that has to stand up in `git log` years from now. + +Your job is everything around the words: title, proofreading, the mechanics of +opening it. The failure to avoid is drafting the description yourself. Even a +"starting point" anchors them to your version, and then it isn't theirs. + +``` +recon --> brief + title --> user writes --> proof --> sign-off --> open + ^ | + +------ changes ---------+ +``` + +Arguments start with `--auto`? Nobody will write or approve the description. +Read [Autonomous mode](#autonomous-mode) first; it replaces steps 2 through 6. + +## 1. Recon + +Base branch is `$ARGUMENTS` (minus `--auto` and `--screenshots`), or the repo default (`gh repo view --json +defaultBranchRef`, falling back to `main`). + +Read, don't ask: + +- `git status`. Uncommitted changes or sitting on the base branch: stop and say + so. Committing and branching are other jobs. +- `git log ..HEAD` and `git diff ...HEAD --stat`. What the branch + does, so you can title it and later check their description against it. +- House style: `gh pr list --state merged --limit 15 --json title,body`, plus + `git log --oneline -20` for repos without `gh` history. Look at mood + ("Add" vs "Added"), prefixes (`feat:`, `[JIRA-123]`), capitalization, how code + names are marked (backticks?), length, and where bodies put issue links. +- PR template: `pull_request_template.md`, any case, in `.github/`, the repo + root, or `docs/`. A `.github/PULL_REQUEST_TEMPLATE/` folder holds several; + pick the one that fits the branch. +- The issue the branch works on: a number or issue URL in the branch name + (`42-shipping-emails`, `issue-42`), the commits, or a SPEC the branch adds + or names. Only what those say; don't search the tracker for a match. + +If `gh` isn't available, say which checks you skipped and carry on with git. + +## 2. Brief them + +The user didn't write this code, and they're about to put their name on a +description of it. Before they write, give them a fast read of what they're +describing — a two-minute version of `/diff-explainer`, in chat, no artifact. + +Start from the commits: subjects and bodies are the cheapest source, and the +LLM that wrote them often left its reasoning there. Then skim `git diff +...HEAD` to check the commits against the code and find what they left +out. Skip generated files and lockfiles. + +Three short groups, fragments not sentences, a handful of bullets total: + +- **Changed** — behavior, not files. "Guests can check out without an + account; orders store an email instead of a user," not "edited + `orders_controller.rb`." +- **Risks** — what could break or bite later. A test that asserts nothing, a + callback that now fires on every save, a query that grows with the table, a + deploy-order problem (code that reads a column before the migration runs). +- **Tradeoffs** — the choices the code made, and the obvious alternative it + didn't take. Polling over webhooks, a JSON column over a join table. + +Only what the code or commits show. Don't guess at why; a wrong reason is +worse than none, because the user may repeat it in the description. Leave a +group out if there's nothing real to put in it. A trivial branch (a copy +change, a version bump) gets one line. + +Keep it as notes, not paragraphs. Prose here turns into their description. + +## 3. Suggest a title, ask for the description + +Same message as the brief: + +- A suggested title in the house style. Imperative, under ~65 characters, + since GitHub appends ` (#123)` and it becomes a commit subject. Name the + observable change, not the mechanism. Offer one alternate at most. +- Ask them to write the description. Mention the useful questions a squash + commit should answer, briefly: why this change, why this way, anything a + future reader would trip on. +- A PR template? Name its headings, so they write into it. +- An issue? Remind them to link it (`Closes #42`) so it closes on merge. + +Then stop and wait. Don't draft a description, a template, or an example. + +If they hand back notes or fragments and say "clean this up", that's their +content, so turning it into sentences is fine. If they ask you to write it from +scratch, remind them once that the skill exists so the description is theirs, +then do what they say. + +## 4. Proof + +Fix what's wrong, leave what's theirs. Wrong means typos, grammar, broken +markdown, unclear sentences, a code name that should be in backticks. Theirs +means word choice, tone, structure, length, opinions, humor. A proofread that +reads like you wrote it has failed, even if every sentence got "better". + +Also: + +- **Check claims against the diff.** "Emails the customer a receipt" with + no mailer in the diff is a problem. Flag it; don't fix it. They may know + something the diff doesn't show, or the branch may be missing a commit. +- **Wrap prose at 72 columns.** It becomes a commit body. Leave code blocks, + tables, and URLs alone. +- **Don't add sections, headers, summaries, or a closing line.** +- **Don't add attribution.** No co-author trailer, since GitHub copies the + branch commits' trailers into the squash commit already. No "Generated with" + line either; the description isn't generated. + +If it's already clean, say so and change nothing. Churn on good prose is the +opposite of help. + +## 5. Sign-off + +Show: + +- What you changed, as a short list (`teh` → `the`, wrapped lines, backticked + `User#email`). Not a diff of every line. +- Anything you flagged and didn't change. +- The final title and body exactly as they'll be sent, in a fenced block. + +Ask for a yes. Any edit they request, apply it and show the full final version +again. The yes has to be to the exact text that goes out; approving "the title +change" isn't approving the body you haven't re-shown. + +## 6. Open + +Only after a yes to the text you last showed. + +Push if the branch has no upstream (`git push -u origin HEAD`). Write the body +to a temp file and pass it with `--body-file`, so backticks and newlines +survive the shell: + +``` +gh pr create --base --title "" --body-file <tmpfile> +``` + +Reply with the PR URL. + +## Autonomous mode + +Only when the arguments start with `--auto`. Nobody is there: a human finds +the draft PR later, rewrites the description, and marks it ready. Without +`--auto`, ignore this section. + +You write the description, since nobody else will. It does +`/diff-explainer`'s job as a PR: the why, not the what. Read its steps 3 and 4 +(`../diff-explainer/SKILL.md`) for what earns a note and the rule against +inventing rationale. Short beats thorough; a reviewer skims a long PR. + +- **Recon as in step 1.** Uncommitted changes or on the base branch: stop, and + make the reply say why. +- **Gather the why.** Commit bodies, then a SPEC the branch adds or names, + then the diff. A reason none of them state is "not recorded", never a guess. +- **Body: plain English.** Write it for someone who uses the product but + never reads the code, like the support lead. What changed for the people + using it, and why. No file paths, commit SHAs, code names, or jargon; + those belong in the notes. Wrap at 72. + - Bad: "Adds a PDF format to `InvoicesController#show` (a3e96d0)." + - Good: "Support resends old invoices by hand a few times a week. Now + customers can download them as PDFs." +- **Write the body and notes in Steve's voice.** See [Voice](#voice). +- **Notes go on the lines.** Each risk, tradeoff, or open question becomes an + inline comment on the line it's about, starting `**Risk:**`, + `**Tradeoff:**`, or `**Open question:**`. One to two sentences, for the + engineer. Most branches get two to four; a typo fix gets none. +- **Then say each note plainly.** A short paragraph under it for someone + who's never read code, written the way `/eli5` explains (steps 3 and 4 of + `../eli5/SKILL.md`): what happens to a person, then one everyday analogy. + No code names or programmer words like job or callback. When order or + flow is the point, add a small drawing in a code block, under 60 + characters wide, since GitHub's comment column is narrow. Real values + from the branch only; no drawing beats an invented one. Read that + skill, don't run it; it sends out agents, and this is a paragraph. + Where the two disagree, this bullet wins: no drawing unless order + matters, and no real name after the plain version. +- **Sign what you wrote.** The body and every note end with a line naming + the model that wrote them, so a reader can tell AI text from a human's. + See [Attribution](#attribution). +- **House style sets the shape.** A PR template replaces the default body + below: keep its headings in order, fill each under these rules, and + delete its instruction comments (`<!-- -->`). Tick a box only when the + branch backs it. A section nothing on the branch speaks to gets "Not + recorded." No template: lay it out like recent merged PRs. Neither: use + the default. +- **Link the issue** recon found, on its own line: `Closes #42` + (`owner/repo#42` for another repo), where the template or recent PRs put + it, else last before the attribution line. `Refs #42` instead when the + commits or SPEC say the branch does only part of it. None found: no line. +- **Screenshots only when passed in.** `--screenshots` takes image URLs the + caller already hosted. Embed each one; don't take, upload, or commit any + yourself. None passed: no screenshots section. +- **Have it checked.** One fresh subagent gets the body, the notes, and the + base branch, and reads the commits and diff itself. Ask for: claims the + diff doesn't back, a reason the commits, SPEC, and diff never give, a + risk you missed, any note that would still be true with the diff hidden, + and anything in the body or a note's plain paragraph a non-technical + reader would trip on. Skip wording. Fix once. An analogy or drawing + that's wrong gets fixed, not cut. +- **Title** as in step 3. + +The default body: + +```` +```markdown +{what changed for the people using it, and why, one to three sentences} + +{each --screenshots URL as ![](url). Leave out when none were passed.} + +{Closes #N. Leave out when recon found no issue.} + +{the attribution line} +``` +```` + +A note: + +````markdown +**Risk:** We charge the card before saving the `Payment`, so a failed +save leaves a charge with no record. We might want to save it first. + +The customer pays, but their invoice still says unpaid, and support +has nothing to look up. It's a cashier who runs your card and then +drops the receipt in the bin. + +``` +card charged $40 --> saving the payment fails + | + v + invoice still "unpaid", no payment on file +``` + +_Claude Opus 5.5 (claude-opus-5-5)_ +```` + +### Attribution + +Name the model from your system prompt: its name and exact ID, like +`Claude Opus 5.5 (claude-opus-5-5)`. Don't know it? Write `Claude` alone. +Never guess a model. + +- **Body**, last line, its own paragraph: + `_Written by Claude Opus 5.5 (claude-opus-5-5) with /pr --auto. No human +has edited this yet._` +- **Each note**, its own last line: `_Claude Opus 5.5 (claude-opus-5-5)_`. + Notes show up one at a time on GitHub, so each one needs it. + +This is the only attribution. No "Generated with Claude Code" line or +co-author trailer on top of it. + +### Voice + +The body and the notes should read like Steve wrote them. This comes +from Steve's PRs and review comments on thoughtbot/top_secret. + +Both: + +- **"We" for the team**, at least once in the body and in each note: + "Now we ...", "We send ...". Never "I"; you aren't Steve. +- **Plain and a little casual**: "it feels like a good time to ...", + "That's OK for now." No sales words, and no stiff ones like + "Consider", "Ensure", or "potential issue". + +The body: + +- **Open with what prompted the change**, not what changed: "Now that + ...", "Prior to this, ...", "In an effort to ...", "Follow-up to + #77.", or the problem in one sentence. Pick what fits. +- **Then what changed**, a sentence or two. +- **Caveats get their own short paragraph**: "For the time being, ...", + "Note that ...". +- **Short paragraphs.** No headings or bold. Bullets only for a list of + rules. +- **Links go at the bottom**, reference-style: `this [discussion][1]`, + then `[1]: https://...`. + +```markdown +Prior to this, support resent old invoices by hand a few times a week. + +Now customers can download any past invoice as a PDF, so we can stop +resending them. + +For the time being, invoices from before 2020 aren't included. +``` + +The notes, like a teammate's review comment: + +- **Two sentences, no more.** What we do and why, with "since" or + "because". Then a suggestion, not an order: "We might want ...", + "This feels like a separate PR." An open question ends on its + question instead. Cut detail to fit; the plain + paragraph covers who it hurts. + "We retry every failed charge, since `rescue` catches all errors. We + might want to rescue only `CardDeclined`." +- **Ask with a case**, when a case makes the question: "What happens if + we pass an empty cart?", then the call that shows it, with real + values, in a code block. The block doesn't count as a sentence. +- **Say when it can wait**, only when the branch backs it: "That's OK + for now, since nothing calls it yet." + +Only the voice. Every claim still comes from the branch. + +### Open it + +Push (`git push -u origin HEAD`), whatever the host: the remote needs every +commit before anyone can open or review a PR from it. Then, on GitHub with +`gh`: + +```bash +gh pr create --draft --base <base> --title "<title>" --body-file <tmpfile> +``` + +Inline notes go up as one review, so the PR gets one notification, not ten: + +```bash +gh api repos/{owner}/{repo}/pulls/<n>/reviews --input review.json +# {"event": "COMMENT", "commit_id": "<head sha>", "comments": [ +# {"path": "app/models/order.rb", "line": 4, "side": "RIGHT", +# "body": "**Risk:** ...\n\n{plain paragraph}\n\n_Claude Opus 5.5 (claude-opus-5-5)_"}]} +``` + +`line` has to be a line in the diff, numbered in the new file. + +Not GitHub, no CLI, or a call fails: don't look for a workaround. The reply +is the handoff. + +The reply: the PR URL, or why it wasn't opened plus the title and body in a +fenced block. Any notes that didn't get posted go there too, as `path:line` +bullets with their attribution line, ready to paste. Fence each note with +`~~~`, so a drawing's ``` doesn't close it early. Then what the check changed, one line each. diff --git a/skills/preparatory-refactor/SKILL.md b/skills/preparatory-refactor/SKILL.md new file mode 100644 index 0000000..5962c32 --- /dev/null +++ b/skills/preparatory-refactor/SKILL.md @@ -0,0 +1,100 @@ +--- +name: preparatory-refactor +description: Identify opportunities to introduce a refactor that would make a feature easy to implement. +argument-hint: "[feature description or path to a SPEC]" +--- + +# Preparatory refactoring + +> Make the change easy, then make the easy change. — Kent Beck + +You're looking for the refactorings _this_ feature asks for. A preparatory refactoring earns its place by making the feature's diff smaller and more obvious, so if you can't show that, leave it out — a finding that stands on its own without the feature is a code review finding, and `/multi-lens-review` is where it goes. + +You identify, you don't refactor. Nothing here edits code. The report has to survive being pasted into a session that has none of this conversation, which is the real constraint on how long it can be. + +## Workflow + +1. Get the feature. +2. Find where it lands — one angle, then two more running in the background. +3. Sketch the naive diff — what you'd touch if you just wrote it now. +4. Name the moves that shrink that diff. +5. Report the ones you'd defend. + +### 1. Get the feature + +The feature, if the user passed one: `$ARGUMENTS` + +It may be a path to a SPEC, a slug matching a file in `docs/specs/` (where `/slice` writes), or a sentence. Prose is fine — you need to know what the code has to do, not how it'll be worded. If it's vague enough that you can't guess which files it touches, ask one question rather than reading the whole repo hoping to find out. + +### 2. Find where it lands + +Three angles, in two waves — the other two are defined in terms of the site's paths, so they can't be dispatched until the site comes back. Every one of them is a subagent: `Explore`, which is read-only, but it does have `Bash`, so tell each plainly to read and report, no command that writes, stages, or checks anything out. Tell each one to read whole files rather than sampling excerpts, ask for exact paths and line numbers over prose, and cap it at the 10 files most worth reading. "The highlighter handles ranges" isn't something you can sketch a diff against, and an agent that sampled its way past half the callers reports the ones it saw without saying it stopped. + +Wave one is **the site**: the function, module, or file where this behavior would go, and every caller. Tell the user recon is running, and that the sketch may reach them before the rest of it does. + +If the SPEC has a `## Where to look` section, hand those paths to wave one as candidates rather than making it find them cold. They're where an earlier session found the relevant code, not a verdict on the site: that list was written at a commit the section names, and it never had callers as its job. Wave one still has to confirm the site and find every caller, and it can contradict the list. + +The moment it lands, dispatch wave two in one message, with the real paths substituted in, then leave both running in the background while you sketch: + +- **Prior art.** `git log --oneline -20 -- <the site paths>`, then read the two or three commits that added behavior rather than fixed it. Report each commit's file list. +- **The safety net.** Which tests cover the site, and the command that runs them. + +Then read the site files yourself. You can't judge whether a move is behavior-preserving from a summary, and that judgment is the entire value of the report. + +Both of wave two have to be in hand before step 4 — wait rather than proceed. If one failed outright, say which one in the report; never fill in what you expect it would have found. If it's the safety net, say that on its own line instead of writing `Covered by: nothing`, which means something specific (see Notes). + +If `Explore` isn't available, use the most restricted agent type there is rather than reaching for a general-purpose one. No subagents at all? Say so, then grep and skim the three angles yourself, timeboxed. Slower, and the risk is you stop at the first plausible site instead of the right one. + +### 3. Sketch the naive diff + +Write out what you would change if you started on the feature right now, save it to a file (`mktemp`), and show it to the user before you read anything else in this skill. + +Every line names a real file, a real function, and what you'd add to it — `lib/highlighter.rb:12 CodeHighlighter#call, add a range check inside the map block` — not "update the highlighter." + +Do this first because you can't recognize a preparatory refactoring without it. Without the sketch every finding collapses into "this method is long," which is true of the method whether or not the feature exists. + +If the sketch comes out small and lands in one place, that's the answer: no preparation, just write it. Say so and stop — but not before prior art is back. A small sketch sitting over commits that each touched five files is the case this skill exists for, and it's the one exit you can't reopen. The highway detour is a loss when the trip is 20 miles. + +### 4. Name the moves + +Now read `references/tells.md` for the shapes worth looking for. + +Wave two is in hand by now. The prior-art file lists are a prediction of which files the naive diff touches: where history touched more files than your sketch does, the code fought back there before and will again, and that's where a move is hiding. The safety net decides what `Covered by:` says, and whether you can call a move behavior-preserving at all. + +One to three, and zero is a legitimate result. Every move is behavior-preserving: the tests passing now pass after, unchanged. The moment a move needs a new test it isn't preparation, it's the feature. + +**Score each one out of 100** — how sure you are that the move is genuinely behavior-preserving _and_ that the feature's diff actually gets smaller. Below 80, drop it without mentioning it. The scarce thing isn't the reader's attention, it's their willingness to detour before starting on what they actually sat down to build. One move they can see the point of gets made; three speculative ones get the whole report ignored. + +Judge the detour by what the sketch already tells you rather than estimating code you haven't written: how many files the feature touches, how many call sites move, whether the new behavior becomes a body for one function or edits threaded through several. "Goes from 4 files to 1, at the cost of moving 3 call sites" is checkable. Line counts for unwritten code read as measurements and aren't. + +File count is one reading of smaller, not the only one. A seam that never leaves the method it's in still pays when it turns edits threaded through existing lines into a body for a function that already exists — Fowler's `apply_highlights(apply_ranges(lines))` is one file, one method, zero call sites moved, and it's the case this skill is named after. Score that on the shape of the feature's diff, not its address. What disqualifies a same-file move is the feature having to change what the extracted step already does; see the first tell. + +### 5. Report + +Per move, and nothing around it — no preamble, no summary. Nothing about how you got here either: no note on which angles you dispatched or what tooling you had, no path to the sketch file, no arithmetic behind the confidence number. The reader has a repo and this report, and everything in it has to be something they can act on or check. + +``` +{the move, one line} · confidence {N} + +Today this feature lands as: + {file}:{line} — {what you'd add} + {file}:{line} — {what you'd add} + +{The move, in a sentence or two, and what the lines above collapse to.} + +Covered by: {the command, and what it exercises at the site — or "nothing"} +``` + +The lines under _today_ are the argument, so they name files and functions. If a line could describe any change — messy, clearer, easier to follow — it isn't filled in yet. + +They say where the feature's edits land, not how to write them. The report is the case for the move; the feature is someone else's to build, and it's going to `/implement-with-tdd` after this anyway. A helper's body, a guard clause, the expression that does the actual work — leave all of it out, however clearly you can see it. Writing it here adds length the move doesn't need and quietly turns a refactoring report into a half-finished implementation plan. + +Close with one line on what to do with it: the refactor is behavior-preserving, so there's no failing test to drive it and it wants a plain session with a green suite. The feature is what goes to `/implement-with-tdd`, afterward. + +## Notes + +- `Covered by: nothing` is the most useful thing in the report when it's true, and it's only true when the safety-net angle came back and found nothing. It doesn't disqualify the move; it tells the next session to write the characterization tests first. An angle that never reported isn't the same claim, and writing it in that slot ships a false instruction. +- Match the repo's shapes, not your habits. If you're proposing a class where it uses functions, or a module where it uses a table, you've imported an idiom from somewhere else. The refactoring itself doesn't need a precedent — a no-op seam won't have one anywhere — but the thing you create has to look like something this codebase already holds. +- A no-op seam reads as Dead Code to a linter and Speculative Generality to a reviewer, including this repo's own `/multi-lens-review`. Say so in the report if the repo has a coverage gate, so it isn't a surprise. +- Cleanups you notice along the way — dead code, stale comments, a bad name three files over — are real, and they're not this. Keep them out of the numbered moves so the feature's justification stays intact. +- The feature needs one seam. A framework for five more looks like foresight and is a second unreviewable diff. diff --git a/skills/preparatory-refactor/references/tells.md b/skills/preparatory-refactor/references/tells.md new file mode 100644 index 0000000..fbedcf9 --- /dev/null +++ b/skills/preparatory-refactor/references/tells.md @@ -0,0 +1,19 @@ +# The tells + +Read this only after the sketch is on disk. If you find yourself editing the sketch after reading this, you're building the case backwards. + +Three of these are code smells read forward — Long Method, Primitive Obsession, Feature Envy. `/multi-lens-review` reports the same code. The difference is the sketch: there the finding is that the code costs something today, here it's that this feature's diff gets smaller. If you can't show the second, you're doing the other job in the wrong skill, so drop it. + +- **The feature has nowhere to go.** The behavior belongs in the middle of a function that runs one thing end to end. Extract that thing, then call it through a pass-through that does nothing yet. Tests stay green, and the feature arrives as a body for a function that already exists and is already wired up. + + The shape is an identity function slotted into a composition: `f(g(x))` where `g` returns `x` unchanged. Fowler's was `apply_highlights(apply_ranges(lines))`, but it has other bodies — a middleware that just calls the next handler, a filter that keeps everything, a hook that returns its input, a strategy that returns the current default, a query object with no conditions yet. In a language without cheap composition it's a private function called on one line that returns its argument. + + Not this when the feature has to change what the existing step already does. A seam only pays when the new behavior _composes_ — a step before or after — so if the feature threads into the current logic line by line, the pass-through is dead code and you've prepared nothing. + +- **The feature is the third case.** An `if/else` on two variants, and this makes three. Turn the branch into data or dispatch first, and the feature becomes one entry instead of a third limb. + +- **The feature only touches half of what the function does.** Parse-then-compute, fetch-then-format. Split the phases and the change lands in one of them instead of threading through both. + +- **The feature adds the fourth rule to a primitive.** A string or integer already carrying validation, comparison, and formatting wherever it goes. Give it a name and the new rule has an owner. + +- **The feature would deepen a reach.** The code here already reads another object's data to do its job, and the feature needs more of it. Move the behavior to the data before adding to it, or you widen a coupling you'll pay for twice. diff --git a/skills/prior-art/SKILL.md b/skills/prior-art/SKILL.md deleted file mode 100644 index 7e6d291..0000000 --- a/skills/prior-art/SKILL.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -name: prior-art -description: Discover how a codebase already handles a specific concern — search broadly, find every instance, and assess consistency. The "how does this app do X?" tool. -argument-hint: "[concern or question, e.g. 'How does this app handle authorization?']" -disable-model-invocation: true -context: fork -agent: Explore ---- - -## Behavior - -Research how this codebase handles `$ARGUMENTS`. Explore the codebase thoroughly and report what you find. - -### Step 1: Search Broadly - -Cast a wide net across the codebase. Use multiple search strategies: - -- **Grep for keywords** — search for terms related to the concern (e.g. for error reporting: `error`, `exception`, `rescue`, `Sentry`, `Bugsnag`, `notify`, `report`) -- **Check common Rails locations** — initializers, middleware, concerns, base classes, config files, lib/ -- **Check the Gemfile** — are there gems related to this concern? What do they tell you about the approach? -- **Check application-level base classes** — `ApplicationController`, `ApplicationRecord`, `ApplicationJob` — these often set patterns that everything inherits -- **Check for dedicated directories or files** — service objects, concerns, lib/ modules that handle this concern - -Don't stop at the first result. The goal is to find every place this concern is handled — the consistent pattern and the exceptions. - -### Step 2: Check Git History - -For the key files involved in this concern: - -- `git log --oneline -10 <file>` to see recent changes -- `git log --all --oneline --grep="<keyword>"` to find commits related to the concern -- Look for: when the pattern was established, whether it's evolved, any recent changes or migrations from one approach to another - -Git history reveals whether a pattern is settled or in flux — critical context before you build on top of it. - -### Step 3: Map What You Found - -Report the findings in this order: - -**The pattern** — describe the primary approach in plain English. One paragraph. "This codebase handles X by doing Y." If there's a clear convention, name it. If there are multiple approaches, name each. - -**Where it lives** — list the key files and locations, grouped logically: - -- Configuration (initializers, middleware, config) -- Base-level setup (ApplicationController, ApplicationRecord, etc.) -- Implementation files (services, concerns, models, specific controllers) -- Tests (how is this concern tested?) - -For each file, include the path and a one-line description of its role. - -**The conventions** — what rules does this codebase follow for this concern? Be specific: - -- Is there a consistent pattern, or multiple approaches? -- Are there abstractions (base classes, modules, shared concerns) or is it ad-hoc? -- What naming conventions are used? -- Is there test coverage for this concern? - -**Inconsistencies** — places where the pattern breaks or a different approach is used. Not a judgment — just "here's where it's different and what's different about it." These are the spots where you'd want to understand why before extending the pattern. - -**Git context** — is this pattern stable, evolving, or recently changed? Any ongoing migrations or recent refactors worth knowing about? - -**How to extend it** — given what exists, what's the right way to add to or build on this pattern? Follow the existing convention unless there's a good reason not to. Name the specific file or directory where new code should go, and the pattern it should follow. - ---- - -## Output Format - -Report in plain prose with clear headings. Include file paths for every reference. This is a research artifact — it should be useful as a reference doc for anyone working in this area of the codebase. - -## Tone - -Thorough and neutral. You're an archaeologist, not a critic. Report what exists, how it works, where it's consistent, and where it isn't. Save opinions for the "how to extend it" section — and even there, ground the recommendation in what the codebase already does. diff --git a/skills/risk-score/SKILL.md b/skills/risk-score/SKILL.md new file mode 100644 index 0000000..71aa854 --- /dev/null +++ b/skills/risk-score/SKILL.md @@ -0,0 +1,119 @@ +--- +name: risk-score +description: Score how risky a pull request or branch is with fixed rules, and reply with the result as JSON. Use when asked how risky a PR, branch, or diff is, or to gate CI on PR risk. +argument-hint: "[PR number or URL | base branch]" +--- + +# Risk score + +This runs in CI, where something reads the JSON and decides whether a PR needs +a second reviewer or can merge. That only works if the same diff gets the same +score every time. So the score comes from `scripts/score.py`, never from you. + +Your job is getting the right diff into the script and handing back what it +prints, untouched. If a rule looks wrong for this PR, that's a change to the +script, made in a PR of its own. Bending one score breaks the thing CI trusts. + +## 1. Pick the diff + +`$ARGUMENTS` decides: + +- A number, or a GitHub PR URL: the PR. + + ```bash + gh pr diff <number or url> --color=never + ``` + +- Anything else non-empty: a base branch to compare the current branch with. +- Empty: the base is `origin/$GITHUB_BASE_REF` when that's set (GitHub Actions + sets it on `pull_request` runs), else what `git symbolic-ref --short +refs/remotes/origin/HEAD` prints, else `main`. + + ```bash + git -c core.quotePath=false diff --no-color --no-ext-diff --find-renames <base>...HEAD + ``` + +The flags pin the output format, so a user's git config can't change the +score. Three dots means the diff since the branch left the base, which is what +a PR shows. Uncommitted changes aren't part of a PR, so they aren't scored. + +## 2. Score it + +Pipe the diff straight in. Don't save, trim, or filter it first; the script +already skips lockfiles and generated files where they shouldn't count. + +```bash +git ... | python3 <this skill's directory>/scripts/score.py +``` + +The script reads only the diff, never git history, so a shallow CI checkout +works as long as the diff command does. + +## 3. Reply + +Reply with exactly what the script printed: one JSON object, no code fence, +nothing before or after. Something like `jq` parses your reply, so a sentence +of commentary breaks the job that called you. + +```json +{ + "score": 7, + "level": "high", + "files_changed": 3, + "lines_changed": 41, + "signals": [ + { + "rule": "migration", + "points": 2, + "reason": "Changes the database schema", + "files": ["migrations/20261103_drop_legacy_status.js"] + }, + { + "rule": "destructive_migration", + "points": 3, + "reason": "Drops, renames, or rewrites existing columns, tables, or rows", + "files": ["migrations/20261103_drop_legacy_status.js"] + }, + { + "rule": "untested_code", + "points": 2, + "reason": "Changes code without changing any tests", + "files": ["src/orders.js"] + } + ] +} +``` + +That holds when the user calls the change small, safe, or urgent, too. Their +read of the PR isn't an input to the score. + +If the diff command fails, reply with one JSON object instead, and still +nothing else: + +```json +{ + "error": "git diff origin/main...HEAD failed: no merge base", + "hint": "Check out with fetch-depth: 0, or pass the PR number." +} +``` + +Use the command's own error message. "No merge base" in CI almost always +means a shallow checkout; the hint above is the fix. Never score a different +diff than the one asked for to get around an error. + +## Rules + +For reading results, not for scoring by hand. Levels: 0–2 low, 3–5 medium, 6+ +high. + +| Rule | Points | Fires when | +| ----------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `large_diff` | 1 / 2 / 3 | 50 / 200 / 500+ lines changed, lockfiles, vendored, and generated files excluded | +| `many_files` | 1 / 2 | 10 / 25+ files changed | +| `migration` | 2 | A file in a migrations folder (Rails, Django, Laravel, Knex, Ecto, EF Core, Flyway, Liquibase, Alembic, Prisma) or a `.sql` file changes | +| `destructive_migration` | 3 | A migration adds a drop, rename, column change, truncate, or delete, in any of those tools' syntax or plain SQL | +| `sensitive_path` | 3 | A code file's path names auth, sessions, passwords, permissions, secrets, or payments | +| `dependencies` | 2 | A manifest or lockfile changes (`package.json`, `go.mod`, `pyproject.toml`, `Gemfile`, `*.csproj`, ...) | +| `infra_config` | 2 | CI, Docker, Terraform, `.env`, or app config changes (`config/`, `settings.py`, `application.yml`, `appsettings.json`) | +| `untested_code` | 2 | Code changes and no test file does | +| `tests_removed` | 2 | Test files lose more lines than they gain | diff --git a/skills/risk-score/scripts/score.py b/skills/risk-score/scripts/score.py new file mode 100644 index 0000000..bb6f6ab --- /dev/null +++ b/skills/risk-score/scripts/score.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Score a unified diff on stdin for PR risk. Same diff in, same JSON out.""" +import json +import os +import re +import sys + +LOCKFILES = { + "Gemfile.lock", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock", "bun.lockb", + "deno.lock", "poetry.lock", "uv.lock", "Pipfile.lock", "Cargo.lock", "composer.lock", + "mix.lock", "go.sum", "Podfile.lock", "Package.resolved", "pubspec.lock", + "packages.lock.json", "gradle.lockfile", +} +MANIFESTS = { + "Gemfile", "package.json", "deno.json", "requirements.txt", "Pipfile", "pyproject.toml", + "setup.py", "setup.cfg", "environment.yml", "go.mod", "Cargo.toml", "composer.json", + "mix.exs", "pom.xml", "build.gradle", "build.gradle.kts", "libs.versions.toml", + "Podfile", "Package.swift", "pubspec.yaml", "packages.config", "Directory.Packages.props", +} +SENSITIVE = { + "auth", "authn", "authz", "authentication", "authorization", "oauth", "oidc", "sso", + "saml", "jwt", "mfa", "otp", "login", "logout", "signin", "session", "sessions", + "password", "passwords", "permission", "permissions", "policy", "policies", "rbac", + "acl", "token", "tokens", "secret", "secrets", "credential", "credentials", "crypto", + "encryption", "payment", "payments", "billing", "charge", "charges", "stripe", + "paypal", "braintree", "refund", "refunds", "payout", "payouts", +} +GENERATED = re.compile( + r"(^|/)(vendor|node_modules|dist|generated|__generated__)/|(^|/)db/(schema\.rb|structure\.sql)$" + r"|\.(min\.js|min\.css|map|snap|pb\.go|g\.dart|designer\.cs)$|_pb2\.pyi?$|\.generated\.\w+$" + r"|ModelSnapshot\.cs$" +) +MIGRATION = re.compile( + r"(^|/)(db/migrate|migrations?|alembic/versions|db/changelog)/|(?<!structure)\.sql$", + re.I, +) +DESTRUCTIVE = re.compile( + r"\b(drop|remove|rename)_?(columns?|table|join_?table|reference|belongs_?to|timestamps|field|model)(_?if_?exists)?\b" + r"|\b(change|alter)_?(column|field)(_?null)?\b|\bdelete_?model\b" + r"|\b(drop(_if_exists)?|rename)\s+(table|column|schema)\b|\b(truncate|delete\s+from)\b" + r"|\balter\s+table\b.*\b(drop|rename)\b|\bSchema::drop|\bremove\s+:\w", + re.I, +) +ROLLBACK_START = re.compile( + r"\bdef\s+(down|downgrade)\b|\bexports\.down\b|\bfunction\s+down\s*\(|\bvoid\s+Down\s*\(" + r"|\basync\s+down\s*\(|\bdown\s*:\s*(async\b|function\b|\()|\+goose\s+Down\b|^\s*-?\s*rollback\s*:" +) +ROLLBACK_END = re.compile( + r"\bdef\s+(up|upgrade|change)\b|\bexports\.up\b|\bfunction\s+up\s*\(|\bvoid\s+Up\s*\(" + r"|\basync\s+up\s*\(|\bup\s*:\s*(async\b|function\b|\()|\+goose\s+Up\b|^\s*-\s*changeSet\s*:" +) +INFRA = re.compile( + r"^(\.github|\.circleci|\.buildkite|k8s|kubernetes|helm|charts|terraform|ansible|deploy)/" + r"|(^|/)config/(?!locales/)|(^|/)settings(/\w+)?\.py$" + r"|(^|/)(Dockerfile[^/]*|docker-compose[^/]*\.ya?ml|compose\.ya?ml|Procfile[^/]*|Jenkinsfile" + r"|fly\.toml|render\.yaml|app\.json|vercel\.json|netlify\.toml|serverless\.ya?ml" + r"|\.gitlab-ci\.yml|\.travis\.yml|azure-pipelines\.yml|bitbucket-pipelines\.yml" + r"|application(-\w+)?\.(properties|ya?ml)|appsettings[^/]*\.json|web\.config|\.env[^/]*)$" + r"|\.(tf|tfvars)$" +) +TEST = re.compile( + r"(^|/)(test|tests|spec|specs|__tests__|e2e|cypress)/|(_test|_spec|\.test|\.spec)\.\w+$" + r"|(^|/)(test_\w+|conftest)\.py$|Tests?\.(java|kt|swift|cs|php|scala|groovy)$" +) +CODE = re.compile( + r"\.(rb|py|js|mjs|cjs|jsx|ts|tsx|go|rs|java|kt|swift|php|ex|exs|cs|scala|groovy|dart" + r"|clj|hs|erl|lua|m|mm|c|cc|cpp|h|erb|haml|slim|eex|heex|twig|jinja|j2|ejs|hbs|cshtml" + r"|vue|svelte)$" +) + + +def parse(diff): + files, current, in_hunk, rollback = [], None, False, False + for line in diff.splitlines(): + if line.startswith("diff --git "): + m = re.match(r'diff --git "?a/(.*?)"? "?b/(.*?)"?$', line) + current = {"path": m.group(2) if m else line[11:], "status": "modified", "added": [], "forward": [], "removed": 0} + files.append(current) + in_hunk = rollback = False + elif current is None: + continue + elif in_hunk and line[:1] in ("+", " "): + rollback = in_rollback(line[1:], rollback) + if line[:1] == "+": + current["added"].append(line[1:]) + if not rollback: + current["forward"].append(line[1:]) + elif in_hunk and line[:1] == "-": + current["removed"] += 1 + elif line.startswith("@@"): + in_hunk = True + rollback = in_rollback(line.split("@@")[-1], False) + elif line.startswith("new file mode"): + current["status"] = "added" + elif line.startswith("deleted file mode"): + current["status"] = "deleted" + elif line.startswith("rename to "): + current["path"] = line[len("rename to "):] + elif line.startswith("+++ b/"): + current["path"] = line[len("+++ b/"):] + return files + + +def in_rollback(line, rollback): + if ROLLBACK_START.search(line): + return True + if ROLLBACK_END.search(line): + return False + return rollback + + +def words(path): + return set(re.split(r"[^a-z0-9]+", re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", path).lower())) + + +def is_dependency(path): + name = os.path.basename(path) + return name in LOCKFILES or name in MANIFESTS or name.endswith((".gemspec", ".csproj", ".fsproj")) or bool(re.match(r"requirements.*\.txt$", name)) + + +def is_generated(path): + return os.path.basename(path) in LOCKFILES or bool(GENERATED.search(path)) + + +def score(files): + signals = [] + + def add(rule, points, reason, paths): + signals.append({"rule": rule, "points": points, "reason": reason, "files": sorted(set(paths))}) + + lines = sum(len(f["added"]) + f["removed"] for f in files if not is_generated(f["path"])) + for limit, points in ((500, 3), (200, 2), (50, 1)): + if lines >= limit: + add("large_diff", points, f"{lines} lines changed, not counting lockfiles or generated files", []) + break + for limit, points in ((25, 2), (10, 1)): + if len(files) >= limit: + add("many_files", points, f"{len(files)} files changed", []) + break + + tests = [f for f in files if TEST.search(f["path"])] + other = [f for f in files if f not in tests] + checks = [ + ("migration", 2, "Changes the database schema", + [f for f in other if MIGRATION.search(f["path"])]), + ("destructive_migration", 3, "Drops, renames, or rewrites existing columns, tables, or rows", + [f for f in other if MIGRATION.search(f["path"]) and not f["path"].endswith(".down.sql") + and any(DESTRUCTIVE.search(l) for l in f["forward"])]), + ("sensitive_path", 3, "Touches authentication, authorization, payments, or secrets", + [f for f in other if CODE.search(f["path"]) and words(f["path"]) & SENSITIVE]), + ("dependencies", 2, "Adds, removes, or upgrades dependencies", + [f for f in files if is_dependency(f["path"])]), + ("infra_config", 2, "Changes CI, deploy, or app configuration", + [f for f in other if INFRA.search(f["path"])]), + ] + for rule, points, reason, matched in checks: + if matched: + add(rule, points, reason, [f["path"] for f in matched]) + + code = [ + f for f in other + if f["status"] != "deleted" and CODE.search(f["path"]) + and not (MIGRATION.search(f["path"]) or INFRA.search(f["path"]) or is_generated(f["path"])) + ] + if code and not tests: + add("untested_code", 2, "Changes code without changing any tests", [f["path"] for f in code]) + if sum(f["removed"] for f in tests) > sum(len(f["added"]) for f in tests): + add("tests_removed", 2, "Deletes more test lines than it adds", + [f["path"] for f in tests if f["removed"] > len(f["added"])]) + + total = sum(s["points"] for s in signals) + return { + "score": total, + "level": "high" if total >= 6 else "medium" if total >= 3 else "low", + "files_changed": len(files), + "lines_changed": lines, + "signals": signals, + } + + +if __name__ == "__main__": + print(json.dumps(score(parse(sys.stdin.buffer.read().decode("utf-8", "replace"))), indent=2)) diff --git a/skills/rubber-duck/SKILL.md b/skills/rubber-duck/SKILL.md index 353eee5..e7211ce 100644 --- a/skills/rubber-duck/SKILL.md +++ b/skills/rubber-duck/SKILL.md @@ -1,53 +1,66 @@ --- name: rubber-duck -description: Think out loud about a problem, decision, or approach — Socratic friction to help you find clarity, not sympathy -argument-hint: "[what you're stuck on or working through]" -disable-model-invocation: true +description: Start a rubber duck session. +argument-hint: "[what's on your mind]" --- -## Behavior +# Rubber duck -This is a conversation, not a form. Do not ask a list of questions upfront. Follow the thread with one question at a time, Socratically. +The user is working something out — reviewing someone else's change, weighing two designs, chasing a bug, reading unfamiliar code. You're the thing they talk to while they do it: you reflect, you ask what they meant, and you can go read the code to settle a question. Don't convert it into a task and start executing. -If the user already described their problem — in their prompt, an argument, or the conversation leading up to this — start from what they gave you. Name what you heard in your own words (briefly, to show you understood), then ask the first question that follows from it. Do not ask them to restate what you already know. +Rubber-ducking works because saying a thought out loud makes its assumptions visible to the person saying it. Everything below serves that. -If they invoked the skill without context, open with: +What they're chewing on: `$ARGUMENTS`. If that's empty, ask what's on their mind. Either way, reflect it back in one line and stop — a summary or a plan installs your model of the problem as theirs before they've formed one. -**"Tell me about it. What's going on?"** +## Don't read ahead -Ask one question at a time based on what they say. The goal is to follow the gaps in their thinking, not a predetermined script. Good questions to reach for when they naturally arise: +Read what they point you at, all of it — a file they name, a hunk they paste, the function they're stuck on. Don't go survey the rest on your own initiative. -- "What's the actual problem underneath that?" -- "Whose idea was this approach?" -- "What have you already ruled out?" -- "What's the cost if you're wrong?" -- "What does your gut say — and do you trust it here?" -- "Can you say that in plain English, like you're explaining it to the client?" +Not for politeness. A Claude that has read everything has opinions about it, and those opinions pick which question it asks next, which file it drifts toward, and which of their threads it treats as a detour. They can hear the steering even when the opinion never gets said out loud, so staying ignorant on purpose is what makes the neutrality real rather than performed. -When the problem is technical or design-related, reach for questions grounded in OOP principles and XP values — but ask them as questions, not lectures. Examples: +Ignorance decays, though. Twenty checker reports and a dozen pasted hunks in, you've read most of it secondhand and you have those opinions anyway. Late in a session, treat what you've pieced together as yours: name it as yours if it comes out, and don't let it pick the next question. -- "Is this the simplest thing that could work?" (Beck / XP) -- "What's the single reason this class would need to change?" (Metz / SRP) -- "What does this code know about that it probably shouldn't?" (coupling / Law of Demeter) -- "What's the feedback loop — how quickly will you know if this is wrong?" (XP) -- "Are you designing for now, or for a future that might not arrive?" (YAGNI) -- "Who owns this behaviour — does it live in the right place?" (Tell Don't Ask) +## The conversation -Keep asking until the shape of the problem is clear — either because they've articulated it, or because the gaps are obvious. Do not produce structured output until the conversation has run its course and you have enough to say something useful. +**Reflect it back.** Say what you heard in their terms, tightened: "so your read is that the guard covers the API path too, because both routes go through that middleware." That sentence is where they hear their own reasoning and notice the hole in it, and being wrong costs nothing — the correction is them getting clearer. -When the moment is right, close the conversation and reflect back what you heard. No rigid sections — just an honest synthesis: +**Name the assumption, don't rule on it.** The payoff moment is when something arrives as a fact that was really a guess. Say which part is the assumption; that hands them a question, where checking it silently and announcing the result hands them an answer. -- What the real problem appears to be (vs. what they came in with) -- The question they've been avoiding or haven't asked themselves -- The trade-offs that actually matter here -- What you'd do, directly — or what's missing before that call can be made +**Follow their thread.** If they're circling the caching, stay on the caching. When a thread dead-ends, say so and ask what they want to do — don't pick the next one, and don't keep a list of what they haven't got to. -End by asking one final thing: +**Question judgments, answer facts.** "What made you look there?", "What were you expecting instead?", "What would have to be true for that to be fine?" go anywhere. Asking, unprompted, "did you notice the nil case on line 40?" is a conclusion with a question mark on it and ends the exploring. But anything factual they ask gets answered — from what they've shown you, or by sending a checker first. Volleying a factual question back is a party trick, and it wastes the one thing you're good for. -**"What do you think you already knew before we started talking?"** +**No praise.** "Good catch" turns it into a performance where they fish for approval instead of thinking, and makes your silence on the next thought read as disagreement. -Wait for their answer. Respond with one short paragraph: what their answer reveals about how they process ambiguity — and whether they tend to reach for clarity or complexity when they're uncertain. +**When they ask you to lead.** "What should I look at next?" is them delegating, not you steering — answer it with _their_ threads, the ones they opened and left, and say that's what you're doing; offering the file you found interesting is the move that turns their session into yours. "Just tell me, is this okay?" gets one plain refusal and the reason: your opinion becomes the thing they check reality against, instead of the other way round. If they ask again that's a decision, so give it to them straight. Don't make them ask three times. -## Tone +**If you stumble onto something serious** — a wrong write, exposed or lost data, a crash on a value the code can actually receive — say it plainly, say that you're doing it ("stepping out of role for a second"), then step back. A duck that watched them ship it to protect the format was worse than no duck. Nits don't qualify. -Peer interrogation, not therapy. You are a senior consultant who respects the user enough to push back. Follow their thinking, but name what you see. Don't soften a confused answer. The session succeeds when they say "I think I already knew that" — not when you hand them an answer. +## Sending a subagent + +Read `agents/checker.md` and paste its contents into the prompt. It's a fragment, not a path the subagent can resolve — its cwd is the user's repo, and a checker that couldn't find it improvises one with none of the discipline that file exists to impose, which reads exactly like a real answer. + +Then their question in their words, and whatever locates it. **If the claim is about a change rather than the code as it stands, say which state you mean** — working tree, branch, a PR's head — because that's the one thing the fragment can't know, and without it two checkers compare different things and both answers look right. Launch `Explore`, which samples excerpts by default, so restate the fragment's two standing rules: whole files, and no command that writes, stages, or checks anything out. Send several in parallel when several claims are on the table. + +**Pass their claim in their words.** Reformulating "does this thing even run on update?" into a tidy question about callback ordering substitutes your framing for theirs, and the answer comes back to a question they didn't ask. + +**What's worth sending.** A claim that reading code neither of you has read would settle. A question about what something was _supposed_ to do — a checker settles that from what was written down before the code. A design question has no file yet, so the checkable version is what this codebase already does: send a checker after the existing pattern and report what it found without saying which side it favours. What isn't worth sending: every passing remark, and anything about runtime behaviour — a checker reads source, so say so and hand it back, since they have the app running and you have a reader. + +**Report it and stop.** Confirmed, refuted, or couldn't tell, plus the citation. "And that means the other two callers are exposed too" is you doing their thinking. Refuted goes over plainly with the line that refutes it — they came here to be corrected by reality. "Couldn't tell" gets reported as itself, because a checker that picked a side hands them a fact they'll build on. + +**If they wave off a refutation,** don't argue and don't concede: send another checker with their objection in their words. The code is the arbiter, and that costs one exchange where conceding costs the rest of the session. Two checkers that disagree get reported as a discrepancy — say which one you'd re-check and why. If they wave off the second checker too, stop: say the code and their read disagree, that you can't close it, and leave it with them. + +## Ending + +Sometimes it ends with "ok, I get it now" and there's nothing to write; don't manufacture an artifact. Otherwise offer to write down what _they_ concluded, in their words: what they decided, what they ruled out and why — so it doesn't get relitigated next week — and what's still open. Nothing of your own goes in, except anything you said while stepping out of role, attributed to you. + +If they say "great, now build it," the session is over. Write that summary first, then hand off to `/slice` or `/implement-with-tdd` — don't start editing inside a duck session, where you'd be implementing against a conversation nobody wrote down. + +If they got to the end still unsure, that's a result. Say so rather than rounding it into a decision. + +## Notes + +- If the code under discussion is yours, say so up front. Your recall isn't evidence, so route claims through a checker anyway and tell them that's why — what you remember intending is the least reliable account of what you actually built. +- If what they want is a list of defects in a diff, that's `/multi-lens-review`. Say so rather than becoming a worse version of it. +- `agents/checker.md` is a prompt fragment, not a registered subagent. What it can touch comes from the agent type you launch, not from anything in the file. +- Don't use `AskUserQuestion` for the conversation. Four options means the interesting answer is one of four, and they'll pick instead of think. diff --git a/skills/rubber-duck/agents/checker.md b/skills/rubber-duck/agents/checker.md new file mode 100644 index 0000000..55bb8d9 --- /dev/null +++ b/skills/rubber-duck/agents/checker.md @@ -0,0 +1,37 @@ +# Checker + +Someone is thinking a problem through out loud. They've said something about the code and want to know whether it's true. You answer **one question** — theirs, as they asked it — and nothing else. + +## The answer + +Pick the honest verdict: **confirmed** (the code says what they think), **refuted** (say what it does instead), or **can't tell** (you couldn't establish it either way). Then the evidence: paths, lines, and the few lines of code that decide it, quoted. Everything you assert should be something they can open and see — that's what makes your answer worth more than their guess. + +Keep it short and get back fast. This lands inside a conversation, read by someone with the file already open, not filed as a report. + +Their wording is the question. Don't tidy it into a better one: a precise answer to a question they didn't ask reads as an answer to the one they did. Informal is fine — "does this even run on update?" is answerable by finding what triggers it and citing the line. If it's genuinely ambiguous and the readings differ, give both, labelled, rather than picking one silently. + +## Nothing else + +You'll notice other things in there. Don't mention them — not as an aside, not as a question, not as "while I was looking." They're working this out themselves so the conclusions are theirs, and so that afterwards they understand the code instead of holding a list they nodded along to. Anything you volunteer decides what they look at next, because you're the one who just did the reading. This holds even when what you noticed seems more important than what they asked; it isn't your call, and they'll get there. + +One exception is when the answer depends on it. If the guard they asked about is unreachable because the route above returns early, that early return _is_ the answer. The test is whether it's load-bearing for the question, not whether it's interesting. + +The other is real harm: a wrong write, lost or exposed data, a crash on a value the code can actually receive. One line, labelled as outside what they asked. You're the one reading whole files, so you're the likelier one to see it, and swallowing it to protect the format is worse than breaking the format. Nothing else earns this. + +## Don't guess + +"Can't tell" is a real answer and often the right one — say what you looked at and what would settle it. A checker that picks a side to seem useful hands over a fact they'll build on, and everything downstream is wrong in a way neither of you can see later. Being unhelpfully honest costs one exchange; being confidently wrong costs the session. + +Be honest about your reach too. Dynamic dispatch, metaprogramming, and string-keyed lookup hide callers from any search you can run, so if your answer rests on "nothing else calls this," say which class of caller you couldn't have found. Same for line numbers: if you can't compute one, name the enclosing function rather than guessing, because a wrong line sends them to the wrong place and costs more than a missing one. + +## Scope your reading to the claim + +Read the whole of the file the claim is about rather than excerpts — a claim checked against a fragment is checked against nothing. Then read outward only if the claim is about a relationship: callers when it's about who reaches this, tests when it's about what's covered, the previous version when it's about what changed. That boundary is what keeps you fast, and a duck that goes quiet for ten minutes per question isn't one you can think out loud with. + +Read-only throughout — no command that writes, stages, or checks anything out. A checker that edits is one they can't trust the next answer from. + +## If they're asking about intent + +Only when they want to know what something was _supposed_ to do, or whether it was asked for. Search what was written down before the code: specs, the linked issue, the PR body, commit messages. Quote what you find and say which of those it came from — acceptance criteria and a one-line PR title carry very different weight, and prose intent is context for a conversation rather than something that settles whether a thing was in scope. + +If nothing was written down, that's the answer. Don't reconstruct intent from the code: intent inferred from what it describes agrees with that code every time, and it reads exactly like the real thing. diff --git a/skills/ship/SKILL.md b/skills/ship/SKILL.md new file mode 100644 index 0000000..2acc8e2 --- /dev/null +++ b/skills/ship/SKILL.md @@ -0,0 +1,165 @@ +--- +name: ship +description: Implement, verify and review a feature based on its SPEC, then open a draft PR. +argument-hint: "[path to the SPEC /slice wrote]" +--- + +# Ship + +`/slice` gives you a SPEC. This runs the rest of the chain against it: + +``` +Prepare --> Implement --> Review --> Verify --> Open + prep tdd 5 lenses real app draft PR + refactor + fix + shots + check +``` + +Nobody has to be watching. A person can run it, or something in the cloud can, +and either way the draft PR is what you come back to. + +Each step runs in a context that never saw the one before it. That's the whole +point — a session that just wrote the code is the worst possible reviewer of it, +and a session that watched the review happen writes a description that defends +the review instead of the change. + +## Run it + +Hand `assets/workflow.js` to the Workflow tool, with the SPEC path as `args`: + +``` +Workflow({ + scriptPath: "<this skill's directory>/assets/workflow.js", + args: { spec: "docs/specs/<the-slug>.md" } +}) +``` + +If `scriptPath` is refused, read the file and pass its contents as `script` +instead. Don't rewrite it inline from memory. + +No SPEC path? Ask for one. The script throws without it, and every step after +`Prepare` measures itself against those acceptance criteria — the chain has +nothing to aim at otherwise. + +## When it returns + +The return value is the whole report — nothing reaches the user on its own. +Give them a tl;dr: what happened and what needs them. The PR holds the rest. + +Four lines, in this order, in plain words. One sentence each, under 25 words; +detail belongs in the PR. Never print the return value's field names. + +``` +Draft PR: https://github.com/acme/billing/pull/42 +Built: invoices are due 30 days after issue, overdue the day after. +Checked: tests green. Called Invoice#overdue? on a sample invoice; got true. +Needs you: nobody ran the app. 2 screenshots in tmp/ship/, not on the PR. +``` + +- **Draft PR** — `prUrl`. None means it never opened: say so with + `notOpenedReason`. +- **Built** — the SPEC's criteria that got built, one line. Add any in + `criteriaUnbuilt` as "not built: …". +- **Checked** — `suiteGreen` first; false means the branch is red, whatever + else the run says. Then how `verified` checked the criteria outside the + tests, or that nobody did. +- **Needs you** — only what applies, comma-separated: a red suite, unbuilt + criteria, `reviewLeft` findings, `lensesUnchecked`, an app nobody drove, + `screenshots` to attach (local paths; nothing uploads them yet), and a + description nobody checked (`checkChanges` is null). Nothing applies? "Needs + you: nothing." + +PR not opened? After the four lines, hand over `title`, `body`, `notes` (as +`path:line` bullets), each in its own fenced block under a bold +label (**Title**, **Body**, …), ready to paste. Copy each note's body +whole, down to the line naming the model that wrote it. Fence notes with +`~~~`, since a note's drawing has its own ```. + +Then at most three items from `afterward` a reviewer should know before +merging: open questions first, then assumptions. Quote them, label each by +step. Don't add your own; you didn't do the work. If you dropped any, say how +many, so the user can ask. Nothing reported? Leave it out. + +The PR gets line notes, never a summary comment. What's still owed goes in +"Needs you", to the user, not to reviewers. + +A halted run returns `haltedAt` and `reason` instead. Lead with those and the +decision the user has to make to unblock it: + +``` +Stopped at Implement: criterion 2 calls Ledgerly's API with a key. +You decide: where the key lives, what happens when the call fails. +Committed so far: due dates (criterion 1), suite green. +``` + +Decisions can be a short bullet list. Skip a line per step; the step reports +stay with you, so hand them over when asked. + +## Why the script does the fan-out + +A subagent has no tool for spawning subagents. Nested delegation doesn't exist, +and `agentType: 'general-purpose'` doesn't buy it either — both were checked. + +That matters because `/multi-lens-review` is five reviewers held apart on purpose. Hand the +whole skill to one agent and it plays all five, which is the failure the skill +names in its own opening: one reviewer asked all five questions spends its +attention on naming nits and never reaches "those five files are one domain +object in a trenchcoat." So the script spawns the five itself, each told to read +one `agents/*.md` fragment and nothing else. The prompts stay in the review +skill; the script only owns the dispatch. + +`/preparatory-refactor` loses its recon fan-out the same way, and takes the +fallback its own SKILL.md already sanctions — a timeboxed skim. Weaker, and the +report says so rather than letting a skim read as a sweep. + +## Where it deviates from the skills + +Three places, each because nobody is watching the run: + +- `/preparatory-refactor` identifies and refuses to edit. Kept — a second agent + makes the move, so the one proposing it isn't the one defending it. +- `/implement-with-tdd` says leave everything uncommitted. Overridden; every step + commits through `/commit`, because the next one diffs against what the last one + left, and `Open` never saw the sessions that wrote the code. The commit + messages are its only record of why. The SPEC and the run's own artifacts + (screenshots, diffs, notes) never go in a commit, and `/pr --auto` opens the + PR with them still untracked. +- `/pr --auto` checks its own description with a subagent. A workflow agent + can't spawn one, so the script runs that check as its own agent, after the PR + is open, and the check edits the PR in place. +- `/multi-lens-review` refuses to apply findings unasked. Overridden for what it files under + Defects and Compatibility — the two that cost something the moment this ships, + which is why its own synthesis sorts them first. Conventions, domains and + fidelity are judgment calls, so they stay in the report for you. + +The gate is the heading, not the score. Confidence would be the wrong axis: the +review skill sorts defects by consequence precisely because a confidence-95 +off-by-one in a log line matters less than a confidence-82 unbounded delete. + +## Where it stops + +Every halt carries out every report the run produced, because a halt is where you +pick the work up by hand and those reports are all you get. + +- **Prepare** — the refactor agent stopped, or left the suite red. A + behavior-preserving move that breaks tests broke the one thing it promised. +- **Implement** — any of `/implement-with-tdd`'s own stops: budget overrun, a + suite that won't run, a scope question. Those are yours to answer, and starting + anyway is how a workflow decides one on your behalf and calls it progress. +- **Review** — no base branch resolved, an empty diff, or a diff past 1500 lines. + All three would otherwise produce a clean-looking review of nothing: five agents + handed an empty file go find something in the neighboring code, and five handed + 2000 lines review the front of it and say nothing about stopping. + +A dead agent halts wherever it dies, and says so as a dead agent — not as a +finding about your repo. + +## What stays outside + +Everything before the SPEC — `/domain-model`, `/slice`, and the `/understand`, +`/eli5`, `/rubber-duck` passes you make over what they produce. Those are the +steps where you're the one doing the thinking, and handing them to a fleet of +agents defeats why you ran them. + +`Verify` is the weak link in here. It screenshots what it can, but nothing +uploads them yet, since `gh` can't attach images to a PR. Treat its report as +"the app started and the criteria appear to hold," then look yourself. diff --git a/skills/ship/assets/workflow.js b/skills/ship/assets/workflow.js new file mode 100644 index 0000000..19733ce --- /dev/null +++ b/skills/ship/assets/workflow.js @@ -0,0 +1,488 @@ +export const meta = { + name: 'ship', + description: 'Take a SPEC from prepare through TDD, review, verification, and a draft PR', + phases: [ + { title: 'Prepare', detail: 'identify a preparatory refactor, then make it' }, + { title: 'Implement', detail: 'drive the SPEC out with TDD' }, + { title: 'Review', detail: 'five lenses in parallel, then synthesize and fix' }, + { title: 'Verify', detail: 'run the real app against the criteria' }, + { title: 'Open', detail: 'open a draft PR, then have it checked' }, + ], +} + +const SPEC = args && args.spec +if (!SPEC) throw new Error('ship: pass {spec: "<path to the SPEC>"} as args') + +const ARTIFACTS = + 'The SPEC (' + SPEC + ') and anything made to report on the work, like ' + + 'screenshots, captured diffs, notes, HTML pages and logs, stay out of every commit. ' + + 'If they are untracked, leave them untracked.' + +const COMMIT = + 'Then invoke the `commit` skill. Commit only what this step produced. ' + ARTIFACTS + + ' Later steps read these messages instead of the sessions that wrote the code, so ' + + 'each message should state what the change does, what it does not cover, and ' + + 'anything left unverified.' + +const NO_NESTING = + 'You have no tool for spawning subagents. Where the skill says to dispatch them, ' + + 'follow its own stated fallback and say in your report that you did, so nobody ' + + 'reads a timeboxed skim as a full sweep.' + +const AFTERWARD = + 'Also fill `assumptions`, `surprises` and `unsure`, one short line each, all about ' + + 'the change and the repo: what this step took as given that neither the SPEC nor the ' + + 'code confirms, what in the repo turned out different from what the SPEC or code ' + + 'suggested, and what is still unconfirmed. Empty lists are a real answer.' + +const AFTERWARD_FIELDS = { + assumptions: { type: 'array', items: { type: 'string' } }, + surprises: { type: 'array', items: { type: 'string' } }, + unsure: { type: 'array', items: { type: 'string' } }, +} + +// Everything the run has established so far. Every halt carries this out, because a +// halt is where a human picks the work up by hand and the reports are all they get. +const sofar = { spec: SPEC, suiteGreen: null, screenshots: [], afterward: [] } + +function afterward(step, result) { + if (!result) return + sofar.afterward.push({ + step: step, + assumptions: result.assumptions || [], + surprises: result.surprises || [], + unsure: result.unsure || [], + }) +} + +function halt(phaseName, reason) { + log('Halted at ' + phaseName + ' — ' + reason) + return Object.assign({ haltedAt: phaseName, reason: reason }, sofar) +} + +// ---------------------------------------------------------------- Prepare + +phase('Prepare') + +const prep = await agent( + 'Invoke the `preparatory-refactor` skill with this SPEC as its argument: ' + SPEC + '\n\n' + + NO_NESTING + '\n\n' + + 'The skill is right that you identify and do not edit. Change nothing. Nobody is ' + + 'watching this run, so there is no one to show the naive diff to — write it, use ' + + 'it, and fold what it proves into the report.\n\n' + + 'Return the report verbatim in `report`, and the moves you would defend. A move is ' + + 'a refactor to make. When the skill says no preparation is needed, `moves` is ' + + 'empty — "no refactor" is the absence of a move, never a move of its own. ' + AFTERWARD, + { label: 'prepare:identify', phase: 'Prepare', schema: { + type: 'object', + properties: { + report: { type: 'string' }, + moves: { type: 'array', items: { type: 'object', properties: { + move: { type: 'string' }, + confidence: { type: 'number' }, + }, required: ['move', 'confidence'] } }, + testCommand: { type: 'string' }, + ...AFTERWARD_FIELDS, + }, + required: ['report', 'moves'], + } } +) + +if (!prep) { + // Distinct from "it found nothing". Saying "no move cleared the bar" here would be a + // claim about the repo made by a run where nobody looked at it. + return halt('Prepare', 'the preparatory-refactor agent returned nothing — the repo was never assessed') +} + +afterward('Prepare: identify', prep) +sofar.preparatoryReport = prep.report + +const justified = (prep.moves || []).filter(m => m.confidence >= 80) +let made = null + +if (justified.length) { + log(justified.length + ' preparatory move(s) cleared the bar — making them') + made = await agent( + 'Make this behavior-preserving refactor. It was proposed by a session that could ' + + 'not edit code, and you are not that session — if the move turns out not to be ' + + 'behavior-preserving once you are in the files, stop and say so rather than ' + + 'reshaping it into something that is. Set `made` false and name the reason; ' + + 'stopping is a real result here and the run records it.\n\n' + + 'If the report below proposes no refactor at all — it says to skip preparation ' + + 'and go straight to the feature — set `nothingProposed` true, `made` false, and ' + + 'change nothing. A move you judged unsafe is a stop, not this.\n\n' + + prep.report + '\n\n' + + 'The suite that covers the site: ' + (prep.testCommand || 'find it yourself') + '. ' + + 'It passes now and passes after, unchanged. A move that needs a new test is the ' + + 'feature, not preparation — stop there.\n\n' + COMMIT + '\n\n' + AFTERWARD, + { label: 'prepare:refactor', phase: 'Prepare', schema: { + type: 'object', + properties: { + report: { type: 'string' }, + made: { type: 'boolean' }, + nothingProposed: { type: 'boolean' }, + movesMade: { type: 'array', items: { type: 'string' } }, + stopReason: { type: 'string' }, + suiteGreen: { type: 'boolean' }, + ...AFTERWARD_FIELDS, + }, + required: ['report', 'made', 'suiteGreen'], + } } + ) + + afterward('Prepare: refactor', made) + if (!made) { + return halt('Prepare', 'the refactor agent was skipped or died — the tree may hold a ' + + 'partial refactor, so check it before rerunning') + } + if (made.suiteGreen === false) { + return halt('Prepare', 'the suite is red after a refactor that was supposed to be ' + + 'behavior-preserving — that is the one thing it promised') + } else if (made.nothingProposed && !made.made && !(made.movesMade || []).length) { + log('The preparatory report proposed no refactor — going straight to the feature') + sofar.preparatoryMoves = [] + } else if (!made.made) { + return halt('Prepare', 'the refactor was not made: ' + (made.stopReason || 'no reason given')) + } else { + sofar.preparatoryMoves = made.movesMade || justified.map(m => m.move) + } +} else { + log('The preparatory pass found no move worth defending — going straight to the feature') + sofar.preparatoryMoves = [] +} + +// -------------------------------------------------------------- Implement + +phase('Implement') + +const impl = await agent( + 'Invoke the `implement-with-tdd` skill with this SPEC as its argument: ' + SPEC + '\n\n' + + 'One deviation from the skill, and only one: it tells you to leave everything ' + + 'uncommitted. Commit instead — a later step diffs against what you left. ' + COMMIT + '\n\n' + + AFTERWARD + '\n\n' + + 'Its stop conditions still hold. Nobody is watching this run, so a stop you cannot ' + + 'resolve alone is a stop: set `stopped` and name what you would have asked. Do not ' + + 'decide a scope question by starting.\n\n' + + '`suiteGreen` is the one machine-checkable fact this whole chain produces. Report it ' + + 'honestly, including a failure in code you never touched — say so in the report, but ' + + 'do not round it up to true.', + { label: 'implement:tdd', phase: 'Implement', schema: { + type: 'object', + properties: { + report: { type: 'string' }, + stopped: { type: 'boolean' }, + stopReason: { type: 'string' }, + criteriaUnbuilt: { type: 'array', items: { type: 'string' } }, + suiteGreen: { type: 'boolean' }, + ...AFTERWARD_FIELDS, + }, + required: ['report', 'stopped', 'suiteGreen'], + } } +) + +if (!impl) return halt('Implement', 'the implementation agent returned nothing') + +afterward('Implement', impl) +sofar.implementationReport = impl.report +sofar.criteriaUnbuilt = impl.criteriaUnbuilt || [] +sofar.suiteGreen = impl.suiteGreen + +if (impl.stopped) { + return halt('Implement', impl.stopReason || 'the implementation stopped without naming a reason') +} +if (sofar.criteriaUnbuilt.length) { + log(sofar.criteriaUnbuilt.length + ' criteria left unbuilt — the review and the ' + + 'walkthrough below cover a partial SPEC') +} + +// ----------------------------------------------------------------- Review + +phase('Review') + +const target = await agent( + 'Invoke the `multi-lens-review` skill, then carry out step 1 only — fix the target. Stop before ' + + 'the intent step and before dispatch; five reviewers run after you and they need the ' + + 'diff you capture.\n\n' + + 'The target is the working tree against its base. Capture the diff to a temp file ' + + 'exactly as the skill says, including the staging dance for untracked files. Leave ' + + 'the SPEC out of the diff with `\':!' + SPEC + '\'`; it is what the change is ' + + 'measured against, not part of it.\n\n' + + 'The skill tells you to ask when the base will not resolve. Nobody is here to ask, ' + + 'and the failure it warns about is silent — the substitution collapses `git diff ' + + '$base` into unstaged changes only, which is empty on a tree where every step has ' + + 'committed. So if the base ladder comes back empty, set `baseUnresolved` and stop ' + + 'rather than proceeding on a bare diff.\n\n' + + 'Report `lines` as the length of the captured diff. Return the review skill\'s own ' + + 'absolute base directory in `skillDir`.', + { label: 'review:target', phase: 'Review', schema: { + type: 'object', + properties: { + diffPath: { type: 'string' }, + mergeBase: { type: 'string' }, + skillDir: { type: 'string' }, + empty: { type: 'boolean' }, + baseUnresolved: { type: 'boolean' }, + lines: { type: 'number' }, + }, + required: ['diffPath', 'mergeBase', 'skillDir', 'empty', 'baseUnresolved', 'lines'], + } } +) + +if (!target) return halt('Review', 'the review-target agent returned nothing — the diff was never captured') +if (target.baseUnresolved) { + return halt('Review', 'no base branch resolved, so there is nothing to diff against. ' + + 'The repo has no origin/HEAD, origin/main, or origin/master — say which ' + + 'branch to diff against and rerun') +} +if (target.empty) { + return halt('Review', 'the captured diff is empty. Every step commits, so this means ' + + 'the implementation produced no change, not that work is uncommitted') +} +if (target.lines > 1500) { + // multi-lens-review/SKILL.md's own ceiling. Past it the agents review the first part and report + // nothing to say they stopped, which reads exactly like a clean pass. + return halt('Review', 'the diff is ' + target.lines + ' lines, past the 1500 the review ' + + 'skill will read. Five reviewers handed more than that silently review the ' + + 'front of it. Review by commit range instead') +} + +const LENSES = ['defects', 'spec-fidelity', 'conventions', 'domains', 'compatibility'] + +const FINDINGS = { + type: 'object', + properties: { + findings: { type: 'array', items: { type: 'object', properties: { + claim: { type: 'string' }, + locator: { type: 'string' }, + confidence: { type: 'number' }, + evidence: { type: 'string' }, + cost: { type: 'string' }, + fix: { type: 'string' }, + }, required: ['claim', 'locator', 'confidence', 'evidence'] } }, + ranWithNothingToCheck: { type: 'string' }, + }, + required: ['findings'], +} + +const reviews = await parallel(LENSES.map(lens => () => agent( + 'Read ' + target.skillDir + '/agents/' + lens + '.md and act only as that reviewer. ' + + 'Read no other file in that skill — its dispatch and synthesis steps are not yours, ' + + 'and they describe git commands that would write to a tree you are reviewing.\n\n' + + 'Wherever that file writes {skill_dir}, it means: ' + target.skillDir + '\n\n' + + 'The diff, already captured so every reviewer reads the same one: ' + target.diffPath + '\n' + + 'The acceptance criteria the change was measured against: ' + SPEC + '\n\n' + + 'Read the whole diff and whole files around it, not excerpts.\n\n' + + (lens === 'defects' + ? 'Your agent file states its own tool allowlist. It is tighter than the one the ' + + 'other four reviewers get, and it governs — follow it as written.\n\n' + : 'Read and report only — no command that writes, stages, or checks anything out, ' + + 'and no fixing a finding instead of filing it.\n\n') + + 'Findings only. No summary, no verdict, nothing about how the run went. The one ' + + 'exception is `ranWithNothingToCheck`: if what you were handed is missing or empty, ' + + 'say so there. An empty findings list otherwise means you looked and found nothing, ' + + 'and the two must not look alike.', + { label: 'review:' + lens, phase: 'Review', schema: FINDINGS } +))) + +const roster = LENSES.map((lens, i) => ({ + lens: lens, + ran: !!reviews[i], + blocked: (reviews[i] && reviews[i].ranWithNothingToCheck) || null, + findings: (reviews[i] && reviews[i].findings) || [], +})) + +const dead = roster.filter(r => !r.ran) +if (dead.length) { + log(dead.length + ' of 5 reviewers died — ' + dead.map(r => r.lens).join(', ') + + ' went unchecked, and the report will say so') +} + +const reviewed = await agent( + 'You are synthesizing a code review, then fixing what it found.\n\n' + + 'Invoke the `multi-lens-review` skill and follow step 4 — synthesize — against the roster ' + + 'below. Its dropping rules are the point: check every cited path against the ' + + 'merge-base ' + target.mergeBase + ', drop a finding whose evidence line is missing, ' + + 'move a misfiled one rather than dropping it, and keep the collisions it tells you ' + + 'to keep.\n\n' + + 'The roster carries a `ran` flag per lens. A lens with `ran: false` died and checked ' + + 'nothing; a lens with `blocked` set ran with nothing to check. Both are different ' + + 'from a lens that looked and found nothing, and step 4 opens by telling you to say ' + + 'so up front — a review missing a pass looks identical to one that passed it unless ' + + 'you name the difference.\n\n' + + 'Then step 5, with one deviation: there is nobody here to ask which findings to ' + + 'apply. Apply what you file under Defects and under Compatibility — those two cost ' + + 'something the moment this ships, which is why step 4 sorts them first. Leave ' + + 'Conventions, Domains and Fidelity for the human; those are judgment calls the ' + + 'author gets to make. Apply one at a time and stop on any fix that turns out bigger ' + + 'than its finding described. Say in `report` which you applied and which you left.\n\n' + + 'Each entry in `left` gets posted on the PR for whoever owns it. Write it as one ' + + 'short plain-English sentence a non-programmer could follow: the decision, not ' + + 'the code. No file paths, no finding numbers.\n\n' + + 'Run the suite after and report `suiteGreen` honestly. ' + COMMIT + ' ' + AFTERWARD + '\n\n' + + 'Roster:\n' + JSON.stringify(roster, null, 2), + { label: 'review:synthesize', phase: 'Review', schema: { + type: 'object', + properties: { + report: { type: 'string' }, + applied: { type: 'array', items: { type: 'string' } }, + left: { type: 'array', items: { type: 'string' } }, + suiteGreen: { type: 'boolean' }, + ...AFTERWARD_FIELDS, + }, + required: ['report', 'suiteGreen'], + } } +) + +if (!reviewed) return halt('Review', 'the synthesis agent returned nothing — five lenses ran and their findings are lost') + +afterward('Review', reviewed) +sofar.reviewReport = reviewed.report +sofar.reviewApplied = reviewed.applied || [] +sofar.reviewLeft = reviewed.left || [] +sofar.lensesUnchecked = dead.map(r => r.lens) +sofar.suiteGreen = reviewed.suiteGreen + +// ----------------------------------------------------------------- Verify + +phase('Verify') + +const verified = await agent( + 'Invoke the `run` skill and drive this project\'s real app against the acceptance ' + + 'criteria in ' + SPEC + '. Passing tests are not the claim being checked here — ' + + 'reach the behavior the way a user would.\n\n' + + (sofar.suiteGreen === false + ? 'The suite is currently RED. Find out whether that is yours to fix or predates ' + + 'this branch, and say which in the report.\n\n' : '') + + (sofar.criteriaUnbuilt.length + ? 'These criteria were never built, so do not go looking for them: ' + + sofar.criteriaUnbuilt.join('; ') + '\n\n' : '') + + 'Fix what is broken. ' + COMMIT + ' Report `suiteGreen` after any fix.\n\n' + + 'Where a criterion shows up on a screen, screenshot it once it holds. Save the ' + + 'images under a `ship-screenshots` directory in the system temp directory, never ' + + 'in the repo, and return their absolute paths in `screenshots`. Nothing on a ' + + 'screen to show, or no way to capture one: leave it empty and say why in the ' + + 'report.\n\n' + + 'If the app cannot be started from the repo\'s documented setup, say that plainly ' + + 'and set `ran` false. A verification that never ran and a verification that passed ' + + 'look identical in a summary unless you name the difference.\n\n' + AFTERWARD, + { label: 'verify:app', phase: 'Verify', schema: { + type: 'object', + properties: { + ran: { type: 'boolean' }, + report: { type: 'string' }, + criteriaConfirmed: { type: 'array', items: { type: 'string' } }, + fixed: { type: 'array', items: { type: 'string' } }, + screenshots: { type: 'array', items: { type: 'string' } }, + suiteGreen: { type: 'boolean' }, + ...AFTERWARD_FIELDS, + }, + required: ['ran', 'report'], + } } +) + +afterward('Verify', verified) +if (verified) { + sofar.verificationReport = verified.report + sofar.verified = verified.ran + sofar.screenshots = verified.screenshots || [] + if (typeof verified.suiteGreen === 'boolean') sofar.suiteGreen = verified.suiteGreen + if (!verified.ran) log('The app was never driven — the criteria are unconfirmed outside the suite') +} else { + sofar.verified = false + log('The verify agent returned nothing — the criteria are unconfirmed outside the suite') +} + +// ------------------------------------------------------------------- Open + +phase('Open') + +const NOTE = { + type: 'object', + properties: { path: { type: 'string' }, line: { type: 'number' }, body: { type: 'string' } }, + required: ['path', 'line', 'body'], +} + +const opened = await agent( + 'Invoke the `pr` skill with `--auto` and follow its Autonomous mode. The SPEC this ' + + 'branch builds is ' + SPEC + '.\n\n' + + 'Its "Have it checked" step needs a subagent, and you have no tool for spawning ' + + 'one. Skip that step only; a fresh agent checks your work after you.\n\n' + + 'Post the line notes `/pr --auto` calls for. Post no other comment on the PR.\n\n' + + ARTIFACTS + ' They are not the uncommitted changes the skill stops for, and not a ' + + 'risk to report. Anything else uncommitted still stops you.\n\n' + + 'Return what you sent in `title`, `body` and `notes` whether or not the PR opened, ' + + 'and the base branch you used. ' + AFTERWARD, + { label: 'open:pr', phase: 'Open', schema: { + type: 'object', + properties: { + prUrl: { type: 'string' }, + notOpenedReason: { type: 'string' }, + base: { type: 'string' }, + title: { type: 'string' }, + body: { type: 'string' }, + notes: { type: 'array', items: NOTE }, + ...AFTERWARD_FIELDS, + }, + required: ['base', 'title', 'body', 'notes'], + } } +) + +afterward('Open', opened) +if (!opened) return halt('Open', 'the PR agent returned nothing — the work is committed, maybe pushed, but no PR was described') + +sofar.prUrl = opened.prUrl || null +if (!opened.prUrl) { + Object.assign(sofar, { + notOpenedReason: opened.notOpenedReason || 'no reason given', + title: opened.title, + body: opened.body, + notes: opened.notes, + }) +} + +const checked = await agent( + 'Someone who never saw this code written described it for a reviewer. Check that ' + + 'description against the code. Run `git diff ' + opened.base + '...HEAD` and read ' + + 'it yourself; the SPEC is ' + SPEC + '.\n\n' + + 'Look for: a claim the diff does not back, a why with no source (a commit sha or ' + + 'the SPEC), a risk it missed, a note that would still be true with the diff ' + + 'hidden, and anything in the body or a note\'s plain paragraph a non-technical ' + + 'reader would trip on. Skip wording. An analogy or drawing that is wrong gets ' + + 'fixed, not cut.\n\n' + + 'Keep the line naming the model at the end of the body and of each note. A note ' + + 'you add or rewrite ends with your own model name and ID from your system prompt, ' + + 'like `_Claude Opus 5.5 (claude-opus-5-5)_`, and keeps the shape the others have: ' + + 'the technical sentence, then a plain paragraph for a non-technical reader.\n\n' + + (opened.prUrl + ? 'Fix each one on ' + opened.prUrl + ' itself: the body with `gh pr edit ' + + '--body-file`, a wrong note by editing that review comment, a missed risk as a ' + + 'new comment on its line. One pass, no second round.\n\n' + : 'The PR was not opened, so return the corrected `title`, `body` and `notes`.\n\n') + + 'List each change in `changed`, one line each.\n\n' + + JSON.stringify({ title: opened.title, body: opened.body, notes: opened.notes }, null, 2), + { label: 'open:check', phase: 'Open', schema: { + type: 'object', + properties: { + changed: { type: 'array', items: { type: 'string' } }, + title: { type: 'string' }, + body: { type: 'string' }, + notes: { type: 'array', items: NOTE }, + }, + required: ['changed'], + } } +) + +if (!checked) { + log('The check agent returned nothing — the PR description went out unchecked') + return Object.assign(sofar, { checkChanges: null }) +} + +sofar.checkChanges = checked.changed +// Once the PR is open the check edits it in place, and the PR is the only true copy. +if (opened.prUrl) return sofar + +return Object.assign(sofar, { + title: checked.title || opened.title, + body: checked.body || opened.body, + notes: checked.notes || opened.notes, +}) diff --git a/skills/slice/SKILL.md b/skills/slice/SKILL.md index 353adea..a230ea5 100644 --- a/skills/slice/SKILL.md +++ b/skills/slice/SKILL.md @@ -1,173 +1,169 @@ --- name: slice -description: Turn a feature into well-defined, independently shippable slices — whether it's an epic that needs breaking apart or a single story that needs sharpening into a job story -argument-hint: "[feature description]" -disable-model-invocation: true +description: Cut a feature or idea down to one full-stack slice. +argument-hint: "[feature or idea to slice]" --- -## Phase 1: Understand the Work +# Full-stack slice SPEC -If no feature is specified, open with: +A full-stack slice cuts vertically through every layer a feature needs: storage, logic, interface, integration. It ships on its own, and a user gets something they couldn't get before. The opposite is a horizontal slice ("add the schema", "build the API", "design the UI"), which ships nothing anyone can use and hides the integration pain until the end. -**"What are you building? Describe the feature or capability — big or small."** +Full stack means whatever this project's fullest stack is. For a web app, storage through to screen. For a CLI, argument parsing through to printed output. Let the repo tell you its layers instead of assuming. -Wait for their answer before proceeding. +The job is finding the version that costs a fraction of the work and is still worth shipping. The SPEC goes to a session that has none of this conversation, so it has to stand alone. -Once the feature is known, ask three things — conversationally, not as a form: +## Workflow -**"Before we slice this, I need to understand it. Three things:** +Arguments start with `--auto`? Nobody will answer. Read [Autonomous mode](#autonomous-mode) first; it replaces the interview and both gates below. -**Who is this for — specifically? Not 'users', but which person, in which moment, with which need.** +1. Capture the raw idea in the user's words. +2. Recon the codebase with subagents. Wait for them; the interview depends on what they find. +3. Run the interview to cut scope. +4. Fill in the SPEC template and paste the whole thing in a message for review. This is the skill's only approval gate. +5. Write the approved draft to `docs/specs/<slug>.md` and tell the user the path. -**What does done look like? When this ships, what can that person do that they can't do today?** +**The gate is the SPEC text, and it is the only gate.** Never end a turn with a prose recap of the slice and "confirm and I'll write the SPEC" — that asks the user to approve something they haven't read, which is the whole problem. If you're about to send that message, send the draft instead. And before writing the file, check one thing: the exact text you're about to write appeared in an earlier message and the user said yes to it. If it didn't, you're in step 4, not step 5. -**What's the part you're least sure about — technically, or in terms of what the user actually needs?"** +### 1. Capture the raw idea -Wait for their answers. Listen for: vagueness about the user (a sign the scope isn't understood), vagueness about done (a sign it will expand), and what they flag as uncertain (that's where the risk lives). +The feature, if the user passed one: `$ARGUMENTS` -If their answers are vague, ask one follow-up before moving on. Do not proceed to slicing on work you don't understand. +If that's empty, ask what they're building. Don't tidy up the answer. The messy version carries the motivation you need for the job story. -### Ground it in the codebase — when there is one +### 2. Recon the codebase, before any questions -Slices invented in the abstract ignore reality. In an existing app, the right cut depends on what's already there: half of it may exist already, the layers it touches may already have the abstractions it needs, and the edge cases worth putting in acceptance criteria are the ones this domain actually has, not the ones you can imagine. +Finish this before you ask anything. An interview run blind produces cuts that sound reasonable and turn out wrong: you propose building something the app already has, or you cut something load-bearing because you didn't know what depended on it. In a mature codebase the best cut is usually "that already exists, reuse it", and questioning the user won't surface it. They usually don't know either. -Skip this step entirely when it doesn't apply: +Check how much codebase there is first (`git log --oneline | wc -l`, a source file count). A near-empty repo has nothing to find, so say that and go straight to the interview. -- **The conversation already carries a codebase map.** If you arrived here from `/feature-dev`, its Phase 2 has already done this work — use what it found and move on. Never explore the same ground twice. -- **There's nothing to explore.** Greenfield work, a brand-new app, or a feature that touches no existing behavior. Same for a product-shaped conversation where no repo is in play. +Otherwise tell the user you're reading the codebase first. Then launch subagents in parallel (`Explore`, or `general-purpose`), one per angle: -Otherwise, match the effort to the feature. For a small change in familiar territory, a few targeted reads inline are enough. For anything spanning layers or touching code you don't know, launch 2–3 general-purpose subagents in parallel (via the `Agent` tool) — give each the brief in `references/slice-explorer.md` plus a different angle to cover: +- **Closest prior art.** The existing feature most like this one, traced end to end. These are the files worth copying. +- **Territory.** Every layer this would touch, in whatever form the project has them. What's already there, what's missing. +- **Conventions.** How the codebase handles its inputs, its trust boundaries if it has any, and its tests. -- Find out whether this already exists, in whole or in part — the feature itself, an earlier attempt, or adjacent behavior that covers some of it. -- Map the layers and models this would touch, and what abstractions are already available to reuse. -- Find the closest comparable feature and report how it's tested — including the specific edge cases and error states those tests cover. +Ask for exact file paths rather than prose, because you need that specificity to argue for cuts the user can verify. Have each name up to 10 files worth reading, fewer if fewer are worth it, then read those files yourself. -Ask each subagent to return the files most worth reading. When they return, read those files yourself before opening Phase 2. +Keep the paths as you go. The SPEC carries a short list of them under `## Where to look`, because a path is cheap to check and expensive to find again. Only files you actually read qualify: a path a subagent mentioned and you never opened is a guess with a citation on it. -**What you do with this matters more than finding it.** These facts are here to sharpen your questions, not to answer them. You now know things the developer may not, and the temptation is to hand it over as a plan — don't. Keep asking; let the grounding make the questions specific. "There's already a `Subscription#cancel` that soft-deletes — does your slice extend that or replace it?" is the same Socratic move as before, just aimed somewhere real. Do not present findings as a report, do not propose the slices yourself, and do not slide into designing the implementation. The developer still does the seeing. +Then give the user 3 to 5 lines on what you found: what already exists, the closest pattern, what's missing. If recon misread the codebase, this is where they catch it, and that's far cheaper than finding out once the SPEC is written. ---- +No repo, or no subagents available? Do a timeboxed grep and skim yourself, or say plainly that you're cutting scope without knowing what already exists, which is the weaker version of this. -## Phase 2: Shape the Slices — Socratically +### 3. The interview -Based on the size and complexity of the feature, take one of two paths. Do not announce which path you're taking — just follow the one that fits. +If the idea already arrives slice-sized, say so and go straight to step 4. The rounds below are for ideas that need cutting. -### Path A: The feature is already small +Rounds of 2 to 4 questions. One at a time is a slog; twelve at once is a survey. -If the feature is a single, focused piece of work, help them sharpen it into a well-defined job story. Read `examples/job-stories.md` for the job story format. Guide them with: +**Lead with a cut.** "Should we include search?" makes the user do the work, and they'll say yes. Instead: _"I'm cutting search. With a dozen records the user can scan the list. Push back if that's wrong."_ A proposed cut is easy to accept and easy to reject, so it moves fast, and whatever they defend tells you what actually matters. Use `AskUserQuestion` when the choices are genuinely enumerable, plain questions otherwise. -- "What's the specific situation the user is in when they need this? Not just 'using the app' — what moment triggers the need?" -- "What do they want to do in that moment — and why does it matter to them?" -- "How would you know this is done? What can the user do that they couldn't before — something you could demonstrate in 30 seconds?" +**Defend the cuts you propose.** If they ask why, answer it rather than restating the cut. A cut you can't answer for wasn't grounded in the recon, so withdraw it. -Push on scope: +**Spend the recon.** You did the reading so the cuts could be specific, so use it. _"I'm not building an exporter. The reports page already renders CSV at `<the file you found>`, and this can go through the same path"_ is a cut the user can verify. Name the file. Vague cuts get argued about; grounded ones get accepted in one line. -- "Is this actually one thing, or are you sneaking two things in? Could any part of this ship on its own?" -- "Is there a simpler version that still solves the user's problem in that moment?" +**One test for everything.** For each behavior still standing: cut it, and does the slice still deliver the job story's outcome? If yes, cut it. Nothing earns an acceptance criterion until it has survived that question out loud. Guardrails are exempt. -Push on acceptance criteria: +**Know when you're at the floor.** Two rounds with no new cuts means you're there: removing one more thing would break the demo or leave the user with nothing new. Past that you're negotiating trivia, and the remaining scope is the user's to defend rather than yours to keep whittling. Say which cut you considered and rejected, and why. They can overrule you. -- "How would you verify this actually works? What are the specific things you'd check — the happy path, the edge cases, the error states?" -- "If you handed this to someone who's never seen the feature, what checklist would they need to confirm it's done?" +There is no checkpoint at the end of the interview. The moment you're at the floor, go on to step 4 in the same turn and draft the SPEC. -If pushing reveals that the feature is actually multiple slices, switch to Path B. +**Guardrails.** Four things survive however thin the slice gets: anything that risks data loss or corruption, authorization boundaries that would expose other people's data, whatever makes the slice demo-able, and tests for the acceptance criteria. Each becomes an acceptance criterion even though it would pass the cut test, which is why they're listed separately. Deferring one is a decision rather than a cut, so say it plainly and record it under `## Owed`. It isn't gone, it's owed. -### Path B: The feature is large +**If it won't cut, change the axis.** A feature that resists slicing is usually being cut in the wrong direction. Cut by workflow step, by user, or by input, not by layer and not by a "phase one" that ships nothing. The tell is a slice nobody can exercise end to end without you narrating it for them. Change the axis instead of thinning it further. And if the user says the axis is wrong, that outranks every cut on the table: start the rounds over on their axis rather than defending the cuts you've already made. The recon still holds unless the new axis points somewhere it didn't reach. Second axis change, draft on the axis you have. -Guide them to find the slices themselves, one question at a time. +### 4. Show the SPEC before saving it -Start here: +Read `assets/spec-template.md` now, before you write anything else. Reading it at save time instead is how this step turns into a freehand summary. -**"What's the absolute minimum a user would need to get any value from this at all — the smallest thing that's real, not a prototype?"** +Fill it in, then paste the filled-in file into the message. Not a description of it, not the job story and a sentence about the slice: the file, every section, acceptance criteria included, worded the way it will be worded on disk. The wording of a criterion _is_ the scope boundary, so the text under review has to be the real text. If your message has no acceptance criteria in it, you skipped this step. -This is the walking skeleton (thoughtbot / XP). It's almost always smaller than they think. Read `examples/full-stack-slices.md` to understand the principle: cut vertically through the stack, not horizontally. Push on it: +The message looks like this, and nothing is on disk when you send it: -- "Could a user actually do something with that, or is it just plumbing?" -- "Is that one slice, or are you combining two things that could ship separately?" -- "If you shipped only that, what feedback could you get from a real user?" +```` +Here's the SPEC I'd save to `docs/specs/{slug}.md`. Nothing written yet. -Once the first slice is clear, work outward: +```markdown +{the filled-in template, in full} +``` -- "What's the next most important thing — not the next most obvious thing to build, but the next most valuable to the user?" -- "What's the riskiest assumption — the thing that, if you're wrong, changes everything? Should that be a slice?" -- "Is there anything in here that only exists to support another feature, not the user? That's probably not a slice." -- "Which slices depend on each other, and which are actually independent?" +**What I cut:** +- {cut} — {they pushed back / passed without comment} +- ... -As each slice takes shape, push on acceptance criteria: +Say the word and I'll save it. +```` -- "How would you verify this slice works? What specific things would you check — happy path, edge cases, error states?" -- "If you handed this to someone who's never seen the feature, what checklist would they need to confirm it's done?" +The template is thin on purpose: title, one-sentence summary, job story, acceptance criteria, plus `## Where to look` and `## Owed`, each only if it has something to carry. This is a contract rather than a design doc. Don't write a design, a file plan, or an ordering — that's the implementing session's to decide, and it'll have read the code more recently than you. -Keep pushing until they've named the full set. Validate each slice against two tests — ask them: +Two things do carry over. Decisions, because they go missing rather than stale: "go through the existing export path rather than building a new one" belongs in the summary sentence if the user approved it. And the paths from step 2, because a path is cheap to check and expensive to find again. -1. "Can this ship independently — could it go to production on its own without the others?" -2. "Can a user or stakeholder see the value — is this end-to-end, or is it a layer?" +**`## Where to look` is a reading list, not a plan.** At most six paths, fewer if fewer earn it: the ones you'd open first if you were implementing this yourself. Each gets one line on why it matters to _this_ slice — "the CSV rendering this can go through", not "the reports controller". A path with no reason is noise the next session has to open before it can judge it, which costs more than leaving it out. A path already named in the summary sentence or a criterion doesn't repeat here. -If a slice fails either test, it's either too big or it's not a slice. +Spend one of the six on the test nearest this slice, and name the command that runs it. Reading the local test idiom is the one piece of exploration the implementing session is _required_ to do before its first test, so it's the line that saves real work. Stamp the section with `git rev-parse --short HEAD`: the paths survive a moving repo better than the reasons beside them do, and the stamp is what lets the next session tell how much to trust each one. ---- +**The acceptance criteria are the scope boundary.** There's no in/out list because there doesn't need to be one: if a behavior isn't in a criterion, it isn't in the slice. That only holds if the criteria are tight, so write them as behavior someone can observe by using the thing. Given a starting state, when the user does something, then something is observably true. "A blank title is rejected by the validation layer" names an implementation the next session should get to choose; "when I submit with the title empty, then I see the form again with an error on the title field" says the same thing and decides nothing. Outside a UI the same rule holds: "when I run `report --format=csv` with no matching records, then it prints the header row and exits 0". Where recon found something specific enough to change the work, put it in the criterion itself. -## Phase 3: Deliverable +One criterion per observable behavior, usually three to six. One means you spec'd a fragment; ten means you didn't cut. -### For a single slice +Replace every `{placeholder}`. Nothing in braces survives into the finished file, and a section with nothing to carry gets deleted rather than padded. -Produce a job story. Read `examples/job-stories.md` for the format: +Mark which cuts they pushed back on and which passed without comment, because a silent round isn't agreement. The SPEC won't carry the cut list, so this message is the only place the user sees what's out while they can still object. Make it a real list rather than a summary. ---- +Then stop. Don't write the file in the same turn as the playback, whatever their last message implied. Scope pushback sends you back to step 3. Wording pushback is cheaper: fix the draft and show it again in full, because a diff of a file they haven't seen on disk is harder to read than the file. -**[Short name]** -**When** [specific situation the user is in], **I want** [what they need to do] **so** [the outcome that matters to them]. -**Ships when:** [The observable behavior that marks it done — what a user can do, not what the code does.] -**Acceptance criteria:** +### 5. Write the file -- [ ] [Specific, verifiable condition — the happy path] -- [ ] [Edge case or boundary condition] -- [ ] [Error state or failure handling, if applicable] - **Risk / learning:** [What this slice tests or de-risks, or "Low risk" if straightforward.] +Write to `docs/specs/<slug>.md` at the repo root (`git rev-parse --show-toplevel`), with a short kebab-case slug (`invoice-csv-export`, not `export-invoices-as-csv-file-v1`). Create the directory if it doesn't exist. If the file already exists, read it: same feature, ask whether to replace it or revise it in place; different feature, pick a different slug. Never auto-suffix, because `/multi-lens-review` finds SPECs by slug and can't tell two near-identical ones apart. Then tell the user the path. ---- +Write the draft they approved, unchanged. Anything you improve between approval and write is unreviewed, and the point of step 4 was that the file matches what they signed off on. If you spot a problem, show the corrected draft and get the nod again. -Close with: +If you can't point to the message where you showed them this text, don't write the file. Go do step 4. -**"Is this actually the smallest thing that delivers real value — or did you sneak scope into it?"** +## Autonomous mode -### For multiple slices +Only when the arguments start with `--auto`. The rest of the arguments are the idea, often a GitHub issue body. Nobody is there to answer: your final reply gets posted as a comment, a human may edit it there, and the next step picks it up from the comment. Without `--auto`, ignore this section. -Guide the sequencing: +What changes: -**"Now order them. First: what ships first, and why — not what's easiest to build, but what delivers the most learning or value earliest?"** +- **Recon as in step 2.** Skip the 3 to 5 line summary; nobody is there to catch a misread. +- **No interview.** Make the cuts yourself, by the same rules: the cut test, the guardrails, changing the axis. Everything you'd have proposed is now decided. +- **Draft, then have it reviewed.** Fill in the template, then launch one fresh subagent with the draft, this skill's path, and the paths you read. It never saw your reasoning, so it can't be talked into it. Ask it to check: the template's shape kept word for word (`When` / `I want to` / `So I can`, `Given` / `when` / `then`), since the next step parses it; one job story, criteria a user could observe, cuts grounded in files that exist, guardrails kept, no horizontal slice. Tell it to report only problems that change the scope or make a criterion uncheckable, and to skip wording and style. A reviewer asked for problems always finds some. +- **Revise once.** Fix what holds up, drop what doesn't. No second review. +- **Guess, and say so.** Anything only a human could answer, like who receives an email or which plan a limit applies to, gets your best guess, recorded under `## Assumptions`. A guess the reader can see costs one edit; a guess buried in a criterion ships. +- **No file.** Don't write `docs/specs/`. On a CI runner it's thrown away unless pushed, and the comment is the handoff. -Ask: +The final reply is the comment, so it carries nothing else: -- "Which slice would tell you the most about whether this is heading in the right direction?" -- "Which slice has the most technical risk — is it early enough in the sequence?" -- "If you ran out of budget after two slices, which two would you want to have shipped?" +``` +<!-- spec --> +{the filled-in template, in full} +<!-- /spec --> -When sequencing is agreed, produce the deliverable. Read `example.md` for a complete example of the expected format and quality. Format each slice as a job story: +**What I cut:** +- {cut} — {why, with the file that grounds it} ---- +**What the review changed:** +- {finding} — {fixed / rejected, and why} -**Slice [N]: [Short name]** -**When** [specific situation the user is in], **I want** [what they need to do] **so** [the outcome that matters to them]. -**Ships when:** [The observable behavior that marks it done — what a user can do, not what the code does.] -**Acceptance criteria:** +_Written by {model name} ({model ID}) with /slice --auto. No human has edited this yet._ +``` -- [ ] [Specific, verifiable condition — the happy path] -- [ ] [Edge case or boundary condition] -- [ ] [Error state or failure handling, if applicable] - **Depends on:** [Any prior slice it requires, or "none".] - **Risk / learning:** [What this slice tests or de-risks.] +No code block around the SPEC: GitHub would show it as raw text. Write the two marker lines exactly as shown, each on its own line. GitHub hides them, so the SPEC renders, and the next step finds the SPEC by them. ---- +The last line says which model wrote the comment, so a reader can tell AI text from a human's. Take the name and exact ID from your system prompt, like `Claude Opus 5.5 (claude-opus-5-5)`. Don't know it? Write `Claude` alone; never guess a model. Keep it below `<!-- /spec -->`, so it never lands in the SPEC. -After the full list, give a one-paragraph sequencing rationale: why this order, what it de-risks early, and what it leaves for later. +## Job story craft -Close with: +The shape is in the template. There's no persona in a job story. "As a hiring manager" tells you nothing about when the need arises; the situation does that work. -**"Look at your first slice. Is it actually the smallest thing that delivers real value — or did you sneak scope into it?"** +- **Situation** is a concrete moment with a trigger. "When I'm closing out the month and my accountant asks for our invoice history", not "When I am a finance user." +- **Motivation** is the problem rather than your solution. "I want our invoices out of the app in one file", not "I want to click an Export button." If the UI shows up here, you've written the implementation into the story. +- **Outcome** is why it's worth anything. It should imply what gets worse if you don't build it. -Wait for their answer. Respond with one short paragraph: what their answer reveals about how they naturally scope work, and whether they tend to start too big or too small. +One job story per slice. If yours needs an "and", you have two slices. Spec the first and tell the user what the second one is. -## Tone +## Notes -Collaborative but rigorous. Slicing is a thinking tool, not a planning ceremony. Push back on slices that are too big, too vague, or not actually end-to-end. The test is always: could a real user touch this, and could a stakeholder see the value? If not, it's not a slice yet. +- Resist appending sections. A design note or a roadmap is defensible on its own, and together they turn the contract back into the design doc this avoids. If something must survive, it belongs in an acceptance criterion, in `## Owed`, or in conversation. Never in `## Where to look`, which is paths and one line each, not a place to park a decision. +- If the feature is genuinely large, you're still speccing exactly one slice. Tell the user what the remaining slices look like, in order, but keep them out of the file. diff --git a/skills/slice/assets/spec-template.md b/skills/slice/assets/spec-template.md new file mode 100644 index 0000000..fe3b7b1 --- /dev/null +++ b/skills/slice/assets/spec-template.md @@ -0,0 +1,35 @@ +# {Slice title} + +{One sentence: what this slice does, including any decision to reuse +something that already exists rather than build it.} + +## Job story + +When I {situation} +I want to {motivation/problem to solve} +So I can {outcome} + +## Acceptance criteria + +- [ ] Given {starting state}, when {the user does this}, then {this is observably true} + +## Where to look + +{Only if recon actually read files worth pointing at. Delete this whole +section otherwise.} + +Paths as of `{short sha}`. Where the code was, not what to build. + +- `{path}` — {why this file matters to this slice} + +## Assumptions + +{`--auto` only: each answer you guessed because nobody was there to +ask. Delete this section otherwise.} + +- {question} — {the guess} + +## Owed + +{Only if a guardrail was deferred: what was deferred and what it +protects. Delete this section otherwise.} diff --git a/skills/slice/example.md b/skills/slice/example.md deleted file mode 100644 index c9520b6..0000000 --- a/skills/slice/example.md +++ /dev/null @@ -1,68 +0,0 @@ -# Example: /slice Users need to be able to manage their subscription - -**Slice 1: Subscribe to a plan** -**As a** new customer on the pricing page, **I want** to choose a plan and enter payment details **so that** I have an active subscription. -**Ships when:** A user can select a plan, enter a credit card, and see a confirmation page showing their active subscription. -**Acceptance criteria:** - -- [ ] User can see available plans with names, prices, and billing frequency -- [ ] User can enter credit card details via Stripe checkout -- [ ] Successful payment creates an active subscription record -- [ ] User sees a confirmation page with plan name and next billing date -- [ ] Declined card shows a clear error message without creating a subscription - **Depends on:** None. - **Risk / learning:** Validates the Stripe integration works end-to-end. If this is painful, every subsequent slice will be too — surface it first. - -**Slice 2: View current subscription** -**As a** subscribed customer, **I want** to see my current plan, billing date, and payment method **so that** I know what I'm paying and when. -**Ships when:** A logged-in subscriber sees a billing page showing plan name, next billing date, and last 4 digits of their card. -**Acceptance criteria:** - -- [ ] Billing page is accessible from account navigation -- [ ] Page displays current plan name and price -- [ ] Page displays next billing date -- [ ] Page displays last 4 digits of card on file -- [ ] Non-subscribed users see a prompt to subscribe instead of billing details - **Depends on:** Slice 1. - **Risk / learning:** Forces the data model to be right — if the subscription record doesn't store what we need, we find out here. - -**Slice 3: Cancel subscription** -**As a** subscribed customer, **I want** to cancel my subscription **so that** I stop being charged. -**Ships when:** A subscriber can click "cancel", sees a confirmation, and their subscription is marked as cancelling (active until end of billing period). No more charges after the period ends. -**Acceptance criteria:** - -- [ ] Cancel button is visible on the billing page for active subscribers -- [ ] Clicking cancel shows a confirmation dialog before proceeding -- [ ] After confirming, subscription status changes to "cancelling" -- [ ] User retains access until the end of the current billing period -- [ ] Stripe cancellation webhook updates the local subscription record when the period ends -- [ ] Cancelled users see a prompt to resubscribe on the billing page - **Depends on:** Slice 2 (needs the billing page to put the cancel button on). - **Risk / learning:** Tests the Stripe cancellation webhook flow — does our system correctly handle the async state change? - -**Slice 4: Change plan** -**As a** subscribed customer, **I want** to upgrade or downgrade my plan **so that** I get the features I need without overpaying. -**Ships when:** A subscriber can switch between plans, sees the prorated cost, and the change takes effect immediately. -**Acceptance criteria:** - -- [ ] User can see other available plans from the billing page -- [ ] Switching plans shows the prorated cost before confirming -- [ ] Plan change takes effect immediately after confirmation -- [ ] User's next billing amount reflects the new plan -- [ ] Attempting to switch to the current plan is a no-op (button disabled or hidden) - **Depends on:** Slice 2. - **Risk / learning:** Proration logic is the most complex billing calculation. Deferring this until Stripe basics are proven. - -**Slice 5: Update payment method** -**As a** subscribed customer, **I want** to update my credit card **so that** my subscription doesn't lapse when my card expires. -**Ships when:** A subscriber can enter a new card on the billing page and see it reflected as their active payment method. -**Acceptance criteria:** - -- [ ] Update payment button is visible on the billing page -- [ ] User can enter new card details via Stripe checkout -- [ ] Successful update shows the new card's last 4 digits on the billing page -- [ ] Failed card update shows an error and retains the previous payment method - **Depends on:** Slice 2. - **Risk / learning:** Low risk — straightforward Stripe API call. Sequenced last because it's high value but low uncertainty. - -**Sequencing rationale:** Slice 1 proves the Stripe integration works. Slice 2 builds the billing page that every subsequent slice needs as a home. Slices 3–5 are independent of each other and ordered by risk: cancellation tests webhooks, plan changes test proration, payment update is a known quantity. If the client runs out of budget after slice 3, subscribers can sign up, see their billing, and cancel — a complete if minimal subscription experience. diff --git a/skills/slice/examples/full-stack-slices.md b/skills/slice/examples/full-stack-slices.md deleted file mode 100644 index b49cf0f..0000000 --- a/skills/slice/examples/full-stack-slices.md +++ /dev/null @@ -1,136 +0,0 @@ -# Break apart your features into full-stack slices - -I often see people split work into horizontal slices. Ticket A: database tables -and models. Ticket B: controllers. Ticket C: front-end. - -There's something better — split the work into full-stack slices. - -## The full-stack slice - -Think of your feature like a stack of pancakes, where each pancake represents a -layer of your system. Eat a piece of all pancakes at the same time. Don't eat -them one at a time. - -![Two images. Left has three pancakes on a plate with an arrow cutting through all three. Right image has three separate pancakes flat on the plate with red X across them.](https://images.thoughtbot.com/blog-vellum-image-uploads/kPlHvn2ASAexM5od3NIY_pancakes-stack-flat.png) - -That may seem unrealistic. After all, there's usually logic that is shared by -every part of the feature. - -Sometimes features are more like icebergs, where a small change in one layer -corresponds to a large change in a separate layer. For example, the UI may have -a smaller footprint than the back-end. That's okay. Handle more of the back-end -in a ticket, but cut vertically through the iceberg. Don't cut horizontally. - -![Two images. Left has iceberg with a green line cutting vertically through it. It takes a little off the top but a lot off the bottom. Right image is an iceberg with a horizontal crack through it. A red X is overlaid.](https://images.thoughtbot.com/blog-vellum-image-uploads/dYj0u4mWRYWFt870ZjV3_icerberg-vertical-horizontal.png) - -## Why it's better - -- Work iteratively. In the [post agile] world, everybody pretends to work in - iterations. But can we ship at the end of our iteration? If we build the - database and tables in one iteration, our customers don't receive any new - work. But if we ship a sliver of the full stack, they get something. - -- Discover the glue code. When working in front-end and back-end slices, we - often overlook the code that ties the two slices together. And that spells - trouble at the eleventh hour — an incorrect abstraction or a missed - parameter, and we're having to order pizza for dinner and work into the night. - But if we build a full-stack slice, we need the glue code while building the - slice. No surprises Friday night. - -- Learn quickly. When working with full-stack slices, we may find a large - roadblock that forces our project in a new direction. Or we may ship a portion - of our feature and receive customer feedback that changes our roadmap. - -- Stay nimble. We know one thing about the future: it will bring change. - External forces change the highest priority project today into a low priority - project tomorrow. If we only work on one layer of our system and priorities - change, our customers will not get any part of the feature. But if we ship - full-stack slices, we can change projects at the drop of a hat with minimal - loss. - -- Only write the code you need. When working on the back-end in isolation from - the final product, we work with incomplete information — guessing what - the front-end will need. So, we over-engineer solutions that take longer to - develop and create unused code paths that we must then maintain. - -[post agile]: https://pragdave.me/blog/2014/03/04/time-to-kill-agile.html - -## An example - -Let's look at an example from a recent project. - -I was assigned three tickets that considered the front-end and back-end as two -completely different aspects of the application: - -![Front-end and back-end split completely as two different tablets. Front-end has UI. Back-end has some plumbing and a database.](https://images.thoughtbot.com/blog-vellum-image-uploads/aMCVIrOTaGjOih1PO28O_split-into-frontend-backend.png) - -- Ticket X: build the back-end — controllers, models, all the - functionality needed for rendering, filtering, and searching. - -- Ticket Y: build the front end — navigation, UI cards, a sidebar for - filtering, and a navbar for search and a create button. - -- Ticket Z: build a sliding panel of the UI that reused a lot of back-end work. - -Tickets X and Y were completely separated into front-end and back-end. The -complexity of each was high, meaning I could spend a lot of time building things -I assumed the other ticket would need. - -Ticket Z was separate from the other two, and it was mostly front-end work since -it used existing back-end functionality. - -### Looking from the perspective of the user - -Instead of following those tickets, I looked at the UI from the perspective of -the user to find pieces that could be shipped separately. That gave me four -major sections with some subsections: A.1, A.2, B, C.1, C.3, and D. - -![The UI broken down into four sections: A, B, C, D. A is the UI card itself. B is a sidebar on the left of the main section. C is the action buttons on the top right nav. D is a transparent sliding panel.](https://images.thoughtbot.com/blog-vellum-image-uploads/MVs5PFeTRVa78lTMqlmA_split-into-full-stack-sections.png) - -- **A.1**: Display the list of items. This was the first slice of the iceberg, - so I included a lot of the shared logic: navigation (a user has to get to the - page), the UI cards with essential information, and all the back-end work - needed to render them. - -- **A.2**: Each card in the list had some complex interactive elements. I - separated those into a new ticket. It mostly included UI work and small - back-end pieces. - -- **B**: Filtering in the sidebar so that users could narrow down the cards they - see. This was blocked by A.1. - -- **C.1**: Adding search that would filter the cards to the ones matching the - query. Much like B, this one needed the core of A.1. - -- **C.2**: Creating a new item. Most of the back-end logic for this already - existed. So this was a trivial UI addition. - -- **D**: Adding the sliding panel. In a new application, I would have made the - sliding panel its own feature made of full-stack slices. Thankfully, most of - the back-end was already built. So this was primarily UI work. - -You can decide where to put the first slice of the iceberg that has shared -logic. I put it in A.1 because it seemed like the most important part of the -feature. Without it, users would not get any value from the rest. - -Some of the other work — like B, C.1, and C.2 — became thin slivers -of full-stack work. And that made for concise pull requests. Avoid the -temptation to group those thin slivers with something else. I have seen many -"simple" ancillary tasks unearth complex issues and delay the release of the -core feature. - -## Full stack depends on your stack - -You may think these lessons don't apply to you because you build APIs or -single-page applications. But it does. Full-stack is whatever your fullest stack -can be. - -If you build APIs, the consumers of the API are your users. And they will -benefit from an endpoint that returns a list of items even before you allow them -to search or filter those items. - -Likewise, if you build single-page applications, splitting your front-end work -into discrete portions that you can deliver separately will bring value to your -users faster while keeping you nimble. - -**Break apart your features into full-stack slices** whatever your stack. diff --git a/skills/slice/examples/job-stories.md b/skills/slice/examples/job-stories.md deleted file mode 100644 index b94f2ec..0000000 --- a/skills/slice/examples/job-stories.md +++ /dev/null @@ -1,20 +0,0 @@ -# Job stories - -Job stories use the format: **When** [situation], **I want** [motivation], **So** -[expected outcome]. - -Unlike user stories ("As a [role], I want..."), job stories anchor on the -_context that triggers the need_ rather than a persona. This makes them -especially useful for slicing because each story describes a distinct moment -worth shipping for. - -## Examples - -**When** I'm buying a baseball card, **I want** to know if it is fairly priced, -**So** I can have confidence in my purchase. - -**When** I'm viewing an event, **I want** to know which comedians are -performing, **So** I can decide if the event is worth attending. - -**When** I've paid my energy bill, **I want** to see how much it was and how -much I saved, **So** I can understand my energy spending. diff --git a/skills/slice/references/slice-explorer.md b/skills/slice/references/slice-explorer.md deleted file mode 100644 index 9bf3819..0000000 --- a/skills/slice/references/slice-explorer.md +++ /dev/null @@ -1,30 +0,0 @@ -# Slice Explorer Brief - -The brief for the Phase 1 grounding subagents. Hand this to each general-purpose subagent along with the one angle it should cover. - -## Mission - -Find out what this app already has, so the slicing conversation is grounded in the real codebase instead of an imagined one. You are gathering facts, not proposing a plan — read, trace, and report. - -Your report feeds a Socratic conversation in which the developer defines the slices themselves. That makes what you leave out as important as what you include: no slice proposals, no draft acceptance criteria, no design recommendations. Report what exists; the orchestrator decides which questions it raises. - -## What to trace - -**Whether this already exists.** The most useful thing you can find is that some or all of the work is already done. Look for the feature itself, an earlier attempt, adjacent behavior that covers part of it, dead or unreachable code, feature flags, and abandoned migrations. Half-built is a finding; so is "nothing like this exists anywhere." - -**What it would touch, and what's reusable.** Identify the models, tables, controllers, jobs, and views in the area, and the abstractions already available (service objects, query objects, form objects, concerns, policies). Note what a new slice could lean on rather than rebuild. - -**How comparable features are tested — and what those tests actually check.** Find the closest existing feature and read its tests. Report the framework and structure, but go further: list the specific edge cases and error states those tests cover. Nullable columns, existing validations, the states a record can be in, what happens when an external call fails. This is the part that turns vague acceptance criteria into concrete ones. - -## What to report - -Keep it tight and factual: - -- **What already exists** — with `file:line`, and how complete it is. -- **What it would touch** — the models, tables, and layers in play. -- **What's reusable** — existing abstractions and helpers, with `file:line`. -- **Real edge cases and failure modes in this area** — drawn from the code and its tests, not invented. -- **How comparable features are tested** — framework, structure, factories, and what those tests cover. -- **The files most worth reading** — the handful the orchestrator needs in context to ask sharp questions. - -Return findings only. Do not contact the user, do not write any code, and do not suggest how the work should be sliced — the orchestrator reads your report and the key files, then runs the conversation. diff --git a/skills/socratic-review/SKILL.md b/skills/socratic-review/SKILL.md deleted file mode 100644 index f3e5b53..0000000 --- a/skills/socratic-review/SKILL.md +++ /dev/null @@ -1,217 +0,0 @@ ---- -name: socratic-review -description: Socratic code review and refactoring session — whether it's your own code, a teammate's PR, or something you inherited. Leads you to see the issues through questions, names smells and moves precisely, then closes with a concrete plan. -argument-hint: "[file path, code snippet, diff or SHA]" -disable-model-invocation: true ---- - -## Behavior - -This is a pairing session, not a report. Do not produce structured output. Do not list issues or moves upfront. Lead with questions that make the user do the seeing — then guide them to act on what they found. - -### Step 0: Silent Assessment - -Before saying anything, build a thorough understanding of the code across every problem space in the question bank below. How you gather that understanding depends on the size of what you're reviewing: - -- **A small, self-contained target** (a single method, a short snippet, a focused diff) — read it yourself, inline. Spinning up subagents would cost more than it returns. -- **A larger or unfamiliar target** (a multi-file PR, a SHA touching several layers, or inherited code whose call sites you'd need to trace) — dispatch general-purpose subagents in parallel (via the `Agent` tool) to explore, then synthesise their findings. This is the default for anything beyond a single file. - -When you fan out, give each subagent the brief in `references/smell-explorer.md` plus one problem space (or a small cluster of related ones) drawn from the question bank — for example: responsibility & coupling; clarity & design; security; performance; data integrity & error handling; testing & edge cases. Send the independent assessments in a single batch so they run concurrently. - -Ask each subagent to return the files most worth reading alongside its findings. When they return, **read those files yourself** before opening the session — the subagents build the map, but Steps 1–3 have you discussing this code line by line and then changing it, which you can't do from severity labels and `file:line` pointers alone. - -Whether you read inline or fan out, the output of this step is the same: for each smell, determine the best refactoring move (Extract Class, Move Method, Replace Conditional with Polymorphism, etc.) and the sequence you'd execute them in. Merge everything into a single **private ranked list** of issues and moves, de-duplicating where subagents overlap and ordering by severity. - -Do not share this list, and do not surface the subagents' raw reports — the assessment stays silent. It is your map for the entire session: it tells you where to lead when the user runs out of things to see, which problem spaces to open up that they would never think to visit on their own, and whether to validate or redirect when they propose a move. - -### Step 1: Let Them Lead - -You already read the code in Step 0 — don't ask the user to explain what it does. Open by briefly naming what you see (one or two sentences that show you understood the code), then ask them to look before you share your full diagnosis. - -Match the frame to what you know from context — the user's prompt, the conversation history, or the nature of the code itself usually makes it clear whether this is their own code, a PR, or something inherited. Ask the question that fits: - -**If they wrote it** (self-review, refactoring their own work): - -**"Before I say anything — what feels off to you? Even vague. What's the part you'd want to revisit before calling it done?"** - -**If they're reviewing someone else's work** (PR review, code review, audit): - -**"Before I say anything — what caught your eye? What's the part that made you stop and read more carefully?"** - -**If they inherited it or are just exploring** (understanding unfamiliar code): - -**"Before I say anything — where did you get lost, or where did you start making assumptions because the code didn't explain itself?"** - -**If the frame genuinely isn't clear**, ask directly: **"Is this your own code, a teammate's, or something you inherited?"** — then proceed to the matching question. - -Wait for their answer. Then begin the Socratic thread. Ask one question at a time, following what they've said. The goal is to lead them to the real issues through questions, not to name the issues for them. - -### Step 2: Guide Toward Blind Spots - -Once the user's thread runs dry — they've named what they can see — do not jump straight to synthesis. Check your silent assessment. If there are problem spaces the conversation hasn't touched that contain real issues, open those spaces with a question. Lead them there Socratically, even though they didn't know to look. - -For example, if the conversation covered clarity and coupling but missed a security issue, don't say "there's a security issue." Ask: "Who can access this action — is there authorization, or just authentication?" Let them find it. - -Work through the untouched problem spaces in order of severity from your assessment. Stop when the remaining issues are minor or when the session has covered enough ground to move to refactoring. - -### Step 3: Transition to Refactoring - -When the diagnosis is clear enough to act on, shift the conversation from seeing problems to solving them. Bridge with: - -**"Now that you can see it — are your tests green? What's your safety net before we start moving things?"** - -Wait for their answer. If tests are green, the XP rhythm applies: refactor with safety, stop when the code is simple, don't gold-plate. If tests aren't green or don't exist, the first question becomes: what would you need to pin down before it's safe to change this? - -Then: - -**"What's the first move you'd make — and why that one first?"** - -Wait for their answer. If they propose a move that doesn't match your assessment — treating the symptom instead of the cause, choosing Extract Method when the real issue is a responsibility split — don't correct them directly. Ask a question that leads them to see the deeper issue: "What's the smell underneath that one?" or "If you do that extraction, how many responsibilities does this class still have?" - -When they've named the smell and proposed a move, engage directly: what they got right, what they missed or undersold, and what the better path is if theirs is off. Name the move precisely — Extract Method, Extract Class, Move Method, Replace Conditional with Polymorphism, Hide Delegate — and say which principle it restores. - -If there are multiple moves, guide the sequencing: which move first, what depends on what, and where to stop. - -### Question Bank — Diagnosis - -Good questions to reach for when they naturally arise: - -**On responsibility and cohesion:** - -- "What are all the reasons this class might need to change?" -- "If you had to rename this method to say exactly what it does, what would you call it?" -- "Who owns this behaviour — does it belong here, or is it a guest?" - -**On coupling and dependency:** - -- "What does this code know about that it probably shouldn't?" -- "If that thing changed, how many places would you have to update?" -- "What would you have to mock to test this in isolation — and does that list surprise you?" - -**On clarity and intention:** - -- "If you read this six months from now with no context, would you know why it was written this way?" -- "Is this code saying what it means, or are you translating?" -- "What's the gap between what this code does and what it's called?" - -**On change and design:** - -- "How hard would it be to add a new type here without touching this class?" -- "Where's the duplication — and is it duplication of code, or duplication of knowledge?" -- "What does this code assume about the future that it probably shouldn't?" - -**On XP and simplicity:** - -- "Is this the simplest thing that could possibly work?" -- "What would you delete from this without losing any behaviour?" -- "Is this abstraction earning its existence, or is it speculative?" - -**On Rails layer and thoughtbot patterns:** - -- "Is there business logic hiding in a callback — something that should be an explicit service call instead?" -- "Is this in the right layer — does it belong in the model, a service object, a form object, or a query object?" -- "Could this be a plain Ruby object instead of reaching for a Rails abstraction?" -- "Is this concern hiding coupling, or genuinely grouping behaviour that belongs together?" -- "If you extracted this to a service object with a single `call` method, what would you name it — and does that name reveal whether it has one responsibility?" - -**On security (Rails-specific):** - -- "What happens if a user sends unexpected params here — are you protected by strong parameters, or is something slipping through?" -- "Is this query built from user input? Could someone inject SQL through this?" -- "Who can access this action — is there authorization, or just authentication? What happens if a user guesses someone else's ID?" -- "Are you rendering user-provided content? Is it escaped, or is there an XSS vector here?" -- "Is there a mass assignment risk — are you passing params directly to `update` or `create` without scoping?" -- "Does this expose data in the response that the user shouldn't see — timestamps, internal IDs, other users' data?" -- "Is this action rate-limited or protected against abuse? What happens if someone hits it 10,000 times?" - -**On performance (Rails-specific):** - -- "How many queries does this action produce? Walk through it — is there an N+1 hiding in that loop?" -- "Are you loading entire records when you only need a count or a subset of columns?" -- "Is this query missing an index? What does the `WHERE` clause filter on, and is that column indexed?" -- "Could this be a scope or a counter cache instead of computing it every request?" -- "Is this work happening in the request cycle that should be in a background job?" -- "What happens when this table has a million rows — does this query still work?" -- "Are you memoizing something expensive, or recomputing it every time?" - -**On testing:** - -- "Is this tested? What's tested — the behaviour or the implementation?" -- "If you refactored this, would the tests break even though the behaviour didn't change? That's a brittle test." -- "What edge case would you be most nervous about if there were no tests?" -- "Is the test setup readable — or do you have to trace through five `let` statements to understand what's being tested?" -- "Are you testing the happy path only, or does the test suite cover what happens when things go wrong?" -- "Is there an integration test that proves this feature works end-to-end, or just unit tests on individual pieces?" - -**On error handling:** - -- "What happens when this fails — does the user see a useful error, a 500, or nothing at all?" -- "Are you rescuing too broadly? What does `rescue StandardError` actually catch that you didn't intend?" -- "Is this error being logged or reported, or is it silently swallowed?" -- "If this external service is down, what happens to the user's request?" -- "Is there a graceful fallback, or does one failure cascade?" - -**On data integrity:** - -- "Is this uniqueness validation backed by a database constraint — or is there a race condition between the check and the insert?" -- "Are these related writes wrapped in a transaction? What happens if the second one fails after the first succeeds?" -- "Does the model validation match what the database enforces? If they disagree, the database wins — and you might not know until production." -- "Can this create orphaned records? What happens to the children if a parent is deleted?" -- "Is there a foreign key constraint, or is referential integrity just a hope?" - -**On edge cases:** - -- "What happens if this is nil? Empty? Zero? A blank string?" -- "What if the collection is empty — does the code handle that, or does it assume there's always at least one?" -- "What happens at the boundaries — the first item, the last item, exactly at the limit?" -- "Is there a time-of-check-time-of-use issue — could the data change between when you read it and when you act on it?" - -### Question Bank — Refactoring - -**On naming the smell:** - -- "Can you name the smell — or describe what it feels like if you don't have the name?" -- "What's the one reason this class exists? If there's more than one, that's your answer." -- "Where does this code know things it probably shouldn't?" -- "What would you have to change in multiple places if this requirement shifted?" - -**On the move:** - -- "What's the smallest change that would meaningfully improve this?" -- "Are you treating the symptom or the cause?" -- "What new problem does that refactoring create?" -- "Does this move fit the patterns your codebase already uses — or does it introduce something new?" -- "Is this business logic hiding in a callback? If so, where does it belong instead?" -- "Would a plain Ruby object solve this — or does it genuinely need to be a model concern?" -- "If you extracted this to a service object, what would its single `call` method do — can you state it in one sentence?" -- "Is this a service object, a form object, or a query object? Naming the type of extraction clarifies whether it has one job." - -**On test safety (XP discipline):** - -- "What tests would catch a mistake here?" -- "Is there anything you'd want to pin down with a test before you move?" -- "How will you know when you're done — what does passing look like?" - -**On simplicity (XP / Beck):** - -- "Is this the simplest thing that reveals the intention?" -- "Are you adding this abstraction because it's needed now, or because it might be useful?" -- "What could you delete without losing any behaviour or clarity?" - -### Step 4: Close - -When the diagnosis is clear, the moves are named, and the sequence is agreed, wrap up with a practical summary: - -1. **What we found** — the key smells or issues, named precisely -2. **What to do** — the agreed refactoring moves, in order -3. **Where to start** — the first concrete step - -Then ask: - -**"Does that feel right — anything you'd reorder or skip?"** - -Let them adjust the plan. The session is done when there's a clear next action. - -## Tone - -Senior pairing partner, not teacher. You're reviewing and refactoring together — you're just further along. Push back when they miss something. Affirm when they find it themselves. Demand specificity — "make it cleaner" is not a diagnosis and "refactor it" is not a move. The session succeeds when they can name the smell, name the move, justify both, and know when to stop. diff --git a/skills/socratic-review/references/smell-explorer.md b/skills/socratic-review/references/smell-explorer.md deleted file mode 100644 index 206d35a..0000000 --- a/skills/socratic-review/references/smell-explorer.md +++ /dev/null @@ -1,27 +0,0 @@ -# Smell Explorer Brief - -The brief for the Step 0 assessment subagents. Hand this to each general-purpose subagent along with the one problem space (or small cluster of related spaces) it should cover. - -## Mission - -Assess the review target for smells within your assigned problem space, thoroughly enough that the orchestrator can lead a Socratic session over what you find. You are diagnosing, not fixing — read, trace, and report. - -## What to trace - -**The target itself.** Read every file in scope for your problem space. If the target is a diff or a SHA, read the surrounding code too — a change is only assessable against what it changed. - -**Call sites and collaborators.** Follow the code outward as far as your problem space requires: who calls this, what it calls, what it inherits from, what it mutates. A responsibility or coupling assessment that stops at the file boundary will miss the real smell. - -**Conventions the app already has.** Note whether what you're looking at fights the grain of the surrounding code or follows it. A pattern used consistently across the app is a different finding than the same pattern used once. - -## What to report - -Keep it tight and diagnostic: - -- **Each smell, named precisely** — Feature Envy, Divergent Change, Shotgun Surgery, Long Method, N+1, missing authorization, and so on. If you can't name it, describe the mechanism rather than reaching for a vague label. -- **Location** — `file:line` for every finding. -- **Severity** — how much this actually costs, so the orchestrator can rank across problem spaces. -- **Evidence** — the specific thing that makes it true (the second reason the class changes, the query inside the loop, the unscoped `params`). -- **The files most worth reading** — the handful the orchestrator needs in context to discuss your findings line by line. - -Return findings only. Do not contact the user, and do not write review prose or recommendations — the orchestrator runs the session, reads the key files, and decides what to surface and when. diff --git a/skills/standup/SKILL.md b/skills/standup/SKILL.md deleted file mode 100644 index 2258076..0000000 --- a/skills/standup/SKILL.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -name: standup -description: Write a client update — identify what was done, what's next, and surface risks before they become surprises. End of day, start of day, or end of week. -argument-hint: "[optional context, e.g. 'end of week update']" -disable-model-invocation: true ---- - -## Behavior - -This is a guided conversation that ends with a polished, ready-to-send update. Start by getting the raw material from the user — then help them sharpen it. - -### Step 1: Gather - -Start by checking git for context: - -- `git log --since="yesterday" --author=$(git config user.email)` (or last few days if no recent commits) -- Check for open branches, uncommitted work, open PRs - -Then open with: - -**"Here's what I can see from git. Before I help you write this — what did you actually spend your time on? Git doesn't always tell the full story."** - -Wait for their answer. Git shows commits but misses investigation, debugging, conversations, decisions, and thinking. Their answer fills the gaps. - -Then ask: - -**"What's the most important thing the client should know from today — if they read one sentence and nothing else?"** - -Wait. This forces them to prioritise. Most updates bury the lead. - -Then: - -**"Is there anything the client needs to decide, unblock, or be aware of before your next working session?"** - -Wait. This surfaces blockers and risks before they become surprises. - -### Step 2: Sharpen — Socratically - -Before writing the update, push on what they've said: - -**On completeness:** - -- "You mentioned [X] — is that done-done, or is there a loose end the client should know about?" -- "Is there anything you learned today that changes the plan or the estimate?" -- "Are you waiting on anything from the client's side? Now's the time to ask — don't let it sit." - -**On risks — push hard here:** - -- "Is there a risk here you're not mentioning because you think you can handle it? Those are the ones worth flagging early." -- "If the client asked 'are we on track?' right now — what's your honest answer?" -- "Are you going to hit the next deadline? If there's any doubt, say it now — not the day before." -- "Is there anything that took longer than expected today? If so, does that change the timeline for what comes next?" -- "Are there areas you shipped without full test coverage? What's the QA gap — and does the client know?" -- "Is there a part of this feature that works but you're not confident in — something that could break under edge cases or real load?" -- "Are there any assumptions you're making about the client's infrastructure, data, or users that you haven't verified?" -- "If you got hit by a bus tomorrow, what would fall through the cracks?" - -Don't ask all of these — pick the 2–3 that are most relevant based on what they've said. The goal is to catch the thing they'd forget to mention or unconsciously downplay. Consultants instinctively soften risks in updates — push against that. - -**On team communication — push here before writing:** - -- "Is there something here you need to raise with your team before this goes to the client?" -- "Did anything come up today that a teammate needs to know about — a decision you made, a direction you changed, or a dependency you introduced?" -- "Is there a conversation you should have with someone on the team before your next working session — not the client, your team?" - -This matters because client updates aren't the only communication that gets neglected. Internal alignment breaks quietly when people assume teammates will figure it out from the code. - -### Step 3: Write the Update - -Produce a clean, ready-to-send update. Keep it short — clients don't read long updates. Format: - ---- - -**Update: [Date]** - -**Done:** - -- [Completed items — written in terms of outcomes, not tasks. "Users can now reset their password" not "Implemented password reset controller"] - -**In progress:** - -- [What's actively being worked on, with brief status. "Billing integration — Stripe webhooks working, proration logic next"] - -**Up next:** - -- [What's planned for the next working session] - -**Heads up:** - -- [Risks, blockers, decisions needed, or anything the client should be aware of. Omit this section entirely if there's nothing — don't manufacture concern] - ---- - -### Writing Principles - -- **Outcomes over tasks** — "Users can now do X" beats "Implemented Y controller" -- **Honest over optimistic** — a small concern flagged early builds trust; a surprise later erodes it -- **Short over thorough** — respect the client's time. If they want more detail, they'll ask -- **No jargon** — write for a smart person who doesn't know Rails. "Background processing" not "Sidekiq workers" -- **No filler** — "Continued working on..." is not an update. Name what changed - -After producing the update, close with: - -**"Read it back — does it honestly reflect where things stand? Is there anything you softened that should be said more directly?"** - -Wait for their answer. If they identify something, help them reword it clearly — then the update is ready to send. - -## Tone - -Efficient and honest. This isn't a ceremony — it's a communication tool. Help them say what matters in as few words as possible, without hiding the uncomfortable parts. diff --git a/skills/test-driven-development/SKILL.md b/skills/test-driven-development/SKILL.md deleted file mode 100644 index 49a8151..0000000 --- a/skills/test-driven-development/SKILL.md +++ /dev/null @@ -1,493 +0,0 @@ ---- -name: test-driven-development -description: Strict red-green-refactor TDD workflow for implementing features, fixing bugs, or changing behavior in Rails applications. Enforces the discipline of writing a failing test before any production code. Use whenever you want to implement with TDD — whether a new feature, a bugfix, a refactor, or any behavior change. -argument-hint: "[feature, bug, or behavior to implement]" -disable-model-invocation: true ---- - -# Test-Driven Development (TDD) - -## Overview - -Write the test first. Watch it fail. Write minimal code to pass. - -**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing. - -**Violating the letter of the rules is violating the spirit of the rules.** - -## The Iron Law - -``` -NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST -``` - -Write code before the test? Delete it. Start over. - -**No exceptions:** - -- Don't keep it as "reference" -- Don't "adapt" it while writing tests -- Don't look at it -- Delete means delete - -Implement fresh from tests. Period. - -## Outside-In Development - -Start every feature with a high-level test that describes behavior from the user's perspective. Run it, read the failure, and let that failure dictate your next move. As failures push you down the stack, write a new failing test at each layer you drop into — never write code for a layer without a failing test at that layer demanding it. - -Read `examples/outside-in-testing.md` for a walkthrough of the philosophy and `examples/testing-pyramid.md` for how test types combine into an optimal suite. - -### One Change, One Run - -After every change — writing a test, adding a route, creating a file, implementing a method — run the affected test immediately: - -```bash -bundle exec rspec spec/features/guest_searches_for_items_spec.rb -``` - -The failure message is your instruction for what to do next. Don't batch changes and don't guess ahead: one change, one run, read the failure, decide. If you made two changes before running, you no longer know which one the test is reacting to. - -### Drop Down by Writing the Next Failing Test - -A failure rarely means "write this exact line." It usually means "the layer below isn't there yet." When the active test's failure points to a layer that has behavior of its own — a controller action, an endpoint, a model method — **drop down and write a failing test at that layer before building it.** - -Think of it as a stack of failing tests: - -- The **active** test is the one whose failure you're reading right now. -- Its failure points to a missing lower layer → write a new failing test at that layer. It becomes the active test. -- Drive that test with Red-Green-Refactor. If _it_ forces you down another level, push another failing test. -- When the active test goes green, pop it: rerun the test one layer up. Its next failure drives the next move. - -Drop to whichever layer the failure names — not always one rung at a time. Continue until the top-level feature spec is green with nothing left on the stack. - -The ladder of test types, top to bottom: - -| When the failure points to… | Write this failing test | -| ------------------------------------------------------------------- | ---------------------------- | -| End-to-end behavior from the user's perspective | Feature / system spec | -| A controller action, response, status, or redirect | Request (or controller) spec | -| Logic in a model, service object, query, calculation, or validation | Model / unit spec | - -Feature and request specs are integration tests: real database records, no mocks — except external services (use webmock or fakes), so the suite runs offline. Unit specs isolate the object under test: mock collaborators aggressively, because the goal is to prove _this_ object, not its collaborators. Difficulty testing two objects in isolation signals too-tight coupling. - -### Build Directly Only for Inert Glue - -A few things have no behavior of their own, so they get no test of their own — but you still add them only because a failing test one layer up demanded them: - -- The route line (a request spec failing with `No route matches` drives it) -- An empty class or module to clear a `NameError` -- Trivial markup a feature spec's content expectation already covers - -Everything with behavior gets its own failing test first. When in doubt, drop down and write the test. - -The testing pyramid: many unit tests at the bottom, fewer request specs in the middle, a few feature specs at the top. Unit tests are fast and precise; feature tests prove the system works end-to-end. Each plays to its strengths. - -## Red-Green-Refactor - -The cycle every test follows — feature spec, request spec, and model spec alike. Each failing test on the stack runs this loop; a test going green is what lets you pop back up to the layer above. - -```dot -digraph tdd_cycle { - rankdir=LR; - red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"]; - verify_red [label="Verify fails\ncorrectly", shape=diamond]; - green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"]; - verify_green [label="Verify passes\nAll green", shape=diamond]; - refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"]; - next [label="Next", shape=ellipse]; - - red -> verify_red; - verify_red -> green [label="yes"]; - verify_red -> red [label="wrong\nfailure"]; - green -> verify_green; - verify_green -> refactor [label="yes"]; - verify_green -> green [label="no"]; - refactor -> verify_green [label="stay\ngreen"]; - verify_green -> next; - next -> red; -} -``` - -### RED — Write Failing Test - -Write one minimal test showing what should happen. - -<Good> - -```ruby -RSpec.describe Item, ".search" do - it "filters items by the search term" do - desired_item = create(:item, name: "Widget") - _other_item = create(:item, name: "Gadget") - - expect(Item.search("Widget")).to eq [desired_item] - end -end -``` - -Clear name, tests real behavior, one thing. - -</Good> - -<Bad> - -```ruby -it "search works" do - relation = spy("relation") - allow(Item).to receive(:where).and_return(relation) - - Item.search("Widget") - - expect(Item).to have_received(:where).with(name: "Widget") -end -``` - -Vague name, tests spy interactions not real behavior, proves nothing about whether search actually returns the right items. - -</Bad> - -**Requirements:** - -- One behavior -- Clear name -- Feature specs: real records, no mocks (except external services) -- Unit tests: mock collaborators, test the object in isolation - -### Verify RED — Watch It Fail - -**MANDATORY. Never skip.** - -```bash -bundle exec rspec spec/models/item_spec.rb -``` - -Confirm: - -- Test fails (not errors) -- Failure message is expected -- Fails because feature missing (not typos) - -**Test passes?** You're testing existing behavior. Fix test. - -**Test errors?** Fix error, re-run until it fails correctly. - -### GREEN — Minimal Code - -Write simplest code to pass the test. - -<Good> - -```ruby -class Item < ApplicationRecord - def self.search(term) - where(name: term) - end -end -``` - -Just enough to pass. - -</Good> - -<Bad> - -```ruby -class Item < ApplicationRecord - def self.search(term, fuzzy: false, limit: nil, scope: :all) - # YAGNI — the test asked for name filtering, not a search framework - end -end -``` - -Over-engineered. - -</Bad> - -Don't add features, refactor other code, or "improve" beyond the test. - -### Verify GREEN — Watch It Pass - -**MANDATORY.** - -```bash -bundle exec rspec spec/models/item_spec.rb -``` - -Confirm: - -- Test passes -- Other tests still pass -- Output pristine (no errors, warnings) - -**Test fails?** Fix code, not test. - -**Other tests fail?** Fix now. - -### REFACTOR — Clean Up - -After green only: - -- Remove duplication -- Improve names -- Extract helpers - -Keep tests green. Don't add behavior. - -### Repeat - -Pop the stack. Rerun the test one layer up and read its next failure — it drives the next move: build inert glue, or push a new failing test for the next layer down. Keep going until the top-level feature spec is green and the stack is empty. - -## Good Tests - -| Quality | Good | Bad | -| ---------------- | ----------------------------------- | ------------------------------------------------ | -| **Minimal** | One thing. "and" in name? Split it. | `it "validates email and domain and whitespace"` | -| **Clear** | Name describes behavior | `it "test1"` | -| **Shows intent** | Demonstrates desired API | Obscures what code should do | - -## Why Order Matters - -**"I'll write tests after to verify it works"** - -Tests written after code pass immediately. Passing immediately proves nothing: - -- Might test wrong thing -- Might test implementation, not behavior -- Might miss edge cases you forgot -- You never saw it catch the bug - -Test-first forces you to see the test fail, proving it actually tests something. - -**"I already manually tested all the edge cases"** - -Manual testing is ad-hoc. You think you tested everything but: - -- No record of what you tested -- Can't re-run when code changes -- Easy to forget cases under pressure -- "It worked when I tried it" ≠ comprehensive - -Automated tests are systematic. They run the same way every time. - -**"Deleting X hours of work is wasteful"** - -Sunk cost fallacy. The time is already gone. Your choice now: - -- Delete and rewrite with TDD (X more hours, high confidence) -- Keep it and add tests after (30 min, low confidence, likely bugs) - -The "waste" is keeping code you can't trust. Working code without real tests is technical debt. - -**"TDD is dogmatic, being pragmatic means adapting"** - -TDD IS pragmatic: - -- Finds bugs before commit (faster than debugging after) -- Prevents regressions (tests catch breaks immediately) -- Documents behavior (tests show how to use code) -- Enables refactoring (change freely, tests catch breaks) - -"Pragmatic" shortcuts = debugging in production = slower. - -**"Tests after achieve the same goals — it's spirit not ritual"** - -No. Tests-after answer "What does this do?" Tests-first answer "What should this do?" - -Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones. - -Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't). - -30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work. - -## Common Rationalizations - -| Excuse | Reality | -| --------------------------------------- | ------------------------------------------------------------------------ | -| "Too simple to test" | Simple code breaks. Test takes 30 seconds. | -| "Controller's just wiring, skip a spec" | Wiring has behavior — routing, params, response. Write the request spec. | -| "I'll run the test once at the end" | You won't know which change caused which failure. One change, one run. | -| "I'll test after" | Tests passing immediately prove nothing. | -| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" | -| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. | -| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. | -| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. | -| "Need to explore first" | Fine. Throw away exploration, start with TDD. | -| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. | -| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. | -| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. | -| "Existing code has no tests" | You're improving it. Add tests for existing code. | - -## Red Flags — STOP and Start Over - -- Code before test -- Built a controller, model method, or service without a failing test at that layer -- Made several changes, then ran the test once -- Test after implementation -- Test passes immediately -- Can't explain why test failed -- Tests added "later" -- Rationalizing "just this once" -- "I already manually tested it" -- "Tests after achieve the same purpose" -- "It's about spirit not ritual" -- "Keep as reference" or "adapt existing code" -- "Already spent X hours, deleting is wasteful" -- "TDD is dogmatic, I'm being pragmatic" -- "This is different because..." - -**All of these mean: Delete code. Start over with TDD.** - -## Example: Feature (Outside-In) - -**Story:** As a guest, I can search for items so I can find what I want. - -**Top of the stack — feature spec** - -```ruby -# spec/features/guest_searches_for_items_spec.rb -feature "Guest searches for items" do - scenario "by name" do - create(:item, name: "Widget") - - visit root_path - fill_in "Search", with: "Widget" - click_on "Search" - - expect(page).to have_content("Widget") - end -end -``` - -Run it. The failure points at the items index — a controller-layer concern. Don't build an empty action the feature spec merely covers; drop down and write a failing **request spec.** - -**Drop down — request spec** - -```ruby -# spec/requests/items_spec.rb -RSpec.describe "Items", type: :request do - it "renders items matching the search term" do - create(:item, name: "Widget") - - get items_path, params: { search: "Widget" } - - expect(response.body).to include("Widget") - end -end -``` - -Run it — one change, one run, each time: - -- `No route matches` → add the route (inert glue). Run again. -- `uninitialized constant ItemsController` → create the controller and an empty `index`. Run again. -- Body is missing "Widget" → the action needs `Item.search`, which is logic. Drop down again and write a failing **model spec.** - -**Drop down — model spec** - -```ruby -# spec/models/item_spec.rb -RSpec.describe Item, ".search" do - it "filters items by name" do - desired = create(:item, name: "Widget") - _other = create(:item, name: "Gadget") - - expect(Item.search("Widget")).to eq [desired] - end -end -``` - -Verify RED. Implement `Item.search`. Verify GREEN — pop the model spec. Rerun the request spec; wire the action and view until it's green, then pop it. Rerun the feature spec and drive the remaining UI pieces the same way until it's green and the stack is empty. - -## Example: Bug Fix - -**Bug:** Empty email accepted - -Start with a feature spec reproducing the bug from the user's perspective. Registration already exists, so the failure points straight at the model's missing validation — drop directly to a model spec rather than through the request layer. Drop to the layer the failure names. - -**Top of the stack — feature spec** - -```ruby -# spec/features/guest_registers_spec.rb -feature "Guest registers" do - scenario "with blank email" do - visit new_registration_path - fill_in "Email", with: "" - click_on "Register" - - expect(page).to have_content("Email can't be blank") - end -end -``` - -**Drop down — model spec** - -```ruby -# spec/models/user_spec.rb -RSpec.describe User do - it "rejects empty email" do - user = User.new(email: "") - - expect(user).not_to be_valid - expect(user.errors[:email]).to include("can't be blank") - end -end -``` - -**GREEN** - -```ruby -class User < ApplicationRecord - validates :email, presence: true -end -``` - -Model spec passes — pop it. Rerun the feature spec; it's green. Done. - -## Verification Checklist - -Before marking work complete: - -- [ ] Every new function/method has a test -- [ ] Ran the affected test after every change — never batched two changes before running -- [ ] Each layer dropped into (controller, model, service) got its own failing test first -- [ ] Watched each test fail before implementing -- [ ] Each test failed for expected reason (feature missing, not typo) -- [ ] Wrote minimal code to pass each test -- [ ] All tests pass -- [ ] Output pristine (no errors, warnings) -- [ ] Tests use real code (mocks only if unavoidable) -- [ ] Edge cases and errors covered - -Can't check all boxes? You skipped TDD. Start over. - -## When Stuck - -| Problem | Solution | -| ---------------------- | -------------------------------------------------------------------- | -| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. | -| Test too complicated | Design too complicated. Simplify interface. | -| Must mock everything | Code too coupled. Use dependency injection. | -| Test setup huge | Extract helpers. Still complex? Simplify design. | - -## Debugging Integration - -Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression. - -Never fix bugs without a test. - -## Testing Anti-Patterns - -When adding mocks or test utilities, read `references/testing-anti-patterns.md` to avoid common pitfalls: - -- Testing mock behavior instead of real behavior -- Adding test-only methods to production classes -- Mocking without understanding dependencies - -## Final Rule - -``` -Production code → test exists and failed first -Otherwise → not TDD -``` - -No exceptions without your human partner's permission. diff --git a/skills/test-driven-development/examples/outside-in-testing.md b/skills/test-driven-development/examples/outside-in-testing.md deleted file mode 100644 index a40ec1d..0000000 --- a/skills/test-driven-development/examples/outside-in-testing.md +++ /dev/null @@ -1,137 +0,0 @@ -> **Note:** This article teaches the outside-in philosophy and where to mock. This -> skill applies a stricter discipline than the walkthrough below: when a failure -> forces you down a layer (e.g. into the controller), write a _failing test at that -> layer first_ — a request spec for the controller — rather than building an empty -> action the feature spec merely covers. See "Drop Down by Writing the Next Failing -> Test" in `SKILL.md`. - -A few months ago my colleague [Josh Steiner] wrote a comprehensive post on [How -We Test Rails Applications], detailing the different types tests we write and -the various technologies that go with them. In this follow up, we will take a -closer look at thoughtbot's testing workflow. - -We use a process known as "Outside-in testing", driving our development from -high-level tests and working our way down to lower-level concerns. Say we are -working on an e-commerce site and want to implement the following story: - -> As a guest, I can add items to my shopping cart so that I can keep on shopping - -Before we start thinking about models, controllers, or other architectural -concerns we write a high-level RSpec feature test that describes the behavior from -the user's perspective. - -```ruby -# spec/features/guest_adds items_to_shopping_cart_spec.rb -feature 'Guest adds items to shopping cart' do - scenario 'via search' do - item = create(:item) - - visit root_path - fill_in 'Search', with: item.name - click_on 'Search Catalogue' - - click_on item.name - click_on 'Add to Cart' - click_on 'Shopping Cart' - - expect(page).to have_content(item.name) - expect(page).to have_content("Subtotal: #{item.price}") - end -end -``` - -Depending on how much of the application is implemented, this test could break -in multiple places. If this were a newly-generated application we might need to -implement a home page. Once we have a home page we would probably get an error -while attempting to use the search bar saying that 'No such route exists'. This -leads us to implement a `/items` route. - -```ruby -# config/routes.rb -# ... -resources :items, only: [:index] -# ... -``` - -The next few errors walk us through creating an `ItemsController`, with an -empty `index` action and corresponding view. Now that we can successfully click -on "Search Catalogue", we get an error saying that there the desired item does -not appear in the search results so we expose some items in the controller and -display them in the view. - -```ruby -# app/controllers/items_controller.rb -#... -def index - @items = Item.search(params[:search_query]) -end -#... -``` - -```erb -# app/views/items/index.html.erb -<% @items.each do |item| %> - <%= link_to item.name, item %> -<% end %> -``` - -This gives us a new error saying that there is no method `search` defined -`Item`. At this point, we drop down a level of abstraction and write a unit -test for `Item`. - -```ruby -# spec/models/item_spec.rb -describe Item, '.search' do - it 'filters items by the search term' do - desired_item = create(:item) - other_item = create(:item) - - expect(Item.search(desired_item.name)).to eq [desired_item] - end -end -``` - -This test leads us to correctly implement `Item.search`: - -```ruby -# app/models/item.rb -#... -def self.search(term) - where(name: term) -end -#... -``` - -Now the unit test passes so we go back up to our feature test. We can -successfully click on the item's name in the search results! - -We keep following this pattern for the remaining test failures, dropping down -to the unit test level when necessary, until we have a green test suite. Now -our story has been successfuly implemented! - -## Mocking and Stubbing - -The goal of a feature test is to test the real system from end-to-end from the -user's perspective. To do this, we use real database records and don't mock or -stub any of our objects. We _do_ stub calls to external websites (via webmock -or a fake) since the network can be unreliable. Our tests should run without an -internet connection. - -When dropping down to the unit test level, we aggressively mock/stub out -dependencies and collaborators. The goal of a unit test is to prove the -functionality of the object being tested, not the functionality of its -collaborators. Difficulty in testing two objects in isolation from each other -often points to too tight coupling between them. - -## Further Reading - -For some more great articles on testing, check out: - -- [How we Test Rails Applications] -- [Don't Stub the System Under Test] -- [Feature tests with Capybara] - -[Josh Steiner]: https://twitter.com/josh_steiner -[How We Test Rails Applications]: https://thoughtbot.com/blog/how-we-test-rails-applications -[Don't Stub the System Under Test]: https://thoughtbot.com/blog/don-t-stub-the-system-under-test -[Feature tests with Capybara]: https://thoughtbot.com/blog/using-capybara-to-test-javascript-that-makes-http diff --git a/skills/test-driven-development/examples/testing-pyramid.md b/skills/test-driven-development/examples/testing-pyramid.md deleted file mode 100644 index 7ef066b..0000000 --- a/skills/test-driven-development/examples/testing-pyramid.md +++ /dev/null @@ -1,51 +0,0 @@ -When testing a Rails application with RSpec, there are many different test types -to pick from. When should you pick each type and how do you combine them into an -optimal test suite? - -## Unit tests - -All these different tests fall along a spectrum. At one end are **unit tests**. -These test individual components in isolation, proving that they implement the -expected behavior independent of the surrounding system. Because of this, unit -tests are usually small and fast. Examples of unit tests are model and view -specs. - -## Integration tests - -In the real world, these components don't exist in a vacuum: they have to -interact with each other. One component may expect a collaborator to have a -particular interface when in fact it has completely different one. Even though -all the tests pass, the software as a whole is broken. - -This is where **integration tests** come in. These tests exercise the system as -a whole rather than its individual components. They typically do so by -simulating a user trying to accomplish a task in our software. Instead of being -concerned with invoking methods or calling out to collaborators, integration -tests are all about clicking and typing as a user. - -Although this is quite effective for proving that we have working software, it -comes at a cost. Integration tests tend to be much slower and more brittle than -their unit counterparts. Feature and request specs are both integration tests. - -## Hybrid - -Many test types are neither purely unit nor integration tests. Instead, they lie -somewhere in between, testing several components together but not the full -system. For example, controller specs generally test some aspect of the model -and helper layers in addition to the controller itself. - -We like to build our test suite using a combination of these to create a -[**testing pyramid**](http://martinfowler.com/bliki/TestPyramid.html). This is a -suite that has a few high-level integration tests that cover the general -functionality of the app, several intermediate-level tests that cover a -sub-system in more detail, and many unit tests to cover the nitty-gritty details -of each component. - -This approach plays to the strength of each type of test while attempting to -minimize the downsides they have (such as slow run times). - -## Testing Rails applications - -This post is an excerpt from our book, [_Testing -Rails_](https://gumroad.com/l/testing-rails). Check it out if you'd like to -learn more about how we test Rails applications at thoughtbot. diff --git a/skills/test-driven-development/references/testing-anti-patterns.md b/skills/test-driven-development/references/testing-anti-patterns.md deleted file mode 100644 index 87c5fe1..0000000 --- a/skills/test-driven-development/references/testing-anti-patterns.md +++ /dev/null @@ -1,173 +0,0 @@ -# Testing Anti-Patterns - -Four categories of test smells that undermine confidence in a test suite. When adding mocks, test utilities, or shared setup, check your work against these. - -## 1. Obscure Tests - -Tests where it is difficult to understand what is being tested. Setup code lives far from the test, making intent unclear. - -The core problem is the **Mystery Guest** — objects defined outside the test case whose attributes and meaning aren't visible where they're used. - -<Bad> - -```ruby -describe Post do - let(:user) { build_stubbed(:user) } - let(:title) { "Example Post" } - subject(:post) { build_stubbed(:post, user: user, title: title) } - - describe "#slug" do - it "generates a slug from the title" do - expect(post.slug).to eq("example-post") - end - end -end -``` - -Where does `post` come from? What title does it have? You have to scroll up and mentally assemble the object. - -</Bad> - -<Good> - -```ruby -describe "#slug" do - it "generates a slug from the title" do - post = build_stubbed(:post, title: "Example Post") - - expect(post.slug).to eq("example-post") - end -end -``` - -Everything you need to understand the test is in the test. - -</Good> - -**Rule:** Each test should read top-to-bottom without jumping elsewhere to understand setup. - -## 2. Fragile Tests - -Tests that break when seemingly unrelated changes are made to shared setup. - -When test objects are created far from the test case, modifications to shared `let` blocks or `before` hooks can unexpectedly break unrelated tests. - -<Bad> - -```ruby -describe Post do - let(:user) { build_stubbed(:user) } - let(:title) { "Example Post" } - subject(:post) { build_stubbed(:post, user: user, title: title) } - - context "with an author" do - let(:user) { build_stubbed(:user, name: "Willy") } - - it "returns the author's name" do - expect(post.author_name).to eq("Willy") - end - end -end -``` - -Overrides `user` locally but relies on `subject` to pick up the override. Change the `subject` definition and this test breaks for no obvious reason. - -</Bad> - -<Good> - -```ruby -context "with an author" do - it "returns the author's name" do - author = build_stubbed(:user) - post = build_stubbed(:post, user: author) - - expect(post.author_name).to eq(author.name) - end -end -``` - -The test owns its setup. No implicit dependencies on shared state. - -</Good> - -**Rule:** Tests should break only when the behavior they describe changes — never because of unrelated setup modifications. - -## 3. Erratic Tests - -Tests that fail intermittently without code changes. These destroy confidence in the suite. - -### Interacting Tests - -Tests with side effects that leak into subsequent tests. Common sources: - -- **Database records** left between test runs -- **Class-level memoization:** `@recent ||= order(created_at: :desc).limit(10)` — cached across tests -- **Mailer queues** retaining emails between tests -- **Caching enabled:** `config.action_controller.perform_caching = true` in test environment - -**Diagnosis:** Run specs with `--order rand`. If failures reproduce only with a specific seed, you have interacting tests. - -### JavaScript Feature Specs - -Async timing issues. These methods introduce erratic behavior because they don't wait for Capybara's synchronization: - -```ruby -# Fragile — race conditions -first(".active").click -all(".active").each(&:click) -execute_script("$('.active').focus()") -expect(find_field("Username").value).to eq("Joe") -expect(find(".user")["data-name"]).to eq("Joe") -expect(has_css?(".active")).to eq(false) -``` - -**Fix:** Use Capybara matchers that synchronize automatically — `have_css`, `have_content`, `have_field`. Let Capybara wait for the DOM rather than querying it directly. - -### Date and Time - -Assertions against specific dates or times break depending on when the suite runs. - -**Fix:** Use `travel_to` (Rails) or Timecop to freeze time in tests that depend on it. - -## 4. Test Hooks - -Methods in production code that only execute during testing. This creates divergence between what you test and what runs in production. - -<Bad> - -```ruby -class ApplicationController < ActionController::Base - unless Rails.env.test? - before_filter :require_login - end -end -``` - -In production, login is required. In tests, it's skipped entirely. If the login flow breaks, no test will catch it. - -</Bad> - -<Good> - -Use test-level utilities that don't pollute production code. For authentication, use a back door that injects middleware in test mode only: - -```ruby -# In feature specs — Clearance's back door -visit root_path(as: user) -``` - -The production code stays clean. The test infrastructure handles the shortcut. - -</Good> - -**Rule:** Production code should never ask "am I in a test?" If you see `Rails.env.test?` in application code, extract the test concern into test infrastructure. - -## Summary - -| Anti-Pattern | Signal | Fix | -| ------------- | ------------------------------------------------------ | ---------------------------------------------- | -| Obscure Tests | Can't understand the test without reading shared setup | Inline setup — everything visible in the test | -| Fragile Tests | Unrelated setup changes break tests | Tests own their data, no implicit dependencies | -| Erratic Tests | Tests fail intermittently or in certain orders | Isolate side effects, use sync matchers | -| Test Hooks | `Rails.env.test?` in production code | Move test concerns to test infrastructure | diff --git a/skills/trace/SKILL.md b/skills/trace/SKILL.md new file mode 100644 index 0000000..234fb5c --- /dev/null +++ b/skills/trace/SKILL.md @@ -0,0 +1,158 @@ +--- +name: trace +description: Run a scenario and record what actually happened. +argument-hint: '[scenario, e.g. "user creates an account"]' +--- + +# Trace + +Reading code tells you what _should_ happen. Running it tells you what does: the +callback nobody mentioned, the job that enqueues two more, the email that goes out +twice. That's the gap this fills. The output is a record, in order, of what one +scenario did when it ran, with every step marked as seen or only read. + +Two ways this fails. You read the code, write it up in the past tense, and it looks +exactly like a run — so the reader trusts a guess as much as an observation. Or you +run a step that can't be undone: a process gets killed, a database gets dropped. The +first is worse, because nothing about it looks wrong. + +## 1. Pin the scenario + +The scenario is `$ARGUMENTS`, or ask for one. It arrives as a sentence ("user creates +an account"), a route, a command, a job name. + +Turn it into three things before running anything: + +- **Entry point.** The route and handler, CLI command, or job that starts it — found + in the code, not assumed. Two plausible ones (sign up by form, sign up by invite)? + Take the common one, say which, and name the other as its own trace. +- **Starting state.** Who is acting and what exists already. "A signed-in user who + owns one project with one app." Give every association the scenario reads or + deletes at least one row. A delete run against a record with no children can't + show you the child table it forgets to clean up. +- **Input.** The real params: `email: "sam@example.com"`, not "valid params". + +Don't ask the user for these. Find them; say what you picked in one line. + +## 2. Set up a development run + +Run it in the **development environment**: the app's real configuration, the one a +developer sees. The test environment swaps things out — jobs run inline, mail and +broadcasts go to fakes, outside calls are stubbed by the test setup — so a trace +there records the test harness as much as the app. Development is made for this: +its data is disposable and its outside calls go to sandbox accounts. + +Read `references/running.md` now. It has the recording taps and the setup details. + +**Starting state.** Build it in the development database with the app's own models, +or its factories if development can load them. Create the actor fresh rather than +borrowing a row that's already there, so every id in the trace is one this run made. + +**How to drive it.** In order of preference: + +1. **A script that loads the app in development** and sends the request through it + in the same process (the stack's in-process request helper, or call the handler + directly). Same process means you can record outside calls and listen to the + app's own events. +2. **The dev server on a spare port**, with a real request sent to it. Use this when + the app can't be driven in-process. Stop it after. + +Never production, never a staging database. + +**Record every outside call.** HTTP calls, payment or email providers, LLM APIs: +let them go out, and log the URL and request body of each. Then read every +captured body, field by field, before writing up. What the app actually sends is +where bugs hide that no one reading the code sees: `"description": "#<Proc:0x...>"`, +`"name": "[object Object]"`, `undefined`, an empty prompt, a user's email in a +field meant for an id. Anything that isn't what the code plainly meant to send goes +in Surprises. Redact keys and tokens before writing a captured call anywhere. + +**Stub anything destructive.** Killing processes, dropping databases, deleting or +moving files outside the repo. Intercept it in your script before the scenario +starts, record the call it _would_ have made, and return what the real one would. +For files, point the run at a temp directory. Can't be intercepted safely? Don't +run past it. Stop the run there, and trace the rest by reading, marked as read. + +Never run a destructive step for real to see what it does. A trace that says "would +have run `dropdb app_42`" is complete; one that ran it isn't a trace, it's an +incident. + +**Follow the chain.** Jobs enqueued during the scenario are part of it. Run them the +way production does: after the request returns, not inside it. Queue them during +the request, then perform them yourself and keep recording, one level at a time, +until nothing new is enqueued or you hit a step you stubbed. Don't start the app's +real job worker: it would pick up jobs you didn't queue. Say which job backend the +app normally uses, and where you stopped and why. + +## 3. Run it and leave nothing behind + +Note `git status --porcelain` before. Put throwaway files where you'd delete them +anyway, run, capture the output, then clean up: + +- Delete the throwaway files. `git status` after has to match before; if the run + touched something you didn't write, say so. +- Stop any server or process you started. + +If it fails to run — missing database, broken setup, a migration that won't apply, +a dependency that isn't installed — that's a result. Don't install or upgrade +packages to get past it: they land in directories other projects share. Work +around it inside your throwaway files if you can, and say what you did. Otherwise +report it, try the next route once, and if nothing runs, fall back to reading the +whole path and say plainly at the top that nothing was executed. + +## 4. Write it up + +Read `assets/trace-template.md` and fill it in. What makes a trace worth having: + +**Every step is marked `ran` or `read`.** `ran` means you saw it in the recorded +output of this run. `read` means you got it from the code. `stubbed` means the code +reached it and you intercepted it. No step goes unmarked, and a step you saw only in +the code is never written up as though you watched it happen. + +**Real values from the run.** `INSERT INTO users (email) VALUES ('sam@example.com')`, +`Project id=17 "Sam's project"`, `WelcomeEmailJob enqueued on default`. Not "a user +is created". The numbers in the drawing and the ledger come from the same run. + +**Order is the point.** Draw it as a sequence, what happened then what, with +branches only where the run took one or a guard stopped it. Plain text, under about +seventy characters wide, labels from the codebase. + +``` +POST /users email=sam@example.com + | + v +UsersController#create + |-- INSERT users id=31 + |-- after create: provision_workspace + | |-- INSERT organizations id=9 + | `-- INSERT projects id=17 + |-- enqueue WelcomeEmailJob + v +302 -> /projects/17 +``` + +**Surprises get their own list.** The things someone reading the code would miss: a +callback three files away, a query per row, a job that runs twice, a write inside a +GET. If there are none, say "none" rather than inventing one — that's also a finding. + +**Holes get named.** What you stubbed, what you only read, where you stopped the +chain. Those are what the next person would have to check by hand. + +Keep prose short. The ledger and the drawing carry it; prose explains the surprises. + +## 5. Save and show it + +Write the trace to `docs/traces/<slug>.md` at the repo root, a short kebab-case slug +(`user-creates-account`). Create the directory if needed. If the file exists, it's an +older trace of the same scenario: overwrite it, and say in one line what changed +since, if anything did — that diff is often the most useful thing in it. + +Don't paste the trace into the chat. The file is the record; the chat is the +headline. Reply with the path and at most three bullets: what the scenario +did in one line, the biggest surprise, and anything stubbed or only read that +changes how far to trust it. If the run turned up nothing surprising, say so. +Don't end on an offer. + +It's a record of what the code did on one run, not a spec and not a review. Don't +recommend changes in it. If the run turned up a real bug — a double charge, a write +that skips authorization — tell the user directly, outside the file, in one line. diff --git a/skills/trace/assets/trace-template.md b/skills/trace/assets/trace-template.md new file mode 100644 index 0000000..1676078 --- /dev/null +++ b/skills/trace/assets/trace-template.md @@ -0,0 +1,28 @@ +# Trace: {scenario, in the user's words} + +{One line: how it was run — which script or request, which environment — +and the commit (`git rev-parse --short HEAD`). If +nothing ran, say that here.} + +**Starting state:** {who is acting and what already exists} +**Input:** {the real params or command} + +## What happened + +``` +{the sequence drawing} +``` + +## Ledger + +| # | Step | Where | Seen | +| --- | --------------------------------- | ------------- | -------------------- | +| 1 | {what happened, with real values} | `{file:line}` | ran / read / stubbed | + +## Surprises + +- {what someone reading the code would miss — or "none"} + +## Holes + +- {what was stubbed, only read, or where the chain stopped, and why} diff --git a/skills/trace/references/running.md b/skills/trace/references/running.md new file mode 100644 index 0000000..ca2ecb7 --- /dev/null +++ b/skills/trace/references/running.md @@ -0,0 +1,82 @@ +# Running and recording a trace + +Drive the entry point with a script that loads the app, record what leaves the +process, record in order. Look for what the stack already gives you before +writing your own. + +## Drive it + +A script in a gitignored folder that imports the app's own code and runs the +entry point in development: + +- **A web handler:** use the framework's in-process request helper if it has + one that works outside the test runner (Rails: + `ActionDispatch::Integration::Session`). Otherwise build the request object + the framework passes in and call the handler directly. +- **A page or view that loads data:** call the data-loading function it calls, + with the same arguments. +- **A CLI command or job:** invoke it the way the app's own entry point does. + +Auth: create the user and whatever session or token record the app checks, +then sign in through the app's real sign-in route, the way a browser would. If +the auth library can't be satisfied from a script, call the code just past the +auth check, and mark the auth check `read`. + +Development guards can block a scripted request: a host allowlist, a CSRF +token check, mail that opens a browser tab. Turn each off for the script only, +and list it in the trace's Holes. + +An in-process request can leave per-request state behind that breaks the +script's next query. Rails: a `NoMethodError` from query logging after a +request; call `ActiveSupport::ExecutionContext.clear` after each one. + +When nothing can be driven in-process, start the dev server on a spare port, +send a real request, and stop the server. + +## Record outside calls + +Wrap the outgoing HTTP function in the script before the scenario runs: log +the call, then pass it through. In JavaScript and TypeScript that's usually +`globalThis.fetch`: + +```ts +const realFetch = globalThis.fetch; +globalThis.fetch = async (input, init) => { + const url = String(input instanceof Request ? input.url : input); + console.log("TRACE http", init?.method ?? "GET", url, init?.body ?? ""); + return realFetch(input, init); +}; +``` + +Check the app doesn't use a different HTTP client (axios, got, Faraday, an SDK +with its own transport); if it does, wrap that. Ruby has no single function to +wrap; WebMock's `after_request` callback with `allow_net_connect!` records +without blocking. + +Destructive calls (process kills, dropping a database, deleting or moving files +outside the repo): replace the function the app calls with one that records the +arguments and returns, or point its configured directory at a temp folder. + +## Record + +- **The framework's own events**, if it has them. Rails: + `ActiveSupport::Notifications.subscribe` to `sql.active_record`, + `enqueue.active_job`, `perform.active_job`, `deliver.action_mailer`, + `redirect_to.action_controller`, `broadcast.action_cable`. +- **Queries:** otherwise the ORM's query log or event. Prisma: + `new PrismaClient({ log: [{ emit: "event", level: "query" }] })` and + `prisma.$on("query", e => ...)`. Keep writes; keep reads only when there are + suspiciously many. +- **Where a write came from:** some query logs print the calling `file:line` + under each query (Rails: `verbose_query_logs`). Note the log's size before + and read only what this run appended. +- **Log level:** most frameworks log requests and queries at debug. Turn it up + for the one run and filter. +- **Background work:** switch the job backend to one that holds jobs (Rails: + `ActiveJob::Base.queue_adapter = :test`), or replace the enqueue function + with one that records and holds. After the request returns, run the held + jobs yourself, one level at a time. +- **Print statements** at each step's entry and exit, as a last resort, in a + copy you delete after. + +Tag every line `TRACE ...` so it filters out of the noise. diff --git a/skills/understand/SKILL.md b/skills/understand/SKILL.md new file mode 100644 index 0000000..c1525d8 --- /dev/null +++ b/skills/understand/SKILL.md @@ -0,0 +1,183 @@ +--- +name: understand +description: Use the Socratic method to understand something. +argument-hint: "[PR, ticket, link, spec, path, or feature to understand]" +--- + +# Understand it by defending it + +Don't explain. A belief the user had to defend, and then watched break against +something real, outlasts an explanation. Find where their model of this thing is +wrong or missing and walk them to that spot. + +That's the Socratic method in its useful sense — elenchus — and not in its caricature: +no feigned ignorance, no withholding what you know, no answering every question with +another question. + +Two ways this goes badly. You lecture: they asked to understand, you write four +paragraphs, nothing lands. Or you guess: you ask about retry logic that doesn't exist, +and because you asked with confidence they believe you, and now they know something +false. The second is worse and harder to undo, which is why the reading comes first. + +## 1. Pin the target and the stakes + +The target is `$ARGUMENTS`, or ask. It arrives in one of a few shapes, and all that +changes between them is where the truth lives. + +- **A rev or a path** — `git rev-parse --verify --quiet <arg>` resolves it, or the file + is there. If both (`docs` the branch, `docs/` the directory), ask which. +- **A number, or a link to a PR or issue** — that's a PR (`gh pr view <n>`, `gh pr +diff <n>`), so pull the number out of the URL instead of fetching the page, which + gets you a rendered description and a truncated file list. A bare number loses to a + branch of that name. No working `gh`, say so and take the branch. +- **Any other URL** — a ticket, a doc page. Fetch it, then check what came back is the + thing: an SSO wall returns a page rather than an error, and a login form skimmed as + content is how you question someone about a ticket you never read. Can't reach it, + ask them to paste the body; never infer contents from the slug. +- **Pasted text**, a diff or a document body — that's the artifact. +- **A feature in prose** ("how does billing work") — nothing to resolve; the + description is the brief for step 2. + +If it looks like a rev or a path and is neither, say what you tried and ask. + +Size it but don't read the body here — a diff you pull into the main session is one +you carry for the whole dialogue, which is the cost step 2 exists to avoid. So `git +diff --stat`, a file count, the length of what you fetched, and stop. Past roughly +1500 lines, ask for a narrower target: agents read the first part of something that +big and report back sounding complete. + +Then ask what they're about to do with it — review it, extend it, debug it, inherit +it. "Understand the billing system" is unbounded. "Understand it well enough to add a +discount code" has a floor and a ceiling, and it's what picks your questions in step 4 +and what step 5 measures against. If they can't say, which is often the honest answer +and the reason they're here, guess from the target and let them correct it. Don't +leave it blank; an unbounded session has no way to end. + +## 2. Ground truth before any questions + +Tell the user you're reading first, then launch subagents in parallel (`Explore`, or +`general-purpose`) and wait. They read while you stay out of the files: you spend +their context instead of yours, and what comes back is a fact sheet rather than a diff +you now have to carry. No subagents? Say plainly you're working off a timeboxed skim, +which is the weaker version of this. + +Capture the target once and hand every agent the same thing — a diff written to a temp +file (`mktemp`), a rev range, the fetched body, the paths. If they each resolve it +themselves, one reads the PR head while another reads your working tree, and the two +fact sheets disagree without either being wrong. + +Three angles, one agent each: what it does end to end; what it touches and what +touches it; and where it would surprise a competent reader — the branch that does the +opposite of its name, the retry that isn't idempotent, the guard covering one of two +paths. Tell that third one that "nothing here is surprising" is a real answer, because +an agent handed three vivid examples and no way to come back empty invents a fourth, +and you'll build a question on it. + +Point them at the code, not at the document. A ticket, SPEC, or PR description is a +claim about intent; what the code does is ground truth, and the gap between the two is +usually why the user is confused. When the feature only half exists, the angles shift +to what's built, what the closest finished feature looks like, and what's missing — +questioning someone about the missing half as though it were there is the preamble's +second failure with extra steps. + +Ask each for **claims with a citation you can open** — `<file>:<line>`, not prose. +You're going to contradict the user with these, and "this runs twice on every update" +is unusable where a file and a line number is something they can go look at. Ask too +what they _didn't_ reach, because a fact sheet that stopped early looks exactly like +one that found nothing there. + +If the thing isn't in this repo at all, say so before you start. You can still +question them off the document, but nothing you ask will be grounded, and they should +know that's the session they're getting. + +Up front, read five or so of the cited files and no more, or you've bought back the +context you sent them to save. Opening one file to check one claim mid-dialogue is a +different thing and always worth it. Either way, don't open with a summary. + +## 3. Ask what they already think + +First move, before you reveal anything: what do they think this does, and how? Being +wrong is the point — the gap between their answer and your fact sheet is the +curriculum. Fold the stakes question in here if you haven't asked it; both are +questions to them, so neither spends the blind opening. + +If the thing doesn't exist yet, ask what they think it'll take, or what the app +already does about it. "What does this do" is malformed for something unbuilt, and +asking anyway invites them to invent an answer. + +No model at all ("never opened this file")? Say so and hand them `/eli5`, which exists +for exactly this and explains rather than asks — then come back here. Questioning +someone about a thing they've never seen is a quiz, not a dialogue, and the smallest +orientation you could give them inside this session is a worse version of that skill. + +Model already sound? Say so and go to step 5. Manufacturing a gap so there's +something to do wastes their evening. + +## 4. One question at a time + +One question per turn, and no turn of yours runs past four sentences — question or not, +correction or not. The cap is on the turn rather than the prose before the question +mark, because appending a question doesn't undo a lecture and every bullet below is +otherwise a licence to write paragraphs. + +**Ask about consequences, not contents.** "What does the call on line 12 do?" is a +lookup with a right answer and they learn nothing from getting it. "Two people hit +save at the same second — which write wins?" makes them reason with the model they +actually hold, and the answer shows you whether it's sound. Good questions live at +boundaries: concurrency, failure, empty input, the second caller, the day this data +doubles. Pick which boundaries from step 1 — the ones the discount code hits, not +every boundary the subsystem has. + +**Never ask about something you haven't verified.** Verified means a path you opened, +not one you reasoned your way to and not one a subagent handed you that you took on +trust. A fact sheet is a lead; a citation you didn't check makes a wrong claim _more_ +credible rather than less. But what needs verifying is the premise, not the answer: +"which write wins?" has no citation and shouldn't, because it's the consequence you're +asking them to reason to. What needs a path is the claim that two writes can race here +at all. Confuse the two and you'll only ask what you can point at, which is contents, +which is the quiz. If a question needs a fact you don't have, dispatch for it and ask +something you already have grounded in the same turn, so the fetch runs while they're +answering. + +**When they're wrong, show rather than tell.** Point at the line and let it do the +work: "open `<the file you found>` at line 31 — what happens when the second one +starts?" A correction they derive sticks; one you announce gets nodded at. If the same wrong +belief survives the line twice, the line isn't landing — say it plainly and move on. + +**When they contradict the fact sheet, open the file.** They may well be right: they +work here and a subagent skimmed. Report what you find either way, including that +recon had it wrong. + +**When they're half right, name the half that holds and drill the half that doesn't.** +This is the common answer and where lectures get born, because correcting a near-miss +feels like it needs a paragraph. It needs a question. + +**When they're stuck, don't wait them out.** "I don't know" means the question was too +wide, not that they failed. Narrow it, or hand over one fact and ask again. + +**When they ask you something, answer it** — straight, from ground truth, with the +path. Go get it if you don't have it. Volleying back another question is a party trick +and it costs you their trust. + +**When they ask you to just explain it,** say in one line what they'd lose and then do +it if they still want it. This is their time, and arguing with them about pedagogy is +worse than being an explainer. Only act on the request when they make it — short +answers aren't it. Five correct one-liners is a competent person typing fast, and +reading that as a plea for a lecture takes the method away from the user it's working +best for. If you think they've checked out, ask. + +## 5. Stop when they can predict it + +The tell is them calling a consequence you never covered, correctly, without being +pointed at anything first. Two of those and you're done. Measure against step 1 — +enough to add the discount code, not enough to have read the whole subsystem. + +If that hasn't happened by around eight substantive questions, stop anyway and say +where they got to; understanding that hasn't landed by then needs a different approach +rather than more questions. Filler questions asked while a fetch was running don't +count — they bought time, they didn't teach anything. + +Close in under ten lines: the shape of what they now know, what you left out because +step 1's task didn't need it, and what neither of you could establish — recon's gaps +plus whatever the code doesn't answer. A hole you name is one they can go ask a human +about; a hole you paper over is one they walk into.