all-for-claudecode 2.13.0 → 2.14.0

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.
Files changed (72) hide show
  1. package/.claude-plugin/marketplace.json +24 -5
  2. package/.claude-plugin/plugin.json +15 -4
  3. package/README.md +12 -0
  4. package/agents/afc-appsec-expert.md +19 -26
  5. package/agents/afc-architect.md +9 -2
  6. package/agents/afc-backend-expert.md +16 -4
  7. package/agents/afc-design-expert.md +17 -7
  8. package/agents/afc-impl-worker.md +7 -1
  9. package/agents/afc-infra-expert.md +16 -6
  10. package/agents/afc-legal-expert.md +16 -18
  11. package/agents/afc-marketing-expert.md +15 -5
  12. package/agents/afc-pm-expert.md +16 -5
  13. package/agents/afc-pr-analyst.md +1 -1
  14. package/agents/afc-security.md +7 -2
  15. package/agents/afc-tech-advisor.md +18 -30
  16. package/docs/agent-authoring-guide.md +144 -0
  17. package/docs/context-management-harness.md +293 -0
  18. package/docs/orchestration-modes.md +228 -0
  19. package/docs/skill-authoring-guide.md +153 -0
  20. package/hooks/hooks.json +27 -2
  21. package/package.json +4 -3
  22. package/schemas/hooks.schema.json +1 -1
  23. package/schemas/marketplace.schema.json +6 -1
  24. package/schemas/plugin.schema.json +0 -4
  25. package/scripts/afc-pipeline-manage.sh +1 -0
  26. package/scripts/afc-post-compact.sh +54 -0
  27. package/scripts/afc-spec-guard.sh +7 -7
  28. package/scripts/afc-stop-failure.sh +46 -0
  29. package/scripts/afc-sync-cache.sh +8 -2
  30. package/scripts/afc-tdd-guard.sh +7 -5
  31. package/scripts/afc-user-prompt-submit.sh +38 -0
  32. package/scripts/pre-compact-checkpoint.sh +10 -0
  33. package/scripts/session-start-context.sh +10 -0
  34. package/skills/architect/SKILL.md +1 -9
  35. package/skills/auto/SKILL.md +228 -910
  36. package/skills/auto/skill-advisor.md +306 -0
  37. package/skills/checkpoint/SKILL.md +7 -1
  38. package/skills/clarify/SKILL.md +3 -2
  39. package/skills/consult/SKILL.md +30 -123
  40. package/skills/consult/peer-mode.md +61 -0
  41. package/skills/debug/SKILL.md +3 -21
  42. package/skills/ideate/SKILL.md +1 -77
  43. package/skills/ideate/brief-template.md +73 -0
  44. package/skills/implement/SKILL.md +68 -260
  45. package/skills/init/SKILL.md +79 -129
  46. package/skills/init/reference.md +55 -0
  47. package/skills/issue/SKILL.md +51 -76
  48. package/skills/launch/SKILL.md +5 -0
  49. package/skills/learner/SKILL.md +1 -25
  50. package/skills/learner/suggestion-format.md +49 -0
  51. package/skills/plan/SKILL.md +1 -5
  52. package/skills/pr-comment/SKILL.md +38 -51
  53. package/skills/principles/SKILL.md +3 -7
  54. package/skills/qa/SKILL.md +3 -14
  55. package/skills/release-notes/SKILL.md +6 -5
  56. package/skills/resolve/SKILL.md +75 -158
  57. package/skills/resolve/graphql.md +48 -0
  58. package/skills/resume/SKILL.md +10 -5
  59. package/skills/review/SKILL.md +56 -202
  60. package/skills/review/perspectives.md +118 -0
  61. package/skills/security/SKILL.md +4 -22
  62. package/skills/security/cross-boundary-verification.md +22 -0
  63. package/skills/setup/SKILL.md +38 -87
  64. package/skills/setup/conflict-detection.md +33 -0
  65. package/skills/spec/SKILL.md +1 -5
  66. package/skills/tasks/SKILL.md +47 -70
  67. package/skills/test/SKILL.md +4 -16
  68. package/skills/triage/SKILL.md +38 -85
  69. package/skills/triage/coupling-detection.md +13 -0
  70. package/skills/triage/pr-analysis-prompt.md +46 -0
  71. package/skills/validate/SKILL.md +24 -62
  72. package/skills/validate/validation-categories.md +39 -0
@@ -21,14 +21,9 @@ model: sonnet
21
21
 
22
22
  - `$ARGUMENTS` — (required) Bug description, error message, or reproduction steps
23
23
 
24
- ## Config Load
24
+ ## Project Config (auto-loaded)
25
25
 
26
- **Always** read `.claude/afc.config.md` first.
27
-
28
- If config file is missing:
29
- 1. Ask the user: "`.claude/afc.config.md` not found. Run `/afc:init` to set up the project?"
30
- 2. If user accepts → run `/afc:init`, then **restart this command** with the original `$ARGUMENTS`
31
- 3. If user declines → **abort**
26
+ !`cat .claude/afc.config.md 2>/dev/null || echo "[CONFIG NOT FOUND] .claude/afc.config.md not found. Create it with /afc:init."`
32
27
 
33
28
  ## Execution Steps
34
29
 
@@ -95,11 +90,7 @@ Run the critic loop until convergence. Safety cap: 5 passes.
95
90
  | **SAFETY** | Does the fix break any other functionality? Any side effects? |
