smallnest avatar

goal-workflow-skills

PRD → SPEC → Issues → implement → review → ship, plus refactor, modernize, and diagram skills — an end-to-end AI development workflow for Claude Code.

GitHub stars
302

Install

/plugin install goal-workflow-skills@goal-workflow

Run it inside Claude Code after adding the marketplace with /plugin marketplace add smallnest/goal-workflow.

Contents

Discovered from source

Skills 19

Article Icons (itshover)

Add tasteful icons to an article using the itshover icon set. itshover publishes 263 icons as shadcn registry components; this skill downloads them and converts each into a clean, static, inline SVG that drops straight into Markdown or HTML — no React, no motion, no build step.

Triggers

Use when the user wants to illustrate a document with icons:

  • /article-icons <file>
  • "给这篇文章配图标", "给文章配图", "add icons to this article", "illustrate with icons"

Inputs

  • Target file — the article to illustrate (.md, .html, .mdx, ...). If not given, ask.
  • Style preferences (optional) — color, size, where icons go. Otherwise use sensible defaults below.

The Tool

scripts/fetch_icon.py is the only moving part. It fetches an icon and prints static SVG to stdout.

# Get one icon (defaults: size 24, color currentColor, stroke-width 2)
python3 scripts/fetch_icon.py heart-icon

# Customize
python3 scripts/fetch_icon.py rocket-icon --size 32 --color "#d97757" --stroke-width 1.5

# Discover names (do this FIRST — names must match exactly)
python3 scripts/fetch_icon.py --list
python3 scripts/fetch_icon.py --search arrow
python3 scripts/fetch_icon.py --search brand

scripts/icon_names.json is a cached list of all 263 names for offline reference.

Most icon names end in -icon (e.g. heart-icon, rocket-icon, database-icon), and brands use brand-<name>-icon (e.g. brand-anthropic-icon). But the convention is not universal — real names include shield-check, credit-card, down-chevron, apple-brand-logo, skull-emoji. Never guess a name. Always resolve it with --search first — a wrong guess just wastes a 404.

Workflow

  1. Read the article. Identify its structure: title, section headings (#/##/<h1>/<h2>), key concepts, list groups, callouts/warnings, and any tech/brand mentions (React, GitHub, AI tools...).

  2. Plan the icon map. For each placement, choose a semantically matching icon. Match meaning, not just keywords — a "performance" section → rocket-icon or zap-icon; a "security" section → shield-icon or lock-icon; a warning callout → alert-triangle-icon. Prefer one consistent icon family (all outline, one color) so the article looks designed, not decorated. Resolve every name with --search.

  3. Confirm the plan with the user before editing — show the heading→icon mapping. This is cheap and avoids reworking a whole document.

  4. Fetch and embed. Run fetch_icon.py for each chosen icon (parallelize independent fetches) and inline the SVG at its placement. See embedding rules below.

  5. Verify. Re-read the edited file; for HTML, open it / screenshot to confirm icons render and align. Report the mapping you applied.

Embedding Rules

HTML — inline the SVG directly. Wrap heading icons so they align with text:

<h2 style="display:flex;align-items:center;gap:.5rem;">
  <svg ...>...</svg> Performance
</h2>

Markdown — GitHub-flavored Markdown renders inline HTML, so embed the raw SVG. Keep it on one line and size it small (16–20px) for inline use, 24–28px beside headings:

## <svg ... width="22" height="22" ...>...</svg> Getting Started

If the target renderer strips inline SVG (some strict Markdown engines do), fall back to saving each SVG into an assets/icons/ folder next to the article and referencing it: ![](assets/icons/rocket-icon.svg). Ask which the user prefers if unsure.

Defaults

  • Size: 24px beside h1, 20–22px beside h2/h3, 16px inline in text.
  • Color: currentColor so icons inherit text color. Override with --color only when the user wants accent colors.
  • Density: one icon per heading + a few for genuinely key concepts. Do not icon every bullet or sentence — restraint reads as polish.
  • Alignment: always display:flex;align-items:center;gap:.4–.5rem for heading icons in HTML.

Icon Selection Cheatsheet

These names are verified to exist, but the set changes — always reconfirm with --search before fetching.

ThemeReal icon names
intro / overviewbook-icon, home-icon, globe-icon, map-pin-icon
performance / speedrocket-icon, gauge-icon, clock-icon
securityshield-check, lock-icon
data / chartsdatabase-family via --search, chart-bar-icon, chart-line-icon, chart-pie-icon, cloud-1-icon
settings / configgear-icon, sliders-horizontal-icon
warning / notetriangle-alert-icon, info-circle-icon, filled-bell-icon
success / donechecked-icon, double-check-icon, simple-checked-icon
ideasbrain-circuit-icon, sparkles-icon, star-icon, bulb-svg
AI / brandsbrand-anthropic-icon, brand-gemini-icon, ... (--search brand)
navigationarrow-narrow-*-icon, down-chevron, right-chevron

Edge Cases

ScenarioHandling
Icon name not found (404)Run --search <term>; pick the closest real name. Never invent names.
Icon won't convert (rare; ~2/263 use a JS map for paths)Script prints a clear error. Pick an alternative icon with similar meaning.
No network accessCannot fetch SVGs; tell the user the skill needs network access to itshover.com.
Markdown renderer strips inline SVGFall back to assets/icons/*.svg + image references.
Article already has iconsAsk whether to replace, supplement, or skip those sections.
Very long articleConfirm the mapping for the first few sections, then apply the same family consistently throughout.

Checklist

Before finishing:

  • Every icon name was resolved with --search/--list (no guessed names)
  • One consistent icon family/color across the article
  • Icons placed at headings + genuinely key points, not everywhere
  • Heading icons vertically aligned with text (flex + gap)
  • Edited file re-read; HTML visually verified to render
  • Mapping summary reported to the user

to-spec — Reverse-Engineer Project Specification

Analyze an existing codebase and produce a structured SPEC document that captures what the project does, how it's built, and what contracts it exposes. The output is a living specification that could be used to rebuild the project from scratch or onboard new contributors.


When to Use

  • You want a comprehensive understanding of an existing project
  • Onboarding new team members who need a high-level overview
  • Documenting a project that was built without a spec
  • Comparing actual implementation against intended design
  • Preparing for a rewrite or major refactor
  • Auditing what a project actually does vs. what people think it does

The Job

  1. Scope confirmation — ask user what to analyze (entire repo, specific directory, or specific aspect)
  2. Deep scan — systematically read project structure, entry points, config, tests, and core logic
  3. Synthesize — produce a structured SPEC document
  4. Review — present to user for feedback and iteration
  5. Save — write final SPEC to agreed location

Step 1: Scope Confirmation

Before scanning, ask the user:

What should I analyze?

A. Entire repository (recommended for small-medium projects)
B. Specific directory or module: [path]
C. Specific aspect only (e.g., API surface, data model, auth flow)

Depth level:
1. Overview — high-level architecture + tech stack + key features (fast, ~5 min)
2. Standard — includes API contracts, data models, config, dependencies (default)
3. Deep — adds internal module interactions, error handling patterns, test coverage analysis

If the project is large (>500 files), recommend starting with Overview or a specific module.


Step 2: Deep Scan

Systematically analyze the following (adapt to what exists):

2.1 Project Identity

  • package.json, go.mod, Cargo.toml, pyproject.toml, pom.xml, etc.
  • README, LICENSE
  • Git history (first commit date, recent activity, contributor count)

2.2 Architecture

  • Directory structure and organization pattern (monorepo, layered, hexagonal, etc.)
  • Entry points (main files, CLI commands, server bootstrap)
  • Module boundaries and dependency graph (internal)

2.3 Tech Stack

  • Language(s) and version constraints
  • Frameworks and major libraries
  • Build tools and bundlers
  • Runtime requirements (Node version, Docker, etc.)

2.4 Features & Behavior

  • Route definitions / CLI commands / exported functions
  • Business logic modules and their responsibilities
  • Background jobs, cron tasks, event handlers

2.5 Data Model

  • Database schemas, migrations, ORMs
  • Key data structures and their relationships
  • State management approach

2.6 API Surface

  • HTTP endpoints (method, path, request/response shapes)
  • GraphQL schema / gRPC protos / WebSocket events
  • CLI interface (commands, flags, arguments)
  • Exported library API (public functions, classes, types)

2.7 Configuration & Environment

  • Environment variables and their purpose
  • Config files and their schema
  • Feature flags, toggles

2.8 External Dependencies

  • Third-party services (databases, queues, APIs)
  • Infrastructure requirements (cloud services, storage)
  • Authentication/authorization providers

2.9 Testing & Quality

  • Test framework and approach (unit, integration, e2e)
  • Coverage patterns (what's tested, what's not)
  • Linting, formatting, type checking setup

2.10 Deployment & Operations

  • CI/CD configuration
  • Deployment targets and strategies
  • Monitoring, logging, health checks

Step 3: SPEC Document Structure

Generate the SPEC with these sections. Omit sections that don't apply.

# SPEC: [Project Name]

> Reverse-engineered specification — generated [date] from commit [short-hash]

## 1. Overview

### 1.1 Purpose
[One paragraph: what problem this project solves and for whom]

### 1.2 Key Capabilities
- [Bullet list of what the system can do, from a user's perspective]

### 1.3 Architecture Style
[e.g., "Monolithic Express.js API with React SPA frontend", "CLI tool with plugin system", "Microservices communicating over gRPC"]

---

## 2. Tech Stack

| Layer | Technology | Version |
|-------|-----------|---------|
| Language | ... | ... |
| Framework | ... | ... |
| Database | ... | ... |
| Build | ... | ... |
| Test | ... | ... |
| Deploy | ... | ... |

---

## 3. Project Structure

[Directory tree with annotations explaining each top-level directory's purpose]

---

## 4. Data Model

### 4.1 Core Entities
[For each entity: name, fields, relationships, constraints]

### 4.2 State Transitions
[If applicable: lifecycle states and valid transitions]

---

## 5. API Surface

### 5.1 [Interface Type: REST / CLI / Library / etc.]

[For each endpoint/command/function:]
| Method | Path/Command | Description | Auth |
|--------|-------------|-------------|------|
| ... | ... | ... | ... |

### 5.2 Request/Response Schemas
[Key request/response shapes with field types]

---

## 6. Configuration

| Variable / Key | Required | Default | Description |
|---------------|----------|---------|-------------|
| ... | ... | ... | ... |

---

## 7. External Dependencies

| Service | Purpose | Failure Impact |
|---------|---------|----------------|
| ... | ... | ... |

---

## 8. Business Rules & Constraints

- [Numbered list of invariants, validation rules, and business logic constraints discovered in the code]

---

## 9. Non-Functional Characteristics

### 9.1 Performance
[Observed patterns: caching, pagination, batch processing, etc.]

### 9.2 Security
[Auth mechanism, input validation patterns, secrets management]

### 9.3 Error Handling
[Error strategy: custom error types, error codes, retry policies]

---

## 10. Testing Strategy

| Type | Framework | Coverage Pattern |
|------|-----------|-----------------|
| Unit | ... | ... |
| Integration | ... | ... |
| E2E | ... | ... |

---

## 11. Known Gaps & Assumptions

- [Things that are unclear from the code alone]
- [Assumptions made during analysis]
- [Areas with no tests or documentation]

---

## 12. Appendix

### A. Dependency Graph
[Key module dependencies, import relationships]

### B. Environment Setup
[Steps to run the project locally, derived from config and scripts]

Step 4: Review & Iteration

After generating the SPEC, present it and ask:

SPEC generated. Please review:

- Are there sections that need more detail?
- Are there inaccuracies I should correct?
- Should I add/remove any sections?
- Is the depth level appropriate?

Reply OK to save, or provide feedback for iteration.

Apply feedback and re-present until user confirms.


Step 5: Save

Ask user for save location:

Where should I save the SPEC?

A. docs/SPEC.md (recommended)
B. SPEC.md (project root)
C. Custom path: [specify]

Analysis Heuristics

Identifying Purpose

  • Look at README first line, package description field, CLI help text
  • Check the main entry point — what does it bootstrap?
  • Look at test descriptions — they often describe expected behavior in plain language

Discovering Architecture

  • Map import/require statements to build dependency graph
  • Identify layers by directory naming: controllers, services, models, routes, handlers, domain, infra
  • Check for dependency injection patterns, middleware chains, plugin registrations

Extracting Business Rules

  • Look for validation functions, guard clauses, assertion statements
  • Check error messages — they often describe what went wrong in business terms
  • Examine test assertions — they encode expected behavior

Finding API Contracts

  • Route registrations (Express: app.get(), FastAPI: @app.get(), Go: mux.HandleFunc())
  • OpenAPI/Swagger files if present
  • Request validation schemas (Joi, Zod, Pydantic, struct tags)
  • CLI flag/argument definitions (cobra, argparse, yargs)

Detecting Data Models

  • ORM model definitions (Prisma, SQLAlchemy, GORM, TypeORM)
  • Migration files (in chronological order)
  • Type/interface definitions for core domain objects
  • Database seed files

Edge Cases

ScenarioHandling
Project has no README or documentationNote this in "Known Gaps"; infer purpose from code
Monorepo with multiple servicesAsk user which service(s) to analyze; produce one SPEC per service or a unified SPEC with clear boundaries
Project uses code generationDocument the generated code's purpose but focus on the source of truth (schemas, proto files, templates)
Legacy project with mixed patternsDocument all observed patterns, note inconsistencies in "Known Gaps"
Project is a library (no runtime)Focus on exported API surface, type contracts, and usage patterns from tests
Incomplete or broken codeDocument what exists, mark broken/incomplete areas explicitly
Project >1000 filesStart with entry points and trace key flows; don't exhaustively read every file
Multiple languages in one repoDocument each language's role and how they interact

Quality Criteria

A good reverse-engineered SPEC should pass these checks:

  • A developer unfamiliar with the project could understand its purpose in 60 seconds
  • The tech stack section is complete enough to set up a dev environment
  • API contracts are specific enough to write a client against
  • Data models are complete enough to recreate the schema
  • Business rules are explicit (not buried in "see code")
  • Known gaps are honestly listed (don't invent what you can't determine)
  • The SPEC matches the actual code (not aspirational documentation)

Anti-Patterns to Avoid

  • Don't invent intent. If you can't determine WHY something exists, say so. Don't fabricate rationale.
  • Don't copy code into the SPEC. Describe behavior and contracts, don't paste implementations.
  • Don't include transient state. The SPEC describes the system's design, not its current runtime state.
  • Don't over-specify internals. Focus on boundaries, contracts, and behavior. Internal implementation details belong in code comments, not specs.
  • Don't assume the README is accurate. READMEs often lag behind code. Verify claims against actual implementation.

graph — Task/PRD to Parallel Execution Graph

Turn a task (or PRD / SPEC / issue set) into a directed acyclic graph of work units, layer it into supersteps (waves), and implement each wave's independent nodes concurrently using subagents. Each node runs the full /goal → /review-it → /ship-it pipeline inside its own git worktree, so parallel nodes never clobber each other's working tree. Between waves, a fan-in barrier merges results and re-plans the next wave.

This is the parallel sibling of /loop-it. /loop-it is strictly sequential (one worktree, one issue at a time). /graph fans out every independent node in a wave at once.


Mental Model (borrowed from LangGraph / graph engineering)

ConceptHere
NodeOne implementable unit of work (an issue / subtask)
EdgeA dependency: B depends on A → edge A → B
Superstep / waveA set of nodes whose deps are all satisfied — run concurrently
Fan-outDispatch one subagent per node in the current wave
Fan-in (barrier)Wait for all nodes in the wave before starting the next
State channel.graph_state — shared checkpoint, rewritten between waves (resume source)
Live trackergraph.html — Claude-style light-theme dashboard, re-rendered from .graph_state at every checkpoint
Dynamic re-planAfter a wave, revise the graph if new work/deps emerged

Core principle: Independent nodes in the same wave have no shared state and no ordering dependency, so they can run in true parallel. Dependencies define the only ordering. Everything else runs at once.


Overview

Input (task / PRD / SPEC / issues)
        │
        ▼
1. Decompose into nodes  ─────────►  nodes = {id, title, deps, criteria, scope}
        │
        ▼
2. Build DAG + validate  ─────────►  detect cycles, orphan deps
        │
        ▼
3. Topological layering  ─────────►  waves = [[n1,n2,n3], [n4,n5], [n6]]
        │
        ▼
4. Render graph + confirm with user
        │
        ▼  (write .graph_state + graph.html — open graph.html to watch live)
┌──────────── per wave (superstep) ────────────┐
│                                               │
│  FAN-OUT: 1 subagent per node (parallel)      │
│    each subagent, in its own git worktree:    │
│      /goal (inline implement) → /review-it    │
│                              → /ship-it        │
│                                               │
│  FAN-IN barrier: wait for ALL nodes           │
│    integrate, update .graph_state             │
│    re-render graph.html                        │
│    re-plan next wave if graph changed         │
│                                               │
└───────────────────────────────────────────────┘
        │
        ▼
All waves done → final summary

Step 1: Locate & Decompose Input

Accept any of: a free-form task description, a PRD/SPEC file, or an existing issue set (GitHub / local .md).

  • PRD/SPEC → reuse /to-issues decomposition rules (one node per User Story; split large, merge tiny).
  • Existing issues → each issue is a node; parse dependencies from issue bodies (Depends on: #3, Dependencies: #3, #5).
  • Free-form task → break into the smallest independently-shippable units yourself.

Each node MUST have:

Node #N
  title:      short imperative title
  deps:       [list of node ids] or []
  criteria:   acceptance criteria (checklist) — how the subagent knows it's done
  type:       backend | frontend | fullstack | ui | infra | docs
  scope_hint: which files/dirs this node is expected to touch (for conflict analysis)

scope_hint matters: two nodes with no dependency edge but overlapping file scope are not truly independent — see Step 3.


Step 2: Build the DAG & Validate

Construct edges from deps. Then validate:

CheckAction on failure
Cycle (A → B → A)Print ⚠️ 循环依赖: #A ↔ #B. Break by node id order, warn user, ask to confirm or fix.
Dangling dep (#7 depends on #99, no such node)Print warning, drop the phantom edge.
Scope collision (two dep-free nodes edit same files)Add a soft edge to serialize them (lower id first), OR flag for user. Never let two parallel worktrees fight over the same files.

Hot-file exception: A shared wiring file that nearly every node must touch (e.g. router.go, main.go, mod.rs, a DI container, an __init__ re-export) does NOT count as a scope collision — treating it as one would serialize the entire graph into a chain. For such files, assume append-only edits merge cleanly, and prefer one of: (a) designate a single node that owns wiring and have others expose a registration hook, or (b) do a tiny follow-up "wire everything" node in the last wave. Reserve the collision rule for nodes that edit the same logic in the same file (e.g. two handlers rewriting the same function).


Step 3: Topological Layering into Waves

Compute waves via Kahn's algorithm:

  1. Wave 0 = all nodes with deps == [] and no scope collision among themselves.
  2. Remove wave-0 nodes; Wave 1 = nodes whose deps are now all satisfied.
  3. Repeat until all nodes placed.
  4. Within a wave, if two nodes edit the same logic in the same file (real collision, per the hot-file exception in Step 2), push the higher-id one to the next wave. Bare wiring-file overlap does not trigger this.

ID conventions (used consistently): lower id wins — cycles break by lowest id first (Step 2), and scope collisions serialize with the lower id first (higher id deferred to the next wave).

Print the layered plan:

📊 Graph: 6 nodes, 3 waves

Wave 0 (parallel ×3):  #1 db schema   #2 config loader   #3 logging util
Wave 1 (parallel ×2):  #4 API handler (deps #1)   #5 CLI flags (deps #2)
Wave 2 (parallel ×1):  #6 integration (deps #4,#5)

Max parallelism: 3 subagents in Wave 0.

Also emit a Mermaid diagram for the user:

```mermaid
graph LR
  n1[#1 db schema] --> n4[#4 API handler]
  n2[#2 config loader] --> n5[#5 CLI flags]
  n3[#3 logging util]
  n4 --> n6[#6 integration]
  n5 --> n6
```

Wait for user confirmation before dispatching any subagent. Let them adjust nodes, deps, or the max-parallelism cap.


Step 4: Pre-flight Checks

Before the first wave (same spirit as /loop-it):

git rev-parse --is-inside-work-tree   # in a repo?
git status --porcelain                # clean tree? (dirty → stash/abort)
git branch --show-current             # on main/master?
git ls-remote --heads origin          # remote reachable?
gh auth status                        # if shipping to GitHub

Any hard failure → print the error and stop. Confirm a max concurrency cap with the user (default 3–4 parallel subagents; more risks rate limits and review noise).

Then initialize the state channel + live tracker (do this once, right after the plan is confirmed and before the first fan-out):

# 1. Write the initial checkpoint (all nodes pending, current_wave 0).
cat > .graph_state <<'JSON'
{ "version": 1, "task": "...", "repo": "owner/repo",
  "waves": [[1,2,3],[4,5],[6]], "current_wave": 0,
  "nodes": { "1": {"title":"...","deps":[],"status":"pending","wave":0}, ... } }
JSON

# 2. Keep it out of git.
grep -qxF '.graph_state' .gitignore || printf '.graph_state\ngraph.html\n' >> .gitignore

# 3. Render the Claude-style light-theme dashboard.
python3 skills/graph/scripts/render_graph_html.py .graph_state graph.html

Tell the user: open graph.html in a browser — it auto-refreshes every 5s, so it tracks execution live (waves, node statuses, progress bar, and a Mermaid DAG colored by status). Re-run the render command at every checkpoint (see Step 5b) to push updates.


Step 5: Execute Wave by Wave (fan-out → fan-in)

For each wave, in order:

5a. FAN-OUT — one subagent per node, in parallel

Dispatch all nodes of the wave in a single response (multiple Agent/subagent calls in one message = concurrent). Each subagent works in its own git worktree so parallel file edits never collide:

# The orchestrator creates a worktree per node BEFORE dispatching:
git worktree add -b feat/node-{N}-{slug} ../.graph-worktrees/node-{N} main

Each subagent receives a self-contained prompt (it does NOT inherit orchestrator context):

You are implementing ONE node of a task graph, working in an ISOLATED git worktree.

Worktree:  ../.graph-worktrees/node-{N}   (already created on branch feat/node-{N}-{slug})
Node #{N}: {title}
Type:      {type}
Scope:     {scope_hint}  — stay within these files; do not touch other nodes' scope

Acceptance criteria (all must pass):
- [ ] {criterion 1}
- [ ] {criterion 2}

Context (deps already merged into main, pull first):
{summaries of dependency nodes' outputs, or the referenced PRD/SPEC excerpt}

Your pipeline (run all three, in order):
1. IMPLEMENT (inline /goal): read the node + any referenced PRD/SPEC, read adjacent
   code, implement to satisfy EVERY acceptance criterion, run build + tests + lint
   (e.g. go build ./... && go vet ./... && go test ./...). Iterate until all green.
2. REVIEW (/review-it): run code review on your changes, apply accepted findings,
   re-run focused tests, repeat until review is clean (max 2 rounds).
3. SHIP (/ship-it): commit (message references the node/issue), push branch,
   create PR, merge, close the issue.

Constraints:
- Work ONLY inside your worktree. Do NOT edit files outside {scope_hint}.
- Do NOT try to call `goal` via the Skill tool (it's a UI command, not a skill) —
  "implement" means you write the code yourself. /review-it and /ship-it ARE skills.
- If you cannot satisfy a criterion, STOP and report what's blocking — don't fake it.

Return: node id, PASS/FAIL, PR/commit refs, files changed, and — if you discovered new required work or a dependency the graph didn't capture — a `NEW_WORK:` line describing it (title + which nodes it blocks). Emit `NEW_WORK: none` if there's nothing.

Why worktrees, not branches alone: /goal mutates the working tree. Two subagents editing the same checkout would corrupt each other. A worktree per node gives each its own filesystem checkout on its own branch — that's what makes the wave genuinely parallel and safe.

5b. FAN-IN — barrier, integrate, re-plan

Wait for every subagent in the wave to return (BSP barrier — the next wave cannot start until this one commits). Then:

  1. Read each subagent's summary. Mark node shipped or failed.
  2. git checkout main && git pull — dependency outputs are now on main for the next wave.
  3. Remove finished worktrees: git worktree remove ../.graph-worktrees/node-{N} (keep failed ones for investigation).
  4. Write checkpoint to .graph_state, then re-render the tracker: python3 skills/graph/scripts/render_graph_html.py .graph_state graph.html (the open graph.html picks it up on its next auto-refresh).
  5. Dynamic re-plan (LangGraph-style conditional edge): scan each subagent's NEW_WORK: line. If any is not none, add the new node(s)/edge(s) and re-layer the remaining nodes before starting the next wave. Show the user the delta.
  6. If any node in the wave failed, mark all nodes that depend on it as blocked and skip them (their inputs aren't ready).

Proceed to the next wave.


State File: .graph_state (+ live tracker graph.html)

.graph_state lives at the repo root and must be in .gitignore. It's the single source of truth: checkpoint it after every wave so a crash resumes at the wave boundary, and re-render graph.html from it so the browser dashboard stays live. graph.html is a derived view — never hand-edit it; regenerate it from .graph_state.

{
  "version": 1,
  "updated_at": "2026-07-21T10:30:00Z",
  "task": "Add user auth",
  "repo": "owner/repo",
  "waves": [[1, 2, 3], [4, 5], [6]],
  "current_wave": 1,
  "nodes": {
    "1": { "title": "db schema", "deps": [], "status": "shipped", "branch": "feat/node-1-db-schema", "pr": 43, "wave": 0 },
    "2": { "title": "config loader", "deps": [], "status": "shipped", "wave": 0 },
    "3": { "title": "logging util", "deps": [], "status": "failed", "wave": 0, "error": "test TestLog failed", "attempts": 2 },
    "4": { "title": "API handler", "deps": [1], "status": "in_progress", "wave": 1 },
    "6": { "title": "integration", "deps": [4, 5], "status": "blocked", "wave": 2, "reason": "depends on #3 (failed)" }
  }
}

Status values: pending | in_progress | shipped | failed | blocked | skipped. Each node carries title + deps so graph.html can draw the DAG and cards straight from the checkpoint.

Render the tracker any time with:

python3 skills/graph/scripts/render_graph_html.py .graph_state graph.html

On resume: read .graph_state, skip shipped, ask about failed (retry/skip), re-derive remaining waves, and re-render graph.html.


Safety Guards

  • Worktree isolation is mandatory — never run two parallel /goal sessions in the same checkout.
  • Fan-in barrier is mandatory — never start wave N+1 before every node in wave N returns and merges.
  • Scope collisions serialize — dep-free nodes touching the same files go in different waves.
  • Never skip /review-it before /ship-it.
  • Cap concurrency — default 3–4; more invites rate limits and merge contention.
  • Never force-push to main. Each node ships via its own branch/PR.
  • Failed node blocks its dependents — don't ship on top of unmet inputs.
  • Max retries per node — reuse /loop-it's error classes; don't loop forever.
  • Confirm the plan before the first fan-out.

Common Mistakes

MistakeFix
Dispatching subagents in separate responsesOne response, multiple calls = parallel. Separate = sequential.
No worktree → parallel edits corrupt the treeOne git worktree per node.
Two "independent" nodes edit the same fileAdd a soft edge; put them in different waves.
Starting the next wave before all nodes mergeEnforce the fan-in barrier.
Over-decomposing into 20 trivial nodesMerge tiny units; a node should be a meaningful shippable unit.
Ignoring a failed node's dependentsMark them blocked, skip them.

Relationship to Other Skills

/prd → /prd-to-spec → /to-issues ─┬─► /loop-it   (sequential: one node at a time)
                                   └─► /graph     (parallel: whole wave at once)
                                          │
                     each node: inline /goal → /review-it → /ship-it (in its own worktree)
  • /to-issues — decomposition rules reused for building nodes.
  • /loop-it — sequential counterpart; use it when nodes heavily share files or serial safety matters.
  • /graph — this skill; use it when the DAG has genuine parallelism (independent subsystems).
  • /review-it, /ship-it — real skills each node's subagent invokes.

Humanize-It: 迭代式去 AI 味改写

对指定文档进行去 AI 味的改写。根据文本类型和内容,从三个子 skill 中自动选择最合适的一个开始改写。如果改写效果不满意,换用另一个 skill 继续迭代,直到效果达标或达到 42 次迭代上限。

子 Skill 能力矩阵

Skill适用场景核心能力改写风格
humanizer-zh通用文本、文章、博客、文案识别 24+ AI 写作模式,注入个性与灵魂,节奏变化自然、有温度、带观点
humanize-chinese通用 + 学术 + 长文本20+ 规则检测 + 统计特征 + LR 融合评分,CLI 工具链多种风格可选(知乎/小红书/学术/文学等)
technical-writing技术文档、架构说明、设计稿、评审文档去除技术黑话,证据先行,消除主持腔平实、严谨、可论证

工作流程

第一步:读取文档并分析

  1. 读取用户指定的文档内容
  2. 判断文档类型:
    • 技术文档(技术方案、架构说明、设计文档、评审稿)→ 优先使用 technical-writing
    • 学术论文(论文、研究文章)→ 优先使用 humanize-chinese(学术模式)
    • 通用文本(博客、文案、文章)→ 优先使用 humanizer-zh
    • 长文本(≥1500 字)→ 优先使用 humanize-chinese(长文本模式)

第二步:改写策略选择

根据文档类型选择第一个改写 skill:

文档类型判断:
├── 技术文档 → technical-writing → humanizer-zh → humanize-chinese
├── 学术论文 → humanize-chinese(academic) → humanizer-zh → technical-writing
├── 通用文本 → humanizer-zh → humanize-chinese → technical-writing
└── 长文本(≥1500字) → humanize-chinese(longform) → humanizer-zh → technical-writing

第三步:迭代改写循环

iteration = 0
MAX_ITERATIONS = 42

while iteration < MAX_ITERATIONS:
    iteration += 1

    # 使用当前 skill 进行改写
    result = humanize(current_text, current_skill)

    # 评估改写效果
    score = evaluate(result)

    if score >= PASS_THRESHOLD:
        # 改写效果达标,输出最终结果
        output(result)
        break

    # 效果不达标,切换到下一个 skill
    current_skill = next_skill(skill_order)
    current_text = result  # 在上次改写基础上继续优化

    if all_skills_exhausted():
        # 所有 skill 都用过一轮,从头开始新一轮组合
        current_skill = first_skill(skill_order)

第四步:质量评估

每次改写后,按以下维度评估效果(百分制):

维度权重评估标准
AI 痕迹去除30%三段式、套话、机械连接词是否消除
自然度25%读起来是否像人写的,节奏是否自然
信息完整20%核心信息是否保留,没有丢失关键内容
风格一致15%语气是否前后统一,符合文档类型
可读性10%句子是否通顺,逻辑是否清晰

评分标准:

  • ≥ 80 分:通过,输出结果
  • 60-79 分:尚可,再迭代一轮看能否提升
  • < 60 分:不达标,必须继续改写

第五步:输出结果

输出最终改写结果,附带:

  1. 改写后的完整文本(写入原文件或指定输出文件)
  2. 改写摘要(使用了哪些 skill,迭代了几次,最终评分)
  3. 主要改动点列表

具体执行指令

调用 humanizer-zh 时

使用 Skill 工具调用 humanizer-zh,将文档内容传入,让其按 24 种 AI 写作模式进行检测和改写。重点关注:

  • 删除填充短语
  • 打破公式结构
  • 变化节奏
  • 信任读者
  • 删除金句
  • 注入个性与灵魂

改写后按其 50 分制质量评分进行初步评估(≥ 40 分为达标)。

调用 humanize-chinese 时

使用 Skill 工具调用 humanize-chinese,根据文档类型选择对应模式:

  • 通用文本:使用 detect + rewrite 流程
  • 学术论文:使用 academic 模式
  • 长文本:使用 --scene novel 或 --scene auto

如果 CLI 工具可用,优先使用 CLI 进行量化检测和改写;否则按其 LLM 使用指南手动执行。

改写后按其 0-100 分评分体系评估(≤ 35 分为 LOW 区间,达标)。

调用 technical-writing 时

使用 Skill 工具调用 technical-writing,主要用于技术文档的改写。重点关注:

  • 去除 buzzword 黑名单中的词汇
  • 消除主持腔和评价腔
  • 按「条件 → 对象 → 判断」重写句子
  • 证据先行,减少无支撑的强判断
  • 去除过场句

迭代策略细节

何时切换 Skill

  1. 同一个 skill 连续改写 3 次评分无提升 → 切换到下一个 skill
  2. 评分下降 → 回退到上一个版本,切换 skill
  3. 所有 skill 都用完一轮但未达标 → 从第一个 skill 重新开始,但使用上一轮的改写结果作为输入
  4. 达到 42 次迭代 → 输出当前最佳结果

组合策略

不同 skill 的改写侧重不同,组合使用可以互补:

  • humanizer-zh → humanize-chinese:先注入个性灵魂,再做量化去 AI 模式
  • humanize-chinese → humanizer-zh:先做系统化去 AI,再注入温度
  • technical-writing → humanizer-zh:先保证技术严谨性,再增加自然度
  • humanizer-zh → technical-writing:先去除通用 AI 痕迹,再调整技术语气

用户交互

如果用户提供了明确的偏好(如"保持学术风格"、"要更口语化"、"技术文档不要太随意"),在改写时遵循用户偏好,并优先选择对应的 skill。

如果用户未指定文档类型,可以通过 AskUserQuestion 询问:

  • 文档类型(通用 / 技术 / 学术)
  • 期望的改写风格(自然随意 / 平实严谨 / 学术规范)
  • 是否需要写入原文件还是输出到新文件

Insight Diagram — 项目图表生成技能

分析任意代码库,自动生成 UML 14种图 + 架构图 + 流程图,使用 /architecture-diagram 渲染为 HTML+SVG。

图表分类与清单

结构性图形 (Structural Diagrams — 静态)

描述系统的物理组成和静态结构。

编号图表类型英文标识关注点
1系统架构图architecture组件关系、全局视角(非UML,最常用)
2类图class定义类、属性、操作及关系
3对象图object特定时刻的对象实例及其关系
4组件图component系统组件及其依赖关系
5部署图deployment物理硬件、节点及软件部署
6包图package将模型元素分组组织
7复合结构图composite-structure类的内部结构
8剖面图profile扩展UML元模型、自定义构造型

行为性图形 (Behavioral Diagrams — 动态)

描述系统与外部参与者或系统内部的交互过程。

编号图表类型英文标识关注点
9流程图flowchart主流程与分支(非UML,最常用)
10用例图usecase从用户角度展示系统功能
11活动图activity过程的流程或步骤
12状态机图state-machine对象生命周期的状态变迁
13序列图sequence按时间顺序展示对象间交互
14通信图communication侧重于对象间的组织关系
15定时图timing侧重于状态变化的时间约束
16交互概览图interaction-overview结合活动图和时序图
17泳道图swimlane跨组件/角色职责流程(活动图变体)

示例参考

本技能的 examples/ 目录包含 13 个已完成的图表 HTML 文件,作为视觉样式和内容结构的参考模板。生成任何图表前,必须先阅读对应的示例文件,以确保风格一致、结构规范。

示例文件清单

文件图表类型英文标识
examples/architecture.html系统架构图architecture
examples/class.html类图class
examples/object.html对象图object
examples/component.html组件图component
examples/deployment.html部署图deployment
examples/flowchart.html流程图flowchart
examples/usecase.html用例图usecase
examples/activity.html活动图activity
examples/sequence.html序列图sequence
examples/communication.html通信图communication
examples/dfd.html数据流图dfd
examples/interaction-overview.html交互概览图interaction-overview
examples/swimlane.html泳道图swimlane

参考规则

  1. 生成前必读: 调用 /architecture-diagram 前,先用 Read 工具阅读对应类型的示例文件,从中提取:

    • SVG 布局策略(节点间距、分组方式、箭头走向)
    • 节点样式层级(核心节点 accent 高亮、普通节点实线边框、可选节点虚线边框)
    • 标注风格(阶段标签、Legend 图例、卡片摘要)
    • 信息密度(每个节点显示多少字段/属性)
  2. 结构对齐: 生成的图表应与示例保持相同的结构层次:

    • 页面顶部:标题 + 副标题 + 图表类型说明
    • 中间主体:SVG 图表区域(带浅色边框容器)
    • 底部:信息摘要卡片 + 页脚
  3. 内容替换而非照搬: 示例中的业务数据(NovaShield 风控系统)是虚构的参考案例,生成时需替换为目标项目的真实架构信息。只参考布局和样式,不复制业务内容。

  4. 无对应示例的类型: 对于包图 (package)、复合结构图 (composite-structure)、剖面图 (profile)、状态机图 (state-machine)、定时图 (timing) 这 5 种没有示例文件的图表类型,参考最相近的已有示例(如包图参考组件图,状态机图参考活动图),并沿用相同的视觉语言。

执行流程

步骤 1:分析代码库

读取项目关键文件,提取架构信息:

  1. 读取项目根目录的 CLAUDE.md(如存在)获取项目概览
  2. 读取各子目录的 CLAUDE.md(如存在)获取模块细节
  3. 用 Glob 扫描源码文件结构(**/*.go, **/*.py, **/*.ts 等)
  4. 读取入口文件(main.go, app.py, index.ts 等)识别顶层组件
  5. 用 Grep 搜索关键模式:接口定义、函数签名、依赖注入、配置项

