claude-flow-novice 2.5.2 → 2.6.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 (46) hide show
  1. package/.claude/agents/CLAUDE.md +740 -978
  2. package/.claude/agents/core-agents/cost-savings-cfn-loop-coordinator.md +47 -2
  3. package/.claude/agents/custom/agent-builder.md +637 -0
  4. package/.claude/api-configs/config-current-zai-config.env +62 -0
  5. package/.claude/api-configs/config-test-zai-config.env +62 -0
  6. package/.claude/api-configs/env-backups/before-anthropic-20251020-025404.env +62 -0
  7. package/.claude/api-configs/env-backups/before-restore-20251020-025431.env +62 -0
  8. package/.claude/artifacts/reflection-merge-logs/cli-agent-spawning-v2.5.2-merge-report.md +61 -0
  9. package/.claude/commands/cfn-loop-epic.md +41 -17
  10. package/.claude/commands/cfn-loop.md +43 -30
  11. package/.claude/commands/custom-routing-activate.md +37 -123
  12. package/.claude/commands/custom-routing-deactivate.md +27 -124
  13. package/.claude/commands/switch-api.md +41 -16
  14. package/.claude/skills/agent-execution/execute-agent.sh +126 -0
  15. package/.claude/skills/redis-coordination/AGENT_LOGGING.md +280 -0
  16. package/.claude/skills/redis-coordination/agent-log.sh +124 -0
  17. package/.claude/skills/redis-coordination/init-swarm.sh +6 -1
  18. package/.claude/skills/redis-coordination/invoke-waiting-mode.sh +62 -5
  19. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh +68 -8
  20. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-1760949407 +933 -0
  21. package/.claude/skills/redis-coordination/store-epic-context.sh +123 -0
  22. package/.claude/skills/redis-coordination/test-iteration-feedback.sh +320 -0
  23. package/.claude/skills/skill-builder/SKILL.md +910 -0
  24. package/CLAUDE.md +76 -2
  25. package/dist/cli/agent-command.js +151 -0
  26. package/dist/cli/agent-command.js.map +1 -0
  27. package/dist/cli/agent-definition-parser.js +176 -0
  28. package/dist/cli/agent-definition-parser.js.map +1 -0
  29. package/dist/cli/agent-executor.js +176 -0
  30. package/dist/cli/agent-executor.js.map +1 -0
  31. package/dist/cli/agent-prompt-builder.js +188 -0
  32. package/dist/cli/agent-prompt-builder.js.map +1 -0
  33. package/dist/cli/agent-spawn.js +46 -1
  34. package/dist/cli/agent-spawn.js.map +1 -1
  35. package/dist/cli/anthropic-client.js +242 -0
  36. package/dist/cli/anthropic-client.js.map +1 -0
  37. package/dist/cli/cli-agent-context.js +353 -0
  38. package/dist/cli/cli-agent-context.js.map +1 -0
  39. package/dist/cli/cli-agent-context.test.js +451 -0
  40. package/dist/cli/cli-agent-context.test.js.map +1 -0
  41. package/dist/cli/index.js +115 -2
  42. package/dist/cli/index.js.map +1 -1
  43. package/dist/cli/iteration-history.js +188 -0
  44. package/dist/cli/iteration-history.js.map +1 -0
  45. package/package.json +3 -1
  46. package/scripts/switch-api.sh +233 -0
@@ -1,1233 +1,995 @@
1
- # The Definitive Guide to Agent Profile Design
1
+ # Agent Creation & Customization Guide
2
2
 
3
- **Version:** 3.0.0
4
- **Last Updated:** 2025-10-17
5
- **Status:** Production-Ready with Phase 4 Template Optimization
3
+ **Version:** 4.0.0
4
+ **Last Updated:** 2025-10-20
5
+ **Audience:** NPM Users & Developers
6
6
 
7
- This document is the single source of truth for creating, editing, and validating agent profiles in the Claude Flow ecosystem. It incorporates empirical findings from our comprehensive Rust benchmarking system, Phase 4 bulk optimization results (75 agents, 73% reduction), and establishes evidence-based best practices with reusable template patterns.
7
+ This is your practical guide to creating, customizing, and maintaining AI agents in the Claude Flow Novice system. Whether you're using our npm package or building custom workflows, this guide will help you create powerful, specialized agents tailored to your needs.
8
8
 
9
9
  ---
10
10
 
11
11
  ## Table of Contents
12
12
 
