
turbo
A human-gated agentic software factory: you decide what to build and judge the result, while skills shape, build, polish, and ship the change, and learn from it.
- GitHub stars
- 422
Install
/plugin install turbo@turboRun it inside Claude Code after adding the marketplace with /plugin marketplace add tobihagemann/turbo.
Contents
Discovered from sourceSkills 73
Apply Findings
Apply evaluated findings from the conversation context. Findings must have been through /evaluate-findings first.
Step 1: Identify Findings
Collect all findings from the conversation context. Findings should have Verdict columns (Apply, Skip, Escalate) from /evaluate-findings.
If findings are unevaluated (raw output without verdicts), stop and say to run /evaluate-findings first.
Step 2: Apply in File Order
Group Apply findings by file path and apply in file order to minimize context switching. For each finding:
- Read the full function or logical block at the referenced location
- Verify the finding still applies to the current code
- Before applying a fix that stops a failure, whether the finding suggested it or you derived it, confirm the fix makes the failure the finding describes unreachable from every code path that can produce it, rather than only defeating the finding's reproduction: search for paths other than the one the finding names that reach the same root cause, including other operations that consume the same state or input and surface that cause as a different failure, and include each in the fix or name what keeps it from reaching that cause; construct an input that clears the point the fix guards, trace whether it still reaches that failure further along, and write any regression test the fix adds from that input. When the fix encodes, escapes, quotes, or otherwise sanitizes untrusted input, construct such inputs from every character class the target interpreter treats specially and name what in the fix blocks each one; a class with no blocker means the fix is incomplete, including when it reproduces the finding's suggested wording. When the finding carries a suggested fix, also treat the fix as a separate claim from the finding and verify it independently — trace it against the failure modes the finding names, then against the behavior the code had before the fix on inputs the finding never mentioned, since a remedy can address the named mode while regressing an axis alongside it. Where the finding arrives with opposing remedies recorded, verify the measured one first, and where none was measured, measure before applying rather than choosing on the proposer's authority. When a fix removes a guard, check, rule, fallback, or retry as unreachable or redundant, including one you chose to remove while applying a fix, and the evidence is a comparison of runs with and without it, those runs must include the inputs it exists for, built on purpose where the condition it protects is hardest to meet, unless the evaluation already ran them. Runs that never reach those inputs leave the removal unsettled, and an unsettled removal does not hold up. If a suggested fix does not hold up, treat the finding as Escalate (surface it in Step 3) and record why the remedy fails, rather than applying an unsound fix on the finding's authority. If a fix you derived does not hold up, revise it, and when no revision holds up, treat the finding as Escalate (surface it in Step 3) and record why.
- When the fix would reverse a decision the user made earlier — in discussion or recorded in the artifact — treat the finding as Escalate (surface it in Step 3) and name the original decision. Judge by the outcome rather than the wording of the option the user chose: a reversal leaves the user with something materially different from what they chose. When the finding refutes only the factual premise the user's choice rested on and the fix leaves the chosen outcome intact, that is a premise correction: confirm the refutation against whichever of the code, the governing artifact, or authoritative documentation the premise turns on, and when none settles it, treat the finding as Escalate. Otherwise continue with the remaining checks, and state both the corrected premise and the chosen outcome it leaves standing in Step 4.
- Check what the fix you are about to make changes about the inputs the code accepts. When the change in accepted inputs is exactly the defect the finding names, continue with the remaining checks. When it turns away or newly admits anything beyond that defect — a value or path a legitimate caller could send — that is a behavior change: treat the finding as Escalate (surface it in Step 3) and name the input class that changes.
- Check whether the fix you are about to make adds machinery the evaluated finding does not name: a lease, lock, queue, versioning scheme, state machine, or new persistent entity. A fix that specifies such machinery in a plan adds it, the same as one that writes it into code. When the fix adds any, treat the finding as Escalate (surface it in Step 3) and name the machinery.
- Make the fix
- If the finding renames an identifier, changes a recurring shape — a type signature, call pattern, or wrapper that appears in many places — or corrects a stated claim about what something does or guarantees, search every caller, reference, and restatement the change reaches, not only the changed files, by concept rather than by the literal just replaced: a stem that survives inflection and compounding, the shape common to every variant, or the claim itself in whatever words a comment, document, or instruction file restates it. A clean search proves nothing when its pattern was derived from a single instance, and the cited location is often only one of several references. When the finding names several sites, also tick them off against the finding text. Complete the sweep, bringing every site it finds in line with the fix, before marking the fix complete.
- When the fix adds or edits a comment stating a contract — what is handled, what is excluded, what callers may rely on — verify the code enforces that contract before marking the fix complete. When it does not, add the enforcement rather than narrowing the comment.
If a finding references code that has changed since it was generated (e.g., by a prior fix in this same run), re-assess whether it still applies. Skip if the code has diverged.
When a finding reports a failing check, fix what the check reports and leave the check as strict as it was: disabling, skipping, or retrying a test, disabling or downgrading a rule, lowering a threshold, or widening an ignore or exclude list fixes nothing. When the check itself is wrong for the code, treat the finding as Escalate (surface it in Step 3) with the evidence. When the check gates only on new or changed code, leave every line the fix does not need as it is, and name any wider rewrite you left out, such as matching the rest of the file, in the finding's Outcome cell.
When an escalated finding's outcome would change what the other fixes should look like, settle it in Step 3 before applying them.
Step 3: Handle Escalated Findings
For findings with Escalate verdict, use AskUserQuestion to let the user decide. Output the finding's technical detail as text first, including the fact that forces the choice, then state the question as the decision the user owns. When the choice changes what the software does for the person using it, open that detail with the behavior that person gets under each option and the goal it serves, before any mechanism terms. When the finding is a disagreement between two artifacts, first establish which artifact changed last and which one the code or content that consumes them follows today. Include that in the detail and weigh it in the recommendation, then ask which behavior is wanted; reconciling the artifacts follows from that answer.
Recommend the genuinely best option: place it first and append (Recommended) to its label, judging "best" on technical merit alone (the soundest engineering outcome), independent of how closely the option conforms to the task's original scope. Reserve the Note for later recommendation for a fix that is not ready to make: it needs design work of its own, or rests on a cause or fact this session cannot establish. Name what it waits on in that option's description. Treat a finding being pre-existing or outside the changeset as a scope cost to state beside the recommended option, with no bearing on which option that is. When the choice hinges on product intent or domain knowledge you lack and merit cannot settle it, say so instead of forcing a pick. Where an established convention answers a visual or interaction choice, that settles it: recommend the option that follows the convention and name it. Take the project's own treatment of like elements ahead of the platform's, and the platform's ahead of general practice. Give each option a plain-language description that carries the trade-off: its concrete effect and what it costs. Before asking, confirm every claim a description makes about what its remedy does, including its effect on legitimate callers and what it leaves untouched, the way Step 2 items 3 and 5 check a fix. Correct a claim that check contradicts. When the check needs material this session has not read, read it. Mark as unverified in that description only a claim this session cannot establish, and leave (Recommended) off the option whose remedy it describes. When a tool available in this session can carry out the remedy directly, make that action the Apply option rather than tooling that would carry it out later, and name in its description the system it acts on and whether the action can be undone. When the recommended option also widens the changeset's scope, name both its merit and that scope cost so the user can weigh them. When an earlier escalation already widened the changeset, state the running total alongside this option's increment. When the choice is costly to reverse — it establishes a pattern others will follow, defines an interface, or commits to a data shape — include the consultation option alongside the concrete alternatives, labeled "Get a second opinion". Include it as well whenever no option earns (Recommended) with conviction, and whenever the finding names a defect in a fix this session made earlier.
- Apply — make the change, then run Step 2's post-fix checks (items 8 and 9) against it
- Skip — leave as-is
- Note for later — run the
/backlogskill to capture it - Get a second opinion — run the
/consult-codexskill for a second opinion on the choice, or the/consult-oracleskill when standard approaches have already failed. Then apply, skip, or note the finding with that answer in hand
After an escalation resolves, hold every other decision the user made earlier, in discussion or recorded in the artifact, against that resolution: re-read what the decision was recorded or described as depending on. Where the resolution takes away a part of the design it depended on, name that part and use AskUserQuestion to re-ask the decision, under this step's rules for framing a question and its options. Bring the artifact in line with the answer, then run Step 2's post-fix checks (items 8 and 9) against that edit.
Step 4: Format Output
Report the outcome as a table, one row per finding, keeping every cell to a single line:
| File | Finding | Outcome |
|---|
Where Outcome is one of:
- Applied — the fix was made
- Escalated — name the resolution the user chose: applied, skipped, or noted for later
- Skipped — name the reason
Keep the report to the table. Add prose only where an escalation's resolution changed what the other fixes look like, where it led to re-asking an earlier decision, or where a fix corrected the factual premise a user's choice rested on. For a re-asked decision, name the decision, the part of the design the resolution took away, and the answer.
Then use the TaskList tool and proceed to any remaining task.
Rules
- Only edit files, except for a direct action the user chose as Apply in Step 3 and the runs Step 2 item 3 calls for. Make those runs before the edit they verify, in a temp directory outside the repo or in an isolated
git worktreecreated there with its own dependency install and discarded afterward. Do not stage, build, or test the shared working tree.
Assess Technical Debt
Surface the structural debt that routine review keeps out of scope: long-lived complexity, deprecated APIs, duplication, tangled architecture, and low-value tests that need deliberate refactoring. Project-wide, analysis-only. Ranks each finding by impact and effort and writes .turbo/technical-debt.md and .turbo/technical-debt.html.
Task Tracking
At the start, use TaskCreate to create a task for each phase:
- Scope and partition
- Run debt analysis agents
- Run
/evaluate-findingsskill - Resolve escalated findings
- Rank and write markdown report
- Generate HTML report
- Offer backlog capture
Step 1: Scope and Partition
If $ARGUMENTS specifies paths, assess those directly (skip the question).
Otherwise, use AskUserQuestion to confirm scope:
- Whole codebase — assess all source and test files
- Specific paths — user provides directories or file patterns
Once scope is determined:
- Glob for source and test files in the selected scope. Exclude generated and vendored directories (
node_modules/,dist/,build/,vendor/,__pycache__/,.build/,DerivedData/,target/,.tox/, and others appropriate to the project). - Partition files by top-level directory. If a single directory holds far more files than its siblings, sub-partition it by its immediate subdirectories.
Step 2: Run Debt Analysis Agents
Before dispatching, read the project's test configuration and CI workflow to identify any test tier that resets a shared external resource between tests, such as a database, a fixed port, or a cache. Such tiers have no cross-process interlock, so agents running them concurrently wipe each other's state and return failures that look like real defects. Name any such tier to every agent as off-limits.
Emit all Agent tool calls below in one assistant message. Each Agent call uses model: "opus" and no name. Wait for every agent to report before continuing. Do not begin the next step on a partial set, and do not relaunch an agent that has not yet reported. Every agent's prompt must direct it to omit name on any Agent tool call it makes itself. Each Agent's prompt instructs it to read ${CLAUDE_SKILL_DIR}/references/debt-reviewer.md for the debt taxonomy, detection heuristics, the impact/effort rubric, and the finding output format before scanning, and to treat the shared working tree and its git index as read-only — any empirical check runs in an isolated git worktree created under $TMPDIR and discarded afterward. Every agent's prompt must also direct it to search the repository with a tool that skips gitignored files, such as git grep --untracked or the Grep tool, and to open or search a gitignored path only when its prompt or a file its prompt directs it to read names it, or when a dependency's installed source is needed to verify a claim, never one holding local configuration or credentials. Each agent keeps the scratch files it writes, such as its starting git status snapshot, probes, and logs, in a scratch directory of its own, uniquely named under the session scratchpad directory, and refers to it by absolute path. HEAD stays where it is: read other refs with git show <ref>:<path> rather than git checkout or git switch. Refer to that worktree by absolute path in every command and join chained steps with &&, so a failed step cannot leave the rest running in the shared checkout. Run teardown and verification as their own commands. Give that worktree its own dependency install rather than reaching the shared tree's install by any route: removing a worktree deletes through symlinks, and a redirected suite writes into the shared install. When its own install is not possible, the check is left unrun and reported as such. Every test runner the agent starts, in a worktree or in the shared checkout, runs in its own process group under a timeout enforced from outside the runner. Before teardown, the agent stops the process group of every runner it started, since stopping a runner can leave the processes it spawned alive. Afterward the agent verifies that git worktree list no longer shows the worktree, that git status --short shows what it showed at the start, that HEAD is still on the branch it started on, and that the shared tree's dependency directory still resolves (a destroyed install leaves git status unchanged, since it is gitignored). It also confirms that no process from those groups, and none whose command line names the worktree path, if any, is still running, and reports by PID any process it could not stop. When it cannot list processes, it reports that check as unrun and names those process groups and the worktree path, if any. Damage the agent cannot repair is reported with the exact repair command in place of findings.
Expect (one per partition, plus one project-wide architecture agent) Agent tool calls total. State the count explicitly when emitting the calls.
- Partition agents — one per partition from Step 1. Each scans its files for complexity hotspots, deprecated API usage, duplication, and low-value tests, and notes coupling it observes reaching outside the partition. Pass the partition's file list and the full project root path.
- Architecture agent — one project-wide pass over the scoped tree for architecture rot: tangled module boundaries, circular dependencies, layering violations, and refactor candidates that span modules. Pass the partition map and the full project root path.
If more partitions exist than fit a single fan-out, group related directories so the partition agents stay within a manageable batch, and note the grouping in the report.
Step 3: Run /evaluate-findings Skill
Aggregate all findings from all agents. Deduplicate items that surface in more than one agent (e.g., duplication a partition agent and the architecture agent both flag). When several agents report the same blocking check, merge them into one finding whose baseline combines their sites. Run the /evaluate-findings skill once on the combined set to verify each finding against the actual code and weed out false positives.
Step 4: Resolve Escalated Findings
Skip when Step 3 assigned no Escalate verdict.
For each finding with an Escalate verdict, output its technical detail as text first, including the fact that forces the choice. Then use AskUserQuestion to state the question as the decision the user owns, offering the report outcomes the finding leaves open:
- Rank as debt — the finding enters the priority matrix with its recommended refactor. When the finding carries competing refactors, offer each as its own option.
- Record as intentional — the finding stays out of the priority matrix and is listed with the decision
- Get a second opinion — run the
/consult-codexskill for a second opinion on the choice, then ask again with that answer in hand. Offer it when the choice is costly to reverse (it establishes a pattern others will follow, defines an interface, or commits to a data shape), and whenever no option earns(Recommended)with conviction.
Place the strongest option first and append (Recommended) to its label. When the choice hinges on product intent or domain knowledge you lack, say so instead of forcing a pick. Keep the question within four options: when the outcomes exceed that, offer the ones that fit the finding best, with the consultation option among them when it applies.
Step 5: Rank and Write Markdown Report
Assign each surviving finding an impact (maintenance drag, change risk, blast radius) and an effort (rough refactor size) per the rubric in references/debt-reviewer.md. Sort findings into priority tiers:
- Quick wins — high impact, low effort
- Strategic refactors — high impact, high effort
- Incremental — low-to-medium impact, low effort
- Defer — low impact, high effort
Leave a finding recorded as intentional in Step 4 out of the Summary counts and the Priority Matrix, and list it under its dimension in Detailed Findings with that decision. Record the decision beside each escalated finding ranked as debt as well.
Output the summary and priority matrix as text. Then write .turbo/technical-debt.md using the template below.
Report Template
# Technical Debt Assessment
**Date:** <date>
**Scope:** <what was assessed>
## Summary
| Dimension | Findings | High impact |
|---|---|---|
| Complexity hotspots | <N> | <N> |
| Deprecated API usage | <N> | <N> |
| Duplication clusters | <N> | <N> |
| Architecture rot | <N> | <N> |
| Low-value tests | <N> | <N> |
## Priority Matrix
Ranked by impact against refactor effort. Take quick wins first; schedule strategic refactors deliberately.
### Quick Wins (high impact, low effort)
| Item | Dimension | Location | Recommended refactor |
|---|---|---|---|
### Strategic Refactors (high impact, high effort)
| Item | Dimension | Location | Recommended refactor |
|---|---|---|---|
### Incremental (low–medium impact, low effort)
| Item | Dimension | Location | Recommended refactor |
|---|---|---|---|
### Defer (low impact, high effort)
| Item | Dimension | Location | Recommended refactor |
|---|---|---|---|
## Detailed Findings
### Complexity Hotspots
<findings: location, description, impact, effort, recommended refactor, and the recorded decision for an escalated finding>
### Deprecated API Usage
<findings>
### Duplication Clusters
<findings>
### Architecture Rot
<findings>
### Low-Value Tests
<findings>
---
This assessment covers in-code structural debt. For dependency freshness and diff-scoped bugs, run `/review-dependencies` and `/review-code`.
Step 6: Generate HTML Report
Convert the markdown report into a styled, interactive HTML page.
- Read
.turbo/technical-debt.mdfor the full report content. - Write a self-contained
.turbo/technical-debt.html(single file, no external dependencies beyond Google Fonts) that presents all findings from the markdown report with:- Summary grid with per-dimension finding counts
- Priority matrix laid out as an impact-by-effort quadrant, color-coded by tier (quick wins highlighted)
- Sticky navigation between sections
- Collapsible dimension sections
[hidden] { display: none !important; }in the base styles, so a section whose own CSS sets adisplayvalue still hides- Finding cards with location, impact, effort, recommended refactor, and the recorded decision where one exists
- Impact and effort badges with color-coding
- Entrance animations and hover states
- Print-friendly styles via
@media print - Responsive layout for mobile
Step 7: Offer Backlog Capture
Skip the question when the Priority Matrix holds no finding.
Use AskUserQuestion to ask which findings to track in the backlog:
- All ranked findings (Recommended) — every tier of the Priority Matrix becomes backlog entries
- High impact only — Quick Wins and Strategic Refactors become backlog entries, and the rest stay in the report
- Keep the report only — the backlog stays unchanged
On either capture answer, sort the chosen findings into entries: group low-to-medium-impact findings that share a dimension and an area of the codebase into one entry, and give every other finding an entry of its own. Have every entry name the report items it covers, so it traces back to .turbo/technical-debt.md. Run the /backlog skill once for each entry. When /backlog wrote at least one entry, tell the user they can run /turbo:implement-backlog to work through them.
Then use the TaskList tool and proceed to any remaining task.
Rules
- Analysis-only: do not modify source code, stage files, or commit.
- If no significant debt is found, report that explicitly and note any scope limitations or analysis caveats.
Backlog
Capture improvement opportunities discovered during work so they don't get silently dropped. Appends to the .turbo/backlog.md file of the repo an improvement concerns.
Step 1: Locate the Backlog File
Each repo keeps its backlog at .turbo/backlog.md relative to that repo's root. Resolve that root with git -C <repo path> rev-parse --show-toplevel, except inside a linked worktree — where git -C <repo path> rev-parse --git-dir differs from --git-common-dir — in which case use the parent of the common dir, so the entry lands in the main checkout rather than in a worktree that is destroyed with its branch.
Step 2: Identify the Improvement
Gather from context or $ARGUMENTS:
- What: One-line summary of the improvement
- Type: One of
direct,investigate, orplan— see criteria below - Category: One of
refactor,performance,reliability,readability,testing,docs,dx(developer experience), orfeature - Where: File path(s) and/or area of the codebase affected
- Why: Brief rationale — what's the benefit? For a defect or risk, whether it was observed in use or derived from reading code or a review.
- Ceiling and Revisit: when the entry records a deliberate simplification, meaning a simpler approach was shipped in place of a fuller one and accepts a known limit — the limit the shipped approach accepts, and the condition that makes the fuller version worth building. Revisit alone when the entry waits on an outside event: that event
Type criteria
- direct — Clear scope and a known approach, ready to apply via
/implement. - investigate — A symptom that needs root-cause analysis first: unclear root cause, performance question, intermittent bug, "something feels off".
- plan — Everything else: the approach warrants writing down before implementing (multi-file refactor, test additions, feature work).
When the criteria above clearly select one value, use it. Otherwise, use AskUserQuestion to confirm; default to plan if the user declines to choose.
Step 3: Route and Append
- Append the entry to the
.turbo/backlog.mdof the repo whose files its Where names, which may not be the current repo. - When Where spans several repos, split it into one entry per repo and append each to its own repo. Give every entry the titles of all its counterparts so a reader of any one backlog finds the others.
- Rewrite each split entry's Where so its paths read repo-local, matching the entries already in that backlog. Qualify any remaining reference that resolves only in another repo with the repo it lives in.
- When a target repo's checkout cannot be found on disk, use
AskUserQuestionto ask where it is cloned, offering as the alternative to note its entry in the backlog of the repo root resolved in Step 1. Given a path, route the entry to the repo at that path. Without one, say that the checkout was not found and append the entry to that backlog, naming the repo it was meant for. - Write to any path outside the current working directory with the Edit or Write tool, the main checkout of the worktree this session runs in included. The Bash sandbox denies a shell append there, and a separately-issued verification command then prints the file's unchanged contents, which reads as success.
- When that write is refused while this session runs inside a linked worktree, report that the entry cannot be persisted from here and print the fully formatted entry so it can be pasted in from a session that can write to the main checkout. Leave it out of the worktree's own
.turbo/, which is gitignored and is destroyed with the worktree.
When a target repo holds the legacy .turbo/improvements.md, carry it into that repo's .turbo/backlog.md before reading, with the Write or Edit tool. When .turbo/backlog.md does not exist, write the legacy content there with its # Improvements header changed to # Backlog. Otherwise, append each legacy entry that .turbo/backlog.md does not already hold word for word. Once .turbo/backlog.md holds every legacy entry, delete the legacy file. When the write or the deletion is refused, tell the user what is left to do.
Read .turbo/backlog.md in each target repo if it exists. Create it with the header below if it doesn't.
File header (only when creating new):
# Backlog
Out-of-scope improvement opportunities captured during work sessions. Review periodically and pull items into active work when appropriate.
Entry format:
### <one-line summary>
- **Type**: <direct | investigate | plan>
- **Category**: <category>
- **Where**: `<file path or area>`
- **Why**: <brief rationale>
- **Ceiling**: <limit the shipped approach accepts>
- **Revisit**: <condition that makes the fuller version worth building>
- **Paired with**: <repo> — <title of the counterpart entry>
- **Noted**: <YYYY-MM-DD>
Include the Ceiling and Revisit lines when the entry records a deliberate simplification, the Revisit line alone when the entry waits on an outside event, and a Paired with line per counterpart when the entry is one half of a split; omit them otherwise. Append the new entry at the end of each target file.
Step 4: Confirm
Tell the user the improvement was noted and where each entry was written, or that it could not be persisted and is printed above.
Then use the TaskList tool and proceed to any remaining task.
Rules
- Deduplicate before appending: search each target backlog for the paths and symbols the new entry names and for entries on a similar subject, and update an existing entry in place when it covers the same improvement. When the existing entry predates the Type field, add a Type line while updating. Remove any Validated line from the updated entry, with the command lines nested under it.
- When updating an existing entry tagged with the legacy values
trivialorstandard, rewrite the Type todirectorplanrespectively so the file converges on current vocabulary. - Keep entries concise. These are backlog items, not specs.
- When a deliberate simplification's revisit condition is not yet knowable, record what would have to be observed to know it.
- Record only; leave action to the user, who decides when to address it.
- When a target repo has no
.turbo/directory, useAskUserQuestionto confirm the location before creating one.
Changelog Rules
The changelog is kept in CHANGELOG.md at the project root. The format is based on Keep a Changelog, and projects using these conventions adhere to Semantic Versioning.
File Structure
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.2.0] - 2024-03-15
### Added
- Add dark mode support ([#38](https://github.com/owner/repo/issues/38), [#42](https://github.com/owner/repo/pull/42))
### Fixed
- Fix crash on startup ([#40](https://github.com/owner/repo/issues/40), [#43](https://github.com/owner/repo/pull/43))
[Unreleased]: https://github.com/<owner>/<repo>/compare/v1.2.0...HEAD
[1.2.0]: https://github.com/<owner>/<repo>/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/<owner>/<repo>/releases/tag/v1.1.0
Changelog-Worthiness
Not every change belongs in a changelog. Changelogs are for humans, not machines.
Skip changes that are purely internal:
- Refactoring with no user-facing impact
- Code formatting, linting, whitespace
- Test additions or modifications (unless they indicate a fixed bug)
- CI/CD configuration
- Developer tooling (linters, editor config)
- Documentation updates (README, comments, docstrings)
- Dependency bumps with no behavior change
Include changes that affect users:
- New features or capabilities
- Changes to existing behavior
- Deprecated or removed functionality
- Bug fixes
- Security patches
Entry Format
- Imperative present tense without trailing periods (e.g., "Add dark mode support")
- One bullet point per distinct change
- Concise but complete. Include enough context that users understand the impact.
User-Centric Writing
Entries describe what changed for the user. Focus on outcomes and impact.
- Lead with a user-visible verb: "Add", "Fix", "Improve", "Allow", "Prevent", "Show", "Check". Avoid developer-centric verbs like "Enforce", "Implement", "Refactor", "Handle", "Register".
- Describe the experience, not the mechanism. "Show grouped notifications: the list buckets items by source before rendering" carries the mechanism after the colon; "Show notifications grouped by the app that sent them" states only what the user gets.
- When a change prevents a problem or protects the user, say what it does for them.
Net Delta from the Last Release
Entries describe the change relative to the last released version.
- Judge each entry by whether a user of the previous release would observe the change. "No longer does X" or "removed the Y glitch" where X or Y never shipped is the obvious tell.
- A positively-phrased entry hides the same trap. "Allow renaming saved filters straight from the list, so fixing a typo takes one click" reads like a real improvement, yet it belongs to the feature when saved filters themselves arrived in the same unreleased cycle.
- When finalizing a release, compare the behavior at the last release tag against the behavior today:
git show <last-tag>:<path>, plusgit log --follow -- <path>when the file moved. A path that exists at the tag settles nothing on its own, since new behavior often lands in files that were already there. - When the behavior an entry describes arrived after the tag, rewrite the entry as the net capability, fold it into whatever introduced that behavior, or drop it.
- Keep one entry per net user-visible change.
PR and Issue References
Reference both the PR and any associated GitHub issue in each entry using inline parenthetical format with linked numbers in ascending order.
- Add dark mode support ([#38](https://github.com/owner/repo/issues/38), [#42](https://github.com/owner/repo/pull/42))
To discover associated issues for a PR, run:
gh pr view <number> --json closingIssuesReferences --jq '.closingIssuesReferences[].number'
- If there is no associated issue, reference only the PR
- If there is no PR (e.g., backfilling from git tags), omit references
Change Types
Standard types in this order when present: Added, Changed, Deprecated, Removed, Fixed, Security. Omit empty sections.
Section Format
- Unreleased section always present at the top
- ISO 8601 dates (
YYYY-MM-DD) - Reverse chronological order (newest first)
- Blank line between each section header and its content
- Version comparison links at the bottom, derived from the repository's remote URL
- Detect whether the project uses
v-prefixed tags (e.g.,v1.0.0) or bare tags (e.g.,1.0.0) and match that convention in comparison links
Code Style: Exist, Reuse, Mirror, Symmetry
When writing new code in an existing codebase, work through these in order. When two pull in different directions, the earlier one wins.
- Establish that the code needs to exist: Drop work the request does not need — an abstraction with one implementation, a configuration point with one caller, a branch for a state the callers cannot reach, scaffolding for an anticipated requirement. Deleting or narrowing beats adding. Before removing code that already exists, trace its callers and confirm nothing depends on the behavior. A new test must earn its place too: before adding one, name the behavior it protects and the credible regression that makes it fail, and confirm no existing test already fails on that regression. When a mutation run checks the new test, read every test that fails under it, not only the new one: if existing tests also fail, keep the new test only for a regression they miss. When an existing test covers the same contract, extend its cases instead. Drive the test through a boundary production code already uses rather than adding an export, flag, or hook that only the test calls. A test pins the behavior it is named for: when one you add or change also covers another behavior only through how it is set up, give that behavior its own test unless another test already fails when it breaks, and set the first test up the way its siblings are. Input validation at trust boundaries, error handling that prevents data loss, security controls, accessibility affordances, and anything explicitly requested outrank this rule.
- Reuse existing code: Before writing a new helper, check if an existing method can be reused or generalized. If a new helper is needed, model it after its closest sibling that is not debt (as rule 3 defines it).
- Reuse existing patterns: Find the closest analogous feature and replicate its structure (method decomposition, control flow, annotations, guard clauses). When an existing pattern fits, use it rather than introducing a new one. When following it would force materially more code or indirection than a different approach, take the different approach and apply it across the whole change. Treat as debt a workaround for a problem inside the codebase, a deprecated API with a usable replacement, a suppression directive with no stated reason, or a TODO marking code temporary. When the closest analog contains debt, replicate its structure without the debt; when its structure is the debt, pass over it and follow the next clean one, and when none is clean, write the clean form, marking any workaround it cannot avoid as rule 7 directs. Name each skipped analog and omitted piece of debt when you report the change.
- Mirror the surrounding code exactly: Match brace style, comment style, naming conventions, blank line spacing, code density, and level of detail by reading nearby code first.
- Maintain symmetry: If adding
fooB()parallel tofooA(), match naming, parameter order, and structure. Symmetry covers every name the new sibling makes asymmetric: identifiers, route paths, config keys, event names, environment variables, CLI flags, and file naming schemes. Rename the existing name by default; keep it as it stands only when it is a published contract whose consumers you cannot update, or cannot update in step with the rename. Treat deployment and registration as costs the change absorbs: updating every place the name is referenced or registered is part of the change. - Logical ordering: Place new methods, switch cases, and fields in the order that mirrors the existing grouping or business lifecycle, rather than appending at the end.
- Default to no comment: Write code that self-explains through naming, extraction, and structure. When you reach for a comment, first try refactoring so it becomes unnecessary. Add one only for a load-bearing constraint the code cannot express (a hidden invariant, a workaround for a defect outside the codebase, with a reference to that defect where one exists, a non-obvious performance characteristic). For a problem inside the codebase, fix the root cause rather than writing a workaround with a comment justifying it. When that fix is out of reach, mark the workaround with a TODO that names the root cause and gives no reason the workaround is acceptable, and name it as debt when you report the change. When in doubt, omit the comment.
Codex Exec
Autonomous task execution via the codex CLI. Runs non-interactively. Progress streams to stderr; final result on stdout.
codex exec --skip-git-repo-check "task description" < /dev/null
For large context, pipe it via stdin. The prompt stays as the argument, context is passed as <stdin> automatically:
cat context.txt | codex exec --skip-git-repo-check "question about the context"
Route text you did not author through this channel whatever its size — a diff, file contents, a code comment, a plan or spec, third-party feedback, command output. Write the context file with the Write tool so nothing is interpreted on the way in. Keep backticks, $, and straight double quotes out of the quoted argument even in text you wrote: the first two stay live inside it, and a double quote ends it. When the prompt itself must carry any of them, as when it quotes a title or a passage, write the whole prompt and its context to one file with the Write tool and pass -, so stdin is the entire prompt:
cat prompt.txt | codex exec --skip-git-repo-check -
Sandbox
All codex Bash calls require dangerouslyDisableSandbox: true (network access to OpenAI API). Without it, codex crashes with an Operation not permitted panic from the system-configuration crate before the model runs.
Git Repository Check
Every codex exec invocation requires --skip-git-repo-check, resume turns included. Outside a git repository codex aborts before doing any work, printing Not inside a trusted directory and --skip-git-repo-check was not specified., and never writes the -o file.
Stdin Gotcha
Codex reads from stdin whenever stdin is non-TTY (per codex exec --help: "If stdin is piped and a prompt is also provided, stdin is appended as a <stdin> block"). In subagent and subprocess contexts the harness leaves stdin connected to a pipe that never EOFs, so a bare codex exec "..." hangs forever, printing only Reading additional input from stdin....
Always redirect stdin on non-piped invocations:
codex exec --skip-git-repo-check "task description" < /dev/null
The piped form (cat context.txt | codex exec "...") is safe — cat closes the pipe after the file, sending EOF.
Synchronous Execution
Run codex via the Bash tool as a foreground call (do not set run_in_background). Set timeout: 600000, the foreground maximum. A larger value is not honored: the harness backgrounds the call immediately and hard-kills codex at 600s, truncating its output. Within a valid timeout, codex runs foreground and returns its result synchronously when it finishes in time.
Capture the session id: from the run's stderr chrome as it starts; it never appears in the -o file, and recovery depends on it. When filtering the run's output for it, use a filter that reads the stream to its end: one that exits early, such as grep -m or a trailing head, closes the pipe and kills the run. Do not pass --ephemeral when the run may need recovery, since it persists no session files.
Give every run its own absolute -o path, named with a random tag so that runs spawned concurrently and successive runs in an iteration loop cannot collide on a path each derived independently. Pass it absolute: a relative path resolves against a working directory that drifts over a session, so the run does its work and exits having written no final message (Failed to write last message file "<path>": No such file or directory). A reused path holds the prior run's complete output until the current run exits, so an early read returns well-formed output from the wrong run; a fresh path turns that same read into a detectable empty one. Treat content in the -o file as final only once the run has exited.
A run that outlives the timeout is normally force-backgrounded: the result carries a task ID and an output file path, and the run continues to completion. Recover it by reading the output file: Read the path, then Read it again once the <task-notification> reports completion.
Rarely the run is hard-killed instead, giving an error exit (code 143) reading Command timed out after <duration> with no task ID and no -o file. Do not re-run the prompt from scratch; that discards the work already done and hits the same ceiling. Resume the session with a fresh output path, asking for the findings as the final message rather than as a file write:
codex exec --skip-git-repo-check --sandbox <original-sandbox> -o <fresh-output-path> resume <session-id> \
"Reply now with your complete findings as your final message." < /dev/null
A resume turn takes its sandbox from its own command line rather than from the session, so pass the original run's --sandbox value again, ahead of the resume subcommand, which does not accept the flag after it. It takes its working directory the same way: when the original run passed -C, pass the same -C value again beside --sandbox. When the kill left no session id in hand, recover it from the newest ~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<timestamp>-<session-id>.jsonl (the id is the UUID in the filename), listing a single day directory so the ordering is right. --last in place of <session-id> also works when no other codex run is in flight. Do not consult ~/.codex/session_index.jsonl; it lags behind the rollout files.
A run can also exit 0 within the timeout without completing the task, its final message asking for authorization to take an approach its own instructions require it to clear first. Read the final message before treating the run as finished: the exit code and the well-formed message both read as success. Resume the session with the authorization as the prompt, per the form above, passing the --sandbox value the authorized approach needs and the original run's -C value when it had one. Do not re-run the original prompt; it reaches the same gate.
Never wait with Monitor (it returns immediately, and events that arrive after your final text are dropped), and never return the task ID, an interim file snapshot, or "Waiting for codex to finish" as the result — each is a false-empty return.
Transient Crash Retry
Re-run the command once when the Bash call returned an error exit with no stdout and no task ID. A timeout is not a crash: when the error text reads Command timed out after <duration>, resume the session per Synchronous Execution rather than re-running. An aborted git-repo check is not a crash either: when the error text reads Not inside a trusted directory and --skip-git-repo-check was not specified., add the flag per Git Repository Check and run again. Recover a force-backgrounded run per Synchronous Execution rather than retrying it. Keep the same prompt. Treat a second failure as final.
Treat models-manager and cache-TTL errors as non-fatal warnings. Read the error text for usage-limit and authentication signatures and report those without retrying.
Options
| Option | Description |
|---|---|
-m <model> | Model for the run |
--sandbox read-only | Analysis, code reading, generating reports |
--sandbox workspace-write | Editing files within the project |
--sandbox danger-full-access | Installing packages, running tests, system operations |
-C <dir> | Working directory for the run |
--json | JSON Lines output (progress + final message) |
-o <path> | Write final message to a file |
--output-schema <path> | Enforce JSON Schema on the output |
--ephemeral | No persisted session files |
--skip-git-repo-check | Bypass git repository requirement |
For fix or implementation tasks, default to --sandbox workspace-write so Codex can edit files. Use --sandbox read-only for analysis or research tasks. Pass --sandbox and no other permission flag. Omitting --sandbox falls back to the codex config and project trust level (trusted projects run workspace-write), so always pass the flag explicitly.
For scratch-workspace mode, a run that executes checks against a repository it must leave untouched, pass --sandbox workspace-write -C <scratch-dir>, where <scratch-dir> is a fresh empty directory under the session scratchpad directory. workspace-write makes the working directory and the temporary directory writable, so the repository stays read-only while tests that create temporary files run. The run starts outside the repository and loads none of its AGENTS.md files, so name the repository by absolute path in the prompt, along with any of its instruction files the run should follow. For a repository that itself sits under /tmp, /private/tmp, or the temporary directory, which stay writable in this mode, use --sandbox read-only instead.
Omit -m, leaving the run on codex's configured model. When the user named a model for this run, add -m <model> to every codex exec command in this skill, resume turns included, and pass the name verbatim.
Prompt Shaping
Codex uses XML tags in its own context scaffolding, so the model parses them natively. Structure prompts with XML tags for clearer responses:
<task>: The concrete job and relevant context.<structured_output_contract>: Required output shape, ordering, and format.<compact_output_contract>: Same purpose but for concise prose responses.<grounding_rules>: When claims must be evidence-based.<dig_deeper_nudge>: Push past surface-level findings to check for second-order failures.<verification_loop>: When correctness matters — ask Codex to verify before finalizing.
Instruct codex to carry out the task itself rather than delegating to a peer review or consultation skill that crosses back to Claude. The prompt has already crossed the tool boundary; a further crossing that fails mid-flight leaves this run holding a question instead of an answer.
Keep prompts compact, with tight output contracts. One clear task per exec call. For a large scope, instruct codex to report findings as it goes rather than verifying exhaustively before reporting, so a run that hits the timeout ceiling still yields usable output.
Parallel Execution
Codex supports parallel sub-agents via spawn_agent / wait_agent. The model will not fan out unless the prompt explicitly requests it. See references/parallel-execution.md for patterns and limitations.
Interpreting Results
- Exec output is a starting point, not a guaranteed solution
- Cross-reference suggestions with project documentation and conventions
- Test incrementally rather than applying all changes at once
- For file-editing tasks, always review the diff before committing
Commit Rules
Commit Message Rules
- Match the style from
git log -n 10 --oneline - Concise and descriptive
- Imperative mood, present tense
- Aim for ≤100 characters in the subject
- No commit description—summarize everything in the message
- Don't reference
.turbo/content (filenames, acceptance criteria, step numbers, headings) in commit messages..turbo/is gitignored, so these references would be opaque to anyone reading without local copies.
Technical Constraints
- Use
git commit -m "message"directly—do not use heredoc syntax (sandbox blocks temp file creation) - Never bypass commit signing (
--no-gpg-sign,-c commit.gpgsign=false). If signing fails, useAskUserQuestionto let the user resolve it—they may need to approve a key prompt.
Commit and Push
Step 1: Run /commit-staged Skill
Run the /commit-staged skill.
Step 2: Push
Push to the current branch's remote:
git push
Commit Staged Changes
Step 1: Run /commit-rules Skill
Run the /commit-rules skill to load commit message rules and technical constraints.
Step 2: Commit
- Changes are already staged and ready to commit
- Do not stage any files
- Keep the current branch and commit on it, including when it is the default branch
Consult Codex
Multi-turn consultation with Codex CLI. Maintains a conversation across multiple turns using session persistence.
Step 1: Gather Context
Identify the 2-5 files most relevant to the problem. Formulate a clear, specific question. Include what has been tried and relevant constraints.
Step 2: Start Session
Run codex exec with -o to capture the response cleanly. Default to -s read-only for safety. Use -s workspace-write when the consultation requires running code, inspecting an artifact passed by path, or reading files outside the workspace, and tell Codex to keep any scratch files it writes under .turbo/. Pass the same -s value on every resume turn of the consultation: a resume turn takes its sandbox from its own command line, and without the flag it falls back to the codex config, where a trusted project runs workspace-write.
Omit -m, leaving the consultation on codex's configured model. When the user named a model for this consultation, add -m <model> to every codex exec command in this skill, resume turns included, and pass the name verbatim.
All codex Bash calls require dangerouslyDisableSandbox: true (network access to OpenAI API). Use .turbo/ as the temp directory — it is in the working directory (sandbox-writable), gitignored, and avoids $TMPDIR path mismatches between sandbox and non-sandbox mode.
Every codex exec invocation requires --skip-git-repo-check, resume turns included. Outside a git repository codex aborts before doing any work, printing Not inside a trusted directory and --skip-git-repo-check was not specified., and never writes the -o file.
Non-piped codex exec invocations require < /dev/null to avoid hanging on stdin. Codex reads from stdin whenever stdin is non-TTY, and in subprocess contexts the harness leaves stdin connected to a pipe that never EOFs — codex blocks forever, printing only Reading additional input from stdin.... The piped form (cat file | codex exec "...") is safe — cat closes the pipe after the file.
Generate a random session tag at the start to keep files unique for parallel use, and print the absolute path prefix it produces:
CODEX_TAG=$(head -c 4 /dev/urandom | xxd -p) && mkdir -p "$PWD/.turbo/codex" && echo "$PWD/.turbo/codex/$CODEX_TAG"
Substitute the printed value for <prefix> in every later command of this consultation. Shell variables do not survive between Bash tool calls, and an earlier cd in a compound command leaves the session in a different directory, so a relative path resolves against that directory instead.
Number the -o file by turn — <prefix>-1.txt for the first, <prefix>-2.txt for the next, and so on. A turn that reuses the previous turn's path finds that turn's complete answer waiting there, so a read landing before the current turn finishes returns the wrong answer with nothing to mark it as stale.
codex exec --skip-git-repo-check -s read-only -o "<prefix>-1.txt" "<question>" < /dev/null
Prompt Shaping
Structure the question using XML tags for clearer Codex responses:
<task>: The concrete question and relevant context.<compact_output_contract>: Desired output shape and brevity requirements.<structured_output_contract>: Same purpose but for structured/schema responses.<grounding_rules>: When claims must be evidence-based (review, research, root-cause analysis).<dig_deeper_nudge>: Push past surface-level findings to check for second-order failures.<verification_loop>: When correctness matters — ask Codex to verify before finalizing.<merit_only>: When a recommendation is wanted, bar answers that appeal to scope.<verdict_line>: When the consultation runs until Codex approves, fix the line that ends every response and terminates the loop.<style_constraints>: When the answer must follow a house style, name the shapes that style forbids.
Example prompt for a diagnosis question:
<task>Diagnose why the auth middleware rejects valid tokens after the session refactor.</task>
<compact_output_contract>Return: (1) most likely root cause, (2) evidence, (3) smallest safe next step.</compact_output_contract>
<grounding_rules>Ground every claim in the provided context or tool outputs. Label hypotheses explicitly.</grounding_rules>
For correctness-critical questions, add <verification_loop> asking Codex to verify its answer before finalizing.
When Codex must judge claims against a source, state in <grounding_rules> whether the material provided is the complete source or an excerpt. When a verdict can turn on something being absent, provide the complete relevant sections: given an excerpt, Codex reports what the excerpt leaves out as unverifiable or missing. Pass the complete source, or its path for Codex to read, whenever it fits. When an excerpt is unavoidable, confirm before running that every passage the claims under judgment rest on made it into the material provided.
When the consultation concerns an artifact Codex can inspect itself, pass its path and let Codex choose how to inspect it, rather than attaching excerpts or other material extracted from it.
When a recommendation is wanted, add <merit_only>: state that "out of scope" or "leave it alone" is not an acceptable argument on its own, and that recommending no change must be justified on technical merit. Pair it with <compact_output_contract> demanding one pick per decision, the reasoning, and the strongest counterargument to that pick, with hedging across options ruled out. When the question lists options, state in that contract that the pick may be a named alternative outside the list when it is sounder than every listed option.
When the consultation runs until Codex approves, add <verdict_line>: require every response to end with exactly one fixed line stating the verdict, in a designated positive or negative form, carrying nothing else, and require the response to state before that line what the verdict rests on: the artifacts, sources, and checks inspected. Terminate the loop when that line reaches the positive form with that evidence stated, so a politely worded answer does not end it early and agreement does not go unrecognized. Pair it with <compact_output_contract> demanding that each finding ship a ready-to-paste replacement rather than an instruction, which keeps a round cheap enough to iterate.
When the consultation is a prose rewrite bound by a house style, add <style_constraints> naming the shapes that style forbids in the first prompt, so they do not have to be corrected across follow-up turns. Common ones: prefixing a summary with a grammatical subject the convention omits, expanding a pronoun to its full noun phrase at every occurrence, and splitting a sentence so a condition is restated in both halves.
Instruct Codex to answer the consultation itself rather than delegating to a peer review or consultation skill that crosses back to Claude. The prompt has already crossed the tool boundary; a further crossing that fails mid-flight leaves this run holding a question instead of an answer.
Keep prompts compact, with tight output contracts. One clear task per Codex turn.
For context that does not belong in the argument, write a context file with the Write tool and pipe it via stdin. The prompt stays as the argument, context pipes in as <stdin> automatically:
cat "<prefix>-ctx.txt" | codex exec --skip-git-repo-check -s read-only -o "<prefix>-1.txt" "<question>"
A cat that fails does not stop the run: codex executes on the bare prompt, burns the full timeout, and returns nothing. Read the stderr chrome for the cat error rather than waiting on the -o file.
Route text you did not author through this channel whatever its size — a diff, file contents, a code comment, a plan or spec, third-party feedback, command output. Write the context file with the Write tool so nothing is interpreted on the way in. Keep backticks, $, and straight double quotes out of the quoted argument even in text you wrote: the first two stay live inside it, and a double quote ends it. When the prompt itself must carry any of them, as when it quotes a title or a passage, write the whole prompt and its context to one file with the Write tool and pass -, so stdin is the entire prompt:
cat "<prefix>-prompt.txt" | codex exec --skip-git-repo-check -s read-only -o "<prefix>-1.txt" -
Parse the session id: line from the CLI output. This UUID is needed for follow-up turns.
The session id: line appears only in the stderr chrome, never on stdout and never in the -o file. When a follow-up turn may be needed, do not discard stderr with 2>/dev/null or capture stdout alone — either silently drops the session id and makes resume impossible. If output must be truncated, 2>&1 | grep for session id: so the id is always retained. Use a filter that reads the stream to its end: one that exits early, such as grep -m or a trailing head, closes the pipe and kills the run.
A grep filter also hides startup failures, whose messages carry neither session id: nor the word error, leaving a missing -o file as the only symptom. When the -o file is absent and the call returned promptly with neither a task ID nor a Command timed out error, codex aborted at startup: re-run with unfiltered stderr before diagnosing anything else.
Run via the Bash tool as a foreground call (timeout: 600000, the foreground maximum; do not set run_in_background) per turn. A larger timeout is not honored: the harness backgrounds the call immediately and hard-kills codex at 600s, truncating its output. A consult that outlives a valid timeout is normally force-backgrounded: the result carries a task ID and the run continues to completion, so recover the answer by reading the current turn's -o file, then reading it again once the <task-notification> reports completion. For a backgrounded run the session id: is in the task's output file rather than the immediate tool result, so grep that file for it when a follow-up turn is needed. An over-max timeout also returns a task ID but truncates the output at 600s, so check that file for a complete answer rather than assuming the run finished. Rarely the result is an error exit (code 143) reading Command timed out after <duration> with no task ID; codex was hard-killed and the -o file was never written, so resume the session id from Step 2 with the next turn's -o path and an instruction to answer immediately, rather than re-running the consult from scratch. Never wait with Monitor, and never return the task ID or an interim file snapshot as the result — each is a false-empty return.
Step 3: Read and Evaluate Response
The -o file contains only Codex's response (cleaner than stdout, which includes CLI chrome and tool-use logs). Read the current turn's -o file. If the output is too large for the Read tool, read stdout from the Bash tool result instead. When the file holds a question put to you rather than an answer, codex halted to ask for input: resume the session with the answer and the original output contract, rather than re-running the consultation from scratch.
Assess whether:
- The answer is sufficient and actionable
- Follow-up questions would improve the answer
- The response contradicts known project facts (verify before accepting)
- The recommendation would violate a documented constraint (follow up rather than discarding or adopting it)
- The recommendation is conditional on a check not yet run that you can run yourself (run it before refining anything that depends on it, and open any follow-up with its result)
If no follow-up is needed, skip to the Synthesize step.
Step 4: Follow Up
Resume the session with the parsed session ID (not --last, which is unsafe for parallel use). <turn> continues the count from Step 2, so the first follow-up writes <prefix>-2.txt:
codex exec --skip-git-repo-check -s read-only -o "<prefix>-<turn>.txt" resume <session-id> "<follow-up question>" < /dev/null
When the follow-up carries text you did not author, or backticks, $, or straight double quotes, write it to a file with the Write tool and pass - so the prompt is read from stdin instead:
cat "<prefix>-followup.txt" | codex exec --skip-git-repo-check -s read-only -o "<prefix>-<turn>.txt" resume <session-id> -
With -, stdin is the whole prompt rather than a <stdin> block appended to an argument, so instruction and context share the one file. Leave off < /dev/null here — the pipe supplies stdin, and cat sends EOF.
Carry the consultation's -s value on each resume turn, ahead of the resume subcommand, which does not accept the flag after it.
When the consultation runs until Codex approves, open each resume turn by listing what was already applied, so Codex judges the current state rather than re-reporting findings that are already fixed. When a positive verdict arrives without stating what it rests on, resume to ask what was inspected and to inspect anything the verdict depends on that it has not yet checked, then apply the <verdict_line> termination rule to the verdict that follows. The 5-turn cap still binds: when it is reached without a positive verdict that states its evidence, carry the outstanding findings into Step 5 as unresolved and state that the consultation ended without approval.
When the recommendation would violate a documented constraint, quote the constraint back and ask Codex to argue it out: whether the constraint is sound or was set without the problem Codex identified in view, whether that problem is reachable given code Codex may not have accounted for, and what the best fix that respects the constraint is. Ask it to quantify the exposure rather than assert it, and say that reversing its prior recommendation is acceptable.
When Codex marks a point as not verifiable from the material provided, check the complete source before replying, and quote the passage that settles it in the resume turn rather than arguing the point. When no passage settles it, the point stands.
Return to Step 3. Cap at 5 turns to prevent runaway conversations.
Step 5: Synthesize
Summarize the key insights from the consultation. Cross-reference suggestions with project documentation and conventions before applying. Codex suggestions are starting points, not guaranteed solutions.
When the consultation rewrote prose rather than answering a question, check the rewrite against the source yourself before adopting it. Treat its own report that the rewrite is faithful as a claim awaiting verification. Verify the source's own factual claims against what they describe, since a rewrite can be faithful to a source that was itself wrong. Read for these drift shapes in the rewrite:
- a tense change that promotes a capability into an event
- a compression that promotes a hedge into a fact, or flattens out the reasoning that made a sentence worth keeping
- a rule promoted into an enforcement claim
- a narrowing that recasts an absence of information as a limitation of what it describes
- a figure or claim re-attributed to a different subject than the source gave it, the predicate left intact
- a claim with no counterpart in the source, asserted as if it were there
- an inverted direction in a described mapping
- a term renamed in prose, drifting from the identifier it documents
- a precise word swapped for a vaguer one, or a dropped modifier that carried the argument
- dropped markup or function words, articles included
- a split that separates clauses whose relationship is the point
- a split that strands a pronoun on the wrong noun
Take the plainer sentences and keep the load-bearing why.
Check separately whether the supporting material in a proposed replacement is already in use. The consultation sees only the files and excerpts the prompt showed it, so a replacement that introduces new material such as a citation, an example, or a quotation can reuse something the document already relies on elsewhere. Search the whole target document for that material before adopting it, and either discard the replacement or mark the reuse in the text.
When an adopted pick's strongest counterargument names a case the pick leaves uncovered, record that case as a known limit of the pick wherever the pick is recorded in a plan or another artifact that governs the work.
When the consultation was opened from a pending question, resolve that question with the answer in hand, re-asking the user when the choice stays theirs. Then use the TaskList tool and proceed to any remaining task.
Consult Oracle
Consult ChatGPT Pro via ChatGPT browser automation for problems that resist standard approaches.
Configuration
The oracle reads from ~/.turbo/config.json:
{
"oracle": {
"chatgptUrl": "https://chatgpt.com/"
}
}
| Key | Purpose | Default |
|---|---|---|
chatgptUrl | ChatGPT URL (e.g., a custom GPT project URL) | https://chatgpt.com/ |
Step 1: Identify Key Files
Find the 2-5 files most relevant to the problem.
Step 2: Formulate the Question
Write a clear, specific problem description. Include what has already been tried and why it failed. Open with a short project briefing (stack, services, build steps). The more context, the better the response.
Step 3: Run the Oracle
Run via the Bash tool (timeout: 600000, do not set run_in_background). The script loads chatgptUrl from ~/.turbo/config.json automatically and consults through the oracle's own signed-in ChatGPT profile. Generate a random tag and persist the response:
ORACLE_TAG=$(head -c 4 /dev/urandom | xxd -p) && mkdir -p "$PWD/.turbo/oracle" && echo "$PWD/.turbo/oracle/$ORACLE_TAG.txt"
Substitute the printed value for <printed-path> in the command below and on every follow-up turn. Shell variables do not survive between Bash tool calls, and an earlier cd in a compound command leaves the session in a different directory, so a relative path resolves against that directory instead.
python3 ${CLAUDE_SKILL_DIR}/scripts/run_oracle.py --prompt "<problem description>" --file <relevant files...> --write-output "<printed-path>"
Keep backticks, $, and straight double quotes out of --prompt even in text you wrote: the first two stay live inside the quotes, and a double quote ends them. Text you did not author — a diff, file contents, an error trace, command output — goes in a file passed with --file, written with the Write tool, as does any title or passage the prompt would otherwise quote. This holds on follow-up turns too.
If the run fails, retry the command once — same prompt, attachments, and timeout — when the failure looks transient, such as a browser challenge or automation error while the signed-in session is otherwise healthy. Report an authentication, browser-challenge, or permission blocker only after the retry reproduces it, and cite the failing output. Do not broaden permissions when the current context already has the access the run needs.
When the failure says the requested model is missing from the model picker and lists the available options, the CLI's default target is out of date. Instead of the identical retry, re-run once with --model gpt-6-pro, and name that model in the Step 5 summary. A Pro entry in that list does not work as a --model value.
A consult that outlives the timeout is normally moved to the background: the result carries a task ID, and the run continues to completion. Wait for the <task-notification> that reports completion, then read <printed-path>. Do not re-run the consult while it runs in the background, and never take the task ID, or <printed-path> read before that notification, as the answer. When the notification reports a failure, read the error from the task's output file and apply the retry rules above.
Step 4: Follow Up
Resume the same ChatGPT conversation with --followup and the session slug. The prior turn's attached files and context persist, so re-attaching the full diff each turn is unnecessary. Run via the Bash tool with the same settings as Step 3 (timeout: 600000, do not set run_in_background), and recover a backgrounded run the same way:
python3 ${CLAUDE_SKILL_DIR}/scripts/run_oracle.py --followup "<session-slug>" --prompt "<follow-up>" --write-output "<printed-path>"
Find the slug with python3 ${CLAUDE_SKILL_DIR}/scripts/run_oracle.py status (the Slug column; follow-ups nest under their parent session) or from the directory names under ~/.oracle/sessions/.
Reuse the chat for a multi-turn review of the same code; start a fresh session (Step 3) for an unrelated question. Cap at 5 turns to prevent runaway conversations.
When the reviewed code changed since the prior turn, re-attach the changed files (--file <paths>) or a fresh diff, or state what changed. Otherwise the model reasons from the earlier attachments and flags already-fixed issues as live contradictions.
Step 5: Synthesize
Read the response from <printed-path>. Summarize the key insights from the consultation. Cross-reference suggestions with official docs and peer open-source implementations before applying. Oracle suggestions are starting points, not guaranteed solutions.
Then use the TaskList tool and proceed to any remaining task.
Context Level
Call the mcp__turbo__context-level tool and report its reading.
Contribute
Propose an improvement to a turbo skill as an issue on tobihagemann/turbo.
Step 1: Identify the Proposed Change
Take the proposed changes from the lessons passed in: each names the turbo skill it targets, the change, and the session evidence behind it. Without them, take the proposed changes from conversation context. When neither describes a change to a turbo skill, tell the user there is nothing to contribute and stop.
Read each target skill's current text upstream, so each change is stated against the file as it stands on main:
gh api repos/tobihagemann/turbo/contents/claude/skills/<name>/SKILL.md -H 'Accept: application/vnd.github.raw'
Leave out a change whose target skill does not exist upstream, and tell the user.
Present the changes in a summary table:
| # | Skill | Change Summary |
|---|-------|----------------|
| 1 | /evaluate-findings | Added handling for security-default findings |
| 2 | /self-improve | Clarified routing for trusted reviewer feedback |
Use AskUserQuestion to confirm which changes to propose.
Step 2: Craft Contribution Context
For each change, construct a "why" explanation. The goal: the turbo maintainer should understand what happened and why the existing instructions were insufficient, without learning anything about the contributor's project.
Use this template:
During [general workflow description], the skill's instructions [what was missing or wrong]. This caused [what happened]. The change [what it does] so that [benefit].
Example:
During a code review session, the evaluate-findings skill encountered a finding with
security-defaultseverity. The existing instructions only handledcritical,high,medium, andlowseverities, causing the finding to be silently dropped. The change addssecurity-defaultto the severity handling table so these findings are properly triaged.
The maintainer implements the change, so state it concretely alongside the "why": the file path under claude/skills/<name>/, the step or section it belongs in, and the exact replacement text or a diff.
Privacy Filter
Before finalizing, verify the whole proposal — the "why" explanation, the cited paths, and the proposed replacement text — contains none of the following:
- Project or repo names
- File paths from the user's project
- Company or product names
- API keys, URLs, or credentials
- Business logic or domain-specific terminology that identifies the project
- User names beyond the contributor's GitHub handle
Output the drafted proposal as text. Then use AskUserQuestion for approval. The user must approve the proposal before proceeding.
Step 3: Run /create-issue Skill
Use TaskCreate to create a task for each approved concern. Process concerns in order, one concern per issue.
For each concern, run the /create-issue skill, filing against tobihagemann/turbo rather than the current project's repo. The approved text from Step 2 is the issue body; leave it as approved rather than re-deriving it from conversation context.
Report each issue URL.
Then use the TaskList tool and proceed to any remaining task.
Create Changelog
Create a changelog backfilled with version history.
Step 1: Run /changelog-rules Skill
Run the /changelog-rules skill to load shared changelog conventions.
Step 2: Check for Existing Changelog
Use git rev-parse --show-toplevel to find the repository root. Look for the changelog file per /changelog-rules. If it already exists, use AskUserQuestion to confirm overwriting it. If the user declines (chooses the free-form "Other" option or asks to abort), stop without running the remaining steps.
Step 3: Backfill Version History
Collect release history from the most authoritative source available:
- GitHub releases (preferred): Run
gh release list --limit 100 --json tagName,name,publishedAtto list releases. For each release, read its notes withgh release view <tag> --json body --jq .bodyand parse them into changelog entries. - Git tags (fallback): If no GitHub releases exist, run
git tag --sort=-v:refnameto list tags. For each consecutive tag pair, rungit log <older-tag>..<newer-tag> --onelineto collect commit summaries.
For each version, classify entries into the standard change types and apply the changelog-worthiness criteria per /changelog-rules.
Step 4: Write Changelog
Write the changelog following the /changelog-rules file structure and conventions.
Step 5: Present the Result
Briefly summarize how many versions were backfilled and which source was used (GitHub releases or git tags).
Create Issue
Draft a focused title and body for a GitHub issue, then file it. Bug reports state reproduction steps and observed versus expected behavior.
Step 1: Gather Context
Determine what the issue is about from the conversation. When the subject is ambiguous, use AskUserQuestion to settle it before drafting.
List the repo's issue templates, read its labels, and search for an existing issue covering the same thing:
ls .github/ISSUE_TEMPLATE/ 2>/dev/null
gh label list --limit 100
gh issue list --search "<keywords>" --state all
When the issue goes to a repository other than the checkout, replace the ls with gh api repos/<owner>/<repo>/contents/.github/ISSUE_TEMPLATE, read the files it lists through the same API, and pass --repo <owner>/<repo> to the label list and the duplicate search.
When the target repository, the checkout included, has no .github/ISSUE_TEMPLATE folder of its own, list its owner's .github repository with gh api repos/<owner>/.github/contents/.github/ISSUE_TEMPLATE, whose files GitHub applies to a repository without that folder.
Treat an empty listing or a 404 as normal. When templates exist, read the one matching the kind of issue, and read .github/ISSUE_TEMPLATE/config.yml when present. Follow the template's structure and required sections, and apply the labels and title prefix the template declares. For a YAML issue form, render each field's attributes.label as a ### heading with the answer beneath, matching what the web form produces. When config.yml sets blank_issues_enabled: false, choose a template rather than filing a blank issue.
When the search surfaces a plausible duplicate, present it and use AskUserQuestion to confirm whether to file anyway.
When a bug report rests on reading code alone, with no run having shown the behavior, offer to reproduce it before drafting. Use AskUserQuestion with Reproduce first (Recommended), which runs the scenario against the target repository's code and drafts from what it shows, and Draft as unobserved, which states in the body that the behavior was derived from code and not observed. When the scenario cannot be run, draft as unobserved.
Step 2: Run /github-voice Skill
Run the /github-voice skill to load writing style rules.
Step 3: Draft Title and Body
Draft the title and body. Output them as chat text so the user can review before anything is filed.
Step 4: Confirm and Create
Use AskUserQuestion for confirmation only. Generate a random tag so the body file is unique across sessions:
head -c 4 /dev/urandom | xxd -p
Write the drafted body to .turbo/issue/<tag>-body.md (using the printed tag) with the Write tool, then create the issue with gh issue create --body-file:
gh issue create --title "<TITLE>" --body-file .turbo/issue/<tag>-body.md --label "<LABEL>,<LABEL>"
Add --repo <owner>/<repo> when the issue goes to a repository other than the checkout. Repeat --label when the template sets several. Drop --label when no existing label fits. Set the issue type with --type <name> when a type is asked for or the template declares one; an issue type is a separate feature from a label, so applying a label of the same name leaves the request unmet. Do not set --assignee or --milestone unless the user explicitly asks.
Then use the TaskList tool and proceed to any remaining task.
Rules
- Don't reference
.turbo/content (filenames, acceptance criteria, step numbers, headings) in the title or body..turbo/is gitignored, so these references would be opaque to anyone reading without local copies. - Create labels only when the user asks.
Create Project Skills
Generates one skill per detected convention area in the project's skill directory so future Claude or Codex sessions auto-load them when working in the repo.
Task Tracking
At the start, use TaskCreate to create a task for each phase:
- Survey codebase
- Extract patterns in parallel
- Evaluate patterns
- Propose skill list
- Run
/write-skillskill
Step 1: Survey Codebase
If $ARGUMENTS specifies paths, scope the scan to those paths; otherwise scan the whole repository.
Build the extraction context:
- Detect primary languages and frameworks from manifest files (
package.json,Cargo.toml,pyproject.toml,go.mod,Package.swift,pom.xml,Gemfile, and others appropriate to the stack). - Map the top-level source directory structure and note test directory conventions.
- Read
CLAUDE.md,.claude/rules/,AGENTS.md, and any.cursor/rulesor.cursorrules. Note the conventions already documented there. The generated skills must not duplicate them. - Determine the target skill directory:
- Check candidate paths
.claude/skills/(Claude Code),.agents/skills/(Codex), and a top-levelskills/directory (match case-insensitively soSkills/or similar non-standard casing is detected too). Resolve symlinks so co-linked paths are treated as one logical location. - Use
AskUserQuestionto confirm where generated skills should live. List each distinct resolved location as an option, noting any symlink alias in the option description. If.claude/skills/is not among the detected locations, include it as a default option. The auto-added "Other" option lets users specify a custom path such as a project-specific directory.
- Check candidate paths
- In the chosen target directory, list existing skills. For each, record the skill name, the description from SKILL.md frontmatter, and the first
##section heading from the body. These signals feed rename-conflict detection in Step 3.
Output a short text summary of detected stack, top-level layout, chosen target directory, and existing skills before moving on.
When that summary shows no source code to extract conventions from, stop here rather than dispatching Step 2. Executable code in any language qualifies, including scripts no manifest declares, so judge from the directory map rather than the detected stack. Documentation, instruction files, and configuration alone do not: extraction run over prose returns that prose's assertions as observed conventions, and Step 3 scores them with no code sites to test them against.
State that as text first — what the survey found, and that conventions extracted from it would have nothing to verify against. Then use AskUserQuestion to offer:
- Write the skills from what we know (Recommended) — build skills from what this session established, rather than from conventions read out of the repo
- Generate nothing yet — leave skills until the repo has code to have conventions about
- Extract anyway — generate skills from the documentation and configuration that are there
On the first option, run the /write-skill skill directly on that knowledge and skip the remaining steps. On either of the first two, mark the extraction phases cancelled so they no longer read as pending work.
Step 2: Extract Patterns in Parallel
Read references/pattern-extractor.md to see the full taxonomy of pattern categories. Decide which categories apply to the detected stack (e.g., drop "Styling and UI" for a backend service, drop "State management" for a static-analysis tool).
Emit all extraction Agent tool calls below in one assistant message. Each Agent call uses model: "opus" and no name. Wait for every agent to report before continuing. Do not begin the next step on a partial set, and do not relaunch an agent that has not yet reported. Launch one Agent per applicable category and state the total count explicitly when emitting the calls. Every agent's prompt must direct it to treat the shared working tree and its git index as read-only and to extract by reading and reasoning. Every agent's prompt must also direct it to search the repository with a tool that skips gitignored files, such as git grep --untracked or the Grep tool, and to open or search a gitignored path only when its prompt or a file its prompt directs it to read names it, or when a dependency's installed source is needed to verify a claim, never one holding local configuration or credentials. HEAD stays where it is: read other refs with git show <ref>:<path> rather than git checkout or git switch. Each agent's prompt must:
- Name its assigned category
- Include the stack summary and directory map from Step 1
- Include the list of conventions already documented in
CLAUDE.mdand.claude/rules/so duplicates are skipped - Instruct the agent to read
${CLAUDE_SKILL_DIR}/references/pattern-extractor.mdas its role brief and return findings in the format defined at the end of that file
Step 3: Evaluate Patterns
Aggregate findings from all agents. For each finding, score three axes:
- Consistency: what share of eligible sites follow the pattern? Drop findings below 30%. Flag findings between 30–70% as "mixed" for Step 4 review.
- Intentionality: does the pattern appear across multiple subsystems and recent commits, or is it isolated? Drop findings confined to a single legacy module unless docs or lint config explicitly mark them as the desired convention.
- Modernity: does the pattern align with current best practices for the stack? Flag patterns that contradict current idioms (e.g., pre-hooks class components in a React codebase also using hooks elsewhere) as "legacy" for Step 4 review.
Group the surviving findings by topic into candidate skills. Each candidate typically covers one category, but related categories may merge if the patterns are tightly coupled. Split a candidate into two skills if its patterns cover clearly distinct sub-topics.
For each candidate skill, produce:
- A proposed
name(kebab-case, narrow to the topic, e.g.,swift-naming,react-state,api-clients) - A one-line description with trigger phrases (e.g., "Use when writing or reviewing ...")
- 3–8 concrete convention statements with evidence citations (
file:line) - A Status tag based on disk comparison:
- New: no skill with that name exists in the target directory.
- Update: a skill with the same name exists in the target directory. Produce a unified diff against the current SKILL.md body.
- Rename conflict: an existing skill in the target directory has a name, description, or first-section heading that covers the same topic under a different name. Flag for user decision.
If rename-conflict detection is ambiguous from the Step 1 signals alone, read the existing skill's SKILL.md body and compare convention statements before finalizing the Status tag.
Step 4: Propose Skill List
Output the full proposal as text first, not inside AskUserQuestion. For each candidate skill, show:
- Status tag, proposed name, one-line description
- The 3–8 convention statements with evidence
- For Update status, the unified diff
- For Rename conflict status, the existing skill name and the overlap summary
After all candidates are listed, use AskUserQuestion to confirm the proposal with these options: "Approve all", "Make edits", "Cancel". If the user selects "Make edits", continue in conversation so the user can specify which candidates to drop, merge, or rename before returning here.
For each Rename conflict candidate, use a separate AskUserQuestion asking whether to update the existing skill, create the new one alongside it, or skip. Add a Get a second opinion option as a fourth choice, since creating alongside always establishes a second skill covering the same conventions. It runs the /consult-codex skill for which resolution leaves the skill set coherent. Then resolve the conflict with that answer in hand, re-asking when the choice stays the user's.
Step 5: Run /write-skill Skill
Build the batch from approved candidates only. Do not include anything not explicitly approved in Step 4.
Output all approved candidates (both New and Update status) as text in a single batch. For each candidate, list the Status tag, proposed name, description, target path <target-skill-directory>/<name>/SKILL.md, and the 3–8 convention statements organized under ## <Section> headings with inline evidence citations (file_path:line). These convention statements define the target state the final SKILL.md should match, regardless of whether the skill is being created or updated.
Run the /write-skill skill once with this batch in context.
After /write-skill completes, output a summary of created and updated skills, grouped by status. If any candidates were dropped or skipped in Step 4, list them so the user knows what was left out.
Rules
- Each generated skill stays narrow: one topic per skill. Splitting is preferred over bundling.
- Do not duplicate conventions already documented in
CLAUDE.mdor.claude/rules/. Reference them instead if needed. - Generated skills must be self-contained: no cross-skill routing, no references to pipelines that invoke them.
- Descriptions must be third-person and include trigger phrases a future Claude session would match when working on the topic (e.g., "Use when writing or reviewing ...", "Use when editing ...").
Create Test Plan
Analyze what changed and generate a comprehensive test plan covering four escalating levels of testing depth.
Step 1: Determine Scope
Resolve scope using the first match:
- User-specified — the user says what to test. Use that.
- PR — a PR URL or number is provided. Fetch the PR details (title, description, changed files, comments) and read the changed code.
- Conversation context — prior conversation contains recent work (a feature, fix, or refactor). Extract what changed, where it lives, and expected behavior.
- App-level discovery — fresh context with no prior work. Examine the project (entry points, routes, commands, README) to identify the app's core user-facing flows.
If the resolved scope spans more than one git branch and the user named no single branch, cover each of them instead of only the branch currently checked out. Include scenarios that exercise them together where the branches can be combined in the working tree the plan's executor will have, and state the required branch state in each such scenario's steps.
Step 2: Determine Testing Approach
Always check for project-specific testing skills or MCP tools first. Use the fallbacks below when nothing project-specific is available:
- Web app →
/agent-browserskill if available, otherwiseclaude-in-chromeMCP - UI/native app →
computer-useMCP - CLI tool → direct terminal execution
- Library with no entry point → report that interactive testing is not applicable and stop, unless the scope changes a check's configuration; then use direct terminal execution for that part of the scope
Step 3: Resolve the Output Path
Pick a slug for the test plan from the change under test:
- Lowercase
- Replace non-alphanumeric characters with hyphens
- Collapse consecutive hyphens
- Trim leading and trailing hyphens
- Truncate to 40 characters at a word boundary
If the work is anchored to an existing plan at .turbo/plans/<slug>.md, reuse that plan's slug verbatim.
The user may pass an explicit slug or output path; honor it.
Resolve a collision at .turbo/test-plans/<slug>.md by how the slug was chosen. A slug generated from the change under test takes -2, -3, and so on until the path is free; do not overwrite. For a slug reused from an anchoring artifact, use AskUserQuestion to offer overwrite or a different slug, since a numeric suffix would break its pairing with that artifact. For a slug or path the user supplied, use AskUserQuestion to offer overwrite, a numeric suffix, or a different slug.
State the chosen slug and the resulting test plan path before continuing.
Step 4: Analyze the Change
After identifying scope, read the actual code in depth to understand:
- What was added, modified, or removed
- Expected behavior (from PR descriptions, comments, commit messages, or specs)
- Assumptions the implementation makes
- Error paths and edge cases
- Other features or components that could be affected
Step 5: Generate the Test Plan
For each level, generate specific, actionable test scenarios tailored to the actual change. Each scenario needs exact steps and an expected outcome.
Confirm a scenario's starting state can be reached before writing it. When a precondition depends on a system the executor does not control (another team's service, an external platform), confirm a write path for it exists. Where the write path is uncertain or absent, write the scenario so it names what to attempt and what to record when the attempt fails.
Confirm any control, command, or other affordance a scenario names exists in the code before writing the scenario: search for the API that would implement it rather than inferring it from what the feature does. Where it cannot be confirmed, write the scenario against the outcome to verify and leave the executor to find the affordance.
When a scenario claims an affordance is available in a state, make each such affordance's first observable effect in that state the expected outcome. For an affordance whose effect is not cleanly undoable, write the scenario to stop at its confirmation step and cancel it, or, when the affordance has none, to act on a record the executor creates for the scenario.
When a scenario's pass condition is that nothing happens — no write, no call, no state change — pair it with a control that differs only in the dimension under test and whose expected outcome is that the effect does occur, since a lone negative scenario cannot distinguish the behavior under test from a harness that never reached it. When such a scenario injects a crafted payload, establish that the payload satisfies every validation layer between the injection point and the code under test, and state which layers the trace cannot settle: a payload rejected at a parse boundary produces the expected absence for the wrong reason. When the guard it targets rejects a repeat invocation, establish that the affordance the scenario drives can be invoked a second time, and name an entry point carrying no busy or pending state when the primary one has it: a repeat the entry surface refuses never reaches the guard.
When the scope changes a check's configuration (linter, formatter, type checker, or CI gate rules), write that part's scenarios against the check itself and list direct terminal execution for them in the plan's Approach. Cover each changed rule with a scenario that exports the tree carrying the change to a scratch directory outside the checkout, adds input there that the rule should flag or accept, and runs the check on it, reaching the check's installed toolchain and plugins without installing into or modifying the checkout. Pair each with the same input under the configuration as it stood before the change as its control, naming that ref in the scenario's steps and writing that configuration into the exported tree beside the configuration it stands in for, so a verdict the old configuration also produces is not credited to the change. Include in each expected outcome that every run, the control included, processed a nonzero number of inputs, and state that a run processing none calls for fixing its setup and rerunning, and is inconclusive only when no fix gets the check to process any input. When the change adds or narrows a suppression and the check reports unused suppressions, add a scenario with the suppressed cause removed whose expected outcome is the stale-suppression report.
Level 1: Basic Functionality
Does the feature work at all? Verify the happy path and the most obvious behavior.
- Core feature works as described
- Expected output/UI matches the spec or PR description
- No regressions in directly related functionality
Level 2: Complex Operations
Combine multiple actions in sequence. Verify state consistency across operations.
- Chain related operations (e.g., create, edit, rename, delete)
- Exercise different combinations of feature parameters
- Verify intermediate states are correct, not just the final result
Level 3: Adversarial Testing
Actively try to break the feature. Explore boundary conditions and unexpected inputs.
- Invalid, empty, or extreme inputs
- Rapid repeated actions
- An action re-applied to its own output, checked against what the feature intends on the second application
- Interrupting operations midway (cancel, disconnect, close)
- Resource limits (very large files, deep structures, long names)
- Permission and access edge cases
Level 4: Cross-Cutting Scenarios
Explore state interactions across system boundaries. These surface the hardest bugs.
- Concurrent modifications from different sources
- State transitions (online to offline to online, foreground to background), each driven from every state the user can be in when it fires and back again, passing only when each side ends in the same state whichever path reached it
- Interactions with other features that share state
- Race conditions between asynchronous operations
When a Level Does Not Apply
If the change is small enough that a level has no meaningful scenarios (e.g., a typo fix has no cross-cutting scenarios), note "N/A for this change" with a brief explanation.
Step 6: Present and Write
Output the plan as text. Then use AskUserQuestion to ask for approval before writing.
Create .turbo/test-plans/ if it does not exist. Write the plan to .turbo/test-plans/<slug>.md using this format:
# Test Plan: <Feature/Change Name>
## Context
<Brief description of what changed and why>
## Approach
<Testing approach: agent-browser / claude-in-chrome / computer-use / terminal>
<Dev server command if applicable>
## Level 1: Basic Functionality
- [ ] **<Test name>** — <Steps to perform> → Expected: <expected outcome>
## Level 2: Complex Operations
- [ ] **<Test name>** — <Steps to perform> → Expected: <expected outcome>
## Level 3: Adversarial Testing
- [ ] **<Test name>** — <Steps to perform> → Expected: <expected outcome>
## Level 4: Cross-Cutting Scenarios
- [ ] **<Test name>** — <Steps to perform> → Expected: <expected outcome>
Then use the TaskList tool and proceed to any remaining task.
Rules
- Generate at least 2 scenarios per level, more for complex changes.
- Each scenario must have concrete steps and an expected outcome specific to the change.
- Tailor all scenarios to the actual change. Generic test advice is not useful.
Create Threat Model
Analyze the current codebase and produce a structured threat model at .turbo/threat-model.md.
The threat model describes the current state of the codebase: what it protects, where trust boundaries are, how it can be attacked, what defenses exist, and how severe each risk is. It is descriptive, not prescriptive. Do not include remediation recommendations.
Optional: $ARGUMENTS may specify scope (directories, modules, or focus areas). When scope is provided, limit reconnaissance and code discovery to the specified directories or modules. Still produce all four sections, but title the overview to reflect the narrowed scope and note what is excluded.
Step 1: Reconnaissance
Build a mental model of the system before analyzing threats.
- Read the project README, CLAUDE.md, and any architecture or security documentation.
- Examine top-level directory structure, build files, and dependency manifests to identify modules, languages, frameworks, and deployment model.
- Classify the application type: library, CLI tool, web service, desktop app, mobile app, or hybrid. This determines which threat categories and trust boundary patterns apply.
- Identify security-critical dependencies (crypto libraries, auth providers, network stacks, native/FFI libraries). Note what this codebase delegates versus what it owns.
- Read any existing security documentation:
SECURITY.md, audit reports, threat models, or changelog entries mentioning CVEs.
Step 2: Security-Relevant Code Discovery
Search the codebase for code that handles security-sensitive operations. Do not read every file. Use targeted searches.
Categories to search for:
- Authentication and authorization (login, OAuth, tokens, sessions, RBAC, API keys)
- Cryptographic operations (encryption, signing, hashing, key generation, key derivation)
- Secret and credential storage (keychains, vaults, env vars, config files with secrets)
- Network communication (HTTP clients, TLS configuration, certificate handling, WebSocket, gRPC)
- Untrusted input processing (file parsing, deserialization, XML/JSON/YAML from external sources)
- IPC and process boundaries (sockets, pipes, CLI subprocesses, shared memory)
- Plugin and extension loading (dynamic imports, ServiceLoader, plugin directories)
- Update and distribution mechanisms (auto-update, download verification, signature checking)
- Implicit network behavior (link previews, auto-fetches, thumbnail generation triggered by remote data)
- Native code / FFI boundaries (C interop, JNI, ctypes, unsafe blocks, bridging headers)
For each flow found, note the relevant files and trace data from input to processing to output.
Read references/analysis-guide.md for detailed guidance by application type and platform.
Step 3: Write the Threat Model
Write to .turbo/threat-model.md (create .turbo/ if needed). The document has exactly four sections. Adapt depth to the codebase: a small CLI tool needs less detail than a multi-component crypto system.
Section 1: Overview
Write 1-2 paragraphs covering:
- What the software is, its deployment model, and high-level architecture with key components (reference source paths)
- Security-sensitive flows as a bulleted list (3-5 items, one sentence each)
- What this repo owns versus what it delegates, and where the largest risks concentrate
For codebases with unique security properties (zero-knowledge design, client-side crypto, opportunistic encryption), call them out explicitly.
Section 2: Threat Model, Trust Boundaries and Assumptions
Assets: What has value to an attacker. Be specific: name data types, key material, tokens, metadata. Group naturally (user data, secrets, integrity artifacts).
Trust boundaries: Where trust levels change. Each boundary gets a bold name, a colon, 1-2 sentences explaining what crosses it, and a parenthetical code reference. Typical boundaries: untrusted storage/network, local OS/filesystem, IPC, admin configuration, identity provider, database.
Inputs by control tier:
- Attacker-controlled: Data from untrusted sources that the software parses. For libraries, include data passed through the API from untrusted origins. Reference specific entry points.
- Operator-controlled: Configuration, credentials, deployment parameters. Trusted but can be misconfigured.
- Developer-controlled: Build scripts, dependency versions, test fixtures, debug-only behavior. The supply chain boundary.
Assumptions: Explicit statements about what must be true for the security model to hold. Include environmental assumptions (OS isolation, entropy sources), dependency assumptions (crypto library correctness), and operational assumptions (caller protects passwords). 2-4 bullets.
Section 3: Attack Surface, Mitigations and Attacker Stories
Organize into subsections by attack surface area (not by STRIDE category or component). Each subsection follows this structure:
### [3.N] [Surface Name]
**Surface**: What is exposed and where (1-2 sentences with file references).
**Entry points and sinks**
- `path:line` (untrusted input) → `path:line` (dangerous operation): what enters and what it reaches. When a surface has no code-level entry point, or nothing dangerous behind it, say so here.
**Hot files**
- `path` (1-3 files whose logic concentrates this surface, beyond the lines cited above)
**Mitigations**
- What the code already does to defend this surface (observations, not recommendations).
**Attacker stories**
- Concrete scenario: "[Attacker type] does [action] to [goal]: [consequence and severity context]."
Decomposition heuristic: One surface per distinct trust boundary crossing or distinct attacker capability. If two areas share the same entry points AND mitigations, merge them. If a single surface needs more than 3-4 unrelated risk/mitigation pairs, split it. Typical range: 4-9 surfaces.
For each surface, document:
- 1-2 sentence surface description with file references
- Each entry point paired to the sink it reaches, both as
path:line, plus the Hot files a reviewer must read end-to-end. When a surface has no code-level entry point or nothing dangerous behind it, say so rather than listing an empty field - 2-4 mitigation bullets describing existing defenses (what the code does, not what it should do)
- 2-3 attacker stories: one sentence each, naming attacker type, action, and consequence
End section 3 with: A brief note on vulnerability classes that are less relevant for this application type, explaining why (e.g., "Web-specific issues like XSS and CSRF do not apply because this is a local library without network endpoints").
Section 4: Criticality Calibration
Group findings into four tiers. Each tier has 2-4 items, each a single sentence describing the impact (not the attack vector).
- Critical: Remote exploitation compromising crown jewels or achieving code execution. Auth bypass, key/credential theft, RCE, cryptographic bypass.
- High: Significant compromise requiring specific preconditions. Privilege escalation, targeted data theft, bypassing a major security control, integration compromise.
- Medium: Real but limited impact or unlikely preconditions. Metadata leaks, DoS, policy bypass without data compromise, local data exposure.
- Low: Theoretical, requires pre-compromised environment, or minimal impact. Verbose error messages, UI-only issues, log noise, debug-only risks.
Close with a calibration paragraph explaining how the application's deployment model and trust boundaries influence severity. For the attacker-position-vs-impact matrix and application-type adjustments, consult references/analysis-guide.md.
Step 4: Review
Before presenting the output, validate:
- Codebase-specific: Every claim references actual files, modules, or architectural patterns. No generic filler.
- Complete coverage: All security-sensitive flows from Step 2 appear in at least one attack surface, anchored by
path:linein that surface's entry points or sinks. - Balanced mitigations: Each surface lists existing defenses. If none exist, state that explicitly.
- Concrete stories: Each attacker story names a specific attacker, action, and consequence. No abstract "an attacker could exploit a vulnerability."
- Consistent severity: Calibration in section 4 is consistent with severity context in section 3 stories.
- Appropriate scope: Dependencies are acknowledged with assumptions, not audited internally. Integration boundaries are analyzed.
- Out-of-scope declared: Irrelevant vulnerability classes are named and dismissed with reasons.
Fix any gaps, then present the threat model to the user.
Rules
- Ground every claim in code. Reference specific classes, functions, or file paths. Do not speculate about code you have not read.
- When a mitigation is absent, say so explicitly. Do not invent mitigations.
- Do not audit the internals of external dependencies. Analyze the integration boundary only.
- Adapt depth to the project. A 500-line CLI tool does not need the same depth as a cryptographic filesystem library.
- The threat model is the only output. Do not create code, fix vulnerabilities, or modify the codebase.
- Use
##for the four top-level sections (numbered 1-4),###for attack surface subsections, and**bold**for sub-headings within subsections. - If the codebase has no meaningful security surface (no crypto, no auth, no network, no untrusted input), produce a brief threat model stating this with rationale, covering only dependency and supply-chain risks.
Discuss Change
Escalate open decisions, agree on the implementation shape, then implement.
Task Tracking
Use TaskCreate to create a task for each step:
- Capture the task
- Escalate product decisions
- Deep-dive discussion
- Confirm the shape
- Act on the user's reply
- Run
/implementskill
Step 1: Capture the Task
Absorb the request without interrupting. Take the task from the user's request, or from conversation context when the task was already established. Restate the goal in one or two sentences and confirm.
Step 2: Escalate Product Decisions
Identify product or design decisions the request did not resolve. Escalate these via AskUserQuestion before any code is written. Read the code the change would touch before judging whether a bullet matches. Skip when no bullet below matches the change.
Escalate when:
- The change requires choosing between user-facing behaviors the request did not specify (opt-in vs opt-out, strict vs lenient, sync vs async)
- The change assumes product requirements that were not stated
- Design trade-offs affect UX or product direction rather than technical implementation
- Multiple valid approaches exist and the choice is a matter of product preference, not technical merit
- The change would introduce a pattern not yet established in this codebase, or follow one sourced from outside it
- The change adds consistency or durability machinery (a lease, lock, queue, versioning scheme, or new persistent entity) that no stated requirement demands; carrying that machinery is itself a product decision
- A constraint on the solution that someone other than the user set and the user has not confirmed, such as a request relayed from another session or a consuming project's stated needs, rules out an option that is sounder on technical merit; offer that option and name the constraint it relaxes
Do not escalate technical decisions the agent can make autonomously: which data structure, which existing pattern to follow, internal implementation approach. The boundary is product intent.
Confirm external constraints before escalating. When an option depends on a third-party API, service, or platform behaving a particular way, query documentation MCP tools (or WebSearch as a fallback) and drop the option unless current documentation confirms that behavior.
Look up a named precedent before escalating. When the request, or a document it points to, names a precedent the change is meant to follow, such as an existing product, a protocol, or a standard, look up how it behaves on the points the change touches, and frame options against what the lookup found. Mark as unverified only a claim about it that the lookup could not settle.
Observe existing surfaces before escalating. When an option concerns how an existing surface looks, observe it as it currently renders, by running the app from the current code, or from a screenshot requested from the user, and drop any option its rendered state rules out.
Read the code an option's benefit lands in before escalating. When an option is justified by what it lets code outside the change do, such as the caller of an interface or the consumer of an output, or by what it does for data already stored, read that code, or every path that has written that data, and follow the benefit through what you read. Confirm the code or data needs what the option provides and does not already get it another way. Drop a benefit the reading does not bear out.
Apply the UX lens before escalating. When a decision concerns what the software does for the person using it, including a default, a control, or a setting in a public interface, run the /user-experience skill on it first, and state each option as the behavior that person gets and the goal it serves. For software that other code consumes, that person is the developer integrating it and the user behind them. Leave the mechanism behind each behavior to Step 3.
Output what is at stake as text first, even when the reading it came from is fresh in this conversation. When the decision turns on a failure or misuse scenario, that means the invariant the change would protect, what makes that scenario reachable given the existing guards, whether that scenario has been observed or is derived from reading, and the failure modes the new guard itself adds. Establish that reachability by tracing every path that can produce the state the scenario needs, including the code's inputs, its public interface, and data already stored, rather than inferring it from the proposed guard's purpose. When no path can produce that state and the scenario has never been observed, drop it as grounds for any option. When the scenario has never been observed, offer leaving the guard out as one of the options. Then use AskUserQuestion to present the decision as a concise trade-off with options. Keep each option's description to the decision being asked and its trade-off. When an option would also commit to a design choice the question does not ask about, ask that choice on its own or state it in the shape Step 4 confirms. Mark the strongest option "(Recommended)" and place it first. Treat the work of departing from the codebase's existing structure as a cost to state beside the option that incurs it, with no bearing on which option is strongest.
Offer a Get a second opinion option whenever the decision is costly to reverse (it establishes a pattern others will follow, defines an interface, commits to a data shape, or imports a pattern the codebase has not used), and whenever no option earns "(Recommended)" with conviction. It runs the /consult-codex skill for what each option commits to, what reversing it costs, and what the prevailing convention is. Hold the concrete options to three so the question stays within the four-option limit. Then resolve the decision with that answer in hand, re-asking when the choice stays the user's.
Step 3: Deep-Dive Discussion
Interview the user about the implementation shape until you reach shared understanding. Use AskUserQuestion in rounds: put every question whose answer depends on nothing still open into one call, up to its four-question limit, and hold a question that depends on an open answer for a later round. Cover whichever of these matter for the task. Do not present a rigid checklist. Skip when the request and the resolved decisions already name the files to touch, the existing code to build on, and the tests to write.
| Area | What to explore |
|---|---|
| Prototype unknowns | What does the surface look like, and does the interaction pattern make sense in the hand? Separate these from ordinary design questions by whether an answer in prose would still leave the user guessing. |
| Reuse vs new | Which existing code should the change build on? Which patterns should it deliberately not follow, and why? |
| File placement | Where do new files live? Which existing files are modified? |
| Data flow | How does data move through the change? Any new boundaries or contracts? |
| Edge cases | Partial failure, empty states, backward compatibility, concurrency |
| Tests | Which existing test patterns apply? Where do new tests live? |
| Scope cut | Anything to explicitly defer? Keep in scope any items the change would otherwise leave as the last holdouts of the behavior it replaces, however small their payoff. |
Discussion Guidelines
- If a question can be answered by exploring the codebase, explore the codebase instead.
- When a question concerns how an existing surface looks, observe it as it currently renders, by running the app from the current code, or from a screenshot requested from the user, before framing options. Drop any option its rendered state rules out.
- When a question concerns how to guard against a state, find where that state is constructed before framing options. When a single place constructs it, offer making the state impossible to construct there alongside the shapes that detect it downstream or change its consumers.
- When an option is justified by what it lets code outside the change do, such as the caller of an interface or the consumer of an output, or by what it does for data already stored, read that code, or every path that has written that data, and follow the benefit through what you read before framing options. Confirm the code or data needs what the option provides and does not already get it another way. Drop a benefit the reading does not bear out.
- When a question defines a boundary, contract, or data shape, add a Get a second opinion option and hold the concrete options to three so the question stays within the four-option limit. It runs the
/consult-codexskill for the soundest answer on technical merit alone, independent of the task's original scope; on a question of product intent, run it for what each answer commits to and what reversing it costs. Then resolve the question with that answer in hand, re-asking when the choice stays the user's. - When a question turns on how a surface looks or how an interaction behaves, and an answer in prose would leave the user guessing, add a Prototype it first option and hold the concrete options to three so the question stays within the four-option limit. It runs the
/prototypeskill on that unknown, then asks the question again with the prototype in hand. - When a question concerns what the software does for the person using it, including a default, a control, or a setting in a public interface, run the
/user-experienceskill on it before framing options, and state each option as the behavior that person gets and the goal it serves. For software that other code consumes, that person is the developer integrating it and the user behind them. - Pair each question with a recommendation and the reasoning behind it, so the discussion stays collaborative.
- Keep each option's description to the decision being asked and its trade-off. When an option would also commit to a design choice the question does not ask about, ask that choice on its own or state it in the shape Step 4 confirms.
- When the user says "you decide," make the call and explain why.
- Probe short answers before moving on.
- Before closing the discussion, hold each decision resolved in Step 2 or earlier in this step against the shape as it now stands: re-read what its chosen option was described as doing. Where a description no longer holds, name the claim that fails and re-ask that decision.
- Stop once the shape is clear or the user signals readiness.
Step 4: Confirm the Shape
Output the agreed shape as text, short enough to read at a glance: what the change does, where it lands, the decisions resolved in Steps 2 and 3, how to tell it worked, and anything deliberately deferred. Label any consistency or durability machinery the shape adds (a lease, lock, queue, versioning scheme, or new persistent entity) as machinery. For each, name the stated requirement or user decision that demands it, or say that none does, and state what dropping it would give up. For each deferred item, including an addition the user declined earlier, state the user story it serves, or what it simplifies when it is a technical item, and recommend noting it for later or dropping it. Recommend noting only an item that serves a goal the person using the software actually has or that simplifies existing code. This text is the change description Step 6 implements, so keep it concrete enough to act on. Before outputting it, confirm each claim the shape makes about how existing code behaves, such as what a mechanism covers, which inputs reach it, or which dependents exist, by reading the code that decides it rather than its comment or name. Drop a claim the reading does not bear out, or re-ask the decision that rests on it.
Close with how to reply: approve the shape as settled, or describe what to change. When the shape defers items, add that an approval notes the ones recommended for noting and drops the rest, and can flip any of them. When an unknown that only a built artifact settles is still open, also offer prototyping it first, and recommend that over approving, since a surface or interaction pattern that is still unproven cannot be judged from the shape description.
Then end the turn.
Step 5: Act on the User's Reply
- Revise — apply the correction the user describes. Then confirm each claim the revised shape newly makes about existing code as Step 4 does, re-present it, close with Step 4's reply guidance, and end the turn again.
- Prototype first — run the
/prototypeskill, then fold what it settled into the shape. Then confirm each claim the revised shape newly makes about existing code as Step 4 does, re-present it, close with Step 4's reply guidance, and end the turn again. - Approve — the shape is settled, along with any deferred item the approval flips. Run the
/backlogskill once for each deferred item settled as noted. Once every such item is noted, continue to Step 6.
Step 6: Run /implement Skill
Run the /implement skill. The shape the user approved is the change it applies.
Then use the TaskList tool and proceed to any remaining task.
Rules
- Confine Steps 1 through 5 to reading, discussion, confirmation, any prototype those steps called for, and the backlog entries Step 5 notes.
- If the work turns out to need writing down — unclear scope surfaces, the approach needs surveying first, or context risks being lost across sessions — stop and tell the user to run
/turbo:planfor plan mode.
Draft Plan
Produce an implementation plan at .turbo/plans/<slug>.md. Capture the task, survey patterns, escalate decisions, discuss, and draft.
Task Tracking
Use TaskCreate to create a task for each step:
- Capture the task and pick a slug
- Run
/survey-patternsskill - Consult task-specific skills and docs
- Escalate product decisions
- Deep-dive discussion
- Draft and write the plan file
- Present summary
- Act on the user's reply
Step 1: Capture the Task and Pick a Slug
Absorb the user's request without interrupting. Restate the goal in one or two sentences and confirm.
Generate a slug for the plan file from the task title:
- Lowercase
- Replace non-alphanumeric characters with hyphens
- Collapse consecutive hyphens
- Trim leading and trailing hyphens
- Truncate to 40 characters at a word boundary
Example: "Add a caching layer to the image pipeline" → add-a-caching-layer-to-the-image-pipeline.
If .turbo/plans/<slug>.md already exists, append -2, -3, etc. until the path is free. Do not overwrite.
The user may pass an explicit slug or output path in their request (e.g., "draft plan as auth-rewrite"). If so, honor it. If .turbo/plans/<slug>.md exists in that case, use AskUserQuestion to ask whether to overwrite, append a numeric suffix, or pick a different slug.
A path to a file that already exists is background input rather than an output destination. Treat it as the output path only when the request says so explicitly.
State the chosen slug and the resulting plan path before continuing.
Background Document as Input
If a path to a background document is passed as input (a design doc, an issue, a written proposal), treat it as the source of truth for product decisions and discussion areas. Read it, then:
- In Step 4, skip escalation for any product decision the document resolves. Only escalate questions it did not answer.
- In Step 5, skip deep-dive areas the document covers. Only discuss areas it did not address.
- Confirm the deployment's bounds with the user even when the document states them, rather than carrying them over as settled.
A question is resolved only when the document makes a definitive statement that answers it. Mentions without a chosen direction, open questions, and deferred decisions do not count as resolved; escalate those normally. Neither does a constraint on the solution that the document carries from someone other than the user: it stays open for Step 4, however definitively the document states it.
Step 2 (pattern survey) and Step 3 (consult skills and docs) still run in full. The document describes what; /draft-plan still surveys how.
Step 2: Run /survey-patterns Skill
Run the /survey-patterns skill with the confirmed task description. Keep the returned findings in conversation context for use in Steps 5 and 6.
Step 3: Consult Task-Specific Skills and Docs
Ground library and framework choices in current reality before escalating decisions.
- Scan for matching skills. Compare the task description against available skill trigger descriptions. For each unambiguous match, run the skill via the Skill tool. This loads decision-level guidance (idiomatic patterns, known pitfalls, version constraints) before product decisions are made. If unsure, do not load.
- Look up library docs. For libraries or frameworks the task clearly depends on, query documentation MCP tools (or WebSearch as a fallback) when the decision hinges on current library state such as whether a feature exists, which versions support it, or whether an API has been deprecated.
- Read both sides of an interface the task implements or adapts. Read the interface's shipped declaration at the installed version in full, including the obligations its documentation places on implementers; it outranks hosted docs for version-exact facts. Read the production code on the other side as well: the implementation real callers pass in, or the caller that drives the new work.
Keep findings at the decision level: what a library can do, which approach is idiomatic, which version to target. Do not embed specific API signatures or code snippets into the plan. Those belong at execution time, where the same skills are re-loaded.
Step 4: Escalate Product Decisions
Identify product or design decisions the user's request did not resolve. Escalate these via AskUserQuestion before drafting steps.
Escalate when:
- A plan step requires choosing between user-facing behaviors the request did not specify (opt-in vs opt-out, strict vs lenient, sync vs async)
- The plan assumes product requirements that were not stated
- Design trade-offs affect UX or product direction rather than technical implementation
- Multiple valid approaches exist and the choice is a matter of product preference, not technical merit
- The plan would introduce a pattern not yet established in this codebase, or follow one sourced from outside it
- The plan adds consistency or durability machinery (a lease, lock, queue, versioning scheme, or new persistent entity) that no stated requirement or deployment bound demands; carrying that machinery is itself a product decision
- A constraint on the solution that someone other than the user set and the user has not confirmed, such as a request relayed from another session or a consuming project's stated needs, rules out an option that is sounder on technical merit; offer that option and name the constraint it relaxes
Do not escalate technical decisions the agent can make autonomously: which data structure, which existing pattern to follow, internal implementation approach. The boundary is product intent.
Confirm external constraints before escalating. When an option depends on a third-party API, service, or platform behaving a particular way, drop it unless that behavior is confirmed by current documentation.
Look up a named precedent before escalating. When the request or a background document names a precedent the design is meant to follow, such as an existing product, a protocol, or a standard, look up how it behaves on the points the design touches, and frame options against what the lookup found. Mark as unverified only a claim about it that the lookup could not settle.
Observe existing surfaces before escalating. When an option concerns how an existing surface looks, observe it as it currently renders, by running the app from the current code, or from a screenshot requested from the user, and drop any option its rendered state rules out.
Read the code an option's benefit lands in before escalating. When an option is justified by what it lets code outside the change do, such as the caller of an interface or the consumer of an output, or by what it does for data already stored, read that code, or every path that has written that data, and follow the benefit through what you read. Confirm the code or data needs what the option provides and does not already get it another way. Drop a benefit the reading does not bear out.
Apply the UX lens before escalating. When a decision concerns what the software does for the person using it, including a default, a control, or a setting in a public interface, run the /user-experience skill on it first, and state each option as the behavior that person gets and the goal it serves. For software that other code consumes, that person is the developer integrating it and the user behind them. Leave the mechanism behind each behavior to the plan.
Output what is at stake as text first, even when the reading it came from is fresh in this conversation. When the decision turns on a failure or misuse scenario, that means the invariant the change would protect, what makes that scenario reachable given the existing guards, whether that scenario has been observed or is derived from reading, and the failure modes the new guard itself adds. Establish that reachability by tracing every path that can produce the state the scenario needs, including the code's inputs, its public interface, and data already stored, rather than inferring it from the proposed guard's purpose. When no path can produce that state and the scenario has never been observed, drop it as grounds for any option. When the scenario has never been observed, offer leaving the guard out as one of the options. Then use AskUserQuestion to present the decision as a concise trade-off with options. Keep each option's description to the decision being asked and its trade-off. When an option would also commit to a design choice the question does not ask about, ask that choice on its own or leave it to the plan. Mark the strongest option "(Recommended)" and place it first. Treat the work of departing from the codebase's existing structure as a cost to state beside the option that incurs it, with no bearing on which option is strongest. Draft plan steps that depend on these decisions only after the user responds.
Offer a Get a second opinion option whenever the decision is costly to reverse (it establishes a pattern others will follow, defines an interface, commits to a data shape, or imports a pattern the codebase has not used), and whenever no option earns "(Recommended)" with conviction. It runs the /consult-codex skill for what each option commits to, what reversing it costs, and what the prevailing convention is. Hold the concrete options to three so the question stays within the four-option limit. Then resolve the decision with that answer in hand, re-asking when the choice stays the user's.
Step 5: Deep-Dive Discussion
Interview the user relentlessly about every aspect of the implementation shape until you reach shared understanding. Use AskUserQuestion in rounds: put every question whose answer depends on nothing still open into one call, up to its four-question limit, and hold a question that depends on an open answer for a later round. Use the pattern survey findings to frame choices. Cover whichever of these matter for the task. Do not present a rigid checklist.
Settle the first two rows before the rest: treat every question from the other rows as depending on the answers to those two, so implementation choices land against concrete outcomes and bounds instead of being taken in the abstract. When the user jumps to implementation shape early, engage briefly then circle back.
| Area | What to explore |
|---|---|
| Outcomes | What must be true when this is done? The observable behaviors that decide whether it worked, and the acceptance criteria that pin each one. |
| Bounds | How many users and operators, now and realistically? Concurrent writers? Which rigor tier is proportionate — personal tool, small team, or business-critical — and what failure tolerance does that imply? |
| Constraints | Which non-functional requirements apply: performance, security, accessibility, i18n, compliance? Which tech-stack, hosting, or integration choices does the work commit to? |
| Prototype unknowns | What does the surface look like, and does the interaction pattern make sense in the hand? Separate these from ordinary design questions by whether an answer in prose would still leave the user guessing. |
| Reuse vs new | Which survey findings should the new work build on? Which should it deliberately not follow, and why? |
| File placement | Where do new files live? Which existing files are modified? |
| Data flow | How does data move through the change? Any new boundaries or contracts? |
| Edge cases | Partial failure, empty states, backward compatibility, concurrency |
| Tests | Which existing test patterns apply? Where do new tests live? |
| Scope cut | Anything to explicitly defer? Keep in scope any items the change would otherwise leave as the last holdouts of the behavior it replaces, however small their payoff. |
Discussion Guidelines
- If a question can be answered by exploring the codebase, explore the codebase instead.
- When a question concerns how an existing surface looks, observe it as it currently renders, by running the app from the current code, or from a screenshot requested from the user, before framing options. Drop any option its rendered state rules out.
- When a question concerns how to guard against a state, find where that state is constructed before framing options. When a single place constructs it, offer making the state impossible to construct there alongside the shapes that detect it downstream or change its consumers.
- When an option is justified by what it lets code outside the change do, such as the caller of an interface or the consumer of an output, or by what it does for data already stored, read that code, or every path that has written that data, and follow the benefit through what you read before framing options. Confirm the code or data needs what the option provides and does not already get it another way. Drop a benefit the reading does not bear out.
- When a question defines a boundary, contract, or data shape, add a Get a second opinion option and hold the concrete options to three so the question stays within the four-option limit. It runs the
/consult-codexskill for the soundest answer on technical merit alone, independent of the task's original scope; on a question of product intent, run it for what each answer commits to and what reversing it costs. Then resolve the question with that answer in hand, re-asking when the choice stays the user's. - When a question turns on how a surface looks or how an interaction behaves, and an answer in prose would leave the user guessing, add a Prototype it first option and hold the concrete options to three so the question stays within the four-option limit. It runs the
/prototypeskill on that unknown, then asks the question again with the prototype in hand. A confirmation of outcomes is such a question when the outcomes describe what a control or gesture does in use. - When a question concerns what the software does for the person using it, including a default, a control, or a setting in a public interface, run the
/user-experienceskill on it before framing options, and state each option as the behavior that person gets and the goal it serves. For software that other code consumes, that person is the developer integrating it and the user behind them. - Pair each question with a recommendation and the reasoning behind it, so the discussion stays collaborative.
- Keep each option's description to the decision being asked and its trade-off. When an option would also commit to a design choice the question does not ask about, ask that choice on its own or leave it to the plan.
- When the user says "you decide," make the call and explain why.
- Probe short answers before moving on.
- Before closing the discussion, hold each decision resolved in Step 4 or earlier in this step against the shape as it now stands: re-read what its chosen option was described as doing. Where a description no longer holds, name the claim that fails and re-ask that decision.
- When the shape is clear or the user signals readiness, confirm before drafting. The confirmation asks only whether to draft: first ask on its own, with its trade-off in each option, any design choice the summarized shape commits to that no earlier question asked, or drop it from the summary and leave it to the plan.
Step 6: Draft and Write the Plan File
Synthesize the task description, pattern survey findings, consulted skill and doc context, resolved product decisions, and deep-dive discussion outcomes into a complete plan document.
When a decision in Step 4 or Step 5 deferred work to the backlog, run the /backlog skill for it before writing the plan. State the deferral in the plan's Context as out of scope and, when the skill wrote a backlog entry, as already noted.
Create .turbo/plans/ if it does not exist. Write the plan to .turbo/plans/<slug>.md using the slug picked in Step 1 (or the override path from Step 1) using this structure:
---
status: draft
---
# Plan: <Task Title>
## Context
<Why this change is being made — the problem or need it addresses, what prompted it, the intended outcome. One or two paragraphs.>
<The deployment's bounds: user and operator count, concurrency, the rigor tier, and the failure tolerance it implies. One or two sentences.>
## Acceptance Criteria
What must be true when this is done:
- When <trigger or condition>, the system shall <expected behavior>.
- As a <persona>, I want <capability> so that <outcome>.
- Acceptance: <criterion>
## Pattern Survey
<Insert the structured findings from `/survey-patterns`: Analogous Features, Reusable Utilities, Convention Anchors, Proposed Alignment. Use the same format the survey returned.>
## Implementation Steps
1. **<Step 1 title>**
- <Concrete action with `file_path` references and named functions or symbols>
- <Another action>
2. **<Step 2 title>**
- ...
3. ...
## Verification
How to verify the change works end-to-end after implementation:
- <Specific test command, manual smoke check, or MCP tool invocation>
- <Expected observable result for each verification step>
- <Edge cases to spot-check>
## Context Files
Files to read in full before starting implementation:
- `<path/to/file1>` — <why it matters>
- `<path/to/file2>` — <why it matters>
- ...
Content Rules for the Plan
- Context: State the deployment's bounds explicitly. Downstream review judges whether the plan's machinery is proportionate against these bounds, so a plan that omits them leaves that judgment ungrounded.
- Acceptance Criteria: State observable outcomes, not implementation steps. Use the behavioral form or the user-story form per criterion; both can appear in one plan. Every criterion with observable behavior must be exercised by the Verification section. Promise no more than the change guarantees: hold each criterion against the exceptions, exclusions, and side effects the plan accepts elsewhere, and narrow it until none of them contradicts it. Omit this section only when the change has no observable behavior, which the Verification section already records.
- Implementation Steps: Use concrete
file_pathreferences and named functions or symbols. Confirm each symbol a step names resolves to a real declaration — same spelling and casing, in a file you opened, carrying the signature, fields, option keys, or event name the step relies on — searching the codebase, or the dependency's shipped interface when the symbol belongs to one. Verify that shape rather than recording it. When the change introduces the symbol instead, mark it new and name where it is defined and what uses it. When a step deletes, renames, or changes the signature of a symbol, list every file that references it, including references on code paths the change otherwise leaves alone or that never execute in practice. When a step turns on behavior that has not been observed, either how a platform, tool, or dependency behaves at runtime or what a plan-specified algorithm produces on its inputs, observe it with a cheap experiment that leaves the working tree unchanged before writing the step, confirm that each setting the experiment varies took effect, and state what it showed. For a plan-specified algorithm, write it as a throwaway script and assert the step's postconditions over randomized and degenerate inputs, keeping in the sample the inputs on which a postcondition is hard or impossible to meet. Measure each postcondition on the outcome the algorithm produces, never by reading back a value it set in order to meet that postcondition, and count how often the condition of each conditional postcondition arose in the sample. A postcondition that could not fail on the sample was not tested: measure it on the outcome, or add inputs that reach its condition. Pair a postcondition that holds only once a state is reached, such as "once nothing is pending", with one asserting that the state is reached whenever it should be. Check each postcondition at the moment it must hold, such as when the operation it describes completes. When the algorithm replaces existing behavior, run the same assertions against that behavior's own code path, through every stage an input passes, rather than a library or reference implementation that does the same job. For each input class, compare the two on the final result, which stage decides it, and how a failure at that stage is handled. Restate a postcondition the current code already violates as no worse than today unless the step sets out to fix it. State the sample size, how often the condition of each conditional postcondition arose, the failures, and the cases left unresolved. When only a person's real input can show the behavior, such as keyboard focus or a gesture, useAskUserQuestionto ask the user for a short hands-on check, and state what it showed. When the check needs the user to act outside this session, such as in another terminal, output its numbered steps, with the exact commands and what to reply once done, as text in place ofAskUserQuestion, useTaskUpdateto record the pending check in Step 6's task description, and end the turn; read the result from the user's reply or from a log the check writes. Mark a behavior that could not be observed as unobserved. When the change introduces per-entity state with an asynchronous lifecycle, state which path creates it, which single path commits its terminal outcome, and which path removes it once that outcome is committed. Confirm every state short of that outcome has a path that reaches it, then check every step that touches that state against those owners. When a step reorders operations that run in sequence today, runs them concurrently, or moves one across the boundary between the change and its caller, read the code that uses their results or effects and state the ordering that code relies on and how the step keeps it. Reference existing functions and utilities from the Pattern Survey instead of reinventing them. Each step describes a discrete unit of work that can be tracked independently during execution. - Verification: Describe how to know the change actually works. Prefer specific test commands, named test files, or named smoke checks over vague phrases like "run the tests." If the change has no observable behavior, say so explicitly. When citing an existing test as proof that a behavior is already pinned, first confirm that the test asserts the real value or behavior at issue rather than a fixture or the pass-through of a fabricated argument, and that its own inputs or match patterns reach each item it is cited for. Shape each test still to be written so it fails when the behavior it guards is absent: where the change introduces or corrects that behavior, drive an input that the code without the change handles wrongly, and assert on an observable the change alters. When it asserts an observable that some other mechanism in the system also produces, name that mechanism and shape both the fixture and the assertion so only the behavior under test can produce the observable. When a test still to be written asserts an outcome, place it in a suite that runs the real code producing that outcome: a suite that replaces that producer with a test double observes only the call into the double and what the double was scripted to return. When the change implements or adapts an interface, include a check that exercises it against the production counterpart, alongside any stand-in.
- Context Files: Curate the minimum set needed to become productive. Do not dump every file touched — only the ones that anchor understanding.
- Scope: Plan content describes what to build. Do not embed task tracking, skill loading,
/finalizeinvocation, test commands, or commit instructions in the plan content — those are execution-wrapper concerns. Keep commit, push, and PR instructions out of every section, Verification included. A Verification item may observe the result of a push without instructing one. One plan file covers one implementation run. When later work must wait on an external gate the implementation cannot pass itself, such as a verified deploy of the earlier work, write that later work as a separate plan file with the same structure, rather than marking a stopping point inside one plan. Derive its slug from the later work with Step 1's rules and state its path before writing it. When the later work changes a different repository than this one, write its plan file to.turbo/plans/in that repository with the Write tool: check Step 1's free-path rule against that directory, write the plan's paths relative to that repository's root, and use the file's absolute path wherever this rule names the later plan's path. Write the later plan against the repository as the earlier plan leaves it: leave out what the earlier plan already removes, account for every caller and every role or access holder it introduces, and wherever the later plan relies on what the earlier plan adds or removes, name the earlier plan's path and the step's title. State the gate in the later plan's Context section as every condition the later work depends on, such as data the earlier work must serve once it is live, unlanded work the later plan's changes affect, and the gate holding in each environment a routine release carries the later plan's change to. When a condition is measured, such as a quiet period, measure it where the later work's own targets are consumed. Name the later plan's path in the earlier plan's Context section. Plan size never justifies a second file.
Step 7: Present Summary
Present a brief summary of the drafted plan: the essence of what it builds and the key decisions behind it, short enough to read at a glance so the user does not have to read the full plan file. When the plan delivers value to a user, developer, or operator, also present a short list of stories capturing what that person gains, in the form "As a , I want so that ". Skip the stories only when no beneficiary or outcome can be named, such as a purely mechanical refactor. Fit both to the plan rather than a fixed template. When Step 6 also wrote a gated plan, summarize each file, and name which one to implement first and the gate the later one waits on.
Then list what the plans leave out that Step 6 has not already noted, leaving aside work a gated plan carries: each deferred item, including a request the user raised that the plan does not cover. For each, state the user story it serves, or what it simplifies when it is a technical item, and recommend noting it for later or dropping it. Recommend noting only an item that serves a goal the person using the software actually has or that simplifies existing code.
Close with how to reply: approve the plan as final, or describe what to change. When the summary lists left-out items, add that an approval notes the ones recommended for noting and drops the rest, and can flip any of them. When an unknown that only a built artifact settles is still open, also offer prototyping it first, and recommend that over approving, since a surface or interaction pattern that is still unproven cannot be judged from the plan text.
Then end the turn.
Step 8: Act on the User's Reply
- Revise — apply the edits the user describes to the affected plan file. Then re-present Step 7's summary, close with its reply guidance, and end the turn again.
- Prototype first — run the
/prototypeskill, then apply what it settled to the plan file. Then re-present Step 7's summary, close with its reply guidance, and end the turn again. - Approve — the plan is final, along with any left-out item the approval flips. Run the
/backlogskill once for each left-out item settled as noted.
Then use the TaskList tool and proceed to any remaining task.
Rules
- Never skip the pattern survey.
- Never skip decision escalation for questions left unanswered. When entering from a Background Document as Input, questions the document already resolves are considered answered and may be skipped.
- The plan file, any gated plan the Scope rule calls for, any backlog entry for work a decision deferred or Step 8 settled as noted, and any prototype the discussion or the user's reply to the summary called for, are the only outputs. Do not write code, scaffolding, or other project files.
- Do not run
/review-planor any review skills here.
Dream
Consolidate this project's auto memory, move what belongs in the repo, then clear out what .turbo/ no longer needs.
Text passed with the invocation steers the memory pass: what to look for and how to organize the notes. Every note is still read, and Step 3's and Step 5's conditions for deleting a note hold regardless.
Task Tracking
Use TaskCreate to create a task for each step:
- Read the memory
- Gather evidence
- Consolidate the memory
- Run
/route-lessonsskill - Remove moved statements
- Clean up
.turbo/ - Report
Step 1: Read the Memory
Use the auto-memory directory the system prompt names. When it names none, an effective autoMemoryDirectory setting gives the location. Otherwise the directory is <Claude config home>/projects/<encoded project root>/memory/. The config home is CLAUDE_CONFIG_DIR when set and ~/.claude otherwise. The key replaces every character outside A-Za-z0-9 with -, and long keys may be truncated and hashed.
List the directory, then read MEMORY.md and every note with the Read tool. When the directory does not exist, or holds no notes and MEMORY.md holds no entry in full, say so and continue with Step 6.
Step 2: Gather Evidence
Judge each statement in every note, and in every entry MEMORY.md holds in full rather than as a pointer to a note, by its kind:
- A claim the project can confirm or refute, such as a path, a symbol, a flag, or a command: check it by searching the current code, reading a file only where the match does not settle the claim. A claim about how a tool behaves at runtime is unverifiable unless reading settles it.
- A decision or preference of the user: the code never contradicts it. Only a note modified more recently, or the user reversing it in a session transcript, does.
- Anything else: unverifiable.
Then check each statement against what the project records in its instruction files, the documents they point to, and its skills. A statement is covered when they hold every detail it holds. A statement they disagree with, where the code does not settle it, is in conflict with the project; a project file is never the evidence for a contradicted verdict. Name the file in both cases.
Search the session transcripts only to settle which of two notes that contradict each other holds. Claude Code writes them to <Claude config home>/projects/<key>/<session-id>.jsonl. A session started in a subdirectory uses its own key, so match the encoded project root as a prefix. An autoMemoryDirectory setting does not move them. Search the transcripts modified after the older of the two notes for a narrow term, and output a short window around each match rather than the whole line, since one line can hold an entire tool result.
The step is done when every statement carries one of three verdicts: confirmed, contradicted with the evidence named, or unverifiable; every statement is marked covered, naming the covering file, or not covered; and every conflict names its file.
Step 3: Consolidate the Memory
Apply these changes without asking, following the memory conventions from the system prompt:
- Merge notes that cover the same fact into the one that covers it best, keeping every detail any of them held, and delete the others.
- Delete a statement the project covers, and its note when nothing else remains in it.
- Correct a contradicted statement so it states what the evidence shows. Delete the note when nothing true remains in it.
- Leave the content of an unverifiable statement, or of one in conflict with the project, as it stands. Merging and date rewriting still apply to it.
- Rewrite a relative date as an absolute one when the note's own text fixes the day.
- Repoint each link in another note that names a note merged away at the note that absorbed it, and remove each link to a deleted note.
- Re-index
MEMORY.md: one line per note, each pointing at a file that exists. Leave entries it holds in full where they are, correcting or deleting them under the rules above.
Before the first edit this step makes to a note, and before deleting one, output its path and its full original text. Output each line of MEMORY.md before changing or removing it. Leave every file that is not a note or the index untouched.
When a write or a deletion is refused, continue with the rest and carry what is left to do into Step 7.
Step 4: Run /route-lessons Skill
Skip when every remaining statement is in conflict with the project, or none remains.
Run the /route-lessons skill with each statement in every note, and in every entry MEMORY.md holds in full, as a candidate lesson: its note or entry as its origin, and the evidence Step 2 gathered for it. Leave out each statement in conflict with the project; Step 7 reports it for the user to settle.
Step 5: Remove Moved Statements
Skip when Step 4 was skipped.
Remove each statement /route-lessons reports as moved from its note, or from its entry when MEMORY.md holds it in full. Delete a note left with nothing, and remove an entry held in full that is left with nothing, keeping MEMORY.md itself. Make these edits under Step 3's rules for outputting original text, removing links, re-indexing MEMORY.md, and refused writes, outputting only the removed statements for a note Step 3 already printed.
Step 6: Clean Up .turbo/
Resolve the repo root with git rev-parse --show-toplevel, except inside a linked worktree — where git rev-parse --git-dir differs from --git-common-dir — in which case use the parent of the common dir. Outside a git repository, use the working directory. When that root has no .turbo/ directory, continue with Step 7.
List the top-level entries of .turbo/ with one command that prints one line per entry: its size and the date of its newest file. Say what each holds from its name and, for a file, its heading. Read the frontmatter status: of every plan with one search.
Recommend deleting or keeping each entry by its kind:
- The backlog (
backlog.mdand a legacyimprovements.md) — keep - A plan — delete when its frontmatter
status:isdone, keep otherwise, including a legacyplan.md - A standing document, one fixed name that a skill replaces on each run — keep
- A handoff, or a file that tracks one execution, named
<label>-<tag>, such as a ledger underloops/— keep - A file that only carried text to a command, named by a random tag or by the identifier of what it carried — delete when it was last modified before today
- A prototype, capture, or scratch directory — delete when its newest file predates the last commit to what it shows
- Anything else, including an entry whose purpose you cannot tell — keep
Where a directory holds items with different recommendations, list the ones recommended for deletion together as one entry and the rest as another.
Output a numbered table of the entries with size, the date of the newest file, what each holds, and the recommendation.
Then use AskUserQuestion, one question per entry recommended for deletion, in number order, filling each call to its four-question limit:
- Header —
#<number> - Question — the entry's name, what it holds, its size and age, ending with "Delete or keep?"
- Options — Delete (Recommended) with the reason in its description, then Keep with what keeping costs in its description
After each call, delete the entries the user chose to delete. When an answer asks a question or gives an instruction in place of a choice, act on it, then ask about that entry again when delete or keep is still open. When a deletion is refused, carry it into Step 7.
Step 7: Report
Output what changed:
- Memory — each note merged, corrected, or deleted, and each statement removed as covered, with the evidence for it, the dates rewritten, and the index lines added, changed, or removed
- Moved out of memory — each statement removed from its note, with the file it now lives in or the upstream proposal that carries it
- Conflicts with the project — each statement a project file contradicts, with the note and the file, for the user to settle
.turbo/— each entry deleted, with the space freed- Left to do — each write or deletion that was refused, with the path
Then use the TaskList tool and proceed to any remaining task.
Evaluate Findings
Assess external feedback (code reviews, AI suggestions, PR comments) with adversarial verification. Triage findings into actionable verdicts. Do not apply fixes.
Step 1: Assess Each Finding
If you already assessed a finding earlier in this session and recorded a verdict of Skip or Escalate — for example when an iterating loop re-runs review and the same finding resurfaces — do not re-adjudicate it from scratch. When a loop ledger path under .turbo/loops/ is in context, read it and treat the Skip and Escalate verdicts it records the same way, whichever session recorded them. When the re-reported finding matches one you already judged (same location and substance) and presents no new evidence beyond what your recorded reason already accounts for, keep that verdict and reason without re-reading the code, re-verifying, or routing it to the Devil's Advocate in Step 2. Assess fresh only when the finding raises materially new evidence, or when neither this session nor the ledger holds a verdict for it.
When several findings rest on a shared premise — for example a source-of-truth choice — verify that premise once before adjudicating them individually. Findings whose premise holds proceed through normal per-finding verification; when it fails, they are all Skip, citing the refuted premise.
When a plan governs the work, re-read the decisions it records before adjudicating. Having read it earlier in the session does not count: once it falls out of context, a recorded decision is indistinguishable from no decision at all.
The repo's backlog is .turbo/backlog.md at the repo root, or at the main checkout's root inside a linked worktree. A legacy .turbo/improvements.md beside it counts as backlog too. When the repo keeps a backlog, search it before adjudicating for the paths and symbols the findings name and for entries on the same subject, leaving out any entry the work in hand sets out to implement. Read every matching entry: run the search uncapped, splitting it into one search per finding when the combined output is too large to read, since output cut off or capped before its end settles nothing about the entries it left out. An entry that parks all or part of the change a finding asks for records a decision to defer it. When that finding holds and acting on it would make the change now, treat it as one that would reverse a decision the user made earlier, naming the entry as the original decision and quoting any condition it records for taking the change up. An entry that only shares the finding's area leaves the verdict to the finding's merits. In both cases, weigh what the entry records about that code when verifying the claim and assessing severity.
For each finding:
-
Read the referenced code at the mentioned location — include the full function or logical block, not just the flagged line
-
Check whether the code has diverged — if the finding references code that no longer exists or has since changed, skip it and note the divergence.
-
Determine scope — clarify whether the issue was introduced by the PR/changeset or is pre-existing.
- Pre-existing issues in earlier commits on the same feature branch are in-scope by default — the entire branch is one coherent unit of work. Judge these on their merits like any in-scope finding.
- Findings genuinely outside the branch's work are the user's call to include. Assign Escalate so the user decides whether to widen the changeset. Before escalating a pre-existing defect, search the sibling code paths that share its root cause, reading every match, and name each one where tracing shows the same defect in the Issue cell, or the paths searched when none has it. Reserve Skip for changes whose cost wildly dwarfs the benefit.
-
Verify the claim against the actual code — does the issue genuinely exist?
- When the finding offers a concrete example as evidence — a claimed mishandled input, a claimed wrong output — verify that example independently: a finding can hold in substance while its example does not. Keep the finding and record the correction beside it; drop it only when the claim rests on that example alone.
- When the finding places a defect on one code path on the strength of something true of another path that shares code with it, whether a defect observed there or a state asserted to hold throughout the shared operation, that holds for the other path only. Trace the flagged path to the point where the defect would fire and confirm the state it needs is already in place there (a failure raised before the step that establishes that state never finds it in place), and Skip the claim for that path when it is not.
- When the finding claims an outcome that a sequence of steps produces, such as an exploit, a bypass, or an exhausted or replenished limit, trace the sequence end to end through the state each step changes (what it consumes, restores, writes, or grants) before assigning Apply. Confirming that its preconditions hold leaves the claim open. When the trace shows the outcome does not arise, Skip, citing the step that prevents it. When a step's effect cannot be traced from the code, assign Escalate, naming that step in the Issue cell.
- When the finding asserts a compatibility property, establish two things before assigning Apply: what the existing check actually enforces, and what real counterparts produce today. A claim stronger than the check enforces is a premise error rather than a defect — Skip, citing what the check enforces, or narrow the finding to the property it does enforce and record the narrowing beside it. When neither can be established from the code, the artifacts, or authoritative documentation, keep the finding Escalate.
- When the finding cites a rule or convention, read the cited text, then look for a place that already applied it before this changeset — the same file, or the nearest files the rule also governs. Where the text alone leaves the reading open, read the rule the way that application reads it; where no such application exists, judge on the text alone.
- When the finding rests on a premise that reading the code in question cannot settle — what a platform API returns at runtime, or what a value measures once the system runs — establish that premise before assigning Apply or Escalate, using a targeted search or count over the source, the implementation behind the premise (the platform's or dependency's own source, or an open-source counterpart of the component checked against the shipped binary as installed on this machine where the two may differ), or a measurement from a surface already running in this session. A premise of this kind reads as sound whether or not it holds, so confidence in the finding is no substitute. When the premise is that a guard, check, or rule is redundant and the evidence is a comparison of runs with and without it, those runs must include the inputs it exists for, built on purpose where the condition it protects is hardest to meet. Runs that never reach those inputs leave the premise unsettled. When nothing available settles it, assign Escalate on that ground, naming the premise as unverified in the Issue cell.
- When the finding, or the verdict you reach on it, rests on an absence beyond the referenced code — nothing else references a symbol, no caller remains, the code is dead — establish it with a search whose every match you read. Output cut off or capped before its end settles nothing about the matches it left out: re-run the search uncapped, splitting it into several runs that together cover the same paths when the full output is too large to read. State the paths searched and the match count in the Issue cell.
-
Assess severity:
Severity Meaning Critical Drop everything. Blocking release or operations. High Urgent. Should be addressed in the next cycle. Medium Normal. To be fixed eventually. Low Nice to have. Minor improvement. If the upstream reviewer already assigned a priority (P0-P3), map it: P0→Critical, P1→High, P2→Medium, P3→Low. Then re-assess based on what the actual code reveals. The upstream level is a starting point, not a binding constraint. When the re-assessed severity differs from the upstream level, note the change and the reason.
If the finding has no upstream priority, assess severity from scratch.
-
Assign a verdict and confidence:
| Verdict | Criteria |
|---|---|
| Apply | The finding is real and in scope: clear bug, missing check, genuine improvement, style violation matching project conventions |
| Skip | False positive, subjective preference, reviewer is wrong, or the change's cost wildly dwarfs its benefit |
| Escalate | Needs the user's judgment: behavior might be intentional, involves product intent, requires domain knowledge the agent lacks, the finding is out of scope, or two findings present a genuine trade-off |
Also assign an internal confidence level — High, Medium, or Low — reflecting how certain you are about the verdict. Confidence is used solely to route findings to the Devil's Advocate in Step 2. It does not appear in the output.
Escalate guidance: When a finding questions whether behavior is intentional and neither docs, specs, nor code comments clarify the intent, assign Escalate. Do not autonomously accept or reject findings that hinge on product intent. If a counterpart implementation exists elsewhere, suggest checking it for consistency.
Conflict guidance: When two findings disagree about whether the code should change at all (one suggests a change to it, another the opposite change or none), treat the conflict as input, not a reason to skip. Verify each against the code and judge each on its merits as usual. If both are defensible and the choice is a genuine trade-off, assign Escalate to both, naming the opposing options so the user can decide.
An affirmation that something is correct is not a finding and carries no evidentiary weight; agreement among reviewers, or a reviewer's authority, does not settle whether a problem exists, nor whether a remedy the reviewers converged on works. When reviewers disagree on whether something is a problem at all — including one asserting it is fine while another flags it — treat the question as unresolved and verify it against the code, without letting the affirmation substitute for verification. When reviewers agree the code should change but propose opposing remedies, assign the verdict on the finding's own merits and name the opposing remedies in the Issue cell. Prefer a remedy whose measurement reports a result concrete enough to re-run over one resting on reading or on a reviewer's authority; a bare claim to have measured ranks no higher than reading. Where no remedy reports one, say so in that cell rather than choosing between them.
A reviewer's report that it could not verify something is a claim to check, not a fact to accept. Attempt the check independently, especially when the reported inability is what justifies skipping a verification step.
Verdict guidance:
- A verdict records whether the finding is real: genuine defect, in scope, at what severity. A finding can hold while the remedy proposed for it does not, so a verdict never certifies the remedy. Judge the remedy's cost and scope where the bullets below call for that, and leave whether it works to be checked when it is applied. Where naming the likely direction helps the user, put it in the Issue cell flagged as unverified.
- Never auto-dismiss findings about security defaults, permission escalation, or fail-open vs fail-closed behavior. Always surface these even if the behavior appears intentional.
- Readability and clarity improvements that genuinely make code cleaner are valid. Do not auto-classify cosmetic changes as subjective.
- Removing a comment that adds no information beyond the code is a valid Apply, not a subjective preference. Keep only comments that capture a constraint the code cannot express.
- Be skeptical of "defensive coding" suggestions that wrap natural code in verbose guards without evidence of real-world failures. Apply a hardening finding only when it names a failure scenario reachable in this deployment, whatever severity the reviewer attached; when the plan's Context bounds the system (a single operator, no concurrent writers, a handful of invited users), a scenario that bound rules out is a Skip, citing the bound.
- Machinery is scope. A finding whose fix adds a lease, lock, queue, versioning scheme, state machine, or new persistent entity expands the project even when the requirement count stays flat. Assign Escalate regardless of confidence; "making states explicit" or "staying within the approved plan" does not make the machinery proportionate. When a stated bound rules the machinery's failure scenario out entirely, Skip instead, citing the bound.
- A finding that would reverse a decision the user made earlier — in discussion or recorded in the artifact — is Escalate, naming the original decision and the new evidence beside it. Judge by the outcome rather than the wording of the option the user chose: a reversal leaves the user with something materially different from what they chose. When the earlier decision accepted a limit to avoid a cost, look for a remedy that avoids that cost, such as a signal or state the code already holds. Name any you find in the Issue cell beside the original decision, flagged as unverified, or state that none was found. Treat the user's choice as one among the options shown at the time, leaving open a remedy that was not among them. A finding that refutes only the factual premise the user's choice rested on, leaving the chosen outcome intact, is a premise correction: confirm the refutation against whichever of the code, the governing artifact, or authoritative documentation the premise turns on, and when none settles it, keep the finding Escalate. Otherwise assign Apply unless another bullet independently calls for Escalate, and add a callout below the table naming both the corrected premise and the chosen outcome it leaves standing.
- In an iterating loop, a structural Apply triggers another full iteration; count that iteration in the change's cost when applying the Skip cost test. A finding that targets code or text introduced by an earlier iteration's accepted finding, and names no defect in it, is churn: Skip.
- When a comment at the code in question records why a behavior is unobservable through every reachable path, verify that record against the code before honoring it. A coverage finding re-reporting the gap, naming no newly reachable path that would observe the behavior, is Skip, citing the record.
- Weight reviewer authority. Feedback from trusted reviewers (repository maintainers or admins) should be treated with higher credibility even when phrased softly.
- Plan deviation is not a verdict. Do not reject a finding on the grounds that it departs from a plan's prescribed shape. When the plan records a load-bearing reason for that shape, assign Escalate so the user can weigh the trade-off. When the plan is silent on why, or the recorded reason reads like "path of least deviation" or "minimal change", treat the shape as a default and judge the finding on its own merits.
Step 2: Devil's Advocate
After the initial assessment, challenge uncertain findings from a different angle.
Spawn when any finding has Medium or Low confidence. Send only those findings to the subagent. High-confidence findings pass through unchallenged. Skip this step entirely if all findings are High confidence.
Run bash ${CLAUDE_SKILL_DIR}/scripts/checkout-snapshot.sh capture before spawning and keep the five-value state it prints. It covers HEAD, the index, and every working-tree file outside gitignored paths and .turbo/. Its fifth value records the paths on disk it leaves out, which restore never deletes. It reports on stderr, as SKIPPED, each gitlink, embedded repository, tracked path now holding a directory, and path whose name contains a newline or carriage return, and these stay outside what it restores. When capture fails, it names the cause, such as an unmerged index: resolve that before spawning.
Launch a single subagent (model: "opus", no name). Wait for it to report before continuing; do not relaunch it if it has not yet reported. Provide the Medium/Low-confidence findings with their file locations, claims, and initial verdicts. Instruct the subagent to challenge each finding: try to prove it wrong, or confirm it with evidence.
Evidence standards: A refutation counts only when it rests on a defense, guarantee, or documented behavior the subagent located and read, or on behavior it observed by running the code; an expectation that a framework, caller, or type already handles the case returns Inconclusive and leaves the initial verdict standing. Confirmed applies to the claim the finding stands or falls on. Establishing the premise beneath that claim leaves it open: that code reads a value settles nothing about whether a test can control that value. When the subagent has established only the premise, it returns Inconclusive. Evidence that a test fails when its subject is changed settles only that the test pins the behavior; whether the pinned behavior is the required one stays open. Where the test was written alongside its implementation, their agreement is guaranteed by construction and carries no evidence about the requirement. A finding resting on that evidence is Confirmed only when the requirement itself has been checked against the code's production consumer, or against the governing plan; when neither is reachable, the subagent returns Inconclusive.
Protect the shared tree: The subagent's prompt must direct it to treat the shared working tree and its git index as read-only; an experiment that needs a scratch project runs in a temp directory outside the repo, or in an isolated git worktree created there and discarded afterward. HEAD stays where it is: read other refs with git show <ref>:<path> rather than git checkout or git switch. Refer to that directory or worktree by absolute path in every command and join chained steps with &&, so a failed step cannot leave the rest running in the shared checkout. Run teardown and verification as their own commands. Give that worktree its own dependency install rather than reaching the shared tree's install by any route: removing a worktree deletes through symlinks, and a redirected suite writes into the shared install. When its own install is not possible, the check is left unrun and reported as such. A check that runs in the shared checkout invokes an already-installed runner directly wherever a package-manager wrapper would front it, since such a wrapper reads as read-only while reconciling the shared install before it runs. Confine dependency installs and reconciliation to an isolated worktree. Every test runner the subagent starts, in a temp directory, a worktree, or the shared checkout, runs in its own process group under a timeout enforced from outside the runner. Before teardown, the subagent stops the process group of every runner it started, since stopping a runner can leave the processes it spawned alive. Afterward the subagent verifies that git worktree list no longer shows the worktree, that git status --short shows what it showed at the start, and that HEAD is still on the branch it started on. Its teardown deletes the temp directory, if any, and it confirms that path no longer exists, reporting the path of one it could not delete. It also confirms that no process from those groups, and none whose command line names the temp directory or worktree path, if any, is still running, and reports by PID any process it could not stop. When it cannot list processes, it reports that check as unrun and names those process groups and the temp directory or worktree path, if any. After any check, in a worktree or in the shared checkout, it verifies that the shared tree's dependency directory still resolves (a destroyed install leaves git status unchanged, since it is gitignored). Damage the subagent cannot repair is reported with the exact repair command in place of findings.
Verify the tree when the subagent returns, including when it terminates early or reports incomplete results: run checkout-snapshot.sh verify with the captured state, and confirm alongside it that the shared tree's dependency directory still resolves, which the snapshot cannot see. When verify exits 0, the subagent left the checkout as it found it. Otherwise run checkout-snapshot.sh restore with the captured state, then verify again. Before writing anything, restore prints the state it found as an UNDO line: keep it and any MOVED lines, since running restore with it undoes the restore apart from the MOVED branches.
Report the RESTORED and INDEX paths, the UNDO state, and each MOVED branch with the commit it held (none when restore created the branch). Also report each path printed as LEFT or SKIPPED, which stayed as the subagent left it, and each path printed as FAILED, whose write failed and whose prior content survives only in the UNDO state. Name any change you see in gitignored paths or .turbo/ as outside what the snapshot restores. Judge the result by verify alone: after a restore, git status can report modifications the bytes do not contain. When restore prints LOST or INVALID, or verify still fails, report what still differs from the captured state, including the LEFT and FAILED paths.
The subagent picks research tools based on claim type:
| Claim Type | Tool |
|---|---|
| API deprecated/removed/changed | Documentation MCP tools or WebSearch |
| Method doesn't exist / wrong signature | Documentation MCP tools, WebSearch fallback |
| Code causes specific bug or behavior | Bash (isolated read-only test snippet) |
| Undocumented platform or dependency behavior | Its source; else an open-source counterpart, checked against the shipped binary where the two may differ |
| Best practice or ecosystem claim | WebSearch |
| Migration or changelog lookup | WebSearch → WebFetch |
Use whatever documentation tools are available. The specific tools vary by project setup.
Budget: max 2 research actions per finding. If the first action is conclusive, skip the second.
Subagent Verdicts
The subagent returns per finding:
- Confirmed — found evidence supporting the claim (with source)
- Disputed — found counter-evidence (with source and explanation)
- Inconclusive — no definitive evidence either way
Step 3: Reconciliation
Merge subagent results with the initial assessment:
- Confirmed: verdict and severity stand. Note the evidence source.
- Disputed: if originally Apply, downgrade to Skip or Escalate. Re-assess severity if the evidence changes the impact picture. Show both perspectives.
- Inconclusive: verdict and severity stand, note the uncertainty.
Findings not investigated by the subagent keep their original verdict.
For Apply findings, document the issue and location. For Escalate findings, note what information would resolve the ambiguity. For Skip findings, document why.
Step 4: Format Output
Summarize the evaluated findings in a table:
| File | Issue | Source | Severity | Verdict |
|---|
When Step 2 ran (any finding was investigated by the Devil's Advocate subagent), add an Investigated column:
| File | Issue | Source | Severity | Verdict | Investigated |
|---|
Where Investigated shows:
- (empty) — not investigated by subagent
- Confirmed (source) — subagent found supporting evidence
- Disputed: [reason] — subagent found counter-evidence
For findings whose severity was re-assessed from the upstream level, append the change in the Severity cell (e.g., "High (was Medium)").
Carry each verdict into the Verdict column exactly as assessed, Escalate included.
For disputed findings, add a callout below the table showing both perspectives. For each finding, indicate scope in the Issue column (e.g., "Pre-existing:" prefix).
Then use the TaskList tool and proceed to any remaining task.
Explain This
Take whatever the user is pointing at and translate it into plain language. "This" is usually the most recent assistant output or something pasted as an argument: a multi-option prompt, a free-form question, a code block, an error, a command output, or an artifact like a plan, findings report, or diff.
Step 1: Identify the Subject
Pick the subject in priority order:
- Text passed as an argument — use that
- A quoted or selected region from the user's most recent message — use that
- The most recent non-trivial assistant output — use that
- If the guess is not obvious, lead the explanation by naming what was picked so the user can redirect
Step 2: Ground in State
Read whatever makes the explanation concrete, no more:
- Files the subject references
- The active skill's
SKILL.mdwhen a skill-specific question is being asked git statusandgit diff --statwhen the subject involves staged or unstaged changes- Any artifact cited (plan, spec, findings, test plan, audit, PR, commit)
Step 3: Produce the Explanation
The reader is an experienced developer who may not be fluent in every tech stack or acronym but doesn't need concepts from first principles. Skip ELI5. Use plain language; strip skill-internal jargon, or define it inline when the jargon is what the user needs explained (for example, "P1 peer" becomes "priority 1 finding from the peer reviewer").
Go beyond "what this does" and surface the trade-offs: pros and cons per choice, benefits and costs, whether the thing reads as clean and elegant or redundant and overcomplicated. Be honest about red flags; be honest about solid work.
Shape the output to match the subject. Use the branch that applies; drop the rest.
Question with discrete options — restate the question plainly, then enumerate options using this template:
**What you're being asked:** <plain-language restatement>
### Your Options
**1. <label as shown>** — <concrete effect: files changed, next step, what is lost>
- **Pros:** <what you gain>
- **Cons:** <what it costs>
**2. <label>** — <concrete effect>
- **Pros:** <...>
- **Cons:** <...>
### When Each Fits
- Pick **<option>** if your goal is <goal>.
- Pick **<option>** if your goal is <other goal>.
Apply these option-specific rules:
- Describe each option's real-world effect. Example:
- Concrete: "Renames the module to
auth-v2and updates the 3 import sites insrc/." - Too abstract: "Cleans up the auth code."
- Concrete: "Renames the module to
- If an option was labelled "(Recommended)" in the original, repeat that label verbatim. Do not add a fresh recommendation.
- If an option would skip a safety step (tests, review, a gate), call that out.
- If the pending question was posed via
AskUserQuestion, re-invokeAskUserQuestionafter the explanation with the same question, header, and options so the user can answer inline without losing the dialog. Preserve any "(Recommended)" label verbatim. Otherwise (plain-text prompt from the assistant), end by noting the question is still pending and the user should reply to the original prompt directly.
Free-form question — restate the question plainly, say what the answer will be used for (which file gets written, which step consumes it), and call out what makes a good answer versus a problematic one. End by noting the question is still pending.
Code, error, or command output — say what it does or means, likely cause or purpose, and what action is typically expected. Judge the design: is it clean and idiomatic, or are there smells like redundant guards, tangled control flow, or unnecessary abstraction?
Artifact (plan, findings, diff, PR) — summarize its contents, the decisions it represents, and what step comes next. Flag strengths and weaknesses: over-engineering, missing cases, clear wins.
Rules
- Read-only. Do not modify files, stage changes, or answer a pending question on the user's behalf.
- If an active skill's SKILL.md contradicts what the conversation shows, trust the conversation and note the discrepancy briefly.
- If the subject cannot be identified at all, say so and stop.
Exploratory Test
Execute multi-level exploratory testing that goes beyond smoke testing to actively find bugs through escalating test scenarios.
Task Tracking
At the start, use TaskCreate to create a task for each step:
- Load or create test plan
- Determine testing approach
- Run
/user-experienceskill (when user-facing) - Run
/test-run-rulesskill - Execute tests by level
- Report
Step 1: Load or Create Test Plan
Resolve the test plan using these rules in order:
- Explicit path — If a file path was passed, use it
- Explicit slug — resolve to
.turbo/test-plans/<slug>.md - Anchoring artifact — If the work under test is anchored to a plan, resolve to
.turbo/test-plans/<that-slug>.mdwhen that file exists - Single file — Glob
.turbo/test-plans/*.md. If exactly one file exists, use it - Most recent — If multiple files exist, use the most recently modified
- Legacy fallback —
.turbo/test-plan.mdif.turbo/test-plans/does not exist - Nothing found — run the
/create-test-planskill first, then use the plan it writes
If multiple test plans exist and the most-recent choice is non-obvious, use AskUserQuestion to let the user pick from the candidates.
Read the resolved test plan and state its path.
Unless an explicit path or slug was passed, confirm the resolved plan still describes the work under test:
- Unavailable branch state — a scenario's steps require a branch that no longer resolves in the repository
- Completed prior run — every checkbox is already ticked and no recorded result is FAIL or PARTIAL
- Superseded context — the plan's Context section names work that changes merged since the plan was written have reversed or removed
When a signal fires, output the signal and the scenarios it affects as text. For a superseded Context, name the scenarios that exercise the reversed or removed work. Then use AskUserQuestion to offer:
- Regenerate — run the
/create-test-planskill with the resolved path, and use the plan it writes - Execute anyway — the signal is a false positive
- Pick another plan — resolve to a different test plan file, then confirm that plan against these same signals
If the user specifies a narrower scope, filter the plan to relevant scenarios rather than executing all of them. Reserve filtering for that case: a superseded plan keeps scenarios that each look plausible alone, so trimming it preserves the wrong ones.
Step 2: Determine Testing Approach
Use the approach specified in the test plan. If the plan does not specify one, determine it using the same logic as /create-test-plan Step 2.
Step 3: Run /user-experience Skill (When User-Facing)
If the app has a user-facing surface (UI, screens, commands, messages, or any behavior a user sees or does), run the /user-experience skill to load the UX lens before executing tests, so usability concerns surface while interacting with the app. When it is unclear whether the surface is user-facing, use AskUserQuestion to ask rather than skipping silently. Skip this step for test targets with no user-facing behavior (internal library or infrastructure).
Step 4: Run /test-run-rules Skill
Run the /test-run-rules skill to load the rules for launching and driving the app.
Step 5: Execute Tests by Level
Work through each level sequentially. Complete all tests in a level before moving to the next.
Execution Loop (Per Test)
- Set up the preconditions described in the test scenario
- Perform the exact steps
- Capture the result (screenshot, output, or state observation)
- Compare against the expected outcome
- Record PASS, FAIL, or PARTIAL with details
- When the UX lens is loaded, note any usability observation it surfaces, kept separate from the verdict
Record a scenario the test run rules leave blocked or inconclusive as PARTIAL, naming what is unproven and why.
When the scenario's output is consumed by another system, withhold PASS until that system accepts it. Decoding a token, reading a response body, or confirming a row exists shows only that the artifact was produced. Stand up the consumer under the same isolation and cleanup rules as any other service this run starts, and exercise its own flow. When standing it up is not possible, record PARTIAL and name which half is unproven. PARTIAL counts as not passed everywhere a verdict is tallied or gated.
Level Progression
- Level 1: Basic Functionality — If any Level 1 test does not pass, report early and use
AskUserQuestionto ask whether to continue. Basic failures may indicate the feature is too broken for deeper testing. - Level 2: Complex Operations — Execute all tests regardless of individual failures.
- Level 3: Adversarial Testing — Execute all tests. Failures here are expected and valuable.
- Level 4: Cross-Cutting Scenarios — Execute all tests.
If a project-specific testing skill or MCP tool was identified in Step 2, use that. The paths below are fallbacks.
Web App Path
Start or reuse a dev server under the test run rules. If /agent-browser is available, run the /agent-browser skill. Otherwise, use claude-in-chrome MCP to interact with the app.
UI/Native App Path
Launch the app. Use computer-use MCP to interact with the UI.
CLI Path
Run commands directly.
Step 6: Report
Present results organized by level:
Exploratory Test Results:
## Level 1: Basic Functionality (X/Y passed)
- [PASS] Test name: description — [substitution, when one was driven]
- [FAIL] Test name: description — [what went wrong]
- [PARTIAL] Test name: description — [what is unproven, and why]
## Level 2: Complex Operations (X/Y passed)
- [PASS] Test name: description — [substitution, when one was driven]
- [FAIL] Test name: description — [what went wrong]
- [PARTIAL] Test name: description — [what is unproven, and why]
## Level 3: Adversarial Testing (X/Y passed)
- [PASS] Test name: description — [substitution, when one was driven]
- [FAIL] Test name: description — [what went wrong]
- [PARTIAL] Test name: description — [what is unproven, and why]
## Level 4: Cross-Cutting Scenarios (X/Y passed)
- [PASS] Test name: description — [substitution, when one was driven]
- [FAIL] Test name: description — [what went wrong]
- [PARTIAL] Test name: description — [what is unproven, and why]
Overall: X/Y passed across all levels
Report usability observations from the UX lens below the level results, separately from the defects. A scenario can pass every functional check and still surface a usability concern.
## Usability Observations
- [UX] <observation> — names the UX context it touches (Understanding, Bridging, or Flowing) and the goal mismatch or friction it creates
For each failure, include the relevant screenshot, output, or state observation.
When the change under test spans several repositories, add a per-repo view of the findings below the usability observations, naming a suggested fix site for each.
Update the resolved test plan file by checking off completed tests and annotating results.
Then use the TaskList tool and proceed to any remaining task.
Rules
- To diagnose failures, run the
/investigateskill on the test report.
Fetch PR Comments
Fetch unresolved review comments, top-level review body comments, and PR conversation comments from a GitHub PR and present them in a readable summary. This is a read-only skill -- it does not evaluate, fix, or reply to any comments.
Step 1: Fetch Comments
Auto-detect owner, repo, and PR number from current branch if not provided. Then run ${CLAUDE_SKILL_DIR}/scripts/fetch-pr-data.sh, which handles full pagination (review threads, inner comment pages for long threads, reviews, issue comments) and emits a single merged JSON document:
bash ${CLAUDE_SKILL_DIR}/scripts/fetch-pr-data.sh <owner> <repo> <pr_number>
Output shape:
{
"meta": { "title", "url", "headRefName", "baseRefName" },
"reviewThreads": [ { "id", "isResolved", "isOutdated", "comments": { "nodes": [ { "author", "body", "path", "line", "originalLine", "diffHunk" } ] } } ],
"reviews": [ { "author", "body", "state" } ],
"issueComments": [ { "author", "body", "createdAt", "url" } ]
}
Filter review threads to unresolved only. Filter reviews to those with a non-empty body, excluding PENDING state (unsubmitted drafts). Filter issue comments to those with a non-empty body.
Step 2: Present Results
Display a summary header followed by comments grouped by file.
Summary header:
- PR title and link
- Branch:
head->base - Total threads / unresolved threads
Top-level review comments (if any):
Show reviews with non-empty body before the file-grouped threads:
## Review Comments
### @reviewer (CHANGES_REQUESTED)
> Review body text here
### @another-reviewer (COMMENTED)
> Another review body here
Issue comments (if any):
Show PR conversation comments after review comments, ordered by createdAt:
## Issue Comments
### @commenter (2026-04-20)
> Issue comment body here
### @another-commenter (2026-04-21)
> Another issue comment body here
Inline threads grouped by file:
For each file with unresolved threads, show:
## `path/to/file.ts`
### Line 42 (by @reviewer)
```diff
<diffHunk from first comment>
```
> Comment body here
### Line 10 (by @another-reviewer) [outdated]
```diff
<diffHunk from first comment>
```
> First comment body
>
> **@reply-author:** Reply body
Formatting rules:
- Show top-level review body comments first, grouped under "Review Comments"
- Show PR conversation comments next, grouped under "Issue Comments", ordered by
createdAt - Then group threads by file path, in the order they appear
- Within each file, order threads by line number
- Show the
diffHunkfrom the first comment in each thread as a fenced diff code block before the comment body. This is the code context the reviewer was looking at. - For the line number, use
lineif available. Fall back tooriginalLinefor outdated comments wherelineis null. - Show all comments in a thread (the first is the original review comment; subsequent ones are replies)
- Mark outdated threads with
[outdated] - Use blockquotes for comment bodies
- For threads with multiple comments, show each comment with its author
- If there are zero unresolved threads, zero review body comments, and zero issue comments, say so and stop
Then use the TaskList tool and proceed to any remaining task.
Rules
- If the user wants to fix or reply to comments, direct them to use
/turbo:resolve-pr-feedback.
Finalize Implementation
Post-implementation QA workflow: tests, code polishing, commit, self-improvement, and landing the pull request.
Task Tracking
At the start, use TaskCreate to create a task for each phase:
- Run
/polish-codeskill - Run
/simplify-docsskill - Run
/update-changelogskill - Run
/self-improveskill - Ship It
- Run
/land-prskill
Phase 1: Run /polish-code Skill
Run the /polish-code skill for the current changes.
Phase 2: Run /simplify-docs Skill
Run the /simplify-docs skill on the staged changes (git diff --cached). Stage any edits it makes before continuing.
Phase 3: Run /update-changelog Skill
Run the /update-changelog skill. Stage any edits it makes before continuing.
Phase 4: Run /self-improve Skill
Run the /self-improve skill for the current session. Always run this phase even if the session seemed routine.
Phase 5: Ship It
Step 1: Analyze Split
Examine the staged changes and evaluate whether they form a single reviewable unit or several independently reviewable units. This step decides only whether to split; the chosen ship skill owns all repository-state detection and the commit, push, branch, and PR intent.
Run git diff --cached --stat and git diff --cached to understand the scope. Categorize changes along three dimensions:
- Concern type: refactoring, bug fix, new feature, cleanup, dependency update
- Layer/domain: backend, frontend, database migrations, i18n, tests, configuration
- Logical unit: files that form a coherent, independently reviewable change
A split is warranted when the staged changes contain multiple reviewable units. Each unit should be independently understandable, testable, and revertable. When deciding group boundaries, consider whether a reviewer could evaluate each group without needing context from the others.
Step 2: Present Analysis and Choose Path
Output the split analysis as text.
If changes form a single cohesive unit, note this and run the /ship skill.
If changes span multiple reviewable units, propose an ordered list of groups. For each group, specify:
- Name and one-line description
- File list (flag files with mixed-concern hunks)
- Dependencies: which earlier groups, if any, this group builds on
Use AskUserQuestion to let the user choose whether to ship the changes together or split them up.
- Ship together — ship all staged changes as one unit; run the
/shipskill - Split up — ship each group as its own unit; run the
/split-and-shipskill
Phase 6: Run /land-pr Skill
Skip this phase when Phase 5 neither opened a pull request nor pushed to the branch of an open one. When Phase 5 left a pull request's body with the user instead of opening it, present /turbo:land-pr to run once it is posted, and skip the skill.
When Phase 5 opened or pushed to several pull requests, present /turbo:land-pr <number> for each, to run from that pull request's checkout, and skip the skill.
Otherwise, run the /land-pr skill for that pull request.
Then use the TaskList tool and proceed to any remaining task.
Rules
- Diff size, number of files changed, passing tests, perceived user urgency, or context window concerns are not reasons to skip a phase. Each phase does work beyond what those signals cover. "The session was long" or "a prior phase was thorough" are never valid reasons to skip a later phase.
- Never stage or commit files containing secrets (
.env, credentials, API keys). Warn if detected. - Do not present diffs to the user — the user reviews diffs in an external git client. Use
git diffinternally as needed. - If a non-test step fails (polish, review), stop and report the failure. Do not skip ahead.
GitHub Voice
Writing Style
- No em dashes (
—) or double hyphens (--) used as dashes. Use periods, commas, colons, or restructure the sentence. - Write in a natural, human tone. Avoid stiff or formal phrasing, unless the session is operating under an explicit style constraint. That constraint governs GitHub text too, and the destination does not relax it.
- Don't over-explain. Say what needs saying, then stop. Answer a question with exactly what it asked, in the vocabulary it used.
- Leave evidence of correctness out of a PR body: a Verification section and test-count lines when CI runs the suite, lines listing the tests or changelog entry the change includes, and figures from a survey of live data. A statistic offered as reassurance reads as an open question rather than a finished change. Keep a measurement the change exists to produce.
- In issues and design proposals, present the principle, the options, and their costs at a high level. Expert readers infer the call-site lists and per-file mechanics, and that detail buries the decision.
- When explaining how the code works, describe its current behavior. Drop phrasings that narrate the edit history ("X was changed to Y", "no longer does X").
- Keep one term per concept, preferring the name the code uses. Once a thing has a name, repeat that name instead of rotating synonyms, and refer to a code element by its identifier rather than a shorthand the text never introduces.
- When the user has stated their reasoning in the conversation, mine it and write from that reasoning. A cleaner argument constructed afterwards reads as someone else's, however sound it is.
- When the user supplies wording for the artifact, that wording is the draft. Keep their phrasing rather than sharpening it into something more precise, more formal, or more technically careful. Where the phrasing names an effect and the mechanism differs, state the mechanism separately. Flagging the deviation to the user does not license it.
- Sound like the author, not like an AI assistant.
- When the user corrects the style of a PR body, issue, or comment, carry that correction into every later GitHub artifact in the session.
- Never attribute session-internal work to its tooling. Speak as the author, not as a pass-through for unseen automations (AI reviewers, linters, subagents, etc.). The recipient doesn't know about these tools.
- Composing prose in the user's voice is not the same as posting it. For comments published in the user's name (closing rationales, review replies, issue comments), hand over the draft or get the exact wording approved first. Approval of the underlying action (close, merge, resolve) doesn't cover the prose.
- Soften opinions when asking questions. Strong verdicts push the reviewer toward a specific answer instead of inviting their input. Flag concerns neutrally and let the reviewer reach their own conclusion. Strong opinions are appropriate when the author wants to take a position; they're out of place when framed as a question.
- Cut hedges that add no information ("perhaps", "possibly", "I think"). Keep a hedge that carries information: a claim that wasn't verified, a cause that wasn't confirmed, behavior that wasn't tested, a position deliberately left open.
- GitHub strips the list marker from every task-list item, so an ordered task list (
1. [ ]) renders exactly like- [ ]with no visible numbers. Use- [ ]for checklists and let item order carry the sequence. When the reader needs the numbers, write them into the item text.
Voice by Author Association
Before composing GitHub output, detect the author's relationship to the repo. For an existing PR or issue, check author_association on that object:
gh api repos/<owner>/<repo>/issues/<number> --jq '.author_association'
When no artifact exists yet, check your own access on the repo the artifact will be filed against, which is the PR base or the issue target. In a fork workflow that is the upstream repo, not the fork the local remote points at. true means insider:
gh api repos/<owner>/<repo> --jq '.permissions.push'
Insider (OWNER, MEMBER, COLLABORATOR)
Write as a teammate. No third-person references to the team you're on, no deferential offers. State things directly.
Skip context the teammate already has. Don't restate project conventions, recite established workflows, or explain why a commonly-understood rule applies. A reply like "Fixed in ." or "Reverted in ." is often all that's needed. Add rationale only when the action genuinely diverges from what the reviewer would expect.
Outsider (CONTRIBUTOR, FIRST_TIME_CONTRIBUTOR, FIRST_TIMER, NONE)
Write as an outside contributor. Referring to "the project" or "the maintainers" is natural. Deferring to maintainer preferences is appropriate.
If the relationship cannot be determined, default to outsider voice.
Handoff
Write a session handoff file at .turbo/handoff/<YYYY-MM-DD>-<slug>.md so a fresh session can pick up where this one left off.
Step 1: Resolve the Target Path
Get today's date: date +%Y-%m-%d.
Pick a slug for the current task:
- Lowercase
- Replace non-alphanumeric characters with hyphens
- Collapse consecutive hyphens
- Trim leading and trailing hyphens
- Truncate to 40 characters at a word boundary
If the work is anchored to an existing plan at .turbo/plans/<slug>.md, reuse that plan's slug verbatim.
The user may pass an explicit slug or output path; honor it.
Resolve the repo root with git rev-parse --show-toplevel, except inside a linked worktree — where git rev-parse --git-dir differs from --git-common-dir — in which case use the parent of the common dir, so the handoff lands in the main checkout rather than in a worktree that is destroyed with its branch.
The target path is .turbo/handoff/<YYYY-MM-DD>-<slug>.md under that root. A generated slug takes -2, -3, and so on until the path is free. When the user supplied the slug or path and it already exists, use AskUserQuestion to offer overwrite, a numeric suffix, or a different slug.
When an open decision will outlive the rest of the session's state, still unresolved while the work around it is finished, give it its own handoff. Everything else stays in a single file. Slug the split handoff for that decision rather than appending a collision suffix, and write it to stand alone.
State the chosen path before continuing.
Step 2: Gather Session State
Run git status --short to see uncommitted changes in the working tree.
Survey the conversation context for:
- Current task: what is being worked on, in one or two sentences
- Workflow status: where in the workflow this session is (drafting, refining iteration N, applying findings, implementing step M of K, investigating, blocked on Q, etc.)
- Active artifact: path to the plan or other file at the center of the work, if one exists
- Open decisions: questions raised but not resolved, choices the user is still weighing, escalations awaiting input, actions only the user can take
- In-flight changes: staged or unstaged edits that are not yet committed; what each change is doing and what is missing
- Closed avenues: approaches that were built or tested and then abandoned, with the observed evidence that ruled them out
- Next step: the first concrete action the new session should take. When the user has stated what they want to work on next, that intent leads and any work left in flight is ordered after it; say so in the same statement when that work should not resume at all
Call the mcp__turbo__open-items tool with action set to list, and carry each item's text and detail, without its id, into the open decisions, merging any the survey already found.
Read the backlog under the repo root resolved in Step 1: .turbo/backlog.md, and the legacy .turbo/improvements.md when one exists. Note any entry this handoff takes over. When no entry clearly matches, leave the backlog alone.
When something is genuinely unclear and would leave a gap in the handoff, use AskUserQuestion to resolve it. Default to inferring quietly when the conversation makes the answer clear.
Step 3: Write the Handoff File
Write the file at the path picked in Step 1 with the Write tool, which creates .turbo/handoff/ if it does not exist, including when that path is in the main checkout outside the current working directory: the Bash sandbox denies a shell write there.
When that write is refused while this session runs inside a linked worktree, write it under the same file name directly in the session scratchpad directory instead, and carry that absolute path forward as the handoff's path. Leave it out of the worktree's own .turbo/, which is gitignored and is destroyed with the worktree.
Lead with # Handoff: <Task Title>. Cover the items gathered in Step 2 in whatever structure fits the session — drafting, refining, implementing, and investigating sessions each have different shapes and don't all map to the same headings. Close with a clear statement of the next concrete action so the new session knows exactly what to do first.
Keep it dense. Omit anything that has no real content. Point to content a plan, issue, commit, or diff already holds by path, URL, or hash rather than restating it. Carry content that lives only in a linked worktree's uncommitted changes or gitignored files into the handoff itself.
Write <REDACTED> in place of any secret the session handled, such as an API key, token, or password.
When this handoff splits an open decision out of an existing one, add a line to that existing handoff pointing at the new path, and remove the content the new file now carries.
Step 4: Confirm
Once the handoff file exists, delete each backlog entry noted in Step 2 from the file that holds it. Delete a backlog file left with no entries. When the handoff was written to the session scratchpad directory, leave those entries in place and name them as still in the backlog.
Tell the user where the handoff was written, name any backlog entry deleted and any existing handoff edited to point at a split, and quote the next-step statement so the path forward is visible at a glance.
Then use the TaskList tool and proceed to any remaining task.
Implement Backlog
Validate improvements from .turbo/backlog.md, propose a specific working set based on the backlog's actual contents, and run one lane per session: direct, investigate, or plan. Mixing lanes in a single run tangles commits, so the skill processes exactly one lane each time. Entries outside the confirmed working set stay in the backlog for future runs.
When a working set and a lane were passed in, by the user or in a message from another session, start at Step 5 with them and create tasks for Steps 5 and 6 alone. Resolve the repo root as Step 1 does, read each working-set entry in full from .turbo/backlog.md under it, and run the lane with each entry's full text alongside what was passed in. When an entry is not there, run the lane with what was passed in for it.
Task Tracking
At the start, use TaskCreate to create a task for each step:
- Read the backlog
- Validate and classify
- Recommend, confirm, and update the backlog
- Brief the extra sessions
- Run the chosen lane
- Prune working-set entries from the backlog
Step 1: Read the Backlog
Resolve the repo root with git rev-parse --show-toplevel, except inside a linked worktree — where git rev-parse --git-dir differs from --git-common-dir — in which case use the parent of the common dir.
When that root holds the legacy .turbo/improvements.md, carry it into .turbo/backlog.md before reading, with the Write or Edit tool. When .turbo/backlog.md does not exist, write the legacy content there with its # Improvements header changed to # Backlog. Otherwise, append each legacy entry that .turbo/backlog.md does not already hold word for word. Once .turbo/backlog.md holds every legacy entry, delete the legacy file. When the write or the deletion is refused, tell the user what is left to do.
Read .turbo/backlog.md under that root. If it does not exist, there are no backlog entries to implement; stop.
Parse all entries, extracting for each:
- Summary (the
###heading) - Type (
direct,investigate, orplan; may be missing in older entries —trivialandstandardare accepted as legacy aliases fordirectandplan) - Category
- Where (file paths or areas)
- Why (rationale)
- Ceiling and Revisit (present when the entry records a deliberate simplification; Revisit alone when the entry waits on an outside event)
- Noted (date)
- Validated (present when an earlier run recorded what the entry's verdict rested on)
Step 2: Validate and Classify
Improvements drift: files get renamed, code gets refactored, issues get fixed as side effects of other work. Before routing, validate each improvement and settle the Type of any entry whose Type is missing or wrong.
Reuse an Earlier Validation
Before validating, note the root of the checkout whose code this step reads (git rev-parse --show-toplevel). When that checkout has the default branch checked out (resolve it with gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name'), run git -C <root> fetch and fast-forward that branch to its upstream with git -C <root> merge --ff-only @{upstream}. When any of these commands fails, report it and validate the checkout as it stands. Then note its commit (git -C <root> rev-parse --short HEAD). The path check for a commit and a set of repo-relative paths passes when git -C <root> diff --quiet <commit> -- <paths> exits 0 and git -C <root> ls-files --others --exclude-standard -- <paths> prints nothing.
For each entry carrying a Validated line, run the path check with its recorded commit and paths, and run each command nested under it from that root. When the path check passes and every command prints its recorded output, whatever its exit status, classify the entry with its recorded verdict and skip the rest of this step for it. Otherwise, including when a command cannot run or cannot reach its source, or when it reads a source outside the repo and would print its recorded output on a failed read too, validate the entry in full.
Validate
For each entry, verify whether the specific problem or opportunity described still exists. Do not rely on git log alone. Recent commits touching the same files do not mean the specific issue was addressed. Read the actual code and confirm:
- Files exist — Do the referenced files/paths still exist? When one was renamed or its code moved, validate the entry at the current location instead. This check marks the entry stale only when the code it names is gone.
- Problem persists — Read the relevant code sections. Is the exact issue or opportunity described in the entry still present? Check the specific claims: if the entry says a function is uncalled, verify it has no callers; if it says error handling is missing, check whether it was added.
- Revisit condition met — For an entry carrying a Revisit field, check whether the recorded condition now holds. A shipped simplification is present by construction, so its presence alone says nothing about whether the fuller version is worth building yet.
- Stated scope matches the real gap — For an entry claiming missing coverage, read what existing tests already pin before accepting its scope: a test that substitutes a test double at a boundary pins the behavior on one side of it and leaves the boundary itself unpinned, so a request to cover several variants often reduces to the single boundary they share. Before dropping an item on the grounds that an existing check covers it, confirm that the check pins that item through its own inputs or match patterns rather than inferring it from the check's name or description; an item no existing check pins stays in the entry's scope. Restate such an entry at its real scope, classify it Active, and use the restatement as its summary in Step 3.
- Claimed consequence holds — For an entry claiming that two paths behave differently, that a change would alter observable behavior, or that the code as it stands leads to a stated outcome, verify the consequence itself rather than confirming only that the code it points at exists. For a claimed difference, between two paths or between the behavior before and after a change, read what each actually returns, exercising both when reading cannot settle it. For a claimed outcome, follow the path from the named code to that outcome and confirm nothing later on that path already stops it. When the claim is that nothing but the case it names reaches or relies on the named code, read that code's own tests: they surface dependents an entry written from a single path routinely omits, and turning up none leaves the claim unproven. When the named code is present but its stated consequence is false, restate the entry at the benefit it actually delivers, classify it Active, and use the restatement as its summary in Step 3; classify it Stale when no benefit survives.
Before using a restatement as an entry's summary in Step 3, confirm each fact it adds to the entry against the code, or against the dependency's shipped artifact when the fact concerns a dependency. When the fact is that a dependency provides a capability, also confirm that the dependency's documentation says the capability is available, since code present in the shipped artifact can be gated off, internal, or not yet public.
Classify each entry as:
- Active — The described problem or opportunity is confirmed present in the current code
- Deferred — The entry carries a Revisit condition that does not yet hold: the shipped approach remains the right one, or the event the entry waits on has not happened
- Stale — The code the entry names no longer exists, the specific issue has been resolved, or the entry's premise never held (cite evidence: what changed and where, or why the claim is false)
- Unclear — Cannot determine from code alone, needs user input
When in doubt, classify as Active. The cost of re-examining a resolved issue is low; dismissing a valid improvement is high.
Classify or Correct the Type
For any Active entry without a Type field, infer one on the fly. For an Active entry whose Type the code read contradicts, correct it. A recorded investigate is contradicted only when the code read settles the question the entry raises. Reading alone does not settle a question that turns on runtime behavior, such as ordering or timing. Base the classification on the code you just read during validation, not just the entry's one-line summary.
- direct — Clear scope and a known approach, ready to apply via
/implement. - investigate — A symptom that needs root-cause analysis first: unclear root cause, performance question, intermittent bug, "something feels off".
- plan — Everything else: the approach warrants writing down before implementing (multi-file refactor, test additions, feature work). Dispatched to
/plan, which routes the work itself.
Pick the type without asking the user. Default to plan when a missing Type is genuinely ambiguous, and keep a recorded Type the code read does not contradict.
Step 3: Recommend, Confirm, and Update the Backlog
When at least two entries are Active, use the ListAgents tool and note the local sessions it shows before outputting anything in this step.
Output the backlog status as text first, grouped by type and status. Include each entry's category inline and a category tally across active entries:
## Backlog Status
Reused earlier validations: N of M entries carrying a Validated line
### Active (N)
Categories: refactor (N), performance (N), testing (N), docs (N)
**Direct (N)**
- [summary] (category) — [one-line reason it's still relevant]
**Investigate (N)**
- [summary] (category) — [one-line reason it's still relevant]
**Plan (N)**
- [summary] (category) — [one-line reason it's still relevant]
### Deferred (N)
- [summary] — [the revisit condition, and what still has to happen]
### Stale (N)
- [summary] — [one-line reason it's stale]
### Unclear (N)
- [summary] — [what's ambiguous]
Recommend a Working Set
When no entry is Active, skip the recommendation: a Deferred entry is not a candidate.
Pick one specific working set tailored to the active entries. Read the entries again before recommending and weigh:
- Cohesion — Entries that share files, modules, or themes are stronger when batched. A cluster of related testing or reliability entries usually beats a scattered mix.
- Decisiveness — One investigation that unblocks several deferred entries can outweigh a larger direct batch.
- Supersession — When an active entry's work, or the pending next step of an entry that lays out several, would rewrite, replace, or make moot the code other active entries target, that work can outweigh a direct batch on that code. When another working set is recommended or offered as an alternative and still includes entries it supersedes, mark those entries as likely discarded by that work.
- Impact vs effort — A reliability or correctness entry whose problem was observed in use often outweighs lower-stakes cleanups even when it's a single entry. One derived from reading code or a review earns no such weight, less still when its fix adds machinery or public interface; count an entry whose Why records no observation as derived. Say in the recommendation when the recommended working set includes one.
- Lane shape — Each lane batches a cluster, just in different shapes. Direct groups clear-scope fixes into one
/implementrun. Investigate dispatches/investigateper symptom, then shares one/implementfor the concluded fixes. Plan hands a cohesive cluster to/plan, which routes the work itself. - Unit of work size — Right-size the session. Prefer the whole cohesive cluster over a narrow filter unless the filter clearly preserves a coherent unit of work; picking 1–2 entries off a cluster of 7 wastes the slot. Route any entry that turns out to be a clear-scope direct fix to the direct lane instead.
- Backlog state — Heavy direct concentration calls for clearing the cluster; a long-deferred symptom often deserves the slot.
State the recommendation as: lane + concrete working set (specific entries or a category-scoped subset) + one or two sentences on why this beats the alternatives. Then list 1–3 honest alternatives, each named with the actual entry or subset (e.g., "investigate the flaky presence test", "plan lane on persist-before-send"). When only one lane has active entries, recommend that lane and skip alternatives.
Then check the active entries outside the recommended working set for parallel sets: working sets an extra session can run at the same time. A parallel set touches no file the recommended working set or another parallel set touches, and no set supersedes another. Name each parallel set with its lane after the alternatives.
Confirm via AskUserQuestion
Use AskUserQuestion to confirm. Combine into the same prompt:
- Confirm the recommended working set or pick one of the named alternatives — include only when active entries exist. When parallel sets exist, add an option that runs the recommended working set here and each parallel set in an extra session, naming how many extra sessions that takes, in place of the weakest alternative when the options would exceed four.
- Whether to remove stale entries — include only when stale entries exist
- Resolution for unclear items — include only when unclear entries exist
Skip the call when no item applies.
If the user confirmed stale removal, edit .turbo/backlog.md to delete the stale entries.
Rewrite in .turbo/backlog.md each Active or Deferred entry whose path, scope, count, consequence, or Type Step 2 corrected, changing only the fields the correction touches, and write the Type Step 2 inferred into each Active entry that lacked one. When that changes an entry's summary, update each Paired with line in its counterpart entries that names the old title.
Record the validation on each Active or Deferred entry that Step 2 validated in full, after its Noted line, replacing any Validated line it carries together with the command lines nested under it:
- **Validated**: <YYYY-MM-DD>, <Active | Deferred> at `<commit>`: `<path>`, `<path>`
- `<command>` → `<output>`
- Commit — the commit Step 2 noted.
- Paths — repo-relative, every file or directory whose content the verdict rests on: the ones the entry names, and the callers, tests, and configuration Step 2 read to reach the verdict.
- Commands — one line for each fact the verdict rests on that the paths do not pin: a repo-wide search that established something is absent, or a fact outside the repo, such as a dependency's latest release or an upstream issue's state. Have each print the one value the verdict turns on, such as a match count or a release tag. When it cannot reach its source, have it print a value no successful run could print, such as
fetch-failedwhen a download fails.
Leave the Validated line off an entry when the path check fails for its commit and paths now, when git -C <root> ls-files --error-unmatch -- <paths> fails because a path is untracked or ignored, or when a fact its verdict rests on has neither a path nor a command that pins it. A Revisit condition only a person can observe, such as a user report, is exempt and needs no command.
Compute the working set from the confirmed choice. If the working set is empty, stop.
Step 4: Brief the Extra Sessions
Skip this step unless the user confirmed the parallel option.
Read references/parallel-split.md and follow its phases.
Step 5: Run the Chosen Lane
Read the reference file for the confirmed lane and follow its phases:
- Direct lane — references/direct-lane.md
- Investigate lane — references/investigate-lane.md
- Plan lane — references/plan-lane.md
State the chosen lane before continuing with the reference file.
Step 6: Prune Working-Set Entries from the Backlog
When this session runs inside a linked worktree (where git rev-parse --git-dir differs from --git-common-dir), use AskUserQuestion to offer two options: leave the worktree and prune from the main checkout, or stay in the worktree. List leaving first and label it (Recommended). While the branch's pull request is open (gh pr view <branch> --json state), list staying first and label it (Recommended) instead.
- Leave — Leave with the ExitWorktree tool (
action: "keep"). When it reports that no worktree session is active, take the Stay path instead. Otherwise:- Resolve the default branch with
gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name'. Fast-forward the main checkout's local default branch toorigin/<default-branch>without switching the branch the main checkout has checked out. When the fast-forward fails, report it and leave that branch as it is. - When the worktree's commits are on
origin/<default-branch>(git merge-base --is-ancestor <branch> origin/<default-branch>) or its branch's pull request is merged (gh pr view <branch> --json state,headRefOid), remove the worktree withgit worktree remove <path>. When git refuses over files this session copied in from the main checkout, delete those copies and remove it again. Otherwise keep the worktree, without--force. - Delete the branch with
git branch -d <branch>when its commits are onorigin/<default-branch>, or withgit branch -D <branch>when its pull request is merged and the branch's tip is that pull request'sheadRefOid. Keep it otherwise, or when git refuses. - Report what was kept, then continue with the rest of this step from the main checkout.
- Resolve the default branch with
- Stay — List every edit the rest of this step would make to the backlog, and print each entry
/backlogcould not persist from the worktree, so both can be applied from a session that can write to the main checkout. Skip the rest of this step, then use the TaskList tool and proceed to any remaining task.
Edit .turbo/backlog.md to delete the working-set entries that the lane processed. "Processed" means:
- Direct lane — entries whose fixes were applied
- Investigate lane — entries the applied fixes resolve in full, and entries whose investigation established that no defect exists
- Plan lane — entries captured in the plan file
/planwrote, and entries whose fixes were applied in this session. Treat planned entries as processed once the plan is written.
Keep any entries the lane re-classified mid-flight (direct → investigate/plan, or investigate → plan), and any entry of which the working set took only one step of several. These stay in the backlog for a future run. Remove the Validated line, with the command lines nested under it, from each working-set entry that stays. Delete the file if no entries remain.
Rewrite in place each kept entry of which the working set took only one step: restate its summary and Where as the steps that remain. When the rewrite changes the summary, update each Paired with line in counterpart entries that names the old title.
Rewrite in place each entry the investigate lane investigated that stays in the backlog: restate its summary and Where as what remains to do, put what the investigation established in its Why (the root cause it confirmed, or the hypotheses it refuted when the cause stayed unresolved), and set the Type the remainder calls for. When the entry waits on an outside event, such as an upstream fix, record that event as its Revisit. When the rewrite changes the summary, update each Paired with line in counterpart entries that names the old title.
When the restated Where names files in another repo, delete the entry in place of rewriting it, drop each Paired with reference to it from its counterpart entries, then run the /backlog skill for the entry as restated, with its Category, Type, Why, and any Ceiling or Revisit.
When a processed entry carries a Paired with line, drop that reference from each counterpart entry it names, so no backlog is left pointing at an entry that no longer exists.
When this session left its worktree at the start of this step, run the /backlog skill for each entry /backlog could not persist from the worktree.
Then use the TaskList tool and proceed to any remaining task.
Rules
.turbo/is gitignored. Edits to.turbo/backlog.mdare local-only and do not need to be staged or committed.- Run exactly one lane per session. Leave active entries outside the confirmed working set and the briefed parallel sets in the backlog for a future run.
Implement Findings
Apply evaluated findings and close out the change.
Task Tracking
At the start, use TaskCreate to create a task for each step:
- Run
/code-styleskill - Run
/apply-findingsskill - Close out the change
Step 1: Run /code-style Skill
Run the /code-style skill to load existence, reuse, mirror, and symmetry rules before editing.
Step 2: Run /apply-findings Skill
Run the /apply-findings skill on the evaluated findings.
Step 3: Close Out the Change
If no changes were made, skip this step.
Use AskUserQuestion to choose how to close out the change:
- Full QA — run the
/finalizeskill - Quick close — run the
/quick-finalizeskill
Then use the TaskList tool and proceed to any remaining task.
Implement Plan
Execute an implementation plan file.
Task Tracking
At the start, use TaskCreate to create a task for each step:
- Resolve and read the plan file
- Read context files
- Run
/implementskill - Update plan status
Step 1: Resolve and Read the Plan File
Determine which plan file to implement using these rules in order:
- Explicit path — If an absolute or relative path was passed and that file exists, use it
- Explicit slug — If a slug was passed (e.g.,
add-image-cache), resolve to.turbo/plans/<slug>.mdif that file exists - Single file — Glob
.turbo/plans/*.md. If exactly one plan exists, use it - Most recent — If multiple plans exist, use the most recently modified
- Legacy fallback — If
.turbo/plans/does not exist but.turbo/plan.mdexists, use it - Nothing found — If no rule above resolved to an existing file, tell the user to run
/turbo:planand stop. When a slug or path was passed but no file matched it, say which one was tried
If multiple plans exist and the most-recent choice is non-obvious (e.g., several plans were modified within the same minute), use AskUserQuestion to let the user pick from the candidates.
State the resolved plan path before continuing, then read the file.
Unless an explicit path or slug was passed, confirm the resolved plan still describes work that remains to be done:
- Already implemented — the frontmatter
status:isdone - Waiting on a gate — the plan's Context states a gate that must pass before its work can start
When you check whether a gate has passed, check each condition it names at its source of record, such as the remote's tags for another repository's release, rather than a local copy.
When a signal fires, output it as text. Then use AskUserQuestion to offer:
- Implement anyway — the marker is stale, or the gate has passed
- Pick another plan — resolve to a different file under
.turbo/plans/, then confirm that plan against these same signals - Leave it unimplemented — the plan needs revising first, or its gate has not passed
On Leave it unimplemented, tell the user to bring the plan current with /turbo:refine-plan and run this skill again, or, for a plan whose gate has not passed, to run this skill again once it has. Mark the remaining implement steps deleted, then use the TaskList tool and proceed to any remaining task.
When the input asks to implement in a worktree and this session does not already run inside a linked worktree (where git rev-parse --git-dir differs from --git-common-dir), enter a new git worktree with the EnterWorktree tool. Name it after the plan's slug. Keep using the plan at its absolute path in the main checkout, and read the files it references under .turbo/ from the main checkout too. Copy from the main checkout each file the worktree lacks that the work needs, such as gitignored local configuration or untracked project instructions, and leave each copied file out of every commit.
Step 2: Read Context Files
The read list, every file to read in full:
- Every file listed in the plan's Context Files section
- Files the user referenced in their original request (if any)
- Every file path the plan references in the Context, Pattern Survey, and Implementation Steps sections
Project the read's share of the context window before the bulk of it. With one Bash call, get the size in bytes of each read-list file that exists, and their total. Call the mcp__turbo__context-level tool, then read the plan's Context Files. Once those reads have returned, call the tool again. While the reading has dropped fewer than five percentage points and read-list files remain unread, read a further batch and call the tool again. The projection is the drop from the first reading to the last, multiplied by the total bytes over the bytes read so far.
When the projection is above 25%, output as text that reading the plan's files is projected to take that share of the context window, with the number of files still unread. Then use AskUserQuestion to ask how to implement the plan:
- Implement in this session — this session reads the remaining files and implements every step itself, and will likely need to compact before QA. Mark it recommended when the projection is 50% or less.
- One subagent per step — the remaining files stay unread here, and each Implementation Step goes to a fresh subagent that reads what its step names. Every subagent gathers its own context, so the run takes longer and uses more tokens overall. Mark it recommended when the projection is above 50%.
Read the remaining read-list files unless the answer was One subagent per step.
Step 3: Run /implement Skill
Run the /implement skill. The plan file, its file references, and its Verification section are already in conversation context from Step 1. When Step 2 settled on one subagent per step, pass that choice along.
Step 4: Update Plan Status
After /implement completes, when this session runs inside a linked worktree (where git rev-parse --git-dir differs from --git-common-dir), use AskUserQuestion to offer two options: leave the worktree and update the plan from the main checkout, or stay in the worktree. List leaving first and label it (Recommended). While the branch's pull request is open (gh pr view <branch> --json state), list staying first and label it (Recommended) instead.
- Leave — Leave with the ExitWorktree tool (
action: "keep"). When it reports that no worktree session is active, take the Stay path instead. Otherwise:- Resolve the default branch with
gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name'. Fast-forward the main checkout's local default branch toorigin/<default-branch>without switching the branch the main checkout has checked out. When the fast-forward fails, report it and leave that branch as it is. - When the worktree's commits are on
origin/<default-branch>(git merge-base --is-ancestor <branch> origin/<default-branch>) or its branch's pull request is merged (gh pr view <branch> --json state,headRefOid), remove the worktree withgit worktree remove <path>. When git refuses over files this session copied in from the main checkout, delete those copies and remove it again. Otherwise keep the worktree, without--force. - Delete the branch with
git branch -d <branch>when its commits are onorigin/<default-branch>, or withgit branch -D <branch>when its pull request is merged and the branch's tip is that pull request'sheadRefOid. Keep it otherwise, or when git refuses. - Report what was kept.
- Resolve the default branch with
- Stay — Continue in the worktree.
Set the plan's frontmatter status: to done with the Edit tool, in the plan under the main checkout's .turbo/plans/ when this session runs inside or has left a linked worktree. If the plan is the legacy .turbo/plan.md without frontmatter, skip the status update.
When that edit is refused while this session runs inside a linked worktree, report that the status update was not applied and name the edit to make from a session that can write to the main checkout: status: done in the resolved plan path.
When the plan's Context names a larger source it implements part of (an assessment, a backlog, an issue), report the plan's completion separately from that source's: name the source's items the plan left out, and say whether another plan under .turbo/plans/ covers them.
When this session left its worktree in this step, run the /backlog skill for each entry /backlog could not persist from the worktree.
Rules
- The plan file is read-only during execution. If revisions are needed, the user runs
/turbo:refine-planor/turbo:draft-planseparately. - Never skip Step 2.
- Never enumerate or execute the plan's Implementation Steps inline. The work runs through
/implement. Restating steps as a turn-level narration counts as inline execution and bypasses the delegation. - If the plan's Implementation Steps or Verification include
git commit,git push, or PR creation, halt before Step 3 and ask the user to remove them via/turbo:refine-plan. A Verification item that observes the result of a push without instructing one is not grounds to halt.
Implement
Standard implementation flow: load style rules, make the change, run post-implementation QA.
Task Tracking
At the start, use TaskCreate to create a task for each step:
- Run
/code-styleskill - Load task-specific skills
- Make the change
- Run verification
- Run
/smoke-testskill for UI/UX changes - Run
/previewskill for UI/UX changes - Post-implementation QA
Step 1: Run /code-style Skill
Run the /code-style skill to load existence, reuse, mirror, and symmetry rules before editing.
Step 2: Load Task-Specific Skills
Scan the work for types that match available skills, matching against the richest context available: a plan's Implementation Steps if a plan is in conversation context, otherwise the user request, a prior skill's task description, or an improvement entry. For each unambiguous match, run the skill via the Skill tool. For example, if the work includes "add a Drizzle migration" and a skill exists whose triggers reference Drizzle migrations, load it. If a work type has no matching skill trigger, do not load a generic skill.
If unsure, do not load.
Step 3: Make the Change
Unless one subagent per step was settled on for a plan that governs the work, apply the change described by the current context — the user request, a prior skill's task description, or an improvement entry. Keep the edit scoped to what the context describes.
When the fix changes how a value is constructed, grep for every other site that constructs it and fix the ones carrying the same defect; treat these siblings as part of the same change. If the scope balloons beyond what the context specified, stop and confirm scope before continuing.
When a plan governs the work and one subagent per step was settled on for it, the Implementation Steps go to subagents, and this session reviews what each one returns. Use TaskCreate to create a task for each Implementation Step, then take them in order, one at a time.
Before each spawn, capture git status --short and run git stash create, which snapshots the working tree without changing it and prints nothing when the tree is clean.
Spawn a single subagent (model: "opus", no name). Wait for it to report before continuing; do not relaunch it if it has not yet reported. Its prompt directs it to read ${CLAUDE_SKILL_DIR}/references/step-implementer.md, and gives:
- The plan's path and the Implementation Step to implement
- What earlier Implementation Steps changed that this one builds on, and anything they left for it to finish
- The task-specific skills from Step 2 that this Implementation Step's work matches
- The checks it must pass
- A cap on any verification whose count the plan leaves open, such as mutation runs
When it reports, stop it with TaskStop on its agent ID, which also ends any background command it left running; a reply that it is not running needs nothing further. Then review what it changed against the plan: git diff <snapshot>, or git diff HEAD when the tree was clean, shows its changes to tracked files, and git status --short compared with the capture shows the files it added. Run the checks the prompt named. Then settle everything the report leaves open before the next Implementation Step starts:
- Make a small correction in this session.
- Give larger rework, or a block this session can clear, to a new subagent for the same Implementation Step, passing along what the first one reported.
- Take a block or a deviation that changes what the plan delivers to the user with
AskUserQuestion, and carry out the answer through one of the two routes above. - Carry a gap that a later Implementation Step's work closes into that step: name it in that step's prompt, and confirm it closed when reviewing what that step changed.
Mark the Implementation Step's task completed once nothing is left open.
When the user asks how a running subagent is doing, read its progress from the same comparison against the capture. When the user asks to change its course, message it with the SendMessage tool. After a subagent has reported, changes go through the routes above.
Step 4: Run Verification
Before this step starts or uses a process that runs until it is stopped, such as a server or a watcher, run the /test-run-rules skill. Its rules verify without modifying code, so act on a failed check as this step directs.
If a Verification section is in conversation context (e.g., from a plan file), execute the commands, smoke checks, or MCP tool invocations it specifies. If a check fails, run the /investigate skill. Fix what it finds in the code, or in a test whose assertion contradicts the behavior the change intends, and leave the failing check as strict as it was: disabling, skipping, or retrying a test, disabling or downgrading a rule, lowering a threshold, or widening an ignore list fixes nothing. If a check is blocked by a dependency, unclear requirement, or environmental issue, or is itself wrong for the code, use AskUserQuestion to surface the blocker and let the user choose how to proceed. If no Verification section is in context, go straight to the configuration check below.
When the Verification section lists both checks that can force code edits, such as a formatter or a linter, and a slow run, such as an integration suite, finish the edit-forcing checks and the edits they force before starting the slow run. When an edit lands after a slow run started, re-run it; when re-running is not practical in this session, state which part of the verification the final code did not get.
When the change adds or documents a configuration override — an environment variable, build flag, or any setting a reader is told to set — prove that a supported path delivers it: set the value, run the build or process meant to consume it, and confirm the output changed. When no supported path delivers it, fix the path or drop the documentation before this step completes. Restore the setting afterwards, and rebuild or discard any output produced with the non-default value. Passing checks are no evidence here, since a default that matches the value already in use keeps a broken override invisible to every run that never asks for a different one.
Step 5: Run /smoke-test Skill for UI/UX Changes
If the change touches a user-facing surface (UI components, styles, templates, markup, user-facing routes or screens), run the /smoke-test skill. When that is unclear, use AskUserQuestion to ask whether the change is user-facing rather than skipping silently. Skip this step for changes with no user-facing surface (backend-only, CLI, library, build or config).
/smoke-test verifies without modifying code, so act on what it reports here: fix each failure and re-run it. When the same failure survives a fix attempt, run the /investigate skill; if investigation finds no root cause, stop and report with its findings. When a blocker cannot be cleared in this session (a path needing real credentials, an external service, or state unavailable here), carry it into Step 6 rather than treating it as a failure. When a fix made here edited code, re-run the Step 4 checks it could affect once no failure remains; when re-running is not practical in this session, state which part of the verification the final code did not get.
Step 6: Run /preview Skill for UI/UX Changes
If Step 5 determined the change is user-facing, run the /preview skill so the user can try it firsthand before QA. Skip this step otherwise. Pass along any blocker Step 5 could not clear, so the hand-over names the cases still left to the user.
Step 7: Post-Implementation QA
When a plan file governs the work, hold this step until every Implementation Step has been applied, and continue to the next Implementation Step at every earlier boundary.
Before starting QA, check for a context signal. Call the mcp__turbo__context-level tool: a reading of 50% or less remaining is one. A request from the user to compact, arriving since the session last compacted, is the other. When the reading is 50% or less and the user has not asked to compact, use AskUserQuestion to ask whether to compact before QA: "Handoff, then compact", marked recommended, or keep going in this session. On "Handoff, then compact", or when the user asked to compact, run the /handoff skill, or, when this session already wrote a handoff, edit that file. Point its next step at what follows here: the /finalize skill when a plan file governs the work, naming the plan's path, and the choice among full QA, a quick close, and stopping otherwise. Use TaskUpdate to set this step's task description to that same next step and leave the task in progress. Then call the mcp__turbo__compact-and-continue tool with the handoff's path. End the turn in place of the TaskList call that closes this step, telling the user that the session compacts and continues on its own, and that if it does not, they should run /compact and then reply "continue".
When a plan file governs the work, run the /finalize skill.
When no plan file governs the work, use AskUserQuestion to offer three options:
- Full QA — run the
/finalizeskill - Quick close — run the
/quick-finalizeskill - Stop here — leave the change as-is
Then use the TaskList tool and proceed to any remaining task.
Rules
- Defer
git commit,git push, and PR creation to Step 7. - Don't reference
.turbo/content (filenames, acceptance criteria, step numbers, headings) in code or comments..turbo/is gitignored, so these references would be opaque to anyone reading without local copies.
Interpret Feedback
Run two independent interpretations of third-party feedback in parallel (internal + codex peer), then reconcile into enriched items with clear intent summaries. Designed for feedback where the author's intent is ambiguous or the correctness of suggestions is uncertain.
Step 1: Identify Feedback Items
Determine the feedback to interpret:
- If feedback items are in conversation context, use them
- If a file path or URL was provided, read or fetch the content
- If called by another skill, use the items passed in
For each item, collect whatever context is available: code snippets, diffs, surrounding discussion, file paths, line numbers. More context produces better interpretation.
Step 2: Run Two Interpretations in Parallel
Emit both Agent tool calls below in one assistant message. Each Agent call uses model: "opus" and no name. Wait for every agent to report before continuing. Do not begin the next step on a partial set, and do not relaunch an agent that has not yet reported. That is two Agent tool calls total. Both agents' prompts must direct them to treat the shared working tree and its git index as read-only and to interpret by reading and reasoning. HEAD stays where it is: read other refs with git show <ref>:<path> rather than git checkout or git switch.
Internal Interpretation
Spawn a subagent with the feedback items and all available context. Instruct it to:
- Read all referenced code and surrounding context
- For each feedback item, produce:
- Intent: What the feedback author most likely wants changed and why (one to two sentences)
- Correctness: Whether the suggestion is technically sound — flag concerns if the reviewer may be mistaken, with evidence
- Ambiguity: Note where the intent is unclear or where multiple valid readings exist
- Return structured results per item
Run /peer-review Skill
Launch an Agent tool call whose prompt instructs the subagent to invoke /peer-review via the Skill tool. Describe the request in natural language:
- Material — the listed third-party feedback items and their surrounding context.
- Task — for each item, determine what the author most likely wants changed and why, whether the suggestion is technically sound, and where the phrasing is ambiguous enough to support multiple valid readings.
- Skepticism guidance — do not take feedback at face value. Check whether the author's stated concern matches the code reality. Look for cases where the reviewer misread the code, confused two similar constructs, or applied a general rule that does not fit this specific context.
- Output format — for each feedback item, return:
- Intent — what the author most likely wants changed and why (one to two sentences)
- Correctness — whether the suggestion is technically sound. If not, explain what the reviewer likely misunderstood, with evidence from the code
- Ambiguity — if the intent supports multiple valid readings, list each reading and which has stronger evidence
- Confidence — high (clear intent, sound suggestion), medium (likely intent but some uncertainty), or low (genuinely ambiguous or likely incorrect)
The prompt must also state explicitly that the subagent's final assistant message must contain the verbatim findings text /peer-review produced.
Step 3: Reconciliation
Merge the two interpretations for each feedback item:
| Agreement | Action |
|---|---|
| Both agree on intent and correctness | High confidence. Use the shared interpretation. |
| Intent agrees, correctness differs | Flag the correctness concern with both perspectives. |
| Intent disagrees | Flag as ambiguous. Present both readings and note which has stronger evidence. |
Step 4: Output Enriched Items
For each feedback item, output the original feedback followed by the interpretation:
### Item <N>: <short label>
**Original:** <feedback text, truncated if long>
**File:** <path:line if applicable>
**Intent:** <reconciled interpretation of what the author wants>
**Correctness:** <sound | concern: <explanation>>
**Confidence:** <high | medium | low>
**Ambiguity:** <none | <description of unclear aspects>>
<If interpreters disagreed, show both perspectives>
After all items, add a summary:
## Interpretation Summary
- Total items: <N>
- High confidence: <N>
- Correctness concerns: <N>
- Ambiguous intent: <N>
Then use the TaskList tool and proceed to any remaining task.
Rules
- If either interpretation agent is unavailable or returns malformed output, proceed with results from the remaining agent.
Investigate
Systematic methodology for finding the root cause of bugs, failures, and unexpected behavior. Cycle through characterize-isolate-hypothesize-test steps, with oracle escalation for hard problems. Diagnose the root cause — do not apply fixes.
Optional: $ARGUMENTS contains the problem description or error message.
Step 1: Characterize
Gather the symptom and establish what is actually happening:
- Collect evidence — error message, stack trace, test output, log entries, or user description of unexpected behavior
- Classify the problem type:
| Signal | Type |
|---|---|
| Stack trace / exception | Runtime error |
| Test assertion failure | Test failure |
| Compilation / bundler / build error | Build failure |
| Type checker error (tsc, mypy, pyright) | Type error |
| Slow response / high CPU / memory growth | Performance |
| "It does X instead of Y" / no error | Unexpected behavior |
- Establish reproduction — run the failing command, test, or operation, and confirm its output shows the reported symptom rather than a neighboring failure. When no command at hand shows the symptom, build one, trying whichever of these fit, in this order:
- A test at the boundary that reaches the failure
- A script that drives the running system from outside and asserts on what it returns
- A captured request, payload, or event log replayed through the failing path
- The same input run through a known-good version and the current one, with the outputs compared
- Many generated inputs, when the failure appears for only some
- For an intermittent failure, the trigger repeated or run concurrently until it fails often enough to test against
Reproduction is established when one command has been run and its output shows the reported symptom. Record that command and its output for verification. For intermittent or long-running reproductions, use the Monitor tool to tail logs filtered for relevant signals (errors, stack traces, specific identifiers) so failures surface live while you work.
When neither the failing command nor any reproduction built from the list above shows the symptom, output what was tried and what each attempt showed. Then use AskUserQuestion to offer three ways forward, and act on the answer:
- Provide access or an artifact — the user supplies an environment where the failure occurs, or a capture from one such as a log, a trace, or a recorded request. Return to item 3 with it.
- Allow temporary instrumentation — add labeled logging where the failure occurs, have the user trigger the failure, and read what it recorded. Remove the logging once it has been read, and confirm with
git diff -- <file>that each file is back to its pre-check state. Carry what it recorded into Step 2 as evidence. When it yields a command whose output shows the symptom, record that command as the reproduction; otherwise continue as under Proceed without a reproduction. - Proceed without a reproduction — document the constraints and continue on historical evidence. Mark Step 4 verdicts and the report's root cause
unverified by reproduction, and give the report's reproduction command asnone, followed by what was tried. When a later step produces a command whose output shows the symptom, record that command from then on and drop the mark.
Minimize the Reproduction
Cut the reproduction down in a throwaway copy, leaving the working tree and its git index unchanged. Remove inputs, configuration, data, callers, and steps, halving what remains before cutting single elements. Re-run after each cut and restore a cut that makes the symptom disappear. Stop when removing any remaining element makes the symptom disappear, or once the reproduction runs quickly and its remaining elements can be named. Record the minimal command alongside the original, with what was cut, then delete the copy and report anything that could not be deleted. The original stays the report's reproduction command. Skip when the reproduction is a single test or command with nothing left to remove, when each run is slow or intermittent, or when no reproduction exists.
Step 2: Isolate
Narrow from "something is wrong" to "the problem is in this area." Read references/problem-type-playbooks.md for type-specific first moves and tool sequences.
Git Archeology
For all problem types, check what changed recently near the failure point:
git log --oneline -20 -- <file>
git blame -L <start>,<end> <file>
If a known-good state exists (e.g., "this worked yesterday"), consider git bisect to pinpoint the breaking commit.
When the problem description names a version, tag, or build that differs from the ref under investigation, resolve it to a ref and read what changed on the failing path between the two before generating hypotheses:
git diff <reported-ref>..HEAD -- <failing-path-files>
Read the full diff rather than its --stat summary. Carry each difference that could produce the symptom forward as a ranked hypothesis.
Upstream Issue Search
When the failure surfaces inside a third-party dependency, search its issue tracker for a distinctive string from the error before reading deeper into the dependency's code. An issue whose symptom matches often names the cause and the fix outright. Carry a match forward as a ranked hypothesis and test it.
Scope Narrowing
- Stack traces: Read the throwing function and its callers — full functions, not just the flagged line
- Test failures: Read both the test and the system under test
- Build errors: Read the config file and the referenced source
- Unexpected behavior: Trace the data flow from input to the unexpected output
Before treating a record, file, or build artifact as evidence of the system's behavior, confirm the system under test produced it: check creator, source metadata, or generation time. Suspect imported, seeded, hand-edited, and leftover data from an earlier run, which reads identically to generated output. A checkout of another repository is the same trap: confirm it is current before reading it as evidence, since a stale one reads identically to the authoritative source.
Step 3: Hypothesize
Before forming a hypothesis about the machinery around a failure, such as a toolchain version, a configuration policy, or an environment difference, read the failing line, identify every path, package, symbol, or resource it names, and confirm each one resolves. Error text often names the site that consumed a missing input rather than the input itself, so the surrounding machinery looks responsible when it is not. Rank a machinery hypothesis only after every named reference checks out.
Once every named reference resolves and the operation has never once succeeded, rank a refusal ahead of any race or resource-exhaustion hypothesis: a denied permission, a firewall rule, an allowlist, an expired or missing credential. Intermittent failure is what a race or a contended resource usually looks like, so a run of attempts with zero successes ranks both below a refusal. Carry the hard blocks on the failing path into Step 4 as the first hypotheses to test, ahead of any measurement or instrumentation.
Generate 2-4 hypotheses ranked by likelihood. Each hypothesis must be falsifiable — specify what evidence would confirm or refute it.
Format:
H1 (most likely): [description] — confirmed if [X], refuted if [Y]
H2: [description] — confirmed if [X], refuted if [Y]
H3: [description] — confirmed if [X], refuted if [Y]
Check that the observed case can discriminate: when confirming and refuting evidence would look identical in it, the case is degenerate and any verdict drawn from it is inconclusive. Degenerate cases hide the difference they are supposed to reveal, such as a scaling factor of 1, a single-element collection, or an identity transform. Find a non-degenerate case, or construct one as a Step 4 experiment.
Parallel Investigation
For complex problems with 3+ hypotheses and a non-obvious root cause, spawn parallel investigators simultaneously.
Spawn condition: 3+ hypotheses AND the problem is not a simple typo, missing import, or syntax error.
Skip when 1-2 hypotheses are obvious (e.g., stack trace points directly to the bug).
Before dispatching, read the project's test configuration and CI workflow to identify any test tier that resets a shared external resource between tests, such as a database, a fixed port, or a cache. Such tiers have no cross-process interlock, so agents running them concurrently wipe each other's state and return failures that look like real defects. Name any such tier to every agent as off-limits.
When the evidence lives in a repository other than this one, including a submodule or a vendored clone with its own remote, establish the authoritative ref before dispatching and bring it up to date, fetching it or reading it through the forge API. A local checkout may be behind its remote, and an agent reading a stale one returns findings the current code has already resolved. Name that ref and how to read it in every agent prompt, including the text the Codex Agent forwards.
Emit all Agent tool calls below in one assistant message. Each Agent call uses model: "opus" and no name. Wait for every agent to report before continuing. Do not begin the next step on a partial set, and do not relaunch an agent that has not yet reported. Expect (one Agent per hypothesis + one Codex Agent) total. State the count explicitly when emitting the calls. Every agent's prompt must direct it to treat the shared working tree and its git index as read-only and to gather evidence by reading and reasoning; experiments that mutate code wait for Step 4, where they run one at a time. HEAD stays where it is: read other refs with git show <ref>:<path> rather than git checkout or git switch.
- Hypothesis Agent (one per hypothesis): Each receives the hypothesis, relevant file paths, what evidence to look for, and instructions to report confirmed / refuted / inconclusive with evidence. Budget: max 5 tool calls per subagent.
- Codex Agent: Launch one Agent whose prompt instructs the subagent to invoke
/consult-codexvia the Skill tool with a focused prompt describing the problem, reproduction, and files examined. The multi-turn conversation allows it to dig deeper into patterns the hypothesis-driven subagents miss. Run the/evaluate-findingsskill on its output after the Agent returns.
One exception to the wait: when every Hypothesis Agent has reported and only the Codex Agent has not, run the Step 4 actions that change nothing in the working tree, its git index, or anything the Codex Agent's prompt points it at, and state each result as it lands. The merge, every other Step 4 action, the Iteration decision, and the Investigation Report wait for the Codex Agent's report.
Merge the investigators' results. Codex findings that overlap with a subagent's confirmed hypothesis reinforce confidence. Novel codex findings become additional hypotheses to test in Step 4.
Step 4: Test
Verify each hypothesis with minimal, targeted actions:
| Action Type | Tool |
|---|---|
| Find usage or pattern | Grep |
| Read surrounding code | Read |
| Check recent changes | Bash (git log, git blame, git diff) |
| Run isolated test | Bash (specific test command) |
| Check dependency version | Bash (npm ls, pip3 show, etc.) |
| Inspect runtime state | Bash (add temporary logging, run, check output) |
| Vary one suspected variable | Bash (construct a throwaway fixture, run, compare) |
When read-only evidence cannot discriminate, construct minimal throwaway fixtures that vary one suspected variable at a time. Exercise the system's inputs, and leave the working tree and its git index unchanged. Label each fixture clearly, delete them once the experiment concludes, and report anything that could not be deleted. When a check edits a tracked file instead, such as adding temporary logging, remove the edit once the check concludes and confirm with git diff -- <file> that the file is back to its pre-check state before recording the result. Write to an external or live system only after explicit user approval via AskUserQuestion, stating the target system, every record the write will touch including those reached through triggers, cascades, and hooks, and the cleanup plan.
When a hypothesis names a timing window behind an intermittent failure, make the failing order deterministic in a throwaway copy of the test or operation, such as with a synchronous stall spanning that window, and confirm the copy fails with exactly the recorded symptom. Once it does, give as the report's reproduction command the command that runs the copy, with where the stall goes and how long it spans, so the copy can be rebuilt once deleted.
Record each result:
| Hypothesis | Verdict | Evidence |
|---|---|---|
| H1 | confirmed / refuted / inconclusive | [what was found] |
| H2 | confirmed / refuted / inconclusive | [what was found] |
Iteration
If all hypotheses are refuted or inconclusive:
- Document what was learned — each refuted hypothesis eliminates a possibility and narrows the search
- Return to Step 2 with the new information to re-isolate
- Generate new hypotheses in Step 3 based on updated understanding
Cycle budget: maximum 2 full cycles (hypothesize → test → learn → repeat) before escalating.
Escalation
After 2 failed hypothesis cycles, offer escalation to /consult-oracle via AskUserQuestion:
Investigation stalled after [N] hypothesis cycles.
Tested: [summary of hypotheses and evidence]
Remaining unknowns: [what is still unclear]
Escalate to Oracle? (consults external model with full context)
Proceed only if the user approves.
Investigation Report
Output results as text:
Investigation Report:
Problem: [one-line description]
Type: [runtime error | test failure | build failure | type error | performance | unexpected behavior]
Root cause: [confirmed cause, or "unresolved" with best hypothesis; append "unverified by reproduction" when the mark applies]
Evidence:
- [what confirmed the root cause]
Suggested fix: [description of what to change, or "needs further investigation"]
Reproduction command: [command to verify the fix once applied, or "none" followed by what was tried]
Hypotheses tested:
1. [hypothesis] — [confirmed/refuted/inconclusive, plus "unverified by reproduction" when the mark applies] — [evidence]
2. [hypothesis] — [confirmed/refuted/inconclusive, plus "unverified by reproduction" when the mark applies] — [evidence]
Escalation: [none | oracle]
Then use the TaskList tool and proceed to any remaining task.
Rules
- If the problem turns out to be environmental (wrong language runtime version, a declared dependency not installed locally, OS-specific), report that clearly — it may not require a code fix. A dependency the project never declared is a manifest defect, so report that as a code fix instead.
- If the problem is in a dependency (not the project's code), document the dependency issue and suggest the options that leave the dependency's code unmodified: workarounds, and a report upstream unless an existing issue covers the defect or the dependency's latest release no longer has it.
Land PR
Task Tracking
At the start of every invocation, including the re-run from Step 6, use TaskCreate to create a task for each step:
- Identify the pull request
- Request a human review
- Wait for reviewers and checks
- Check context
- Run
/resolve-pr-feedbackskill - Re-run
/land-prskill if fixes were pushed - Offer the merge
- Clean up
Step 1: Identify the Pull Request
Take the pull request from the number or URL provided, otherwise from the current branch: gh pr view [number] --json number,url,state,headRefName,headRefOid,baseRefName,headRepository,headRepositoryOwner. Take the owner and repository from its URL, and the head repository's owner and name from headRepositoryOwner.login and headRepository.name. Take the round from the invocation, 1 when none was provided, and any cases left unverified that were passed along with the pull request.
When TaskList shows a pending task of a /resolve-pr-feedback run, that run is already working through the pull request's feedback: mark this invocation's tasks completed, then use the TaskList tool and proceed to any remaining task.
Otherwise mark completed every task an earlier /land-pr invocation for this pull request left pending or in progress. Note the checkout root (git rev-parse --show-toplevel), the current branch, and whether the checkout is a linked worktree, where git rev-parse --git-dir differs from --git-common-dir. Use TaskUpdate to write the pull request's URL, the round, and the cases left unverified into Step 6's task description; after a compaction, read them back from that task.
- No pull request, or a closed one that was not merged — present this message: "No open pull request found for
<branch, number, or URL>; nothing to land." Mark this invocation's remaining tasks completed, then use the TaskList tool and proceed to any remaining task. - Open, but the current branch is not its head branch — present this message: "PR #
<number>is on<headRefName>; run/turbo:land-prfrom that branch's checkout." Mark this invocation's remaining tasks completed, then use the TaskList tool and proceed to any remaining task. - Merged — mark Steps 2 through 7 completed and continue with Step 8.
- Open on the current branch — continue with Step 2.
Step 2: Request a Human Review
This skill reads the pull request's state with:
bash ${CLAUDE_SKILL_DIR}/scripts/fetch-pr-status.sh <owner> <repo> <number>
Output shape:
{
"meta": { "isDraft", "author", "viewer", "headRefOid", "headCommittedDate",
"mergeable", "mergeStateStatus", "reviewDecision" },
"reviewRequests": [ { "reviewer", "type" } ], // type: Bot, User, Team, Mannequin, or Unknown
"reviews": [ { "author", "authorType", "submittedAt", "hasBody" } ],
"unresolvedThreads": [ { "author", "lastAuthor", "path" } ], // author of the first and of the latest comment
"issueComments": [ { "author", "createdAt" } ],
"checks": [ { "name", "app", "state", "title" } ] // state: failing, pending, or passing
}
meta.viewer is the account this session posts as. A review request of type Unknown names a reviewer this account cannot read, and counts as a human one.
In round 2 and later, skip the rest of this step. In round 1, run the script, and skip the rest of this step when a review request of type User, Team, or Unknown is pending, or when reviews holds one whose authorType is User.
Otherwise list the candidates:
bash ${CLAUDE_SKILL_DIR}/scripts/fetch-reviewer-candidates.sh <owner> <repo> <number>
It emits [ { "login", "source", "prs" } ]: GitHub's suggested reviewers first, then the people who reviewed the repository's recently merged pull requests, most such pull requests first. Skip the rest of this step when it lists no one.
Use AskUserQuestion to offer up to the first three candidates, each requesting that person's review, plus No human review. Name each candidate's source and pull request count in its description. Mark the first candidate recommended when reviewDecision is REVIEW_REQUIRED. For the candidate chosen, or each login a freeform answer names, run gh pr edit <number> --add-reviewer <login>.
Step 3: Wait for Reviewers and Checks
Use the Monitor tool with an until-loop that runs the status script every 30 seconds and ends once no check has the state pending and no review request of type Bot is pending, or after 20 minutes. When this session pushed the head commit less than 3 minutes before the loop starts, start its first run 3 minutes after that push. Pipe the script's output into jq directly or through printf '%s', never echo. Treat only a false result as not ready, and end the loop reporting the error when jq cannot parse the output or the script fails on three runs in a row.
Then run the script once more and list as text the feedback to resolve:
- Every unresolved review thread whose
lastAuthoris notmeta.viewer - Every check with the
statefailing - Every review with a body, from someone other than
meta.authorandmeta.viewer, submitted aftermeta.headCommittedDate - Every conversation comment from someone other than
meta.authorandmeta.viewer, created aftermeta.headCommittedDate
Leave out a review body or conversation comment that holds no observation, counting any nested inside collapsed blocks, such as a summary reporting no open issues, an acknowledgement of a review command, or a notice that a review was skipped. Read the bodies with gh pr view <number> --json reviews,comments to decide.
Also list each check and review request still pending when the loop ended. The step is done once that list, or a statement that nothing awaits resolution, is output.
Step 4: Check Context
Skip this step when Step 3 listed no feedback to resolve and the user has not asked to compact since the session last compacted.
Call the mcp__turbo__context-level tool: a reading of 50% or less remaining is a context signal. A request from the user to compact, arriving since the session last compacted, is the other. When the reading is 50% or less and the user has not asked to compact, use AskUserQuestion to ask whether to compact before resolving the feedback: "Handoff, then compact", marked recommended, or keep going in this session.
On "Handoff, then compact", or when the user asked to compact, run the /handoff skill, or, when this session already wrote a handoff, edit that file. Point its next step at running /land-pr for the pull request's URL, at this round, with the cases left unverified, from the checkout root. Use TaskUpdate to set this step's task description to that same next step and leave the task in progress. Then call the mcp__turbo__compact-and-continue tool with the handoff's path. End the turn in place of continuing to Step 5, telling the user that the session compacts and continues on its own, and that if it does not, they should run /compact and then reply "continue".
Step 5: Run /resolve-pr-feedback Skill
Skip this step when Step 3 listed no feedback to resolve.
Note meta.headRefOid. Then run the /resolve-pr-feedback skill for the pull request.
Step 6: Re-run /land-pr Skill if Fixes Were Pushed
Read the head commit with gh pr view <number> --json headRefOid. When Step 5 was skipped or the head commit is the one Step 5 noted, continue with Step 7. Otherwise:
- Round 1 or 2 — run the
/land-prskill again for the pull request, at the next round, with the cases left unverified. - Round 3 or later — output a summary of what this round fixed and what the reviewers raised. Then use
AskUserQuestionto offer another round or stopping here. Mark another round recommended when this round's fixes corrected defects, such as wrong behavior, a security exposure, or a failing check, and stopping when they only applied style or wording suggestions.- Another round — run the
/land-prskill again for the pull request, at the next round, with the cases left unverified. - Stop here — present this message: "Stopped following PR #
<number>after round<round>. The reviewers' response to the latest push is not handled yet; the branch and checkout stay. Run/turbo:land-prfrom<checkout root>to pick up again." Mark this step and Steps 7 and 8 completed, then use the TaskList tool and proceed to any remaining task.
- Another round — run the
Step 7: Offer the Merge
Run the status script again. When mergeable or mergeStateStatus is UNKNOWN, use the Monitor tool with an until-loop that runs gh pr view <number> --json mergeable,mergeStateStatus every 10 seconds and ends once neither is UNKNOWN, or after 1 minute.
Hand the pull request back without merging when any of these holds:
isDraftis true- A check has the
statefailingorpending reviewDecisionisCHANGES_REQUESTEDorREVIEW_REQUIRED, or a review request oftypeUser,Team, orUnknownis pendingmergeableisCONFLICTINGorUNKNOWN, ormergeStateStatusisBEHIND,DIRTY,BLOCKED, orUNKNOWN- The local branch's tip (
git rev-parse HEAD) is notheadRefOid, orgit status --porcelain --untracked-files=nolists changes
To hand it back, present this message: "PR #<number> is not ready to merge: <each reason that holds>. The branch and checkout stay. Run /turbo:land-pr from <checkout root> once that clears." Mark this step and Step 8 completed, then use the TaskList tool and proceed to any remaining task.
Otherwise, output the state as text:
- The checks that passed
- The reviewers who reviewed the head commit
- Each
Botreviewer whose check, the one whoseappornamematches its login, reports in itstitlethat it skipped the head commit, as on a rate limit - Each review request of
typeBotstill pending - Each unresolved thread, with its author and path
- Each case left unverified
Resolve the merge methods the repository allows with gh repo view --json squashMergeAllowed,mergeCommitAllowed,rebaseMergeAllowed. Run git fetch origin <baseRefName> and sample the base branch's history with git log --first-parent origin/<baseRefName> -n 30 --pretty=%s: (#N)-suffixed subjects point to squash, and merge-PR commits to a merge commit.
Use AskUserQuestion to offer one option per allowed method, each merging the pull request and deleting its branch along with any worktree it is checked out in, plus Don't merge yet. List first, labeled (Recommended), the allowed method the history points to, or, when it points to none that is allowed, the first allowed one of squash, merge commit, and rebase.
On a merge method, run gh pr merge <number> --<squash|merge|rebase> --match-head-commit <headRefOid>, then read the state with gh pr view <number> --json state. When it is not MERGED, because a merge queue or auto-merge took the pull request or the command failed, hand the pull request back as above with what gh reported.
On Don't merge yet, hand the pull request back as above, with the user's choice as the reason.
Step 8: Clean Up
Read the head branch's tip on GitHub with gh api repos/<head owner>/<head repository>/git/ref/heads/<headRefName> --jq .object.sha. When it is the pull request's headRefOid, delete the branch with gh api -X DELETE repos/<head owner>/<head repository>/git/refs/heads/<headRefName>. When the read finds no branch, skip the deletion. When its tip differs, keep it and report that it moved past the merged head. Then run git fetch --prune.
Then take the case that matches where Step 1 found this session:
- On another branch — leave the checkout as it is.
- In a linked worktree on the head branch — leave with the ExitWorktree tool (
action: "keep"). When it reports that no worktree session is active, present the worktree's path and the commands that finish the cleanup from the main checkout: fast-forward the main checkout's local<baseRefName>toorigin/<baseRefName>, rungit worktree remove <path>, and rungit branch -D <headRefName>when the local branch's tip isheadRefOid. Skip the local branch deletion below. Otherwise:- Fast-forward the main checkout's local
<baseRefName>branch toorigin/<baseRefName>without switching the branch the main checkout has checked out. When the fast-forward fails, report it and leave that branch as it is. - Remove the worktree with
git worktree remove <path>. When git refuses over files this session copied in from the main checkout, delete those copies and remove it again. Otherwise keep the worktree, without--force. - Run the
/backlogskill for each entry/backlogcould not persist from the worktree.
- Fast-forward the main checkout's local
- In the main checkout on the head branch — when
git status --porcelain --untracked-files=nolists changes, report them, keep the branch checked out, and skip the local branch deletion below. Otherwise rungit switch <baseRefName>andgit merge --ff-only origin/<baseRefName>.
When the local branch exists and its tip is the pull request's headRefOid, delete it with git branch -D <headRefName>, keeping it when git refuses. When its tip differs, keep it and report the commits it holds beyond the merged head (git log --oneline <headRefOid>..<headRefName>).
Report what was merged, removed, and kept.
Then use the TaskList tool and proceed to any remaining task.
Peer Review
Independent peer review via codex. Translates a natural-language review request into a codex-specific prompt so invocations stay implementation-agnostic.
Step 1: Understand the Request
Identify from the invoking prompt or conversation context:
- Material — the code scope, artifact text, feedback items, or other content under review
- Criteria — reference file paths codex should read directly, inline criteria text, or the material's own domain conventions
- Dimensions — one review concern (single-pass) or multiple independent concerns (fan-out, one per dimension)
- Skepticism guidance — any material-specific instruction for pushing past surface findings; optional
- Prior adjudications — findings already judged, one line each with its verdict and the recorded reason; optional
- Execution limits — test tiers that are off-limits, timeouts, or other limits the request places on running checks; optional
- Output format — finding layout, priority scale, or verdict labels; optional
If no reviewable material is available, stop and state that material is required.
Step 2: Build the Codex Prompt
Assemble the prompt using codex's XML tag conventions (see /codex-exec Prompt Shaping):
-
<task>— the scope or material, criteria pointers (file paths codex should read, or inline criteria), and any needed context. When the material is a git diff or working-tree scope, write the diff to a file under.turbo/and reference that file as the review subject. Pin it as the sole subject: state that only this diff is under review and that any output addressing other files, languages, or topics is off-topic. List the changed file paths to reinforce the pin. When the review revisits material an earlier round already covered, rebuild the review subject from the material's current content and state that any earlier version of it is superseded. When prior adjudications were identified in Step 1, carry them into the<task>labeled as decisions already reached on proposed changes rather than as established properties of the material, and state that a listed finding is raised again only on evidence its recorded reason does not already account for. When multiple independent dimensions are specified, wrap the dimension list with explicit parallel fan-out instructions so codex delegates each dimension to its own sub-agent and waits for all before synthesizing. When the request instead asks explicitly for a single-pass review covering all dimensions, keep the review in one pass with each dimension in its own labeled section rather than fanning out, stating an explicit outcome for every dimension, including one with no qualifying findings. See/codex-execreferences/parallel-execution.md for the prompt pattern. -
<dig_deeper_nudge>— the skepticism guidance from the request if provided; otherwise the default: "Do not stop at surface-level findings. Check for second-order failures, transformation-chain bypasses, and cases where the material relies on unstated assumptions." -
<structured_output_contract>— the output format from the request if provided. Otherwise use the default, which aligns with the finding shape internal reviews emit so findings can be concatenated without transformation:### [P<N>] <title (imperative, ≤80 chars)> **File:** `<file path>` (lines <start>-<end>) or **Section:** <location> **Reviewer:** peer (<dimension>) <one paragraph explaining the issue and its impact>The
(lines <start>-<end>)slot is optional; include it when reviewing code, omit for section references. Include the(<dimension>)parenthetical whenever the request identifies a dimension label (covers both single- and multi-dimension cases); omit only for undifferentiated reviews where no dimension was named. Default priority scale: P0 (fundamentally flawed or blocking), P1 (significant gap or urgent), P2 (moderate issue), P3 (minor improvement). End with an Overall Verdict block containing a 1–3 sentence assessment. If there are no issues, state that the material looks sound.
Instruct codex to bound its reads to the material under review, the sources needed to verify claims about it, and the criteria identified in Step 1. Exclude documents unrelated to those three. Instruct codex to search the repository with a tool that skips gitignored files, such as git grep --untracked, and to open or search a gitignored path only when this prompt, the material, or the criteria name it, or when a dependency's installed source is needed to verify a claim, never one holding local configuration or credentials.
When the material is code, state in the prompt that the repository is read-only, that the working directory is an empty scratch directory outside it, and that the temporary directory is writable. Name the repository and every path the prompt mentions by absolute path. Instruct codex to read the AGENTS.md files that govern the reviewed paths as project instructions, since a run started outside the repository loads none. Carry any execution limits identified in Step 1 into the prompt. Instruct codex to run any check that modifies files against a copy of the repository under the temporary directory, deleted afterward, in place of a git worktree, which the read-only repository refuses. Instruct it to name any check it could not run and to mark a verdict that rests on reading alone as such.
Include an explicit instruction that codex perform the review itself rather than delegating to another peer review skill or back to Claude. The prompt has already crossed the tool boundary; further forwarding would loop.
Step 3: Run /codex-exec Skill
Invoke /codex-exec via the Skill tool with the assembled prompt: in scratch-workspace mode when the material is code, in read-only mode otherwise.
Step 4: Shape the Response
Compare codex's output against the reviewed material and the dimensions and structure requested in Step 2, then classify it into one of three branches:
- Codex returned the requested findings — output them verbatim.
- Incomplete output (any reason — partial fan-out with missing dimensions, mid-run truncation, sections cut off, sub-agent failure, single-dimension review that ends mid-finding, etc.) — output what came back verbatim, name what is missing relative to Step 2's request, then append: "Action required: Peer review returned partial output. Use the
AskUserQuestiontool to ask the user whether to retry peer review now (transient codex errors like usage limits often clear within minutes) or proceed with the partial findings. State what is missing so the user can decide." - No output / codex failed — codex returned nothing, errored, hit a usage limit, or returned off-topic output that addresses code, files, or topics outside the reviewed material instead of the requested findings. Do not emit off-topic content as findings. Output a single notice stating the cause, then append: "Action required: Peer review failed. Use the
AskUserQuestiontool to ask the user whether to retry peer review now (transient codex errors like usage limits often clear within minutes) or proceed without peer review."
Do not synthesize peer findings locally to fill a gap. Peer review's value is independence; locally written findings labeled "peer" mislead the consumer.
Then use the TaskList tool and proceed to any remaining task.
When You Are a Subagent
If you are a subagent, follow the guardrails in references/subagent-wrapping.md. Otherwise codex events can drop after you emit final text, producing a false-empty return that silently bypasses Step 4's AskUserQuestion gate.
Pick Next Issue
Rank open GitHub issues by engagement and plan the selected issue.
Step 1: Fetch and Rank Issues
Run gh issue list to fetch open issues with engagement data:
gh issue list --state open --json number,title,body,url,reactionGroups,comments,labels,createdAt --limit 50
Calculate an engagement score for each issue:
- Reactions score: Sum all reaction counts from
reactionGroups(thumbs up, heart, hooray, etc.). Weight thumbs-up (THUMBS_UP) reactions 2x since they signal explicit demand. - Comments score: Count of comments on the issue.
- Engagement score:
(weighted reactions) + comments
Sort issues by engagement score descending.
Step 2: Present Top 3
Present the top 3 issues in a numbered list. For each issue, show:
- Title with issue number and link
- Labels (if any)
- Engagement: reaction breakdown and comment count
- Created: date
- First paragraph of the issue body (truncate if long)
If fewer than 3 open issues exist, present all of them.
If no open issues exist, inform the user and stop.
Step 3: User Picks an Issue
Ask the user to pick one of the presented issues (or request to see more).
If the user asks to see more, present the next 3 issues from the ranked list.
Step 4: Read the Full Issue
Fetch the complete issue details for the selected issue:
gh issue view <number> --json number,title,body,url,labels,comments,reactionGroups,assignees,milestone
Read the full issue body and comments to understand the requirements and any discussion context.
Step 5: Run /plan Skill
Run the /plan skill with the issue body as the task description. Tell /plan that the plan must include a final implementation step: "Close issue #N or reference it in the PR with Closes #N."
Rules
- Requires
ghCLI authenticated with access to the current repo - If
ghfails (not in a repo, not authenticated), inform the user and stop - Never modify issues. This skill is read-only until the implementation is committed.
Plan
Analyze task complexity to recommend an execution mode, then let the user set the final route.
Categorize the user-supplied task along these dimensions using subjective judgment. This analysis makes the recommendation informed:
- Scope: single feature / single subsystem vs multi-feature / multi-subsystem
- Stakes: one-off change vs long-lived project with architectural implications
- Unknowns: clear approach vs needs exploration and product decisions
Modes are named by what they produce: no plan, or a plan file.
| Mode | Criteria | Route |
|---|---|---|
| Direct | Clear scope, with any remaining decisions small enough to settle in conversation rather than write down. Aligns on the shape, then implements. | Read references/direct-mode.md and follow its steps. |
| Plan | The approach warrants writing down before implementing — to survey patterns, settle architectural decisions, or survive a fresh session. Produces a plan file, however large the work turns out to be. | Read references/plan-mode.md and follow its steps. |
Recommend and Confirm the Route
Form a recommended route from the dimensions and criteria above. Output the recommendation as text: the recommended mode and a line or two on why it fits over its neighbor.
Then use AskUserQuestion to have the user set the final route. Offer the recommended mode first, marked "(Recommended)", alongside the other mode; the auto-appended "Other" lets the user describe a different path.
Add a third Get a second opinion option whenever committing to the wrong mode would cost a session of rework, and whenever the recommended mode does not earn "(Recommended)" with conviction. It runs the /consult-codex skill for the soundest route given the task's scope, stakes, and unknowns. Then resolve the route with that answer in hand, re-asking when the choice stays the user's.
Carry the confirmed route into its reference file from the table above and follow its steps.
Rules
- Diff size, perceived task simplicity, and context window concerns are not reasons to skip the chosen mode's phases.
Polish Code
Task Tracking
At the start of every invocation (including re-runs from Step 7), use TaskCreate to create a task for each step:
- Run
/stageskill - Run
/run-checksskill - Run
/review-codeskill - Run
/evaluate-findingsskill - Run
/apply-findingsskill - Run
/smoke-testskill - Re-run
/polish-codeskill if changed
Loop State
Loop state lives in a ledger at .turbo/loops/polish-code-<label>-<tag>.md. The label is the governing plan's slug when one is in context, otherwise the current branch name with non-alphanumerics replaced by hyphens. The tag is the output of head -c 4 /dev/urandom | xxd -p, minted once when the loop starts. The ledger records Branch: (the unmodified branch name, or (detached)), Plan: when a plan governs, a one-line purpose, and per iteration an Iteration <N>: <state> line, its verdicts, and Step 7's classification. A ledger that exists belongs to an active loop.
At the start of every invocation, before /stage runs in Step 1, resolve the ledger:
- Carried path: this invocation was passed a ledger path, by the re-run Step 7 starts or by a handoff. Continue that ledger. A carried path whose file no longer exists falls through to discovery. Take a carried path only from those two sources, never from a task another invocation left behind.
- Discovery: with nothing carried, list the untracked ledgers in
.turbo/loops/whose name starts withpolish-code-and whoseBranch:is the current branch. Also list every untrackedpolish-code-ledger there that holds aPending smoke-test baseline, on any branch. Output each one's purpose, last iteration and its state, and file modification time as text. For a pending baseline, add its differing paths, found by items 1-3 of the pending-baseline reconciliation. When any are listed, useAskUserQuestionto offer resuming a ledger, discarding a ledger, or starting fresh, naming the ledger in each resume and discard option; when more ledgers are listed than options fit, first ask which ledger to act on, offering the most recently modified ones and leaving the rest to the free-text answer. Starting fresh mints a new path and deletes nothing. Delete a ledger named for discarding once any pending baseline in it is reconciled, then run discovery again. Reconciling a pending baseline right after discovery reuses the capture and differences discovery produced. - Fresh: mint a new path and write the ledger with
Iteration 1: open.
Once the ledger resolves, use TaskUpdate to write its path into this invocation's Step 7 task description. After a compaction, this invocation reads its ledger path back from that task.
Iteration state. The current iteration's state line reads open until Step 7 reaches a gate, awaiting <gate> while Step 7 waits on the user at one (the in-place round, the skip permission, the hard cap, or the context-signal question, recorded with the gate it wraps), and classified once Step 7 has settled whether another iteration runs. On a continued ledger, read the last iteration's state:
classified: carry out the decision recorded with the classification. On another iteration, this invocation is the next one: appendIteration <N+1>: open. On an escalation to/consult-oracle, resume that escalation, and once the oracle answers, record the decision its answer leads to (another iteration, or a stop that deletes the ledger) in place of the escalation.awaiting <gate>: the interrupted iteration already ran Steps 1-6, so mark this invocation's Step 1-6 tasks completed. Ask that gate again before anything else; for the context-signal question, ask only the gate it wraps, since this session starts with fresh context. When it wrapped an automatic re-run, offer run another iteration, marked recommended, or stop iterating; when it wrapped a run that edited nothing, the loop has ended, so delete the ledger. Then proceed by the answer as Step 7 does.open: the iteration was interrupted. Rerun it under its own number from Step 1. The verdicts it already recorded stand: Step 4 keeps them rather than recording them again.
A compaction in flight is not a resume: this invocation continues its own iteration. A continued ledger supplies the most recent /review-code diff command it records, when it records one, in place of Step 3's default.
Pending smoke-test baseline. This entry means an iteration was interrupted between delegating the smoke test and verifying the tree. Reconcile it before Step 1 whenever a resumed or discarded ledger holds one, so Step 1 does not stage what the interrupted subagent left behind. The entry holds a state from ${CLAUDE_SKILL_DIR}/scripts/checkout-snapshot.sh:
- Run
checkout-snapshot.sh checkwith that state. When it printsLOST,git gchas pruned the snapshot; when it printsINVALID, the state names a HEAD ref outside the local branches or paths git never checks out. Either way, report it, write nothing, and clear the entry once the report is out. - Run
checkout-snapshot.sh capturefor the current state. - List what differs between the two: the paths
git diff --name-only --no-renamesreports between their index trees and between their raw trees, and any difference in REF or COMMIT. - When nothing differs, clear the entry and continue.
- Otherwise output the differences as text, then use
AskUserQuestionto offer restoring the pending baseline or keeping the current state. Restoring runscheckout-snapshot.sh restorewith the pending state; record theUNDOline and anyMOVEDlines it prints in the ledger asPost-run state, as Step 6 does. Then runverifyand handle its result as Step 6's tree verification does. Keeping clears the entry.
Recording. Have the ledger path in context when Steps 3 and 4 run, so recorded verdicts are honored. Append each Skip, Escalate, and Apply verdict with its reason under the current iteration as Steps 4-6 reach it, along with the user's resolution of an Escalate. For an Escalate the user resolved, the reason attributes to the user only what they decided; the details you picked while implementing it stay open to review.
Closing the loop. Delete the ledger at a convergence stop, at a stop the user chooses at a Step 7 gate, and at a stop granted at the skip gate. Keep it when escalating to /consult-oracle, since the oracle's answer decides what follows, when the user stops the loop at Step 6 to repair the checkout by hand, and when halting on an unresolved failure.
Step 1: Run /stage Skill
Resolve the ledger as Loop State describes, then run the /stage skill.
Step 2: Run /run-checks Skill
Run the /run-checks skill.
Stage all changes made in this step before continuing.
Step 3: Run /review-code Skill
Run the /review-code skill on the staged changes. The diff command is git diff --cached. When a plan governs the work, supply the ledger's Plan: path as the governing document. Supply every Skip and Escalate verdict and every narrowed Apply the ledger records, across all iterations, as the already-adjudicated list, one line each: the finding, its verdict, and the recorded reason. An Escalate the user resolved carries their resolution. A narrowed Apply carries what the remedy covered and what it left, so the untouched remainder reads as settled rather than as an unaddressed gap. A finding that re-proposes a remedy an earlier round narrowed stays in scope regardless of the list: the remainder having since caused a defect is evidence the earlier reason did not account for, and it is the signal Step 5's recurring-class rule depends on.
Step 4: Run /evaluate-findings Skill
Run the /evaluate-findings skill on the results from Step 3.
Step 5: Run /apply-findings Skill
Record the staged tree with git write-tree before applying anything, and write the tree ID it prints to the ledger as Review tree, replacing any entry already there.
Run the /apply-findings skill on the evaluated results.
When a defect this run fixes, in this step or in Step 6, is a further instance of a class of defect an earlier iteration already fixed, stop patching the individual instance and instead encode the root-cause invariant structurally — a shared guard or type, or a regression test that pins the class against the worked failures it must prevent. For a finding, make that the fix /apply-findings applies for it, so that skill's checks run on it. Recognize a class by its failure and what triggers it, so a further instance in another function or file counts as the class recurring. Count a defect that swings to the opposite failure after its fix, such as a check found too strict in one round and too lax in the next, as the same class recurring. In the same pass, audit the existing code against the newly encoded invariant and fix every instance it catches, including code written before it existed. When the recurring instance sits in code outside the changeset and so reaches the user as an escalated finding, make the invariant and that audit the remedy offered for it, with a fix to the individual instance as the narrower alternative. Treat recurrence on a new axis of the same invariant as a signal that the invariant is incomplete: widen it to cover the new axis rather than assuming the latest fix failed.
Append any fix whose remedy you deliberately narrowed to the ledger as you make it, naming what the remedy covered and what it left, so Step 7 carries it forward without reconstructing the decision later.
When a fix ships with a regression test, confirm the test fails with the fix reverted, then restore the fix. When that test's outcome depends on the order of concurrent events, also run it many times over with the fix in place. Find what caused a failure on any of those runs, typically an ordering defect in the code or a missing synchronization point in the test, and fix it, then repeat both checks before this step closes. When the fix consists only of new tests for existing code, mutate the branch each new test or case targets and confirm that test or case is among those reported failing. When the runner does not report that case on its own, run it alone against the mutation.
Stage the fix immediately before mutating it (git add <file>), so git checkout -- <file> restores it exactly from the index. A file staged in an earlier step has an index copy older than the current edits, and restoring reverts them. Stage only the files about to be mutated: a broader restore point sweeps in working-tree changes the project may require stay uncommitted. When one also carries unrelated changes, write git diff <file> to a patch file, back the unrelated changes out of it (delete their + lines and turn their - lines into context lines), and stage it with git apply --cached --recount <patch>. Its index copy then lacks those changes, so copy that file aside before mutating it and restore it from the copy instead of the index. Each mutation edits the shared working tree in place, so hold anything that reads or builds that tree until the mutation is restored.
Before running the tests against a mutation, confirm it landed: git diff -- <file> shows the intended change against the index for each mutated file. An edit whose match pattern missed leaves the file untouched. Count a mutation as caught only when the test run reports a failing test, not when the mutation command or a step chained before the tests exited nonzero. When the mutation checks a particular test, count it only when that test is among those reported failing. When the suite crashes or hangs before that test reports, re-run the mutation against the narrowest test selection that includes that test: that run settles only whether that test catches the mutation, and a mutation it does not report on either stays uncounted.
When the fixed code combines several signals, also apply the plausible rewrites a maintainer might reach for — reordering the signals, substituting a fallback chain for a conjunction, dropping a term that looks redundant — and confirm each fails at least one test, then restore the fixed code. A rewrite that passes every test while changing behavior on some input means the tests pin the examples rather than the invariant; add the test that distinguishes it. When the fix guards against an unbounded loop or wait, bound the test itself so that reverting the fix fails rather than hangs: cap the iteration count for a loop; enforce a deadline for a wait. A deadline inside the test can depend on the test cooperating, so also run each such mutation under a timeout enforced from outside the test process.
When the fix changes when, whether, or how often a mechanism runs, mutate the changed line and run the whole affected suite, not only the test written for this fix: a fix can disarm tests that already existed, and those keep passing. Concentrate on the tests whose pass condition is an absence, and establish for each one that still passes whether it passes for the reason it did before. Those tests cannot distinguish a guard that rejected the work from a mechanism that never ran.
A test whose pass condition is an absence needs an assertion establishing the mechanism was reachable. Place that arming assertion before anything that can consume the state it reads. Placed after, the assertion holds whether or not the guard exists, and the test looks rigorous while pinning nothing.
A test that asserts only the direction of a numeric change passes on any movement of the right sign, including rounding noise or drift the fix did not cause. Assert the expected size of the change instead.
When the test still passes with the fix reverted, suspect the mutation before the test: confirm it reaches the branch under test and reproduces the original behavior rather than a third one. Name the branch under test and the original behavior it reproduces before running the mutation, then re-read the mutated lines. A mutation that lands a statement away from that branch also changes paths the fix never touched, and the resulting failure is indistinguishable from a caught mutation.
When the mutation is faithful and the test still passes, the test cannot observe the defect. Determine which of four shapes applies before reworking the test's setup:
- The assertion inspects output that is identical whether or not the defect is present. Assert on the mechanism itself rather than on the output it produces: teardown, cancellation, deduplication, and ran-only-once fixes leave no trace there.
- The inputs the test drives land the same way under the fixed value and the mutated one. When the fix seeds an initial value, drive an input on the far side of that seed; a test that only advances past it never observes the seed.
- An earlier guard against the same condition catches first, leaving the guard under test unreachable. Construct the ordering that reaches the later guard specifically. A defense-in-depth guard is reachable only through the window its predecessor does not cover, and an end-to-end exercise of the operation misses it systematically.
- The entry surface the test drives is itself closed for the window the guard covers, so no input the test can send reaches the guard. Where the earlier shape puts a predecessor in the code path, this one puts the block ahead of it: when the fix guards a repeat invocation, a busy or pending state on that affordance refuses the repeat before the guard sees it, and the test passes for the wrong reason. Drive an entry point that carries no such state instead.
A test that genuinely cannot be made to fail does not pin the behavior; say so rather than counting it as coverage.
After every mutation in this step, re-run whatever that mutation was checked against and confirm it passes again and the test command itself exits 0, not a filter piped after it, before reporting the result. A clean git status looks identical whether the fix was restored or deleted. A run that a mutation made fail can leave behind what a passing run cleans up, such as temporary files and spawned processes. Before that re-run, clear what the failed run left, identified by what the run itself started or named. Leave anything whose origin that does not establish, and name it when reporting the result.
A project command run to verify a fix writes to the shared tree the same way a mutation does. Establish whether it writes tracked files before running it, and read git status --short afterward: revert what it wrote, so files it regenerated are not swept into the changeset by the staging below.
Stage all changes made in this step before continuing.
Step 6: Run /smoke-test Skill
Run bash ${CLAUDE_SKILL_DIR}/scripts/checkout-snapshot.sh capture before spawning. It prints the checkout's state as five values, REF COMMIT IDX RAW HID: HEAD's full ref (- when detached), its commit (unborn when there is none), the index tree, a tree of every working-tree file outside gitignored paths and .turbo/, hashed byte for byte, and a list of the paths on disk it leaves out, which restore never deletes. It reports on stderr, as SKIPPED, each gitlink, embedded repository, tracked path now holding a directory, and path whose name contains a newline or carriage return. These stay outside what it restores. When capture fails, it names the cause, such as an unmerged index: resolve that before spawning.
When the ledger records a Smoke-tested baseline, compare its state against the capture. When COMMIT, IDX, and RAW all match, report the result recorded with that baseline as carried forward and close this step, running neither the /smoke-test skill nor a test run. A partial match also carries the result forward the same way when all four of these hold. COMMIT matches. The unstaged changes are the same: git diff --raw --no-renames <baseline IDX> <baseline RAW> equals git diff --raw --no-renames <IDX> <RAW>. The recorded run ran no integration test suite. Every file git diff --name-only --no-renames <baseline IDX> <IDX> lists lies in test sources, test fixtures, or documentation that the app's build and runtime never load. Name those files when carrying the result forward. On any other difference, or with no such entry, continue.
Run the /smoke-test skill to produce the smoke test plan.
Record the captured state in the ledger as Pending smoke-test baseline, replacing any entry already there.
Delegate test execution to an Agent tool call (model: "opus", no name). Wait for it to report before continuing; do not relaunch it if it has not yet reported. Pass the plan and the diff command (git diff --cached) to the subagent, and instruct it to invoke /test-run-rules via the Skill tool before executing the plan. State in its prompt that the writes the plan's Setup contract authorizes are already approved, and that any write outside that enumeration leaves its scenario blocked.
Verify the tree when the subagent returns, including when it terminates early or reports incomplete results: run checkout-snapshot.sh verify with the pending state. When it exits 0, the subagent left the checkout as it found it. Otherwise run checkout-snapshot.sh restore with the pending state, then verify again. Before writing anything, restore prints the state it found as an UNDO line: record that and any MOVED lines in the ledger as Post-run state, replacing any entry already there, so running restore with it undoes the restore apart from the MOVED branches.
Report the RESTORED and INDEX paths, the UNDO state, and each MOVED branch with the commit it held (none when restore created the branch). Also report each path printed as LEFT or SKIPPED, which stayed as the subagent left it, and each path printed as FAILED, whose write failed and whose prior content survives only in the UNDO state. Name any change you see in gitignored paths or .turbo/ as outside what the snapshot restores. Judge the result by verify alone: after a restore, git status can report modifications the bytes do not contain.
When verify passes, on the first run or after the restore, clear the Pending smoke-test baseline entry. When restore prints LOST or INVALID, or verify still fails, keep the entry. Output what still differs from the pending state as text, including the LEFT and FAILED paths, then use AskUserQuestion to offer keeping the current state, which clears the entry so later steps stage the checkout as it stands, or stopping the loop so the checkout can be repaired by hand, which keeps the ledger.
If any test fails, or the subagent reports a defect in the staged changes outside the plan's scenarios and the code confirms it, fix the issues and stage the fixes. When every planned test passed, this step made no fix, and the first verify exited 0, record the Smoke-tested baseline in the ledger, replacing any entry already there: the captured state and the result the run reported, including whether it ran an integration test suite.
Step 7: Re-run /polish-code Skill if Changed
Check whether any file was edited during Steps 5-6: git diff --name-only <tree> --cached lists them, where <tree> is the ledger's Review tree. Any edit counts.
The iteration number below is the ledger's number for the /polish-code run currently executing Step 7. It is not the iteration number of a prospective re-run. Iteration 1 is the initial run; iteration 2 is the first auto-re-run; iteration 3 is the second auto-re-run; iteration 4 and beyond exist only when the user opts in at the hard-cap ask. Iterations 1 and 2 always follow the classification gate (they never trigger the hard cap at their own Step 7, even when the auto-re-run they spawn would be iteration 3). The hard cap fires at the end of iteration 3 and every iteration thereafter.
Iterations 1 and 2, if changes were made, classify what Steps 5-6 edited:
- Structural edits (fixed bugs, new or removed functions, changed function signatures, moved code between files, changed control flow, added or removed dependencies, corrected a stale or wrong comment that was itself a documentation bug) — run
/polish-codeagain using the Skill tool, passing the ledger path. Scope the diff command to what changed since this iteration's review: usegit diff <tree> --cachedas the diff command for/review-code. Smoke test scope remains unchanged (full feature scope, not narrowed to that diff). If the round contains both structural and in-place edits, treat it as structural and re-run automatically. - In-place edits only (renamed local variables without changing behavior, reformatted, adjusted whitespace, edited neutral comments) — output a summary of what changed, then use
AskUserQuestionto ask whether to run one more round or stop here. Do not silently continue or silently stop.
Iterations 1 and 2, if changes were made but you believe re-running is unnecessary, use AskUserQuestion to ask for skip permission. Do not skip silently.
Judge whether another round is worthwhile by the trend across iterations: when rounds have stopped surfacing defects (wrong behavior, security exposures, broken contracts) and keep surfacing improvements of kinds earlier rounds already applied, the loop has converged even though the edits were structural — recommend stopping. A round that surfaces no defects is the termination signal; never add a confirmation round, an extra reviewer, or review steps beyond this skill's own.
Treat reversal as the stronger signal: when a round's accepted findings undo an earlier round's accepted findings on the same lines, the reviewers are trading equally defensible positions rather than converging on one answer. Recommend stopping there even though such edits classify as structural. Keep the current round's version of the reversed code, which is as likely to be the better answer as the one it replaced.
Weigh where a round's defects live alongside whether it found any. When the change the run set out to make has been stable for two or more rounds and every new defect sits in verification scaffolding an earlier round added — a probe, a gate, a check, or the documentation describing them — the loop is generating its own work rather than converging on the change. Recommend stopping there even though the round surfaced defects.
Wherever this step asks or recommends stopping rather than re-running automatically, weigh the files Steps 5-6 changed that this iteration's review did not read: every iteration reviews the diff as it stood before its own fixes, so those files have had no review pass. Let them argue for one more round whose /review-code diff command is git diff <tree> --cached. The reversal and defect-location signals outrank that, so a round tripping either one stops even with files left unread. Files a later round's review reads stop counting toward this.
Every stop this step reaches with changes pending names those unread files, by path, or by cluster with a count when there are many. State alongside them that stopping leaves those files covered by the Step 6 smoke run and by Step 5's per-fix verification, and not by /review-code or by the Step 2 check gate, which ran before they existed. When Step 6 carried its result forward, name only Step 5's per-fix verification and state that no smoke run followed those edits. Name separately any file a Step 6 fix edited: the smoke run and Step 5's verification preceded that fix as well.
Iteration 3 or later, if Steps 5-6 of this run made changes, the hard cap is reached. This replaces the classification gate above for iteration 3 and every iteration after it. Output a summary of what is still changing, whether it is structural or in-place, and where this round's defects lived (in the product, or in the build, CI, and gate scaffolding around it). Then use AskUserQuestion to offer three options: run another iteration, whose review scope includes the unread files named above; stop iterating, accepting the current state so the workflow moves on; or escalate to /consult-oracle for a different perspective on the remaining issues.
Before each AskUserQuestion call this step makes, mark the current iteration awaiting <gate> in the ledger, naming the gate, and for the context-signal question the gate it wraps. Once this step has settled what follows, by a gate's answer or by an automatic re-run, mark the iteration classified, and append the classification, the decision (another iteration, a stop, or an escalation to /consult-oracle), and, when another iteration runs, its /review-code diff command with the tree ID filled in. Write these before starting the re-run or the escalation, writing a handoff, or deleting the ledger. When an escalation's answer settles what follows, record that decision in place of the escalation before acting on it.
Before acting on any gate above, check for a context signal. Call the mcp__turbo__context-level tool: a reading of 25% or less remaining is one. A request from the user to compact, arriving since the session last compacted, is the other. When either is present, turn whatever this step reached, including an automatic re-run and a run that edited nothing, into one AskUserQuestion call. Its first question asks whether to compact before what comes next: "Handoff, then compact", marked recommended, or keep going in this session, which acts on the gate's answer here. Leave it out when the user asked to compact. Its second question offers the choices of the gate this step reached, with the recommendation that gate would make; in place of an automatic re-run, it offers run another iteration, marked recommended, or stop iterating. Leave it out when no file was edited in Steps 5-6. Make no AskUserQuestion call when both are left out. When no file was edited and TaskList shows no pending task that no /polish-code iteration created, nothing remains to resume: ignore the signal and let the loop end.
On "Handoff, then compact", or when the user asked to compact, check first whether the gate's answer is stop iterating while TaskList shows no pending task that no /polish-code iteration created. Then nothing remains to resume: tell the user so and close this step without a handoff. Otherwise run the /handoff skill, or, when this session already wrote a handoff, edit that file. Point its next step at what the gate's answer leads to, and once the handoff is written, update this step's task as that branch says:
- Run another iteration — the re-run. The handoff names the ledger path and the re-run's
/review-codediff command; the iteration number, the already-adjudicated list, and the smoke baseline stay in the ledger. UseTaskUpdateto set this step's task description to the re-run: run/polish-codewith ledger<path>and that diff command. Leave the task in progress. - Escalate to
/consult-oracle— the escalation. The handoff carries the summary above and names the ledger path, which the escalation keeps. UseTaskUpdateto set this step's task description to that escalation, reading the summary from the handoff at its path. Leave the task in progress. - Stop iterating, or no file was edited — the first pending task that no
/polish-codeiteration created. The handoff carries the unread files this stop leaves, and the message ending the turn names them as every stop does. Mark this step's task completed, along with every Step 7 task earlier iterations left in progress.
Then call the mcp__turbo__compact-and-continue tool with the handoff's path. End the turn in place of the TaskList call that closes this step, telling the user that the session compacts and continues on its own, and that if it does not, they should run /compact and then reply "continue".
The re-invocation is a full, fresh run of this skill. Every step (1-7) executes with its own task tracking and skill invocations, apart from a smoke result Step 6 carries forward. The narrowed diff command only affects what /review-code reads. It does not affect which steps run or whether skills are invoked. Whichever gate above sends the run into another iteration, pass that iteration the ledger path.
Then use the TaskList tool and proceed to any remaining task.
Rules
- Every step must run in every iteration.
/review-coderuns every review type it activates across parallel internal reviewers plus peer review./evaluate-findingsis a judgment gate that must run before/apply-findings. - Each step must invoke its designated skill via the Skill tool, not be replaced by inline reasoning or agent calls.
- Re-invocations from Step 7 are full runs with fresh task tracking and complete skill invocations.
- Two exceptions apply to the rules above: Step 6 carrying a smoke result forward on a matching baseline, or after a run with no integration test suite on one that differs only in test or documentation files the app never loads; and an invocation resuming a ledger whose last iteration is
awaiting <gate>, which starts at that gate.
Pull Request
Create the branch's pull request, or bring an existing one's title and description up to date with the branch.
Route to Create or Update
Both routes draft by the rules in references/body-elements.md. Read it alongside the route's reference, before the first phase.
When this request gives a PR number, read references/update.md and follow its phases for that PR.
Otherwise, look up the current branch's PR. A base branch given with the request is the base of a new PR, never a lookup key.
gh pr view --json number,state
When the lookup fails for any reason other than finding no PR, report the error and stop.
- The branch has an open PR — read references/update.md and follow its phases for that PR's number.
- The branch has no PR, or only a closed or merged one — read references/create.md and follow its phases.
Hooks 1
Sponsors
Details
- Marketplace
- tobihagemann/turbo
- Source
- claude
- Category
- Community