从以上信息中提炼出:

  • 组件清单: 服务、模块、外部依赖
  • 关系图: 谁调用谁、谁依赖谁、数据流向
  • 核心类型: 结构体/类、接口、枚举
  • 流程: 主业务流程、异常处理流程
  • 部署: 进程、中间件、外部服务

步骤 2:选择图表

使用 AskUserQuestion 让用户选择要生成的图表(multiSelect: true),分4组展示:

第1组 — 结构性图形(静态):

  • 系统架构图 (architecture)
  • 类图 (class)
  • 对象图 (object)
  • 组件图 (component)

第2组 — 结构性图形续 + 部署:

  • 部署图 (deployment)
  • 包图 (package)
  • 复合结构图 (composite-structure)
  • 剖面图 (profile)

第3组 — 行为性图形(动态):

  • 流程图 (flowchart)
  • 用例图 (usecase)
  • 活动图 (activity)
  • 状态机图 (state-machine)

第4组 — 交互图 + 常用非UML:

  • 序列图 (sequence)
  • 通信图 (communication)
  • 交互概览图 (interaction-overview)
  • 泳道图 (swimlane)
  • 全部生成 (all)

默认推荐:architecture + sequence + flowchart

步骤 3:逐个生成

对每个选中的图表类型:

  1. 先读示例: 用 Read 工具阅读 examples/<标识>.html(如 examples/architecture.html),提取布局模式、节点样式、标注方式
  2. 根据步骤 1 提取的架构信息,整理出该图表应展示的元素和关系
  3. 调用 /architecture-diagram skill,传入图表类型、标题、内容描述、输出路径,必须指定 light 风格
  4. 输出文件保存到 docs/<标识>.html(如 docs/architecture.html)
  5. 生成后必须 review: 运行几何校验脚本,按结果修正后再继续下一张(见下方「步骤 3.5」)
  6. 简要报告完成状态

生成规则:

  • 风格: 必须使用 light Claude 风格(暖白背景 #FAF9F6、terracotta/sage/plum/rose 配色、Inter 字体、白色卡片容器),与 Anthropic Claude 品牌视觉一致
  • 防遮盖: 所有 SVG 元素(节点、箭头、标签)不得互相遮盖。具体做法:
    • 计算每个元素的边界框,确保无重叠
    • 箭头绘制在节点下方(SVG 中先画箭头再画节点)
    • 节点间留足间距(垂直最少 40px,水平最少 30px)
    • 文字不超出所在节点边界,超长文字截断或换行
    • 连接线的标签放置在线段中点偏移处,避免覆盖线段或节点
    • 如果元素过多导致图表拥挤,拆分为多个子图或缩小元素尺寸

批量生成顺序(宏观→微观): architecture → component → deployment → package → composite-structure → profile → class → object → usecase → flowchart → activity → state-machine → swimlane → sequence → communication → timing → interaction-overview

步骤 3.5:几何 review(每张图生成后必做)

生成的 SVG 常见三类几何缺陷,必须用脚本逐张校验并修正:

python3 skills/insight-diagram/scripts/review_svg.py docs/<标识>.html --min-gap 8
# 批量: python3 skills/insight-diagram/scripts/review_svg.py docs/*.html --min-gap 8

脚本检查(与三条核心要求一一对应):

  1. 箭头落点:每个带箭头的端点必须恰好落在目标框/椭圆/菱形的边缘线上(容差 6px)。
    • ERROR 深入框内:端点穿入框内部 >8px → 缩短连线,让它止于边缘。
    • WARNING 空接:端点悬空、距最近框 >8px 且不汇入任何其它连线 → 把端点对齐到框边或汇合点。
    • 合法情形:端点落在框边、生命线、或与另一条连线交汇(分支/汇聚)——脚本不会误报。
  2. 框重叠(ERROR):非嵌套的两个框在水平、垂直两个方向都有交叠 → 必须移开其中一个。嵌套(一个完全包住另一个,如分组边界框包子节点)是允许的。
  3. 框间距(WARNING):投影相邻的两框净间距 < --min-gap(默认 8px)→ 拉开距离。

处理原则:

  • ERROR 必须修复后再进入下一张;修完重跑脚本确认归零。
  • WARNING 逐条核对:序列图生命线底部的消息、泳道边界、紧贴的分组等可能是设计本意,确认无误可保留;其余应调整坐标。
  • 修正方式是直接编辑 docs/<标识>.html 里对应的 <rect>/<line>/<path> 坐标,而非重新生成整张图。
  • 退出码:有 ERROR 返回 1,干净返回 0;CI 中可加 --strict 让 WARNING 也阻断。

步骤 4:报告

全部完成后输出:

  • 生成的文件列表
  • 每个图表的简要描述

各图表的内容指南

系统架构图 (architecture) — 非UML,最常用

  • 展示系统顶层组件及其连接关系
  • 区分内部模块与外部依赖
  • 标注核心数据流方向

类图 (class)

  • 核心类型为类节点(名称+字段+方法)
  • 继承、组合、依赖关系
  • 接口与实现分离
  • 限制在 10-15 个核心类型

对象图 (object)

  • 选取一个典型运行时场景
  • 展示对象实例及其属性值
  • 对象间的链接关系

组件图 (component)

  • 每个组件为一个节点
  • 箭头表示依赖/调用方向
  • 标注接口名称

部署图 (deployment)

  • 物理节点(服务器、容器、Serverless)
  • 中间件(消息队列、缓存、数据库)
  • 外部服务(第三方 API)
  • 标注通信协议

包图 (package)

  • 按模块/命名空间分组
  • 包间依赖关系
  • 体现分层架构

复合结构图 (composite-structure)

  • 类/组件的内部结构
  • 部件(Part)与连接器(Connector)
  • 端口(Port)与接口

剖面图 (profile)

  • 自定义构造型(Stereotype)
  • 扩展元模型的标签定义(Tagged Values)
  • 领域特定建模约束

流程图 (flowchart) — 非UML,最常用

  • 主流程 + 关键分支
  • 失败/异常路径
  • 起止节点清晰

用例图 (usecase)

  • 参与者(人/外部系统)
  • 用例椭圆
  • include/extend 关系

活动图 (activity)

  • 阶段/步骤为活动节点
  • 并行分支用 fork/join
  • 决策点用菱形

状态机图 (state-machine)

  • 对象的关键状态
  • 触发状态变迁的事件
  • 动作/守卫条件
  • 初始态和终态

序列图 (sequence)

  • 参与者为纵向生命线
  • 水平箭头为消息调用
  • 标注关键返回值
  • 关注 2-5 个核心交互场景

通信图 (communication)

  • 组件为节点,消息为连线
  • 标注消息序号
  • 强调协作关系而非时序

定时图 (timing)

  • 时间轴横向展开
  • 状态变化的时间约束
  • 持续时间标注

交互概览图 (interaction-overview)

  • 控制流节点内嵌交互片段
  • 展示条件分支和循环
  • 宏观概览各交互场景

泳道图 (swimlane) — 活动图变体

  • 按组件/角色分泳道
  • 流程步骤在对应泳道内
  • 跨泳道箭头表示交互

ListenHub TTS: 文本转语音

使用 ListenHub OpenAPI 将文本转换为语音。支持三种合成模式,覆盖从短文本到长文本的全场景。

API 信息

  • Base URL: https://api.marswave.ai/openapi
  • 认证: Authorization: Bearer $LISTENHUB_API_KEY(从环境变量读取)
  • 前置检查: 调用任何 API 前先确认 LISTENHUB_API_KEY 环境变量已设置,未设置则提示用户配置

音色选择流程

用户已明确指定音色

直接使用用户指定的 speakerId,跳过选择流程。

用户未指定音色

  1. 调用 GET /v1/speakers/list?language=zh 获取可用音色列表
  2. 按 AskUserQuestion 展示音色列表供用户选择,格式如下:
    • 默认选中 chat-girl-105-cn(晓曼 dxqqq)
    • 列表展示:{name}({gender},{speakerId})
    • 附带每个音色的 demoAudioUrl 供参考
  3. 用户确认后使用选定的 speakerId

默认音色

字段值
speakerIdchat-girl-105-cn
名称晓曼 dxqqq

三种合成模式

模式一:快速合成(短文本,单音色)

适用场景: 短文本(< 1000 字),单音色,需要低延迟

接口: POST /v1/tts

请求体:

{
  "text": "要合成的文本",
  "speakerId": "chat-girl-105-cn",
  "format": "mp3",
  "sampleRate": 24000,
  "speed": 1.0
}
参数类型必填说明
textstring是要合成的文本
speakerIdstring是音色 ID
formatstring否输出格式,默认 mp3
sampleRateint否采样率,默认 24000
speedfloat否语速,默认 1.0,范围 0.5 ~ 2.0

响应: 直接返回 MP3 二进制流(Content-Type: audio/mpeg)

调用示例:

curl -X POST "https://api.marswave.ai/openapi/v1/tts" \
  -H "Authorization: Bearer $LISTENHUB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "你好世界", "speakerId": "chat-girl-105-cn"}' \
  -o output.mp3

模式二:多角色脚本合成

适用场景: 多角色对话、播客、有声书片段,需要不同音色交替朗读

接口: POST /v1/speech

请求体:

{
  "script": [
    {
      "text": "你好,欢迎收听本期节目。",
      "speakerId": "chat-girl-105-cn"
    },
    {
      "text": "谢谢,今天我们来聊聊 AI。",
      "speakerId": "chat-boy-101-cn"
    }
  ],
  "format": "mp3",
  "sampleRate": 24000
}
参数类型必填说明
scriptarray是脚本数组,每项包含 text 和 speakerId
script[].textstring是该段文本
script[].speakerIdstring是该段的音色 ID
formatstring否输出格式,默认 mp3
sampleRateint否采样率,默认 24000

响应: JSON

{
  "audioUrl": "https://cdn.example.com/output.mp3",
  "duration": 12.5
}

调用示例:

curl -X POST "https://api.marswave.ai/openapi/v1/speech" \
  -H "Authorization: Bearer $LISTENHUB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "script": [
      {"text": "你好,欢迎收听。", "speakerId": "chat-girl-105-cn"},
      {"text": "谢谢,我们开始吧。", "speakerId": "chat-boy-101-cn"}
    ]
  }'

模式三:长文本流式合成

适用场景: 长文本(> 1000 字),文章朗读,需要 AI 润色或分段处理

接口: POST /v1/flow-speech/episodes

请求体:

{
  "title": "文章标题",
  "content": "长文本内容...",
  "speakerId": "chat-girl-105-cn",
  "mode": "direct",
  "format": "mp3"
}
参数类型必填说明
titlestring是音频标题
contentstring否文本内容(与 contentUrl 二选一)
contentUrlstring否内容 URL(与 content 二选一)
speakerIdstring是音色 ID
modestring否direct(直接合成)或 aiPolish(AI 润色),默认 direct
formatstring否输出格式,默认 mp3

响应: JSON

{
  "episodeId": "ep_abc123",
  "status": "processing"
}

轮询获取结果:

GET /v1/flow-speech/episodes/{episodeId}

轮询策略:

  1. 提交后等待 30 秒
  2. 之后每 10 秒轮询一次
  3. 直到 status 变为 completed 或 failed

轮询响应:

{
  "episodeId": "ep_abc123",
  "status": "completed",
  "audioUrl": "https://cdn.example.com/output.mp3",
  "duration": 180.5
}
status 值说明
processing合成中,继续轮询
completed合成完成,audioUrl 可用
failed合成失败,查看 errorMessage

调用示例:

# 提交任务
curl -X POST "https://api.marswave.ai/openapi/v1/flow-speech/episodes" \
  -H "Authorization: Bearer $LISTENHUB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "AI 技术趋势",
    "content": "长文本内容...",
    "speakerId": "chat-girl-105-cn",
    "mode": "direct"
  }'

# 轮询结果
curl "https://api.marswave.ai/openapi/v1/flow-speech/episodes/ep_abc123" \
  -H "Authorization: Bearer $LISTENHUB_API_KEY"

音色列表查询

接口: GET /v1/speakers/list

查询参数:

参数类型必填说明
languagestring否筛选语言,如 zh(中文)、en(英文)

响应:

{
  "speakers": [
    {
      "name": "晓曼 dxqqq",
      "speakerId": "chat-girl-105-cn",
      "demoAudioUrl": "https://cdn.example.com/demo.mp3",
      "gender": "female",
      "language": "zh"
    }
  ]
}

模式选择逻辑

根据用户输入自动选择最合适的模式:

条件模式
文本 ≤ 1000 字,单音色模式一:/v1/tts
多角色脚本,需要不同音色模式二:/v1/speech
文本 > 1000 字,或需要 AI 润色模式三:/v1/flow-speech/episodes
用户提供 URL 作为内容来源模式三:/v1/flow-speech/episodes

如果用户明确指定模式,优先使用用户指定的模式。

用户交互

音色选择

当用户未指定音色时,使用 AskUserQuestion 展示音色列表:

请选择音色(默认:晓曼 dxqqq):
A. 晓曼 dxqqq(女,chat-girl-105-cn)[默认]
B. [其他音色名称]([性别],[speakerId])
C. ...

合成参数

可选询问:

  • 语速 speed(默认 1.0)
  • 输出格式 format(默认 mp3)
  • 长文本模式:direct 还是 aiPolish(默认 direct)
  • 输出文件路径(默认 ./output.mp3)

输出

  1. 将音频保存到指定路径(默认 ./output.mp3)
  2. 输出合成摘要:
    • 使用的模式
    • 音色名称和 ID
    • 音频时长
    • 文件大小
    • 文件路径

错误处理

  • 401 Unauthorized: 提示用户检查 LISTENHUB_API_KEY 环境变量
  • 400 Bad Request: 检查请求参数,向用户报告具体错误
  • flow-speech failed: 报告 errorMessage,建议用户重试或切换模式
  • 网络错误: 提示检查网络连接,建议重试

完整示例

用户输入: "把这段文字转成语音:今天天气真好,适合出去散步。"

执行流程:

  1. 检查 LISTENHUB_API_KEY ✓
  2. 文本长度 < 1000 字,单音色 → 选择模式一 /v1/tts
  3. 用户未指定音色 → 默认使用 chat-girl-105-cn(晓曼)
  4. 调用 API 合成
  5. 保存到 ./output.mp3
  6. 输出摘要

用户输入: "用晓曼的声音朗读这篇文章:article.md"

执行流程:

  1. 读取 article.md 内容
  2. 检查文本长度 > 1000 字 → 选择模式三 /v1/flow-speech/episodes
  3. 音色已指定:chat-girl-105-cn(晓曼)
  4. 提交合成任务
  5. 轮询直到完成
  6. 下载音频保存到 ./article.mp3
  7. 输出摘要

loop-it — 带检查点恢复的自动化 Issue 实现循环

Fetch all open GitHub issues, resolve dependency order, implement each through the full pipeline (内联实现 → /review-it → /ship-it), persist progress to state file, and resume from checkpoint on crash.

⚠️ 关键前提:实现步骤由 agent 内联自主完成,不依赖任何外部 /goal 命令。 本环境中不存在可调用的 goal 命令或 skill。因此「实现 issue」这一步必须由 agent 内联完成:直接读取该 issue 的标题与正文(含其引用的 PRD/SPEC 与验收条件),自主完成"理解需求 → 写/改代码 → 跑测试与 lint → 满足全部验收条件"的闭环,持续工作直到该 issue 的验收条件全部满足且测试/构建通过。不要尝试用 Skill 工具调用 goal(会报 goal is a UI command, not a skill),也不要因为找不到 /goal 而中止循环。/review-it、/ship-it 仍是真实 skill,经 Skill 工具调用。loop-it 循环中不调用 /note-it。


Overview

前置检查 → 读取状态文件 → Fetch Issues → 构建依赖图 → 拓扑排序
                                                              |
    ┌───────────────────────────────────────────────────────────┘
    |
    v
┌──────────────── 单 Issue 循环 ────────────────┐
|                                               |
|  从检查点恢复?—— 跳过已完成/失败的             |
|                                               |
|  分支准备 (checkout main, pull, create branch) |
|        |                                      |
|  Skip/Blocked? ── 是 → 标记 skipped/blocked, 写检查点 |
|        |                                      |
|        否                                      |
|        |                                      |
|  内联实现 → 出错?→ 分类 → 恢复 → 重试        |
|        |              |                       |
|        |           失败 → 检查点, 下一个         |
|        |                                      |
|  /review-it → 有问题?→ 修复 → 重跑 review     |
|        |                                      |
|  /ship-it → 出错?→ 分类 → 恢复                |
|        |                                      |
|  分支清理 (checkout main, pull, delete branch) |
|        |                                      |
|  检查点 (标记 shipped)                         |
|        |                                      |
└────────┴──────────────────────────────────────┘
         |
         v
    全部完成 → 最终 Summary

前置检查

开始循环前,按顺序验证所有前提条件。任何检查失败则停止并打印错误。

Check 1: gh CLI 认证

gh auth status

失败 → 打印 ❌ gh CLI 未认证。运行: gh auth login,退出。

Check 2: Git 仓库

git rev-parse --is-inside-work-tree

失败 → 打印 ❌ 不在 git 仓库中,退出。

Check 3: Git 工作树清洁度

git status --porcelain

有输出(dirty)→ 打印 ⚠️ 工作树有未提交的更改,提供选项:

  • A. git stash 暂存后继续
  • B. 中止,让用户自行处理
  • C. 强制继续(不推荐)

默认 B。

Check 4: 在默认分支上

git branch --show-current

不在 main/master → 打印 ⚠️ 当前在 {branch} 分支,提供选项:

  • A. git checkout main && git pull 切换
  • B. 继续在当前分支

Check 5: 远程可达

git ls-remote --heads origin

失败 → 打印 ❌ 无法访问远程仓库。检查网络和权限,退出。

Check 6: 状态文件存在?

cat .loop-state.json

存在 → 打印进度摘要,提供选项:

  • A. 从检查点恢复
  • B. 从头开始(删除状态文件)
  • C. 中止

状态文件

位置

.loop-state.json,放在 repo 根目录。必须添加到 .gitignore。如果文件被 git 跟踪,打印警告并建议用户添加到 .gitignore。

格式

{
  "version": 1,
  "started_at": "2025-06-09T10:00:00Z",
  "updated_at": "2025-06-09T10:30:00Z",
  "repo": "owner/repo-name",
  "total_issues": 8,
  "issues": {
    "3": {
      "status": "shipped",
      "branch": "feat/issue-3-add-priority",
      "started_at": "2025-06-09T10:00:00Z",
      "completed_at": "2025-06-09T10:15:00Z",
      "attempts": 1
    },
    "4": {
      "status": "failed",
      "phase": "goal",
      "error_class": "build_failure",
      "branch": "feat/issue-4-filter-tasks",
      "started_at": "2025-06-09T10:15:00Z",
      "updated_at": "2025-06-09T10:30:00Z",
      "attempts": 3,
      "last_error": "test TestFilterPriority failed: expected 3, got 0"
    },
    "7": {
      "status": "pending"
    }
  }
}

状态值

pending | in_progress | skipped | shipped | failed | blocked

写入规则

  • 每次状态转换后立即写入(pending → in_progress、in_progress → shipped/failed/skipped 等)
  • 写入使用 cat > .loop-state.json << 'LOOPSTATE'\n{json}\nLOOPSTATE
  • 如果状态文件已存在但内容损坏(非法 JSON),打印警告,提供从头开始或中止的选项。绝不自动覆盖损坏文件
  • 循环完成后保留状态文件(作为记录),用户可手动删除

Step 1: Fetch Issues & Build Dependency Graph

Fetch all open issues:

gh issue list --state open --json number,title,labels,body --limit 100

Parse Dependencies

Read each issue body, look for patterns:

  • Dependencies: #3, #5 or Depends on: #3
  • depends on #3 or requires #3 (in body text)

Build a dependency graph. Sort using topological order:

  1. Issues with no dependencies first (sorted by number ascending)
  2. Issues whose dependencies are all shipped/closed next
  3. Blocked issues (depend on other open issues) last
  4. Circular dependencies → print warning ⚠️ 循环依赖检测到: #A ↔ #B,按编号顺序处理,break cycle by number order

If no dependency patterns found in any issue body, fall back to number-ascending sort.

Print ordered list:

📋 Found N open issues (topological sort):
  #1: Add priority field (无依赖)
  #3: Display indicator (依赖 #1)
  #5: Add selector (依赖 #1)
  #7: Filter view (依赖 #1, #3)

If no open issues → print ✅ No open issues found. Nothing to do. and exit.


Step 2: Resume or Initialize

If .loop-state.json exists (from 前置检查 Check 6)

  1. Read the file
  2. Print progress summary:
📊 从检查点恢复 (上次更新: {updated_at})
   ✅ Shipped:  #1, #3
   ⏭️  Skipped:   #2 (question)
   ❌ Failed:    #4 (build_failure — 3 attempts)
   📋 Remaining: #5, #7
  1. For each failed issue: ask user — retry or skip?
  2. For in_progress issues: check if branch exists, changes exist → decide resume from current state or restart
  3. Skip all shipped/skipped issues
  4. Continue from first pending/retryable issue

If no state file

  1. Initialize new state file with all fetched issues as pending
  2. Start from first issue in topological order

Step 3: Process Single Issue

For each issue, print a banner:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔄 Processing Issue #{number}: {title}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

3a. Branch Prep

Prepare a clean git environment for this issue:

# 确认在 main 上
git checkout main
git pull

# 创建功能分支
git checkout -b feat/issue-{N}-{short-desc}

Branch naming: feat/issue-N-short-desc or fix/issue-N-short-desc(与 /ship-it 保持一致)

3b. Skip or Implement

Read the issue title and body. Decide if it needs code implementation:

Skip if the issue is:

  • A question / discussion / clarification
  • Documentation-only (typos, wording)
  • Already implemented (check codebase)
  • A duplicate of another issue
  • Clearly labeled wontfix, question, discussion, or invalid
  • Not actionable (no clear acceptance criteria and cannot infer any)

