5-phase-workflow 1.8.2 → 1.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "5-phase-workflow",
3
- "version": "1.8.2",
3
+ "version": "1.8.5",
4
4
  "description": "A 5-phase feature development workflow for Claude Code",
5
5
  "bin": {
6
6
  "5-phase-workflow": "bin/install.js"
@@ -12,16 +12,16 @@ You follow existing codebase patterns. You do NOT deviate from the plan.
12
12
  <process>
13
13
  ## Implementation Process
14
14
 
15
- 1. **Read the plan context** provided in your prompt (feature name, components, implementation notes)
15
+ 1. **Read required files FIRST** If your prompt includes a `Pattern File` or `Read First` field, you MUST read every listed file before writing any code. This establishes ground truth and prevents assumptions about conventions, naming, or structure.
16
16
  2. **For creating files:**
17
- - Find a similar existing file via Glob
18
- - Read that file to understand the pattern
19
- - Create the new file following the same conventions
17
+ - Read the pattern file (from step 1) to understand conventions
18
+ - Create the new file following the same patterns exactly
19
+ - If no pattern file was provided, find a similar existing file via Glob and read it
20
20
  3. **For modifying files:**
21
21
  - Read the target file
22
22
  - Apply the described change via Edit
23
23
  - Verify the change is correct
24
- 4. **Verify** each file exists after changes
24
+ 4. **Run verify command** — If your prompt includes a `Verify` field, run that command and confirm it passes. If it fails, fix the issue (subject to the 3-attempt limit). If no verify command was provided, verify each file exists after changes.
25
25
  </process>
26
26
 
27
27
  <output-format>
@@ -31,6 +31,8 @@ When done, output your result in this exact format:
31
31
  STATUS: success | failed
32
32
  FILES_CREATED: [comma-separated paths]
33
33
  FILES_MODIFIED: [comma-separated paths]
34
+ VERIFY: passed | failed | skipped
35
+ DEVIATIONS: none | {brief list of auto-fixes applied}
34
36
  ERROR: none | {error description}
35
37
  ---END---
36
38
  </output-format>
@@ -44,5 +46,12 @@ You WILL discover unplanned work. Handle as follows:
44
46
  |---------|--------|------------|
45
47
  | Bug/error in existing code | Fix → verify → note in result | Auto |
46
48
  | Missing import/dependency | Add → verify → note in result | Auto |
47
- | Architectural change needed | STOPreport in ERROR field | Ask user |
49
+ | Missing validation/auth/logging | Addverify → note in result | Auto |
50
+ | Blocking issue (prevents task completion) | Fix → verify → note in result | Auto |
51
+ | Architectural change needed (new DB table, schema change, service switch) | STOP → report in ERROR field | Ask user |
52
+ | Auth error ("401", "Not authenticated", "Set ENV_VAR") | STOP → report as AUTH_GATE in ERROR | Ask user |
53
+
54
+ **Priority:** Architectural/Auth (ask) > Auto-fix rules > Unsure (treat as architectural, ask)
55
+
56
+ **3-attempt limit:** If you have attempted 3 auto-fixes on a SINGLE issue and it still fails, STOP. Report the issue in the ERROR field with `ATTEMPTS_EXHAUSTED: {description}`. Do not keep trying — the orchestrator will handle it.
48
57
  </deviation-rules>
@@ -3,7 +3,6 @@ name: 5:address-review-findings
3
3
  description: Applies annotated review findings and/or addresses GitHub PR review comments. Use --github to process PR comments only.
4
4
  allowed-tools: Bash, Read, Edit, Write, Glob, Grep, AskUserQuestion, Task, Skill, mcp__jetbrains__*
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: sonnet
8
7
  context: fork
9
8
  ---
@@ -3,7 +3,6 @@ name: 5:configure
3
3
  description: Configures the project. Analyzes project, gathers preferences, writes config.json, and creates feature spec for remaining setup. Follow up with /5:plan-implementation CONFIGURE.
4
4
  allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: opus
8
7
  context: fork
9
8
  ---
@@ -212,6 +211,11 @@ The skill-creator plugin from the official Claude store helps generate higher-qu
212
211
  - "Generate/update CLAUDE.md? This will analyze your codebase to document structure and conventions."
213
212
  - Options: "Yes (recommended)", "Skip"
214
213
 
214
+ **2k2. Confirm rules generation:**
215
+ - "Generate `.claude/rules/` files? These are scoped instruction files that automatically load when Claude works with matching file types (e.g., testing rules load only when editing test files, code-style rules load only for source files)."
216
+ - Options: "Yes (recommended)", "Skip"
217
+ - Note: Rules complement CLAUDE.md — they provide focused, file-type-scoped directives derived from your project's actual conventions.
218
+
215
219
  **2l. Review detected patterns for skill generation:**
216
220
 
217
221
  Present ONLY patterns that were actually detected in steps 1g and 1h.
@@ -271,7 +275,7 @@ Using the values gathered from Steps 1 and 2, write `.5/config.json` directly.
271
275
  mkdir -p .5
272
276
  ```
273
277
 
274
- **Schema:** Read `.claude/references/configure-tables.md` section "Config Schema" for the full JSON structure. Fill all values from user responses. Write with pretty-printed JSON. Read back to verify correctness.
278
+ **Schema:** Read `.claude/references/configure-tables.md` section "Config Schema" for the full JSON structure. Fill all values from user responses (including `rules.generate` from step 2k2). Write with pretty-printed JSON. Read back to verify correctness.
275
279
 
276
280
  **Update `.5/version.json` with configure timestamp:**
277
281
 
@@ -348,6 +352,15 @@ Analyze the codebase and generate modular documentation:
348
352
 
349
353
  Include only patterns/commands where user selected "Generate".
350
354
 
355
+ ### Requirement 3: Generate Scoped Rules (if selected)
356
+ Generate `.claude/rules/` files with project-specific conventions scoped to relevant file types.
357
+ Rules are concise directives (15-40 lines, NOT documentation) derived from codebase analysis.
358
+ Only generate rules for patterns that were actually detected:
359
+ - `code-style.md` — naming, formatting, import conventions (scoped to source files)
360
+ - `testing.md` — test patterns, mocking, fixtures (scoped to test files)
361
+ - `api-patterns.md` — API conventions, error handling (scoped to API/route/controller files)
362
+ - `dependencies.md` — dependency usage patterns, env var conventions (unconditional)
363
+
351
364
  ## Acceptance Criteria
352
365
  - [ ] `.5/` directory created
353
366
  - [ ] All 7 documentation files exist and are populated:
@@ -364,6 +377,10 @@ Include only patterns/commands where user selected "Generate".
364
377
  - [ ] All specified project-specific skills are generated in `.claude/skills/`
365
378
  - [ ] Generated skills reference actual project conventions
366
379
  - [ ] If CLAUDE.md existed before, user-written sections are preserved
380
+ - [ ] `.claude/rules/` directory exists with scoped rule files (if rules generation selected)
381
+ - [ ] Generated rules use `paths:` frontmatter for scoping where applicable
382
+ - [ ] Rules contain concise directives, not documentation
383
+ - [ ] No rules generated for undetected patterns
367
384
  ```
368
385
 
369
386
  **Important:** Use `mkdir -p .5/features/CONFIGURE` before writing the feature spec.
@@ -3,7 +3,6 @@ name: 5:discuss-feature
3
3
  description: Discusses and refines an existing feature specification through iterative Q&A. Use after /plan-feature when requirements need clarification or changes. Updates the feature spec based on discussion.
4
4
  allowed-tools: Read, Write, Glob, Grep, Task, AskUserQuestion
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: opus
8
7
  context: inherit
9
8
  ---
@@ -3,7 +3,6 @@ name: 5:implement-feature
3
3
  description: Executes an implementation plan by delegating to agents. Phase 3 of the 5-phase workflow.
4
4
  allowed-tools: Task, Read, Write, Glob, Grep, Bash, TaskCreate, TaskUpdate, TaskList
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: opus
8
7
  context: fork
9
8
  ---
@@ -35,6 +34,15 @@ You are a thin orchestrator:
35
34
  - State is the source of truth: write it before moving on
36
35
  - Forward progress: failed components are logged, not blocking
37
36
  - Resumable: state enables restart from any interrupted step
37
+ - Context budget: keep orchestrator lean — delegate ALL implementation to agents
38
+
39
+ **Context Budget Rules:**
40
+ Your context window is shared across all steps. To avoid running out of context on large features:
41
+ - NEVER read source files yourself — that's the executor agent's job
42
+ - NEVER paste full agent outputs into your reasoning — extract only the `---RESULT---` block
43
+ - Keep state.json updates minimal — write only changed fields
44
+ - If an agent returns a very long response, parse the RESULT block and discard the rest
45
+ - For features with 10+ components: after processing each step's results, summarize the step outcome in one line and move on. Do NOT accumulate detailed logs across steps.
38
46
 
39
47
  **State verification rule:** After every state.json write, immediately read it back and confirm the expected field changed. If verification fails, stop with an error message. This applies to every state write below — marked as **(verify write)**.
40
48
 
@@ -99,6 +107,37 @@ Then remove the planning guard marker (planning is over, implementation is start
99
107
  rm -f .5/.planning-active
100
108
  ```
101
109
 
110
+ ### Step 2c: Regression Baseline
111
+
112
+ Before spawning any agents, establish a baseline by running the project's build and test commands:
113
+
114
+ ```bash
115
+ # Build command from plan (or auto-detect)
116
+ {build-command}
117
+
118
+ # Test command from plan (or auto-detect)
119
+ {test-command}
120
+ ```
121
+
122
+ Record the results in state.json as `baseline`:
123
+ ```json
124
+ {
125
+ "baseline": {
126
+ "buildStatus": "success|failed",
127
+ "testStatus": "success|failed|skipped",
128
+ "checkedAt": "{ISO-timestamp}"
129
+ }
130
+ }
131
+ ```
132
+
133
+ **(verify write)** — confirm `baseline.checkedAt` is set.
134
+
135
+ **If the baseline build fails:** Warn the user: `"⚠ Build fails BEFORE implementation. Any post-implementation build failures may be pre-existing."` Continue — don't block on pre-existing failures.
136
+
137
+ **If baseline tests fail:** Warn the user: `"⚠ {N} tests fail BEFORE implementation. These will be excluded from regression comparison."` Record the failing test names/patterns if available, so Step 4 can distinguish pre-existing failures from new ones.
138
+
139
+ This baseline enables Step 4 to detect regressions: tests that passed before but fail after implementation.
140
+
102
141
  ### Step 2b: Create Progress Checklist
103
142
 
104
143
  Before executing any steps, create one TaskCreate entry per step:
@@ -115,6 +154,19 @@ Then mark the task for Step 1 as `in_progress`.
115
154
 
116
155
  Group components by step number from the plan. For each step (starting from `currentStep` in state.json):
117
156
 
157
+ **3pre. Pre-step dependency check (steps 2+)**
158
+
159
+ Before executing step N (where N > 1), verify that prior steps' outputs exist on disk:
160
+
161
+ 1. For each component in `completedComponents` from prior steps: use Glob to confirm every file in `filesCreated` and `filesModified` still exists
162
+ 2. If ANY file is missing:
163
+ - Log: `"⚠ Pre-step check: {file} from step {M} component {name} not found on disk"`
164
+ - Move the component back from `completedComponents` to `pendingComponents`
165
+ - STOP execution for this step. Report to user: `"Step {N} blocked: prior step output missing. Re-run step {M} or fix manually."`
166
+ 3. If all files verified, proceed to 3a
167
+
168
+ This prevents cascading failures where step N assumes step N-1's outputs exist but they don't.
169
+
118
170
  **3a. Analyze step for parallel execution**
119
171
 
120
172
  Components within the same step are independent by design. For steps with multiple components:
@@ -145,7 +197,13 @@ Task tool call:
145
197
 
146
198
  ## Feature: {feature-name}
147
199
  ## Components
148
- {component(s) from plan table: name, action, file, description}
200
+ {component(s) from plan table: name, action, file, description, complexity}
201
+
202
+ ## Read First
203
+ {Pattern File value(s) from plan table — executor MUST read these before writing any code}
204
+
205
+ ## Verify
206
+ {Verify command(s) from plan table — executor runs these after implementation}
149
207
 
150
208
  ## Implementation Notes
151
209
  {relevant notes from plan}
@@ -153,9 +211,9 @@ Task tool call:
153
211
 
154
212
  The agent file defines the implementation process, output format, and deviation rules. If the agent file is not found (local install), fall back to `.claude/agents/component-executor.md` relative to the project root.
155
213
 
156
- **3d. Process results**
214
+ **3d. Process results (context-lean)**
157
215
 
158
- Collect results from all agents (parallel or sequential). Parse the `---RESULT---` block from each agent's response. For each:
216
+ Collect results from all agents (parallel or sequential). Parse ONLY the `---RESULT---` block from each agent's response — do NOT retain the full agent output in your context. For each:
159
217
  - If `STATUS: success` → component succeeded; note files from `FILES_CREATED`/`FILES_MODIFIED`
160
218
  - If `STATUS: failed` → component failed; log the `ERROR` message
161
219
  - If no `---RESULT---` block found → treat as success if the agent reported creating/modifying files, otherwise treat as failed
@@ -251,8 +309,13 @@ For each non-test component with action "create" that contains logic:
251
309
  **(verify write)** — confirm `verificationResults.builtAt` is set.
252
310
 
253
311
  If build or tests fail:
312
+ - Compare against `baseline` in state.json:
313
+ - If build failed in baseline AND still fails → report as `"Pre-existing build failure (not a regression)"`
314
+ - If build passed in baseline BUT fails now → report as `"⚠ REGRESSION: Build broke during implementation"`
315
+ - If tests that passed in baseline now fail → report as `"⚠ REGRESSION: {N} tests broke during implementation: {test names}"`
316
+ - If tests that failed in baseline still fail → report as `"Pre-existing test failure (not a regression)"`
254
317
  - Record in state.json
255
- - Report to user with error details
318
+ - Report to user with error details and regression classification
256
319
 
257
320
  Mark the "Run verification" TaskCreate task as `completed`.
258
321
 
@@ -3,7 +3,6 @@ name: 5:plan-feature
3
3
  description: Plans feature implementation by analyzing requirements, identifying affected modules, and creating a structured feature specification. Use at the start of any new feature to ensure systematic implementation. This is Phase 1 of the 5-phase workflow.
4
4
  allowed-tools: Read, Write, Task, AskUserQuestion
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: opus
8
7
  context: fork
9
8
  ---
@@ -22,6 +21,8 @@ HARD CONSTRAINTS — violations waste tokens and get blocked by plan-guard:
22
21
  - NEVER spawn Task agents with subagent_type other than Explore
23
22
  - NEVER write to any file except .5/features/{name}/feature.md (where {name} may include a ticket prefix) and .5/.planning-active
24
23
  - NEVER call EnterPlanMode — the workflow has its own planning process
24
+ - NEVER use Bash to create, write, or modify files — this bypasses the plan-guard and is a constraint violation
25
+ - NEVER continue past the completion message — when you output "Feature spec created at...", you are DONE
25
26
  - The feature spec describes WHAT and WHY, never HOW
26
27
  - If you feel the urge to implement, STOP and ask a clarifying question instead
27
28
  - Your output is a SPECIFICATION, not a design document. No code. No file layouts. No API shapes.
@@ -30,7 +31,8 @@ HARD CONSTRAINTS — violations waste tokens and get blocked by plan-guard:
30
31
  <write-rules>
31
32
  You have access to the Write tool for exactly these files:
32
33
  1. `.5/.planning-active` — Step 0 only
33
- 2. `.5/features/{name}/feature.md` — Step 4 only
34
+ 2. `.5/features/{name}/codebase-scan.md` — Step 2 only (Explore agent results cache)
35
+ 3. `.5/features/{name}/feature.md` — Step 4 only
34
36
  Any other Write target WILL be blocked by the plan-guard hook. Do not attempt it.
35
37
  </write-rules>
36
38
 
@@ -63,6 +65,20 @@ testing strategy, integration points (from findings), alternative approaches, co
63
65
 
64
66
  # Plan Feature (Phase 1)
65
67
 
68
+ ## Progress Checklist
69
+
70
+ Follow these steps IN ORDER. Do NOT skip steps. Do NOT proceed to a later step until the current one is complete. After completing each step, output a status line: `✓ Step N complete`.
71
+
72
+ - [ ] Step 0: Activate planning guard — write `.5/.planning-active`
73
+ - [ ] Step 1: Gather feature description — ask developer via AskUserQuestion
74
+ - [ ] Step 2: Explore codebase — spawn Explore sub-agent, wait for results, cache to codebase-scan.md
75
+ - [ ] Step 3: Ask 5+ clarifying questions — one at a time, minimum 5 before proceeding
76
+ - [ ] Step 3b: Pre-write checkpoint — verify ≥5 Q&A pairs exist, no code in spec
77
+ - [ ] Step 4: Write feature specification — create `.5/features/{name}/feature.md`
78
+ - [ ] Output completion message and STOP
79
+
80
+ > **MANDATORY:** After each step, output `✓ Step N complete` before moving on. This is your progress anchor — if you cannot say which step you just completed, you are skipping ahead. If Step 3b fails (< 5 Q&A), return to Step 3.
81
+
66
82
  ## Process
67
83
 
68
84
  ### Step 0: Activate Planning Guard
@@ -82,17 +98,19 @@ This activates the plan-guard hook which prevents accidental source file edits d
82
98
 
83
99
  Ask the developer for the feature description using AskUserQuestion:
84
100
 
85
- "Please describe the feature you want to develop. Paste the full ticket description or explain it in your own words."
101
+ "Please describe the feature you want to specify. Paste the full ticket description or explain it in your own words."
86
102
 
87
103
  - Expect free-text answer, do NOT provide options
88
104
  - Do NOT ask follow-up questions yet
89
105
 
90
106
  ### Step 2: Spawn Explore Agent for Codebase Analysis
91
107
 
108
+ > **ROLE CHECK:** You are a Feature Planner. Your ONLY output is feature.md. If you are tempted to write code or create files, STOP and return to the next question in Step 3.
109
+
92
110
  Spawn a Task with `subagent_type=Explore`:
93
111
 
94
112
  ```
95
- Analyze the codebase for a feature planning session.
113
+ Analyze the codebase for a feature specification session.
96
114
 
97
115
  **Feature Description:** {paste the user's feature description}
98
116
 
@@ -118,7 +136,11 @@ Analyze the codebase for a feature planning session.
118
136
 
119
137
  Wait for the sub-agent to return before proceeding.
120
138
 
121
- ### Step 3: Intensive Q&A (5-10 Questions, One at a Time)
139
+ **Cache the results:** Write the Explore agent's full output to `.5/features/{name}/codebase-scan.md` using the Write tool. This saves Phase 2 from re-scanning the same codebase and saves significant tokens.
140
+
141
+ ### Step 3: Intensive Q&A
142
+
143
+ > **ROLE CHECK:** You are gathering requirements, NOT designing solutions. Questions ask WHAT and WHY, never HOW.
122
144
 
123
145
  Ask 5-10 clarifying questions using AskUserQuestion. ONE question at a time — wait for the answer before asking the next. Use the sub-agent findings to inform questions. Cover: requirements clarity, scope boundaries, edge cases, performance expectations, testing strategy, integration points, alternative approaches, and complexity trade-offs. Challenge assumptions: "Is this the simplest solution?", "Could we reuse existing X?", "What happens when Y fails?"
124
146
 
@@ -141,6 +163,8 @@ If you have fewer than 5 Q&A pairs, go back to Step 3 and ask more questions.
141
163
 
142
164
  ### Step 4: Create Feature Specification
143
165
 
166
+ > **ROLE CHECK:** You are writing a SPECIFICATION (WHAT/WHY), not a design document (HOW). Zero code, zero file paths to create, zero signatures. After writing feature.md you are DONE — do NOT proceed to implementation planning or coding.
167
+
144
168
  **Extract ticket ID from git branch:**
145
169
  - The Explore agent from Step 2 already ran `git branch --show-current` — find the branch name in its results
146
170
  - Use the configurable ticket pattern from `.5/config.json` (e.g., `PROJ-\d+`) to extract the ticket ID from the branch name
@@ -163,7 +187,13 @@ Populate all sections:
163
187
  - Affected Components (from exploration)
164
188
  - Acceptance Criteria
165
189
  - Alternatives Considered
166
- - Questions & Answers (from Q&A session)
190
+ - Decisions (from Q&A session) — label each with **[DECIDED]**, **[FLEXIBLE]**, or **[DEFERRED]**
191
+
192
+ **Decision labeling rules:**
193
+ - **[DECIDED]**: The user gave a clear, specific answer → Phase 2 planner and Phase 3 agents MUST honor exactly
194
+ - **[FLEXIBLE]**: The user said "up to you", "whatever works", or didn't express a strong preference → planner chooses
195
+ - **[DEFERRED]**: The user explicitly said "not now", "later", "skip this" → planner MUST NOT include in the plan
196
+ - When in doubt, label as **[DECIDED]** — it's safer to honor a decision than to override it
167
197
 
168
198
  ## PLANNING COMPLETE
169
199
 
@@ -3,7 +3,6 @@ name: 5:plan-implementation
3
3
  description: Creates an implementation plan from a feature spec. Phase 2 of the 5-phase workflow.
4
4
  allowed-tools: Read, Write, Task, AskUserQuestion
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: opus
8
7
  context: fork
9
8
  ---
@@ -21,8 +20,12 @@ HARD CONSTRAINTS — violations get blocked by plan-guard:
21
20
  - NEVER create source files — you create ONE file: plan.md
22
21
  - NEVER call EnterPlanMode — the workflow has its own planning process
23
22
  - NEVER spawn Task agents with subagent_type other than Explore
23
+ - NEVER use Bash to create, write, or modify files — this bypasses the plan-guard and is a constraint violation
24
+ - NEVER continue past the completion message — when you output "Plan created at...", you are DONE
24
25
  - The plan describes WHAT to build and WHERE. Agents figure out HOW by reading existing code.
25
- - Each component in the table gets: name, action, file path, one-sentence description, complexity
26
+ - Each component in the table gets: name, action, file path, one-sentence description, pattern file, verify command, complexity
27
+ - **Pattern File** (required for "create" actions): Path to an existing file the executor reads before implementing. For "modify" actions, this is the target file itself. Helps executor match conventions exactly.
28
+ - **Verify** (required): A concrete command or grep check the executor runs after implementing. Examples: `grep -q 'export class UserService' src/services/user.service.ts`, `npm test -- --testPathPattern=user`, `npx tsc --noEmit`. Never use vague checks like "works correctly".
26
29
  - If a component needs more than one sentence to describe, split it into multiple components
27
30
  - Implementation Notes reference EXISTING pattern files, not new code
28
31
  - Every component with action "create" that contains logic (services, controllers, repositories, hooks, utilities, helpers) MUST have a corresponding test component. Declarative components (types, interfaces, models without logic, route registrations, config files) are exempt. When uncertain, include the test.
@@ -31,7 +34,8 @@ HARD CONSTRAINTS — violations get blocked by plan-guard:
31
34
  <write-rules>
32
35
  You have access to the Write tool for exactly these files:
33
36
  1. `.5/.planning-active` — Step 0 only
34
- 2. `.5/features/{name}/plan.md` — Step 5 only
37
+ 2. `.5/features/{name}/codebase-scan.md` — Step 2 only (if fresh scan was needed)
38
+ 3. `.5/features/{name}/plan.md` — Step 5 only
35
39
  Any other Write target WILL be blocked by the plan-guard hook. Do not attempt it.
36
40
  </write-rules>
37
41
 
@@ -58,6 +62,22 @@ Assign complexity per component using this rubric:
58
62
 
59
63
  # Plan Implementation (Phase 2)
60
64
 
65
+ ## Progress Checklist
66
+
67
+ Follow these steps IN ORDER. Do NOT skip steps. Do NOT proceed to a later step until the current one is complete. After completing each step, output a status line: `✓ Step N complete`.
68
+
69
+ - [ ] Step 0: Activate planning guard — write `.5/.planning-active`
70
+ - [ ] Step 1: Load feature spec — read `.5/features/{name}/feature.md`
71
+ - [ ] Step 1b: Load project configuration — read `.5/config.json` if it exists
72
+ - [ ] Step 2: Load or generate codebase scan — reuse cached scan from Phase 1, or spawn Explore if missing
73
+ - [ ] Step 3: Ask 2-3 technical questions — one at a time via AskUserQuestion
74
+ - [ ] Step 4: Design components — identify files, order, step grouping
75
+ - [ ] Step 5: Write the plan — create `.5/features/{name}/plan.md`
76
+ - [ ] Step 5b: Plan self-check — verify format, no code, scope, completeness, tests
77
+ - [ ] Output completion message and STOP
78
+
79
+ > **MANDATORY:** After each step, output `✓ Step N complete` before moving on. This is your progress anchor — if you cannot say which step you just completed, you are skipping ahead. If Step 5b fails, fix plan.md before outputting completion.
80
+
61
81
  ## Output Format
62
82
 
63
83
  Read the plan template at `.claude/templates/workflow/PLAN.md` for the exact structure and rules. Your output must follow that template precisely — fill in the placeholders with real values from the feature spec and codebase scan.
@@ -82,7 +102,12 @@ This activates (or refreshes) the plan-guard hook which prevents accidental sour
82
102
 
83
103
  Read `.5/features/{feature-name}/feature.md` (where `{feature-name}` is the argument provided).
84
104
 
85
- Extract: Ticket ID, requirements (functional and non-functional), acceptance criteria, affected components.
105
+ Extract: Ticket ID, requirements (functional and non-functional), acceptance criteria, affected components, and **decisions**.
106
+
107
+ **Decision labels from feature spec:**
108
+ - **[DECIDED]** items are locked — your plan MUST honor them exactly. Do not override or reinterpret.
109
+ - **[FLEXIBLE]** items are your discretion — choose the best approach based on codebase patterns.
110
+ - **[DEFERRED]** items are out of scope — do NOT plan components for them. If a deferred item is needed as a dependency, flag it in Implementation Notes.
86
111
 
87
112
  If the file doesn't exist, tell the user to run `/5:plan-feature` first.
88
113
 
@@ -95,7 +120,15 @@ Read `.5/config.json` if it exists. Extract:
95
120
 
96
121
  If config.json doesn't exist, proceed without it.
97
122
 
98
- ### Step 2: Spawn Explore Agent for Codebase Scan
123
+ ### Step 2: Load or Generate Codebase Scan
124
+
125
+ > **ROLE CHECK:** You are an Implementation Planner. Your ONLY output is plan.md. You do NOT write code, create source files, or start implementation. If you feel the urge to implement, STOP — that is Phase 3's job.
126
+
127
+ **First, check for a cached scan from Phase 1:**
128
+
129
+ Read `.5/features/{feature-name}/codebase-scan.md`. If it exists and is non-empty, use it as the codebase scan results. This was generated during Phase 1 (`/5:plan-feature`) and contains project structure, naming conventions, pattern files, and test framework detection.
130
+
131
+ **If `codebase-scan.md` does NOT exist** (e.g., user skipped Phase 1 or ran an older version), spawn a fresh Explore agent:
99
132
 
100
133
  Spawn a Task with `subagent_type=Explore`:
101
134
 
@@ -136,6 +169,8 @@ Focus scan on {projectType}-relevant directories and patterns.
136
169
 
137
170
  Wait for the sub-agent to return before proceeding.
138
171
 
172
+ **If a fresh scan was spawned**, write the results to `.5/features/{feature-name}/codebase-scan.md` for future reference.
173
+
139
174
  ### Step 3: Ask 2-3 Technical Questions (One at a Time)
140
175
 
141
176
  Use AskUserQuestion to clarify:
@@ -159,6 +194,8 @@ Targeted scan for implementation planning.
159
194
 
160
195
  ### Step 4: Design Components
161
196
 
197
+ > **ROLE CHECK:** You are identifying WHAT and WHERE — component names, actions, file paths, one-sentence descriptions. You are NOT writing code, pseudo-code, or implementation details. The HOW is figured out by Phase 3 agents reading existing code.
198
+
162
199
  Based on feature spec and codebase scan, identify:
163
200
  - Files to create
164
201
  - Files to modify
@@ -195,6 +232,8 @@ Not every feature needs all non-test steps. Use what makes sense. But testable c
195
232
 
196
233
  ### Step 5: Write the Plan
197
234
 
235
+ > **ROLE CHECK:** You are writing plan.md — a components table with descriptions, NOT code. After writing and verifying, output the completion message and STOP. Do NOT continue to implementation.
236
+
198
237
  Create a single file at `.5/features/{feature-name}/plan.md`.
199
238
 
200
239
  Include:
@@ -212,22 +251,26 @@ Include:
212
251
 
213
252
  Read plan.md back and verify:
214
253
 
215
- 1. **Format:** Every row in the Components table has all 6 columns filled
254
+ 1. **Format:** Every row in the Components table has all 8 columns filled (Step, Component, Action, File, Description, Pattern File, Verify, Complexity)
216
255
  2. **No code:** Implementation Notes contain ONLY references to existing files and business rules
217
256
  3. **Scope:** Every component traces back to a requirement in feature.md — if not, remove it
218
257
  4. **Completeness:** Every functional requirement from feature.md has at least one component
219
258
  5. **Description length:** Each Description cell is one sentence. If longer, split the component.
220
- 6. **Unit test coverage:** Every "create" component with logic has a corresponding unit test component. Declarative-only components (types, interfaces, route wiring) are exempt.
221
- 7. **Integration/e2e coverage:** If the explore agent detected integration or e2e frameworks AND the feature touches endpoints or cross-module flows, verify at least one integration or e2e test component is planned.
259
+ 6. **Pattern files:** Every "create" component has a Pattern File pointing to an existing file. Verify these files exist via Glob.
260
+ 7. **Verify commands:** Every component has a concrete Verify command (grep, test, build). No vague checks.
261
+ 8. **Unit test coverage:** Every "create" component with logic has a corresponding unit test component. Declarative-only components (types, interfaces, route wiring) are exempt.
262
+ 9. **Integration/e2e coverage:** If the explore agent detected integration or e2e frameworks AND the feature touches endpoints or cross-module flows, verify at least one integration or e2e test component is planned.
222
263
 
223
264
  Output the verification result:
224
265
  ```
225
266
  Plan self-check:
226
- - Format: pass/fail
267
+ - Format (8 columns): pass/fail
227
268
  - No code: pass/fail
228
269
  - Scope: pass/fail
229
270
  - Completeness: pass/fail
230
271
  - Description length: pass/fail
272
+ - Pattern files exist: pass/fail
273
+ - Verify commands concrete: pass/fail
231
274
  - Unit test coverage: pass/fail
232
275
  - Integration/e2e coverage: pass/fail/n-a
233
276
  ```
@@ -3,7 +3,6 @@ name: 5:quick-implement
3
3
  description: Execute small, focused implementations quickly with state tracking and atomic commits. Skips extensive planning phases and verification agents - use for tasks where you know exactly what to do.
4
4
  allowed-tools: Read, Write, Edit, Glob, Grep, Bash, Task, AskUserQuestion, Skill, TaskCreate, TaskUpdate, TaskList, mcp__jetbrains__*
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  context: fork
8
7
  ---
9
8
 
@@ -25,6 +24,7 @@ Fast path for small, well-understood tasks (1-5 files). Skips extensive planning
25
24
  Your job in this command:
26
25
  ✅ Get task description
27
26
  ✅ Extract ticket ID
27
+ ✅ Scope check (>5 files or >3 modules → redirect to full workflow)
28
28
  ✅ Create quick plan (max 5 components)
29
29
  ✅ Get user approval on plan
30
30
  ✅ Initialize state tracking
@@ -90,12 +90,23 @@ Check if `.5/features/${feature_name}/state.json` already exists:
90
90
  - If Resume: skip Steps 4–7 initialization; go directly to Step 7b (recreate TaskCreate tasks) and Step 8 (resume remaining `pendingComponents`)
91
91
  - If Restart: delete state.json, proceed normally from Step 4
92
92
 
93
- ### Step 4: Analyze and Plan
93
+ ### Step 4: Analyze and Scope Check
94
94
 
95
95
  1. **Identify affected files** using Glob and Grep
96
96
  2. **Determine skills needed** based on task type
97
97
  3. **List components** (max 5 for quick mode)
98
98
 
99
+ **Scope gate — check BEFORE planning:**
100
+
101
+ Count the number of files that will be created or modified and the number of distinct modules/directories involved. Apply these rules:
102
+
103
+ - **>5 files** → STOP. Tell the user: `"This task affects {N} files, which exceeds quick-implement's scope (max 5). Use the full workflow instead: /5:plan-feature"`. Do NOT continue.
104
+ - **>3 distinct modules/directories** → STOP. Tell the user: `"This task spans {N} modules ({list}), which is too broad for quick-implement. Use the full workflow: /5:plan-feature"`. Do NOT continue.
105
+ - **Involves database schema changes, new API endpoints with auth, or architectural decisions** → STOP. Tell the user: `"This task involves {reason}, which needs proper planning. Use: /5:plan-feature"`. Do NOT continue.
106
+ - **≤5 files AND ≤3 modules AND no architectural changes** → Proceed to Step 5.
107
+
108
+ This gate prevents quick-implement from being used for tasks that should go through full planning, where the absence of a feature spec and structured plan leads to poor results.
109
+
99
110
  **If unclear about implementation details**, ask 2-3 focused questions using AskUserQuestion:
100
111
  - What validation rules apply?
101
112
  - Which existing patterns to follow?
@@ -3,7 +3,6 @@ name: 5:reconfigure
3
3
  description: Lightweight refresh of project documentation and skills without full Q&A. Re-detects codebase changes, regenerates .5/*.md docs, updates CLAUDE.md, and refreshes all skills.
4
4
  allowed-tools: Read, Write, Bash, Glob, Grep, Task, AskUserQuestion
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  context: fork
8
7
  ---
9
8
 
@@ -91,6 +90,11 @@ Perform the same detection as configure Steps 1b-1h:
91
90
  - Read each skill's SKILL.md frontmatter
92
91
  - Categorize as workflow-generated (create-*, run-*) or user-created
93
92
 
93
+ **2f. Scan existing rules** — list ALL rule files in `.claude/rules/`:
94
+ - Read each `.md` file
95
+ - Note which are workflow-generated (code-style, testing, api-patterns, dependencies) vs user-created
96
+ - User-created rules are never modified or removed
97
+
94
98
  ### Step 3: Compare and Prepare Summary
95
99
 
96
100
  Use the existing skills in `.claude/skills/` (from Step 2e) as the source of truth — not config.json. Compare what's installed with what's detected in the codebase:
@@ -103,14 +107,22 @@ Use the existing skills in `.claude/skills/` (from Step 2e) as the source of tru
103
107
  - **Stale commands**: a `run-*` skill exists but the command is no longer detected → offer to remove or keep
104
108
  - **User-created skills** (not matching `create-*` or `run-*` naming) → always refresh with current conventions, never remove
105
109
 
110
+ **Rules comparison** (if `rules.generate` is `true` in config.json):
111
+ - **Existing workflow rules** (from Step 2f) — code-style, testing, api-patterns, dependencies
112
+ - **Stale rules**: a workflow rule exists but its prerequisite patterns are no longer detected → offer to remove
113
+ - **New rules**: patterns detected that could benefit from a rule but none exists yet → offer to create
114
+ - **User-created rules** → never modify or remove
115
+
106
116
  ### Step 4: Confirm with User
107
117
 
108
118
  Use `AskUserQuestion` to show a summary and get confirmation. Present:
109
119
 
110
120
  1. **Documentation files that will be rewritten** — list all 7 `.5/*.md` files + CLAUDE.md
111
121
  2. **Skills that will be refreshed** — list ALL skills found in `.claude/skills/` (both workflow-generated and user-created)
112
- 3. **New patterns detected** (if any) — "These patterns were found in your codebase but don't have skills yet: [list]. Create skills for them?"
113
- 4. **Stale patterns** (if any) — "These patterns are in your config but weren't found in the codebase: [list]. Remove them?"
122
+ 3. **Rules that will be refreshed** (if rules enabled) — list workflow-generated rule files in `.claude/rules/`
123
+ 4. **New patterns detected** (if any) — "These patterns were found in your codebase but don't have skills yet: [list]. Create skills for them?"
124
+ 5. **Stale patterns** (if any) — "These patterns are in your config but weren't found in the codebase: [list]. Remove them?"
125
+ 6. **Stale rules** (if any) — "These rule files no longer have matching patterns in the codebase: [list]. Remove them?"
114
126
 
115
127
  Options:
116
128
  - "Proceed with refresh" — regenerate everything as shown
@@ -134,12 +146,20 @@ Refresh ALL existing skills in .claude/skills/:
134
146
  - New skills to create: [list from user confirmation, if any]
135
147
  - Skills to remove: [list from user confirmation, if any]
136
148
 
149
+ Refresh rules in .claude/rules/ (if rules.generate is true):
150
+ - Existing workflow rules: [list from Step 2f]
151
+ - Rules to remove: [list from user confirmation, if any]
152
+ - New rules to create: [if applicable]
153
+
137
154
  Re-analyze the entire codebase (A1 analysis) and:
138
155
  1. Rewrite all 7 .5/*.md documentation files
139
156
  2. Update CLAUDE.md (preserve user-written sections)
140
157
  3. Refresh ALL skills in .claude/skills/ — read current conventions from codebase and update each skill
141
158
  4. Create new skills for newly-added patterns
142
- 5. Remove skills the user chose to drop"
159
+ 5. Remove skills the user chose to drop
160
+ 6. Refresh all workflow-generated rule files in .claude/rules/ with updated conventions
161
+ 7. Create new rule files for newly-detected patterns
162
+ 8. Remove rule files the user chose to drop"
143
163
  ```
144
164
 
145
165
  Use `subagent_type: "general-purpose"` for the Task.
@@ -167,6 +187,9 @@ Show the user a summary:
167
187
  - List of skills refreshed
168
188
  - List of new skills created (if any)
169
189
  - List of skills removed (if any)
190
+ - List of rules refreshed (if any)
191
+ - List of new rules created (if any)
192
+ - List of rules removed (if any)
170
193
  - Timestamp of reconfiguration
171
194
  - Suggest running `/clear` to reset context
172
195
 
@@ -3,7 +3,6 @@ name: 5:review-code
3
3
  description: Reviews code changes using Claude (built-in) or CodeRabbit CLI. Categorizes findings and saves them for /5:address-review-findings.
4
4
  allowed-tools: Bash, Read, Glob, Grep, AskUserQuestion, Task, mcp__jetbrains__*
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: sonnet
8
7
  context: fork
9
8
  ---
@@ -3,7 +3,6 @@ name: 5:unlock
3
3
  description: Remove the planning guard lock to allow edits outside the workflow
4
4
  allowed-tools: Bash
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  context: inherit
8
7
  ---
9
8
 
@@ -3,7 +3,6 @@ name: 5:update
3
3
  description: Update the 5-Phase Workflow to the latest version
4
4
  allowed-tools: Bash, Read, AskUserQuestion
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: haiku
8
7
  context: fork
9
8
  ---
@@ -3,7 +3,6 @@ name: 5:verify-implementation
3
3
  description: Verifies a feature implementation is complete and working with multi-layer checks. Phase 4 of the 5-phase workflow.
4
4
  allowed-tools: Read, Glob, Grep, Bash, Write, Task, AskUserQuestion
5
5
  user-invocable: true
6
- disable-model-invocation: true
7
6
  model: sonnet
8
7
  context: fork
9
8
  ---
@@ -20,8 +20,8 @@ process.stdin.on('end', () => {
20
20
  const data = JSON.parse(input);
21
21
  const toolName = data.tool_name || '';
22
22
 
23
- // Short-circuit: only check Task, Write, Edit, and EnterPlanMode tools
24
- if (toolName !== 'Task' && toolName !== 'Write' && toolName !== 'Edit' && toolName !== 'EnterPlanMode') {
23
+ // Short-circuit: only check Task, Write, Edit, EnterPlanMode, and Bash tools
24
+ if (toolName !== 'Task' && toolName !== 'Write' && toolName !== 'Edit' && toolName !== 'EnterPlanMode' && toolName !== 'Bash') {
25
25
  process.exit(0);
26
26
  }
27
27
 
@@ -43,13 +43,15 @@ process.stdin.on('end', () => {
43
43
  // Planning mode enforcement
44
44
  if (toolName === 'EnterPlanMode') {
45
45
  const blockCount = incrementBlockCount(workspaceDir);
46
+ const phase = getPlanningPhase(workspaceDir);
46
47
  const escalation = blockCount >= 3
47
- ? ` WARNING: Block #${blockCount}. Repeated violations. Complete your planning artifact and STOP.`
48
+ ? ` CRITICAL: Block #${blockCount}. You have attempted to break out of planning ${blockCount} times. You MUST return to your current step in the Progress Checklist, complete your planning artifact, output the completion message, and STOP. Do NOT attempt any other action.`
48
49
  : '';
49
50
  process.stderr.write(
50
51
  `BLOCKED: EnterPlanMode is not allowed during workflow planning phases. ` +
51
52
  `The 5-phase workflow has its own planning process. ` +
52
- `REDIRECT: Continue with your current planning task. ` +
53
+ `REDIRECT: You are in ${phase || 'a planning phase'}. Return to your Progress Checklist. ` +
54
+ `Find the last "✓ Step N complete" you output, then continue with Step N+1. ` +
53
55
  `Write your output to .5/features/{name}/ and output the completion message when done.${escalation}`
54
56
  );
55
57
  process.exit(2);
@@ -59,13 +61,15 @@ process.stdin.on('end', () => {
59
61
  const agentType = toolInput.subagent_type || '';
60
62
  if (agentType && agentType !== 'Explore') {
61
63
  const blockCount = incrementBlockCount(workspaceDir);
64
+ const phase = getPlanningPhase(workspaceDir);
62
65
  const escalation = blockCount >= 3
63
- ? ` WARNING: Block #${blockCount}. You are repeatedly attempting actions outside your planning role. STOP. Complete your planning artifact and output the completion message.`
66
+ ? ` CRITICAL: Block #${blockCount}. You are a planner, NOT an implementer. You have attempted to spawn non-Explore agents ${blockCount} times. This is Phase 1 or 2 — implementation happens in Phase 3. Return to your Progress Checklist immediately, complete your planning artifact, and STOP.`
64
67
  : '';
65
68
  process.stderr.write(
66
69
  `BLOCKED: Only Explore agents are allowed during planning phases. ` +
67
70
  `Attempted: subagent_type="${agentType}". ` +
68
- `REDIRECT: Return to your planning process. ` +
71
+ `You are in ${phase || 'a planning phase'}. Implementation agents are Phase 3 only. ` +
72
+ `REDIRECT: Return to your Progress Checklist. Find your last "✓ Step N complete" and continue with Step N+1. ` +
69
73
  `If you need codebase information, use subagent_type=Explore. ` +
70
74
  `If you are done planning, output the completion message and STOP.${escalation}`
71
75
  );
@@ -73,17 +77,39 @@ process.stdin.on('end', () => {
73
77
  }
74
78
  }
75
79
 
80
+ if (toolName === 'Bash') {
81
+ const command = toolInput.command || '';
82
+ // Detect file-writing shell commands that bypass Write/Edit guards
83
+ const writePatterns = /\b(cat\s*>|cat\s*<<|echo\s.*>|tee\s|printf\s.*>|cp\s|mv\s|mkdir\s.*&&.*>|sed\s+-i|awk\s.*>|touch\s|install\s)/;
84
+ if (writePatterns.test(command)) {
85
+ const blockCount = incrementBlockCount(workspaceDir);
86
+ const phase = getPlanningPhase(workspaceDir);
87
+ const escalation = blockCount >= 3
88
+ ? ` CRITICAL: Block #${blockCount}. You are repeatedly attempting to write files via Bash to bypass planning guards. STOP immediately.`
89
+ : '';
90
+ process.stderr.write(
91
+ `BLOCKED: File-writing Bash commands are not allowed during planning phases. ` +
92
+ `You are in ${phase || 'a planning phase'}. ` +
93
+ `REDIRECT: Return to your Progress Checklist. Planners do not create or modify source files. ` +
94
+ `Complete your planning artifact and output the completion message.${escalation}`
95
+ );
96
+ process.exit(2);
97
+ }
98
+ }
99
+
76
100
  if (toolName === 'Write' || toolName === 'Edit') {
77
101
  const filePath = toolInput.file_path || '';
78
102
  if (filePath && !isInsideDotFive(filePath, workspaceDir)) {
79
103
  const blockCount = incrementBlockCount(workspaceDir);
104
+ const phase = getPlanningPhase(workspaceDir);
80
105
  const isSourceFile = !filePath.includes('.5/') && !filePath.includes('.claude/');
81
106
  const escalation = blockCount >= 3
82
- ? ` WARNING: Block #${blockCount}. Repeated violations. Complete your planning artifact and STOP.`
107
+ ? ` CRITICAL: Block #${blockCount}. You have attempted to write source files ${blockCount} times. You are a PLANNER, not an implementer. Writing source code is Phase 3's job. Return to your Progress Checklist, finish your planning artifact, and STOP.`
83
108
  : '';
84
109
  const redirectMsg = isSourceFile
85
- ? `REDIRECT: You are in a planning phase. You may ONLY write to .5/features/. ` +
86
- `Source file creation happens in Phase 3 (/5:implement-feature).`
110
+ ? `REDIRECT: You are in ${phase || 'a planning phase'}. You may ONLY write to .5/features/. ` +
111
+ `Source file creation happens in Phase 3 (/5:implement-feature). ` +
112
+ `Return to your Progress Checklist — find your last "✓ Step N complete" and continue with Step N+1.`
87
113
  : `REDIRECT: The path "${filePath}" is outside the allowed .5/ directory. ` +
88
114
  `Check your file path — you should be writing to .5/features/{name}/.`;
89
115
  process.stderr.write(
@@ -179,6 +205,16 @@ function incrementBlockCount(workspaceDir) {
179
205
  }
180
206
  }
181
207
 
208
+ function getPlanningPhase(workspaceDir) {
209
+ const markerPath = path.join(workspaceDir, '.5', '.planning-active');
210
+ try {
211
+ const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'));
212
+ return marker.phase || null;
213
+ } catch (e) {
214
+ return null;
215
+ }
216
+ }
217
+
182
218
  function isFeatureInImplementationMode(workspaceDir, featureName) {
183
219
  // Check if this specific feature has a state.json (created in Phase 3)
184
220
  const stateFile = path.join(
@@ -109,6 +109,9 @@ For each command found: record exact syntax, note variants (e.g., `test:unit`, `
109
109
  },
110
110
  "dotFiveFolder": {
111
111
  "gitignore": true
112
+ },
113
+ "rules": {
114
+ "generate": true
112
115
  }
113
116
  }
114
117
  ```
package/src/settings.json CHANGED
@@ -38,7 +38,7 @@
38
38
  ]
39
39
  },
40
40
  {
41
- "matcher": "Task|Write|Edit|EnterPlanMode",
41
+ "matcher": "Task|Write|Edit|EnterPlanMode|Bash",
42
42
  "hooks": [
43
43
  {
44
44
  "type": "command",
@@ -327,6 +327,97 @@ Executes the project's {command} command.
327
327
 
328
328
  ---
329
329
 
330
+ ## C. Generate Scoped Rules
331
+
332
+ If `rules.generate` is `true` in `.5/config.json`, generate `.claude/rules/` files with project-specific conventions scoped to relevant file types.
333
+
334
+ Rules are **concise directives** (15-40 lines each), NOT documentation. Documentation lives in `.5/*.md` files. Rules tell Claude what to do when working with specific file types.
335
+
336
+ ### C1. Determine Which Rules to Generate
337
+
338
+ Based on the A1 analysis results, determine which rules apply:
339
+
340
+ | Rule File | Generate When | Source Analysis |
341
+ |-----------|---------------|-----------------|
342
+ | `code-style.md` | Always (if source files exist) | Conventions Analysis |
343
+ | `testing.md` | Test files detected | Testing Analysis |
344
+ | `api-patterns.md` | Controller/route/handler patterns detected | Architecture Analysis |
345
+ | `dependencies.md` | External integrations detected | Integration Analysis |
346
+
347
+ **Skip** any rule whose prerequisite patterns were not detected. Do NOT generate empty or placeholder rule files.
348
+
349
+ ### C2. Extract Directives and Write Rules
350
+
351
+ For each applicable rule:
352
+
353
+ 1. **Derive `paths:` globs** from detected file locations (e.g., if tests are at `src/**/*.test.ts` and `tests/**/*.spec.ts`, use those patterns)
354
+ 2. **Convert analysis observations into imperative directives** — "Use X", "Always Y", "Never Z"
355
+ 3. **Keep each file 15-40 lines** — be concise and actionable
356
+ 4. **Do NOT repeat** the 6 mandatory coding guidelines from CLAUDE.md
357
+
358
+ Write files to `.claude/rules/`:
359
+
360
+ ```bash
361
+ mkdir -p .claude/rules
362
+ ```
363
+
364
+ ### C3. Rule File Format
365
+
366
+ Each rule file uses YAML frontmatter with `paths:` for scoping. Rules without `paths:` load unconditionally.
367
+
368
+ **Example — `testing.md`:**
369
+
370
+ ```markdown
371
+ ---
372
+ paths:
373
+ - "**/*.test.ts"
374
+ - "**/*.spec.ts"
375
+ ---
376
+
377
+ # Testing Conventions
378
+
379
+ - Use `describe`/`it` blocks with descriptive names
380
+ - Mock external dependencies with jest.mock, never mock internal modules
381
+ - Use factory functions from `tests/factories/` for test data
382
+ - Each test file mirrors its source file path: `src/foo/Bar.ts` → `src/foo/__tests__/Bar.test.ts`
383
+ - Assert one behavior per test
384
+ ```
385
+
386
+ **Example — `code-style.md`:**
387
+
388
+ ```markdown
389
+ ---
390
+ paths:
391
+ - "src/**/*.{ts,tsx}"
392
+ ---
393
+
394
+ # Code Style
395
+
396
+ - Use PascalCase for classes and types, camelCase for functions and variables
397
+ - Import order: external packages → internal modules → relative imports
398
+ - Use absolute imports with `@/` alias
399
+ - Prefer named exports over default exports
400
+ ```
401
+
402
+ **Example — `dependencies.md` (unconditional):**
403
+
404
+ ```markdown
405
+ # Dependency Conventions
406
+
407
+ - Database access through Prisma client only, never raw SQL
408
+ - HTTP requests use axios instance from `src/lib/http.ts`
409
+ - Environment variables accessed via `src/config/env.ts`, never `process.env` directly
410
+ ```
411
+
412
+ ### Refresh Mode Behavior for Rules
413
+
414
+ When running in REFRESH MODE:
415
+ - Re-analyze codebase and overwrite all existing rule files with updated directives
416
+ - Remove rule files for patterns no longer detected in the codebase
417
+ - Create new rule files if new patterns are detected that weren't present before
418
+
419
+ ---
420
+
330
421
  ## Output Contract
331
422
 
332
423
  Returns structured results for each component:
@@ -343,6 +434,7 @@ Component A (Documentation): SUCCESS - Created 7 documentation files + index
343
434
  - CLAUDE.md (index with references)
344
435
  Component B (Pattern Skills): SUCCESS - Generated 3 create-* skills (create-component, create-hook, create-context)
345
436
  Component C (Command Skills): SUCCESS - Generated 2 run-* skills (run-tests, run-lint)
437
+ Component D (Rules): SUCCESS - Generated 3 rule files (code-style, testing, dependencies)
346
438
  ```
347
439
 
348
440
  Or on failure:
@@ -350,6 +442,7 @@ Or on failure:
350
442
  ```
351
443
  Component A (Documentation): FAILED - Unable to read template files
352
444
  Component B (Pattern Skills): FAILED - No patterns found in codebase
445
+ Component D (Rules): SKIPPED - rules.generate is false in config
353
446
  ```
354
447
 
355
448
  ## DO NOT
@@ -357,7 +450,9 @@ Component B (Pattern Skills): FAILED - No patterns found in codebase
357
450
  - DO NOT overwrite existing user-written CLAUDE.md sections
358
451
  - DO NOT generate skills for patterns that don't exist in the project
359
452
  - DO NOT generate command skills for commands that don't exist in the project
453
+ - DO NOT generate rules for patterns not detected in the codebase
360
454
  - DO NOT include `steps` in config.json
361
455
  - DO NOT hardcode conventions - always derive from actual project analysis
362
- - DO NOT generate empty or placeholder skill files
456
+ - DO NOT generate empty or placeholder skill or rule files
363
457
  - DO NOT assume command syntax - always read from actual config files (package.json, Makefile, etc.)
458
+ - DO NOT repeat the 6 mandatory coding guidelines from CLAUDE.md in rule files
@@ -76,13 +76,22 @@
76
76
  ### Chosen Approach: {Selected approach}
77
77
  **Rationale:** {Why this approach was chosen}
78
78
 
79
- ## Questions & Answers
79
+ ## Decisions
80
+
81
+ <!-- Tag every Q&A with exactly one of: [DECIDED], [FLEXIBLE], [DEFERRED]
82
+ - [DECIDED]: Locked decision — Phase 2 planner and Phase 3 agents MUST honor exactly
83
+ - [FLEXIBLE]: Claude's discretion — planner chooses the best approach
84
+ - [DEFERRED]: Explicitly out of scope — planner MUST NOT include in the plan
85
+ -->
80
86
 
81
87
  ### Q1: {Question from collaboration phase}
82
- **A:** {Answer from developer}
88
+ **A:** {Answer from developer} **[DECIDED]**
83
89
 
84
90
  ### Q2: {Question}
85
- **A:** {Answer}
91
+ **A:** {Answer} **[FLEXIBLE]**
92
+
93
+ ### Q3: {Question about a nice-to-have}
94
+ **A:** {Answer — let's skip this for now} **[DEFERRED]**
86
95
 
87
96
  ...
88
97
 
@@ -8,6 +8,8 @@ created: {ISO-timestamp}
8
8
  <!-- PLAN RULES:
9
9
  - This file is interpolated into agent prompts. Write it as instructions, not documentation.
10
10
  - Description column: one action-oriented sentence per component
11
+ - Pattern File column: path to an existing file the executor MUST read before implementing (establishes conventions)
12
+ - Verify column: a concrete command or check the executor runs after implementing (grep pattern, test command, build check)
11
13
  - Implementation Notes: reference existing files as patterns, no code snippets
12
14
  - Components table must cover all functional requirements from feature.md
13
15
  - Three test tiers: unit (always required for logic), integration (when framework detected + cross-module/DB/API), e2e (when framework detected + endpoints/UI flows)
@@ -22,16 +24,16 @@ created: {ISO-timestamp}
22
24
 
23
25
  ## Components
24
26
 
25
- | Step | Component | Action | File | Description | Complexity |
26
- |------|-----------|--------|------|-------------|------------|
27
- | 1 | {name} | create | {path} | {what it does} | simple |
28
- | 1 | {name} | create | {path} | {what it does} | simple |
29
- | 2 | {name} | create | {path} | {what it does} | moderate |
30
- | 2 | {name} | modify | {path} | {what to change} | moderate |
31
- | 3 | {name} | create | {path} | {what it does} | complex |
32
- | 4 | {name} unit tests | create | {test-path} | Test {what it tests} | moderate |
33
- | 4 | {name} integration tests | create | {test-path} | Test {cross-module interaction} | moderate |
34
- | 4 | {name} e2e tests | create | {test-path} | Test {user-facing flow end-to-end} | moderate |
27
+ | Step | Component | Action | File | Description | Pattern File | Verify | Complexity |
28
+ |------|-----------|--------|------|-------------|-------------|--------|------------|
29
+ | 1 | {name} | create | {path} | {what it does} | {existing file to read first} | {grep/test command} | simple |
30
+ | 1 | {name} | create | {path} | {what it does} | {pattern} | {verify} | simple |
31
+ | 2 | {name} | create | {path} | {what it does} | {pattern} | {verify} | moderate |
32
+ | 2 | {name} | modify | {path} | {what to change} | {target file} | {verify} | moderate |
33
+ | 3 | {name} | create | {path} | {what it does} | {pattern} | {verify} | complex |
34
+ | 4 | {name} unit tests | create | {test-path} | Test {what it tests} | {existing test} | {test command} | moderate |
35
+ | 4 | {name} integration tests | create | {test-path} | Test {cross-module interaction} | {existing test} | {test command} | moderate |
36
+ | 4 | {name} e2e tests | create | {test-path} | Test {user-facing flow end-to-end} | {existing test} | {test command} | moderate |
35
37
 
36
38
  ## Testing Strategy
37
39