13
- 1. [Quick Start](#quick-start)
14
- 2. [Phase 4 Template System](#phase-4-template-system)
15
- 3. [Core Universal Principles](#core-universal-principles)
16
- 4. [Agent Profile Structure](#agent-profile-structure)
17
- 5. [Examples & Templates](#examples--templates)
18
- 6. [Specialized Guidance](#specialized-guidance)
13
+ 1. [Quick Start - Create Your First Agent](#quick-start-create-your-first-agent)
14
+ 2. [Understanding the Agent Directory](#understanding-the-agent-directory)
15
+ 3. [Agent Anatomy](#agent-anatomy)
16
+ 4. [Step-by-Step Agent Creation](#step-by-step-agent-creation)
17
+ 5. [Ready-to-Use Templates](#ready-to-use-templates)
18
+ 6. [Customization Guide](#customization-guide)
19
+ 7. [Testing Your Agent](#testing-your-agent)
20
+ 8. [Advanced Concepts](#advanced-concepts)
21
+ 9. [Troubleshooting](#troubleshooting)
19
22
 
20
23
  ---
21
24
 
22
- ## Quick Start
25
+ ## Quick Start - Create Your First Agent
23
26
 
24
- ### The Three Golden Rules
27
+ ### What You'll Learn
28
+ In 5 minutes, you'll create a custom agent that can perform specialized tasks in your workflow.
25
29
 
26
- 1. **Complexity-Verbosity Inverse Law**: As task complexity increases, prompt verbosity should DECREASE
27
- 2. **Priming Paradox**: Verbose prompts excel at basic tasks, minimal prompts excel at complex reasoning
28
- 3. **Rust Validation**: These findings are validated for Rust; hypotheses for other languages
29
-
30
- ### Format Selection in 30 Seconds
30
+ ### Prerequisites
31
+ ```bash
32
+ # Install claude-flow-novice
33
+ npm install claude-flow-novice
31
34
 
32
- ```yaml
33
- Is the task BASIC (parsing, simple logic, CRUD)?
34
- → Use CODE-HEAVY format (+43% quality improvement)
35
+ # Verify installation
36
+ npx claude-flow-novice --version
37
+ ```
35
38
 
36
- Is the task COMPLEX with clear requirements (architecture, review)?
37
- → Use MINIMAL format (avoid over-constraining)
39
+ ### Your First Agent (3 Steps)
38
40
 
39
- Is the task MEDIUM complexity with structured steps?
40
- → Use METADATA format (structured guidance)
41
+ **Step 1: Create the agent file**
42
+ ```bash
43
+ mkdir -p .claude/agents/custom
44
+ touch .claude/agents/custom/my-first-agent.md
41
45
  ```
42
46
 
43
- **For detailed format guidance:** See [Format Selection Principles](./agent-principles/format-selection.md)
47
+ **Step 2: Add basic configuration**
48
+ ```markdown
49
+ ---
50
+ name: my-first-agent
51
+ description: |
52
+ MUST BE USED when performing [your specific task].
53
+ Keywords - [relevant, keywords, for, your, task]
54
+ tools: [Read, Write, Edit, Bash, TodoWrite]
55
+ model: haiku
56
+ type: specialist
57
+ ---
58
+
59
+ # My First Agent
44
60
 
45
- ### Agent Size Guidelines (Phase 4 Validated)
61
+ You are a specialized agent that helps with [describe what your agent does].
46
62
 
47
- **Target:** 100-200 lines per agent (average: 137 lines)
63
+ ## Core Responsibilities
64
+ - [Responsibility 1]
65
+ - [Responsibility 2]
66
+ - [Responsibility 3]
48
67
 
49
- ```yaml
50
- All Agents:
51
- → Use 5 reusable templates for common patterns
52
- → Preserve only unique domain logic
53
- Target: 100-200 lines (validated across 75 agents)
54
-
55
- Templates Available:
56
- - redis-coordination.md (90 lines)
57
- - memory-operations.md (78 lines)
58
- - post-edit-validation.md (121 lines)
59
- - cfn-loop-mechanics.md (70 lines)
60
- - team-dynamics.md (80 lines)
68
+ ## Approach
69
+ [Describe how your agent should approach tasks]
70
+ ```
71
+
72
+ **Step 3: Test your agent**
73
+ ```bash
74
+ # Spawn your agent
75
+ npx claude-flow-novice agent-spawn my-first-agent --task-id test-1
61
76
  ```
62
77
 
63
- **Phase 4 Results:** 75 agents optimized, 73% codebase reduction, 50-66% faster loading
78
+ **That's it!** You've created a working agent.
64
79
 
65
80
  ---
66
81
 
67
- ## Phase 4 Template System
82
+ ## Understanding the Agent Directory
68
83
 
69
- ### Overview
84
+ ### Directory Structure
70
85
 
71
- **Phase 4 (October 2025)** successfully optimized 75 of 81 agents using template extraction:
72
- - **23,615 lines removed** (71% average reduction per agent)
73
- - **Average agent size:** 137 lines (down from 470 lines)
74
- - **5 reusable templates** created
75
- - **100% functionality preserved**
86
+ ```
87
+ .claude/agents/
88
+ ├── CLAUDE.md # This guide
89
+ ├── core-agents/ # Production-ready core agents
90
+ │ ├── coder.md # Code implementation
91
+ │ ├── reviewer.md # Code review & quality
92
+ │ ├── tester.md # Testing & validation
93
+ │ └── coordinator.md # Multi-agent coordination
94
+ ├── development/ # Development-focused agents
95
+ │ ├── backend-dev.md
96
+ │ ├── frontend-dev.md
97
+ │ └── devops-engineer.md
98
+ ├── security/ # Security-focused agents
99
+ │ └── security-specialist.md
100
+ ├── custom/ # YOUR CUSTOM AGENTS GO HERE
101
+ │ └── your-agent.md
102
+ └── templates/ # Reusable templates
103
+ ├── redis-coordination.md
104
+ ├── memory-operations.md
105
+ └── team-dynamics.md
106
+ ```
76
107
 
77
- ### The 5 Core Templates
108
+ ### Where to Put Your Agents
78
109
 
79
- #### 1. Redis Coordination (`.claude/templates/redis-coordination.md`)
80
- **What:** Redis pub/sub patterns, LPUSH/BLPOP, hierarchical broadcast, mesh hybrid
81
- **When:** All agents need Redis coordination
82
- **Size:** 90 lines
83
- **Usage:**
84
- ```markdown
85
- ## Redis Coordination
110
+ **Option 1: Project-Specific** (Recommended for teams)
111
+ ```bash
112
+ # Lives in your project repo
113
+ <project-root>/.claude/agents/custom/
114
+ ```
115
+ - ✅ Version controlled with your code
116
+ - Shared across team
117
+ - ✅ Project-specific workflows
86
118
 
87
- See: `.claude/templates/redis-coordination.md`
119
+ **Option 2: Personal Agents**
120
+ ```bash
121
+ # Lives in your home directory
122
+ ~/.claude/agents/
123
+ ```
124
+ - ✅ Available across all projects
125
+ - ✅ Personal productivity tools
126
+ - ⚠️ Not shared with team
127
+
128
+ ---
129
+
130
+ ## Agent Anatomy
88
131
 
89
- - Event publishing patterns
90
- - Signal ACK protocol
91
- - Error handling strategies
132
+ Every agent has three main parts:
133
+
134
+ ### 1. Frontmatter (YAML Configuration)
135
+
136
+ ```yaml
137
+ ---
138
+ name: agent-name # Unique identifier (lowercase, hyphens)
139
+ description: | # What the agent does & when to use it
140
+ MUST BE USED when [use case].
141
+ Keywords - [searchable, terms]
142
+ tools: [Read, Write, Edit, Bash] # Available tools (Bash includes Redis CLI)
143
+ model: haiku # haiku | sonnet | opus
144
+ type: specialist # specialist | coordinator | swarm
145
+ capabilities: # Optional tags
146
+ - api-development
147
+ - database-design
148
+ acl_level: 1 # Data access level (1-5)
149
+ ---
92
150
  ```
93
151
 
94
- #### 2. Memory Operations (`.claude/templates/memory-operations.md`)
95
- **What:** SQLite + Redis integration, 5-level ACL, retention policies
96
- **When:** All agents need memory persistence
97
- **Size:** 78 lines
98
- **Usage:**
152
+ ### 2. Agent Body (Instructions)
153
+
99
154
  ```markdown
100
- ## Memory Operations
155
+ # Agent Name
101
156
 
102
- See: `.claude/templates/memory-operations.md`
157
+ Brief description of what this agent does.
158
+
159
+ ## Core Responsibilities
160
+ - Primary duty 1
161
+ - Primary duty 2
162
+
163
+ ## Approach & Methodology
164
+ How the agent thinks about and solves problems.
165
+
166
+ ## Collaboration
167
+ How this agent works with other agents.
103
168
 
104
- - SQLite lifecycle hooks
105
- - ACL-based access control
106
- - Retry logic for persistence
169
+ ## Success Metrics
170
+ How to measure if the agent succeeded.
107
171
  ```
108
172
 
109
- #### 3. Post-Edit Validation (`.claude/templates/post-edit-validation.md`)
110
- **What:** Hook integration, 5 feedback types, validation patterns
111
- **When:** All agents perform file edits
112
- **Size:** 121 lines
113
- **Usage:**
173
+ ### 3. Template References (Optional)
174
+
114
175
  ```markdown
115
- ## 🚨 MANDATORY POST-EDIT VALIDATION
176
+ ## Redis Coordination
177
+ → See: `.claude/templates/redis-coordination.md`
116
178
 
117
- ```bash
118
- npx claude-flow@alpha hooks post-edit [FILE_PATH] --memory-key "agent/step" --structured
179
+ ## Memory Operations
180
+ See: `.claude/templates/memory-operations.md`
119
181
  ```
120
182
 
121
- → See: `.claude/templates/post-edit-validation.md` for feedback types
122
- ```
183
+ ---
123
184
 
124
- #### 4. CFN Loop Mechanics (`.claude/templates/cfn-loop-mechanics.md`)
125
- **What:** Loop structure, decision framework (PROCEED/LOOP/DEFER/ESCALATE), mode thresholds
126
- **When:** Agents participate in CFN Loop
127
- **Size:** 70 lines
128
- **Usage:**
129
- ```markdown
130
- ## CFN Loop Mechanics
185
+ ## Step-by-Step Agent Creation
131
186
 
132
- See: `.claude/templates/cfn-loop-mechanics.md`
187
+ ### Step 1: Define Your Agent's Purpose
133
188
 
134
- - Loop progression logic
135
- - Mode-specific thresholds (MVP/Standard/Enterprise)
136
- - Decision framework
137
- ```
189
+ **Ask yourself:**
190
+ - What specific task will this agent perform?
191
+ - When should it be automatically triggered?
192
+ - What expertise does it need?
193
+ - How will it collaborate with other agents?
138
194
 
139
- #### 5. Team Dynamics (`.claude/templates/team-dynamics.md`)
140
- **What:** Dynamic role adaptation, collaboration patterns, confidence calibration
141
- **When:** All agents work in teams
142
- **Size:** 80 lines
143
- **Usage:**
144
- ```markdown
145
- ## Team Role Awareness
195
+ **Example:**
196
+ > "I need an agent that reviews database schema migrations for security issues and performance problems."
197
+
198
+ ### Step 2: Choose Your Template
199
+
200
+ We provide 3 templates based on task complexity:
146
201
 
147
- See: `.claude/templates/team-dynamics.md`
202
+ | Template | Best For | Size | Example Use |
203
+ |----------|----------|------|-------------|
204
+ | **Simple** | Single, focused tasks | 100-200 lines | File formatter, linter |
205
+ | **Standard** | Multi-step workflows | 200-400 lines | API developer, reviewer |
206
+ | **Advanced** | Complex coordination | 400-700 lines | Architect, coordinator |
148
207
 
149
- **Specialty:** [Agent domain]
150
- **Solo Confidence:** ≥0.80
151
- **Team Confidence:** ≥0.75
208
+ ### Step 3: Create Your Agent File
152
209
 
153
- ## Collaboration Patterns
154
- - **With Implementers:** Provide specifications
155
- - **With Validators:** Share results via Redis
156
- - **Solo:** Full implementation cycle
210
+ ```bash
211
+ # For a database migration reviewer
212
+ touch .claude/agents/custom/migration-reviewer.md
157
213
  ```
158
214
 
159
- ### Template-Based Agent Structure (Validated)
215
+ ### Step 4: Fill in the Template
160
216
 
161
- **New Standard (100-200 lines):**
217
+ **Simple Template Example:**
162
218
 
163
219
  ```markdown
164
220
  ---
165
- # Frontmatter (30 lines)
166
- name: agent-name
221
+ name: migration-reviewer
167
222
  description: |
168
- MUST BE USED when [use case]
169
- Keywords - [keywords]
170
- tools: [Read, Write, Edit, Bash, TodoWrite]
223
+ MUST BE USED when reviewing database migrations for security and performance.
224
+ Use PROACTIVELY for SQL schema changes, migrations, database updates.
225
+ Keywords - database, migration, schema, SQL, security, performance
226
+ tools: [Read, Grep, TodoWrite]
171
227
  model: haiku
172
228
  type: specialist
173
- acl_level: 1
174
- validation_hooks:
175
- - agent-template-validator
176
- - cfn-loop-memory-validator
177
- lifecycle:
178
- pre_task: "sqlite-cli exec 'INSERT INTO agents...'"
179
- post_task: "sqlite-cli exec 'UPDATE agents...'"
229
+ capabilities:
230
+ - database-security
231
+ - sql-review
232
+ - performance-analysis
233
+ acl_level: 3
180
234
  ---
181
235
 
182
- # Agent Name (1 line)
183
-
184
- Brief intro (2-3 lines)
236
+ # Database Migration Reviewer
185
237
 
186
- ## 🚨 MANDATORY POST-EDIT VALIDATION (8 lines)
238
+ You are a specialized database expert focused on reviewing migration files for
239
+ security vulnerabilities and performance issues.
187
240
 
188
- See: `.claude/templates/post-edit-validation.md`
241
+ ## Core Responsibilities
189
242
 
190
- ## Template References (20 lines)
243
+ 1. **Security Review**
244
+ - Check for SQL injection vulnerabilities
245
+ - Validate access control patterns
246
+ - Review encryption of sensitive data
247
+ - Ensure proper sanitization
191
248
 
192
- See: `.claude/templates/redis-coordination.md`
193
- See: `.claude/templates/memory-operations.md`
194
- See: `.claude/templates/team-dynamics.md`
195
- See: `.claude/templates/cfn-loop-mechanics.md`
249
+ 2. **Performance Analysis**
250
+ - Identify missing indexes
251
+ - Flag inefficient queries
252
+ - Check for N+1 query patterns
253
+ - Validate transaction boundaries
196
254
 
197
- ## Core Unique Logic (50-120 lines)
255
+ 3. **Best Practices**
256
+ - Ensure migrations are reversible
257
+ - Check for breaking changes
258
+ - Validate naming conventions
259
+ - Verify proper error handling
198
260
 
199
- [ONLY agent-specific domain expertise]
261
+ ## Review Process
200
262
 
201
- ## Success Metrics (10 lines)
202
- ```
263
+ 1. Read migration file
264
+ 2. Analyze SQL patterns
265
+ 3. Check against security checklist
266
+ 4. Evaluate performance implications
267
+ 5. Provide actionable feedback
203
268
 
204
- ### Benefits of Template System
269
+ ## Output Format
205
270
 
206
- **Developer Productivity:**
207
- - easier maintenance (single template update propagates)
208
- - Faster agent creation (templates provide scaffolding)
209
- - Consistent structure across 75 agents
271
+ Provide a confidence score (0.0-1.0) and structured feedback:
272
+ - Critical issues (must fix)
273
+ - Warnings (should address)
274
+ - Suggestions (nice to have)
275
+ - Approved changes
210
276
 
211
- **System Performance:**
212
- - 50-66% faster agent loading
213
- - 73% reduction in token usage
214
- - 70% more efficient rule processing
277
+ ## Success Metrics
278
+ - Zero critical security issues
279
+ - No obvious performance bottlenecks
280
+ - Migrations are reversible
281
+ - Confidence score ≥ 0.85
282
+ ```
215
283
 
216
- **Quality:**
217
- - 100% functionality preserved
218
- - All validation hooks maintained
219
- - Standardized patterns reduce bugs
284
+ ### Step 5: Test Your Agent
220
285
 
221
- **Cost Savings:**
222
- - 73% fewer tokens per agent
223
- - ~32,925 equivalent lines reused via templates
224
- - reduction in maintenance effort
286
+ ```bash
287
+ # Test with a sample task
288
+ npx claude-flow-novice agent-spawn migration-reviewer \
289
+ --task-id test-migration \
290
+ --prompt "Review the migration in db/migrations/001_add_users_table.sql"
291
+ ```
225
292
 
226
- ### Creating New Agents (Template-First Approach)
293
+ ---
227
294
 
228
- **Step 1:** Choose appropriate templates (typically all 5)
295
+ ## Ready-to-Use Templates
229
296
 
230
- **Step 2:** Define unique domain logic only (50-120 lines)
297
+ ### Template 1: Code Implementer
231
298
 
232
- **Step 3:** Reference templates, don't duplicate
233
299
  ```markdown
234
- ## Redis Coordination
235
-
236
- → See: `.claude/templates/redis-coordination.md`
237
-
238
- [Only agent-specific Redis patterns here]
239
- ```
240
-
241
- **Step 4:** Validate agent size <200 lines
300
+ ---
301
+ name: my-implementer
302
+ description: |
303
+ MUST BE USED when implementing [specific type of code].
304
+ Keywords - implement, build, create, develop
305
+ tools: [Read, Write, Edit, Bash, TodoWrite]
306
+ model: haiku
307
+ type: specialist
308
+ acl_level: 1
309
+ ---
242
310
 
243
- **Example:** See optimized agents in `.claude/agents/` (all <200 lines)
311
+ # [Type] Implementer
244
312
 
245
- ---
313
+ You implement [specific type of code] following best practices.
246
314
 
247
- ## Core Universal Principles
315
+ ## Core Responsibilities
316
+ - Write clean, maintainable code
317
+ - Follow TDD approach
318
+ - Implement features from specifications
319
+ - Optimize for readability
248
320
 
249
- ### 1. Agent Profile Structure **REQUIRED FORMAT**
321
+ ## Implementation Workflow
322
+ 1. Understand requirements
323
+ 2. Write tests first
324
+ 3. Implement solution
325
+ 4. Refactor for quality
326
+ 5. Validate coverage
250
327
 
251
- Every agent MUST include:
328
+ ## Success Criteria
329
+ - All tests pass
330
+ - Code coverage ≥ 80%
331
+ - Follows coding standards
332
+ - Confidence score ≥ 0.80
333
+ ```
252
334
 
253
- #### Frontmatter (YAML)
335
+ ### Template 2: Code Reviewer
254
336
 
255
- ```yaml
337
+ ```markdown
256
338
  ---
257
- name: agent-name # REQUIRED: Lowercase with hyphens
258
- description: | # REQUIRED: Clear, keyword-rich description
259
- MUST BE USED when [primary use case].
260
- Use PROACTIVELY for [specific scenarios].
261
- ALWAYS delegate when user asks [trigger phrases].
262
- Keywords - [comma-separated keywords for search]
263
- tools: [Read, Write, Edit, Bash, TodoWrite, mcp__claude-flow__swarm_init, mcp__claude-flow__agent_spawn] # REQUIRED: Comma-separated list, can include MCP commands
264
- model: sonnet # REQUIRED: sonnet | opus | haiku
265
- provider: zai # OPTIONAL: zai | anthropic | custom (defaults to zai if not specified)
266
- color: seagreen # REQUIRED: Visual identifier
267
- type: specialist # OPTIONAL: specialist | coordinator | swarm
268
- capabilities: # OPTIONAL: Array of capability tags
269
- - rust
270
- - error-handling
271
- lifecycle: # OPTIONAL: Hooks for agent lifecycle
272
- pre_task: "npx claude-flow@alpha hooks pre-task"
273
- post_task: "npx claude-flow@alpha hooks post-task"
274
- hooks: # OPTIONAL: Integration points
275
- memory_key: "agent-name/context"
276
- validation: "post-edit"
277
- validation_hooks: # OPTIONAL: Auto-triggered validators
278
- - agent-template-validator # Auto-validates on .md save
279
- - cfn-loop-memory-validator # Auto-validates memory.set() calls
280
- - test-coverage-validator # Auto-validates after tests
281
- - blocking-coordination-validator # For coordinators only
282
- triggers: # OPTIONAL: Automatic activation patterns
283
- - "build rust"
284
- - "implement concurrent"
285
- constraints: # OPTIONAL: Limitations and boundaries
286
- - "Do not modify production database"
339
+ name: my-reviewer
340
+ description: |
341
+ MUST BE USED for reviewing [specific type of code].
342
+ Keywords - review, validate, quality, security
343
+ tools: [Read, Grep, TodoWrite]
344
+ model: haiku
345
+ type: validator
346
+ acl_level: 3
287
347
  ---
288
- ```
289
348
 
290
- #### Body Structure
349
+ # [Type] Code Reviewer
291
350
 
292
- ```markdown
293
- # Agent Name
351
+ You review [specific type of code] for quality, security, and best practices.
294
352
 
295
- [Opening paragraph: WHO you are, WHAT you do]
353
+ ## Review Criteria
296
354
 
297
- ## 🚨 MANDATORY POST-EDIT VALIDATION
355
+ ### Code Quality
356
+ - [ ] Clear variable names
357
+ - [ ] Proper error handling
358
+ - [ ] Minimal complexity
359
+ - [ ] Good documentation
298
360
 
299
- **CRITICAL**: After **EVERY** file edit operation, you **MUST** run the enhanced post-edit hook:
361
+ ### Security
362
+ - [ ] No hardcoded secrets
363
+ - [ ] Proper input validation
364
+ - [ ] Safe API usage
365
+ - [ ] No XSS/injection risks
300
366
 
301
- ```bash
302
- npx claude-flow@alpha hooks post-edit [FILE_PATH] --memory-key "agent/step" --structured
367
+ ### Performance
368
+ - [ ] Efficient algorithms
369
+ - [ ] No memory leaks
370
+ - [ ] Proper caching
371
+ - [ ] Optimized queries
372
+
373
+ ## Output Format
374
+ Provide confidence score and categorized feedback:
375
+ - 🔴 Critical (blocking issues)
376
+ - 🟡 Warnings (should fix)
377
+ - 🟢 Suggestions (improvements)
378
+
379
+ ## Success Metrics
380
+ - Confidence score ≥ 0.90
381
+ - Zero critical issues
382
+ - Actionable feedback provided
303
383
  ```
304
384
 
305
- **This provides:**
306
- - 🧪 **TDD Compliance**: Validates test-first development practices
307
- - 🔒 **Security Analysis**: Detects eval(), hardcoded credentials, XSS vulnerabilities
308
- - 🎨 **Formatting**: Prettier/rustfmt analysis with diff preview
309
- - 📊 **Coverage Analysis**: Test coverage validation with configurable thresholds (≥80%)
310
- - 🤖 **Actionable Recommendations**: Specific steps to improve code quality
311
- - 💾 **Memory Coordination**: Stores results for cross-agent collaboration
385
+ ### Template 3: Specialist Agent
312
386
 
313
- **Additional Validators:**
314
- - **Agent Template Validator**: Auto-validates SQLite lifecycle hooks, ACL declarations, error handling patterns (triggers on `.claude/agents/**/*.md` edits)
315
- - **CFN Loop Memory Validator**: Auto-validates ACL levels for Loop 3/2/4 memory operations (triggers on `memory.set()` calls)
316
- - **Test Coverage Validator**: Auto-validates 80% line coverage, 75% branch coverage thresholds (triggers after test execution)
317
- - **Blocking Coordination Validator**: Auto-validates HMAC secrets, signal ACK patterns (coordinators only)
387
+ ```markdown
388
+ ---
389
+ name: my-specialist
390
+ description: |
391
+ MUST BE USED when [specialized task].
392
+ Use PROACTIVELY for [scenarios].
393
+ Keywords - [domain, specific, keywords]
394
+ tools: [Read, Write, Edit, Bash, Grep, Glob, TodoWrite]
395
+ model: sonnet
396
+ type: specialist
397
+ capabilities:
398
+ - [capability-1]
399
+ - [capability-2]
400
+ acl_level: 1
401
+ ---
318
402
 
319
- ## Core Responsibilities
403
+ # [Domain] Specialist
320
404
 
321
- [Primary duties in clear, actionable bullet points]
405
+ You are an expert in [domain] with deep knowledge of [specific expertise].
322
406
 
323
- ## Approach & Methodology
407
+ ## Expertise Areas
408
+ - [Area 1]: [Description]
409
+ - [Area 2]: [Description]
410
+ - [Area 3]: [Description]
324
411
 
325
- [HOW the agent accomplishes tasks - frameworks, patterns, decision-making]
412
+ ## Approach
413
+ [How you analyze and solve problems in this domain]
326
414
 
327
- ## Integration & Collaboration
415
+ ## Tools & Techniques
416
+ - [Tool/Technique 1]
417
+ - [Tool/Technique 2]
418
+ - [Tool/Technique 3]
328
419
 
329
- [How this agent works with other agents and the broader system]
420
+ ## Collaboration
421
+ - **With Implementers**: Provide specifications and guidance
422
+ - **With Reviewers**: Share domain expertise
423
+ - **Solo**: Full end-to-end implementation
330
424
 
331
425
  ## Success Metrics
332
-
333
- [How to measure agent effectiveness]
426
+ - Domain-specific quality criteria
427
+ - Stakeholder satisfaction
428
+ - Technical accuracy
429
+ - Confidence score ≥ 0.85
334
430
  ```
335
431
 
336
432
  ---
337
433
 
338
- ### 2. The Complexity-Verbosity Inverse Law
434
+ ## Customization Guide
339
435
 
340
- **Empirical Finding:** Task complexity and prompt verbosity have an inverse relationship.
436
+ ### 1. Choosing the Right Model
341
437
 
342
- ```
343
- Basic Tasks (parsing, CRUD):
344
- - Code-Heavy: 85.3% quality (+43% vs Minimal)
345
- - Best approach: Detailed examples with step-by-step guidance
438
+ | Model | Speed | Cost | Best For |
439
+ |-------|-------|------|----------|
440
+ | **haiku** | ⚡⚡⚡ | $ | Simple tasks, quick iterations |
441
+ | **sonnet** | ⚡⚡ | $$ | Balanced performance, most tasks |
442
+ | **opus** | ⚡ | $$$ | Complex reasoning, critical tasks |
346
443
 
347
- Complex Tasks (architecture, lock-free algorithms):
348
- - Minimal: 87.2% quality (+31% vs Code-Heavy)
349
- - Best approach: High-level principles with reasoning freedom
350
- ```
444
+ **Recommendation:** Start with `haiku`, upgrade to `sonnet` if needed.
351
445
 
352
- **Why This Matters:**
353
- - Basic tasks benefit from concrete patterns (priming effect)
354
- - Complex tasks need creative freedom (over-specification creates tunnel vision)
355
- - Medium tasks need structured scaffolding without over-constraining
446
+ ### 2. Selecting Tools
356
447
 
357
- **For detailed analysis:** See [Format Selection Principles](./agent-principles/format-selection.md)
448
+ Available tools:
449
+ ```yaml
450
+ # File Operations
451
+ tools: [Read, Write, Edit, MultiEdit]
358
452
 
359
- ---
453
+ # Search & Navigation
454
+ tools: [Grep, Glob]
360
455
 
361
- ### 3. Mandatory Post-Edit Validation System
456
+ # Execution
457
+ tools: [Bash]
362
458
 
363
- **UNIVERSAL REQUIREMENT:** Every agent MUST run post-edit hooks after file modifications.
459
+ # Coordination & Task Management
460
+ tools: [TodoWrite]
364
461
 
365
- ```bash
366
- npx claude-flow@alpha hooks post-edit [FILE_PATH] \
367
- --memory-key "agent-name/context" \
368
- --structured
462
+ # Agent Spawning (Coordinators)
463
+ tools: [Bash] # For CLI spawning: npx claude-flow-novice agent-spawn
369
464
  ```
370
465
 
371
- **Core Benefits:**
372
- - TDD compliance verification
373
- - Security analysis (XSS, eval(), hardcoded credentials)
374
- - Formatting validation (Prettier, rustfmt)
375
- - Test coverage analysis (≥80% line, ≥75% branch)
376
- - Cross-agent memory coordination
377
- - Actionable recommendations
378
-
379
- **Four Production-Ready Validators:**
380
-
381
- 1. **Agent Template Validator** (Priority 1 - CRITICAL)
382
- - Validates SQLite lifecycle hooks (spawn, update, terminate)
383
- - Validates ACL level declarations (1-5)
384
- - Validates error handling patterns (SQLite failures, Redis connection loss)
385
- - Validates blocking coordination imports (coordinators only)
386
- - Triggers: On edit to `.claude/agents/**/*.md` files
387
- - Automation: 95% (WASM-accelerated pattern matching)
388
-
389
- 2. **CFN Loop Memory Pattern Validator** (Priority 2 - HIGH)
390
- - Validates ACL level correctness (Loop 3: Private=1, Loop 2: Swarm=3, Loop 4: Project=4)
391
- - Validates memory key format (`cfn/phase-{id}/loop{N}/...`)
392
- - Validates TTL values match retention policies (Loop 4: 365 days)
393
- - Validates encryption for sensitive data (Loop 3 private data)
394
- - Triggers: On `memory.set()` calls in code
395
- - Automation: 90% (deterministic rule matching)
396
-
397
- 3. **Test Coverage Validator** (Priority 3 - MEDIUM)
398
- - Validates line coverage ≥ 80%
399
- - Validates branch coverage ≥ 75%
400
- - Validates function coverage ≥ 80%
401
- - Validates agent lifecycle tests present
402
- - Validates signal ACK protocol tests present
403
- - Triggers: After test execution
404
- - Automation: 100% (quantitative metrics)
405
-
406
- 4. **Blocking Coordination Validator** (DEPRECATED - Use Redis BLPOP instead)
407
- - ⚠️ **Status**: Deprecated in favor of Redis BLPOP primitives
408
- - See: `.claude/skills/redis-coordination/SKILL.md` for modern patterns
409
- - Migration guide: `legacy/v1/deprecated/BLOCKING_COORDINATION_MIGRATION.md`
410
-
411
- **Hook Composition Pattern:**
412
-
413
- Hooks compose for comprehensive validation:
414
-
415
- ```javascript
416
- // CompositeHook pattern enables layered validation
417
- const agentValidation = new CompositeHook(
418
- new AgentTemplateValidator(),
419
- new CFNLoopMemoryValidator(),
420
- new TestCoverageValidator()
421
- );
466
+ **Note:** Agent coordination uses Redis pub/sub + CLI spawning, not MCP tools.
422
467
 
423
- // Results merge for actionable recommendations
424
- const result = await agentValidation.validate(file, content);
425
- // → { valid: boolean, results: [], combinedRecommendations: [] }
426
- ```
468
+ **Rule of Thumb:** Only include tools your agent will actually use. More tools = more complexity.
427
469
 
428
- **Performance Expectations:**
429
- - Individual validator: <2s (WASM-accelerated)
430
- - Composite validation: <5s total (parallel execution)
431
- - False positive rate: <2%
470
+ ### 3. Setting ACL Levels
432
471
 
433
- **For integration details:** See [Prompt Engineering Best Practices](./agent-principles/prompt-engineering.md)
472
+ | Level | Scope | Use When |
473
+ |-------|-------|----------|
474
+ | **1** | Private | Agent's own data only |
475
+ | **3** | Swarm | Shared across team of agents |
476
+ | **4** | Project | Strategic decisions, audit logs |
477
+ | **5** | System | Infrastructure only |
434
478
 
435
- ---
479
+ **Most agents use level 1 or 3.**
436
480
 
437
- ### 4. Agent Template Validator Specification
481
+ ### 4. Adding Capabilities (Tags)
438
482
 
439
- **Purpose:** Ensures all agent templates follow SQLite lifecycle, ACL, and error handling best practices.
440
-
441
- **Validation Criteria:**
442
-
443
- ✅ **SQLite Lifecycle Hooks** (All agents MUST persist to SQLite for audit trail)
444
- ```typescript
445
- // Agent spawn registration
446
- await sqlite.execute(`
447
- INSERT INTO agents (id, type, status, spawned_at)
448
- VALUES (?, ?, 'active', CURRENT_TIMESTAMP)
449
- `, [agentId, agentType]);
450
-
451
- // Confidence score updates during execution
452
- await sqlite.execute(`
453
- UPDATE agents SET status = ?, confidence = ?, updated_at = CURRENT_TIMESTAMP
454
- WHERE id = ?
455
- `, [status, confidenceScore, agentId]);
456
-
457
- // Agent termination and cleanup
458
- await sqlite.execute(`
459
- UPDATE agents SET status = 'completed', completed_at = CURRENT_TIMESTAMP
460
- WHERE id = ?
461
- `, [agentId]);
462
- ```
463
-
464
- ✅ **ACL Level Declaration** (Data access control by agent type)
465
483
  ```yaml
466
- # ACL Level Guidelines by Agent Type:
467
- implementers:
468
- acl_level: 1 # Private (agent-scoped data)
469
- example: "coder, backend-dev, frontend-dev"
470
-
471
- validators:
472
- acl_level: 3 # Swarm (shared across validation team)
473
- example: "reviewer, security-specialist, tester"
474
-
475
- coordinators:
476
- acl_level: 3 # Swarm (coordinate multiple agents)
477
- example: "architect, planner, devops-engineer"
478
-
479
- product_owner:
480
- acl_level: 4 # Project (strategic decisions, audit trail)
481
- example: "product-owner (CFN Loop 4 only)"
482
- ```
483
-
484
- ✅ **Error Handling for SQLite Failures**
485
- ```javascript
486
- try {
487
- await sqlite.memoryAdapter.set(key, value, { aclLevel: 1 });
488
- } catch (error) {
489
- if (error.code === 'SQLITE_BUSY') {
490
- // Retry with exponential backoff
491
- await retryWithBackoff(() => sqlite.memoryAdapter.set(key, value));
492
- } else if (error.code === 'SQLITE_LOCKED') {
493
- // Wait for lock release
494
- await waitForLockRelease(key);
495
- } else {
496
- // Log and gracefully degrade
497
- console.error('SQLite failure:', error);
498
- // Fallback to Redis for non-critical data
499
- await redis.set(key, value);
500
- }
501
- }
484
+ capabilities:
485
+ - rust # Language expertise
486
+ - api-design # Domain knowledge
487
+ - security-review # Specialized skill
488
+ - performance-opt # Focus area
502
489
  ```
503
490
 
504
- **Redis BLPOP Coordination** (Coordinators - Modern Pattern)
505
- ```bash
506
- # Zero-token blocking coordination using Redis primitives
507
- # See: .claude/skills/redis-coordination/SKILL.md
491
+ These help with agent discovery and routing.
508
492
 
509
- # Agent signals completion
510
- redis-cli lpush "swarm:${TASK_ID}:${AGENT_ID}:done" "complete"
493
+ ### 5. Customizing Behavior
511
494
 
512
- # Coordinator blocks until agent completes (zero tokens consumed)
513
- redis-cli blpop "swarm:${TASK_ID}:${AGENT_ID}:done" 30
495
+ **Tone & Style:**
496
+ ```markdown
497
+ You are a [friendly/professional/technical] agent that [approach].
514
498
 
515
- # Wake agent for next iteration
516
- ./.claude/skills/redis-coordination/invoke-waiting-mode.sh wake \
517
- --task-id "$TASK_ID" --agent-id "$AGENT_ID" --reason "cfn_loop_iteration"
499
+ ## Communication Style
500
+ - Use [formal/casual] language
501
+ - Provide [detailed/concise] explanations
502
+ - Focus on [theory/practice]
518
503
  ```
519
504
 
520
- **Memory Key Patterns:**
521
-
522
- ```yaml
523
- # Standard agent memory patterns
524
- agent_memory:
525
- format: "agent/{agentId}/confidence/{taskId}"
526
- example: "agent/coder-1/confidence/auth-implementation"
527
- acl_level: 1 # Private to agent
528
-
529
- # CFN Loop memory patterns
530
- cfn_loop_memory:
531
- loop_3: "cfn/phase-{id}/loop3/agent-{id}/{metric}"
532
- loop_2: "cfn/phase-{id}/loop2/validation/{validator-id}"
533
- loop_4: "cfn/phase-{id}/loop4/decision/{decision-type}"
534
-
535
- # ACL levels by loop
536
- loop_3_acl: 1 # Private (implementation details)
537
- loop_2_acl: 3 # Swarm (validation team access)
538
- loop_4_acl: 4 # Project (strategic decisions)
505
+ **Decision-Making:**
506
+ ```markdown
507
+ ## Decision Framework
508
+ When [situation], prioritize:
509
+ 1. [Criterion 1]
510
+ 2. [Criterion 2]
511
+ 3. [Criterion 3]
539
512
  ```
540
513
 
541
- **Validation Trigger:**
542
- - File path: `.claude/agents/**/*.md`
543
- - Trigger event: File save/edit
544
- - Execution time: <2s (WASM-accelerated)
545
- - Integration: Automatic via post-edit hook
546
-
547
- **Validation Output Example:**
548
-
549
- ```json
550
- {
551
- "validator": "agent-template-validator",
552
- "file": ".claude/agents/backend/coder.md",
553
- "valid": false,
554
- "violations": [
555
- {
556
- "type": "missing_sqlite_lifecycle",
557
- "severity": "error",
558
- "message": "Missing agent spawn registration (INSERT INTO agents)",
559
- "line": null,
560
- "recommendation": "Add SQLite lifecycle hooks in agent initialization"
561
- },
562
- {
563
- "type": "missing_acl_declaration",
564
- "severity": "error",
565
- "message": "No ACL level declared for memory operations",
566
- "line": 45,
567
- "recommendation": "Add aclLevel: 1 for implementer agents"
568
- }
569
- ],
570
- "warnings": [
571
- {
572
- "type": "error_handling_basic",
573
- "message": "Basic error handling present, consider retry logic",
574
- "recommendation": "Implement exponential backoff for SQLite BUSY errors"
575
- }
576
- ]
577
- }
514
+ **Error Handling:**
515
+ ```markdown
516
+ ## Error Handling Strategy
517
+ - For [error type]: [action]
518
+ - If [condition]: [fallback]
519
+ - Always: [safety measure]
578
520
  ```
579
521
 
580
- **For CFN Loop integration:** See section on SQLite Integration Requirements below.
581
-
582
522
  ---
583
523
 
584
- ### 5. SQLite Integration Requirements
585
-
586
- **All agents MUST persist to SQLite for audit trail and cross-session recovery.**
587
-
588
- **ACL Level Guidelines:**
589
-
590
- | Agent Type | ACL Level | Scope | Example Use Cases |
591
- |-----------|-----------|-------|-------------------|
592
- | **Implementers** | 1 (Private) | Agent-scoped data | Code snippets, temporary state, confidence scores |
593
- | **Validators** | 3 (Swarm) | Validation team shared | Review feedback, security findings, test results |
594
- | **Coordinators** | 3 (Swarm) | Multi-agent coordination | Task assignments, progress tracking, blocking signals |
595
- | **Product Owner** | 4 (Project) | Strategic decisions | GOAP decisions, backlog items, phase approvals |
596
-
597
- **Memory Key Patterns:**
598
-
599
- ```javascript
600
- // Standard agent memory
601
- const agentKey = `agent/${agentId}/confidence/${taskId}`;
602
- await sqlite.memoryAdapter.set(agentKey, confidenceScore, {
603
- aclLevel: 1, // Private to agent
604
- ttl: 2592000 // 30 days
605
- });
606
-
607
- // CFN Loop patterns
608
- const loop3Key = `cfn/phase-auth/loop3/agent-coder-1/implementation`;
609
- await sqlite.memoryAdapter.set(loop3Key, implementationDetails, {
610
- aclLevel: 1, // Private (Loop 3 implementation)
611
- ttl: 2592000 // 30 days
612
- });
613
-
614
- const loop2Key = `cfn/phase-auth/loop2/validation/reviewer-1`;
615
- await sqlite.memoryAdapter.set(loop2Key, validationResults, {
616
- aclLevel: 3, // Swarm (Loop 2 validation team)
617
- ttl: 7776000 // 90 days
618
- });
619
-
620
- const loop4Key = `cfn/phase-auth/loop4/decision/proceed`;
621
- await sqlite.memoryAdapter.set(loop4Key, goapDecision, {
622
- aclLevel: 4, // Project (Loop 4 strategic decision)
623
- ttl: 31536000 // 365 days (compliance requirement)
624
- });
625
- ```
626
-
627
- **Error Handling Patterns:**
628
-
629
- ```javascript
630
- // Retry with exponential backoff for transient errors
631
- async function retryWithBackoff(operation, maxRetries = 3) {
632
- for (let i = 0; i < maxRetries; i++) {
633
- try {
634
- return await operation();
635
- } catch (error) {
636
- if (error.code === 'SQLITE_BUSY' && i < maxRetries - 1) {
637
- const delay = Math.pow(2, i) * 100; // 100ms, 200ms, 400ms
638
- await new Promise(resolve => setTimeout(resolve, delay));
639
- } else {
640
- throw error;
641
- }
642
- }
643
- }
644
- }
645
-
646
- // Graceful degradation for non-critical data
647
- async function writeWithFallback(key, value, options) {
648
- try {
649
- await sqlite.memoryAdapter.set(key, value, options);
650
- } catch (error) {
651
- console.warn('SQLite write failed, falling back to Redis:', error);
652
- // Fallback to Redis for non-audit data only
653
- if (options.aclLevel < 4) {
654
- await redis.set(key, JSON.stringify(value));
655
- } else {
656
- // Critical data MUST persist to SQLite
657
- throw new Error('Cannot write critical data to fallback store');
658
- }
659
- }
660
- }
661
- ```
524
+ ## Testing Your Agent
662
525
 
663
- **Agent Lifecycle Hooks Integration:**
526
+ ### Manual Testing
664
527
 
665
- ```yaml
666
- # In agent frontmatter
667
- lifecycle:
668
- pre_task: |
669
- # Register agent in SQLite on spawn
670
- sqlite-cli exec "INSERT INTO agents (id, type, status, spawned_at)
671
- VALUES ('${AGENT_ID}', '${AGENT_TYPE}', 'active', CURRENT_TIMESTAMP)"
528
+ ```bash
529
+ # Basic spawn test
530
+ npx claude-flow-novice agent-spawn my-agent --task-id test-1
672
531
 
673
- post_task: |
674
- # Update agent status and confidence on completion
675
- sqlite-cli exec "UPDATE agents
676
- SET status = 'completed',
677
- confidence = ${CONFIDENCE_SCORE},
678
- completed_at = CURRENT_TIMESTAMP
679
- WHERE id = '${AGENT_ID}'"
532
+ # With specific prompt
533
+ npx claude-flow-novice agent-spawn my-agent \
534
+ --task-id test-2 \
535
+ --prompt "Specific task instructions"
680
536
  ```
681
537
 
682
- **For CFN Loop memory patterns:** See CFN Loop Memory Pattern Validator above.
683
-
684
- ---
538
+ ### Integration Testing
685
539
 
686
- ### 6. Integration with Claude Flow
540
+ Create a test task:
541
+ ```bash
542
+ # Create test directory
543
+ mkdir -p tests/agents
687
544
 
688
- #### Hook System
545
+ # Create test file
546
+ cat > tests/agents/test-my-agent.sh << 'EOF'
547
+ #!/bin/bash
548
+ set -e
689
549
 
690
- Every agent integrates with:
691
- - **Pre-task hooks**: Initialize context, set up memory namespace, register in SQLite
692
- - **Post-edit hooks**: Validate quality, coordinate with other agents, run validators
693
- - **Post-task hooks**: Finalize task, export metrics, update SQLite status
694
- - **Session management**: Persist state across sessions via SQLite
550
+ echo "Testing my-agent..."
695
551
 
696
- #### Memory Coordination (SQLite + ACL)
552
+ # Spawn agent
553
+ npx claude-flow-novice agent-spawn my-agent \
554
+ --task-id test-integration
697
555
 
698
- ```javascript
699
- // Standard memory key pattern: {agent-type}/{domain}/{aspect}
700
- await sqlite.memoryAdapter.set("architect/auth/design", designDoc, { aclLevel: 3 });
701
- await sqlite.memoryAdapter.set("coder/auth/implementation", code, { aclLevel: 1 });
702
- await sqlite.memoryAdapter.set("reviewer/auth/feedback", feedback, { aclLevel: 3 });
703
- await sqlite.memoryAdapter.set("tester/auth/coverage", coverage, { aclLevel: 3 });
556
+ # Verify output
557
+ # [Add your verification logic]
704
558
 
705
- // CFN Loop memory pattern: cfn/phase-{id}/loop{N}/{agent-id}/{metric}
706
- await sqlite.memoryAdapter.set("cfn/phase-auth/loop3/coder-1/confidence", 0.85, {
707
- aclLevel: 1, // Loop 3: Private implementation data
708
- ttl: 2592000 // 30 days
709
- });
559
+ echo "✅ Test passed"
560
+ EOF
710
561
 
711
- await sqlite.memoryAdapter.set("cfn/phase-auth/loop2/reviewer-1/consensus", 0.92, {
712
- aclLevel: 3, // Loop 2: Swarm validation data
713
- ttl: 7776000 // 90 days
714
- });
562
+ chmod +x tests/agents/test-my-agent.sh
715
563
 
716
- await sqlite.memoryAdapter.set("cfn/phase-auth/loop4/decision", "DEFER", {
717
- aclLevel: 4, // Loop 4: Project strategic decision
718
- ttl: 31536000 // 365 days (compliance)
719
- });
564
+ # Run test
565
+ ./tests/agents/test-my-agent.sh
720
566
  ```
721
567
 
722
- **ACL Enforcement:**
723
- - ACL Level 1 (Private): Only creating agent can read
724
- - ACL Level 3 (Swarm): All agents in same swarm can read
725
- - ACL Level 4 (Project): All agents in project can read
726
- - ACL Level 5 (Team/System): Reserved for infrastructure
568
+ ### Validation Checklist
727
569
 
728
- #### Swarm Coordination with SQLite Lifecycle
570
+ Before deploying your agent:
729
571
 
730
- When spawning multiple agents:
731
- 1. **Pre-task hook**: Register agent in SQLite, initialize memory namespace
732
- 2. **Execute work**: Implement task with progress updates to SQLite
733
- 3. **Post-edit hook**: Validate each file with all 4 validators (agent-template, cfn-loop-memory, test-coverage, blocking-coordination)
734
- 4. **Store results**: Persist to SQLite with appropriate ACL level
735
- 5. **Post-task hook**: Finalize task, update agent status to 'completed', export metrics
572
+ - [ ] YAML frontmatter is valid
573
+ - [ ] Name is unique and descriptive
574
+ - [ ] Description includes use cases and keywords
575
+ - [ ] Tools list includes only needed tools
576
+ - [ ] Core responsibilities are clear
577
+ - [ ] Success metrics are defined
578
+ - [ ] Agent tested with sample tasks
579
+ - [ ] Documentation is complete
736
580
 
737
- **Hook Execution Sequence:**
581
+ ---
738
582
 
739
- ```bash
740
- # 1. Pre-task: Agent registration
741
- sqlite-cli exec "INSERT INTO agents (id, type, status, spawned_at) VALUES ('coder-1', 'coder', 'active', CURRENT_TIMESTAMP)"
583
+ ## Advanced Concepts
742
584
 
743
- # 2. Work execution with progress updates
744
- sqlite-cli exec "UPDATE agents SET status = 'in_progress', updated_at = CURRENT_TIMESTAMP WHERE id = 'coder-1'"
585
+ ### Multi-Agent Coordination
745
586
 
746
- # 3. Post-edit: Run all applicable validators
747
- npx claude-flow@alpha hooks post-edit src/auth.js --memory-key "agent/coder-1/auth" --structured
748
- # → Triggers: agent-template-validator, cfn-loop-memory-validator, test-coverage-validator
587
+ Agents can work together using Redis pub/sub and CLI spawning:
749
588
 
750
- # 4. Store results with ACL
751
- sqlite-cli exec "INSERT INTO memory (key, value, acl_level, ttl) VALUES ('agent/coder-1/confidence/auth', '0.85', 1, 2592000)"
589
+ ```markdown
590
+ ## Redis Coordination
591
+ → See: `.claude/templates/redis-coordination.md`
752
592
 
753
- # 5. Post-task: Finalization
754
- sqlite-cli exec "UPDATE agents SET status = 'completed', confidence = 0.85, completed_at = CURRENT_TIMESTAMP WHERE id = 'coder-1'"
593
+ ### Agent Spawning Pattern
594
+ ```bash
595
+ # Spawn agents via CLI (coordinators only)
596
+ npx claude-flow-novice agent-spawn backend-dev --task-id "${TASK_ID}"
597
+ npx claude-flow-novice agent-spawn reviewer --task-id "${TASK_ID}"
755
598
  ```
756
599
 
757
- **Hook Composition for Coordinators:**
758
-
759
- Coordinator agents run standard validation:
760
-
600
+ ### Signaling Pattern
761
601
  ```bash
762
- # Coordinators trigger standard validators
763
- npx claude-flow@alpha hooks post-edit src/coordinator.js --memory-key "agent/coordinator-1/phase" --structured
764
- # → Triggers: agent-template-validator, cfn-loop-memory-validator
602
+ # Signal completion
603
+ redis-cli lpush "swarm:${TASK_ID}:${AGENT_ID}:done" "complete"
765
604
 
766
- # For Redis coordination validation, see:
767
- # .claude/skills/redis-coordination/test-orchestrator.sh (8/8 passing tests)
605
+ # Wait for other agent (zero-token blocking)
606
+ redis-cli blpop "swarm:${TASK_ID}:other-agent:done" 30
607
+ ```
768
608
  ```
769
609
 
770
- **Performance:**
771
- - Sequential validators: ~5-8s total
772
- - Parallel validators (independent): ~2-3s total (recommended)
773
- - WASM acceleration: 52x speedup for pattern matching
774
-
775
- **For detailed integration:** See [Prompt Engineering Best Practices](./agent-principles/prompt-engineering.md)
776
-
777
- ---
778
-
779
- ## Agent Profile Structure
780
-
781
- ### The Three Formats
782
-
783
- 1. **MINIMAL (200-400 lines)**: For complex, strategic tasks requiring reasoning freedom
784
- 2. **METADATA (400-700 lines)**: For medium complexity with structured workflows
785
- 3. **CODE-HEAVY (700-1200 lines)**: For basic tasks benefiting from concrete examples
610
+ ### Memory Operations
786
611
 
787
- **Detailed format specifications:** [Format Selection Principles](./agent-principles/format-selection.md)
612
+ Agents can persist and share data:
788
613
 
789
- ### Format Selection Decision Tree
614
+ ```markdown
615
+ ## Memory Operations
616
+ → See: `.claude/templates/memory-operations.md`
790
617
 
618
+ ### SQLite Integration
619
+ ```typescript
620
+ await sqlite.memoryAdapter.set(
621
+ `agent/${agentId}/data/${taskId}`,
622
+ { confidence: 0.85, status: 'complete' },
623
+ { aclLevel: 1, ttl: 2592000 }
624
+ );
791
625
  ```
792
- Task Complexity Assessment
793
-
794
- ┌───┴────┐
795
- │ │
796
- BASIC COMPLEX
797
- │ │
798
- CODE-HEAVY MINIMAL
799
626
  ```
800
627
 
801
- **Full decision tree and factors:** [Format Selection Principles](./agent-principles/format-selection.md)
628
+ ### CFN Loop Integration
802
629
 
803
- ---
630
+ For self-correcting workflows:
804
631
 
805
- ## Examples & Templates
632
+ ```markdown
633
+ ## CFN Loop Mechanics
634
+ → See: `.claude/templates/cfn-loop-mechanics.md`
806
635
 
807
- ### Example 1: Minimal Format (Complex Tasks)
636
+ Agents participate in 3-loop validation:
637
+ - Loop 3: Implementation
638
+ - Loop 2: Validation
639
+ - Loop 4: Strategic decisions
640
+ ```
808
641
 
809
- **File:** `.claude/agents/architecture/system-architect.md`
642
+ ### Lifecycle Hooks
810
643
 
811
- ```markdown
812
- ---
813
- name: system-architect
814
- description: |
815
- MUST BE USED when designing enterprise-grade system architecture.
816
- Use PROACTIVELY for distributed systems, event-driven architecture.
817
- Keywords - architecture, system design, microservices, scalability
818
- tools: [Read, Write, Edit, Bash, Grep, Glob, TodoWrite]
819
- model: sonnet
820
- color: seagreen
821
- type: coordinator
822
- validation_hooks:
823
- - agent-template-validator
824
- - cfn-loop-memory-validator
644
+ ```yaml
825
645
  lifecycle:
826
646
  pre_task: |
827
- sqlite-cli exec "INSERT INTO agents (id, type, status, spawned_at)
828
- VALUES ('${AGENT_ID}', 'system-architect', 'active', CURRENT_TIMESTAMP)"
829
- post_task: |
830
- sqlite-cli exec "UPDATE agents
831
- SET status = 'completed', confidence = ${CONFIDENCE_SCORE},
832
- completed_at = CURRENT_TIMESTAMP
833
- WHERE id = '${AGENT_ID}'"
834
- ---
835
-
836
- # System Architect Agent
647
+ # Runs before agent starts
648
+ echo "Initializing agent..."
837
649
 
838
- You are a senior system architect with deep expertise in designing
839
- scalable, maintainable, and robust software systems.
650
+ post_task: |
651
+ # Runs after agent completes
652
+ echo "Agent completed with confidence: ${CONFIDENCE_SCORE}"
653
+ ```
840
654
 
841
- ## 🚨 MANDATORY POST-EDIT VALIDATION
655
+ ### Validation Hooks
842
656
 
843
- After EVERY file edit:
844
- ```bash
845
- npx claude-flow@alpha hooks post-edit [FILE] --memory-key "architect/${AGENT_ID}/step" --structured
657
+ ```yaml
658
+ validation_hooks:
659
+ - agent-template-validator # Validates agent structure
660
+ - cfn-loop-memory-validator # Validates memory operations
661
+ - test-coverage-validator # Validates test coverage
846
662
  ```
847
663
 
848
- This triggers: agent-template-validator, cfn-loop-memory-validator
664
+ ---
849
665
 
850
- ## SQLite Integration
666
+ ## Troubleshooting
851
667
 
852
- All architectural decisions MUST persist to SQLite with ACL Level 3 (Swarm):
668
+ ### Agent Not Found
853
669
 
854
- ```javascript
855
- // Store ADR in SQLite
856
- await sqlite.memoryAdapter.set(
857
- `architect/${agentId}/adr/${componentName}`,
858
- architectureDecisionRecord,
859
- { aclLevel: 3, ttl: 31536000 } // 1 year retention
860
- );
670
+ **Problem:** `Error: Agent 'my-agent' not found`
861
671
 
862
- // Error handling with retry
863
- try {
864
- await sqlite.memoryAdapter.set(key, value, options);
865
- } catch (error) {
866
- if (error.code === 'SQLITE_BUSY') {
867
- await retryWithBackoff(() => sqlite.memoryAdapter.set(key, value, options));
868
- } else {
869
- throw error;
870
- }
871
- }
872
- ```
672
+ **Solutions:**
673
+ 1. Check file is in `.claude/agents/` directory
674
+ 2. Verify filename matches agent name: `my-agent.md`
675
+ 3. Ensure YAML frontmatter has `name: my-agent`
873
676
 
874
- ## Core Responsibilities
677
+ ### Invalid YAML
875
678
 
876
- - Design system architectures from business requirements
877
- - Make strategic technical decisions with clear rationale
878
- - Define component boundaries and interactions
879
- - Ensure scalability, security, and maintainability
880
- - Create Architecture Decision Records (ADRs)
881
- - Persist all decisions to SQLite for audit trail
679
+ **Problem:** `Error: Invalid YAML frontmatter`
882
680
 
883
- ## Architectural Approach
681
+ **Solutions:**
682
+ 1. Check YAML syntax with `---` delimiters
683
+ 2. Ensure proper indentation (2 spaces)
684
+ 3. Quote special characters in strings
685
+ 4. Validate at https://www.yamllint.com/
884
686
 
885
- ### Requirements Analysis
886
- Extract functional and non-functional requirements, identify constraints
887
- and quality attributes, understand stakeholder needs.
687
+ ### Agent Behavior Issues
888
688
 
889
- ### Design Process
890
- Apply appropriate patterns (microservices, event-driven, CQRS), consider
891
- trade-offs, document decisions with ADRs.
689
+ **Problem:** Agent doesn't perform as expected
892
690
 
893
- ### Quality Attributes
894
- - Performance: Response times, throughput
895
- - Scalability: Horizontal and vertical scaling
896
- - Security: Zero-trust, defense-in-depth
897
- - Maintainability: Modular design, clear interfaces
898
- - Reliability: Fault tolerance, disaster recovery
691
+ **Solutions:**
692
+ 1. Review and clarify core responsibilities
693
+ 2. Simplify instructions (less is often more)
694
+ 3. Add specific examples of desired behavior
695
+ 4. Test with varied prompts
696
+ 5. Check model choice (try upgrading haiku → sonnet)
899
697
 
900
- ## Collaboration
698
+ ### Tools Not Working
901
699
 
902
- - Work with Coder agents for implementation guidance (ACL 1)
903
- - Coordinate with Reviewer agents for design validation (ACL 3)
904
- - Provide specifications to DevOps for infrastructure (ACL 3)
905
- - Share ADRs via SQLite memory system (ACL 3)
700
+ **Problem:** `Error: Tool [X] not available`
906
701
 
907
- ## Success Metrics
702
+ **Solutions:**
703
+ 1. Verify tool is in frontmatter `tools` list
704
+ 2. Check spelling matches exactly
705
+ 3. For agent spawning, use Bash tool with CLI commands
706
+ 4. Review tool permissions
908
707
 
909
- - Architecture meets quality attributes
910
- - Team can implement the design
911
- - Documentation is clear and comprehensive
912
- - Trade-offs are explicitly documented
913
- - All decisions persisted to SQLite with appropriate ACL
914
- ```
708
+ ### Memory/Coordination Issues
915
709
 
916
- **For more examples:** [Format Selection Principles](./agent-principles/format-selection.md)
710
+ **Problem:** Agents can't share data
917
711
 
918
- ---
712
+ **Solutions:**
713
+ 1. Check Redis is running: `redis-cli ping`
714
+ 2. Verify ACL levels are compatible
715
+ 3. Ensure memory keys follow patterns
716
+ 4. Check SQLite database exists
919
717
 
920
- ### Example 2: Metadata Format (Medium Tasks with CFN Loop Integration)
718
+ ---
921
719
 
922
- **File:** `.claude/agents/development/api-developer.md`
720
+ ## Example: Complete Custom Agent
923
721
 
924
- **Key additions for CFN Loop:**
925
- ```yaml
926
- validation_hooks:
927
- - agent-template-validator
928
- - cfn-loop-memory-validator
929
- - test-coverage-validator
930
- lifecycle:
931
- pre_task: "sqlite-cli exec 'INSERT INTO agents ...'"
932
- post_task: "sqlite-cli exec 'UPDATE agents SET status=completed ...'"
933
- ```
722
+ Here's a real-world example - a Terraform reviewer agent:
934
723
 
935
- **CFN Loop Memory Persistence:**
936
- ```javascript
937
- // Loop 3: Implementation confidence (Private)
938
- await sqlite.memoryAdapter.set(
939
- `cfn/phase-api/loop3/api-developer-1/confidence`,
940
- 0.85,
941
- { aclLevel: 1, ttl: 2592000 } // Private, 30 days
942
- );
724
+ ```markdown
725
+ ---
726
+ name: terraform-reviewer
727
+ description: |
728
+ MUST BE USED when reviewing Terraform infrastructure code.
729
+ Use PROACTIVELY for IaC review, security validation, cost optimization.
730
+ Keywords - terraform, infrastructure, IaC, cloud, AWS, security
731
+ tools: [Read, Grep, Glob, TodoWrite]
732
+ model: sonnet
733
+ type: specialist
734
+ capabilities:
735
+ - terraform
736
+ - infrastructure-as-code
737
+ - cloud-security
738
+ - cost-optimization
739
+ acl_level: 3
740
+ ---
943
741
 
944
- // Loop 2: Validation feedback (Swarm)
945
- await sqlite.memoryAdapter.set(
946
- `cfn/phase-api/loop2/reviewer-1/feedback`,
947
- reviewFeedback,
948
- { aclLevel: 3, ttl: 7776000 } // Swarm, 90 days
949
- );
950
- ```
742
+ # Terraform Infrastructure Reviewer
951
743
 
952
- **For complete example:** See API Developer template in [Format Selection Principles](./agent-principles/format-selection.md)
744
+ You are an infrastructure expert specializing in Terraform code review with
745
+ focus on security, best practices, and cost optimization.
953
746
 
954
- ---
747
+ ## Core Responsibilities
955
748
 
956
- ### Example 3: Code-Heavy Format (Basic Tasks with Blocking Coordination)
749
+ ### 1. Security Review
750
+ - Check for exposed secrets or credentials
751
+ - Validate IAM policies (principle of least privilege)
752
+ - Review security group rules
753
+ - Ensure encryption at rest and in transit
754
+ - Verify logging and monitoring
755
+
756
+ ### 2. Best Practices
757
+ - Validate resource naming conventions
758
+ - Check for proper tagging strategy
759
+ - Ensure state management best practices
760
+ - Review module structure and reusability
761
+ - Validate provider versioning
762
+
763
+ ### 3. Cost Optimization
764
+ - Identify over-provisioned resources
765
+ - Flag expensive resource types
766
+ - Suggest reserved instances where applicable
767
+ - Review data transfer patterns
768
+ - Validate auto-scaling configurations
769
+
770
+ ### 4. Compliance
771
+ - Check against company standards
772
+ - Validate regulatory requirements
773
+ - Ensure disaster recovery provisions
774
+ - Review backup strategies
775
+
776
+ ## Review Process
777
+
778
+ 1. **Parse Terraform Files**
779
+ - Read all `.tf` files in directory
780
+ - Identify resource types and configurations
781
+ - Map dependencies
782
+
783
+ 2. **Security Analysis**
784
+ - Run security checklist
785
+ - Flag critical issues
786
+ - Identify vulnerabilities
787
+
788
+ 3. **Cost Analysis**
789
+ - Estimate monthly costs
790
+ - Identify optimization opportunities
791
+ - Calculate potential savings
792
+
793
+ 4. **Compliance Check**
794
+ - Verify against standards
795
+ - Document exceptions
796
+ - Recommend remediation
797
+
798
+ 5. **Generate Report**
799
+ - Categorize findings by severity
800
+ - Provide specific recommendations
801
+ - Include confidence score
802
+
803
+ ## Output Format
804
+
805
+ ### Summary
806
+ - Overall confidence score (0.0-1.0)
807
+ - Total issues found by severity
808
+ - Estimated monthly cost
809
+ - Compliance status
810
+
811
+ ### Detailed Findings
812
+
813
+ **🔴 Critical Issues** (must fix before deployment)
814
+ - [Issue description]
815
+ - File: `path/to/file.tf:line`
816
+ - Recommendation: [specific fix]
817
+
818
+ **🟡 Warnings** (should address)
819
+ - [Issue description]
820
+ - Impact: [description]
821
+ - Suggestion: [improvement]
822
+
823
+ **🟢 Optimizations** (nice to have)
824
+ - [Opportunity description]
825
+ - Potential savings: [amount]
826
+ - Effort: [low/medium/high]
957
827
 
958
- **File:** `.claude/agents/coordination/coordinator.md`
828
+ ## Success Metrics
829
+ - Security score ≥ 0.90
830
+ - Zero critical vulnerabilities
831
+ - Cost optimization opportunities identified
832
+ - Compliance requirements met
833
+ - Clear, actionable feedback
959
834
 
960
- **Key additions for coordinators:**
961
- ```yaml
962
- type: coordinator
963
- validation_hooks:
964
- - agent-template-validator
965
- - cfn-loop-memory-validator
966
- - blocking-coordination-validator # Coordinator-specific
835
+ ## Collaboration
836
+ - **With DevOps**: Review infrastructure changes
837
+ - **With Security Team**: Validate security posture
838
+ - **With Finance**: Optimize cloud spend
839
+ - **Solo**: Complete IaC review and reporting
967
840
  ```
968
841
 
969
- **Redis BLPOP Coordination Pattern:**
842
+ **Usage:**
970
843
  ```bash
971
- # Modern zero-token coordination using Redis BLPOP primitives
972
- # See: .claude/skills/redis-coordination/SKILL.md
973
-
974
- # 1. Agent enters waiting mode (zero-token blocking)
975
- ./.claude/skills/redis-coordination/invoke-waiting-mode.sh enter \
976
- --task-id "task-123" \
977
- --agent-id "coder-1" \
978
- --context "iteration-1"
979
-
980
- # 2. Coordinator blocks until agent reports (BLPOP - no API calls)
981
- redis-cli blpop "swarm:task-123:coder-1:done" 30
982
-
983
- # 3. Wake agent for next iteration
984
- ./.claude/skills/redis-coordination/invoke-waiting-mode.sh wake \
985
- --task-id "task-123" \
986
- --agent-id "coder-1" \
987
- --reason "cfn_loop_iteration" \
988
- --iteration 2
989
-
990
- # Benefits:
991
- # - Zero tokens consumed while waiting (BLPOP blocks without API calls)
992
- # - Instant wake-up (<100ms latency)
993
- # - Auto-cleanup (keys deleted on read)
994
- # - Validated by 8/8 passing tests
844
+ npx claude-flow-novice agent-spawn terraform-reviewer \
845
+ --prompt "Review Terraform files in ./infrastructure"
995
846
  ```
996
847
 
997
- **For complete example:** See Rust Coder template in [Format Selection Principles](./agent-principles/format-selection.md)
998
-
999
848
  ---
1000
849
 
1001
- ## Specialized Guidance
1002
-
1003
- ### By Agent Type
1004
-
1005
- Different agent types have different format requirements and validation hooks:
1006
-
1007
- - **Coder Agents (Implementers)**:
1008
- - Format: Code-Heavy for basic tasks, Minimal for complex algorithms
1009
- - ACL Level: 1 (Private)
1010
- - Validators: agent-template-validator, cfn-loop-memory-validator, test-coverage-validator
1011
- - SQLite: Persist confidence scores, implementation notes
1012
-
1013
- - **Reviewer Agents (Validators)**:
1014
- - Format: Minimal (requires contextual reasoning)
1015
- - ACL Level: 3 (Swarm)
1016
- - Validators: agent-template-validator, cfn-loop-memory-validator
1017
- - SQLite: Persist review feedback, validation consensus
1018
-
1019
- - **Architect Agents (Coordinators)**:
1020
- - Format: Minimal (strategic thinking)
1021
- - ACL Level: 3 (Swarm)
1022
- - Validators: agent-template-validator, cfn-loop-memory-validator
1023
- - SQLite: Persist ADRs, design decisions (1 year retention)
1024
-
1025
- - **Coordinator Agents**:
1026
- - Format: Metadata (structured workflows)
1027
- - ACL Level: 3 (Swarm)
1028
- - Validators: agent-template-validator, cfn-loop-memory-validator
1029
- - SQLite: Persist coordination state, agent assignments
1030
- - Special: Redis BLPOP coordination (see `.claude/skills/redis-coordination/SKILL.md`)
1031
-
1032
- - **Tester Agents (Validators)**:
1033
- - Format: Code-Heavy for unit tests, Metadata for test strategy
1034
- - ACL Level: 3 (Swarm)
1035
- - Validators: agent-template-validator, test-coverage-validator
1036
- - SQLite: Persist test results, coverage metrics
1037
-
1038
- - **Researcher Agents**:
1039
- - Format: Minimal (open-ended exploration)
1040
- - ACL Level: 1 (Private) or 3 (Swarm) depending on context
1041
- - Validators: agent-template-validator
1042
- - SQLite: Persist research findings, competitive analysis
1043
-
1044
- - **DevOps Agents**:
1045
- - Format: Metadata (structured workflows)
1046
- - ACL Level: 3 (Swarm)
1047
- - Validators: agent-template-validator, cfn-loop-memory-validator
1048
- - SQLite: Persist deployment logs, infrastructure state
1049
-
1050
- - **Product Owner (CFN Loop 4 only)**:
1051
- - Format: Minimal (strategic GOAP decisions)
1052
- - ACL Level: 4 (Project)
1053
- - Validators: agent-template-validator, cfn-loop-memory-validator
1054
- - SQLite: Persist GOAP decisions, backlog items (365 day retention for compliance)
1055
-
1056
- **Full type-specific guidance:** [Agent Type Guidelines](./agent-principles/agent-type-guidelines.md)
1057
-
1058
- ---
850
+ ## Quick Reference
1059
851
 
1060
- ### Prompt Engineering
852
+ ### Common Agent Patterns
1061
853
 
1062
- Key principles for effective agent prompts:
1063
-
1064
- 1. **Clear Role Definition**: Establish expertise domain
1065
- 2. **Specific Responsibilities**: Concrete, actionable duties
1066
- 3. **Appropriate Tool Selection**: Only essential tools
1067
- 4. **Integration Points**: Explicit collaboration contracts
1068
- 5. **Validation Hooks**: Mandatory quality gates (4 production-ready validators)
1069
- 6. **SQLite Lifecycle**: Agent spawn, update, completion hooks
1070
- 7. **ACL Declaration**: Appropriate access control level by agent type
1071
- 8. **Error Handling**: SQLite retry logic, graceful degradation
1072
-
1073
- **Hook-Agent Collaboration Interface:**
1074
-
1075
- For complex validation requiring semantic understanding:
1076
-
1077
- ```javascript
1078
- class HybridValidator {
1079
- async validate(file, content) {
1080
- // Hook performs pattern detection (95% automation)
1081
- const patterns = await this.detectPatterns(content);
1082
-
1083
- if (patterns.hasComplexLogic) {
1084
- // Delegate semantic analysis to reviewer agent (5% requiring human-level understanding)
1085
- const agentReview = await this.requestAgentReview({
1086
- file,
1087
- content,
1088
- concern: 'State machine correctness',
1089
- context: patterns.extracted
1090
- });
1091
-
1092
- return { ...patterns, agentReview };
1093
- }
854
+ **Code Writer:**
855
+ ```yaml
856
+ tools: [Read, Write, Edit, Bash, TodoWrite]
857
+ model: haiku
858
+ type: specialist
859
+ acl_level: 1
860
+ ```
1094
861
 
1095
- return patterns;
1096
- }
1097
- }
862
+ **Code Reviewer:**
863
+ ```yaml
864
+ tools: [Read, Grep, TodoWrite]
865
+ model: sonnet
866
+ type: validator
867
+ acl_level: 3
1098
868
  ```
1099
869
 
1100
- **Incremental Validation with Caching:**
870
+ **Coordinator:**
871
+ ```yaml
872
+ tools: [Read, Bash, TodoWrite] # Bash for Redis CLI + agent spawning
873
+ model: sonnet
874
+ type: coordinator
875
+ acl_level: 3
876
+ ```
1101
877
 
1102
- Avoid re-validating unchanged files (10-100x speedup):
878
+ ### File Naming Convention
1103
879
 
1104
- ```javascript
1105
- const hash = computeHash(content);
1106
- if (cache.has(hash)) {
1107
- return cache.get(hash); // Instant validation for unchanged files
1108
- }
880
+ ```
881
+ .claude/agents/
882
+ ├── [category]/
883
+ │ └── [agent-name].md # lowercase, hyphens, descriptive
1109
884
  ```
1110
885
 
1111
- **Anti-patterns to avoid:**
1112
- - Over-specification (tunnel vision)
1113
- - Under-specification (too vague)
1114
- - Example overload (cognitive burden)
1115
- - Rigid checklists (context-insensitive)
1116
- - Missing SQLite lifecycle hooks (no audit trail)
1117
- - Wrong ACL level (data exposure or access denial)
1118
- - Missing error handling (cascading failures)
1119
- - Using deprecated BlockingCoordinationSignals (use Redis BLPOP instead)
886
+ **Good:** `terraform-reviewer.md`, `api-security-validator.md`
887
+ **Bad:** `TerraformReviewer.md`, `agent1.md`, `myAgent.md`
1120
888
 
1121
- **Detailed best practices:** [Prompt Engineering Best Practices](./agent-principles/prompt-engineering.md)
889
+ ### Essential YAML Fields
1122
890
 
891
+ **Minimum required:**
892
+ ```yaml
1123
893
  ---
894
+ name: agent-name
895
+ description: |
896
+ What the agent does and when to use it
897
+ tools: [Read, Write]
898
+ model: haiku
899
+ ---
900
+ ```
1124
901
 
1125
- ### Quality Metrics & Validation
1126
-
1127
- **Pre-Deployment Checklist:**
1128
- - [ ] Valid YAML frontmatter (including validation_hooks, lifecycle)
1129
- - [ ] Format matches task complexity (Minimal/Metadata/Code-Heavy)
1130
- - [ ] Clear responsibilities defined
1131
- - [ ] Integration points specified (memory keys, ACL levels)
1132
- - [ ] Post-edit hook included (mandatory)
1133
- - [ ] SQLite lifecycle hooks present (pre_task, post_task)
1134
- - [ ] ACL level declared (1-5 based on agent type)
1135
- - [ ] Error handling patterns implemented (retry, fallback)
1136
- - [ ] Redis BLPOP coordination patterns (coordinators - see redis-coordination skill)
1137
-
1138
- **Hook Validation Metrics:**
1139
- - Agent template validation pass rate (target: 100%)
1140
- - CFN Loop ACL compliance rate (target: 100%, zero violations in production)
1141
- - Test coverage above thresholds (≥80% line, ≥75% branch)
1142
- - Blocking coordination pattern correctness (coordinators: 100%)
1143
- - Hook execution time (<5s total for composite validation)
1144
- - False positive rate (<2%)
1145
-
1146
- **Ongoing Monitoring:**
1147
- - First-time success rate (>80%)
1148
- - Iteration count (<3)
1149
- - Quality score (>85%)
1150
- - User satisfaction (>4.5/5)
1151
- - SQLite persistence success rate (>99.9%)
1152
- - ACL violation rate (0% in production)
1153
- - Agent lifecycle completion rate (>95%)
1154
-
1155
- **Hook Performance Targets:**
1156
- - Individual validator: <2s (WASM-accelerated)
1157
- - Composite validation: <5s (parallel execution)
1158
- - Cache hit rate: >70% during development (incremental validation)
1159
- - Manual validation required: <2% (only semantic edge cases)
1160
-
1161
- **Comprehensive validation guide:** [Quality Metrics & Validation](./agent-principles/quality-metrics.md)
1162
-
902
+ **Recommended:**
903
+ ```yaml
904
+ ---
905
+ name: agent-name
906
+ description: |
907
+ MUST BE USED when [use case]
908
+ Keywords - [keywords]
909
+ tools: [Read, Write, Edit, TodoWrite]
910
+ model: haiku
911
+ type: specialist
912
+ capabilities: [capability-tags]
913
+ acl_level: 1
1163
914
  ---
915
+ ```
1164
916
 
1165
- ## Benchmark System
917
+ ---
1166
918
 
1167
- ### Running Benchmarks
919
+ ## Resources
1168
920
 
1169
- ```bash
1170
- cd benchmark/agent-benchmarking
921
+ ### Template Files
922
+ - `.claude/templates/redis-coordination.md` - Multi-agent coordination
923
+ - `.claude/templates/memory-operations.md` - Data persistence
924
+ - `.claude/templates/team-dynamics.md` - Agent collaboration
925
+ - `.claude/templates/cfn-loop-mechanics.md` - Self-correcting workflows
1171
926
 
1172
- # Run Rust benchmarks (VALIDATED)
1173
- node index.js run 5 --rust --verbose
927
+ ### Example Agents
928
+ - `.claude/agents/core-agents/coder.md` - Code implementation
929
+ - `.claude/agents/core-agents/reviewer.md` - Code review
930
+ - `.claude/agents/core-agents/tester.md` - Testing & validation
931
+ - `.claude/agents/development/backend-dev.md` - Backend development
932
+ - `.claude/agents/security/security-specialist.md` - Security analysis
1174
933
 
1175
- # Run JavaScript benchmarks (HYPOTHESIS)
1176
- node index.js run 5 --verbose
934
+ ### Documentation
935
+ - `README.md` - Project overview
936
+ - `.claude/skills/` - Reusable skill modules
937
+ - `.claude/commands/` - Slash command definitions
1177
938
 
1178
- # Analyze results
1179
- node index.js analyze
1180
- ```
939
+ ### Technical Deep-Dive
1181
940
 
1182
- **Detailed benchmarking guide:** [Quality Metrics & Validation](./agent-principles/quality-metrics.md)
941
+ For advanced users who want to understand the theoretical foundations:
942
+ - [Format Selection Principles](./agent-principles/format-selection.md)
943
+ - [Agent Type Guidelines](./agent-principles/agent-type-guidelines.md)
944
+ - [Prompt Engineering Best Practices](./agent-principles/prompt-engineering.md)
945
+ - [Quality Metrics & Validation](./agent-principles/quality-metrics.md)
1183
946
 
1184
947
  ---
1185
948
 
1186
- ## Conclusion
949
+ ## Need Help?
1187
950
 
1188
- ### Key Takeaways
951
+ ### Common Questions
1189
952
 
1190
- 1. **Format matters**: Choose based on task complexity (inverse relationship)
1191
- 2. **Validation is critical**: 4 production-ready hooks ensure quality and coordination
1192
- 3. **SQLite integration**: All agents MUST persist lifecycle and data for audit trail
1193
- 4. **ACL enforcement**: Appropriate access control prevents data exposure
1194
- 5. **Hook composition**: CompositeHook pattern enables layered validation (<5s total)
1195
- 6. **Hybrid validation**: Hooks automate 85%, agents handle semantic understanding (15%)
1196
- 7. **Integration is essential**: Memory, swarm, and event bus enable collaboration
1197
- 8. **Continuous improvement**: Use metrics to refine agents
953
+ **Q: How many agents should I create?**
954
+ A: Start with 1-3 focused agents. Add more as needed. Quality > quantity.
1198
955
 
1199
- ### Four Production-Ready Validators
956
+ **Q: Should I modify core agents?**
957
+ A: No, create custom agents instead. Core agents may be updated in new releases.
1200
958
 
1201
- 1. **Agent Template Validator**: SQLite lifecycle, ACL, error handling (95% automation)
1202
- 2. **CFN Loop Memory Pattern Validator**: ACL correctness, key format, TTL (90% automation)
1203
- 3. **Test Coverage Validator**: Line/branch/function coverage thresholds (100% automation)
1204
- 4. **Blocking Coordination Validator**: HMAC, signals, state machines (60% automation + agent review)
959
+ **Q: Can agents call other agents?**
960
+ A: Yes! Coordinators spawn agents via CLI: `npx claude-flow-novice agent-spawn [agent-name]`
1205
961
 
1206
- ### Next Steps
962
+ **Q: How do I share agents with my team?**
963
+ A: Put them in `.claude/agents/` and commit to git.
1207
964
 
1208
- 1. Choose appropriate format for your agent (Minimal/Metadata/Code-Heavy)
1209
- 2. Use templates as starting points (includes SQLite lifecycle hooks)
1210
- 3. Add validation_hooks to frontmatter (agent-template, cfn-loop-memory, test-coverage, blocking-coordination)
1211
- 4. Implement SQLite lifecycle hooks (pre_task, post_task)
1212
- 5. Declare ACL level (1=Private, 3=Swarm, 4=Project)
1213
- 6. Add error handling patterns (retry, fallback)
1214
- 7. Test with benchmark system
1215
- 8. Deploy with validation hooks (automatic on save)
1216
- 9. Monitor hook metrics (<5s validation, <2% false positives)
1217
- 10. Iterate based on metrics and agent feedback
965
+ **Q: What's the difference between skills and agents?**
966
+ A: Skills are reusable behaviors (like templates). Agents are executable workers that use skills.
967
+
968
+ ### Getting Help
969
+
970
+ 1. Check existing agents for examples
971
+ 2. Review template files for patterns
972
+ 3. Test incrementally with simple tasks
973
+ 4. Start simple, add complexity gradually
974
+ 5. Open issues on GitHub for bugs
1218
975
 
1219
976
  ---
1220
977
 
1221
- ## Reference Documents
978
+ ## What's Next?
979
+
980
+ Now that you understand agent creation, explore:
981
+
982
+ 1. **Multi-Agent Workflows** - Coordinate multiple agents for complex tasks
983
+ 2. **CFN Loop Integration** - Build self-correcting pipelines
984
+ 3. **Custom Skills** - Create reusable behavior modules
985
+ 4. **Web Portal** - Monitor agent execution in real-time
986
+ 5. **Advanced Coordination** - Redis pub/sub, memory operations
1222
987
 
1223
- - **[Format Selection Principles](./agent-principles/format-selection.md)**: Detailed format guidance, benchmarking findings, decision tree
1224
- - **[Agent Type Guidelines](./agent-principles/agent-type-guidelines.md)**: Type-specific recommendations for coders, reviewers, architects, testers, researchers, DevOps
1225
- - **[Prompt Engineering Best Practices](./agent-principles/prompt-engineering.md)**: Effective prompt patterns, anti-patterns, integration with Claude Flow
1226
- - **[Quality Metrics & Validation](./agent-principles/quality-metrics.md)**: Validation checklists, benchmark system, continuous improvement
988
+ **Ready to build something amazing? Start creating your first agent!**
1227
989
 
1228
990
  ---
1229
991
 
1230
- **Document Version:** 2.0.0
1231
- **Last Updated:** 2025-09-30
1232
- **Maintained By:** Claude Flow Core Team
1233
- **Feedback:** Document improvements and findings for future versions
992
+ **Document Version:** 4.0.0 (User-Friendly Edition)
993
+ **Last Updated:** 2025-10-20
994
+ **Maintained By:** Claude Flow Novice Team
995
+ **Feedback:** We'd love to hear how you're using agents! Share your creations.