96
91
  | **CORRECTNESS** | Does it actually resolve the root cause? Or just mask the symptom? |
97
92
 
98
- **On FAIL**: auto-fix and continue to next pass.
99
- **On ESCALATE**: pause, present options to user, apply choice, resume.
100
- **On DEFER**: record reason, mark criterion clean, continue.
101
- **On CONVERGE**: `✓ Critic converged ({N} passes, {M} fixes, {E} escalations)`
102
- **On SAFETY CAP**: `⚠ Critic safety cap ({N} passes). Review recommended.`
93
+ Follow verdict handling and output format per `docs/critic-loop-rules.md`.
103
94
 
104
95
  ### 6. Verification
105
96
 
@@ -146,15 +137,6 @@ Debug complete
146
137
  └─ Suggestion: {documentation improvement if non-obvious, or "none"}
147
138
  ```
148
139
 
149
- ## Debugging Checklist (applied automatically)
150
-
151
- Always check the Debugging Checklist from CLAUDE.md:
152
- 1. Race Conditions — contention between async operations
153
- 2. Stale State — stale state references
154
- 3. Missing Error Handling — missing Promise .catch()
155
- 4. Incorrect Ordering — operation order dependencies
156
- 5. Boundary Conditions — edge case handling
157
-
158
140
  ## Notes
159
141
 
160
142
  - **Not every report is a bug**: Always evaluate "intended behavior" hypothesis first. Do not modify code to match incorrect expectations.
@@ -80,83 +80,7 @@ If running inside a project with source code:
80
80
 
81
81
  ### 4. Write Product Brief
82
82
 
83
- Create `.claude/afc/ideate.md` (overwrite if exists after confirmation):
84
-
85
- ```markdown
86
- # Product Brief: {idea name}
87
-
88
- > Created: {YYYY-MM-DD}
89
- > Status: Exploration
90
- > Input: {original $ARGUMENTS summary}
91
-
92
- ## Problem Statement
93
- {What problem does this solve? Who has this problem? How painful is it?}
94
- {2-3 sentences, specific and measurable where possible}
95
-
96
- ## Target Users
97
-
98
- ### Primary Persona
99
- - **Who**: {role/demographic}
100
- - **Context**: {when/where they encounter the problem}
101
- - **Current workaround**: {what they do today}
102
- - **Pain level**: {High/Medium/Low — with justification}
103
-
104
- ### Secondary Persona (if applicable)
105
- {same format}
106
-
107
- ## Value Proposition
108
- {One sentence: "For {persona} who {need}, this {product} provides {benefit} unlike {alternatives}"}
109
-
110
- ## Core Features (MoSCoW)
111
-
112
- ### Must Have (MVP)
113
- 1. {feature} — {why it's essential}
114
- 2. {feature} — {why it's essential}
115
- 3. {feature} — {why it's essential}
116
-
117
- ### Should Have (v1.1)
118
- 1. {feature} — {value added}
119
-
120
- ### Could Have (future)
121
- 1. {feature} — {potential value}
122
-
123
- ### Won't Have (explicit scope cut)
124
- 1. {feature} — {why excluded}
125
-
126
- ## User Journey (primary flow)
127
-
128
- ```mermaid
129
- graph LR
130
- A[Entry Point] --> B[Core Action]
131
- B --> C[Key Decision]
132
- C --> D[Success State]
133
- C --> E[Error/Edge Case]
134
- ```
135
-
136
- {Describe the 3-5 step primary user flow in plain text as well}
137
-
138
- ## Competitive Analysis
139
-
140
- | Aspect | {Competitor 1} | {Competitor 2} | This Product |
141
- |--------|---------------|---------------|-------------|
142
- | Core strength | {X} | {X} | {X} |
143
- | Key weakness | {X} | {X} | {X} |
144
- | Pricing | {X} | {X} | {X} |
145
- | Differentiator | — | — | {what makes this unique} |
146
-
147
- ## Open Questions
148
- - {Decision that needs user input before proceeding to spec}
149
- - {Technical uncertainty that affects scope}
150
- - {Business assumption that should be validated}
151
-
152
- ## Suggested Next Steps
153
- 1. Resolve Open Questions above
154
- 2. Run `/afc:spec {refined feature description}` to formalize as a specification
155
- 3. {Any other recommended action}
156
-
157
- ## Research Sources
158
- - [{source title}]({url}) — {what was learned}
159
- ```
83
+ Create `.claude/afc/ideate.md` (overwrite if exists after confirmation) using the template in `${CLAUDE_SKILL_DIR}/brief-template.md`. Read it first, then generate the brief using that structure.
160
84
 
161
85
  ### 5. Interactive Refinement
162
86
 
@@ -0,0 +1,73 @@
1
+ # Product Brief: {idea name}
2
+
3
+ > Created: {YYYY-MM-DD}
4
+ > Status: Exploration
5
+ > Input: {original $ARGUMENTS summary}
6
+
7
+ ## Problem Statement
8
+ {What problem does this solve? Who has this problem? How painful is it?}
9
+ {2-3 sentences, specific and measurable where possible}
10
+
11
+ ## Target Users
12
+
13
+ ### Primary Persona
14
+ - **Who**: {role/demographic}
15
+ - **Context**: {when/where they encounter the problem}
16
+ - **Current workaround**: {what they do today}
17
+ - **Pain level**: {High/Medium/Low — with justification}
18
+
19
+ ### Secondary Persona (if applicable)
20
+ {same format}
21
+
22
+ ## Value Proposition
23
+ {One sentence: "For {persona} who {need}, this {product} provides {benefit} unlike {alternatives}"}
24
+
25
+ ## Core Features (MoSCoW)
26
+
27
+ ### Must Have (MVP)
28
+ 1. {feature} — {why it's essential}
29
+ 2. {feature} — {why it's essential}
30
+ 3. {feature} — {why it's essential}
31
+
32
+ ### Should Have (v1.1)
33
+ 1. {feature} — {value added}
34
+
35
+ ### Could Have (future)
36
+ 1. {feature} — {potential value}
37
+
38
+ ### Won't Have (explicit scope cut)
39
+ 1. {feature} — {why excluded}
40
+
41
+ ## User Journey (primary flow)
42
+
43
+ ```mermaid
44
+ graph LR
45
+ A[Entry Point] --> B[Core Action]
46
+ B --> C[Key Decision]
47
+ C --> D[Success State]
48
+ C --> E[Error/Edge Case]
49
+ ```
50
+
51
+ {Describe the 3-5 step primary user flow in plain text as well}
52
+
53
+ ## Competitive Analysis
54
+
55
+ | Aspect | {Competitor 1} | {Competitor 2} | This Product |
56
+ |--------|---------------|---------------|-------------|
57
+ | Core strength | {X} | {X} | {X} |
58
+ | Key weakness | {X} | {X} | {X} |
59
+ | Pricing | {X} | {X} | {X} |
60
+ | Differentiator | — | — | {what makes this unique} |
61
+
62
+ ## Open Questions
63
+ - {Decision that needs user input before proceeding to spec}
64
+ - {Technical uncertainty that affects scope}
65
+ - {Business assumption that should be validated}
66
+
67
+ ## Suggested Next Steps
68
+ 1. Resolve Open Questions above
69
+ 2. Run `/afc:spec {refined feature description}` to formalize as a specification
70
+ 3. {Any other recommended action}
71
+
72
+ ## Research Sources
73
+ - [{source title}]({url}) — {what was learned}
@@ -7,7 +7,7 @@ argument-hint: "[task ID or phase specification]"
7
7
  # /afc:implement — Execute Code Implementation
8
8
 
9
9
  > Executes implementation phase by phase with dependency-aware scheduling.
10
- > Generates tasks.md automatically from plan.md if absent. Swarm mode activates for >5 parallel tasks per phase.
10
+ > Generates tasks.md automatically from plan.md if absent. Swarm mode activates for high-parallelism phases.
11
11
 
12
12
  ## Arguments
13
13
 
@@ -51,63 +51,51 @@ This enables Stop Gate and CI Gate hooks during standalone implementation. Relea
51
51
  ### 1. Load Context
52
52
 
53
53
  1. **Current branch** → `BRANCH_NAME`
54
- 2. Load the following files from `.claude/afc/specs/{feature}/`:
54
+ 2. Load from `.claude/afc/specs/{feature}/`:
55
55
  - **plan.md** (required) — abort if missing: "plan.md not found. Run `/afc:plan` first."
56
56
  - **spec.md** (for reference)
57
57
  - **research.md** (if present)
58
58
  - **tasks.md** (if present — may be generated in Step 1.3)
59
- 3. **Recent changes**: run `git log --oneline -20` to understand what changed recently (context for implementation)
60
- 4. **Smoke test**: run `{config.gate}` before starting implementation:
61
- - If it fails → diagnose before implementing (existing code is broken — fix first or report to user)
62
- - If it passes continue to baseline test
63
- 5. **Baseline test** (if `{config.test}` is non-empty): run `{config.test}` before starting implementation:
64
- - If it fails report pre-existing test failures to user and ask: "(1) Proceed anyway (tests were already broken) (2) Fix first (3) Abort"
65
- - If it passes → full baseline confirmed, proceed
66
- - If `{config.test}` is empty → skip (no test framework configured)
59
+ 3. **Recent changes**: run `git log --oneline -20`
60
+ 4. **Smoke test**: run `{config.gate}` before starting:
61
+ - Fails → diagnose before implementing (fix first or report to user)
62
+ 5. **Baseline test** (if `{config.test}` is non-empty): run `{config.test}`:
63
+ - Fails ask user: "(1) Proceed anyway (2) Fix first (3) Abort"
64
+ - Emptyskip
67
65
 
68
66
  ### 1.3. Task List Generation (if tasks.md absent)
69
67
 
70
- If `.claude/afc/specs/{feature}/tasks.md` does not exist, generate it from plan.md:
71
-
72
68
  1. **Parse plan.md File Change Map**: extract files, actions, descriptions, `Depends On`, `Phase`
73
69
  2. **Generate tasks.md**:
74
- - Convert each row to task format: `- [ ] T{NNN} {[P]} {description} \`{file}\` {depends: [TXXX]}`
70
+ - Convert each row to: `- [ ] T{NNN} {[P]} {description} \`{file}\` {depends: [TXXX]}`
75
71
  - Assign `[P]` to tasks in the same Phase with no file dependency overlap
76
72
  - Map `Depends On` column to `depends: [TXXX]` references
77
73
  - Include phase gate validation task per phase
78
- - Include coverage mapping at the bottom:
79
- - FR/NFR → tasks (every FR-*/NFR-* maps to at least one task)
80
- - Entity → tasks (every spec Key Entity maps to at least one task)
81
- - Constraint → tasks (every spec Constraint is addressed by at least one task)
82
- 3. **Validate** (script-based, no critic loop):
74
+ - Include coverage mapping at bottom (FR/NFR → tasks, Entity → tasks, Constraint → tasks)
75
+ 3. **Validate**:
83
76
  ```bash
84
77
  "${CLAUDE_SKILL_DIR}/../../scripts/afc-dag-validate.sh" .claude/afc/specs/{feature}/tasks.md
85
78
  "${CLAUDE_SKILL_DIR}/../../scripts/afc-parallel-validate.sh" .claude/afc/specs/{feature}/tasks.md
86
79
  ```
87
- 4. If validation fails → fix tasks.md and re-validate (max 2 attempts)
80
+ 4. If validation fails → fix and re-validate (max 2 attempts)
88
81
  5. Save to `.claude/afc/specs/{feature}/tasks.md`
89
82
 
90
- If tasks.md already exists (e.g., from standalone `/afc:tasks` run): use as-is, skip generation.
83
+ If tasks.md already exists: use as-is, skip generation.
91
84
 
92
85
  ### 1.5. Parse Task List
93
86
 
94
- 1. Parse tasks.md:
95
- - Extract each task's ID, [P] marker, [US*] label, description, file paths, `depends:` list
96
- - Group by phase
97
- - Build dependency graph (validate DAG abort if circular)
98
- - Identify already-completed `[x]` tasks
99
- 2. Load **Implementation Context** section from plan.md (used in sub-agent prompts)
87
+ 1. Extract each task's ID, [P] marker, description, file paths, `depends:` list
88
+ 2. Group by phase; build dependency graph (validate DAG abort if circular)
89
+ 3. Identify already-completed `[x]` tasks
90
+ 4. Load **Implementation Context** section from plan.md (used in sub-agent prompts)
100
91
 
101
92
  ### 1.7. Retrospective Check
102
93
 
103
- If `.claude/afc/memory/retrospectives/` exists, load the **most recent 10 files** (sorted by filename descending) and check:
104
- - Were there implementation issues in past pipelines (e.g., file conflicts, unexpected dependencies, CI failures after parallel execution)?
105
- - Flag similar patterns in the current task list. Warn before implementation begins.
106
- - Skip gracefully if directory is empty or absent.
94
+ If `.claude/afc/memory/retrospectives/` exists, load the most recent 10 files and check for past patterns (file conflicts, unexpected dependencies, CI failures after parallel execution). Flag similar patterns. Skip gracefully if absent.
107
95
 
108
96
  ### 2. Check Progress
109
97
 
110
- - If completed tasks exist, display status:
98
+ - If completed tasks exist, display:
111
99
  ```
112
100
  Progress: {completed}/{total} ({percent}%)
113
101
  Next: {first incomplete task ID} - {description}
@@ -116,263 +104,88 @@ If `.claude/afc/memory/retrospectives/` exists, load the **most recent 10 files*
116
104
 
117
105
  ### 3. Phase-by-Phase Execution
118
106
 
119
- Execute each phase in order. Choose the orchestration mode by evaluating whether multi-agent coordination overhead would be justified given the tasks' characteristics:
107
+ Execute each phase in order. Choose orchestration mode based on whether multi-agent coordination overhead is justified.
120
108
 
121
109
  #### Mode Selection
122
110
 
123
- **Default: Main agent executes directly.** Delegation to impl-workers is the exception, not the rule.
111
+ | Condition | Mode |
112
+ |-----------|------|
113
+ | No [P] markers | Sequential |
114
+ | [P] tasks but delegation criteria NOT met | Sequential |
115
+ | [P] tasks, ALL criteria met, moderate parallelism | Parallel Batch |
116
+ | [P] tasks, ALL criteria met, high parallelism (multiple rounds needed) | Swarm |
124
117
 
125
- | Condition | Mode | Strategy |
126
- |-----------|------|----------|
127
- | No [P] markers | Sequential | Main agent executes tasks one by one |
128
- | [P] tasks but delegation criteria NOT met | Sequential | Main agent executes directly (preserves full context) |
129
- | [P] tasks, delegation criteria ALL met, coordination overhead justified, moderate parallelism | Parallel Batch | Launch Task() calls in parallel |
130
- | [P] tasks, delegation criteria ALL met, coordination overhead clearly justified, high parallelism | Swarm | Create task pool → orchestrator pre-assigns tasks to worker agents |
118
+ **Default is direct execution**: main agent executes tasks directly unless all 4 parallel delegation criteria are met. See `docs/orchestration-modes.md` for full criteria, execution patterns, failure recovery, and dependency resolution.
131
119
 
132
- **Mode judgment**: Ask — "Given these N tasks with their complexity, file scope, and interdependencies, would spawning multiple agents and merging their results be faster and safer than executing sequentially?" If the answer is not clearly yes, default to Sequential.
120
+ #### Sequential Mode
133
121
 
134
- - **Parallel Batch** is appropriate when there are enough independent tasks that parallel execution provides meaningful speed gain, but the total count is manageable enough that a single orchestrator round-trip suffices.
135
- - **Swarm** is appropriate when the number of independent tasks is large enough that a single batch of Task() calls would saturate the concurrent agent limit, requiring multiple orchestrator rounds.
122
+ Execute one at a time in order. On start: `▶ {ID}: {description}`. On complete: `✓ {ID} complete`.
136
123
 
137
- **Parallel delegation criteria** (ALL must be satisfied):
138
- 1. Tasks have **no `depends:` edges** between them in the DAG (no ordering constraint)
139
- 2. **Enough parallelizable tasks** that multi-agent overhead is worth it (a very small number of short tasks → sequential is cheaper)
140
- 3. Each task is **self-contained** (does not require runtime results from other tasks in the same batch)
141
- 4. Each task's **target files do not overlap** with any other task in the batch (no shared file writes)
124
+ **Dependent task chaining**: When Task B depends on Task A (same worker), use `SendMessage` to resume the existing worker instead of spawning a new one. This preserves Task A's full context (file reads, decisions, test results) for Task B.
142
125
 
143
- If ANY criterion fails → main agent sequential execution (context preservation outweighs parallelism speed).
126
+ #### Parallel Batch Mode
144
127
 
145
- #### Sequential Mode (no P marker)
128
+ For moderate independent [P] tasks. Launch multiple Task() calls in a single message (concurrent). See `docs/orchestration-modes.md` for prompt template, verification steps, and failure recovery.
146
129
 
147
- - Execute one at a time in order
148
- - On task start: `▶ {ID}: {description}`
149
- - On completion: `✓ {ID} complete`
130
+ Key constraints:
131
+ - Pre-validate no file overlap before launching (downgrade to sequential if overlapping)
132
+ - After each batch: poll TaskList manually for newly-unblocked tasks (auto-unblocking not guaranteed in sub-agent mode)
133
+ - Verification failures → main agent fixes directly, no re-delegation
134
+ - `run_in_background: true` is **never** used on Task calls
150
135
 
151
- #### Parallel Batch Mode (moderate [P] tasks)
136
+ #### Swarm Mode
152
137
 
153
- **Pre-validation**: Verify no file overlap (downgrade to sequential if overlapping).
138
+ For high-parallelism phases requiring multiple orchestrator rounds. Orchestrator pre-assigns tasks — workers never self-claim. Max 5 concurrent sub-agents (platform limit). See `docs/orchestration-modes.md` for full swarm protocol, worker prompt template, and failure recovery.
154
139
 
155
- **Step 1 Register**: Create tasks for the current phase only (phase-locked registration):
156
- ```
157
- TaskCreate({ subject: "T003: Create UserService", description: "..." })
158
- TaskCreate({ subject: "T004: Create AuthService", description: "..." })
159
- TaskUpdate({ taskId: "T004", addBlockedBy: ["T002"] }) // if T004 depends on T002
160
- ```
140
+ #### Phase Completion Gate
161
141
 
162
- **Step 2 Launch unblocked [P] tasks in a single message** (Claude Code executes multiple Task() calls in a single message concurrently, up to ~10):
163
- ```
164
- Task("T003: Create UserService", subagent_type: "afc:afc-impl-worker",
165
- isolation: "worktree",
166
- prompt: "Implement the following task:
167
-
168
- ## Task
169
- {task ID}: {description} — `{file path}`
170
-
171
- ## Implementation Context
172
- {paste full ## Implementation Context section from plan.md}
173
-
174
- ## Relevant Acceptance Criteria
175
- {extract FR/AC items from spec.md that relate to this task — NOT the full spec, only matching items}
176
- {e.g., FR-001, FR-003, SC-002 — with their full text from spec.md}
177
-
178
- ## Plan Context
179
- {relevant Phase section from plan.md for this task}
180
-
181
- ## Rules
182
- - {config.code_style} and {config.architecture}
183
- - Follow CLAUDE.md and afc.config.md
184
-
185
- ## Output
186
- Return a structured summary (max 2000 chars):
187
- - Files changed: {list}
188
- - Key decisions: {any design choices made}
189
- - Issues: {blockers or concerns, if any}
190
- - Verification: {config.gate} result")
191
- Task("T004: Create AuthService", subagent_type: "afc:afc-impl-worker", isolation: "worktree", ...)
192
- ```
142
+ > **Always** read `${CLAUDE_SKILL_DIR}/../../docs/phase-gate-protocol.md` first and perform all steps in order.
143
+ > Cannot advance to the next phase without passing the gate. Abort and report after 3 consecutive CI failures.
193
144
 
194
- **Step 3 — Collect results and verify**: After all parallel agents return:
195
- 1. Read each agent's returned output and verify completion
196
- 2. **Post-task individual verification** (per worker, before marking complete):
197
- a. If `{config.gate}` is non-empty: run it against the worker's changed files only. If empty: skip gate check (log "no gate configured, skipping")
198
- b. Check `git diff` to confirm changes stay within the task's declared file scope (no unplanned file modifications)
199
- c. If verification fails → main agent fixes directly (do NOT re-delegate — context loss on re-delegation causes compound failures)
200
- d. If verification passes → proceed to step 3
201
- 3. Mark `TaskUpdate(status: "completed")` for each verified task
202
- 4. **Manually check for newly-unblocked tasks**: Call `TaskList`, inspect `blockedBy` lists — if all blockers are now completed, the task is unblockable. (Note: auto-unblocking is only guaranteed in Agent Teams mode; in sub-agent mode, the orchestrator must poll and check manually.)
203
- 5. If newly-unblockable tasks exist → launch next batch (repeat Step 2)
204
- 6. If no more pending tasks remain → phase complete
205
-
206
- **Failure Recovery** (per-task, not per-batch):
207
- 1. Identify the failed task from the agent's error return
208
- 2. Capture the `agentId` from the failed agent's result (returned in Task tool output)
209
- 3. Reset: `TaskUpdate(taskId, status: "pending")`
210
- 4. Track: `TaskUpdate(taskId, metadata: { retryCount: N, lastAgentId: agentId })`
211
- 5. **Classify the error before deciding to retry**:
212
- - **First failure** (no `metadata.lastError` exists): store `metadata.lastError = {current error message}`. Classify as transient (no prior error to compare) and proceed with retry.
213
- - **Subsequent failures** (`metadata.lastError` exists): Compare the current error with `metadata.lastError`. If the error is **the same** (deterministic failure — same message, same stack location) → stop immediately and mark as failed. Retrying a deterministic failure wastes cycles.
214
- - If the error **differs** from the previous attempt (transient/flaky — different message, network blip, lock contention) → re-launch with `resume: lastAgentId`. The resumed agent retains full context from the previous attempt (what it tried, what failed, partial progress), enabling more targeted retry.
215
- - **Worktree caveat**: if the failed worker made no file changes, its worktree is auto-cleaned and `resume` will fail. In this case, fall back to a fresh launch (omit `resume`) for the retry.
216
- - Update `metadata.lastError` with the current error on each attempt.
217
- 6. If retryCount >= 5 (absolute safety cap) → mark as failed, report: `"T{ID} failed after {retryCount} attempts: {last error}"`
218
- 7. Continue with remaining tasks — a single failure does not block the entire phase
219
-
220
- #### Swarm Mode (high [P] task count)
221
-
222
- When a phase has enough parallelizable tasks that a single batch of Task() calls would saturate the concurrent agent limit and require multiple orchestrator rounds, use the **orchestrator-managed swarm pattern**.
223
-
224
- > **Key constraint**: Claude Code's TaskUpdate uses **last-write-wins** with local file locking only. Multiple sub-agents calling TaskUpdate on the same task simultaneously can cause lost writes. The orchestrator must mediate task assignment to prevent collisions.
225
-
226
- **Step 1 — Register current-phase tasks only** (phase-locked):
227
- ```
228
- // Register ONLY this phase's tasks — never register future phases
229
- TaskCreate({ subject: "T007: Create ComponentA", description: "..." })
230
- TaskCreate({ subject: "T008: Create ComponentB", description: "..." })
231
- // ... for all tasks in this phase
232
- TaskUpdate({ taskId: "T008", addBlockedBy: ["T006"] }) // if dependency exists
233
- ```
234
-
235
- **Step 2 — Orchestrator assigns tasks** (no self-claiming):
236
- Instead of workers self-claiming (race-prone), the **orchestrator pre-assigns** tasks:
237
- ```
238
- // Orchestrator assigns: each worker gets a unique, non-overlapping task set
239
- Task("Worker 1: T007, T009, T011", subagent_type: "afc:afc-impl-worker",
240
- isolation: "worktree",
241
- prompt: "Implement these tasks in order:
242
- 1. T007: {description} — `{file path}`
243
- 2. T009: {description} — `{file path}`
244
- 3. T011: {description} — `{file path}`
245
-
246
- ## Implementation Context
247
- {paste full ## Implementation Context section from plan.md}
248
-
249
- ## Relevant Acceptance Criteria
250
- {extract FR/AC items from spec.md that relate to these tasks — NOT the full spec, only matching items}
251
- {e.g., FR-001, FR-003, SC-002 — with their full text from spec.md}
252
-
253
- For each task:
254
- - Read the target file before modifying
255
- - Implement following plan.md design
256
- - Verify with {config.gate} after each task
257
-
258
- ## Rules
259
- - {config.code_style} and {config.architecture}
260
- - Follow CLAUDE.md and afc.config.md
261
-
262
- ## Output
263
- Return a structured summary per task (max 2000 chars total):
264
- - Files changed, key decisions, issues encountered per task.")
265
-
266
- Task("Worker 2: T008, T010, T012", subagent_type: "afc:afc-impl-worker", isolation: "worktree", ...)
267
- ```
268
-
269
- **Step 3 — Collect and verify**:
270
- 1. Wait for all workers to return (foreground execution)
271
- 2. **Post-task individual verification** (per worker):
272
- a. If `{config.gate}` is non-empty: run it against each worker's changed files. If empty: skip gate check (log "no gate configured, skipping")
273
- b. Check `git diff` to confirm changes stay within declared file scope
274
- c. If verification fails → main agent fixes directly (no re-delegation)
275
- 3. Read results, mark `TaskUpdate(status: "completed")` for each verified task
276
- 4. Call `TaskList` to check for remaining pending/blocked tasks
277
- 5. If unblocked tasks remain → assign to new worker batch (repeat Step 2)
278
- 6. If all tasks complete → phase done
279
-
280
- **Worker count**: N = min(5, unblocked task count). Max 5 concurrent sub-agents per phase (5 is the Claude Code platform limit for concurrent agents — not a semantic preference).
281
-
282
- **Task assignment strategy**: Round-robin by file path — each worker gets tasks targeting different files to maximize isolation. If a worker has multiple tasks, order them by `depends:` topology.
283
-
284
- #### Swarm Failure Recovery
285
-
286
- When a worker agent returns an error:
287
- 1. Identify which tasks the worker was assigned (from the pre-assigned list)
288
- 2. Check which tasks the worker actually completed (from its result summary)
289
- 3. Capture the `agentId` from the failed worker's result
290
- 4. Reset uncompleted tasks: `TaskUpdate(taskId, status: "pending")`
291
- 5. Track retry count: `TaskUpdate(taskId, metadata: { retryCount: N, lastAgentId: agentId })`
292
- 6. **Classify the error before deciding to retry**:
293
- - **First failure** (no `metadata.lastError` exists): store `metadata.lastError = {current error message}`. Classify as transient (no prior error to compare) and proceed with retry.
294
- - **Subsequent failures** (`metadata.lastError` exists): Compare the current error with `metadata.lastError`. If the error is **the same** (deterministic failure — same message, same stack location) → stop immediately and mark as failed. Retrying a deterministic failure wastes cycles.
295
- - If the error **differs** from the previous attempt (transient/flaky — different message, network blip, lock contention) → re-launch with `resume: lastAgentId`. The resumed agent retains its full conversation history (files read, changes attempted, errors encountered), enabling targeted retry.
296
- - **Worktree caveat**: if the failed worker made no file changes, its worktree is auto-cleaned and `resume` will fail. In this case, fall back to a fresh launch (omit `resume`) for the retry.
297
- - Update `metadata.lastError` with the current error on each attempt.
298
- 7. If retryCount >= 5 (absolute safety cap) → mark as failed, report: `"T{ID} failed after {retryCount} attempts: {last error}"`
299
- 8. Continue with remaining tasks
300
-
301
- > Single task failure does not block the phase. The orchestrator reassigns failed tasks to subsequent batches.
302
-
303
- #### Dependency Resolution
304
-
305
- - Tasks with `depends: [T001, T002]` are registered via `TaskUpdate(addBlockedBy: ["T001", "T002"])`
306
- - **Auto-unblocking is NOT guaranteed in sub-agent mode**. The orchestrator must:
307
- 1. After each batch completes, call `TaskList` to get current state
308
- 2. For each pending task, check if all `blockedBy` tasks are now completed
309
- 3. If all blockers resolved → task is eligible for the next batch
310
- - **Phase-locked registration**: Only register tasks for the current phase. Never register Phase N+1 tasks until Phase N is fully complete and its gate has passed. This prevents workers from claiming future-phase tasks.
311
- - **Cross-phase dependencies**: A Phase 2 task may `depends:` on a Phase 1 task. Since Phase 1 must complete before Phase 2 begins, this is always satisfied. Within the same phase, `depends:` creates intra-phase ordering.
312
-
313
- #### Phase Completion Gate (3 steps)
314
-
315
- > **Always** read `${CLAUDE_SKILL_DIR}/../../docs/phase-gate-protocol.md` first and perform the 3–4 steps (CI gate → Mini-Review → Integration/E2E Gate (conditional) → Auto-Checkpoint) in order.
316
- > Cannot advance to the next phase without passing the gate. Abort and report to user after 3 consecutive CI failures.
317
-
318
- After passing the gate, create a phase rollback point:
145
+ After passing the gate:
319
146
  ```bash
320
147
  "${CLAUDE_SKILL_DIR}/../../scripts/afc-pipeline-manage.sh" phase-tag {phase_number}
321
148
  ```
322
- This enables granular rollback: `git reset --hard afc/phase-{N}` restores state after Phase N completed.
323
149
 
324
150
  ### 4. Task Execution Pattern
325
151
 
326
152
  For each task:
327
153
 
328
- 1. **Read files**: always read files before modifying them
329
- 2. **TDD cycle** (when plan.md Test Strategy classifies the task's target file as "required"):
330
- - **Red**: write the test file first (failing test that defines expected behavior)
331
- - **Green**: implement the minimum code to pass the test
332
- - **Refactor**: clean up while keeping tests green
333
- - If `{config.tdd}` is `strict` or `guide`: always follow this order. If `off` or unset: recommended but not enforced.
334
- 3. **Implement**: write code following the design in plan.md
335
- 4. **Type/Lint check**: verify new code passes `{config.gate}`
154
+ 1. **Read files**: always read before modifying
155
+ 2. **TDD cycle** (when plan.md Test Strategy marks target file as "required"):
156
+ - Red Green Refactor
157
+ - If `{config.tdd}` is `strict` or `guide`: enforce order. If `off` or unset: recommended only.
158
+ 3. **Implement**: write code following plan.md design
159
+ 4. **Type/Lint check**: verify with `{config.gate}`
336
160
  5. **Update tasks.md**: mark completed tasks as `[x]`
337
- ```markdown
338
- - [x] T001 {description} ← complete
339
- - [ ] T002 {description} ← incomplete
340
- ```
341
161
 
342
162
  ### 5. Final Verification
343
163
 
344
- After all tasks are complete:
345
-
346
164
  ```bash
347
165
  {config.ci}
348
166
  ```
349
167
 
350
- - **Pass**: output final report
351
- - **Fail**: **Debug-based RCA** (replaces blind retry):
352
- 1. Execute `/afc:debug` logic inline with the CI error output as input
353
- 2. Debug performs RCA: error trace → data flow → hypothesis → targeted fix
168
+ - **Pass** output final report
169
+ - **Fail** Debug-based RCA:
170
+ 1. Execute `/afc:debug` logic inline with the CI error as input
171
+ 2. RCA: error trace → data flow → hypothesis → targeted fix
354
172
  3. Re-run `{config.ci}` after fix
355
- 4. If debug-fix cycle fails 3 times → report to user with diagnosis details (not a simple fix)
356
- 5. This produces targeted fixes instead of blind retries
173
+ 4. If debug-fix cycle fails 3 times → report to user with diagnosis details
357
174
 
358
175
  ### 6. Implement Critic Loop
359
176
 
360
- After CI passes, run a convergence-based Critic Loop to verify design alignment before reporting completion.
177
+ After CI passes, run a convergence-based Critic Loop to verify design alignment.
361
178
 
362
179
  > **Always** read `${CLAUDE_SKILL_DIR}/../../docs/critic-loop-rules.md` first and follow it.
363
180
 
364
181
  **Critic Loop until convergence** (safety cap: 5):
365
182
 
366
- - **SCOPE_ADHERENCE**: Compare `git diff` changed files against plan.md File Change Map. Flag any file modified that is NOT in the plan. Flag any planned file NOT modified. Provide "M of N files match" count.
367
- - **ARCHITECTURE**: Validate changed files against `{config.architecture}` rules (layer boundaries, naming conventions, import paths). Provide "N of M rules checked" count.
368
- - **CORRECTNESS**: Cross-check implemented changes against spec.md acceptance criteria (AC). Verify each AC has corresponding code. Provide "N of M AC verified" count.
369
- - **SIDE_EFFECT_SAFETY**: For tasks that changed call order, error handling, or state flow: verify that callee behavior is compatible with the new call pattern. Provide "{M} of {N} behavioral changes verified" count.
370
- - **Adversarial 3-perspective** (mandatory each pass):
371
- - Skeptic: "Which implementation assumption is most likely wrong?"
372
- - Devil's Advocate: "How could this implementation be misused or fail unexpectedly?"
373
- - Edge-case Hunter: "What input would cause this implementation to fail silently?"
374
- - State one failure scenario per perspective. If realistic → FAIL + fix. If unrealistic → state quantitative rationale.
375
- - FAIL → auto-fix, re-run `{config.ci}`, and continue. ESCALATE → pause, present options, resume after response. DEFER → record reason, mark clean.
183
+ - **SCOPE_ADHERENCE**: Compare `git diff` changed files against plan.md File Change Map. "M of N files match."
184
+ - **ARCHITECTURE**: Validate against `{config.architecture}` rules. "N of M rules checked."
185
+ - **CORRECTNESS**: Cross-check against spec.md acceptance criteria. "N of M AC verified."
186
+ - **SIDE_EFFECT_SAFETY**: Verify callee behavior compatibility for changed call order/error handling/state flow. "{M} of {N} behavioral changes verified."
187
+ - **Adversarial 3-perspective** (mandatory each pass): Skeptic, Devil's Advocate, Edge-case Hunter — one failure scenario each. Realistic → FAIL + fix. Unrealistic → quantitative rationale.
188
+ - FAIL auto-fix + re-run `{config.ci}`. ESCALATE → pause for user. DEFER → record reason.
376
189
 
377
190
  ### 7. Final Output
378
191
 
@@ -392,16 +205,11 @@ Implementation complete
392
205
 
393
206
  ## Notes
394
207
 
395
- - **Read existing code first**: always read file contents before modifying. Do not blindly generate code.
396
- - **No over-modification**: do not refactor or improve beyond what is in plan.md.
397
- - **Architecture compliance**: follow {config.architecture} rules.
398
- - **{config.ci} gate**: must pass on phase completion. Do not bypass.
399
- - **Swarm workers**: max 5 concurrent. File overlap is strictly prohibited between parallel tasks.
400
- - **On error**: classify errors before retrying. Stop immediately on deterministic (same) errors. Allow additional attempts for transient (different) errors. Hard cap at 5 retries total.
208
+ - **Read existing code first**: always read file contents before modifying.
209
+ - **No over-modification**: do not refactor beyond what is in plan.md.
210
+ - **Architecture compliance**: follow `{config.architecture}` rules.
211
+ - **`{config.ci}` gate**: must pass on phase completion. Do not bypass.
212
+ - **File overlap**: strictly prohibited between parallel tasks.
213
+ - **Error classification**: stop on deterministic (same) errors; allow retries for transient (different) errors. Hard cap: 5 retries.
401
214
  - **Real-time tasks.md updates**: mark checkbox on each task completion.
402
- - **Default is direct execution**: main agent executes tasks directly unless all 4 parallel delegation criteria are met. This preserves full context and avoids multi-agent context loss.
403
- - **Mode selection is automatic**: do not manually override. Sequential (default), batch when moderate independent parallelism justifies coordination overhead, swarm when high task count requires multiple orchestrator rounds.
404
- - **NEVER use `run_in_background: true` on Task calls**: agents must run in foreground so results are returned before the next step.
405
- - **No worker self-claiming**: In swarm mode, the orchestrator pre-assigns tasks to workers. Workers do NOT call TaskList/TaskUpdate to claim tasks — this avoids last-write-wins race conditions on TaskUpdate.
406
- - **Phase-locked registration**: Only register (TaskCreate) the current phase's tasks. Never pre-register future phases. This is the primary mechanism for phase boundary enforcement.
407
- - **Orchestrator polls for unblocking**: After each batch, the orchestrator calls TaskList and manually checks blockedBy status. Do not rely on automatic unblocking outside Agent Teams mode.
215
+ - **Orchestration modes reference**: `docs/orchestration-modes.md`