Skip (blocked) if the issue has unresolved dependencies:

  • Check the dependency graph from Step 1
  • If any dependency issue is not shipped (still pending, failed, blocked, or not in state file) → skip as blocked
  • The dependency issue itself may have failed or been skipped — in either case, this issue cannot proceed safely

When skipping:

⏭️  Skipping Issue #{number}: {title}
   Reason: {why}

When blocked:

🔒 Blocking Issue #{number}: {title}
   Reason: dependency #{dep_number} not shipped ({status})

Update state: pending → skipped or pending → blocked, write checkpoint, run 3g Branch Cleanup, proceed to next issue.

3c. Implement (内联自主实现)

Update state: pending → in_progress, phase: "implement", write checkpoint.

由 agent 内联完成实现(本环境无 goal 命令/skill 可调用,必须自己干):

  1. 读取该 issue 的标题与正文,提取需求与全部验收条件(Acceptance Criteria);若正文引用了 PRD/SPEC 文件(如 tasks/prd-*.md),一并读取作为上下文
  2. 阅读相关现有代码,遵循项目既有风格、命名与依赖约定
  3. 实现/修改代码以满足全部验收条件
  4. 跑项目的构建、测试与 lint(如 go build ./...、go vet ./...、go test ./...)
  5. 持续工作直到该 issue 的验收条件全部满足且测试/构建/lint 通过

不要尝试用 Skill 工具调用 goal(会报 goal is a UI command, not a skill),也不要因找不到 /goal 而中止——实现就是你自己内联完成的工作。

On success:

✅ Issue #{number} implementation complete

Write checkpoint with phase: "implement_done".

On failure — classify error (see 错误分类与恢复), apply recovery strategy, retry up to max attempts. If all retries exhausted:

⚠️  Issue #{number} failed: {error_class} after {N} attempts
   Manual intervention required.

Update state: in_progress → failed, write checkpoint, run 3g Branch Cleanup, proceed to next issue.

3d. Review with /review-it

Write checkpoint with phase: "review".

/review-it

If review finds actionable issues:

🔍 Review found N issue(s) for #{number}. Fixing...

Fix each accepted finding, re-run /review-it. Repeat until clean or max 2 review rounds.

If review is clean:

✅ Review clean for Issue #{number}

Write checkpoint with phase: "review_done".

3e. Ship with /ship-it

/ship-it

This commits, pushes, creates PR, merges, and closes the issue.

On success:

🚀 Issue #{number} shipped successfully!

On failure — classify error (see 错误分类与恢复), apply recovery. If unresolvable:

⚠️  Issue #{number} ship failed: {error}. Manual merge required.

Update state: in_progress → failed, phase: "ship", write checkpoint, run 3g Branch Cleanup, proceed to next issue.

3f. Checkpoint

After successful ship, update state: in_progress → shipped, set completed_at, write checkpoint.

Print progress (see 进度可观测性).

3g. Branch Cleanup

After each issue (shipped, skipped, or failed):

# 切回 main
git checkout main
git pull

# 删除本地功能分支(仅当 shipped 时)
git branch -d feat/issue-{N}-{short-desc}

For failed issues: do NOT delete the branch. Keep it for investigation.

Next Issue

Return to Step 3 for the next issue in topological order.

When all issues processed, print final summary:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Loop Complete — Summary
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  ✅ Shipped:   N issues  (#1, #3, ...)
  ⏭️  Skipped:   N issues  (#2 — reason, #5 — reason, ...)
  🔒 Blocked:   N issues  (#7 — depends on #4, ...)
  ❌ Failed:    N issues  (#4 — error, ...)
  📋 Total:     N issues
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

错误分类与恢复

当错误发生时,先分类,再按策略恢复。

错误类别检测信号恢复策略最大重试
build_failure编译错误、undefined、类型错误读错误,修代码,重新构建3
test_failure断言失败、test failed读测试输出,修实现,重跑测试3
lint_failurelint 错误、格式问题自动修复 (lint --fix),重跑2
merge_conflictCONFLICT 标记rebase origin/main,解决冲突,push2
ci_failuregh pr checks 失败读 CI 日志,本地修复,push2
auth_failure403、401、认证错误停止,告知用户重新认证0
rate_limitrate limit、secondary abuse等待 60s,重试3
issue_unclearissue 无验收条件且无法推断需求跳过,标记 failed0
network_errortimeout、connection refused等待 30s,重试3
unknown其他情况记录完整错误,跳过0

恢复协议:

  1. 匹配错误类别
  2. 匹配成功 → 应用恢复策略,重试最多 N 次
  3. 重试全部失败 → 标记 failed,写检查点,继续下一个 issue
  4. 无法匹配 → 标记 failed(error_class: unknown),继续
  5. 绝不无限重试。绝不未经确认 force-push。

进度可观测性

每完成一个 issue 后,打印结构化进度:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Progress: 3/8 issues (37%)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  ✅ Shipped:  #1, #3
  ⏭️  Skipped:   #2 (question), #6 (duplicate)
  🔒 Blocked:   #7 (depends on #4 — failed)
  ❌ Failed:    #4 (build_failure — 3 attempts)
  📋 Remaining: #5, #8
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Logging Rules

Every key step MUST print a log line with emoji prefix:

EmojiMeaning
📋Fetch / list
🔄Processing issue
⏭️Skip
🔒Blocked (dependency not shipped)
✅Success
❌Failure
🔍Review
🚀Ship
⚠️Warning / retry
📊Progress / summary

Safety Guards

  • Never force-push to main/master — always use feature branches
  • Never skip review — always run /review-it before /ship-it
  • Max retries per error class — 参见错误分类与恢复表,不无限重试
  • Max 2 review rounds — don't over-polish
  • Pause on CI failure — log and continue, don't auto-override branch protection
  • Preserve issue labels — only close issues that were actually shipped
  • Never auto-delete failed branches — 保留供调查
  • Checkpoint at every transition — 每次状态变更写检查点,不仅仅在 ship 时
  • State file integrity — 损坏时警告用户,绝不自动覆盖
  • State file in .gitignore — 提醒用户添加 .loop-state.json
  • Strictly sequential — 一次只处理一个 issue(实现会修改工作树,不能并行)
  • Skip dependency-blocked issues — 依赖的 issue 未 shipped 时标记 blocked
  • 实现由 agent 内联完成 — 本环境无 goal 命令/skill 可调用;「实现 issue」必须由 agent 自己读 issue、写代码、跑测试完成。报 goal is a UI command, not a skill 时不要中止,直接内联实现

Edge Cases

ScenarioHandling
No open issuesPrint "nothing to do" and exit
All issues are questionsSkip all, report summary
gh not authenticatedPrint error, suggest gh auth login, exit
Issue has no bodyUse title only to decide skip/implement
Issue references PRD/SPEC读取被引用的 PRD/SPEC 作为上下文,agent 内联实现
Multiple issues depend on each otherTopological sort; dependencies already shipped first
Git repo is dirty before starting前置检查 Check 3: stash/abort/force
State file corrupted (invalid JSON)警告用户,提供从头开始或中止选项。绝不自动覆盖
State file from different repo检测 repo 字段不匹配,警告,提供从头开始选项
Issue in_progress from previous run检查分支是否存在、是否有变更 → 恢复或重新开始
User aborts mid-loop状态文件已包含最新检查点,下次运行可恢复
New issues created during loop不重新获取。完成当前批次后运行新 /loop-it
Circular dependencies打印警告,按编号顺序打破循环
.loop-state.json is git-tracked警告用户添加到 .gitignore,继续
误以为需要外部 goal 命令本环境无此命令;「实现 issue」由 agent 内联完成(读 issue → 写代码 → 测试),不要中止循环

Relationship to Other Skills

/loop-it
  ├── 内联实现   ← implement each issue(agent 自主读 issue、写代码、测试;非外部命令)
  ├── /review-it  ← review code before shipping(skill)
  └── /ship-it    ← commit, PR, merge, close(skill)

Part of the goal-workflow pipeline:

/prd → /prd-to-spec → /to-issues → /loop-it (→ 内联实现 → /review-it → /ship-it)×N

modern-go

Modernize Go source code by applying version-appropriate idioms, APIs, and language features. Works like go fix plus additional transformations curated from the Go team's modernize analysis passes and community best practices.

Usage

Invoke this skill when the user asks to modernize Go code. By default, modernize the entire project; the user may specify a file or directory instead.

When invoked:

  1. Detect the project's Go version from go.mod (the go directive).
  2. Find all .go files in the target scope (excluding vendor/, .git/, testdata/).
  3. For each file, apply all transformations for versions ≤ the project's Go version, starting from the oldest to the newest.
  4. After all transformations, print a summary of what was changed and what was skipped.

If the user specifies a file or directory, limit the scope to that path.

Transformation Catalog

Each transformation includes a Go version gate—only apply when the project's go.mod version ≥ that version. Never apply a transformation that requires a version higher than the project declares.

Go 1.0+ — time.Since

BeforeAfter
time.Now().Sub(start)time.Since(start)
// before
elapsed := time.Now().Sub(start)
// after
elapsed := time.Since(start)

Go 1.8+ — time.Until

BeforeAfter
deadline.Sub(time.Now())time.Until(deadline)
// before
remaining := deadline.Sub(time.Now())
// after
remaining := time.Until(deadline)

Go 1.10+ — strings.Builder (loop concatenation)

BeforeAfter
s += item in a loopvar b strings.Builder; b.WriteString(item)
// before
s := ""
for _, item := range items {
    s += item
}
// after
var b strings.Builder
for _, item := range items {
    b.WriteString(item)
}
s := b.String()

Only when += concatenation happens inside a loop.

Go 1.13+ — errors.Is

BeforeAfter
err == io.EOFerrors.Is(err, io.EOF)
// before
if err == io.EOF {
    return
}
// after
if errors.Is(err, io.EOF) {
    return
}

Go 1.17+ — //go:build constraints (plusbuild)

BeforeAfter
// +build linux + //go:build linux (both present)keep only //go:build linux
// before
//go:build linux && amd64
// +build linux,amd64

package foo
// after
//go:build linux && amd64

package foo

The plusbuild modernizer removes obsolete // +build constraint lines once the equivalent //go:build line is present (the //go:build syntax landed in Go 1.17). Only strip the old line when a matching //go:build already exists — never drop the sole constraint.

Go 1.17+ — unsafe.Add / unsafe.Slice (unsafefuncs)

BeforeAfter
unsafe.Pointer(uintptr(ptr) + uintptr(n))unsafe.Add(ptr, n)
(*[n]T)(unsafe.Pointer(p))[:] slice constructionunsafe.Slice(p, n)
// before — pointer arithmetic via uintptr
p2 := unsafe.Pointer(uintptr(ptr) + uintptr(offset))
// after
p2 := unsafe.Add(ptr, offset)
// before — building a slice from a base pointer
s := (*[1 << 30]byte)(unsafe.Pointer(p))[:n:n]
// after
s := unsafe.Slice(p, n)

The unsafefuncs modernizer (gopls v0.22.0) rewrites error-prone uintptr pointer math into unsafe.Add / unsafe.Slice, which the compiler and go vet understand as GC-safe.

Go 1.18+ — any

BeforeAfter
interface{}any
// before
func decode(v interface{}) error { ... }
// after
func decode(v any) error { ... }

Go 1.18+ — strings.Cut

BeforeAfter
i := strings.Index(s, sep); ... s[:i], s[i+len(sep):]key, val, found := strings.Cut(s, sep)
// before
if i := strings.Index(s, "="); i >= 0 {
    key, val := s[:i], s[i+1:]
}
// after
if key, val, found := strings.Cut(s, "="); found {
    ...
}

Go 1.18+ — bytes.Cut

BeforeAfter
i := bytes.Index(b, sep); ... b[:i], b[i+len(sep):]before, after, found := bytes.Cut(b, sep)
// before
if i := bytes.Index(b, sep); i >= 0 {
    before, after := b[:i], b[i+len(sep):]
}
// after
before, after, found := bytes.Cut(b, sep)

Go 1.19+ — fmt.Appendf

BeforeAfter
buf = append(buf, fmt.Sprintf(...)...)buf = fmt.Appendf(buf, ...)
// before
buf = append(buf, fmt.Sprintf("x=%d", x)...)
// after
buf = fmt.Appendf(buf, "x=%d", x)

Go 1.19+ — Type-safe atomics (atomictypes)

BeforeAfter
atomic.StoreInt32(&v, 1) / atomic.LoadInt32(&v)var v atomic.Int32; v.Store(1); v.Load()
atomic.AddInt64(&v, 1)var v atomic.Int64; v.Add(1)
atomic.Value + type assertionatomic.Pointer[T]
// before
var ready int32
atomic.StoreInt32(&ready, 1)
if atomic.LoadInt32(&ready) == 1 { ... }

// after
var ready atomic.Int32
ready.Store(1)
if ready.Load() == 1 { ... }
// before
var cache atomic.Value
cache.Store(&Config{})
cfg := cache.Load().(*Config)

// after
var cache atomic.Pointer[Config]
cache.Store(&Config{})
cfg := cache.Load()

The atomictypes modernizer (gopls v0.22.0, AtomicTypesAnalyzer) rewrites both the variable declaration and every call site. Typed wrappers (atomic.Int32/Int64/Uint32/Uint64/Bool/Pointer[T]) have identical performance but prevent accidental non-atomic access and fix 64-bit alignment crashes on 32-bit architectures.

Go 1.20+ — strings.Clone

BeforeAfter
string([]byte(s))strings.Clone(s)
// before
s2 := string([]byte(s)) // force copy
// after
s2 := strings.Clone(s)

Go 1.20+ — bytes.Clone

BeforeAfter
make([]byte, len(src)); copy(dst, src)bytes.Clone(src)
// before
dst := make([]byte, len(src))
copy(dst, src)
// after
dst := bytes.Clone(src)

Go 1.20+ — strings.CutPrefix / strings.CutSuffix

BeforeAfter
if strings.HasPrefix(s, p) { s = s[len(p):] }if rest, ok := strings.CutPrefix(s, p); ok { s = rest }
if strings.HasSuffix(s, sf) { s = s[:len(s)-len(sf)] }if rest, ok := strings.CutSuffix(s, sf); ok { s = rest }
// before
if strings.HasPrefix(s, "pre_") {
    s = s[len("pre_"):]
}
// after
if rest, ok := strings.CutPrefix(s, "pre_"); ok {
    s = rest
}
// before
if strings.HasSuffix(s, ".txt") {
    s = s[:len(s)-len(".txt")]
}
// after
if rest, ok := strings.CutSuffix(s, ".txt"); ok {
    s = rest
}

Go 1.20+ — errors.Join

BeforeAfter
fmt.Errorf("...: %w: %w", err1, err2)errors.Join(err1, err2)
// before
return fmt.Errorf("load config: %w: %w", err1, err2)
// after
return errors.Join(fmt.Errorf("load config"), err1, err2)

Go 1.20+ — context.WithCancelCause

BeforeAfter
ctx, cancel := context.WithCancel(parent) + bare cancel()ctx, cancel := context.WithCancelCause(parent) + cancel(err)
// before
ctx, cancel := context.WithCancel(parent)
// ... somewhere ...
cancel()

// after
ctx, cancel := context.WithCancelCause(parent)
cancel(ErrShutdown)
// caller: context.Cause(ctx) → ErrShutdown

Go 1.21+ — min / max

BeforeAfter
if a < b { v = a } else { v = b }v = min(a, b)
if a > b { v = a } else { v = b }v = max(a, b)
if x < lo { x = lo }; if x > hi { x = hi }x = min(max(x, lo), hi)
// before
lo := a
if b < lo {
    lo = b
}
// after
lo := min(a, b)
// before
if x < 0 {
    x = 0
}
if x > 100 {
    x = 100
}
// after
x = min(max(x, 0), 100)

Go 1.21+ — clear

BeforeAfter
for k := range m { delete(m, k) }clear(m)
for i := range s { s[i] = zero }clear(s)
// before
for k := range m {
    delete(m, k)
}
// after
clear(m)
// before
for i := range s {
    s[i] = 0
}
// after
clear(s)

Go 1.21+ — slices package

BeforeAfter
Manual loop to find elementslices.Contains(items, target)
Loop returning index or -1slices.Index(items, target)
sort.Slice(items, func(i,j int) bool { return items[i] < items[j] })slices.SortFunc(items, cmp.Compare)
Max/min finding loopslices.Max(items) / slices.Min(items)
Reverse swap loopslices.Reverse(s)
Remove consecutive duplicates loopslices.Compact(s)
s[:len(s):len(s)]slices.Clip(s)
make([]T, len(src)); copy(dst, src)slices.Clone(src)
// before → after: slices.Contains(items, target)
found := false
for _, x := range items {
    if x == target {
        found = true
        break
    }
}
// before → after: slices.Index(items, target)
for i, x := range items {
    if x == target {
        return i
    }
}
return -1
// before → after: slices.SortFunc(items, cmp.Compare)
sort.Slice(items, func(i, j int) bool { return items[i] < items[j] })
// before → after: slices.Max(items) / slices.Min(items)
max := items[0]
for _, v := range items[1:] {
    if v > max {
        max = v
    }
}
// before → after: slices.Reverse(s)
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
    s[i], s[j] = s[j], s[i]
}
// before → after: slices.Compact(s)
i := 0
for j := 1; j < len(s); j++ {
    if s[j] != s[i] {
        i++
        s[i] = s[j]
    }
}
s = s[:i+1]
// before → after: slices.Clip(s)
s = s[:len(s):len(s)]
// before → after: slices.Clone(src)
dst := make([]T, len(src))
copy(dst, src)

Requires importing "slices" and "cmp" (for SortFunc).

Go 1.21+ — slices.Delete / slices.Insert

BeforeAfter
append(s[:i], s[i+1:]...)slices.Delete(s, i, i+1)
append(s[:i:i], append([]T{x}, s[i:]...)...)slices.Insert(s, i, x)
// before — element removal (classic aliasing/leak footgun)
s = append(s[:i], s[i+1:]...)
// after
s = slices.Delete(s, i, i+1)
// before — insert at index i
s = append(s[:i], append([]T{v}, s[i:]...)...)
// after
s = slices.Insert(s, i, v)

slices.Delete zeroes the tail elements to avoid retaining pointers (the manual append form leaks). Requires importing "slices".

Go 1.21+ — slices.Equal / maps.Equal

BeforeAfter
reflect.DeepEqual(a, b) for comparable slicesslices.Equal(a, b)
reflect.DeepEqual(m1, m2) for comparable mapsmaps.Equal(m1, m2)
// before
if reflect.DeepEqual(got, want) { ... }   // got, want are []string
// after
if slices.Equal(got, want) { ... }

Faster and type-safe, with no reflection. Only for element types that are directly comparable (use slices.EqualFunc / maps.EqualFunc otherwise). Requires importing "slices" or "maps".

Go 1.21+ — maps package

BeforeAfter
Manual loop to copy a mapmaps.Clone(m)
for k, v := range src { dst[k] = v }maps.Copy(dst, src)
Loop + conditional deletemaps.DeleteFunc(m, predicate)
// before → after: maps.Clone(m)
dst := make(map[K]V)
for k, v := range src {
    dst[k] = v
}
// before → after: maps.Copy(dst, src)
for k, v := range src {
    dst[k] = v
}
// before → after: maps.DeleteFunc(m, func(k K, v V) bool { return v == 0 })
for k, v := range m {
    if v == 0 {
        delete(m, k)
    }
}

Requires importing "maps".

Go 1.22+ — slices.Concat (appendclipped)

BeforeAfter
append(append([]T(nil), s1...), s2...)slices.Concat(s1, s2)
append(slices.Clip(s1), s2...) for a fresh resultslices.Concat(s1, s2)
// before
all := append(append([]int(nil), a...), b...)
// after
all := slices.Concat(a, b)
// before — three-way concat
merged := append(append(append([]string(nil), x...), y...), z...)
// after
merged := slices.Concat(x, y, z)

The appendclipped modernizer replaces nested append concatenation of multiple slices with slices.Concat, which allocates a fresh, correctly-sized result. slices.Concat was added in Go 1.22. Requires importing "slices". Only apply when the pattern builds a new slice (starts from []T(nil) or a clipped base) — not when it appends in place to an existing slice.

Go 1.21+ — sync.OnceFunc / sync.OnceValue

BeforeAfter
var once sync.Once; once.Do(func() { ... })f := sync.OnceFunc(func() { ... }); f()
sync.Once + stored result variablesync.OnceValue(func() T { return val })
// before
var once sync.Once
func init() { once.Do(func() { setup() }) }

// after
var initOnce = sync.OnceFunc(func() { setup() })
// before
var once sync.Once
var cfg *Config
func getConfig() *Config {
    once.Do(func() { cfg = loadConfig() })
    return cfg
}
// after
var getConfig = sync.OnceValue(func() *Config { return loadConfig() })

Go 1.21+ — context.AfterFunc

BeforeAfter
go func() { <-ctx.Done(); cleanup() }()stop := context.AfterFunc(ctx, cleanup)
// before
go func() {
    <-ctx.Done()
    conn.Close()
}()
// after
stop := context.AfterFunc(ctx, func() { conn.Close() })

Go 1.21+ — context.WithTimeoutCause / WithDeadlineCause

BeforeAfter
context.WithTimeout(parent, d)context.WithTimeoutCause(parent, d, err)
// before
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
// after
ctx, cancel := context.WithTimeoutCause(parent, 5*time.Second, ErrTimeout)

Only apply when a meaningful cause error is available.

Go 1.22+ — Range over integer

BeforeAfter
for i := 0; i < n; i++ { ... }for i := range n { ... }
for i := 0; i < n; i++ { ... } (i unused)for range n { ... }
// before
for i := 0; i < len(items); i++ {
    process(i, items[i])
}
// after
for i := range len(items) {
    process(i, items[i])
}
// before
for i := 0; i < n; i++ {
    doWork()
}
// after
for range n {
    doWork()
}

Go 1.22+ — Loop variable shadowing removal

BeforeAfter
for _, x := range items { x := x; ... }for _, x := range items { ... }
// before
for _, x := range items {
    x := x          // capture for goroutine
    go func() { use(x) }()
}
// after
for _, x := range items {
    go func() { use(x) }()
}

The x := x capture idiom is redundant since Go 1.22.

Go 1.22+ — cmp.Or

BeforeAfter
Chain of if v == "" { v = fallback }v := cmp.Or(val, fallback1, fallback2, ...)
// before
name := os.Getenv("NAME")
if name == "" {
    name = os.Getenv("USER")
}
if name == "" {
    name = "anonymous"
}
// after
name := cmp.Or(os.Getenv("NAME"), os.Getenv("USER"), "anonymous")

Requires importing "cmp".

Go 1.22+ — reflect.TypeFor

BeforeAfter
reflect.TypeOf((*T)(nil)).Elem()reflect.TypeFor[T]()
// before
t := reflect.TypeOf((*MyType)(nil)).Elem()
// after
t := reflect.TypeFor[MyType]()

Go 1.22+ — Enhanced http.ServeMux

BeforeAfter
mux.HandleFunc("/api/", h) + manual path parsingmux.HandleFunc("GET /api/{id}", h) + r.PathValue("id")
// before
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
    id := strings.TrimPrefix(r.URL.Path, "/api/")
    ...
})
// after
mux.HandleFunc("GET /api/{id}", func(w http.ResponseWriter, r *http.Request) {
    id := r.PathValue("id")
    ...
})

Go 1.22+ — math/rand/v2

BeforeAfter
rand.Intn(n)rand.IntN(n)
rand.Int63n(n) / rand.Int31n(n)rand.Int64N(n) / rand.Int32N(n)
rand.Seed(...) + global funcsdrop Seed; use auto-seeded top-level funcs or rand.N[T]
// before
import "math/rand"
n := rand.Intn(100)
// after
import "math/rand/v2"
n := rand.IntN(100)
// before — type-specific bound
d := time.Duration(rand.Int63n(int64(max)))
// after — generic N works for any integer type
d := rand.N(max)

math/rand/v2 (Go 1.22) drops the deprecated global Seed (top-level funcs are auto-seeded) and adds generic rand.N[T]. Semantic migration: the random stream differs from math/rand, so do not apply where reproducibility from a fixed seed matters. Flag as a suggestion, not auto-apply.

Go 1.23+ — Range over function (iterators)

BeforeAfter
Custom func Walk(yield func(T) bool) callback traversalfunc Walk() iter.Seq[T] returning an iterator
// before — callback-based iteration
func (t *Tree) Each(fn func(v int)) {
    for _, v := range t.values {
        fn(v)
    }
}
// caller: t.Each(func(v int) { use(v) })

// after — standard iterator, usable with range
func (t *Tree) All() iter.Seq[int] {
    return func(yield func(int) bool) {
        for _, v := range t.values {
            if !yield(v) { return }
        }
    }
}
// caller: for v := range t.All() { use(v) }

Adopt the iter.Seq[T] / iter.Seq2[K,V] protocol (Go 1.23) so custom containers compose with range, slices.Collect, maps.Keys, etc. Requires importing "iter". Flag as a suggestion — it reshapes the API surface.

Go 1.23+ — Iterator helpers

BeforeAfter
var keys []K; for k := range m { keys = append(keys, k) }slices.Collect(maps.Keys(m))
var vals []V; for _, v := range m { vals = append(vals, v) }slices.Collect(maps.Values(m))
// before
var keys []string
for k := range m {
    keys = append(keys, k)
}
// after
keys := slices.Collect(maps.Keys(m))
// before
var vals []int
for _, v := range m {
    vals = append(vals, v)
}
// after
vals := slices.Collect(maps.Values(m))

Requires importing "slices" and "maps".

Go 1.23+ — strings.SplitSeq / strings.FieldsSeq

BeforeAfter
for _, part := range strings.Split(s, sep)for part := range strings.SplitSeq(s, sep)
for _, field := range strings.Fields(s)for field := range strings.FieldsSeq(s)
// before
for _, part := range strings.Split(line, ",") {
    process(part)
}
// after
for part := range strings.SplitSeq(line, ",") {
    process(part)
}

Only when the loop body does not need the index or the full slice.

Go 1.23+ — bytes.SplitSeq / bytes.FieldsSeq

BeforeAfter
for _, part := range bytes.Split(b, sep)for part := range bytes.SplitSeq(b, sep)
// before
for _, part := range bytes.Split(data, sep) {
    process(part)
}
// after
for part := range bytes.SplitSeq(data, sep) {
    process(part)
}

Go 1.23+ — slices.Backward (slicesbackward)

BeforeAfter
for i := len(s) - 1; i >= 0; i-- { use(s[i]) }for _, v := range slices.Backward(s) { use(v) }
reverse loop needing the index toofor i, v := range slices.Backward(s) { ... }
// before
for i := len(items) - 1; i >= 0; i-- {
    process(items[i])
}
// after
for _, v := range slices.Backward(items) {
    process(v)
}
// before — index still needed
for i := len(items) - 1; i >= 0; i-- {
    fmt.Println(i, items[i])
}
// after
for i, v := range slices.Backward(items) {
    fmt.Println(i, v)
}

The slicesbackward modernizer (gopls v0.22.0) replaces manual descending-index loops with the slices.Backward iterator. Requires importing "slices". Caveat: the rewrite preserves exact semantics in normal cases, but do not apply it when the loop body mutates the slice length or the index is used for out-of-band arithmetic — those edge cases can become unsound.

Go 1.24+ — t.Context() in tests

BeforeAfter
ctx, cancel := context.WithCancel(context.Background()); defer cancel()ctx := t.Context()
// before
func TestFetch(t *testing.T) {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    result := fetch(ctx)
}
// after
func TestFetch(t *testing.T) {
    result := fetch(t.Context())
}

Go 1.24+ — strings.Lines / bytes.Lines

BeforeAfter
bufio.Scanner line loop over a string/bufferfor line := range strings.Lines(s)
// before
sc := bufio.NewScanner(strings.NewReader(s))
for sc.Scan() {
    process(sc.Text())
}
// after
for line := range strings.Lines(s) {
    process(strings.TrimSuffix(line, "\n"))
}

strings.Lines / bytes.Lines (Go 1.24) return line iterators — no Scanner setup, no default 64KB token-size limit. Note the yielded line retains its trailing \n, unlike Scanner.Text(); trim it if the old code relied on stripped lines. Only apply for in-memory strings/buffers, not streaming io.Readers.

Go 1.24+ — os.Root (directory-scoped filesystem access)

BeforeAfter
manual filepath.Clean + prefix check to block traversalroot, _ := os.OpenRoot(dir); root.Open(name)
// before — hand-rolled path-traversal guard
p := filepath.Join(base, name)
if !strings.HasPrefix(filepath.Clean(p), filepath.Clean(base)+string(os.PathSeparator)) {
    return errUnsafePath
}
f, err := os.Open(p)
// after — the OS enforces the boundary
root, err := os.OpenRoot(base)
if err != nil { return err }
defer root.Close()
f, err := root.Open(name) // symlinks/".." escaping base are rejected

os.Root (Go 1.24) confines all operations to a directory tree, rejecting .. and symlink escapes at the syscall layer — far more robust than string prefix checks. Security hardening: flag as a strong suggestion wherever user-controlled paths are joined to a base directory.

Go 1.24+ — omitzero struct tag

BeforeAfter
json:"field,omitempty" (for time.Time, time.Duration, structs, slices, maps)json:"field,omitzero"
// before
type Config struct {
    Timeout time.Duration `json:"timeout,omitempty"`
    Labels  []string      `json:"labels,omitempty"`
}
// after
type Config struct {
    Timeout time.Duration `json:"timeout,omitzero"`
    Labels  []string      `json:"labels,omitzero"`
}

Only for types where omitempty fails: time.Time, time.Duration, structs, slices, maps. Flag as suggestion, not auto-apply.

Go 1.24+ — b.Loop() in benchmarks

BeforeAfter
for i := 0; i < b.N; i++ { ... }for b.Loop() { ... }
// before
func BenchmarkHash(b *testing.B) {
    for i := 0; i < b.N; i++ {
        hash(input)
    }
}
// after
func BenchmarkHash(b *testing.B) {
    for b.Loop() {
        hash(input)
    }
}

Go 1.25+ — sync.WaitGroup.Go

BeforeAfter
wg.Add(1); go func() { defer wg.Done(); fn() }()wg.Go(fn)
// before
var wg sync.WaitGroup
for _, item := range items {
    wg.Add(1)
    go func(item Item) {
        defer wg.Done()
        process(item)
    }(item)
}
wg.Wait()
// after
var wg sync.WaitGroup
for _, item := range items {
    wg.Go(func() { process(item) })
}
wg.Wait()

Go 1.26+ — new with expressions

BeforeAfter
v := val; &vnew(val)
Helper func ptr[T any](v T) *T { return &v }new(val) directly
// before
timeout := 30
debug := true
cfg := Config{
    Timeout: &timeout,
    Debug:   &debug,
}
// after
cfg := Config{
    Timeout: new(30),
    Debug:   new(true),
}
// before
func ptr[T any](v T) *T { return &v }
cfg := Config{Count: ptr(10)}

// after
cfg := Config{Count: new(10)}

Go 1.26+ — errors.AsType

BeforeAfter
var t *T; errors.As(err, &t)t, ok := errors.AsType[*T](err)
// before
var pathErr *os.PathError
if errors.As(err, &pathErr) {
    log.Println(pathErr.Path)
}
// after
if pathErr, ok := errors.AsType[*os.PathError](err); ok {
    log.Println(pathErr.Path)
}

Go 1.27+ — Embedded field literals (embedlit)

BeforeAfter
T{U: U{x: 1}} (redundant embedded-type specifier)T{x: 1}
type Base struct {
    ID   int
    Name string
}
type User struct {
    Base
    Age int
}

// before
u := User{
    Base: Base{ID: 1, Name: "alice"},
    Age:  30,
}
// after
u := User{
    ID:   1,
    Name: "alice",
    Age:  30,
}

The embedlit modernizer (gopls v0.22.0, EmbedLitAnalyzer) strips redundant embedded-struct field-type specifiers from composite literals. Go 1.27 lets you initialize promoted fields directly without the nested literal. Only apply when the promoted field names don't collide with the outer struct's own fields.

Operation Phases

Phase 1: Detect

Read go.mod to extract the Go version (go 1.xx line). If no go.mod is found, default to go 1.21.

Phase 2: Gather files

Find all .go files in the target scope (project root, or user-specified file/directory). Exclude vendor/, .git/, and testdata/ directories.

Phase 3: Apply transformations

For each .go file, apply all transformations for versions ≤ the detected Go version. Process files sequentially. For each file:

  1. Read the file content.
  2. Identify applicable transformations by scanning for the "Before" patterns.
  3. Apply each transformation using the Edit tool.
  4. Run goimports -w (or gofmt -w) on the file after all edits.

Never apply a transformation that requires a version higher than the project's Go version.

Phase 4: Report

Print a summary table showing:

  • File: path relative to project root
  • Transformations applied: list of transformation names per file
  • Total files modified and total transformations applied
  • Skipped transformations (available but not applicable due to version constraints) and their required Go version

Example Summary Output

## Modernization Summary

| File | Transformations |
|---|---|
| main.go | any, strings.Cut, min/max (2 occurrences) |
| pkg/handler.go | range over int (3), slices.Contains, t.Context() |
| pkg/util.go | new(expr) (1), errors.AsType → errors.Is |

**3 files modified, 10 transformations applied**

Skipped (requires higher Go version):
- new(expr): requires go 1.26 (project is go 1.24)
- WaitGroup.Go: requires go 1.25 (project is go 1.24)

Safety Rules

  • Never apply transformations that change semantics in edge cases without the user's awareness.
  • Do not apply omitzero blindly—it changes JSON serialization behavior; flag it as a suggestion instead.
  • Treat semantic migrations as suggestions, not auto-applies: math/rand/v2 (changes the random stream), iter.Seq iterators (reshapes the API), os.Root (behavior/error-path change). Point them out and let the user opt in.
  • When replacing a bufio.Scanner loop with strings.Lines/bytes.Lines, remember the yielded line keeps its trailing \n; add a TrimSuffix if the old code relied on Scanner.Text() semantics.
  • Do not apply strings.SplitSeq or bytes.SplitSeq when the loop body references the index or the full slice elsewhere.
  • Do not apply strings.Builder if the concatenation happens outside a loop (single += is fine).
  • When a transformation requires a new import, ensure the import is added to the file.
  • After all edits, run goimports -w on each modified file to clean up imports.
  • If goimports is not available, fall back to gofmt -w.
  • If the project has no go.mod, ask the user for the target Go version before proceeding.

Automated tooling (Go 1.27+)

Many of these transformations are now shipped as official modernizers in gopls/go fix. On Go 1.27+ the whole set can be applied across a module with:

go fix ./...

gopls v0.22.0 added four notable passes covered above:

ModernizerMin GoTransformation
unsafefuncs1.17uintptr pointer math → unsafe.Add / unsafe.Slice
atomictypes1.19primitive atomic.* funcs → typed atomic.Int32/Pointer[T] wrappers
slicesbackward1.23descending-index loops → slices.Backward iterator
embedlit1.27redundant embedded-field literals → promoted-field init

Other modernizers in the same suite that this catalog covers: minmax, efaceany, fmtappendf, stringscut, stringsseq, sortslice/slicescontains, mapsloop, stditerators, forvar, rangeint, testingcontext, bloop, waitgroup, newexpr, errorsastype, appendclipped (→ slices.Concat), and plusbuild (→ drop obsolete // +build).

To disable an over-eager pass (e.g. slicesbackward rewriting loops that mutate the slice), scope the run with -fixes or exclude that analyzer in your editor's gopls settings.

Implementation Notes

After completing implementation and review/fix for an Issue, capture a running implementation notes file that documents how the implementation diverges from or interprets the spec.

Triggers

Use when:

  • After /goal implementation and /review-it are both complete
  • User says "记录笔记", "implementation notes", "note-it", "/note-it"
  • Before /ship-it (as a final checkpoint)
  • Any time the user wants to capture design rationale

The Job

  1. Determine the Issue number from context (branch name, /goal target, or user input)
  2. Review the implementation against the Issue spec / PRD
  3. Generate an HTML notes file at docs/issue#XXXX.html
  4. Present a summary to the user

Notes Structure

The HTML file must cover these four categories. If a category has nothing to report, write "None" with a brief explanation.

1. Design Decisions

Choices made where the spec was ambiguous or silent:

  • What was the ambiguity?
  • What choice did you make?
  • What was the rationale?

2. Deviations

Places where you intentionally departed from the spec:

  • What did the spec say?
  • What did you implement instead?
  • Why was the deviation necessary or better?

3. Tradeoffs

Alternatives you considered and why you picked what you did:

  • What were the viable alternatives?
  • What were the pros/cons of each?
  • Why did the chosen approach win?

4. Open Questions

Anything you'd want confirmed or revised:

  • What assumption are you unsure about?
  • What should the user verify?
  • What might need follow-up?

Output

  • Format: HTML
  • Location: docs/
  • Filename: issue#XXXX.html (where XXXX is the zero-padded Issue number, e.g., issue#0042.html)

HTML Template

Use this exact HTML structure:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Implementation Notes — Issue #XXXX</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
      background: #FAF9F6;
      color: #1a1a1a;
      padding: 2.5rem 2rem;
      line-height: 1.7;
    }
    .container { max-width: 800px; margin: 0 auto; }
    h1 { font-size: 1.375rem; font-weight: 700; margin-bottom: 0.25rem; }
    .meta { color: #8B8680; font-size: 0.8125rem; margin-bottom: 2rem; }
    h2 {
      font-size: 1rem;
      font-weight: 600;
      margin-top: 2rem;
      margin-bottom: 0.75rem;
      padding-bottom: 0.375rem;
      border-bottom: 1px solid #E8E4DE;
      display: flex; align-items: center; gap: 0.5rem;
    }
    .dot {
      width: 8px; height: 8px; border-radius: 50%; display: inline-block;
    }
    .dot.design { background: #5B8A72; }
    .dot.deviation { background: #D97757; }
    .dot.tradeoff { background: #4A6FA5; }
    .dot.question { background: #D4A843; }
    .item {
      background: #FFFFFF;
      border: 1px solid #E8E4DE;
      border-radius: 8px;
      padding: 1rem 1.25rem;
      margin-bottom: 0.75rem;
      box-shadow: 0 1px 3px rgba(0,0,0,0.03);
    }
    .item h3 { font-size: 0.875rem; font-weight: 600; margin-bottom: 0.375rem; }
    .item p { font-size: 0.8125rem; color: #4A4540; margin-bottom: 0.375rem; }
    .label {
      display: inline-block;
      font-size: 0.6875rem;
      font-weight: 500;
      padding: 0.125rem 0.5rem;
      border-radius: 4px;
      margin-right: 0.375rem;
    }
    .label-design { background: #F5F8F6; color: #5B8A72; border: 1px solid #5B8A72; }
    .label-deviation { background: #FFF5F0; color: #D97757; border: 1px solid #D97757; }
    .label-tradeoff { background: #F0F4F8; color: #4A6FA5; border: 1px solid #4A6FA5; }
    .label-question { background: #FDF8F0; color: #D4A843; border: 1px solid #D4A843; }
    .none { color: #B0AAA4; font-style: italic; font-size: 0.8125rem; }
    .footer {
      text-align: center; margin-top: 2.5rem; color: #B0AAA4;
      font-size: 0.6875rem;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Implementation Notes</h1>
    <p class="meta">Issue <a href="{{ISSUE_URL}}">#{{ISSUE_NUMBER}}</a> &mdash; {{ISSUE_TITLE}} &mdash; {{DATE}}</p>

    <h2><span class="dot design"></span> Design Decisions</h2>
    <!-- One .item per decision, or .none if none -->

    <h2><span class="dot deviation"></span> Deviations</h2>
    <!-- One .item per deviation, or .none if none -->

    <h2><span class="dot tradeoff"></span> Tradeoffs</h2>
    <!-- One .item per tradeoff, or .none if none -->

    <h2><span class="dot question"></span> Open Questions</h2>
    <!-- One .item per question, or .none if none -->

    <p class="footer">Generated by goal-workflow /note-it</p>
  </div>
</body>
</html>

Example Item

<div class="item">
  <h3><span class="label label-design">Decision</span> Used interface-based polymorphism instead of switch</h3>
  <p><strong>Ambiguity:</strong> The spec said "handle different types" without specifying how.</p>
  <p><strong>Choice:</strong> Defined a <code>Handler</code> interface with per-type implementations.</p>
  <p><strong>Rationale:</strong> Adding new types requires no changes to existing code (Open/Closed Principle). A switch would grow unboundedly.</p>
</div>

How to Determine the Issue Number

  1. If the user provides it directly (e.g., /note-it #42), use it
  2. If on a branch named feat/issue-42-* or fix/issue-42-*, extract 42
  3. If the last /goal target was #42, use 42
  4. Otherwise, ask the user: "Which Issue number should I use for the notes file?"

Edge Cases

ScenarioHandling
No Issue number foundAsk the user to specify
docs/ directory does not existAuto-create it
Notes file already exists for this IssueAsk: "Update existing notes or overwrite?" — default to update (append new items)
No deviations or open questionsWrite "None — implementation followed the spec as written."
Spec/PRD file not foundNote in Open Questions: "No PRD found at tasks/prd-*.md — verify against original requirements."

Checklist

Before saving:

  • Issue number identified
  • All four categories reviewed (even if some are "None")
  • Design decisions explain rationale, not just what was done
  • Deviations clearly contrast spec vs implementation
  • Tradeoffs mention specific alternatives considered
  • Open questions are actionable (user can answer yes/no or give direction)
  • HTML is well-formed and renders correctly

prd-to-spec — PRD to Technical Specification

Transform a Product Requirements Document (PRD) into a detailed technical SPEC that an engineer or AI agent can implement against. The PRD says what to build; the SPEC says how to build it.


When to Use

  • A /prd has been generated and you need to bridge the gap to implementation
  • You want architecture decisions documented before coding starts
  • Multiple developers/agents will implement the feature and need a shared contract
  • You need to validate technical feasibility before committing to a PRD
  • You want to catch design issues early — before code is written

The Job

  1. Locate PRD — find or receive the PRD document
  2. Analyze context (optional) — if a codebase exists, scan it to understand current architecture, patterns, and constraints
  3. Ask clarifying questions — resolve technical ambiguities (max 3-5 questions)
  4. Generate SPEC — produce a structured technical specification
  5. Review — present to user for feedback and iteration
  6. Save — write final SPEC to agreed location

Step 1: Locate PRD

Find the input PRD in one of these ways:

Provide the PRD to convert:

A. File path (e.g., tasks/prd-priority-system.md)
B. GitHub Issue URL
C. Paste PRD content directly
D. Auto-detect: scan tasks/ directory for recent PRDs

If auto-detecting, list available PRDs and let the user choose:

Found PRDs in tasks/:
  1. tasks/prd-priority-system.md (2024-03-15)
  2. tasks/prd-user-auth.md (2024-03-10)

Which PRD should I convert? [1/2]

Step 2: Analyze Context (Optional)

Skip this step if no codebase exists yet (greenfield project). In that case, the SPEC will propose architecture from scratch based on the PRD requirements and clarifying questions.

If a codebase exists, scan it to understand:

  • Existing architecture — how the current system is structured
  • Tech stack — languages, frameworks, libraries already in use
  • Patterns — naming conventions, file organization, error handling approach
  • Database — current schema, migration tool, ORM
  • API style — REST/GraphQL/gRPC, authentication method, response format
  • Testing — test framework, coverage patterns, test utilities

This ensures the SPEC aligns with the existing system rather than proposing incompatible solutions.


Step 3: Clarifying Questions

Ask only when the PRD leaves technical decisions ambiguous. Focus on:

  • Architecture choices — where does this feature live? New service or extend existing?
  • Data storage — new table? Extend existing? Cache strategy?
  • API design — new endpoints? Extend existing? Breaking changes?
  • Dependencies — any new libraries needed? Version constraints?
  • Performance — expected load? Latency requirements? Batch size limits?

Format:

Technical questions before I generate the SPEC:

1. Where should the priority logic live?
   A. Extend existing TaskService
   B. New PriorityService
   C. Inline in controller
   D. Let me decide based on the codebase

2. Database migration approach?
   A. Add column to existing tasks table
   B. New priority table with FK
   C. JSON field on tasks
   D. Let me decide based on current schema

3. API versioning concern?
   A. Add to existing v1 endpoints
   B. New v2 endpoints
   C. No versioning needed

If user selects "let me decide" options, make the best choice based on codebase analysis and document the rationale in the SPEC.


Step 4: SPEC Document Structure

# SPEC: [Feature Name]

> Technical specification derived from: [PRD filename/link]
> Generated: [date] | Target branch: [branch] | Commit: [short-hash]

## 1. Summary

### 1.1 What This SPEC Covers
[One paragraph: what feature this specifies and the scope of implementation]

### 1.2 PRD Reference
- Source: [path or URL to PRD]
- User Stories covered: [US-001, US-002, ...]
- Functional Requirements covered: [FR-1, FR-2, ...]

### 1.3 Design Decisions Summary
| Decision | Choice | Rationale |
|----------|--------|-----------|
| ... | ... | ... |

---

## 2. Architecture

### 2.1 System Context
[Where this feature fits in the overall system — diagram or description]

### 2.2 Component Design
[New components/modules introduced, their responsibilities, and boundaries]

### 2.3 Module Interactions
[How new components interact with existing ones — sequence or data flow]

### 2.4 File Structure
[New files to create and existing files to modify]

src/ ├── services/ │ └── priority.service.ts [NEW] ├── controllers/ │ └── task.controller.ts [MODIFY: add priority endpoints] ├── models/ │ └── priority.model.ts [NEW] └── migrations/ └── 20240315_add_priority.ts [NEW]


---

## 3. Data Model

### 3.1 Schema Changes
[New tables, columns, indexes — with SQL or ORM notation]

### 3.2 Entity Definitions
[TypeScript interfaces / Go structs / Python dataclasses for new entities]

### 3.3 Relationships
[How new entities relate to existing ones — FK, embedded, reference]

### 3.4 Migration Plan
[Migration steps, backward compatibility, rollback strategy]

---

## 4. API Design

### 4.1 Endpoints

| Method | Path | Description | Auth | Request | Response |
|--------|------|-------------|------|---------|----------|
| ... | ... | ... | ... | ... | ... |

### 4.2 Request/Response Schemas
[Detailed shapes with field types, validation rules, and examples]

### 4.3 Error Responses
[Error codes, messages, and HTTP status codes for each failure mode]

### 4.4 Breaking Changes
[Any backward-incompatible changes and migration path for consumers]

---

## 5. Business Logic

### 5.1 Core Algorithms
[Step-by-step logic for key operations — pseudocode or structured description]

### 5.2 Validation Rules
[Input validation, business rule validation, with specific constraints]

### 5.3 State Machine
[If applicable: states, transitions, guards, and side effects]

### 5.4 Edge Cases
[Known edge cases and how they should be handled]

---

## 6. Error Handling

### 6.1 Error Taxonomy
| Error Code | HTTP Status | Condition | User Message |
|------------|-------------|-----------|--------------|
| ... | ... | ... | ... |

### 6.2 Retry Strategy
[Which operations are retryable, backoff policy, max attempts]

### 6.3 Failure Modes
[What happens when dependencies fail — graceful degradation plan]

---

## 7. Security

### 7.1 Authentication & Authorization
[Who can access what, permission model, role checks]

### 7.2 Input Validation
[Sanitization rules, injection prevention, size limits]

### 7.3 Data Protection
[Sensitive fields, encryption at rest/transit, audit logging]

---

## 8. Performance

### 8.1 Expected Load
[Estimated QPS, data volume, growth projection]

### 8.2 Optimization Strategy
[Caching, pagination, lazy loading, batch processing]

### 8.3 Database Considerations
[Index strategy, query patterns, N+1 prevention]

---

## 9. Testing Strategy

### 9.1 Unit Tests
[What to test, test boundaries, mock strategy]

### 9.2 Integration Tests
[API tests, database tests, service interaction tests]

### 9.3 Edge Case Tests
[Specific scenarios to cover based on Section 5.4]

### 9.4 Acceptance Criteria Mapping
| US/FR | Test | Type | Description |
|-------|------|------|-------------|
| US-001 | ... | unit | ... |
| FR-2 | ... | integration | ... |

---

## 10. Implementation Plan

### 10.1 Phases
[Order of implementation — what to build first, dependencies between steps]

### 10.2 Issue Mapping
[Map SPEC sections to PRD Issues for implementation tracking]

| Issue | SPEC Sections | Priority | Depends On |
|-------|--------------|----------|------------|
| #1 | 3.1, 3.4 | high | — |
| #2 | 4.1, 4.2, 5.1 | high | #1 |
| ... | ... | ... | ... |

### 10.3 Incremental Delivery
[How to ship incrementally — feature flags, dark launches, gradual rollout]

---

## 11. Open Questions & Risks

### 11.1 Unresolved Questions
- [Questions that need product/engineering input before implementation]

### 11.2 Technical Risks
| Risk | Impact | Mitigation |
|------|--------|-----------|
| ... | ... | ... |

### 11.3 Assumptions
- [Technical assumptions made during SPEC creation — validate before implementing]

Step 5: Review & Iteration

After generating the SPEC, present it and ask:

SPEC generated from PRD. Please review:

- Are the architecture choices appropriate?
- Are there missing edge cases or error scenarios?
- Is the API design consistent with existing patterns?
- Should any section have more/less detail?

Reply OK to save, or provide feedback for iteration.

Step 6: Save

Ask user for save location:

Where should I save the SPEC?

A. tasks/spec-[feature-name].md (alongside PRD, recommended)
B. docs/spec-[feature-name].md
C. Custom path: [specify]

Mapping Strategy: PRD → SPEC

How PRD elements translate to SPEC sections:

PRD SectionSPEC Section(s)Transformation
User Stories5. Business Logic, 9.4 Acceptance MappingStories → algorithms + test cases
Functional Requirements4. API Design, 5. Business LogicFRs → endpoints + logic
Acceptance Criteria9. Testing StrategyCriteria → specific test scenarios
Non-Goals11.1 Open QuestionsClarify what's explicitly excluded
Technical Considerations2. Architecture, 8. PerformanceConstraints → design decisions
Success Metrics8.1 Expected Load, 10.3 DeliveryMetrics → monitoring + rollout plan

Quality Criteria

A good SPEC should pass these checks:

  • Every PRD User Story has corresponding SPEC sections
  • Every Functional Requirement maps to an API endpoint or business logic rule
  • Every Acceptance Criterion maps to at least one test case
  • Architecture choices are justified with rationale
  • API schemas are specific enough to generate client code
  • Error handling covers all identified failure modes
  • Implementation order respects dependencies
  • No "TBD" or "TODO" items — resolve or move to Open Questions

Edge Cases & Fallback

ScenarioHandling
PRD is vague or incompleteGenerate SPEC with best-effort choices, mark assumptions in Section 11.3
PRD conflicts with existing codeFlag conflicts explicitly, propose resolution in Section 11.1
Feature is too large for one SPECSplit into multiple SPECs (one per service boundary), link them
No existing codebase (greenfield)Skip Step 2, propose architecture from scratch based on PRD + clarifying questions
PRD has no User Stories (just bullet points)Infer structure, map bullets to SPEC sections, note in Summary
User wants SPEC without reading codebaseSkip Step 2, note that assumptions about existing code are unverified
Multiple PRDs need one SPECMerge PRD inputs, deduplicate requirements, note source for each

Anti-Patterns to Avoid

  • Don't restate the PRD. The SPEC adds technical depth, not a copy of requirements in different words.
  • Don't over-specify trivial operations. CRUD with no special logic doesn't need a full algorithm section.
  • Don't pick technologies without context. Always check what the project already uses before suggesting new tools.
  • Don't design in isolation. The SPEC must fit the existing system — same patterns, same conventions, same style.
  • Don't leave decisions implicit. If you made a choice (e.g., "add column to existing table"), state it and say why.
  • Don't write implementation code. The SPEC describes contracts and behavior, not code. Pseudocode is acceptable for complex algorithms.

Relationship to Other Skills

/prd  →  /prd-to-spec  →  /goal  →  /review-it  →  /ship-it
 │              │              │
 │  Requirements │  Technical   │  Implementation
 │  (what)       │  (how)       │  (code)
  • /prd produces the PRD (input to this skill)
  • /prd-to-spec produces the SPEC (this skill)
  • /goal implements Issues with SPEC as the technical reference
  • /code-to-spec reverse-engineers SPEC from existing code (complementary — forward vs. reverse)

PRD Generator

Create detailed Product Requirements Documents that are clear, actionable, and suitable for implementation. After PRD is confirmed, use /to-issues to decompose it into Issues, and optionally /prd-to-spec for technical design before that.


The Job

  1. Receive a feature description from the user
  2. Ask clarifying questions to cover key ambiguities — scale the count to complexity, not a fixed number (see Step 1)
  3. Generate a structured PRD based on answers
  4. Present PRD to user for review — ask "Please review the PRD. Let me know if any adjustments are needed, or reply OK to confirm."
  5. Apply any adjustments, then save to tasks/prd-[feature-name].md
  6. Suggest next steps (see Step 3)

Important: Do NOT start implementing. Just create the PRD.


Step 1: Clarifying Questions

Ask only critical questions where the initial prompt is ambiguous. Scale the number of questions to the feature's complexity — the goal is covering key ambiguities, not hitting a fixed count:

  • Simple, well-scoped feature: 2-3 questions
  • Typical feature: 3-5 questions
  • Complex feature (multiple user roles, cross-system integration, significant ambiguity): 6-8 questions

If a dimension is already unambiguous from the user's input, skip it — don't ask filler questions just to reach a number. Focus on:

  • Problem/Goal: What problem does this solve?
  • Core Functionality: What are the key actions?
  • Scope/Boundaries: What should it NOT do?
  • Success Criteria: How do we know it's done?

Format Questions Like This:

1. What is the primary goal of this feature?
   A. Improve user onboarding experience
   B. Increase user retention
   C. Reduce support burden
   D. Other: [please specify]

2. Who is the target user?
   A. New users only
   B. Existing users only
   C. All users
   D. Admin users only

3. What is the scope?
   A. Minimal viable version
   B. Full-featured implementation
   C. Just the backend/API
   D. Just the UI

This lets users respond with "1A, 2C, 3B" for quick iteration. Remember to indent the options.


Edge Cases & Fallback

ScenarioHandling
User skips clarifying questions (e.g., replies "whatever", "just write it")Fill with reasonable defaults, mark with [Assumption] in PRD, prompt user to confirm during review
User input is too vague (e.g., "add a feature")Ask once for specifics; if still vague, infer from project context and mark assumptions
tasks/ directory does not existAuto-create tasks/ directory
feature-name is hard to extract from inputAsk the user directly: "Suggested PRD filename is prd-XXX.md, please confirm or modify"
User requests PRD changes after reviewApply changes and re-save without re-running the clarification flow
PRD content exceeds 500 linesSuggest the user consider splitting into multiple sub-feature PRDs
User declines to proceedJust save the PRD, user can run /to-issues later
Issue creation needed laterSuggest running /to-issues with the saved PRD file

Step 2: PRD Structure

Generate the PRD with these sections:

1. Introduction/Overview

Brief description of the feature and the problem it solves. Use plain language — avoid jargon or explain it. Assume the reader may be a junior developer or AI agent.

2. Goals

Specific, measurable objectives (bullet list).

3. User Stories

Each story needs:

  • Title: Short descriptive name
  • Description: "As a [user], I want [feature] so that [benefit]"
  • Acceptance Criteria: Verifiable checklist of what "done" means

Numbering rule: US-001, US-002, US-003... (three digits, starting from 001). Each US should be independently implementable and small enough to complete within one focused agent session.

Mandatory E2E test story: Every PRD MUST include one end-to-end (E2E) test user story as the last user story. It validates the complete feature flow across the whole stack — from user action through UI, API, and data layer — not an isolated unit. Its acceptance criteria describe the full happy-path journey a real user takes to accomplish the feature's core goal, plus at least one critical edge/failure path, all asserted through an automated E2E test (e.g., Playwright/Cypress for UI, or an API-level integration test for backend-only features). This story depends on all others and confirms the feature works as a whole.

Acceptance criteria self-check template: Each criterion must satisfy at least one of the following, otherwise it is considered "vague" and must be rewritten:

  • Observable: describes a specific UI state or API response (e.g., "button shows confirmation dialog")
  • Testable: has clear input/output pairs (e.g., "entering an empty email shows a red warning")
  • Verifiable: can be checked by tools (e.g., "Typecheck/lint passes")
  • ❌ Bad example: "works correctly", "good user experience", "excellent performance" → these are unverifiable

Format:

### US-001: [Title]
**Description:** As a [user], I want [feature] so that [benefit].

**Acceptance Criteria:**
- [ ] Specific verifiable criterion
- [ ] Another criterion
- [ ] Typecheck/lint passes
- [ ] **[UI stories only]** Verify in a browser (e.g., via the `run` skill)

E2E story format:

### US-NNN: End-to-end test of [feature] flow
**Description:** As a QA engineer, I want an automated end-to-end test covering the full [feature] journey so that we catch regressions across the entire stack.

**Acceptance Criteria:**
- [ ] Automated E2E test simulates the full happy path (user action → UI → API → data → visible result)
- [ ] Covers at least one critical edge/failure path (e.g., invalid input, empty state, permission denied)
- [ ] Test runs in CI and passes
- [ ] Test is independent and repeatable (sets up and tears down its own data)

Important:

  • Acceptance criteria must be verifiable, not vague. "Works correctly" is bad. "Button shows confirmation dialog before deleting" is good.
  • For any story with UI changes: Always include "Verify in a browser" as acceptance criteria (e.g., via the run skill). This ensures visual verification of frontend work.

4. Functional Requirements

Numbered list of specific functionalities:

  • "FR-1: The system must allow users to..."
  • "FR-2: When a user clicks X, the system must..."

FR specification: Each FR starts with FR-N: (N increments from 1), uses "system must / system shall" phrasing, and describes one specific behavior. Avoid combining multiple "and"-linked behaviors in a single FR.

5. Non-Goals (Out of Scope)

What this feature will NOT include. Critical for managing scope.

6. Design Considerations (Optional)

  • UI/UX requirements
  • Link to mockups if available
  • Relevant existing components to reuse

7. Technical Considerations (Optional)

  • Known constraints or dependencies
  • Integration points with existing systems
  • Performance requirements

8. Success Metrics

How will success be measured?

  • "Reduce time to complete X by 50%"
  • "Increase conversion rate by 10%"

9. Open Questions

Remaining questions or areas needing clarification.


Output

  • Format: Markdown (.md)
  • Location: tasks/
  • Filename: prd-[feature-name].md (kebab-case)

Step 3: Next Steps

After the PRD is saved, suggest the user:

✅ PRD saved to tasks/prd-[feature-name].md

Next steps:
  /prd-to-spec  →  Generate technical SPEC (optional — for complex features)
  /to-issues    →  Decompose into Issues and create tickets

Or go straight to implementation:
  /to-issues    →  Create Issues, then /goal to implement

If the user wants to proceed, invoke the corresponding skill.


Example PRD

# PRD: Task Priority System

## Introduction

Add priority levels to tasks so users can focus on what matters most. Tasks can be marked as high, medium, or low priority, with visual indicators and filtering to help users manage their workload effectively.

## Goals

- Allow assigning priority (high/medium/low) to any task
- Provide clear visual differentiation between priority levels
- Enable filtering and sorting by priority
- Default new tasks to medium priority

## User Stories

### US-001: Add priority field to database
**Description:** As a developer, I need to store task priority so it persists across sessions.

**Acceptance Criteria:**
- [ ] Add priority column to tasks table: 'high' | 'medium' | 'low' (default 'medium')
- [ ] Generate and run migration successfully
- [ ] Typecheck passes

### US-002: Display priority indicator on task cards
**Description:** As a user, I want to see task priority at a glance so I know what needs attention first.

**Acceptance Criteria:**
- [ ] Each task card shows colored priority badge (red=high, yellow=medium, gray=low)
- [ ] Priority visible without hovering or clicking
- [ ] Typecheck passes
- [ ] Verify in a browser (e.g., via the `run` skill)

### US-003: Add priority selector to task edit
**Description:** As a user, I want to change a task's priority when editing it.

**Acceptance Criteria:**
- [ ] Priority dropdown in task edit modal
- [ ] Shows current priority as selected
- [ ] Saves immediately on selection change
- [ ] Typecheck passes
- [ ] Verify in a browser (e.g., via the `run` skill)

### US-004: Filter tasks by priority
**Description:** As a user, I want to filter the task list to see only high-priority items when I'm focused.

**Acceptance Criteria:**
- [ ] Filter dropdown with options: All | High | Medium | Low
- [ ] Filter persists in URL params
- [ ] Empty state message when no tasks match filter
- [ ] Typecheck passes
- [ ] Verify in a browser (e.g., via the `run` skill)

### US-005: End-to-end test of task priority flow
**Description:** As a QA engineer, I want an automated end-to-end test covering the full priority journey so that we catch regressions across the entire stack.

**Acceptance Criteria:**
- [ ] E2E test creates a task, sets its priority via the edit modal, and asserts the badge color updates on the card
- [ ] Test applies a priority filter and asserts only matching tasks remain visible
- [ ] Covers edge case: filtering to a priority with no tasks shows the empty state message
- [ ] Test runs in CI and passes
- [ ] Test sets up and tears down its own task data

## Functional Requirements

- FR-1: Add `priority` field to tasks table ('high' | 'medium' | 'low', default 'medium')
- FR-2: Display colored priority badge on each task card
- FR-3: Include priority selector in task edit modal
- FR-4: Add priority filter dropdown to task list header
- FR-5: Sort by priority within each status column (high to medium to low)

## Non-Goals

- No priority-based notifications or reminders
- No automatic priority assignment based on due date
- No priority inheritance for subtasks

## Technical Considerations

- Reuse existing badge component with color variants
- Filter state managed via URL search params
- Priority stored in database, not computed

## Success Metrics

- Users can change priority in under 2 clicks
- High-priority tasks immediately visible at top of lists
- No regression in task list performance

## Open Questions

- Should priority affect task ordering within a column?
- Should we add keyboard shortcuts for priority changes?

Checklist

Before saving the PRD:

  • Asked clarifying questions with lettered options
  • Incorporated user's answers
  • User stories are small and specific
  • Included a mandatory end-to-end (E2E) test story as the last user story
  • Functional requirements are numbered and unambiguous
  • Non-goals section defines clear boundaries
  • Saved to tasks/prd-[feature-name].md
  • Suggested next steps: /prd-to-spec (optional) and /to-issues

Refactor — Expert Code Restructuring

Surgical code refactoring based on Martin Fowler's (2nd Edition) catalog. Improve structure, readability, and maintainability without changing external behavior. Gradual evolution, not revolution.


When to Use

This skill activates when:

  • Code is hard to understand or maintain
  • Functions/classes have grown too large
  • Code smells are detected
  • Adding features is difficult due to poor structure
  • User explicitly requests refactoring, cleanup, or improvement
  • User says: refactor, 重构, clean up, improve code, code smell, extract method, rename, simplify

The Golden Rules

These five rules are non-negotiable. Violating any of them turns refactoring into reckless editing.

1. Behavior is Preserved

Only how the code works changes, never what it does. If tests existed before, they must pass after. If the refactoring introduces a behavioral change, it's not refactoring — it's rewriting.

2. Small Steps

Each change should be the smallest possible transformation that compiles and passes tests. If a step breaks, you know exactly which change caused it. Refactoring is a series of tiny, safe transformations, not one big rewrite.

3. Version Control is Your Friend

Commit before starting. Commit after each successful step. This gives you infinite undo. Branch from a clean state so you can abandon the refactoring without consequences.

4. Tests are Essential

"Without tests, you're not refactoring — you're just editing." If tests don't exist for the target code, write characterization tests first. These tests capture the current behavior so you can detect regressions.

5. One Thing at a Time

Never mix refactoring with feature changes. Never refactor two unrelated things simultaneously. Each commit should contain exactly one refactoring operation.


When NOT to Refactor

ScenarioAction
Code works and won't change againLeave it alone
Critical production path with no testsWrite characterization tests first
Under tight deadline pressureDocument the smell, refactor later
No clear purpose or benefitDon't refactor for refactoring's sake
Code is fundamentally wrongThis is a rewrite, not a refactoring

Refactoring Decision Rubric

Principles guide judgment; they are not independent reasons to rewrite code. Before choosing a Fowler technique, record one decision card:

FieldRequired answer
Primary smellOne root cause, not one entry per principle
EvidenceLocation, behavior, callers, change history, or measurement
Primary principleThe most specific applicable principle
Related principlesExplanatory labels only; do not count separately
Expected impactObservable reduction in change spread, cognitive load, duplicated knowledge, coupling, delayed failure, or measured runtime cost
Smallest refactoringThe least invasive Fowler technique that addresses the root cause
Baseline / success conditionHow behavior preservation and the expected benefit will be verified

Use these four decision lenses:

LensPrinciplesQuestions to answer
Responsibility and dependenciesSOLID, SRP, OCP, DIP, Separation of ConcernsAre reasons to change mixed? Does a real new variant repeatedly modify stable logic? Does high-level policy depend on concrete mechanism? Do concerns leak across a boundary?
Reuse and structureDRY, CompositionIs the same knowledge duplicated, or merely similar syntax? Would composition localize a real variation better than inheritance?
Simplicity and scopeKISS, YAGNIIs the proposed structure simpler for today's problem? Is every abstraction backed by an existing variation or boundary?
Runtime and feedbackFail Fast, Measure FirstCan invalid state fail nearer its source without changing error semantics? What baseline proves the problem and the result?

SOLID is an umbrella. When evidence supports SRP, OCP, or DIP, use that specific lens and do not create a second SOLID issue. LSP and ISP may be labeled SOLID/LSP and SOLID/ISP. DRY means shared knowledge, not all similar code. Composition is preferred when inheritance creates real coupling, not by default. OCP and DIP never justify speculative layers that violate KISS or YAGNI.

Numeric thresholds in this skill—line counts, parameter counts, method counts, and nesting depth—are context-dependent candidate indicators. Confirm mixed responsibilities, cognitive cost, repeated change, duplicated knowledge, or measured runtime impact before acting.


Code Smells Catalog

Based on Fowler's taxonomy. Before refactoring, identify which smell is present.

Bloaters

SmellDescriptionPrimary Refactoring
Long MethodCandidate: method > 10-15 lines; confirm mixed responsibilities or cognitive costExtract Method, Replace Temp with Query
Large ClassCandidate: many fields/methods; confirm independent reasons to changeExtract Class, Extract Subclass
Primitive ObsessionUsing primitives instead of small objectsReplace Data Value with Object, Replace Type Code with Class
Long Parameter ListCandidate: > 3-4 parameters; confirm a missing concept or recurring data clumpIntroduce Parameter Object, Preserve Whole Object
Data ClumpsSame group of data appearing togetherExtract Class, Introduce Parameter Object

Object-Orientation Abusers

SmellDescriptionPrimary Refactoring
Switch StatementsRepeated switch/if-else on type codesReplace Conditional with Polymorphism, Replace Type Code with Subclasses
Temporary FieldField only set in certain circumstancesExtract Class, Introduce Null Object
Refused BequestSubclass doesn't use inherited membersReplace Inheritance with Delegation, Push Down Method/Field
Alternative Classes with Different InterfacesClasses doing similar things with different namesRename Method, Move Method, Extract Superclass

Change Preventers

SmellDescriptionPrimary Refactoring
Divergent ChangeOne class changed for different reasonsExtract Class
Shotgun SurgeryOne change requires many small changes across classesMove Method, Move Field, Inline Class
Parallel Inheritance HierarchiesAdding a subclass to one hierarchy forces adding to anotherMove Method, Move Field

Dispensables

SmellDescriptionPrimary Refactoring
CommentsComments explaining what code does (not why)Extract Method, Rename Variable, Introduce Assertion
Duplicate CodeSame code structure in multiple placesExtract Method, Pull Up Method, Form Template Method
Lazy ClassClass doing too little to justify existenceInline Class, Collapse Hierarchy
Data ClassClass with only fields and getters/settersMove Method, Encapsulate Field, Encapsulate Collection
Dead CodeUnused code, imports, commented-out blocksDelete it (git history has it)
Speculative GeneralityCode built for "someday" that never cameInline Class, Collapse Hierarchy, Remove Parameter

Couplers

SmellDescriptionPrimary Refactoring
Feature EnvyMethod uses another class's data more than its ownMove Method, Extract Method + Move Method
Inappropriate IntimacyClasses know too much about each other's internalsMove Method, Move Field, Replace Delegation with Hidden Delegate
Message Chainsa.getB().getC().getD().doSomething()Hide Delegate, Extract Method
Middle ManClass delegates everything to another classRemove Middle Man, Inline Method
Incomplete Library ClassLibrary missing methods you needIntroduce Foreign Method, Introduce Local Extension

Refactoring Techniques Catalog

Organized by category, from Fowler's catalog. Each technique includes its mechanical steps.

Composing Methods

Extract Method

Turn a code fragment into a method whose name explains its purpose.

Mechanics:

  1. Create a new method named after what the fragment does (not how)
  2. Copy the extracted code into the new method
  3. Identify local variables: read-only become parameters, modified become return values
  4. Pass parameters and handle return values
  5. Replace the original fragment with a call to the new method
  6. Test

Before:

void printOwing() {
    printBanner();
    // Print details
    System.out.println("name: " + _name);
    System.out.println("amount: " + getOutstanding());
}

After:

void printOwing() {
    printBanner();
    printDetails(getOutstanding());
}

void printDetails(double outstanding) {
    System.out.println("name: " + _name);
    System.out.println("amount: " + outstanding);
}
Inline Method

Replace a method call with its body when the method body is as clear as the name.

Mechanics:

  1. Check the method is not polymorphic (no subclasses override it)
  2. Find all callers
  3. Replace each call with the method body
  4. Delete the method definition
  5. Test
Extract Variable

Put the result of an expression (or part of it) in a self-explanatory variable.

Before:

if (platform.toUpperCase().indexOf("MAC") > -1 &&
    browser.toUpperCase().indexOf("IE") > -1 &&
    wasInitialized() && resize > 0) {
    // ...
}

After:

final boolean isMacOs = platform.toUpperCase().indexOf("MAC") > -1;
final boolean isIEBrowser = browser.toUpperCase().indexOf("IE") > -1;
final boolean wasResized = resize > 0;
if (isMacOs && isIEBrowser && wasInitialized() && wasResized) {
    // ...
}
Inline Temp

Replace a temp variable with its expression when the temp is only used once and the expression is clear.

Replace Temp with Query

Extract the expression into a method. Temps that are computed once and reused are replaced with method calls.

Split Temporary Variable

A temp assigned more than once (not loop/collecting) should be split into separate variables, one per responsibility.

Remove Assignments to Parameters

Don't assign to parameters. Use a local variable instead.

Replace Method with Method Object

When a long method uses many local variables that make Extract Method hard, turn the method into its own class, with locals as fields.

Substitute Algorithm

Replace an algorithm with a clearer one.


Moving Features Between Objects

Move Method

Move a method to the class where it's used most.

Mechanics:

  1. Check all features used by the method on its current class
  2. Check for polymorphism (subclass/superclass methods)
  3. Create the method on the target class, adapting as needed
  4. Reference the target object from the source
  5. Turn the source method into a delegating method, or remove it
  6. Test
Move Field

Move a field to the class where it's used most.

Extract Class

When a class does the work of two, split it. Create a new class and move relevant fields and methods.

Inline Class

When a class does almost nothing, absorb it into the class that uses it most.

Hide Delegate

Create methods on the server to hide the delegate chain. manager = person.getDepartment().getManager() → manager = person.getManager().

Remove Middle Man

When a class is doing too much delegation, call the delegate directly.

Introduce Foreign Method

When a server class needs an additional method but you can't modify it, create a method on the client with the server instance as the first argument.

Introduce Local Extension

When you need multiple foreign methods, create an extension class (subclass or wrapper).


Organizing Data

Self Encapsulate Field

Access fields through getters and setters, even within the owning class.

Replace Data Value with Object

When a data item needs additional data or behavior, turn it into an object.

Before:

class Order {
    private String customer;  // Just a string
}

After:

class Order {
    private Customer customer;  // Rich object with name, address, credit rating
}
Change Value to Reference

When you need to share one instance of an object across multiple places.

Change Reference to Value

When a reference object is small, immutable, and you want value semantics.

Replace Array with Object

When an array holds heterogeneous data (String[] row = new String[3] — name, score, wins), replace with an object.

Duplicate Observed Data

Domain data lives in a GUI control but domain logic needs it. Copy the data into a domain object and set up an observer to keep the two in sync (Observer pattern). Separates presentation from domain so each can evolve independently.

Change Unidirectional Association to Bidirectional

Two classes need each other's features but only one holds a reference. Add a back-pointer and make the modifiers on both ends keep the link consistent. Add the reference only when genuinely needed — bidirectional links raise coupling and risk inconsistency.

Change Bidirectional Association to Unidirectional

A two-way link exists but one side no longer uses the other. Drop the unneeded direction. Reduces coupling, simplifies lifecycle management, and avoids "zombie" objects kept alive only by a stale back-pointer.

Replace Magic Number with Symbolic Constant

Replace literal numbers/strings with named constants.

Encapsulate Field

Make public fields private and provide accessors.

Encapsulate Collection

Never return the raw collection. Return a read-only view and provide add/remove methods.

Replace Type Code with Class

Replace a numeric/string type code with a class that has meaningful behavior.

Replace Type Code with Subclasses

When type code affects behavior, use polymorphism instead of conditionals.

Replace Type Code with State/Strategy

Similar to subclasses but uses composition when the type can change at runtime.

Replace Subclass with Fields

When subclasses vary only in constant data, replace them with fields on a single class.


Simplifying Conditional Expressions

Decompose Conditional

Extract the condition, then-part, and else-part into separate methods.

Before:

if (date.before(SUMMER_START) || date.after(SUMMER_END)) {
    charge = quantity * _winterRate + _winterServiceCharge;
} else {
    charge = quantity * _summerRate;
}

After:

if (isSummer(date)) {
    charge = summerCharge(quantity);
} else {
    charge = winterCharge(quantity);
}
Consolidate Conditional Expression

Combine multiple conditionals that have the same result.

Consolidate Duplicate Conditional Fragments

Move code that appears in every branch outside the conditional.

Remove Control Flag

Replace control flags with break, continue, or return.

Replace Nested Conditional with Guard Clauses

Use early returns for special cases instead of deep nesting.

Before (arrow code):

double getPayAmount() {
    double result;
    if (_isDead) {
        result = deadAmount();
    } else {
        if (_isSeparated) {
            result = separatedAmount();
        } else {
            if (_isRetired) {
                result = retiredAmount();
            } else {
                result = normalPayAmount();
            }
        }
    }
    return result;
}

After:

double getPayAmount() {
    if (_isDead) return deadAmount();
    if (_isSeparated) return separatedAmount();
    if (_isRetired) return retiredAmount();
    return normalPayAmount();
}
Replace Conditional with Polymorphism

When a conditional chooses different behavior based on the type of an object, use subclasses.

Introduce Null Object

Replace null checks with a null object that provides default behavior.

Introduce Assertion

State assumptions explicitly with assertions.


Making Method Calls Simpler

Rename Method

The name should say what the method does. If you can't think of a good name, the method may have multiple responsibilities.

Add Parameter / Remove Parameter

Add parameters when a method needs more info. Remove parameters when the method can get the info another way.

Separate Query from Modifier

A method should either return a value OR change state, never both.

Parameterize Method

Several methods doing similar things with different values → one method with a parameter.

Replace Parameter with Explicit Methods

The inverse: when a parameter essentially selects different behavior, create separate methods.

Preserve Whole Object

Pass the whole object instead of pulling individual fields from it.

Replace Parameter with Method

(refactoring.guru: Replace Parameter with Method Call) When a parameter can be computed from data the object already has, remove the parameter and let the method call the query itself.

Introduce Parameter Object

Group parameters that naturally go together into an object.

Remove Setting Method

Make a field immutable by removing its setter and setting it in the constructor.

Hide Method

Make methods private when they're not used outside the class.

Replace Constructor with Factory Method

When you need more flexibility than a simple constructor call.

Replace Error Code with Exception

Throw an exception instead of returning an error code.

Replace Exception with Test

Check the condition first instead of catching an exception.


Dealing with Generalization

Pull Up Field/Method/Constructor Body

Move identical fields/methods/constructor code from subclasses to superclass.

Push Down Method/Field

Move behavior from superclass to only the subclasses that use it.

Extract Subclass

Create a subclass for a subset of features used in some instances.

Extract Superclass

Create a superclass for shared features of similar classes.

Extract Interface

Create an interface from a subset of a class's public methods.

Collapse Hierarchy

Merge a superclass and subclass when they're not different enough.

Form Template Method

Generalize an algorithm in the superclass, letting subclasses fill in the specifics.

Replace Inheritance with Delegation

When a subclass only uses part of the superclass, use composition instead.

Replace Delegation with Inheritance

When a delegating class needs access to all of the delegate's behavior.


The Refactoring Process

Phase 1: Prepare

  1. Write characterization tests if they don't exist. These capture current behavior — they don't need to be elegant, just comprehensive enough to catch regressions.
  2. Record a baseline for the claimed problem: representative behavior, change spread, relevant callers, or a benchmark/profile/query count for performance work. Without a performance baseline, describe a performance idea as a candidate, not a measured improvement.
  3. Commit current state. Start from a clean working tree.
  4. Create a branch for the refactoring. Keep it separate from feature work.

Phase 2: Identify

  1. Smell the code. Use the smell catalog above to classify what's wrong, treating thresholds as candidate signals.
  2. Understand the code. Read it thoroughly, map relevant callers and dependencies, and identify the concrete failure or change scenario.
  3. Choose a primary principle. Attach related principles only as explanations; do not split one root cause into multiple findings.
  4. Check counter-pressures. Confirm that DRY will not create a false abstraction, that OCP/DIP are not speculative, that SRP will not create pass-through fragments, and that composition addresses real inheritance coupling.
  5. Choose the right refactoring. Pick the smallest technique from the catalog and define how the baseline and behavior will be checked.

Phase 3: Refactor (Small Steps)

For each step:

  1. Make one small change. Address one verifiable part of the primary smell; do not bundle unrelated principle cleanups.
  2. Compile. The code should compile after every change.
  3. Run tests. All tests must pass. If they don't, you've changed behavior.
  4. Check the seam. A new interface, adapter, or indirection must remove real caller complexity or support an existing variation; otherwise keep the simpler design.
  5. Commit. Create a commit with a message like refactor: extract validateEmail method.

Repeat until the smell is resolved.

Phase 4: Verify

  1. Behavior. All tests, type checks, compilation, and a manual smoke test pass.
  2. Structure. Compare dependency direction, relevant callers, duplicated knowledge, or change spread against the decision card.
  3. Fail fast semantics. If validation moved earlier, preserve error types/codes, aggregation, retry, transaction, and cleanup behavior.
  4. Performance. Re-run the same workload and environment when performance was part of the claim. Report the result and noise range; without a baseline, only report that no obvious regression was observed.
  5. Diff review. Check for unintended changes and confirm the success condition is met.

Phase 5: Clean Up

  1. Remove stale comments. If a refactoring made a comment obvious, delete the comment.
  2. Check for dead code. After refactorings, unused code may emerge.
  3. Remove speculative seams. Delete single-implementation interfaces, pass-through modules, or unused extension points that add no current leverage.
  4. Final commit. Summarize the refactoring sequence.

Refactoring Checklist

Code Quality

  • One primary smell/root cause is being addressed; related principles are not counted as separate work
  • Evidence, expected impact, baseline, and success condition are recorded
  • Functions are appropriately sized for their context (line counts are candidate signals, not limits)
  • Each function does one thing when that improves responsibility boundaries (SRP)
  • No duplicated knowledge (DRY), without merging independently changing code
  • Names describe what, not how
  • No magic numbers or strings
  • Dead code removed

Structure

  • Related code is grouped together and concerns do not leak across intended boundaries
  • Module boundaries are clear
  • Dependencies flow in one direction (no cycles); DIP abstractions correspond to real boundaries
  • OCP/DIP changes do not introduce speculative layers that violate KISS/YAGNI
  • Composition is preferred only where it reduces real inheritance coupling
  • No circular dependencies

Conditionals

  • Guard clauses replace deep nesting
  • Complex conditions extracted to named methods
  • Polymorphism replaces type-switching conditionals
  • Null Object pattern where appropriate

Type Safety (typed languages)

  • Types defined for all public APIs
  • No any usage without qualification
  • Nullable types explicitly marked
  • Type codes replaced with classes/enums

Testing

  • Refactored code is tested
  • Edge cases are covered
  • Invalid input/state fails near its source where appropriate (Fail Fast)
  • Error, retry, transaction, and cleanup semantics remain unchanged
  • All tests pass after each step
  • Characterization tests capture pre-refactoring behavior
  • Performance claims have comparable before/after measurements

Language-Specific Guidance

Java

  • Prefer final for locals that shouldn't change
  • Use IDE automated refactorings (Eclipse/IntelliJ) for mechanical steps
  • Leverage the type system: enums, records (Java 14+), sealed classes (Java 17+)

JavaScript/TypeScript

  • Use destructuring to reduce parameter count
  • Prefer const over let for immutable bindings
  • Use TypeScript union types instead of type codes
  • Nullish coalescing (??) and optional chaining (?.) eliminate null-check noise

Python

  • Use type hints for documenting intent during refactoring
  • Use dataclasses to replace tuple/data-class patterns
  • Use @property to replace getters
  • Context managers for resource cleanup patterns

Go

  • Small interfaces preferred: accept interfaces, return structs
  • Use named return values when they improve clarity
  • Table-driven tests pair well with refactoring
  • Avoid deep nesting with early returns

Rust

  • Use Result and Option instead of error codes and null
  • Pattern matching replaces if-else chains
  • From trait implementations clean up type conversions
  • Derive macros reduce boilerplate

Common Refactoring Sequences

Extract Method Sequence

  1. Create a new method named after intent
  2. Copy code fragment into new method
  3. Identify local variables → parameters / return values
  4. Call new method from original location
  5. Test

Replace Conditional with Polymorphism Sequence

  1. Create subclasses for each variant
  2. Create a factory method that returns the right subclass
  3. Move the conditional body to the appropriate subclass method
  4. Delete the conditional

Extract Class Sequence

  1. Identify a coherent subset of fields and methods
  2. Create a new class
  3. Create an instance from the old class
  4. Move fields and methods one at a time
  5. Update references in old class
  6. Test after each move

Inline Class Sequence

  1. Identify all callers of the target class
  2. Move all methods/fields to the absorbing class
  3. Redirect all references to the absorbing class
  4. Delete the empty class
  5. Test

Safety Protocol

Before You Touch Anything

1. Characterization tests  →  capture what the code does now
2. Git commit              →  save a known-good state
3. Branch                  →  isolate refactoring from other work

Every Single Step

1. One change              →  one refactoring technique
2. Compile                 →  must compile clean
3. Tests                   →  every test must pass
4. Commit                  →  message: "refactor: <technique> <what>"

If Tests Break

1. Undo the last change
2. Understand what broke and why
3. Try a smaller step
4. If the test was wrong and behavior was correct, fix the test FIRST, then retry

On Completion

1. Full test suite         →  all tests pass
2. Manual smoke test       →  quick sanity check
3. Self-review diff        →  catch unintended changes
4. Final commit            →  describe the overall transformation

Design Patterns in Refactoring

Strategy Pattern

Replace a conditional that chooses an algorithm. Smell: Switch on type code with different behavior per branch. Technique: Replace Conditional with Polymorphism + Extract Method.

Template Method

Extract common algorithm skeleton to superclass, letting subclasses fill in the variants. Smell: Duplicate code with slight variations. Technique: Form Template Method.

State Pattern

Replace a state-based conditional by extracting each state's behavior into a class. Smell: Switch on status field with behavior variation. Technique: Replace Type Code with State/Strategy.

Composite Pattern

Treat individual objects and groups uniformly. Smell: Client code has special handling for single vs. collection cases. Technique: Extract Interface + Create Composite.

Decorator Pattern

Add behavior dynamically by wrapping objects. Smell: Conditional logic for optional behaviors. Technique: Extract Class + use composition.

Null Object Pattern

Replace null checks with a default object. Smell: Repeated if (x == null) checks. Technique: Introduce Null Object.


Edge Cases & Gotchas

ScenarioHandling
No tests existWrite characterization tests first. Run the code with various inputs, capture outputs. These are your safety net.
Refactoring breaks a distant testFIRST understand why. Maybe the test relied on implementation detail. If so, fix the test to test behavior, not implementation. Then resume.
User wants behavior change + refactor togetherREFUSE. Do them separately. Refactor first to make the behavior change easy, commit, then change behavior.
Method is too complex to step throughUse Replace Method with Method Object. Turn the whole method into a class where each step can be extracted.
Refactoring across a large codebaseExtract a micro-service or module boundary first. Then refactor within the boundary. "There is a refactoring for everything except too many refactorings."
IDE automated refactoring availableUse it. Modern IDEs can safely rename, extract method, introduce variable, etc. Only do it manually when the IDE can't.
Undo neededgit stash or git reset --hard back to last commit. Small commits make this painless.

Resources

CC Review

Run automated code review as a closeout check before committing or shipping. Works across multiple AI coding agents.

Use when:

  • user asks for code review / review-it / autoreview
  • after non-trivial code edits, before final/commit/ship
  • reviewing a local branch or PR branch after fixes

Supported Agents

AgentReview CommandNotes
Claude Code/reviewBuilt-in, works on uncommitted changes or diff
Codexcodex reviewPass diff file or let it auto-detect
OpenCode/reviewSame as Claude Code
DeepSeek TUI/review or manual diff reviewPass diff content for analysis
Antigravity CLI/code-reviewBuilt-in slash command, auto-detects diff

Contract

  • Treat review output as advisory. Never blindly apply it.
  • Verify every finding by reading the real code path and adjacent files.
  • Read dependency docs/source/types when the finding depends on external behavior.
  • Reject unrealistic edge cases, speculative risks, broad rewrites, and fixes that over-complicate the codebase.
  • Prefer small fixes at the right ownership boundary; no refactor unless it clearly improves the bug class.
  • Keep going until review returns no accepted/actionable findings.
  • If a review-triggered fix changes code, rerun focused tests and rerun review.
  • Stop as soon as the review comes back clean with no actionable findings.
  • If rejecting a finding as intentional/not worth fixing, add a brief inline code comment only when it explains a real invariant or ownership decision that future reviewers should know.
  • Do not push just to review. Push only when the user requested push/ship/PR update.

Review Focus

请 review 当前 diff。不要只看语法和明显 bug,请重点检查以下维度,最后按严重程度排序:

  1. 隐藏副作用 (Hidden Side Effects) — 变更是否在非显而易见的地方产生级联影响?是否修改了共享状态、全局变量、或外部依赖的行为?
  2. 破坏兼容性 (Breaking Compatibility) — 是否改变了 API 签名、数据结构、配置文件格式、或命令行接口?现有调用方是否会受影响?
  3. 边界情况 (Edge Cases) — null/空值/空集合、极大/极小值、并发/竞态条件、异常路径是否被正确处理?
  4. 性能风险 (Performance Risks) — 是否引入了不必要的循环嵌套、N+1 查询、大对象分配、阻塞 I/O、或锁竞争?
  5. 安全风险 (Security Risks) — 是否存在注入、越权、敏感信息泄露、不安全的反序列化、或依赖版本漏洞?
  6. 命名误导 (Naming Misleading) — 变量/函数/类型名称是否与实际行为不一致?是否存在名不副实或语义模糊的命名?
  7. 测试不足 (Insufficient Testing) — 关键路径、边界条件、错误处理是否缺少测试覆盖?现有测试是否真正验证了期望行为?
  8. 未来维护成本 (Future Maintenance Cost) — 是否引入了不必要的抽象、重复代码、隐式耦合、或难以追踪的控制流?后来者是否容易理解和修改?

Pick Target

Claude Code / OpenCode / DeepSeek TUI

Dirty local work (default — /review works on uncommitted changes):

/review

Branch/PR work — review all changes against base:

First generate a diff, then review it:

git diff origin/main...HEAD > /tmp/review-it.diff

Then review the diff file with a focused prompt:

/review the changes in /tmp/review-it.diff against origin/main

If an open PR exists, use its actual base:

base=$(gh pr view --json baseRefName --jq .baseRefName)
git diff "origin/$base"...HEAD > /tmp/review-it.diff

Antigravity CLI (agy)

Dirty local work:

/code-review

Branch/PR work — review all changes against base:

git diff origin/main...HEAD > /tmp/review-it.diff

Then pass the diff to the review command:

/code-review the changes in /tmp/review-it.diff against origin/main

If an open PR exists, use its actual base:

base=$(gh pr view --json baseRefName --jq .baseRefName)
git diff "origin/$base"...HEAD > /tmp/review-it.diff

Codex

# Review uncommitted changes
codex review

# Review branch diff
git diff origin/main...HEAD > /tmp/review-it.diff
codex review /tmp/review-it.diff

Parallel Closeout

Format first if formatting can change line locations. Then it's OK to run tests and review in parallel:

scripts/review-it --parallel-tests "<focused test command>"

Tradeoff: tests may force code changes that stale the review. If tests or review lead to code edits, rerun the affected tests and rerun review until no accepted/actionable findings remain.

Uncommitted vs Branch Review

Choose the right mode:

  • Uncommitted changes (staged/unstaged): use /review directly (Antigravity: /code-review, Codex: codex review)
  • Committed, not pushed: use git diff origin/main...HEAD + review
  • Pushed/PR: same as committed, against the PR base
  • Clean working tree: skip review if there's truly nothing to review

Helper

Bundled helper script for parallel test + review orchestration:

~/.claude/skills/review-it/scripts/review-it --help

The helper:

  • Detects which agent is running (Claude Code, Antigravity CLI, Codex) via --agent auto
  • Detects whether to use uncommitted review or branch diff review
  • For branch mode: generates diff against origin/main (or PR base), then triggers review
  • Supports --parallel-tests for concurrent test + review execution
  • Supports --dry-run for checking what command would be used
  • Prints review-it clean: no accepted/actionable findings reported when review is clean

Final Report

Include:

  • review target (uncommitted / branch / PR base)
  • tests/proof run
  • findings accepted/rejected, briefly why
  • the clean review result, or why a remaining finding was consciously rejected

Do not run another review solely to improve the final report wording. If review exited clean with no actionable findings, report that as clean.

After-Goal: 代码提交、PR 合入、Issue 关闭工作流(GitHub)

完成 GitHub Issue 实现后的标准收尾流程:提交代码 → 推送分支 → 创建 PR → 合入 → 关闭 Issue。

前置条件

  • 当前 git 仓库有已实现的代码变更
  • 已知 Issue 编号(如 #42)
  • gh CLI 已登录(gh auth status 可验证)

工作流

Step 1: 提交代码

# 1a. 检查变更状态
git status
git diff --stat HEAD

# 1b. 暂存本次 Issue 相关的文件(不要 add 不相关的文件)
git add <files related to this issue>

# 1c. 提交,commit message 关联 Issue
git commit -m "$(cat <<'EOF'
{简要描述} (#issue-number)

{可选的详细说明}
EOF
)"

关键规则:

  • commit message 中包含 #issue-number 以关联 Issue
  • 只暂存当前 Issue 相关的文件,不要混入其他变更

Step 2: 推送分支

# 如果还在 main/master 上,先创建功能分支
git checkout -b {branch-name}  # 如已在功能分支则跳过

# 推送到远程
git push -u origin {branch-name}

分支命名建议:feat/issue-42-short-desc 或 fix/issue-42-short-desc

Step 3: 创建 PR

gh pr create \
  --title "{简要描述}" \
  --body "$(cat <<'EOF'
## Summary
- 实现内容概述

Closes #{issue-number}

## Test plan
- [ ] 测试项 1
- [ ] 测试项 2
EOF
)"

关键规则:

  • PR body 中写 Closes #N 或 Fixes #N,合入后 GitHub 自动关闭 Issue
  • title 简洁,不超过 70 字符

Step 4: 合入 PR

# 4a. 查看 PR 状态(确认 checks 通过)
gh pr checks

# 4b. 合入(默认 merge commit,可选 --squash 或 --rebase)
gh pr merge --squash --delete-branch

参数说明:

  • --squash: 压缩为单个 commit 合入(推荐)
  • --rebase: rebase 合入
  • --merge: 普通 merge commit
  • --delete-branch: 合入后删除远程分支

Step 5: 添加实现总结评论

PR 合入 / Issue 关闭时,始终在 Issue 上添加实现总结评论,方便后续直接从 Issue 回溯设计决策与代码变更。

参考 note-it 的四类结构组织总结内容:Design Decisions(设计决策)、Deviations(偏离)、Tradeoffs(权衡)、Open Questions(待确认)。某一类无内容时写 None 并简要说明。

gh issue comment {issue-number} --body "$(cat <<'EOF'
## 实现总结

**核心变更**
- {从 PR body Summary 提取的实现摘要,3-5 条 bullet}

**实现亮点(Highlights)**
- {值得强调的技术亮点:性能优化、优雅设计、复用抽象、关键测试覆盖等},或 None

**设计决策(Design Decisions)**
- {spec 模糊/未定处所做的选择及理由},或 None

**偏离(Deviations)**
- {有意偏离 spec 之处:spec 怎么说 → 实际怎么做 → 为什么},或 None

**权衡(Tradeoffs)**
- {考虑过的备选方案及最终选择的原因},或 None

**待确认(Open Questions)**
- {需用户确认的假设或后续跟进项},或 None

---
- **PR**: #{pr-number}
- **Commit**: {hash}
EOF
)"

关键规则:

  • 无论是 auto-close 还是手动 close,都必须添加此评论
  • 参考 note-it 的四类结构(设计决策 / 偏离 / 权衡 / 待确认);某类无内容写 None
  • 「实现亮点」提炼本次实现最值得关注的技术点(性能、设计、复用、测试等),无则写 None
  • 核心变更从 PR body 的 Summary 部分提取,保持简洁(3-5 条 bullet)
  • 附加 PR 编号和 commit hash,方便直接跳转
  • 若已通过 /note-it 生成 docs/issue#XXXX.html,可直接复用其四类内容,并在末尾附上该文件链接

Step 6: 手动关闭 Issue(仅当未自动关闭时)

如果 PR body 中已写 Closes #N,合入后 Issue 会自动关闭,跳过此步。否则手动关闭:

gh issue close {issue-number} --reason completed

错误处理

场景处理方式
gh pr checks 有失败项查看失败原因,修复后追加 commit 推送
PR 有 merge conflictgit fetch origin main && git rebase origin/main,解决冲突后 force push
gh pr merge 被 branch protection 阻止确认 required reviews 已满足,或请 reviewer approve
Issue 合入后未自动关闭确认 PR body 包含 Closes #N,或执行 Step 6 手动 gh issue close

完整示例

# 创建分支并提交
git checkout -b feat/issue-42-case-model
git add cases/case.go cases/case_test.go
git commit -m "$(cat <<'EOF'
Add Case data model and Markdown read/write (#42)

Define Case struct with YAML frontmatter + Markdown body
serialization. Provide WriteCase/ReadCase/ListCases/UpdateCase.
EOF
)"

# 推送
git push -u origin feat/issue-42-case-model

# 创建 PR
gh pr create \
  --title "Add Case data model and Markdown read/write" \
  --body "$(cat <<'EOF'
## Summary
- Define Case struct with YAML frontmatter + Markdown body
- Implement WriteCase/ReadCase/ListCases/UpdateCase functions
- Add comprehensive test coverage

Closes #42

## Test plan
- [x] Unit tests pass
- [x] go vet / lint clean
EOF
)"

# 确认 checks 通过后合入
gh pr checks
gh pr merge --squash --delete-branch

# 添加实现总结评论(参考 note-it 四类结构)
gh issue comment 42 --body "$(cat <<'EOF'
## 实现总结

**核心变更**
- Define Case struct with YAML frontmatter + Markdown body
- Implement WriteCase/ReadCase/ListCases/UpdateCase

**实现亮点(Highlights)**
- 单文件自包含存储,读写无需外部索引,测试覆盖率 100%

**设计决策(Design Decisions)**
- Markdown body 与 YAML frontmatter 分离存储,便于人工编辑与 diff

**偏离(Deviations)**
- None — 实现与 spec 一致

**权衡(Tradeoffs)**
- 选用 frontmatter 而非独立 JSON 元数据:单文件自包含,牺牲了少量解析性能

**待确认(Open Questions)**
- None

---
- **PR**: #43
- **Commit**: abc1234
EOF
)"

# 切回主分支
git checkout main
git pull

Smell — Architecture Bad Smell Detector

Analyze a codebase to find violations of software architecture principles, anti-patterns, code "bad smells," and algorithmic complexity hotspots. Produce a comprehensive, actionable markdown report.

Knowledge base: This skill encodes architectural patterns, anti-patterns, code smells, and algorithmic complexity heuristics drawn from industry research and practice, including the classic code smells catalog by Martin Fowler / Kent Beck (as organized on refactoring.guru: Bloaters, Object-Orientation Abusers, Change Preventers, Dispensables, Couplers).


The Job

  1. Understand the scope — ask what part of the project to analyze (full project, specific module, or recent changes)
  2. Scan the codebase using find, grep, and Agent (Explore subagent) to gather candidate signals and evidence
  3. Validate candidates against context, callers, history, workload, and measurements before confirming findings
  4. Generate a detailed markdown report saved to tasks/smell-report-[timestamp].md
  5. Present a summary of confirmed findings and separate candidates to the user

Step 1: Scope Clarification

Ask the user:

What scope should I analyze?
  A. Entire project (thorough, may take time)
  B. Specific module/directory: [please specify]
  C. Only recently changed files (git diff)
  D. Only architectural-level issues (skip low-level code smells)

If the user doesn't specify, default to option A for small projects (< 100 files) or C for large projects.


Step 2: Evidence Gathering

Use the Explore subagent (Agent with subagent_type: "Explore") to scan the codebase for architectural patterns and anti-patterns. Run multiple parallel explorations:

Exploration Commands

Run these in parallel to gather evidence efficiently:

  1. Project Structure Scan: Map the directory tree, identify the architectural style (layered, modular monolith, microservices, etc.)
  2. Dependency Analysis: Find import/include patterns, check for circular dependencies, identify coupling hotspots
  3. Module/Component Scan: Identify God Objects (files > 500 lines), check cohesion, check single responsibility violations
  4. Pattern Detection: Look for known anti-pattern signatures (static cling, service locator abuse, leaky abstractions)
  5. Testing Scan: Check test coverage patterns, test file locations, test-to-code ratios
  6. Naming & Clarity Scan: Flag misleading names, overly generic names (Manager, Helper, Util), inconsistent naming conventions
  7. Complexity Scan: Detect algorithmic complexity hotspots — nested loops, N+1 queries, repeated scans, sort-in-loop, expensive recomputation in render paths

Key Heuristics

Heuristics are candidate signals, not findings. A line-count, nesting, naming, or Big-O match must be validated against the code's responsibility, callers, change history, workload, and intentional constraints. Do not assign severity from a threshold alone.

CategorySmellDetection Heuristic
ArchitectureBig Ball of MudNo clear directory structure; everything in root or one flat folder; no separation of concerns
ArchitectureViolated Layer BoundariesInner layers importing outer layers; infrastructure code in domain/core layer
ArchitectureMissing ArchitectureNo src/, lib/, core/ separation; SQL inline with UI code; HTTP handlers mixed with business logic
ArchitectureDistributed MonolithMicroservices sharing a database; services that can't deploy independently
ArchitectureAnemic Domain ModelModel/entity classes with only getters/setters and no behavior; all logic in services
ArchitectureCQRS Without NeedSeparate read/write models for simple CRUD; unnecessary complexity
ArchitectureOver-Layered ArchitectureExcessive layers/tiers that add pass-through code with no real value
ArchitectureOver-AbstractionSo many indirections/interfaces/generics that you get lost following the code
ArchitectureFuturistic ArchitectureSpeculative flexibility for requirements that may never come (predicting the future)
ArchitectureTechnology-Enthusiast ArchitectureShiny/unproven tech adopted in production because it's new, not because it fits
ArchitectureOverkill ArchitectureHeavyweight architecture/tech thrown at a simple problem
ArchitectureCloud/Visio ArchitectureDiagrams disconnected from the actual code and runtime reality
CouplingCircular DependenciesModule A imports B, B imports A; detected via import graph analysis
CouplingContent CouplingOne module directly accesses another's internal/private members
CouplingCommon CouplingExcessive global variables/shared mutable state; singleton abuse
CouplingStamp CouplingPassing large data structures when only a few fields are needed
CohesionGod ObjectSingle class/module > 500 lines; > 20 public methods; handles unrelated concerns
CohesionShotgun SurgeryA single change requires touching 5+ files across unrelated modules
CohesionFeature EnvyMethod calls foreign class methods more than its own class methods
CohesionData ClumpsSame group of 3+ parameters appearing together in multiple method signatures
DesignLeaky AbstractionsImplementation details (DB queries, HTTP calls) exposed through interfaces
DesignStatic ClingExcessive use of static methods; static state that prevents testability
DesignService Locator AbuseDI container passed around instead of proper constructor injection
DesignViolated SOLIDSRP violations, OCP violations (switch/if-else chains on types), ISP violations (fat interfaces)
DesignSwitch StatementsSame switch/if-else chain on a type code appearing in multiple places; should be polymorphism
DesignRefused BequestSubclass inherits methods/fields it doesn't use or overrides them to throw/no-op
DesignAlternative Classes w/ Different InterfacesTwo classes do the same thing but have differently-named methods
DesignParallel Inheritance HierarchiesCreating a subclass in one hierarchy forces a matching subclass in another
DesignSpeculative GeneralityUnused abstract classes, hooks, params, or generics "for future needs" (YAGNI)
DesignIncomplete Library ClassWrapping/patching a third-party class because it lacks needed methods
CohesionDivergent ChangeOne module changed for many unrelated reasons (opposite of Shotgun Surgery)
CohesionData ClassClass with only fields + getters/setters, no behavior (anemic data bag)
CohesionLazy ClassClass/module that does too little to justify its existence
CouplingInappropriate IntimacyTwo classes access each other's private/internal parts too much
CouplingMessage ChainsLong call chains a.getB().getC().getD() (Law of Demeter violation)
CouplingMiddle ManClass that only delegates every call to another class
CodeTemporary FieldInstance field set/used only in certain circumstances, empty otherwise
CodeDuplicated CodeIdentical/similar logic appearing in 3+ places; copy-paste patterns
CodeLong MethodMethods > 50 lines; deep nesting (> 3 levels)
CodeLong Parameter ListMethods with > 4 parameters
CodePrimitive ObsessionUsing strings/ints instead of domain types (e.g., string email instead of Email type)
CodeMagic Numbers/StringsHardcoded literals without named constants
CodeComments as DeodorantExcessive comments explaining bad code instead of refactoring
CodeDead CodeUnused imports, unreachable code, commented-out blocks
TestingNo TestsModules with zero test coverage
TestingTest-Implementation CouplingTests that assert internal implementation details instead of behavior
TestingSlow TestsTests doing real I/O, database calls, network requests without mocking
NamingVague NamesManager, Handler, Processor, Helper, Util, Service, Data, Info used excessively without context
NamingInconsistent NamingSnake_case and camelCase mixed; different patterns for same concept
ReadabilityDeep Nesting (Arrow Anti-Pattern)Loops/conditionals nested > 3 levels deep; rightward-drifting "arrow" shape hard to trace
ComplexityNested Loops (O(n^2)+)Loop inside loop; forEach inside for; map inside map; nested iteration suggesting polynomial complexity
ComplexityRepeated Linear Scanincludes()/indexOf()/.find() inside a loop; O(n*m) membership check on list instead of Set/Map
ComplexitySort-in-Loop.sort() or sorted() called inside iterative code; repeated O(n log n) when sort-once suffices
ComplexityN+1 Query PatternDatabase/API/HTTP call inside a loop; fetch/query/execute/findMany per iteration instead of batch
ComplexityRender-Path Recompute.filter().map().sort() chains in component render body; expensive transforms without memoization
ComplexityPairwise ComparisonNested iteration comparing every element with every other; O(n^2) when sort+two-pointer would be O(n log n)
ComplexityUnnecessary RecomputeSame expensive computation repeated without caching; missing useMemo/memo/lazy eval
ComplexityWrong Data StructureArray used where Set/Map would give O(1) lookup; List where Queue/Heap/Stack is natural fit

Step 3: Report Generation

Finding Identity and Evidence

Process every candidate in three stages:

  1. Candidate detection: static patterns, file metrics, and dependency scans produce candidates only.
  2. Context validation: read the implementation and relevant callers; check change frequency, input size, runtime frequency, framework constraints, generated/vendor status, and existing mitigations.
  3. Finding confirmation: merge candidates with the same root cause, affected path, failure/change scenario, and remediation direction into one finding.

Count findings by independent root cause, never by the number of principles they implicate. Use one Primary principle and optional Related principles. SOLID is an umbrella label; use SRP, OCP, or DIP as the primary label when the evidence supports a specific lens, without also creating a separate SOLID finding.

Canonical 11-Principle Matrix

PrincipleConfirming evidenceCommon false positive / constraint
SOLIDA design problem spans multiple SOLID lenses or no narrower lens is reliableDo not duplicate a specific SRP/OCP/DIP finding
DRYThe same business rule or knowledge must change in multiple placesSimilar syntax that is expected to evolve independently
KISSExtra layers, indirection, or machinery add cost without observable leverageA small abstraction that removes real complexity
YAGNIUnused extension points, parameters, adapters, or speculative requirementsA tested seam required by an existing boundary or change
SRPMultiple independent reasons to change, supported by responsibilities or change historyFile size or method count alone
Open/Closed (OCP)Adding a known variant repeatedly modifies stable branching logicOne simple, local conditional
Dependency Inversion (DIP)High-level policy directly depends on concrete infrastructure, harming replacement or testingAdding an interface for a single stable implementation
CompositionInheritance causes unwanted coupling, refused behavior, or inseparable variation axesReplacing every valid inheritance relationship mechanically
Separation of ConcernsBusiness policy, I/O, presentation, or persistence concerns leak across boundariesA deliberately thin boundary adapter
Fail FastInvalid input, state, or dependency propagates until a distant operation failsIntentional aggregation, retry, or deferred validation semantics
Measure FirstA performance, scale, or optimization claim lacks a baseline or representative workloadStatic complexity reported as a measured bottleneck

For each confirmed finding, record evidence strength (Measured, Observed, or Inferred) separately from confidence (High, Medium, or Low/Candidate). Evidence strength does not imply severity.

Severity Rubric

  • Critical: correctness, reliability, security, data consistency, or measured system-level impact; normally requires high confidence.
  • Warning: clear reach or repeated change/runtime cost with a concrete maintenance or runtime consequence.
  • Suggestion: local, low-frequency, or limited-impact improvement with evidence.
  • Candidate requiring measurement: static signal with unknown impact; exclude it from severity totals and put it in a separate report section.

Generate the report in this structure:

# Architecture Smell Report

**Project:** [project-name]
**Scope:** [scope description]
**Date:** [date]
**Analyzer:** smell skill (Ducc)

---

## Executive Summary

[2-3 paragraph summary of confirmed findings only: architectural style detected, overall health assessment, and top 3-5 critical issues. Mention candidates separately.]

---

## Architectural Style Detected

[Identify the architectural style: Layered, Modular Monolith, Microservices, Hexagonal, Clean Architecture, or Big Ball of Mud]

### Style Expectations vs. Reality

| Expectation | Reality | Status |
|-------------|---------|--------|
| [e.g., Clear layer separation] | [what was found] | ✅/⚠️/🔴 |

---

## Findings by Category

### 🔴 Critical Issues (Must Fix)

[Issues that fundamentally undermine architecture]

### 🟡 Warnings (Should Fix)

[Issues that degrade maintainability but don't block function]

### 🔵 Suggestions (Nice to Fix)

[Minor improvements that would increase quality]

### Candidates Requiring Measurement

[Static candidates whose runtime impact, change frequency, or workload is not yet established. These do not count toward severity totals.]

---

## Detailed Findings

### Finding #1: [Title]

- **Category:** [Architecture/Coupling/Cohesion/Design/Code/Testing/Naming/Complexity]
- **Severity:** 🔴 Critical / 🟡 Warning / 🔵 Suggestion
- **Anti-Pattern:** [Name of anti-pattern]
- **Location:** [file:line references and relevant callers]
- **Confidence:** [High/Medium]
- **Evidence strength:** [Measured/Observed/Inferred]
- **Failure or change scenario:** [Concrete scenario]
- **Primary principle:** [Most specific principle]
- **Related principles:** [Explanatory only; do not count separately]
- **Description:** [What was found and why it's a problem]
- **Evidence:** [Code, dependency, history, or measurement]
- **Measured/observed impact:** [Reach, frequency, consequence, or baseline]
- **Recommendation:** [Smallest justified refactoring]
- **Verification:** [How to prove behavior and impact]

---

## Dependency Graph Analysis

[Summary of module dependencies, circular dependencies found, coupling hotspots]

---

## Module Health Scorecard

| Module | Lines | God Object Risk | Coupling | Cohesion | Test Coverage | Health |
|--------|-------|----------------|----------|----------|---------------|--------|
| [name] | [N] | [Low/Med/High] | [Low/Med/High] | [Low/Med/High] | [% or N/A] | 🟢/🟡/🔴 |

---

## Smell Distribution

Count only deduplicated confirmed findings by their primary category. Related principles and candidates do not affect these totals.

| Category | Count | Critical | Warning | Suggestion |
|----------|-------|----------|---------|------------|
| Architecture | [N] | [N] | [N] | [N] |
| Coupling | [N] | [N] | [N] | [N] |
| Cohesion | [N] | [N] | [N] | [N] |
| Design | [N] | [N] | [N] | [N] |
| Code | [N] | [N] | [N] | [N] |
| Testing | [N] | [N] | [N] | [N] |
| Naming | [N] | [N] | [N] | [N] |
| Complexity | [N] | [N] | [N] | [N] |

---

## Refactoring Roadmap

Order work by impact, confidence, dependency sequence, and verification cost—not by principle count or smell name. Put only high-confidence, verifiable findings in Immediate Actions; for candidates, recommend the next measurement instead of a rewrite.

### Immediate Actions (This Sprint)
1. [Actionable fix 1]
2. [Actionable fix 2]

### Short-Term (1-3 Months)
1. [Structural improvement 1]
2. [Structural improvement 2]

### Long-Term (3-12 Months)
1. [Architectural transformation 1]
2. [Architectural transformation 2]

---

## Appendix: Anti-Pattern Reference

[A condensed reference of anti-patterns checked, with brief descriptions]

Step 4: Save and Present

Save the report to tasks/smell-report-[YYYY-MM-DD-HHmm].md and present a brief summary to the user.


Anti-Pattern Knowledge Base

This section documents the architectural anti-patterns and bad smells the skill knows about.

Architectural Anti-Patterns

Big Ball of Mud

The most common de-facto architecture. A haphazardly structured, sprawling system with no perceivable architecture. Characterized by:

  • Promiscuous sharing of information between distant elements
  • Global or duplicated important state
  • Structure eroded beyond recognition or never defined
  • Repeated expedient repair ("duct tape and bailing wire")
  • Forces: Time pressure, cost, inexperience, complexity, change, scale
  • Remedy: Define architecture boundaries, refactor incrementally, apply SHEARING LAYERS, KEEP IT WORKING
Distributed Monolith

Microservices that must be deployed together. Symptoms:

  • Services share a database
  • Synchronous chains of service calls
  • Changes require coordinated deployments
  • Remedy: Decouple data stores, introduce async messaging, enforce bounded contexts
Anemic Domain Model

Domain objects with only getters/setters (data bags), all logic in services. Violates:

  • "Tell, Don't Ask" principle
  • Rich Domain Model pattern from DDD
  • Remedy: Move behavior into domain objects, use domain services only for cross-aggregate operations
God Object

A class that knows too much or does too much. Characteristics:

  • 500 lines or > 20 public methods

  • Handles unrelated concerns
  • Difficult to test in isolation
  • Single Responsibility Principle violation
  • Remedy: Extract cohesive groups of methods into dedicated classes
Leaky Abstractions

Abstractions that expose implementation details. Signs:

  • Interface methods named after implementation (e.g., SaveToPostgres, FetchFromRedis)
  • Consumers catching implementation-specific exceptions
  • Configuration details exposed through abstractions
  • Remedy: Design interfaces from the consumer's perspective, hide implementation details
Static Cling

Excessive use of static methods/state. Problems:

  • Untestable (can't mock static calls)
  • Hidden dependencies
  • Thread-safety issues with static state
  • Remedy: Use dependency injection, convert stateless statics to instance methods
Service Locator Abuse

Using a service locator instead of dependency injection. Issues:

  • Hidden dependencies (dependencies not visible in constructor)
  • Runtime errors instead of compile-time errors
  • Testing difficulty
  • Remedy: Use constructor injection, register dependencies at composition root
Violated Layer Boundaries (Clean/Onion/Hexagonal Architecture)

In layered architectures:

  • Clean Architecture: Outer layers (frameworks) leaking into inner layers (use cases, entities)
  • Onion Architecture: Infrastructure concerns in domain core
  • Hexagonal Architecture: Business logic coupled to specific adapters instead of ports
  • Remedy: Apply dependency inversion, define clear port interfaces
CQRS Overuse

Applying CQRS to simple CRUD. Signs:

  • Separate read/write models for trivial data access
  • Event sourcing when events don't add business value
  • Unnecessary complexity
  • Remedy: Use CQRS only when read/write models genuinely differ or have different scaling needs
Vertical Slice Contamination

In Vertical Slice Architecture:

  • Cross-slice coupling (one feature directly calling another)
  • Shared service classes undermining slice independence
  • Remedy: Use events/messages for cross-slice communication, duplicate simple logic if needed

Top Ten Software Architecture Mistakes

A set of architecture-level anti-patterns describing over- and under-engineering. The common thread: architecture disconnected from real needs and reality. The opposite extreme (too little architecture) is equally a smell.

Over-Layered / Multitier Architecture

"Layers on layers on layers." Adding tiers beyond what the problem needs:

  • Each layer just forwards calls to the next with no transformation or value
  • Simple read requires touching 6+ classes across 4 layers
  • Remedy: Collapse pass-through layers; keep only layers that carry real responsibility
Over-Abstraction

Abstraction piled on until the code is impossible to follow:

  • Excessive interfaces, generics, factories, and indirection for single implementations
  • You can't tell what actually runs without stepping through many hops
  • Remedy: Inline single-implementation abstractions; abstract only at real variation points (rule of three)
Futuristic Architecture

Solution built for imagined future requirements that no one can actually predict:

  • Extensibility points, plugin systems, config knobs nothing uses
  • Most speculative flexibility is wasted effort — closely related to Speculative Generality and YAGNI
  • Remedy: Build for today's known requirements; add flexibility when a real second case arrives
Technology-Enthusiast Architecture

New/shiny technology put into production because the architect liked it:

  • Unproven tech adopted without validating it fits the problem or scales
  • Chasing trends over stability
  • Remedy: Evaluate tech against actual requirements; prefer proven tools; prototype before committing
Overkill Architecture

A simple problem solved with a disproportionate amount of architecture and technology:

  • Microservices, event sourcing, k8s for a CRUD app with a handful of users
  • Remedy: Match architecture weight to problem size (KISS); start simple, evolve when justified
Cloud / Visio Architecture

"Architecture" that exists only in nice diagrams, disconnected from the code and runtime reality:

  • Diagrams don't match what's actually deployed; boxes and arrows with no code correspondence
  • Remedy: Keep architecture docs grounded in and verified against the real system

Note on the opposite extreme: total lack of architecture (no boundaries, no structure) is equally a smell — see Big Ball of Mud and Missing Architecture. Both under- and over-engineering are failures.

Coupling & Cohesion Smells

Circular Dependencies

Module A → Module B → Module A. Detected via:

  • Import graph analysis
  • "Cannot access before initialization" errors
  • Remedy: Extract shared interface/common module, apply dependency inversion
Content Coupling

One module directly modifying another's internal state. Signs:

  • Direct field access across module boundaries
  • friend/package-private abuse
  • Remedy: Use public APIs, encapsulate internal state
Common Coupling (Global State)

Multiple modules depending on shared global mutable state:

  • Global variables, singletons with mutable state
  • Ambient context (e.g., CurrentUser static property)
  • Remedy: Parameterize, use dependency injection, make state explicit
Stamp Coupling

Passing entire data structures when only a few fields needed:

  • Functions receiving large DTOs but using one field
  • Remedy: Create focused parameters or smaller interfaces (ISP)
Shotgun Surgery

A single change requires modifications across many files:

  • Adding a field touches 5+ files in different modules
  • Remedy: Consolidate related behavior, apply Single Responsibility
Feature Envy

A method that uses another class's methods more than its own:

  • Method calls other.foo(), other.bar(), other.baz() with few self-calls
  • Remedy: Move the method to the class it envies
Data Clumps

Same group of fields appearing together in multiple places:

  • (street, city, zip) appearing in 5 method signatures
  • Remedy: Extract into a value object
Divergent Change

One module/class is repeatedly changed for many unrelated reasons (the opposite of Shotgun Surgery):

  • "I always change these three methods for DB changes, and those two for UI changes" in the same class
  • Remedy: Split the class along its axes of change (Single Responsibility)
Inappropriate Intimacy

Two classes are too entangled with each other's internals:

  • Reaching into another class's private fields, tight bidirectional references
  • Remedy: Move methods/fields to the class they belong to, extract a shared class, or replace with delegation
Message Chains

Long navigation chains like a.getB().getC().getD().doThing():

  • Client coupled to the whole object graph; violates the Law of Demeter
  • Remedy: Hide delegation — add a method on the first object that returns what the client needs
Middle Man

A class that delegates almost all of its work to another class:

  • Most methods just forward calls; adds indirection without value
  • Remedy: Remove the middle man and let clients talk to the real object (inline the delegation)
Parallel Inheritance Hierarchies

Every time you add a subclass to one hierarchy, you must add one to another:

  • Shape/ShapeRenderer, Employee/EmployeePermission growing in lockstep
  • Remedy: Merge hierarchies or make one hierarchy reference the other instead of mirroring it

Code-Level Smells

Long Method
  • Methods > 50 lines (or whatever suits the language)
  • Deep nesting > 3 levels
  • Multiple levels of abstraction mixed
  • Remedy: Extract methods at same abstraction level, compose
Long Parameter List
  • Methods with > 4 parameters
  • Boolean flags controlling behavior
  • Remedy: Introduce parameter object, split method, remove flag arguments
Duplicated Code
  • Identical or near-identical logic in 3+ places
  • Copy-paste with slight variations
  • Remedy: Extract shared method, apply Template Method or Strategy pattern
Primitive Obsession

Using primitives instead of domain types:

  • string for Email, PhoneNumber, URL
  • int for Money, Age, Quantity
  • decimal without Currency context
  • Remedy: Create value objects with validation and behavior
Magic Numbers/Strings
  • Hardcoded literals without explanation
  • if (status == 3) instead of if (status == Status.COMPLETED)
  • Remedy: Extract named constants or enums
Comments as Deodorant
  • Comments that explain what code does (code should be self-documenting)
  • Commented-out code blocks
  • "TODO" comments accumulating without resolution
  • Remedy: Refactor to make code clear, delete dead code, track TODOs as issues
Deep Nesting (Arrow Anti-Pattern)

Loops and conditionals nested so deeply the code drifts rightward into an "arrow" shape:

  • if { if { for { if { ... } } } } — hard to trace which conditions hold at any point
  • Usually > 3 levels of indentation in one function
  • Remedy: Guard clauses / early returns, extract nested blocks into methods, invert conditions, replace conditional with polymorphism
Dead Code
  • Unused imports, variables, functions
  • Unreachable branches
  • Commented-out code in version control
  • Remedy: Delete it (git history preserves it if needed)
Data Class

A class that is only fields plus getters/setters, with no meaningful behavior:

  • A "data bag" other classes reach into and manipulate from outside
  • Closely related to Anemic Domain Model at the class level
  • Remedy: Move the behavior that operates on the data into the class ("Tell, Don't Ask")
Lazy Class

A class/module that no longer does enough to justify its existence:

  • Left over after refactoring, or an abstraction that never grew
  • Remedy: Inline it into its caller or collapse the hierarchy
Speculative Generality

Abstractions, hooks, parameters, or generics added for hypothetical future needs:

  • Unused abstract base classes, unused parameters, "just in case" configuration
  • Violates YAGNI
  • Remedy: Remove unused abstraction; add it when a real second use case appears
Temporary Field

An instance field that is only set/used in certain circumstances and empty otherwise:

  • Fields populated only during one algorithm, confusing readers the rest of the time
  • Remedy: Extract the field + the methods that use it into their own class (Extract Class / introduce a Method Object)

Testing Smells

No Tests
  • Modules with zero test coverage
  • Business logic without unit tests
  • Remedy: Write characterization tests first, then add behavior tests
Test-Implementation Coupling
  • Tests asserting internal method calls, private state, or implementation details
  • Tests breaking on refactoring without behavior changes
  • Remedy: Test through public APIs, assert behavior not implementation
Test Environment Dependency
  • Tests depending on file system, network, database, system clock without mocking
  • Non-deterministic tests (flaky tests)
  • Remedy: Use test doubles, control environment, use DI

Complexity Smells (Algorithmic Anti-Patterns)

A static complexity pattern is a candidate, not proof of a bottleneck. Apply Measure First:

  1. Establish actual input size, call frequency, I/O latency, and whether the path is hot.
  2. Prefer a profiler, representative benchmark, query log, trace, or explicit operation count.
  3. Promote the candidate to a finding only when the workload and impact justify it.
  4. Re-measure the same workload after a fix; without a baseline, do not claim a performance improvement.

For every complexity candidate, state what to measure, when it becomes a finding, and when not to flag it. Keep the Big-O analysis and correctness checks below, but do not infer severity from syntax alone.

Nested Loops (O(n^2) and Worse)

Two or more loops nested inside each other, producing polynomial complexity.

  • Detection: for/while inside another for/while; forEach/map inside forEach/map; loop containing another loop (any depth)
  • Impact: O(n^2) for double-nested, O(n^3) for triple; explodes with moderate data sizes
  • Remedy:
    • Build a Map/Set index for the inner collection → O(n+m)
    • Sort + two-pointer approach → O(n log n)
    • Group/bucket data before iterating
    • Sweep-line for interval/range problems
  • Correctness checks: Does order matter? Are there duplicate keys? Is the original picking first/last/all matches?
N+1 Query Pattern

A database query, API call, or I/O operation inside a loop body.

  • Detection: fetch()/axios()/query()/execute()/findMany()/findOne()/findUnique()/select()/where() inside any loop construct
  • Impact: 1 + N round-trips instead of 1; network latency multiplied by item count
  • Remedy:
    • Batch fetch by IDs: SELECT * FROM x WHERE id IN (...) then join in memory
    • Use ORM eager-loading / include / preload / DataLoader
    • Bulk API endpoints accepting arrays
    • Preserve: auth filters, tenancy isolation, ordering, pagination, error semantics
  • Correctness checks: Don't fetch records the original per-item logic wouldn't authorize; preserve missing-record behavior
Repeated Linear Scan (Missing Index)

Linear search (includes, indexOf, .find, in_array) inside a loop, where a Set/Map would give O(1) lookup.

  • Detection: .includes() / .indexOf() / .find() / .findIndex() / in_array() / contains() inside a loop body
  • Impact: O(n*m) instead of O(n+m) — each iteration scans the entire collection
  • Remedy: Build a Set (for membership) or Map (for key→value lookup) once before the loop
  • Correctness checks: Does equality semantics change after Set conversion? JavaScript object identity vs. value equality; Python hashability
Sort-in-Loop

Sorting inside a loop body, repeating O(n log n) work unnecessarily.

  • Detection: .sort() / sorted() / sort() inside any iterative block
  • Impact: O(k * n log n) instead of O(n log n) — sort repeated k times
  • Remedy:
    • Sort once outside the loop
    • Maintain a heap (PriorityQueue) if incremental top-K is needed
    • Use binary search/insertion into sorted collection
  • Correctness checks: Is each intermediate sorted state externally observable? Does comparator depend on loop-local state?
Render-Path Recompute (UI Complexity)

Expensive data transformation (filter→map→sort chains) inside UI component render bodies, recomputed on every render.

  • Detection: .filter().map().sort().reduce() chains inside React/Vue/Svelte component function bodies; inside function Component() or const Component = () => in JSX/TSX
  • Impact: Re-derivation on every state change even if inputs unchanged; jank with large collections
  • Remedy:
    • useMemo / computed / derived with correct dependency arrays
    • Move derivation to selectors, loaders, or server-side
    • Virtualize long lists (windowing)
    • Stabilize callbacks and object props only when child renders are affected
  • Correctness checks: Dependency arrays must include every semantic input; memoization must not hide mutations of mutable inputs
Pairwise Comparison

Comparing every element with every other element using double-nested iteration.

  • Detection: Two nested loops iterating the same or similar collections, comparing pairs
  • Impact: O(n^2) for pair matching, overlap detection, conflict checking, nearest-neighbor
  • Remedy:
    • Sort + two-pointer for pair/range matching
    • Sweep-line for interval overlaps
    • Spatial hashing or grid bucketing for proximity
    • Union-find for connectivity
  • Correctness checks: Order stability; tie-breaking in equality cases
Unnecessary Recompute (Missing Memoization)

Same pure computation repeated with same inputs without caching.

  • Detection: Identical function calls with same arguments in hot paths; repeated expensive transforms; recursive calls without memoization
  • Impact: Linear/polynomial wasted work; especially bad with recursive Fibonacci-style patterns (O(2^n) → O(n) with memo)
  • Remedy: Add memoization/caching with proper invalidation; use lru_cache/memoize/useMemo as appropriate
Wrong Data Structure

Using a suboptimal data structure for the access pattern.

  • Detection:
    • Array/List used for frequent membership tests → should be Set
    • Array/List used for key-value lookups → should be Map/Object
    • Array used as queue with shift()/pop(0) (O(n) per dequeue) → should use proper Queue
    • Sorted insertion into array (O(n) per insert) → should use Heap
  • Remedy: Replace with the data structure whose complexity matches the access pattern:
    • Set → O(1) has/add/delete
    • Map → O(1) get/set
    • Heap → O(log n) push/pop for priority
    • Queue/Deque → O(1) enqueue/dequeue
What NOT to Flag
  • Cold paths: Complexity that only runs on startup, config loading, or tiny N (< 100) is rarely worth fixing
  • Intentional tradeoffs: Clear, readable O(n) code where O(n log n) would add complexity with no measurable gain
  • Already optimized: Map/Set already in use; batch loading already implemented; memoization already present

Design Principle Violations

Use the canonical matrix in Step 3 as the reporting contract. These design checks refine candidate detection; they do not create one finding per principle.

  • SOLID umbrella: Use only when multiple SOLID concerns share one root cause or a narrower lens is not reliable.
  • SRP: Confirm independent reasons to change; size alone is insufficient.
  • OCP: Confirm repeated edits for a real variant; do not replace a simple local conditional with speculative polymorphism.
  • LSP: Subtypes must preserve the base contract's preconditions, postconditions, and invariants. Report as SOLID/LSP.
  • ISP: Confirm clients depend on methods they do not use. Report as SOLID/ISP.
  • DIP: Confirm high-level policy is coupled to concrete mechanism in a way that harms testing or replacement; a single implementation does not automatically justify an interface.
  • DRY: Deduplicate shared knowledge, not coincidentally similar syntax.
  • KISS and YAGNI: Reject abstractions whose future variation or leverage is not demonstrated.
  • Composition: Prefer it when inheritance exposes unwanted behavior or binds independent variation axes—not as a mechanical rule.
  • Separation of Concerns: Confirm policy, presentation, persistence, or I/O leakage across an intended boundary.
  • Fail Fast: Detect invalid state near its source while preserving established error, retry, transaction, and cleanup semantics.
  • Measure First: Lower unmeasured optimization claims to candidates instead of reporting a second "principle violation."
Object-Orientation Abusers (from Fowler / refactoring.guru)
Switch Statements (Type-Code Conditionals)

Repeated switch/if-else chains that branch on a type code or enum:

  • The same conditional structure duplicated in several places
  • Adding a new type forces editing every switch (OCP violation)
  • Remedy: Replace conditional with polymorphism (Strategy/State), or Replace Type Code with Subclasses
Refused Bequest

A subclass inherits methods/fields it doesn't need:

  • Overrides inherited methods to throw, no-op, or do something unrelated
  • Signals the inheritance relationship is wrong
  • Remedy: Push down unused members, or replace inheritance with delegation
Alternative Classes with Different Interfaces

Two classes perform the same role but expose differently-named methods:

  • sort() vs arrange(), getUser() vs fetchUser() for interchangeable classes
  • Remedy: Unify the interface (rename methods, extract a common superclass/interface)
Incomplete Library Class

A third-party/library class lacks methods you need and can't be modified:

  • Scattered helper functions or copy-paste wrappers around the library
  • Remedy: Introduce a Foreign Method or wrap it in an adapter/local extension class

Other refactoring.guru smells are documented in their thematic sections above: Divergent Change, Data Class, Lazy Class, Speculative Generality, Temporary Field, Parallel Inheritance Hierarchies, Inappropriate Intimacy, Message Chains, and Middle Man.


Edge Cases & Fallback

ScenarioHandling
User doesn't specify scopeDefault to recent changes (git diff) for repos > 200 files, full analysis otherwise
Project has no clear architectureReport "Big Ball of Mud" with evidence, recommend incremental refactoring
Empty/monorepo projectReport that architecture analysis requires code; ask user to specify module
Language not supportedReport general structural observations; note language-specific checks are limited
Report file path conflictsAppend -2, -3, etc. to filename
User wants a quick checkRun only Critical-level scans, skip Code and Naming categories
User wants only one categoryFocus analysis on that category, skip others

Report Output Example

🔍 Architecture Smell Analysis Complete

Project: goal-workflow
Style: Modular Monolith (with some layering violations)
Files Analyzed: 47
Health: 🟡 Fair

Critical: 3  |  Warnings: 6  |  Suggestions: 9

🔴 Critical Issues:
  1. Anemic Domain Model — `models/` classes have only getters/setters,
     all logic in `services/`. Violates DDD Rich Domain Model principle.
  2. N+1 Query Pattern — `services/order.ts:142` fetches user per order in loop;
     should batch-load users by IDs (O(n*m) → O(n+m)).
  3. Static Cling — `util/ApiClient.ts` uses all static methods,
     making consumer code untestable.

🟡 Warnings:
  1. God Object — `services/workflow.ts` at 847 lines handles too many concerns
  2. Nested Loop O(n^2) — `analytics.ts:89` pairwise comparison of events;
     sort+two-pointer would be O(n log n)
  3. Leaky Abstraction — `repositories/user.ts` exposes MongoDB query syntax
  4. Duplicated Code — validation logic duplicated across 4 controllers
  5. Circular Dependency — `auth` ↔ `user` modules depend on each other
  6. Magic Numbers — ~23 hardcoded values without named constants

Full report: tasks/smell-report-2026-05-27-1530.md

to-design — PRD to Design Document

Turn a PRD (or a rough idea) into a design document written in the style of Go's official design proposals: plain language, concrete examples, and—above all—an honest account of why this approach and not the alternatives.

This is not the same as prd-to-spec. A SPEC is an implementation contract (tables, endpoints, schemas) for an engineer to build against. A design document is a decision artifact: it argues for an approach, surfaces the tradeoffs, and lets a team agree on the same facts before anyone writes code. When the question is "how should we build this and why", produce a design doc; when the question is "give me the exact contract to implement", produce a SPEC.

设计哲学源自对 5 篇 Go 官方 proposal(泛型 / 错误包装 / loopvar / slog / try)的分析。核心信念:文档的价值不取决于方案是否通过,而取决于它是否让讨论建立在同一套事实和取舍之上。


When to Use

  • A PRD exists and you need to decide how to build it before committing to implementation
  • The approach has real tradeoffs and you want them documented and debated
  • The change is risky, breaking, or hard to reverse (a design doc forces the compatibility conversation early)
  • Multiple people need to agree on a direction before work fans out
  • You want a durable record of "why we chose X and rejected Y" — even if the proposal is later rejected

If the team just needs the concrete contract to code against, use /prd-to-spec instead (or run to-design first, then prd-to-spec).


The Job

  1. Locate input — find or receive the PRD (or idea)
  2. Analyze context (optional) — scan the codebase for existing patterns, constraints, and prior art
  3. Surface the decisions — identify the real design forks and ask clarifying questions (max 3-5)
  4. Generate the design doc — following the structure and writing style below
  5. Review — present for feedback, especially on the Rationale and Compatibility sections
  6. Save — write to the agreed location

Step 1: Locate Input

Provide the PRD (or idea) to design from:

A. File path (e.g., tasks/prd-priority-system.md)
B. GitHub Issue URL
C. Paste content directly
D. Just describe the idea — I'll design from the conversation

A design doc can start from a half-formed idea, not only a polished PRD. If the input is thin, lean harder on Step 3.


Step 2: Analyze Context (Optional)

Skip for greenfield. Otherwise scan to ground the design in reality:

  • Existing patterns the design should match (naming, error handling, module boundaries)
  • Prior art — has something similar been tried or rejected here before?
  • Constraints — compatibility promises, public APIs, data the design can't break
  • Real pain — find the actual buggy/awkward code the design fixes, so Background can quote it

The most persuasive Background sections quote real code from the user's own repo, not hypotheticals.


Step 3: Surface the Decisions

A design doc lives or dies on its Rationale. Before writing, find the real forks in the road — the points where a competent engineer could reasonably go two ways — and resolve them.

Ask only about genuine forks:

Design decisions to settle before I write the doc:

1. Where does this logic live?
   A. Extend the existing X
   B. New standalone component Y
   C. Let me recommend based on the codebase

2. Is this a breaking change for existing callers?
   A. Yes — needs a migration path
   B. No — purely additive
   C. Unsure — I'll analyze and flag it

3. What's the one promise this design must keep? (e.g. backward compatibility,
   latency budget, no new dependencies)

For every fork, also note the option you are NOT choosing — that becomes the Rationale.


Step 4: Design Document Structure

This is the standard skeleton distilled from the 5 Go proposals. Keep section names; drop sections that genuinely don't apply (and say why if the omission is notable).

Title: <一句话说清"做什么" —— 标题就是结论,不是名词短语>
Author(s): <作者>
Last updated: <YYYY-MM-DD>
Discussion at <issue / PR / 文档链接>   # 让文档不孤立,永远附讨论入口
Status: Draft | Under review | Accepted | Rejected

## Abstract / 摘要

一段话讲完全文:做什么、大致怎么做、以及**最重要的那个承诺**(如"向后兼容""不引入新依赖")。
读者读完这一段就该知道全貌。把隐含的核心约束埋在这里。

## Background / 背景与动机

用**具体、可感的例子**说明"痛在哪",而不是抽象地说"现状不好"。
- 能贴一段真实的 bug 代码 / 别扭的调用,就贴。先让读者"疼"起来。
- 量化痛点(出现频率、踩坑次数、损失),不要用形容词堆砌。
- 一句话给问题定性。

## Design / Proposal / 设计

文档主体。遵循三条:
- **从简单到复杂,渐进式教学**:从最小例子起步,复杂场景留到读者有直觉之后。
- **声明 + 示例 + 边界**三件套:每个 API/接口先给声明,再给用法片段,再划清适用边界。
- **改造前 vs 改造后对照**:能并排展示收益的,就并排展示。
能用一段可运行代码说清的,绝不用一段文字描述。

## Rationale / 理由与取舍

> Rationale = "为什么是这个方案,而不是别的"的论证。这是区分好文档和平庸文档的关键章节。

- 解释关键决策的动机。
- **主动列出被放弃的备选方案 + 放弃原因**("我们没选 X,因为 Y")。这比单方面论证你选的方案更可信,也避免后人重复讨论。
- 回应可预见的质疑。

## Compatibility / 兼容性

凡涉及破坏性变更,必须正面回应。
- 是不是破坏性变更?**开门见山承认**。
- 代价是什么(性能、行为变化、迁移成本)?**诚实列出**,不藏着。
- 渐进迁移路径(按模块/按文件 opt-in、灰度、特性开关)。
- 有先例佐证更好("某系统做过类似变更,结果平淡无奇")。

## Implementation / Transition / 实现与过渡

- 如何落地、分几步、配套什么工具。
- **用数据和工具支撑"可落地"**:实测失败率、灰度结果、自动化迁移工具,比任何"我们认为风险可控"都管用。
- 兼容老版本的过渡方案(如独立发布的兼容库)。

## Appendix / 附录(可选)

把会打断主线的细节后置:完整 API、端到端示例、FAQ。
FAQ 专门回应高频质疑("为什么叫这个名字""为什么不用某语言的做法""和 X 有何不同")。

Writing Style (照搬 Go 文档的文风)

Structure is the skeleton; style is the muscle. Enforce these — they're what make the doc readable.

Voice / 主语

  • 决策用 "我们 / We" — 把设计说成一群人可负责的选择,不是客观真理。("We propose…", "我们决定移除…")
  • 行为用代码本身当主语 — "this code has a bug" / "这段代码会…",让注意力落在程序上。
  • 说理对读者用 "你 / you" — 像面对面解释。
  • 禁止无主语的被动腔 — 不写"据建议应当…""It is suggested that…"这类推卸责任的句式。

Sentences / 句子

  • 判断用短句,论证用长句。先用一个极短的句子拍板("这段代码有 bug。"),再用信息密集的长句铺开机制。
  • 长短交替制造节奏。不要通篇绕来绕去的长句。

Paragraphs / 段落

  • 一段只讲一件事,观点放段首(结论先行)。
  • 小标题写成一句完整的论点,而不是名词短语。
    • 写 老代码不受影响,编译结果与之前完全一致,而不是 兼容性。
    • 读者光看标题就能读完整条论证链。

Tone / 语气

  • 克制的诚实,甚至自嘲。承认代价、承认自己也踩过坑,比形容词更有说服力。
  • 强调要省着用。全文只在最关键处加粗/斜体一次,反而最醒目。

Step 5: Review & Iteration

Present the doc and steer feedback to the sections that matter most:

设计文档已生成。重点请看这几处:

- Rationale:被放弃的方案和理由是否站得住?有没有遗漏的备选项?
- Compatibility:破坏性和代价是否如实说清?迁移路径可行吗?
- Background:痛点是否用具体例子讲清,而不是形容词?
- 文风:标题是否是"结论"而非名词?有没有无主语的被动腔?

回复 OK 保存,或给出修改意见。

Step 6: Save

设计文档保存到哪里?

A. tasks/design-[feature-name].md(紧挨 PRD,推荐)
B. docs/design/[feature-name].md
C. 自定义路径:[指定]

Mapping: PRD → Design Doc

PRD 部分Design Doc 部分转化方式
Problem / 背景Background找到真实的痛点代码/场景,量化它
Goals / 目标Abstract + Background提炼成"最重要的承诺"埋进摘要
User Stories / 需求Design转成渐进式的设计示例
Technical ConsiderationsDesign + Rationale约束 → 设计决策 + 取舍论证
Non-GoalsRationale写成"我们没做 X,因为 Y"
Risks / 风险Compatibility + Implementation风险 → 兼容性代价 + 迁移/灰度方案
隐含的备选方案Rationale显式列出并解释为何不选

Quality Criteria

A good design doc should pass these checks:

  • 标题是一句"做什么"的结论,不是名词短语,且附了讨论链接
  • 摘要里埋了最重要的承诺/约束
  • Background 用了具体例子或真实代码讲痛点,而非形容词
  • Design 遵循"声明 + 示例 + 边界",并有渐进式教学
  • Rationale 主动列出了至少一个被放弃的方案及原因(最关键的检查项)
  • 凡破坏性变更,Compatibility 都正面承认并列出代价
  • Implementation 用数据/工具支撑"可落地",而非空喊"风险可控"
  • 文风:决策用"我们"、行为用代码、无无主语被动腔;长短句交替;小标题是论点句
  • 没有 "TBD / TODO"——要么解决,要么挪进 Open Questions

Edge Cases & Fallback

场景处理
PRD 含糊不全在 Step 3 多问,把缺失项写进 Open Questions / 假设
没有真实痛点代码可引用最小可信的示例代码代替,并注明是构造的
没有备选方案可写强迫思考"最朴素的做法是什么、为什么不够"——总有一个被否决的基线
不是破坏性变更Compatibility 一句话说明"纯增量、无破坏",不必硬凑
方案最终被否决照样写好——记录"这条路为什么走不通"本身就是高价值产物,Status 标 Rejected
特性太大拆成多篇 design doc(按边界),互相链接
用户只要实现契约提示改用 /prd-to-spec,或先 to-design 再 prd-to-spec

Anti-Patterns to Avoid

  • 别只论证你选的方案。 不写被放弃的备选项,文档就少了一半价值。
  • 别用形容词讲痛点。 "现状很糟"没有说服力;一段真实的 bug 代码才有。
  • 别藏代价。 性能变慢、行为变化、迁移成本——都明说,再给迁移路径。
  • 别把标题写成名词。 "兼容性" → "老代码不受影响,编译结果完全一致"。
  • 别用无主语的被动腔。 决策要有人负责,主语用"我们"。
  • 别写成 SPEC。 设计文档讲"为什么这么选"和"取舍",不是字段级的实现契约。
  • 别因为方案可能被否就敷衍。 文档质量与提案是否通过无关。

Relationship to Other Skills

/prd  →  /to-design  →  /prd-to-spec  →  /goal  →  /review-it  →  /ship-it
 │            │               │              │
 │ 需求(what) │ 决策与取舍     │ 实现契约(how) │ 编码
 │            │ (why/which)   │
  • /prd 产出 PRD(本 skill 的输入)
  • /to-design 产出设计文档:论证方案、暴露取舍、对齐认知(本 skill)
  • /prd-to-spec 产出实现级 SPEC:字段、接口、schema 契约
  • /code-to-spec 从既有代码逆向出 SPEC(互补:正向 vs 逆向)

写设计文档的终极目的不是"说服别人同意你",而是"让所有人在同一个事实和取舍基础上做决定"。

to-issues — PRD/SPEC to Issues

Decompose a PRD and/or technical SPEC into small, independently demoable Issues, each sized to fit a single fresh context window, then create them in your chosen platform. Works standalone — you don't need to have run /prd first.

Every Issue this skill produces is agent-ready by construction: a fresh session that has never seen your PRD/SPEC can pick it up and finish it.


Core principle: tracer bullets, not layers

This is the rule that matters most, and the one models break most often.

  • A horizontal slice ships one layer of the change (all the schema in one ticket, all the API in another, all the UI in a third). Nothing works until every layer lands, and each ticket's acceptance criteria have to reach into work another ticket owns. This is the default the model falls into — avoid it.
  • A vertical slice — the tracer bullet — ships one thin but complete path through every layer at once (schema + API + UI + tests for a single narrow behaviour). It is verifiable alone the moment it lands, and it owns everything it grades.

The test for every Issue: "What can I demo when this is done?" If the answer is a layer ("the database has a priority column") rather than a behaviour ("a user can set a task's priority and see it persist"), it is a horizontal slice — re-slice it.

Sizing floor: if the whole change fits in one context window, you don't need Issues at all. Say so and point the user straight at /goal.

Keep this skill in the same context window as /prd-to-spec. Don't clear or compact between them, or the SPEC has to be re-fetched and may truncate.


The Job

  1. Locate input — find a PRD or SPEC file (auto-detect or user-specified)
  2. Find prefactoring — surface "make the change easy, then make the easy change" work and order it first
  3. Decompose into vertical Issues — break behaviour into tracer-bullet tickets with blocking edges
  4. Quiz the user — present the numbered list and push on granularity, edges, and demo paths before publishing
  5. Choose platform — GitHub / Local
  6. Create Issues — blockers first, with native blocking links, then print summary

Step 1: Locate Input

Find the input document:

What should I base the Issues on?

A. Auto-detect: scan tasks/ for recent PRDs and SPECs
B. Specific PRD file (e.g., tasks/prd-priority-system.md)
C. Specific SPEC file (e.g., tasks/spec-priority-system.md)
D. Both PRD and SPEC (best: PRD for requirements, SPEC for technical contracts)
E. Paste requirements directly

If auto-detecting, list available files and let the user choose.

If both PRD and SPEC are available, use the SPEC's Section 10.2 (Issue Mapping) as the primary guide, supplemented by PRD's User Stories. If only PRD is available, generate Issues directly from User Stories.


Step 2: Find Prefactoring First

Before slicing features, look for prefactoring: mechanical groundwork that makes the feature Issues small and safe — extracting a shared helper, widening a type, adding a seam, moving a file. Order this work first, as its own Issue(s), so the feature tickets that depend on it stay thin.

If you find none, skip this step. Don't invent busywork.


Step 3: Decompose into Vertical Issues

Generate the Issue list. Rules:

  • Each Issue is a tracer bullet — a narrow, complete, demoable path through every layer it touches. Not "the backend for X"; rather "X, end to end, for one case."
  • Each Issue fits one fresh context window — a single agent session completes it without needing you in the room.
  • Split by behaviour, not by layer — if a User Story is large, split it into 2-3 narrower behaviours, each still vertical, with explicit blocking edges. Never split it into a backend ticket and a frontend ticket.
  • Merge tiny stories — 1-2 trivial criteria that don't stand alone as a demo should merge into a related Issue.
  • Declare blocking edges explicitly — every Issue lists what must finish before it can start. These edges are the point of the artifact.
  • Number Issues in dependency order — blockers first, so an implementer (or the tracker) always has a valid frontier to start from.
  • If SPEC is available — enrich each Issue with SPEC references (API contracts, data model sections, error handling). But keep file paths and line numbers out of the body — they rot; describe behaviour and contracts instead.

Falsifiable acceptance criteria. For each criterion, name the observation that would show it false, and confirm it would fail at the commit the implementer starts from. Reject three shapes: a criterion already true at the base commit, one that can only be satisfied by work another Issue owns, and one that merely restates the request. A vertical slice delivers behaviour that didn't exist before, so it should be red at the base commit by construction.

Issue format:

Issue #N: [Title — a behaviour, not a layer]
---
Description: [What behaviour this delivers, end to end, and why]
Demo path: [The one thing you can show working when this lands]
Acceptance Criteria:
- [ ] [Falsifiable — names an observation that fails at the base commit]
- [ ] ...
Blocked by: [None / Issue #X, #Y]
Priority: [high / medium / low]
SPEC Reference: [Section X.Y — contracts only, no file paths; only if SPEC available]

Step 4: Quiz the User (do not skip)

Present the breakdown as a numbered list and quiz the user before publishing anything. Over-decomposition and accidental horizontal slicing are the two most common failures — this step catches both.

📋 Generated N Issues from [PRD/SPEC], in dependency order:

#1: Extract task-mutation helper (prefactoring) — Blocked by: none
#2: A user can set a task's priority and see it persist — Blocked by: #1
    demo: open a task, pick High, reload, still High
#3: A user can filter the task list to one priority — Blocked by: #2
    demo: select High, list shows only High tasks
#4: A user can sort the task list by priority — Blocked by: #2
    demo: click Sort, tasks reorder High→Low

Review before I create anything:
- Granularity: too fine? "merge #3 and #4". Too coarse? "split #2".
- Demo path: any Issue whose demo is a layer, not a behaviour, is mis-sliced — tell me.
- Edges: are the "Blocked by" links real? Any missing or spurious?
- Adjust: "change #2 priority to high", "add an issue for a priority badge"
- Confirm: reply OK to proceed

Wait for confirmation before creating any Issues.


Step 5: Choose Creation Mode

Choose where to create these Issues:

A. GitHub (via gh CLI, with native blocking links and optional sub-issues)
B. Local (one markdown file per Issue, dependency-ordered)

Your choice:

Step 6: Mode-Specific Creation

Mode A: GitHub

Prerequisites: gh CLI installed and authenticated, v2.94+ for --parent / --blocked-by.

Create blockers first so their Issue numbers exist before any Issue that depends on them. Capture each returned number.

Actions:

  1. For each Issue, in dependency order:
    gh issue create \
      --title "[Title]" \
      --body "[Description + Demo path + Acceptance Criteria + SPEC Reference]" \
      --label "priority: [priority]" \
      --blocked-by [comma-separated blocker numbers, if any] \
      --parent [spec issue number, if creating as sub-issues]
    
    • Use native --blocked-by for edges. Only fall back to a "Blocked by #X" line in the body if the tracker rejects the flag.
    • If the SPEC lives in a GitHub issue, pass --parent <spec_issue> so these become sub-issues of it. To wire a parent after the fact: gh issue edit <parent> --add-sub-issue <n>.
  2. If labels don't exist, create them first or skip the --label flag.
  3. Report created Issue numbers and URLs.

Mode B: Local

Ask user:

Where should I save the Issue files? (default: .autoresearch/issues/[feature-slug])

Actions:

  1. Create the feature folder with mkdir -p if it doesn't exist. One folder per feature keeps parallel agents from racing on a shared file.
  2. For each Issue, in dependency order, save NN-[slug].md (zero-padded, NN is a real ticket ID so /goal 03 works):
    # [Title — a behaviour]
    
    ## Description
    [What behaviour this delivers, end to end, and why]
    
    ## Demo path
    [The one thing you can show working when this lands]
    
    ## Acceptance Criteria
    - [ ] [Falsifiable criterion 1]
    - [ ] [Falsifiable criterion 2]
    
    ## Blocked by
    [None / #NN, #NN]
    
    ## Priority
    [high / medium / low]
    
    ## SPEC Reference
    [Section X.Y — contracts only; omit if no SPEC]
    
  3. Report created file paths in dependency order.

The wide-refactor exception

One shape breaks the tracer-bullet rule: a wide refactor — a single mechanical change (rename a column, retype a shared symbol) whose blast radius fans across the whole codebase, so one edit breaks thousands of call sites and no vertical slice can land green.

Sequence it as expand → migrate → contract instead:

  • Expand — add the new form beside the old, so nothing breaks. One Issue.
  • Migrate — move call sites over in batches sized by blast radius (per package, per directory), one Issue per batch, each blocked by the expand. CI stays green because the old form still exists.
  • Contract — delete the old form once no caller remains, in an Issue blocked by every migrate batch.

Where even the batches can't stay green alone, have them share an integration branch and all block a final integrate-and-verify Issue; green is promised only there.


Step 7: Summary Report

✅ Issue creation complete!

Source: [PRD/SPEC path]
Mode: [GitHub / Local]
Issues created: N (in dependency order)

#  | Title (behaviour)                        | Blocked by | Identifier
---|------------------------------------------|------------|------------
1  | Extract task-mutation helper             | —          | #42 / 01-*.md
2  | Set & persist task priority              | #1         | #43 / 02-*.md
3  | Filter task list by priority             | #2         | #44 / 03-*.md
4  | Sort task list by priority               | #2         | #45 / 04-*.md

Frontier (no open blockers, start now): #1

💡 Dispatch is manual — one Issue per fresh session, cleared between them.
   Count the Issues with no open blockers, open that many sessions, implement with /goal:
   /goal 42                # GitHub mode
   /goal 01-*.md           # Local mode
   Note: /goal may not auto-close the ticket — update its state yourself when done.

It's working if

  • Every Issue answers "what can I demo when this is done?" — and the answer is a behaviour, not a layer.
  • The list came back numbered with a real "Blocked by" line on each, before anything was published.
  • The Issue at the top has no blockers and can be started immediately.
  • No Issue body carries a file path or line number (except a snippet a prototype produced).
  • Each Issue reads like something a fresh session could finish without you in the room.
  • Prefactoring, where any was found, sits at the front of the order — not mixed into feature Issues.
  • Every acceptance criterion names an observation that fails at the base commit.

Edge Cases & Fallback

ScenarioHandling
Whole change fits one context windowSay so; skip Issues, point at /goal directly
No PRD/SPEC found in tasks/Ask user to provide file path or paste requirements
PRD has no User StoriesDerive Issues from Functional Requirements instead
SPEC has Issue Mapping (Section 10.2)Use it as primary source, cross-reference with PRD
Model produced one-per-layer IssuesCatch at the quiz: any Issue whose demo is a layer gets re-sliced vertically
Model over-decomposed (12 tickets for a 3-line change)Quiz step: ask to merge; if the whole thing fits one window, skip Issues
Wide mechanical refactorUse the expand → migrate → contract sequence above
gh too old for --blocked-by / --parentFall back to "Blocked by" body line; suggest upgrading gh to v2.94+
gh CLI not authenticated for GitHub modeShow error, suggest gh auth login, offer to switch to Local mode
Issue folder does not exist for Local modeAuto-create per-feature folder
User declines Issue creationPrint the dependency-ordered list as a text summary for manual creation later

Relationship to Other Skills

/prd  →  /prd-to-spec (optional)  →  /to-issues  →  /goal  →  /review-it  →  /ship-it
 │              │                        │              │
 │  Requirements │  Technical design     │  Vertical    │  Implementation
 │  (what)       │  (how)                │  tickets     │  (code)
  • /prd — produces the PRD (input to this skill)
  • /prd-to-spec — produces the SPEC (optional; keep in the same context window as this skill)
  • /to-issues — produces the vertically-sliced Issues (this skill)
  • /goal — implements Issues one by one, one per fresh session

understand

把「本次(AI)新生成的代码变更」变成一个可交互的审阅网页:左侧按真实项目布局列出变更文件树,右侧显示所选文件的 diff(高亮、增删与未变更代码明显区分),并在右侧边栏逐段给出相关单位需求与代码解释;解释下方可按需提供「伪代码」「调用树」两个展开式文本视图(参考 show-me skill 的呈现方式)。

始终用中文产出解释与需求。

何时用

  • 用户说 /understand、"review 这次改动"、"解释下新写的代码"、"看看这次变更做了啥"。
  • 目标是理解 + 审阅当前工作区里尚未吃透的改动(通常是 AI 刚生成的),不是重构或修 bug。

组成

skill 目录下三件套(都在 ~/.claude/skills/understand/):

  • understand.py — 纯标准库生成器,两个子命令:scan(解析 git diff → data.json + annotations.json 骨架)、render(合并注释 → report.html)。
  • template.html — Claude light 主题两栏页面(占位符 __UNDERSTAND_PAYLOAD__ 注入数据),Prism.js 走 CDN 做语法高亮。
  • 本文件 — 流程说明。

执行流程

在**用户当前工作目录(仓库内)**执行以下步骤。全程把 SKILL_DIR 当作本 skill 目录的绝对路径(即本文件所在目录)。

1. 扫描变更

python3 "$SKILL_DIR/understand.py" scan
  • 默认基线 = 当前分支与主分支(origin/main→main→master)的 merge-base;如用户指定范围可加 --base <ref>(例如只看最后一次提交用 --base HEAD~1)。
  • 默认输出目录 .understand/(相对 CWD)。可用 --out <dir> 改。
  • 它覆盖:已提交(base..HEAD) + 已暂存 + 未暂存 + 未跟踪新文件。
  • 命令会打印 JSON:文件数、增删行数、data.json / annotations.json 路径、以及 paths(变更文件列表)。读这个输出了解改了哪些文件。

2. 通读改动并撰写注释

先把改动读懂,再落注释。建议:

  • Read 每个变更文件(结合 data.json 里的 hunks 看具体增删行号),必要时读周边未改代码补足上下文。
  • 判断每处改动对应的单位需求:优先从仓库线索找真实依据——commit message、docs/ 需求文档、代码注释里写的需求编号/背景、相关 issue。找到真实需求就照写;确实找不到,就基于代码逻辑写「推测意图」并在注释里把 inferred 置为 true(前端会标成灰色「推测意图」而非「需求」,避免把猜测伪装成事实)。

然后编辑 .understand/annotations.json(scan 已生成骨架,保留其 files[].path 顺序,逐个填充)。结构:

{
  "title": "本次变更的一句话主题",
  "summary": "整体在做什么、为什么(2~4 句,可用 **加粗** 与 `代码`)",
  "files": [
    {
      "path": "src/main/java/.../PwaTierInvitationService.java",
      "summary": "这个文件这次改了什么、为何改(1~3 句)",
      "annotations": [
        {
          "side": "new",
          "start": 52,
          "end": 53,
          "requirement": "expires_at 为 timestamptz,需正确编码",
          "explanation": "Vert.x PG 客户端不支持 `java.time.Instant`,改绑 `OffsetDateTime`(`atOffset(UTC)`),否则运行期报 coercion 错误。",
          "pseudocode": "on(save)\n  if content is unchanged\n    return cached result\n  write new content\n  return fresh result",
          "callTree": "submitForm\n  createSession\n    persistPrompt\n    launchAgent\n  navigateToSession",
          "inferred": false
        }
      ]
    }
  ]
}

注释字段:

  • side — "new" 锚定新版本行号(增行/上下文),"old" 锚定旧版本行号(删行)。绝大多数解释用 "new"。
  • start / end — 该段代码的行号区间(data.json 里对应 side 的 newNo/oldNo;单行时 end 可省或等于 start)。行号是文件真实行号,不是 diff 里的序号。
  • requirement — 该段对应的单位需求(简短一句,作为标签展示)。可留空。
  • explanation — 代码解释:讲清这段在干嘛、为什么这么写、有何风险/前提。可用 `code` 和 **bold**。
  • pseudocode / callTree — 可选的两种补充视图(参考 show-me skill),给了字段,该卡片解释下方才会出现「伪代码」「调用树」按钮,点击展开文本面板:
    • pseudocode — 把这段的逻辑/算法写成语言无关的伪代码:两空格缩进表结构与分支,只保留关键判断、边界与数据流向,不照抄源码(不写变量声明、类型等噪音)。
    • callTree — 这段代码运行期的控制流调用树:根节点是本段入口,两空格缩进表调用层级,只列真正会执行到的调用(必要处可带一句 # 注释 说明分支条件),不列未走过的分支。
    • 这两个视图不必每条注释都写:只为算法较绕(多分支/状态机/缓存判定)或调用链较深(跨多层模块)的段落写;都不适用就两个都省略。
  • inferred — 需求为推测时置 true。

注释密度:聚焦关键/易错/体现需求的段落(新增的核心逻辑、边界处理、并发/事务、类型坑、SQL 口径等),不必逐行;每个重要文件给 1~5 条即可。可参考项目记忆里的常见坑(如 Vert.x Future.await()、PG = ANY 数值数组、timestamptz 编码)来判断哪些点值得解释。

3. 渲染并打开

python3 "$SKILL_DIR/understand.py" render
open .understand/report.html    # macOS;Linux 用 xdg-open

render 会把 data.json + annotations.json 合并注入模板,产出 .understand/report.html(单文件,纯前端,Prism 走 CDN)。用浏览器打开即可:左树选文件 → 右侧看 diff → 边栏卡片点「定位 →」跳到对应代码行(会高亮闪一下);若注释写了 pseudocode/callTree,卡片解释下方会出现「伪代码」「调用树」按钮,点击展开/收起(同卡片内两个视图互斥)。左侧文件树栏可拖动分隔条调整宽度(宽度记忆在 localStorage,双击分隔条恢复默认)。

最后用中文向用户简述:改了几个文件、核心变更是什么、有哪些值得注意的点,并给出 report.html 路径。

注意

  • .understand/ 是产物目录,建议提醒用户按需 git clean 或加 .gitignore,别误提交。
  • 若 data.json 为空(无变更),如实告知用户没有检测到改动,不要硬造。
  • 行号务必对齐 data.json:annotations.json 里的 start/end 用文件真实行号,side 决定用新/旧行号系。填错会导致边栏卡片锚不到代码行(不报错,但点「定位」无反应)。
  • 不改动用户业务代码;本 skill 只读代码 + 写 .understand/ 下的产物。

walkthrough — Phase 2: The Walkthrough Plan

Once the agent finishes execution and verification, it outputs a walkthrough artifact: a single Markdown file that lets you quickly catch up on what was changed and what is proven to work, and lets you do a staging-check with Git before merging.

This is modeled on Google Antigravity's walkthrough plan: the agent is expected to prove the change works (unit tests + real browser behavior), capture visual evidence, and hand you a review gate — not just dump a diff.

When to use

  • After /goal (or any implementation) plus its verification pass are complete — e.g., after /review-it / /verify / manual testing
  • Before /ship-it, as the last checkpoint before commit/PR/merge
  • User says "walkthrough", "生成 walkthrough", "生成走查文档", "write the walkthrough", "/walkthrough", "Phase 2 walkthrough"

The Job

  1. Determine the change scope — which feature / Issue / branch is being walked through, and which repos it spans
  2. Write the plain-language opening — before/after + why, readable by someone who has never seen the code
  3. Write the Change Summary — the technical detail, for whoever will read the diff next
  4. Run and record Verification Steps — execute the tests and commands, capture real output, label each claim's provenance
  5. Capture Visual Proof — screenshot / record the UI behavior you verified
  6. Build the Review Gate — stage-check the diff with Git, draft the PR description, spell out deploy-order prerequisites
  7. Save to tasks/ and present — write walkthrough-[feature].md, render it to HTML, summarize for the user

Section-by-section

1. 先说人话 / Plain-language opening (读前必读)

The first thing in the file. A PM, QA, a neighbouring team, or you in three months must be able to read only this section and know what changed and why they should care.

Required content:

  • Before / after, concretely — what the caller/user sees, not what the code does:

    改之前改之后
    {用户/调用方看到什么}{old behaviour}{new behaviour}
  • Why it changed — 2–3 reasons in plain words. If you cannot state a reason without naming a class, a flag, or a table, you do not understand the change well enough to write this section.

  • What the reader must do differently, if anything (call a new endpoint, run a migration, change the client).

Rules:

  • Never open with an identifier. dryRun, draft_id, PriorityResolver are not explanations. Introduce the concept in plain words first, name it second.
  • A sentence like "X 从「A」改为「B」" is banned unless A and B are both explained in plain words.
  • If the change has a user-visible effect, describe it from the user's side.
BAD  (技术上没错,但读的人解不开)
> 把优先级的写入时机从「即时落库」改为「先返回 draft_id、确认后落库」

GOOD (同一件事)
> 用户改任务优先级时,以前客户端发一次就直接写进数据库;现在后端先把可选的优先级算出来
> 让用户挑一个,挑完才写。用户没挑就不写。

1b. Glossary — only if the doc uses internal jargon

If the doc uses any of: internal flag/field names (dryRun), numeric interface ids (1001), domain terms an outsider can't decode (「归一化」「草稿」), or module names not inferable from the file tree — add a two-column mapping from the doc's wording to plain language.

| 文中说法 | 说人话 |
|---|---|
| `dryRun` | 开关:`true` = 只算不写,不传 = 老行为 |
| 「草稿」 | 算出来、还没落库的中间结果 |
  • Do not gloss standard terms (HTTP, SQL, PR) — that reads as padding.
  • Pay special attention to pairs that look alike but mean different things. If two similarly-named concepts are easy to confuse, say so explicitly in the table — that is where readers actually get lost.

2. Change Summary

The technical description, for a reader who is about to open the diff. This is where identifiers belong — the plain-language section already paid for them.

  • Read the diff (git diff, git log) and the Issue/PRD it serves
  • Summarize in 3–6 bullets: what was built, refactored, added, or removed
  • List the key files and components, and the shape of what's new (modules, pages, APIs, data structures)
  • State the requirement it satisfies and link the Issue / PRD if present

3. Verification Steps

Proof that the implementation actually works — evidence, not assertion. Record what you ran and what it output.

  • Terminal commands & unit tests: run the test suite (or the targeted tests), lint/build, and any smoke commands. Paste the exact command and its successful output (truncate noise, keep pass counts).
    go test ./... -run TestPriority
    
    ok  	github.com/example/app 0.042s
    
  • Automated browser testing outcomes (if the change has UI): open the app in a sandbox/headless browser, click through the demo path, and record the outcome. For each scenario: the action performed, the observed result, pass/fail.
    Scenario: user sets a task's priority
      1. open /tasks — renders list
      2. click priority select on task #3 → pick "High"
      3. reload — task still shows High  ✓
    
  • If a step was skipped (no tests, no UI), say so explicitly — don't invent evidence.

Label the provenance of every claim. Three levels, and say which one applies:

LabelMeansExample
已实测You ran it, you have the output95 PASSED / 0 FAILED
代码推断Read from the code or a unit test, not executed「没有优先级时回落 normal」(PriorityResolverTest 里有对应用例,但没跑)
未验证Neither — and it must be said out loud「本机无数据库/缓存/外部服务,服务级行为未在本环境验证」

Never present 代码推断 or 未验证 as if it were 已实测. A walkthrough that overstates its evidence is worse than one with gaps, because the gaps are what the reader would have checked.

Record how you made the command run at all. If it needed a workaround — offline mode, a config override, an init script, a narrowed test filter — record it, otherwise the reader cannot reproduce your evidence.

./gradlew test --offline --rerun -I /tmp/no-failfast.gradle \
  --tests "com.example.tasks.*" --console=plain
# 依赖仓库在本机不可达,必须加 --offline;构建脚本设了 failFast=true,
# 不覆盖的话第一条失败就停,看不到完整清单

Also record a baseline caveat whenever the runner's defaults would mislead: failFast hiding later failures, a test cache replaying stale results (--rerun), a suite that is already red before your change.

If the broader suite is red, trace every failure — do not write "unrelated". For each one, give:

  • the file/class, the commit that last touched it, and its date
  • whether that commit is an ancestor of your base (→ pre-existing)
  • whether it falls inside your own commit range (→ yours)
| 失败用例 | 所属类最后修改提交 | 是 base 祖先? | 在本分支提交内? |
|---|---|---|---|
| `PriorityResolverTest > defaultsToNormal()` | `1a2b3c4d` 2026-01-15 | 是 | 否 |

A failure traceable to a commit before your base is pre-existing — say so with the hash, so the reader can re-check. A failure inside your range is yours, however unrelated it looks.

4. Visual Proof

Screenshots or short screen recordings captured during browser testing, embedded directly into the file so it renders anywhere (GitHub, VS Code, browser).

  • Screenshots: capture during the browser walkthrough above. Embed as base64 data URIs for a fully self-contained file (recommended):
    ![Task priority — set to High](data:image/png;base64,<base64>)
    
    On macOS you can capture a window with screencapture; for web pages prefer browser automation tooling (e.g. Playwright: npx playwright screenshot <url> tasks/shot.png, then read the PNG and embed it).
  • Recordings: if you captured a screen recording, note its path and link it in the file (![Demo](tasks/recording-demo.mov)).
  • Prefer 2–4 focused screenshots that prove the demo path (before → action → after), not a screenshot dump.
  • If the change has no visual surface, write "None — change is backend/CLI only" rather than forcing a screenshot.

5. Review Gate

The final diff / PR description where you (or the user) staging-check the code with Git before merging.

  • Diff stat + file list: git status, git diff --stat HEAD, git diff --name-status

  • High-risk notes: call out force-pushed history, migrations, config changes, wide refactors, submodule pointer bumps

  • Deploy-order prerequisites (required whenever the change ships a DDL / migration / config key / feature flag) — state (a) exactly what must be applied, (b) how (manual vs automatic), (c) the failure mode if the order is wrong:

    > `0042-add-priority-to-tasks.sql` 给 `tasks` 表加 `priority` 列。
    > **不会被任何 compose 自动执行**(唯一挂载的 initdb 目录指向的是另一个路径),
    > 必须手工应用到所有环境。实体已映射该列且 ddl-auto=none →
    > 代码先上线会让**每一次** Task 查询抛 SQLGrammarException,
    > 即整个服务的任务查询全挂,而非仅新功能不可用。
    

    "记得跑一下 migration" is not enough. The reader needs the blast radius, because that is what determines whether they schedule it carefully or wing it.

  • Draft PR description: a ready-to-paste PR body (summary, test plan, Closes #N), mirroring /ship-it

  • Merge checklist: confirm tests green, review pass done, no stray artifacts in git status, commit messages reference the Issue

Multi-repo changes. If the work spans more than one repo:

  • one file list + verification section per repo, each with its own branch state (local == remote? pushed? PR open?)
  • state explicitly that the branches must merge together, and what breaks if only one lands
  • verify each repo's checkout individually. A repo you did not open is not a repo you verified — do not conclude "the other half isn't implemented" from a single checkout; the same repo often exists at several paths on different branches.

Output

Two files, same basename:

FileRole
tasks/walkthrough-[feature-name].mdSource. What you author and edit. Kebab-case, e.g. walkthrough-priority-system.md
tasks/walkthrough-[feature-name].htmlDeliverable. What you hand to a reviewer. Generated from the .md, never hand-edited

The HTML is not optional — it is the artifact people actually read. It is light-themed (warm off-white, serif headings, terracotta accent), self-contained (no CDN, no external assets), and carries a fixed table-of-contents sidebar on the left built from the document's h2/h3.

Render it with the script bundled with this skill:

python3 scripts/md2html.py tasks/walkthrough-[feature-name].md
# or, once installed:
python3 ~/.claude/skills/walkthrough/scripts/md2html.py tasks/walkthrough-[feature-name].md
  • Writes walkthrough-[feature-name].html beside the input; pass a second path to override.
  • --title "…" overrides the page title (default: the document's # H1).
  • Needs the markdown package: python3 -m pip install --user markdown. If it is missing the script exits with that instruction — relay it, do not silently skip the HTML.
  • Embedded data: image URIs pass through untouched, so Visual Proof screenshots survive.
  • Re-render after every edit to the .md. A stale HTML beside an updated Markdown is worse than no HTML: the reviewer reads the stale one.

If the user passes a name (/walkthrough user-auth) or an Issue number (/walkthrough #42), use that. If the current branch is feat/issue-42-* or feat/priority-system, derive the feature name from it. Otherwise ask.

Template

# Walkthrough — {Feature / Issue Title}

> Phase 2 walkthrough artifact · generated {date} · {author}
> {跨哪几个仓 / 分支名,若只有一仓则省略}

## Change Summary

### 先说人话:这次到底改了什么

{2–4 句,不含任何标识符。改之前什么样、改之后什么样。}

| | 改之前 | 改之后 |
|---|---|---|
| {用户/调用方看到什么} | {old behaviour} | {new behaviour} |

{为什么改,2–3 条大白话。}
{读的人需要做什么不同的事吗?}

### 术语表

| 文中说法 | 说人话 |
|---|---|
| {identifier / 数字接口号 / 领域词} | {plain meaning} |

### 技术摘要

{2–4 sentence high-level description — 到这里才允许出现标识符}

- {bullet: what was built/refactored/added/removed}
- {key files, components, pages, APIs}
- {requirement satisfied — link Issue/PRD}

## Verification Steps

### Terminal commands & unit tests

```bash
{exact command, including any workaround needed to make it run}
```
```
{actual output — pass counts, ok lines}
```

**provenance:** {已实测 / 代码推断 / 未验证} — {对每条重要结论标注}
{若跑不了:本机缺什么(DB/Redis/外部服务),因此哪一层未被验证}

{若更宽的测试面是红的,逐条列表并给出「是 base 祖先吗 / 在本分支内吗」}

### Automated browser testing

| # | Scenario | Action | Observed result | Status |
|---|----------|--------|-----------------|--------|
| 1 | {demo step} | {clicks / inputs} | {what happened} | ✅ / ❌ |

## Visual Proof

![{caption}](data:image/png;base64,{base64})

_{or: None — change is backend/CLI only}_

## Review Gate

```bash
git status
git diff --stat HEAD
git diff --name-status
```
{output}

### High-risk notes

{force-pushed history / migrations / config / submodule bumps}

**部署顺序前置** {仅当涉及 DDL / migration / 配置项 / 开关}
- 要应用什么:{文件路径}
- 怎么应用:{手工 / 自动;若「不会被任何东西自动执行」就直说}
- **顺序错了会怎样**:{blast radius,不是「功能不可用」而是「什么会一起挂」}

### Draft PR

{ready-to-paste PR body — Summary / Test plan / Closes #N}

### Merge checklist

- [ ] Unit tests / build pass (evidence in Verification Steps)
- [ ] Browser testing done where UI changed (evidence in Visual Proof)
- [ ] Review pass complete (/review-it)
- [ ] No stray artifacts in `git status`
- [ ] Commit messages reference the Issue
- [ ] 每条结论都标了 provenance(已实测 / 代码推断 / 未验证)
- [ ] 若有更宽测试面的红,逐条追溯到 commit 并说明是否在本次范围内
- [ ] 部署顺序前置已写清(含 blast radius),若有
- [ ] 多仓时:每个仓各自的文件清单/证据/分支状态都齐了

Determining the feature name

  1. If the user provides it (/walkthrough user-auth), use it
  2. If on a branch feat/issue-42-* / feat/priority-system / fix/issue-42-*, derive from the branch (strip the feat/ prefix and issue number)
  3. If a PRD/SPEC exists in tasks/ (prd-*.md, spec-*.md), reuse its feature name
  4. Otherwise ask: "What feature name should the walkthrough use?"

Edge cases

ScenarioHandling
No changes detected (git diff empty, nothing new)Say so plainly; do not fabricate a walkthrough
No tests existNote "no automated tests in repo" and rely on manual/browser verification evidence
Change has no UIVisual Proof = "None — backend/CLI only"; browser-testing section marked N/A
Screenshot embedding failsFall back to tasks/*.png relative paths and note the files to commit alongside
tasks/ directory missingAuto-create it
Walkthrough already exists for this featureAsk: update in place or overwrite? default = overwrite (fresh snapshot)
Verification couldn't be completedRecord it as a blocker in the Review Gate — never mark unverified work as proven
Broader test suite is redTrace each failure to a commit (ancestor of base?) before writing anything. "unrelated" without a hash is not evidence
Change spans multiple reposOne section per repo + explicit "must merge together"; check each checkout — a repo you didn't open isn't verified
Change ships a DDL / migration / flagDeploy-order prerequisite with blast radius is mandatory
Only part of the change is testable locally (no DB/Redis/external service)Say which layer is unverified in this environment; a doc that overstates evidence is worse than one with declared gaps
Doc is heavy with internal identifiersAdd the plain-language opening + glossary. If the opening paragraph contains a flag name, it isn't written yet
markdown package not installedRelay the script's install hint (python3 -m pip install --user markdown); do not silently skip the HTML
Markdown edited after renderingRe-run the renderer. Never leave a stale .html next to a newer .md
Document will be shared outside the team / into a public repoReplace every repo-specific example (paths, class/table/column names, commit hashes, internal hosts) with a neutral one before writing

Relationship to other skills

/goal → /review-it → /note-it → /walkthrough → /ship-it
   │         │           │           │             │
 execute   find/fix   rationale   proven +      commit + PR
                                  review gate
  • /review-it — fixes issues and confirms the change is sound; walkthrough assumes this (or equivalent) already ran
  • /note-it — captures design rationale per Issue; walkthrough captures proof + summary, complementary
  • /understand — explains what new code does; walkthrough is the formal artifact you hand to a reviewer
  • /ship-it — consumes the walkthrough: the Review Gate's draft PR and checklist feed straight into it

Checklist

Before saving:

  • Plain-language opening exists and contains no identifiers — a non-engineer can read it standalone
  • It says what changed before vs after, and why
  • Glossary present if the doc uses internal ids / flags / domain jargon; confusable concept pairs called out
  • Change Summary is written for a fresh reader (not a diff dump)
  • Every Verification Step shows the actual command + actual output
  • Where the command needed a workaround to run, that's recorded
  • Every claim labelled 已实测 / 代码推断 / 未验证
  • Red tests on the broader suite traced to a commit (hash + is-it-before-base), not hand-waved as "unrelated"
  • Browser scenarios recorded with pass/fail outcomes, where UI exists
  • Visual Proof embedded (base64) or explicit "None"
  • Review Gate shows git status / git diff --stat + draft PR + merge checklist
  • Deploy-order prerequisites + blast radius, if the change ships a migration/config/flag
  • Multi-repo: every repo has its own file list, evidence, and branch state
  • Unverified claims are marked as unverified — nothing invented
  • Saved to tasks/walkthrough-[feature-name].md
  • Rendered to .html and re-rendered after the last Markdown edit (left TOC sidebar present)
  • No repo-internal specifics leaked into examples if this document is destined for a shared/public place

Sponsors

Details

Marketplace
smallnest/goal-workflow
Category
Engineering
Keywords
workflow, prd, spec, issues, code-review, refactor, go