claude-flow-novice 1.5.9 → 1.5.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-flow-novice/dist/src/cli/commands/index.js +1049 -1087
- package/.claude-flow-novice/dist/src/cli/commands/index.js.map +1 -1
- package/.claude-flow-novice/dist/src/cli/simple-commands/init/templates/CLAUDE.md +301 -26
- package/.claude-flow-novice/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +3 -40
- package/.claude-flow-novice/dist/src/cli/simple-commands/mcp.js +2 -1
- package/CLAUDE.md +326 -1910
- package/package.json +1 -1
- package/src/cli/simple-commands/init/templates/CLAUDE.md +276 -26
- package/src/cli/simple-commands/init/templates/enhanced-templates.js +3 -40
- package/src/cli/simple-commands/mcp.js +2 -1
- package/.claude-flow-novice/dist/src/cli/simple-commands/init/CLAUDE.md +0 -188
package/CLAUDE.md
CHANGED
|
@@ -1,78 +1,59 @@
|
|
|
1
|
-
# Claude
|
|
1
|
+
# Claude Flow Novice - AI Agent Orchestration
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## Core Orchestration Patterns
|
|
4
|
+
|
|
5
|
+
## 🚨 CRITICAL: MANDATORY AGENT-BASED EXECUTION
|
|
6
|
+
|
|
7
|
+
**YOU MUST USE AGENTS FOR ALL NON-TRIVIAL WORK - NO EXCEPTIONS**
|
|
4
8
|
|
|
5
9
|
**ABSOLUTE RULES**:
|
|
6
|
-
1.
|
|
7
|
-
2. **NEVER
|
|
8
|
-
3.
|
|
9
|
-
4.
|
|
10
|
+
1. **ALWAYS USE AGENTS** - Any task requiring >3 steps MUST use agent coordination
|
|
11
|
+
2. **NEVER WORK SOLO** - Spawn multiple agents in parallel for ALL significant tasks
|
|
12
|
+
3. **MANDATORY SWARM COORDINATION** - Complex features require 3-8 agent swarms minimum
|
|
13
|
+
4. ALL operations MUST be concurrent/parallel in a single message
|
|
14
|
+
5. **NEVER save working files, text/mds and tests to the root folder**
|
|
15
|
+
6. ALWAYS organize files in appropriate subdirectories
|
|
16
|
+
7. **USE CLAUDE CODE'S TASK TOOL** for spawning agents concurrently, not just MCP
|
|
17
|
+
|
|
18
|
+
### 🚫 WHEN YOU MUST USE AGENTS (MANDATORY)
|
|
19
|
+
|
|
20
|
+
**TRIGGER CONDITIONS - If ANY apply, you MUST spawn agents:**
|
|
21
|
+
- Task requires >3 distinct steps
|
|
22
|
+
- Multiple files need to be created or modified
|
|
23
|
+
- Need research + implementation + testing
|
|
24
|
+
- Architecture or design decisions required
|
|
25
|
+
- Code review or quality validation needed
|
|
26
|
+
- Security, performance, or compliance concerns
|
|
27
|
+
- Integration across multiple systems/components
|
|
28
|
+
- Documentation generation needed
|
|
29
|
+
- Refactoring or optimization work
|
|
30
|
+
- ANY feature development (even "simple" ones)
|
|
31
|
+
|
|
32
|
+
**MINIMUM AGENT REQUIREMENTS:**
|
|
33
|
+
- **Simple tasks** (3-5 steps): 2-3 agents minimum (coder + tester + reviewer)
|
|
34
|
+
- **Medium tasks** (6-10 steps): 4-6 agents (add researcher + architect + security-specialist)
|
|
35
|
+
- **Complex tasks** (11-20 steps): 8-12 agents (full team with specialists)
|
|
36
|
+
- **Enterprise features** (20+ steps): 15-20 agents with swarm coordination
|
|
10
37
|
|
|
11
38
|
### ⚡ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"
|
|
12
39
|
|
|
13
40
|
**MANDATORY PATTERNS:**
|
|
41
|
+
- **Agent Spawning**: ALWAYS spawn ALL required agents in ONE message using Task tool
|
|
14
42
|
- **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)
|
|
15
43
|
- **Task tool (Claude Code)**: ALWAYS spawn ALL agents in ONE message with full instructions
|
|
16
44
|
- **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message
|
|
17
45
|
- **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
|
|
18
46
|
- **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message
|
|
19
47
|
|
|
20
|
-
###
|
|
21
|
-
|
|
22
|
-
**Claude Code's Task tool is the PRIMARY way to spawn agents:**
|
|
23
|
-
```javascript
|
|
24
|
-
// ✅ CORRECT: Use Claude Code's Task tool for parallel agent execution
|
|
25
|
-
[Single Message]:
|
|
26
|
-
Task("Research agent", "Analyze requirements and patterns...", "researcher")
|
|
27
|
-
Task("Coder agent", "Implement core features...", "coder")
|
|
28
|
-
Task("Tester agent", "Create comprehensive tests...", "tester")
|
|
29
|
-
Task("Reviewer agent", "Review code quality...", "reviewer")
|
|
30
|
-
Task("Architect agent", "Design system architecture...", "system-architect")
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
## Project Overview
|
|
34
|
-
|
|
35
|
-
**Project Type**: react-typescript
|
|
36
|
-
**Primary Language**: javascript
|
|
37
|
-
**Primary Framework**: react
|
|
38
|
-
**Package Manager**: npm
|
|
39
|
-
**Build Tools**: none
|
|
40
|
-
|
|
41
|
-
**Detected Languages**: javascript, typescript, rust, python
|
|
42
|
-
**Detected Frameworks**: react, express, vue, django, flask, nextjs, angular, spring, fastapi
|
|
43
|
-
**Project Directories**: src
|
|
44
|
-
|
|
45
|
-
*Auto-generated on 2025-09-30*
|
|
46
|
-
|
|
47
|
-
## 📁 File Organization Rules
|
|
48
|
+
### ⚠️ PROHIBITED SOLO WORK
|
|
48
49
|
|
|
49
|
-
**
|
|
50
|
-
-
|
|
51
|
-
-
|
|
52
|
-
-
|
|
53
|
-
-
|
|
54
|
-
-
|
|
55
|
-
-
|
|
56
|
-
|
|
57
|
-
## 🚀 Available Agent Types
|
|
58
|
-
|
|
59
|
-
### Core Development
|
|
60
|
-
`coder`, `reviewer`, `tester`, `planner`, `researcher`
|
|
61
|
-
|
|
62
|
-
### Backend Development
|
|
63
|
-
`backend-dev`, `api-docs`, `system-architect`, `code-analyzer`
|
|
64
|
-
|
|
65
|
-
### Frontend Development
|
|
66
|
-
`mobile-dev` (React Native), specialized frontend agents
|
|
67
|
-
|
|
68
|
-
### Testing & Validation
|
|
69
|
-
`tdd-london-swarm`, `production-validator`
|
|
70
|
-
|
|
71
|
-
### GitHub & Repository Management
|
|
72
|
-
`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`
|
|
73
|
-
|
|
74
|
-
### Performance & Optimization
|
|
75
|
-
`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`
|
|
50
|
+
**YOU ARE FORBIDDEN FROM:**
|
|
51
|
+
- ❌ Working alone on multi-step tasks
|
|
52
|
+
- ❌ Implementing features without agent coordination
|
|
53
|
+
- ❌ Skipping agent spawning because "it's simple"
|
|
54
|
+
- ❌ Writing code without a tester agent
|
|
55
|
+
- ❌ Making architectural decisions without an architect agent
|
|
56
|
+
- ❌ Deploying without security review from security-specialist agent
|
|
76
57
|
|
|
77
58
|
## 🎯 Claude Code vs MCP Tools
|
|
78
59
|
|
|
@@ -82,1909 +63,344 @@
|
|
|
82
63
|
- Code generation and programming
|
|
83
64
|
- Bash commands and system operations
|
|
84
65
|
- Implementation work
|
|
66
|
+
- Project navigation and analysis
|
|
67
|
+
- TodoWrite and task management
|
|
68
|
+
- Git operations
|
|
69
|
+
- Package management
|
|
70
|
+
- Testing and debugging
|
|
85
71
|
|
|
86
72
|
### MCP Tools ONLY COORDINATE:
|
|
87
73
|
- Swarm initialization (topology setup)
|
|
88
74
|
- Agent type definitions (coordination patterns)
|
|
89
75
|
- Task orchestration (high-level planning)
|
|
90
76
|
- Memory management
|
|
77
|
+
- Neural features
|
|
91
78
|
- Performance tracking
|
|
79
|
+
- GitHub integration
|
|
92
80
|
|
|
93
81
|
**KEY**: MCP coordinates the strategy, Claude Code's Task tool executes with real agents.
|
|
94
82
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
### Every Agent Spawned via Task Tool MUST:
|
|
83
|
+
### Agent Coordination Framework
|
|
98
84
|
|
|
99
|
-
|
|
85
|
+
#### Pre-Task Hooks (Setup & Validation)
|
|
100
86
|
```bash
|
|
101
|
-
|
|
102
|
-
npx claude-flow
|
|
103
|
-
```
|
|
87
|
+
# Validate safety and prepare resources
|
|
88
|
+
npx claude-flow-novice hooks pre-command --command "[command]" --validate-safety true --prepare-resources true
|
|
104
89
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "swarm/[agent]/[step]"
|
|
108
|
-
npx claude-flow@alpha hooks notify --message "[what was done]"
|
|
90
|
+
# Auto-assign agents and load context
|
|
91
|
+
npx claude-flow-novice hooks pre-edit --file "[file]" --auto-assign-agents true --load-context true
|
|
109
92
|
```
|
|
110
93
|
|
|
111
|
-
|
|
94
|
+
#### Post-Task Hooks (Validation & Quality)
|
|
112
95
|
```bash
|
|
113
|
-
|
|
114
|
-
npx claude-flow
|
|
115
|
-
```
|
|
96
|
+
# Track metrics and store results
|
|
97
|
+
npx claude-flow-novice hooks post-command --command "[command]" --track-metrics true --store-results true
|
|
116
98
|
|
|
117
|
-
|
|
99
|
+
# Enhanced post-edit pipeline with comprehensive TDD validation
|
|
100
|
+
npx enhanced-hooks post-edit "[file]" --memory-key "swarm/[agent]/[step]" --minimum-coverage 80 --structured
|
|
118
101
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
npm install
|
|
122
|
-
npm run build
|
|
123
|
-
npm run test
|
|
124
|
-
npm run lint
|
|
125
|
-
|
|
126
|
-
# Claude Flow commands
|
|
127
|
-
npx claude-flow@alpha init
|
|
128
|
-
npx claude-flow@alpha hooks setup
|
|
129
|
-
npx claude-flow@alpha memory store
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
## Javascript Configuration
|
|
133
|
-
|
|
134
|
-
### JavaScript Development Patterns
|
|
135
|
-
|
|
136
|
-
**Code Style & Standards:**
|
|
137
|
-
- Use ES6+ features (arrow functions, destructuring, modules)
|
|
138
|
-
- Prefer `const`/`let` over `var`
|
|
139
|
-
- Use async/await over Promise chains
|
|
140
|
-
- Implement proper error boundaries
|
|
141
|
-
- Follow ESLint/Prettier configurations
|
|
142
|
-
|
|
143
|
-
**Concurrent Agent Execution:**
|
|
144
|
-
```javascript
|
|
145
|
-
// ✅ CORRECT: JavaScript development with concurrent agents
|
|
146
|
-
[Single Message]:
|
|
147
|
-
Task("Frontend Developer", "Build responsive UI with modern JavaScript", "coder")
|
|
148
|
-
Task("API Developer", "Create REST endpoints with Express/Fastify", "backend-dev")
|
|
149
|
-
Task("Test Engineer", "Write Jest/Vitest tests with >85% coverage", "tester")
|
|
150
|
-
Task("Build Engineer", "Configure Webpack/Vite build system", "system-architect")
|
|
151
|
-
Task("Quality Reviewer", "Review code quality and performance", "reviewer")
|
|
152
|
-
|
|
153
|
-
// Batch all file operations
|
|
154
|
-
Write("src/app.js")
|
|
155
|
-
Write("src/api/routes.js")
|
|
156
|
-
Write("tests/app.test.js")
|
|
157
|
-
Write("webpack.config.js")
|
|
158
|
-
|
|
159
|
-
// Batch todos for tracking
|
|
160
|
-
TodoWrite({ todos: [
|
|
161
|
-
{content: "Set up project structure", status: "in_progress", activeForm: "Setting up project structure"},
|
|
162
|
-
{content: "Implement core modules", status: "pending", activeForm: "Implementing core modules"},
|
|
163
|
-
{content: "Add error handling", status: "pending", activeForm: "Adding error handling"},
|
|
164
|
-
{content: "Write comprehensive tests", status: "pending", activeForm: "Writing comprehensive tests"},
|
|
165
|
-
{content: "Configure build pipeline", status: "pending", activeForm: "Configuring build pipeline"}
|
|
166
|
-
]})
|
|
167
|
-
```
|
|
102
|
+
# Manual hook execution (guaranteed working)
|
|
103
|
+
node src/hooks/enhanced-hooks-cli.js post-edit "[file]" --memory-key "[key]" --structured
|
|
168
104
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
// Preferred module structure
|
|
172
|
-
src/
|
|
173
|
-
components/ # Reusable components
|
|
174
|
-
utils/ # Helper functions
|
|
175
|
-
services/ # API and business logic
|
|
176
|
-
config/ # Configuration files
|
|
177
|
-
hooks/ # Custom hooks (if React)
|
|
178
|
-
types/ # Type definitions (if TypeScript)
|
|
105
|
+
# Validates: formatting, linting, type checking, dependencies, security, tests, TDD compliance
|
|
106
|
+
# Progressive validation: graceful degradation when dependencies missing (beginner-friendly)
|
|
179
107
|
```
|
|
180
108
|
|
|
181
|
-
**
|
|
182
|
-
```javascript
|
|
183
|
-
import { jest } from '@jest/globals';
|
|
184
|
-
|
|
185
|
-
describe('Module Tests', () => {
|
|
186
|
-
beforeEach(() => {
|
|
187
|
-
jest.clearAllMocks();
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
test('handles async operations correctly', async () => {
|
|
191
|
-
const mockFn = jest.fn().mockResolvedValue({ success: true });
|
|
192
|
-
const result = await asyncOperation(mockFn);
|
|
109
|
+
## 🎯 **Enhanced Post-Edit Hook System**
|
|
193
110
|
|
|
194
|
-
|
|
195
|
-
expect(mockFn).toHaveBeenCalledTimes(1);
|
|
196
|
-
});
|
|
111
|
+
### **🚨 MANDATORY: Manual Hook Execution After Every File Edit**
|
|
197
112
|
|
|
198
|
-
|
|
199
|
-
const mockFn = jest.fn().mockRejectedValue(new Error('Test error'));
|
|
113
|
+
**CRITICAL RULE**: After **EVERY** file edit operation, you **MUST** run the enhanced post-edit hook:
|
|
200
114
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
115
|
+
```bash
|
|
116
|
+
# After editing any file, IMMEDIATELY run:
|
|
117
|
+
npx enhanced-hooks post-edit "[FILE_PATH]" --memory-key "swarm/[AGENT]/[STEP]" --minimum-coverage 80 --structured
|
|
118
|
+
|
|
119
|
+
# Or via slash command:
|
|
120
|
+
/hooks post-edit [FILE_PATH] --memory-key "[CONTEXT]" --structured
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
**⚠️ NO EXCEPTIONS**: This applies to:
|
|
124
|
+
- All JavaScript/TypeScript files
|
|
125
|
+
- All Rust files
|
|
126
|
+
- All Python files
|
|
127
|
+
- All configuration files
|
|
128
|
+
- ALL file modifications
|
|
129
|
+
|
|
130
|
+
### **Enhanced Post-Edit Pipeline Features:**
|
|
131
|
+
- **🧪 TDD Testing**: Single-file testing without full system compilation
|
|
132
|
+
- **📊 Real-time Coverage**: Coverage analysis with configurable thresholds (default: 80%)
|
|
133
|
+
- **🌐 Multi-Language Support**:
|
|
134
|
+
- **JavaScript/TypeScript**: Jest, Mocha, Prettier, ESLint integration
|
|
135
|
+
- **Rust**: cargo check, cargo test, cargo-tarpaulin, rustfmt
|
|
136
|
+
- **Python**: pytest, unittest, black, pylint
|
|
137
|
+
- **Go**: go test, go fmt, go vet
|
|
138
|
+
- **Java**: JUnit, TestNG, google-java-format
|
|
139
|
+
- **C/C++**: GTest, Catch2, clang-format
|
|
140
|
+
- **🎨 Formatting**: Prettier, Black, RustFmt, GoFmt with diff preview
|
|
141
|
+
- **🔒 Security Analysis**: XSS, eval(), hardcoded credentials, SQL injection detection
|
|
142
|
+
- **✅ TDD Compliance**: Red-Green-Refactor phase detection and enforcement
|
|
143
|
+
- **🔍 Framework Detection**: Automatic test framework identification
|
|
144
|
+
- **🤖 Agent Feedback**: Structured JSON with actionable recommendations
|
|
145
|
+
- **💾 Memory Coordination**: Cross-agent state sharing and enhanced persistence
|
|
146
|
+
- **🚫 Blocking Mechanisms**: Quality gates for critical validation failures
|
|
147
|
+
|
|
148
|
+
### **Usage Examples:**
|
|
149
|
+
```bash
|
|
150
|
+
# For JavaScript/TypeScript files
|
|
151
|
+
npx enhanced-hooks post-edit "src/components/Button.tsx" --memory-key "frontend/button" --structured
|
|
205
152
|
|
|
206
|
-
|
|
207
|
-
-
|
|
208
|
-
- Implement lazy loading for routes/components
|
|
209
|
-
- Minimize bundle size with tree shaking
|
|
210
|
-
- Use Web Workers for heavy computations
|
|
211
|
-
- Implement proper caching strategies
|
|
153
|
+
# For Rust files (full cargo integration)
|
|
154
|
+
npx enhanced-hooks post-edit "src/lib.rs" --memory-key "backend/rust" --minimum-coverage 90 --structured
|
|
212
155
|
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
// Global error handler
|
|
216
|
-
process.on('unhandledRejection', (reason, promise) => {
|
|
217
|
-
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
|
218
|
-
// Application specific logging logic here
|
|
219
|
-
});
|
|
220
|
-
|
|
221
|
-
// Async error wrapper
|
|
222
|
-
const asyncHandler = (fn) => (req, res, next) => {
|
|
223
|
-
Promise.resolve(fn(req, res, next)).catch(next);
|
|
224
|
-
};
|
|
156
|
+
# Via slash commands in Claude Code
|
|
157
|
+
/hooks post-edit your-file.js --memory-key "agent-memory-key" --structured
|
|
225
158
|
```
|
|
226
159
|
|
|
227
|
-
**
|
|
228
|
-
```javascript
|
|
229
|
-
// config/index.js
|
|
230
|
-
const config = {
|
|
231
|
-
development: {
|
|
232
|
-
api: {
|
|
233
|
-
baseURL: 'http://localhost:3000',
|
|
234
|
-
timeout: 5000
|
|
235
|
-
}
|
|
236
|
-
},
|
|
237
|
-
production: {
|
|
238
|
-
api: {
|
|
239
|
-
baseURL: process.env.API_BASE_URL,
|
|
240
|
-
timeout: 10000
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
};
|
|
244
|
-
|
|
245
|
-
export default config[process.env.NODE_ENV || 'development'];
|
|
246
|
-
```
|
|
247
|
-
|
|
248
|
-
## Typescript Configuration
|
|
249
|
-
|
|
250
|
-
### TypeScript Configuration & Patterns
|
|
251
|
-
|
|
252
|
-
**Type Safety & Standards:**
|
|
253
|
-
- Use strict TypeScript configuration
|
|
254
|
-
- Prefer interfaces over types for object shapes
|
|
255
|
-
- Use utility types (Partial, Pick, Omit, Record)
|
|
256
|
-
- Implement proper generic constraints
|
|
257
|
-
- Avoid `any` type - use `unknown` when necessary
|
|
258
|
-
|
|
259
|
-
**TypeScript Config (tsconfig.json):**
|
|
160
|
+
### **Response Structure:**
|
|
260
161
|
```json
|
|
261
162
|
{
|
|
262
|
-
"
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
"
|
|
270
|
-
"
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
"allowSyntheticDefaultImports": true,
|
|
274
|
-
"forceConsistentCasingInFileNames": true,
|
|
275
|
-
"moduleResolution": "node",
|
|
276
|
-
"resolveJsonModule": true,
|
|
277
|
-
"isolatedModules": true,
|
|
278
|
-
"noEmit": true
|
|
279
|
-
},
|
|
280
|
-
"include": ["src/**/*"],
|
|
281
|
-
"exclude": ["node_modules", "dist", "build"]
|
|
163
|
+
"success": true,
|
|
164
|
+
"file": "src/component.js",
|
|
165
|
+
"validation": { "passed": true, "issues": [], "coverage": "advanced" },
|
|
166
|
+
"formatting": { "needed": true, "changes": 12, "formatter": "prettier" },
|
|
167
|
+
"testing": { "executed": true, "framework": "jest", "results": {...} },
|
|
168
|
+
"tddCompliance": { "hasTests": true, "coverage": 85, "recommendations": [...] },
|
|
169
|
+
"recommendations": [
|
|
170
|
+
{ "type": "security", "priority": "high", "message": "...", "action": "..." },
|
|
171
|
+
{ "type": "formatting", "priority": "medium", "action": "prettier file.js" }
|
|
172
|
+
],
|
|
173
|
+
"memory": { "stored": true, "enhancedStore": true }
|
|
282
174
|
}
|
|
283
175
|
```
|
|
284
176
|
|
|
285
|
-
|
|
286
|
-
```
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
Task("TypeScript Developer", "Build type-safe modules with generics", "coder")
|
|
290
|
-
Task("Interface Designer", "Design comprehensive type definitions", "system-architect")
|
|
291
|
-
Task("Test Engineer", "Write typed tests with Jest and @types", "tester")
|
|
292
|
-
Task("Build Engineer", "Configure TypeScript compilation pipeline", "backend-dev")
|
|
293
|
-
Task("Type Reviewer", "Review type safety and consistency", "reviewer")
|
|
294
|
-
|
|
295
|
-
// Batch file operations with TypeScript focus
|
|
296
|
-
Write("src/types/api.ts")
|
|
297
|
-
Write("src/services/ApiService.ts")
|
|
298
|
-
Write("src/utils/validators.ts")
|
|
299
|
-
Write("tests/ApiService.test.ts")
|
|
300
|
-
|
|
301
|
-
// TypeScript-specific todos
|
|
302
|
-
TodoWrite({ todos: [
|
|
303
|
-
{content: "Define core type interfaces", status: "in_progress", activeForm: "Defining core type interfaces"},
|
|
304
|
-
{content: "Implement generic utility functions", status: "pending", activeForm: "Implementing generic utility functions"},
|
|
305
|
-
{content: "Add runtime type validation", status: "pending", activeForm: "Adding runtime type validation"},
|
|
306
|
-
{content: "Configure path mapping aliases", status: "pending", activeForm: "Configuring path mapping aliases"},
|
|
307
|
-
{content: "Setup strict linting rules", status: "pending", activeForm: "Setting up strict linting rules"}
|
|
308
|
-
]})
|
|
309
|
-
```
|
|
310
|
-
|
|
311
|
-
**Type Definitions Pattern:**
|
|
312
|
-
```typescript
|
|
313
|
-
// types/api.ts
|
|
314
|
-
export interface ApiResponse<T = unknown> {
|
|
315
|
-
data: T;
|
|
316
|
-
message: string;
|
|
317
|
-
status: 'success' | 'error';
|
|
318
|
-
timestamp: string;
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
export interface PaginatedResponse<T> extends ApiResponse<T[]> {
|
|
322
|
-
pagination: {
|
|
323
|
-
page: number;
|
|
324
|
-
limit: number;
|
|
325
|
-
total: number;
|
|
326
|
-
hasNext: boolean;
|
|
327
|
-
};
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
// Generic service interface
|
|
331
|
-
export interface CRUDService<T, CreateT = Partial<T>, UpdateT = Partial<T>> {
|
|
332
|
-
getAll(): Promise<ApiResponse<T[]>>;
|
|
333
|
-
getById(id: string): Promise<ApiResponse<T>>;
|
|
334
|
-
create(data: CreateT): Promise<ApiResponse<T>>;
|
|
335
|
-
update(id: string, data: UpdateT): Promise<ApiResponse<T>>;
|
|
336
|
-
delete(id: string): Promise<ApiResponse<void>>;
|
|
337
|
-
}
|
|
338
|
-
```
|
|
339
|
-
|
|
340
|
-
**Advanced TypeScript Patterns:**
|
|
341
|
-
```typescript
|
|
342
|
-
// Utility types for better type inference
|
|
343
|
-
type NonNullable<T> = T extends null | undefined ? never : T;
|
|
344
|
-
|
|
345
|
-
// Conditional types for API responses
|
|
346
|
-
type ApiResult<T> = T extends string
|
|
347
|
-
? ApiResponse<string>
|
|
348
|
-
: T extends number
|
|
349
|
-
? ApiResponse<number>
|
|
350
|
-
: ApiResponse<T>;
|
|
351
|
-
|
|
352
|
-
// Template literal types for routes
|
|
353
|
-
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
354
|
-
type ApiRoute<T extends string> = `/api/${T}`;
|
|
355
|
-
|
|
356
|
-
// Branded types for stronger type safety
|
|
357
|
-
type UserId = string & { readonly __brand: unique symbol };
|
|
358
|
-
type Email = string & { readonly __brand: unique symbol };
|
|
359
|
-
|
|
360
|
-
// Factory function with proper typing
|
|
361
|
-
function createUserId(value: string): UserId {
|
|
362
|
-
// Runtime validation here
|
|
363
|
-
return value as UserId;
|
|
364
|
-
}
|
|
365
|
-
```
|
|
366
|
-
|
|
367
|
-
**Testing with TypeScript:**
|
|
368
|
-
```typescript
|
|
369
|
-
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
|
|
370
|
-
|
|
371
|
-
interface MockApiService {
|
|
372
|
-
fetchUser: jest.MockedFunction<(id: string) => Promise<User>>;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
describe('UserService', () => {
|
|
376
|
-
let mockApi: MockApiService;
|
|
377
|
-
let userService: UserService;
|
|
378
|
-
|
|
379
|
-
beforeEach(() => {
|
|
380
|
-
mockApi = {
|
|
381
|
-
fetchUser: jest.fn()
|
|
382
|
-
};
|
|
383
|
-
userService = new UserService(mockApi);
|
|
384
|
-
});
|
|
385
|
-
|
|
386
|
-
it('should fetch user with proper typing', async () => {
|
|
387
|
-
const mockUser: User = {
|
|
388
|
-
id: 'user-123',
|
|
389
|
-
name: 'Test User',
|
|
390
|
-
email: 'test@example.com'
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
mockApi.fetchUser.mockResolvedValue(mockUser);
|
|
394
|
-
|
|
395
|
-
const result = await userService.getUser('user-123');
|
|
396
|
-
|
|
397
|
-
expect(result).toEqual(mockUser);
|
|
398
|
-
expect(mockApi.fetchUser).toHaveBeenCalledWith('user-123');
|
|
399
|
-
});
|
|
400
|
-
});
|
|
177
|
+
#### Session Management
|
|
178
|
+
```bash
|
|
179
|
+
# Generate summaries and persist state
|
|
180
|
+
npx claude-flow-novice hooks session-end --generate-summary true --persist-state true --export-metrics true
|
|
401
181
|
```
|
|
182
|
+
## 🚀 MANDATORY AGENT SPAWNING PATTERNS
|
|
402
183
|
|
|
403
|
-
**
|
|
404
|
-
```typescript
|
|
405
|
-
// Result pattern for better error handling
|
|
406
|
-
type Result<T, E = Error> =
|
|
407
|
-
| { success: true; data: T }
|
|
408
|
-
| { success: false; error: E };
|
|
409
|
-
|
|
410
|
-
class ApiService {
|
|
411
|
-
async fetchData<T>(url: string): Promise<Result<T, ApiError>> {
|
|
412
|
-
try {
|
|
413
|
-
const response = await fetch(url);
|
|
414
|
-
if (!response.ok) {
|
|
415
|
-
return { success: false, error: new ApiError(response.statusText) };
|
|
416
|
-
}
|
|
417
|
-
const data = await response.json() as T;
|
|
418
|
-
return { success: true, data };
|
|
419
|
-
} catch (error) {
|
|
420
|
-
return { success: false, error: error as ApiError };
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
// Usage with proper type checking
|
|
426
|
-
const result = await apiService.fetchData<User>('/api/users/123');
|
|
427
|
-
if (result.success) {
|
|
428
|
-
console.log(result.data.name); // TypeScript knows this is User
|
|
429
|
-
} else {
|
|
430
|
-
console.error(result.error.message); // TypeScript knows this is ApiError
|
|
431
|
-
}
|
|
432
|
-
```
|
|
184
|
+
**YOU MUST USE THESE PATTERNS FOR ALL NON-TRIVIAL WORK:**
|
|
433
185
|
|
|
434
|
-
|
|
435
|
-
```
|
|
436
|
-
|
|
437
|
-
types/
|
|
438
|
-
api.ts # API response types
|
|
439
|
-
domain.ts # Business domain types
|
|
440
|
-
utils.ts # Utility types
|
|
441
|
-
services/
|
|
442
|
-
BaseService.ts # Generic base service
|
|
443
|
-
UserService.ts # Concrete implementations
|
|
444
|
-
utils/
|
|
445
|
-
validators.ts # Runtime type validation
|
|
446
|
-
typeGuards.ts # Type guard functions
|
|
447
|
-
hooks/ # Custom hooks (if React)
|
|
448
|
-
useApi.ts # Generic API hook
|
|
449
|
-
```
|
|
450
|
-
|
|
451
|
-
## React Framework Configuration
|
|
452
|
-
|
|
453
|
-
### React Development Patterns
|
|
454
|
-
|
|
455
|
-
**Component Architecture:**
|
|
456
|
-
- Use functional components with hooks
|
|
457
|
-
- Implement proper component composition
|
|
458
|
-
- Follow single responsibility principle
|
|
459
|
-
- Use TypeScript for better type safety
|
|
460
|
-
- Implement proper error boundaries
|
|
461
|
-
|
|
462
|
-
**Concurrent Agent Execution:**
|
|
463
|
-
```jsx
|
|
464
|
-
// ✅ CORRECT: React development with specialized agents
|
|
186
|
+
### Pattern 1: Simple Tasks (2-3 agents MINIMUM)
|
|
187
|
+
```javascript
|
|
188
|
+
// ✅ MANDATORY for any code change - ALWAYS use swarm coordination
|
|
465
189
|
[Single Message]:
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
// Batch React file operations
|
|
473
|
-
Write("src/components/App.jsx")
|
|
474
|
-
Write("src/hooks/useApi.js")
|
|
475
|
-
Write("src/context/AppContext.jsx")
|
|
476
|
-
Write("src/styles/globals.css")
|
|
477
|
-
Write("tests/components/App.test.jsx")
|
|
478
|
-
|
|
479
|
-
// React-specific todos
|
|
480
|
-
TodoWrite({ todos: [
|
|
481
|
-
{content: "Setup component library structure", status: "in_progress", activeForm: "Setting up component library structure"},
|
|
482
|
-
{content: "Implement custom hooks for data fetching", status: "pending", activeForm: "Implementing custom hooks for data fetching"},
|
|
483
|
-
{content: "Add error boundaries and loading states", status: "pending", activeForm: "Adding error boundaries and loading states"},
|
|
484
|
-
{content: "Configure routing with React Router", status: "pending", activeForm: "Configuring routing with React Router"},
|
|
485
|
-
{content: "Optimize performance with memoization", status: "pending", activeForm: "Optimizing performance with memoization"}
|
|
486
|
-
]})
|
|
487
|
-
```
|
|
488
|
-
|
|
489
|
-
**Project Structure:**
|
|
490
|
-
```
|
|
491
|
-
src/
|
|
492
|
-
components/
|
|
493
|
-
common/ # Reusable UI components
|
|
494
|
-
Button.jsx
|
|
495
|
-
Modal.jsx
|
|
496
|
-
Input.jsx
|
|
497
|
-
layout/ # Layout components
|
|
498
|
-
Header.jsx
|
|
499
|
-
Sidebar.jsx
|
|
500
|
-
Footer.jsx
|
|
501
|
-
pages/ # Page-level components
|
|
502
|
-
HomePage.jsx
|
|
503
|
-
UserProfile.jsx
|
|
504
|
-
hooks/ # Custom hooks
|
|
505
|
-
useApi.js
|
|
506
|
-
useLocalStorage.js
|
|
507
|
-
useAuth.js
|
|
508
|
-
context/ # React context providers
|
|
509
|
-
AuthContext.jsx
|
|
510
|
-
ThemeContext.jsx
|
|
511
|
-
services/ # API services
|
|
512
|
-
api.js
|
|
513
|
-
auth.js
|
|
514
|
-
utils/ # Helper functions
|
|
515
|
-
validators.js
|
|
516
|
-
formatters.js
|
|
517
|
-
styles/ # Global styles
|
|
518
|
-
globals.css
|
|
519
|
-
variables.css
|
|
520
|
-
```
|
|
521
|
-
|
|
522
|
-
**Component Patterns:**
|
|
523
|
-
```jsx
|
|
524
|
-
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
|
525
|
-
import PropTypes from 'prop-types';
|
|
526
|
-
|
|
527
|
-
// Functional component with hooks
|
|
528
|
-
const UserProfile = ({ userId, onUpdate }) => {
|
|
529
|
-
const [user, setUser] = useState(null);
|
|
530
|
-
const [loading, setLoading] = useState(true);
|
|
531
|
-
const [error, setError] = useState(null);
|
|
532
|
-
|
|
533
|
-
// Memoized expensive calculations
|
|
534
|
-
const userStats = useMemo(() => {
|
|
535
|
-
if (!user) return null;
|
|
536
|
-
return {
|
|
537
|
-
totalPosts: user.posts?.length || 0,
|
|
538
|
-
joinedDate: new Date(user.createdAt).toLocaleDateString()
|
|
539
|
-
};
|
|
540
|
-
}, [user]);
|
|
541
|
-
|
|
542
|
-
// Memoized callbacks to prevent unnecessary re-renders
|
|
543
|
-
const handleUpdateUser = useCallback(async (updates) => {
|
|
544
|
-
try {
|
|
545
|
-
const updatedUser = await updateUser(userId, updates);
|
|
546
|
-
setUser(updatedUser);
|
|
547
|
-
onUpdate?.(updatedUser);
|
|
548
|
-
} catch (err) {
|
|
549
|
-
setError(err.message);
|
|
550
|
-
}
|
|
551
|
-
}, [userId, onUpdate]);
|
|
552
|
-
|
|
553
|
-
useEffect(() => {
|
|
554
|
-
let cancelled = false;
|
|
555
|
-
|
|
556
|
-
const fetchUser = async () => {
|
|
557
|
-
try {
|
|
558
|
-
setLoading(true);
|
|
559
|
-
const userData = await getUserById(userId);
|
|
560
|
-
if (!cancelled) {
|
|
561
|
-
setUser(userData);
|
|
562
|
-
}
|
|
563
|
-
} catch (err) {
|
|
564
|
-
if (!cancelled) {
|
|
565
|
-
setError(err.message);
|
|
566
|
-
}
|
|
567
|
-
} finally {
|
|
568
|
-
if (!cancelled) {
|
|
569
|
-
setLoading(false);
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
};
|
|
573
|
-
|
|
574
|
-
fetchUser();
|
|
575
|
-
|
|
576
|
-
return () => {
|
|
577
|
-
cancelled = true;
|
|
578
|
-
};
|
|
579
|
-
}, [userId]);
|
|
580
|
-
|
|
581
|
-
if (loading) return <LoadingSpinner />;
|
|
582
|
-
if (error) return <ErrorMessage message={error} />;
|
|
583
|
-
if (!user) return <NotFound />;
|
|
584
|
-
|
|
585
|
-
return (
|
|
586
|
-
<div className="user-profile">
|
|
587
|
-
<ProfileHeader user={user} stats={userStats} />
|
|
588
|
-
<ProfileContent user={user} onUpdate={handleUpdateUser} />
|
|
589
|
-
</div>
|
|
590
|
-
);
|
|
591
|
-
};
|
|
592
|
-
|
|
593
|
-
UserProfile.propTypes = {
|
|
594
|
-
userId: PropTypes.string.isRequired,
|
|
595
|
-
onUpdate: PropTypes.func
|
|
596
|
-
};
|
|
597
|
-
|
|
598
|
-
export default React.memo(UserProfile);
|
|
599
|
-
```
|
|
600
|
-
|
|
601
|
-
**Custom Hooks Pattern:**
|
|
602
|
-
```jsx
|
|
603
|
-
import { useState, useEffect, useCallback } from 'react';
|
|
604
|
-
|
|
605
|
-
// Generic API hook
|
|
606
|
-
export const useApi = (url, options = {}) => {
|
|
607
|
-
const [data, setData] = useState(null);
|
|
608
|
-
const [loading, setLoading] = useState(true);
|
|
609
|
-
const [error, setError] = useState(null);
|
|
610
|
-
|
|
611
|
-
const fetchData = useCallback(async () => {
|
|
612
|
-
try {
|
|
613
|
-
setLoading(true);
|
|
614
|
-
setError(null);
|
|
615
|
-
const response = await fetch(url, options);
|
|
616
|
-
|
|
617
|
-
if (!response.ok) {
|
|
618
|
-
throw new Error(`HTTP error! status: ${response.status}`);
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
const result = await response.json();
|
|
622
|
-
setData(result);
|
|
623
|
-
} catch (err) {
|
|
624
|
-
setError(err.message);
|
|
625
|
-
} finally {
|
|
626
|
-
setLoading(false);
|
|
627
|
-
}
|
|
628
|
-
}, [url, options]);
|
|
629
|
-
|
|
630
|
-
useEffect(() => {
|
|
631
|
-
fetchData();
|
|
632
|
-
}, [fetchData]);
|
|
633
|
-
|
|
634
|
-
const refetch = useCallback(() => {
|
|
635
|
-
fetchData();
|
|
636
|
-
}, [fetchData]);
|
|
637
|
-
|
|
638
|
-
return { data, loading, error, refetch };
|
|
639
|
-
};
|
|
640
|
-
|
|
641
|
-
// Local storage hook
|
|
642
|
-
export const useLocalStorage = (key, initialValue) => {
|
|
643
|
-
const [storedValue, setStoredValue] = useState(() => {
|
|
644
|
-
try {
|
|
645
|
-
const item = window.localStorage.getItem(key);
|
|
646
|
-
return item ? JSON.parse(item) : initialValue;
|
|
647
|
-
} catch (error) {
|
|
648
|
-
console.error(`Error reading localStorage key "${key}":`, error);
|
|
649
|
-
return initialValue;
|
|
650
|
-
}
|
|
651
|
-
});
|
|
652
|
-
|
|
653
|
-
const setValue = useCallback((value) => {
|
|
654
|
-
try {
|
|
655
|
-
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
656
|
-
setStoredValue(valueToStore);
|
|
657
|
-
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
658
|
-
} catch (error) {
|
|
659
|
-
console.error(`Error setting localStorage key "${key}":`, error);
|
|
660
|
-
}
|
|
661
|
-
}, [key, storedValue]);
|
|
662
|
-
|
|
663
|
-
return [storedValue, setValue];
|
|
664
|
-
};
|
|
665
|
-
```
|
|
190
|
+
// Step 1: Initialize swarm (REQUIRED for consistency)
|
|
191
|
+
mcp__claude-flow-novice__swarm_init({
|
|
192
|
+
topology: "mesh",
|
|
193
|
+
maxAgents: 3,
|
|
194
|
+
strategy: "balanced"
|
|
195
|
+
})
|
|
666
196
|
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
// State and actions
|
|
672
|
-
const initialState = {
|
|
673
|
-
user: null,
|
|
674
|
-
isAuthenticated: false,
|
|
675
|
-
loading: false,
|
|
676
|
-
error: null
|
|
677
|
-
};
|
|
678
|
-
|
|
679
|
-
const authReducer = (state, action) => {
|
|
680
|
-
switch (action.type) {
|
|
681
|
-
case 'LOGIN_START':
|
|
682
|
-
return { ...state, loading: true, error: null };
|
|
683
|
-
case 'LOGIN_SUCCESS':
|
|
684
|
-
return {
|
|
685
|
-
...state,
|
|
686
|
-
user: action.payload,
|
|
687
|
-
isAuthenticated: true,
|
|
688
|
-
loading: false,
|
|
689
|
-
error: null
|
|
690
|
-
};
|
|
691
|
-
case 'LOGIN_FAILURE':
|
|
692
|
-
return {
|
|
693
|
-
...state,
|
|
694
|
-
user: null,
|
|
695
|
-
isAuthenticated: false,
|
|
696
|
-
loading: false,
|
|
697
|
-
error: action.payload
|
|
698
|
-
};
|
|
699
|
-
case 'LOGOUT':
|
|
700
|
-
return initialState;
|
|
701
|
-
default:
|
|
702
|
-
return state;
|
|
703
|
-
}
|
|
704
|
-
};
|
|
705
|
-
|
|
706
|
-
// Context creation
|
|
707
|
-
const AuthContext = createContext();
|
|
708
|
-
|
|
709
|
-
// Provider component
|
|
710
|
-
export const AuthProvider = ({ children }) => {
|
|
711
|
-
const [state, dispatch] = useReducer(authReducer, initialState);
|
|
712
|
-
|
|
713
|
-
const login = useCallback(async (credentials) => {
|
|
714
|
-
dispatch({ type: 'LOGIN_START' });
|
|
715
|
-
try {
|
|
716
|
-
const user = await authService.login(credentials);
|
|
717
|
-
dispatch({ type: 'LOGIN_SUCCESS', payload: user });
|
|
718
|
-
return user;
|
|
719
|
-
} catch (error) {
|
|
720
|
-
dispatch({ type: 'LOGIN_FAILURE', payload: error.message });
|
|
721
|
-
throw error;
|
|
722
|
-
}
|
|
723
|
-
}, []);
|
|
724
|
-
|
|
725
|
-
const logout = useCallback(() => {
|
|
726
|
-
authService.logout();
|
|
727
|
-
dispatch({ type: 'LOGOUT' });
|
|
728
|
-
}, []);
|
|
729
|
-
|
|
730
|
-
const value = {
|
|
731
|
-
...state,
|
|
732
|
-
login,
|
|
733
|
-
logout
|
|
734
|
-
};
|
|
735
|
-
|
|
736
|
-
return (
|
|
737
|
-
<AuthContext.Provider value={value}>
|
|
738
|
-
{children}
|
|
739
|
-
</AuthContext.Provider>
|
|
740
|
-
);
|
|
741
|
-
};
|
|
742
|
-
|
|
743
|
-
// Custom hook for using auth context
|
|
744
|
-
export const useAuth = () => {
|
|
745
|
-
const context = useContext(AuthContext);
|
|
746
|
-
if (!context) {
|
|
747
|
-
throw new Error('useAuth must be used within an AuthProvider');
|
|
748
|
-
}
|
|
749
|
-
return context;
|
|
750
|
-
};
|
|
197
|
+
// Step 2: Spawn agents with coordinated approach
|
|
198
|
+
Task("Coder", "Implement feature with TDD approach", "coder")
|
|
199
|
+
Task("Tester", "Create comprehensive test suite", "tester")
|
|
200
|
+
Task("Reviewer", "Review code quality and security", "reviewer")
|
|
751
201
|
```
|
|
752
202
|
|
|
753
|
-
|
|
754
|
-
```jsx
|
|
755
|
-
import React from 'react';
|
|
756
|
-
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
|
757
|
-
import userEvent from '@testing-library/user-event';
|
|
758
|
-
import { jest } from '@jest/globals';
|
|
759
|
-
import UserProfile from '../UserProfile';
|
|
760
|
-
import * as api from '../../services/api';
|
|
761
|
-
|
|
762
|
-
// Mock the API module
|
|
763
|
-
jest.mock('../../services/api');
|
|
764
|
-
|
|
765
|
-
describe('UserProfile', () => {
|
|
766
|
-
const mockUser = {
|
|
767
|
-
id: '123',
|
|
768
|
-
name: 'John Doe',
|
|
769
|
-
email: 'john@example.com',
|
|
770
|
-
posts: [{ id: 1, title: 'Test Post' }]
|
|
771
|
-
};
|
|
772
|
-
|
|
773
|
-
beforeEach(() => {
|
|
774
|
-
jest.clearAllMocks();
|
|
775
|
-
});
|
|
776
|
-
|
|
777
|
-
test('renders user profile after loading', async () => {
|
|
778
|
-
api.getUserById.mockResolvedValue(mockUser);
|
|
779
|
-
|
|
780
|
-
render(<UserProfile userId="123" />);
|
|
781
|
-
|
|
782
|
-
// Check loading state
|
|
783
|
-
expect(screen.getByTestId('loading-spinner')).toBeInTheDocument();
|
|
784
|
-
|
|
785
|
-
// Wait for user data to load
|
|
786
|
-
await waitFor(() => {
|
|
787
|
-
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
|
788
|
-
});
|
|
789
|
-
|
|
790
|
-
expect(screen.getByText('john@example.com')).toBeInTheDocument();
|
|
791
|
-
expect(screen.getByText('1 Posts')).toBeInTheDocument();
|
|
792
|
-
});
|
|
793
|
-
|
|
794
|
-
test('handles update user interaction', async () => {
|
|
795
|
-
const user = userEvent.setup();
|
|
796
|
-
const onUpdate = jest.fn();
|
|
797
|
-
|
|
798
|
-
api.getUserById.mockResolvedValue(mockUser);
|
|
799
|
-
api.updateUser.mockResolvedValue({ ...mockUser, name: 'Jane Doe' });
|
|
800
|
-
|
|
801
|
-
render(<UserProfile userId="123" onUpdate={onUpdate} />);
|
|
802
|
-
|
|
803
|
-
await waitFor(() => {
|
|
804
|
-
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
|
805
|
-
});
|
|
806
|
-
|
|
807
|
-
const editButton = screen.getByRole('button', { name: /edit/i });
|
|
808
|
-
await user.click(editButton);
|
|
809
|
-
|
|
810
|
-
const nameInput = screen.getByDisplayValue('John Doe');
|
|
811
|
-
await user.clear(nameInput);
|
|
812
|
-
await user.type(nameInput, 'Jane Doe');
|
|
813
|
-
|
|
814
|
-
const saveButton = screen.getByRole('button', { name: /save/i });
|
|
815
|
-
await user.click(saveButton);
|
|
816
|
-
|
|
817
|
-
await waitFor(() => {
|
|
818
|
-
expect(onUpdate).toHaveBeenCalledWith({ ...mockUser, name: 'Jane Doe' });
|
|
819
|
-
});
|
|
820
|
-
});
|
|
821
|
-
|
|
822
|
-
test('displays error message on API failure', async () => {
|
|
823
|
-
api.getUserById.mockRejectedValue(new Error('Network error'));
|
|
824
|
-
|
|
825
|
-
render(<UserProfile userId="123" />);
|
|
826
|
-
|
|
827
|
-
await waitFor(() => {
|
|
828
|
-
expect(screen.getByText(/network error/i)).toBeInTheDocument();
|
|
829
|
-
});
|
|
830
|
-
});
|
|
831
|
-
});
|
|
832
|
-
```
|
|
833
|
-
|
|
834
|
-
**Performance Optimization:**
|
|
835
|
-
```jsx
|
|
836
|
-
import React, { memo, lazy, Suspense } from 'react';
|
|
837
|
-
|
|
838
|
-
// Lazy loading for code splitting
|
|
839
|
-
const LazyUserProfile = lazy(() => import('./UserProfile'));
|
|
840
|
-
const LazyUserSettings = lazy(() => import('./UserSettings'));
|
|
841
|
-
|
|
842
|
-
// Memoized component to prevent unnecessary re-renders
|
|
843
|
-
const UserCard = memo(({ user, onUpdate }) => {
|
|
844
|
-
return (
|
|
845
|
-
<div className="user-card">
|
|
846
|
-
<h3>{user.name}</h3>
|
|
847
|
-
<p>{user.email}</p>
|
|
848
|
-
<button onClick={() => onUpdate(user.id)}>
|
|
849
|
-
Update
|
|
850
|
-
</button>
|
|
851
|
-
</div>
|
|
852
|
-
);
|
|
853
|
-
});
|
|
854
|
-
|
|
855
|
-
// Main app with lazy loading
|
|
856
|
-
const App = () => {
|
|
857
|
-
return (
|
|
858
|
-
<div className="app">
|
|
859
|
-
<Suspense fallback={<div>Loading...</div>}>
|
|
860
|
-
<Routes>
|
|
861
|
-
<Route path="/profile" element={<LazyUserProfile />} />
|
|
862
|
-
<Route path="/settings" element={<LazyUserSettings />} />
|
|
863
|
-
</Routes>
|
|
864
|
-
</Suspense>
|
|
865
|
-
</div>
|
|
866
|
-
);
|
|
867
|
-
};
|
|
868
|
-
```
|
|
869
|
-
|
|
870
|
-
**State Management with Zustand:**
|
|
871
|
-
```jsx
|
|
872
|
-
import { create } from 'zustand';
|
|
873
|
-
import { devtools, persist } from 'zustand/middleware';
|
|
874
|
-
|
|
875
|
-
const useUserStore = create(
|
|
876
|
-
devtools(
|
|
877
|
-
persist(
|
|
878
|
-
(set, get) => ({
|
|
879
|
-
users: [],
|
|
880
|
-
currentUser: null,
|
|
881
|
-
loading: false,
|
|
882
|
-
|
|
883
|
-
fetchUsers: async () => {
|
|
884
|
-
set({ loading: true });
|
|
885
|
-
try {
|
|
886
|
-
const users = await api.getUsers();
|
|
887
|
-
set({ users, loading: false });
|
|
888
|
-
} catch (error) {
|
|
889
|
-
set({ loading: false });
|
|
890
|
-
throw error;
|
|
891
|
-
}
|
|
892
|
-
},
|
|
893
|
-
|
|
894
|
-
setCurrentUser: (user) => set({ currentUser: user }),
|
|
895
|
-
|
|
896
|
-
updateUser: async (userId, updates) => {
|
|
897
|
-
const updatedUser = await api.updateUser(userId, updates);
|
|
898
|
-
set((state) => ({
|
|
899
|
-
users: state.users.map((user) =>
|
|
900
|
-
user.id === userId ? updatedUser : user
|
|
901
|
-
),
|
|
902
|
-
currentUser: state.currentUser?.id === userId ? updatedUser : state.currentUser
|
|
903
|
-
}));
|
|
904
|
-
return updatedUser;
|
|
905
|
-
}
|
|
906
|
-
}),
|
|
907
|
-
{ name: 'user-store' }
|
|
908
|
-
)
|
|
909
|
-
)
|
|
910
|
-
);
|
|
911
|
-
|
|
912
|
-
// Usage in component
|
|
913
|
-
const UserList = () => {
|
|
914
|
-
const { users, loading, fetchUsers } = useUserStore();
|
|
915
|
-
|
|
916
|
-
useEffect(() => {
|
|
917
|
-
fetchUsers();
|
|
918
|
-
}, [fetchUsers]);
|
|
919
|
-
|
|
920
|
-
if (loading) return <LoadingSpinner />;
|
|
921
|
-
|
|
922
|
-
return (
|
|
923
|
-
<div>
|
|
924
|
-
{users.map((user) => (
|
|
925
|
-
<UserCard key={user.id} user={user} />
|
|
926
|
-
))}
|
|
927
|
-
</div>
|
|
928
|
-
);
|
|
929
|
-
};
|
|
930
|
-
```
|
|
931
|
-
|
|
932
|
-
## 🚀 Concurrent Execution Patterns
|
|
933
|
-
|
|
934
|
-
### JavaScript/TypeScript Patterns
|
|
935
|
-
|
|
936
|
-
```javascript
|
|
937
|
-
// ✅ CORRECT: Batch all operations in single message
|
|
938
|
-
[Single Message]:
|
|
939
|
-
Task("Frontend Developer", "Build React components with hooks", "coder")
|
|
940
|
-
Task("Backend Developer", "Create Express API endpoints", "backend-dev")
|
|
941
|
-
Task("Test Engineer", "Write Jest tests with >80% coverage", "tester")
|
|
942
|
-
|
|
943
|
-
// Batch file operations
|
|
944
|
-
Write("src/components/App.jsx")
|
|
945
|
-
Write("src/api/server.js")
|
|
946
|
-
Write("tests/App.test.js")
|
|
947
|
-
```
|
|
948
|
-
|
|
949
|
-
### Python Patterns
|
|
950
|
-
|
|
951
|
-
```python
|
|
952
|
-
# ✅ CORRECT: Parallel agent execution
|
|
953
|
-
[Single Message]:
|
|
954
|
-
Task("Django Developer", "Build models and views with DRF", "backend-dev")
|
|
955
|
-
Task("Frontend Developer", "Create React frontend with API integration", "coder")
|
|
956
|
-
Task("Test Engineer", "Write pytest tests with fixtures", "tester")
|
|
957
|
-
|
|
958
|
-
# Batch Python operations
|
|
959
|
-
Write("apps/models.py")
|
|
960
|
-
Write("apps/views.py")
|
|
961
|
-
Write("tests/test_models.py")
|
|
962
|
-
```
|
|
963
|
-
|
|
964
|
-
### React Development Patterns
|
|
965
|
-
|
|
966
|
-
```javascript
|
|
967
|
-
// React-specific concurrent patterns
|
|
968
|
-
[Single Message]:
|
|
969
|
-
Task("Component Developer", "Build reusable components with TypeScript", "coder")
|
|
970
|
-
Task("State Manager", "Implement Redux/Context state management", "coder")
|
|
971
|
-
Task("Test Engineer", "Write React Testing Library tests", "tester")
|
|
972
|
-
Task("Style Developer", "Create responsive CSS/Styled Components", "coder")
|
|
973
|
-
```
|
|
974
|
-
|
|
975
|
-
### API Development Patterns
|
|
976
|
-
|
|
977
|
-
```bash
|
|
978
|
-
# API-focused concurrent execution
|
|
979
|
-
[Single Message]:
|
|
980
|
-
Task("API Developer", "Build RESTful endpoints with validation", "backend-dev")
|
|
981
|
-
Task("Database Designer", "Design schema and migrations", "code-analyzer")
|
|
982
|
-
Task("Security Engineer", "Implement authentication and authorization", "reviewer")
|
|
983
|
-
Task("API Tester", "Create integration and unit tests", "tester")
|
|
984
|
-
Task("Documentation Writer", "Generate OpenAPI/Swagger docs", "researcher")
|
|
985
|
-
```
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
## 📋 Best Practices
|
|
990
|
-
|
|
991
|
-
### General Development
|
|
992
|
-
- **Modular Design**: Keep files under 500 lines
|
|
993
|
-
- **Environment Safety**: Never hardcode secrets
|
|
994
|
-
- **Test-First**: Write tests before implementation
|
|
995
|
-
- **Clean Architecture**: Separate concerns
|
|
996
|
-
- **Documentation**: Keep updated
|
|
997
|
-
|
|
998
|
-
### JavaScript/TypeScript
|
|
999
|
-
- **ES6+ Features**: Use modern JavaScript syntax
|
|
1000
|
-
- **Type Safety**: Prefer TypeScript for larger projects
|
|
1001
|
-
- **Async/Await**: Use async/await over Promise chains
|
|
1002
|
-
- **Error Handling**: Implement proper error boundaries
|
|
1003
|
-
- **Code Splitting**: Lazy load components and routes
|
|
1004
|
-
|
|
1005
|
-
### Python
|
|
1006
|
-
- **PEP 8**: Follow Python style guidelines
|
|
1007
|
-
- **Type Hints**: Use type annotations for clarity
|
|
1008
|
-
- **Virtual Environments**: Always use venv or conda
|
|
1009
|
-
- **Docstrings**: Document all functions and classes
|
|
1010
|
-
- **Error Handling**: Use specific exception types
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
## 🧪 Testing Patterns
|
|
1015
|
-
|
|
1016
|
-
### React Testing
|
|
1017
|
-
|
|
1018
|
-
```javascript
|
|
1019
|
-
import { render, screen, fireEvent } from '@testing-library/react';
|
|
1020
|
-
import userEvent from '@testing-library/user-event';
|
|
1021
|
-
|
|
1022
|
-
// Component testing pattern
|
|
1023
|
-
describe('Component', () => {
|
|
1024
|
-
test('renders and handles interaction', async () => {
|
|
1025
|
-
const user = userEvent.setup();
|
|
1026
|
-
render(<Component />);
|
|
1027
|
-
|
|
1028
|
-
const button = screen.getByRole('button');
|
|
1029
|
-
await user.click(button);
|
|
1030
|
-
|
|
1031
|
-
expect(screen.getByText(/result/i)).toBeInTheDocument();
|
|
1032
|
-
});
|
|
1033
|
-
});
|
|
1034
|
-
```
|
|
1035
|
-
|
|
1036
|
-
### Python Testing
|
|
1037
|
-
|
|
1038
|
-
```python
|
|
1039
|
-
import pytest
|
|
1040
|
-
from unittest.mock import patch, MagicMock
|
|
1041
|
-
|
|
1042
|
-
class TestAPI:
|
|
1043
|
-
@pytest.fixture
|
|
1044
|
-
def client(self):
|
|
1045
|
-
return TestClient()
|
|
1046
|
-
|
|
1047
|
-
def test_endpoint(self, client):
|
|
1048
|
-
response = client.get("/api/endpoint")
|
|
1049
|
-
assert response.status_code == 200
|
|
1050
|
-
assert response.json()["status"] == "success"
|
|
1051
|
-
```
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
## Custom Configuration
|
|
1056
|
-
|
|
1057
|
-
<!-- Preserved from existing CLAUDE.md -->
|
|
1058
|
-
hooks/ # Custom hooks (if React)
|
|
1059
|
-
types/ # Type definitions (if TypeScript)
|
|
1060
|
-
```
|
|
1061
|
-
|
|
1062
|
-
**Testing Patterns:**
|
|
203
|
+
### Pattern 2: Medium Tasks (4-6 agents REQUIRED)
|
|
1063
204
|
```javascript
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
});
|
|
1084
|
-
});
|
|
1085
|
-
```
|
|
1086
|
-
|
|
1087
|
-
**Performance Best Practices:**
|
|
1088
|
-
- Use code splitting for large applications
|
|
1089
|
-
- Implement lazy loading for routes/components
|
|
1090
|
-
- Minimize bundle size with tree shaking
|
|
1091
|
-
- Use Web Workers for heavy computations
|
|
1092
|
-
- Implement proper caching strategies
|
|
1093
|
-
|
|
1094
|
-
**Error Handling:**
|
|
205
|
+
// ✅ MANDATORY for multi-file features - ALWAYS use swarm coordination
|
|
206
|
+
[Single Message]:
|
|
207
|
+
// Step 1: Initialize swarm (REQUIRED for consistency)
|
|
208
|
+
mcp__claude-flow-novice__swarm_init({
|
|
209
|
+
topology: "mesh",
|
|
210
|
+
maxAgents: 6,
|
|
211
|
+
strategy: "balanced"
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
// Step 2: Spawn coordinated agents
|
|
215
|
+
Task("Researcher", "Analyze requirements and existing patterns", "researcher")
|
|
216
|
+
Task("Architect", "Design system architecture", "system-architect")
|
|
217
|
+
Task("Coder", "Implement core functionality with TDD", "coder")
|
|
218
|
+
Task("Tester", "Create unit, integration, and E2E tests", "tester")
|
|
219
|
+
Task("Security Reviewer", "Perform security audit", "security-specialist")
|
|
220
|
+
Task("Reviewer", "Final quality review", "reviewer")
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### Pattern 3: Complex Tasks (8-12 agents REQUIRED)
|
|
1095
224
|
```javascript
|
|
1096
|
-
//
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
225
|
+
// ✅ MANDATORY for full features - MUST use swarm coordination
|
|
226
|
+
[Single Message]:
|
|
227
|
+
// Step 1: Initialize swarm coordination (REQUIRED for 8+ agents)
|
|
228
|
+
mcp__claude-flow-novice__swarm_init({
|
|
229
|
+
topology: "hierarchical",
|
|
230
|
+
maxAgents: 12,
|
|
231
|
+
strategy: "adaptive"
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
// Step 2: Spawn working agents using Task tool
|
|
235
|
+
Task("Product Owner", "Define requirements", "planner")
|
|
236
|
+
Task("System Architect", "Design architecture", "system-architect")
|
|
237
|
+
Task("Backend Developer", "Implement backend services", "backend-dev")
|
|
238
|
+
Task("Frontend Developer", "Create UI components", "coder")
|
|
239
|
+
Task("Tester", "Comprehensive testing", "tester")
|
|
240
|
+
Task("Security Specialist", "Security review", "security-specialist")
|
|
241
|
+
Task("Performance Analyst", "Performance optimization", "perf-analyzer")
|
|
242
|
+
Task("DevOps Engineer", "CI/CD setup", "cicd-engineer")
|
|
243
|
+
Task("API Documenter", "API documentation", "api-docs")
|
|
244
|
+
Task("Reviewer", "Final quality gate", "reviewer")
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### 🎯 SWARM INITIALIZATION RULE
|
|
248
|
+
|
|
249
|
+
**CRITICAL**: You MUST initialize swarm WHENEVER spawning multiple agents:
|
|
1107
250
|
|
|
1108
|
-
**Environment Configuration:**
|
|
1109
251
|
```javascript
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
```
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
// Functional component with hooks
|
|
1159
|
-
const UserProfile = ({ userId, onUpdate }) => {
|
|
1160
|
-
const [user, setUser] = useState(null);
|
|
1161
|
-
const [loading, setLoading] = useState(true);
|
|
1162
|
-
const [error, setError] = useState(null);
|
|
1163
|
-
|
|
1164
|
-
// Memoized expensive calculations
|
|
1165
|
-
const userStats = useMemo(() => {
|
|
1166
|
-
if (!user) return null;
|
|
1167
|
-
return {
|
|
1168
|
-
totalPosts: user.posts?.length || 0,
|
|
1169
|
-
joinedDate: new Date(user.createdAt).toLocaleDateString()
|
|
1170
|
-
};
|
|
1171
|
-
}, [user]);
|
|
1172
|
-
|
|
1173
|
-
// Memoized callbacks to prevent unnecessary re-renders
|
|
1174
|
-
const handleUpdateUser = useCallback(async (updates) => {
|
|
1175
|
-
try {
|
|
1176
|
-
const updatedUser = await updateUser(userId, updates);
|
|
1177
|
-
setUser(updatedUser);
|
|
1178
|
-
onUpdate?.(updatedUser);
|
|
1179
|
-
} catch (err) {
|
|
1180
|
-
setError(err.message);
|
|
1181
|
-
}
|
|
1182
|
-
}, [userId, onUpdate]);
|
|
1183
|
-
|
|
1184
|
-
useEffect(() => {
|
|
1185
|
-
let cancelled = false;
|
|
1186
|
-
|
|
1187
|
-
const fetchUser = async () => {
|
|
1188
|
-
try {
|
|
1189
|
-
setLoading(true);
|
|
1190
|
-
const userData = await getUserById(userId);
|
|
1191
|
-
if (!cancelled) {
|
|
1192
|
-
setUser(userData);
|
|
1193
|
-
}
|
|
1194
|
-
} catch (err) {
|
|
1195
|
-
if (!cancelled) {
|
|
1196
|
-
setError(err.message);
|
|
1197
|
-
}
|
|
1198
|
-
} finally {
|
|
1199
|
-
if (!cancelled) {
|
|
1200
|
-
setLoading(false);
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
};
|
|
1204
|
-
|
|
1205
|
-
fetchUser();
|
|
1206
|
-
|
|
1207
|
-
return () => {
|
|
1208
|
-
cancelled = true;
|
|
1209
|
-
};
|
|
1210
|
-
}, [userId]);
|
|
1211
|
-
|
|
1212
|
-
if (loading) return <LoadingSpinner />;
|
|
1213
|
-
if (error) return <ErrorMessage message={error} />;
|
|
1214
|
-
if (!user) return <NotFound />;
|
|
1215
|
-
|
|
1216
|
-
return (
|
|
1217
|
-
<div className="user-profile">
|
|
1218
|
-
<ProfileHeader user={user} stats={userStats} />
|
|
1219
|
-
<ProfileContent user={user} onUpdate={handleUpdateUser} />
|
|
1220
|
-
</div>
|
|
1221
|
-
);
|
|
1222
|
-
};
|
|
1223
|
-
|
|
1224
|
-
UserProfile.propTypes = {
|
|
1225
|
-
userId: PropTypes.string.isRequired,
|
|
1226
|
-
onUpdate: PropTypes.func
|
|
1227
|
-
};
|
|
1228
|
-
|
|
1229
|
-
export default React.memo(UserProfile);
|
|
1230
|
-
```
|
|
1231
|
-
|
|
1232
|
-
**Custom Hooks Pattern:**
|
|
1233
|
-
```jsx
|
|
1234
|
-
import { useState, useEffect, useCallback } from 'react';
|
|
1235
|
-
|
|
1236
|
-
// Generic API hook
|
|
1237
|
-
export const useApi = (url, options = {}) => {
|
|
1238
|
-
const [data, setData] = useState(null);
|
|
1239
|
-
const [loading, setLoading] = useState(true);
|
|
1240
|
-
const [error, setError] = useState(null);
|
|
1241
|
-
|
|
1242
|
-
const fetchData = useCallback(async () => {
|
|
1243
|
-
try {
|
|
1244
|
-
setLoading(true);
|
|
1245
|
-
setError(null);
|
|
1246
|
-
const response = await fetch(url, options);
|
|
1247
|
-
|
|
1248
|
-
if (!response.ok) {
|
|
1249
|
-
throw new Error(`HTTP error! status: ${response.status}`);
|
|
1250
|
-
}
|
|
1251
|
-
|
|
1252
|
-
const result = await response.json();
|
|
1253
|
-
setData(result);
|
|
1254
|
-
} catch (err) {
|
|
1255
|
-
setError(err.message);
|
|
1256
|
-
} finally {
|
|
1257
|
-
setLoading(false);
|
|
1258
|
-
}
|
|
1259
|
-
}, [url, options]);
|
|
1260
|
-
|
|
1261
|
-
useEffect(() => {
|
|
1262
|
-
fetchData();
|
|
1263
|
-
}, [fetchData]);
|
|
1264
|
-
|
|
1265
|
-
const refetch = useCallback(() => {
|
|
1266
|
-
fetchData();
|
|
1267
|
-
}, [fetchData]);
|
|
1268
|
-
|
|
1269
|
-
return { data, loading, error, refetch };
|
|
1270
|
-
};
|
|
1271
|
-
|
|
1272
|
-
// Local storage hook
|
|
1273
|
-
export const useLocalStorage = (key, initialValue) => {
|
|
1274
|
-
const [storedValue, setStoredValue] = useState(() => {
|
|
1275
|
-
try {
|
|
1276
|
-
const item = window.localStorage.getItem(key);
|
|
1277
|
-
return item ? JSON.parse(item) : initialValue;
|
|
1278
|
-
} catch (error) {
|
|
1279
|
-
console.error(`Error reading localStorage key "${key}":`, error);
|
|
1280
|
-
return initialValue;
|
|
1281
|
-
}
|
|
1282
|
-
});
|
|
1283
|
-
|
|
1284
|
-
const setValue = useCallback((value) => {
|
|
1285
|
-
try {
|
|
1286
|
-
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
1287
|
-
setStoredValue(valueToStore);
|
|
1288
|
-
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
1289
|
-
} catch (error) {
|
|
1290
|
-
console.error(`Error setting localStorage key "${key}":`, error);
|
|
1291
|
-
}
|
|
1292
|
-
}, [key, storedValue]);
|
|
1293
|
-
|
|
1294
|
-
return [storedValue, setValue];
|
|
1295
|
-
};
|
|
1296
|
-
```
|
|
1297
|
-
|
|
1298
|
-
**Context Pattern:**
|
|
1299
|
-
```jsx
|
|
1300
|
-
import React, { createContext, useContext, useReducer, useCallback } from 'react';
|
|
1301
|
-
|
|
1302
|
-
// State and actions
|
|
1303
|
-
const initialState = {
|
|
1304
|
-
user: null,
|
|
1305
|
-
isAuthenticated: false,
|
|
1306
|
-
loading: false,
|
|
1307
|
-
error: null
|
|
1308
|
-
};
|
|
1309
|
-
|
|
1310
|
-
const authReducer = (state, action) => {
|
|
1311
|
-
switch (action.type) {
|
|
1312
|
-
case 'LOGIN_START':
|
|
1313
|
-
return { ...state, loading: true, error: null };
|
|
1314
|
-
case 'LOGIN_SUCCESS':
|
|
1315
|
-
return {
|
|
1316
|
-
...state,
|
|
1317
|
-
user: action.payload,
|
|
1318
|
-
isAuthenticated: true,
|
|
1319
|
-
loading: false,
|
|
1320
|
-
error: null
|
|
1321
|
-
};
|
|
1322
|
-
case 'LOGIN_FAILURE':
|
|
1323
|
-
return {
|
|
1324
|
-
...state,
|
|
1325
|
-
user: null,
|
|
1326
|
-
isAuthenticated: false,
|
|
1327
|
-
loading: false,
|
|
1328
|
-
error: action.payload
|
|
1329
|
-
};
|
|
1330
|
-
case 'LOGOUT':
|
|
1331
|
-
return initialState;
|
|
1332
|
-
default:
|
|
1333
|
-
return state;
|
|
1334
|
-
}
|
|
1335
|
-
};
|
|
1336
|
-
|
|
1337
|
-
// Context creation
|
|
1338
|
-
const AuthContext = createContext();
|
|
1339
|
-
|
|
1340
|
-
// Provider component
|
|
1341
|
-
export const AuthProvider = ({ children }) => {
|
|
1342
|
-
const [state, dispatch] = useReducer(authReducer, initialState);
|
|
1343
|
-
|
|
1344
|
-
const login = useCallback(async (credentials) => {
|
|
1345
|
-
dispatch({ type: 'LOGIN_START' });
|
|
1346
|
-
try {
|
|
1347
|
-
const user = await authService.login(credentials);
|
|
1348
|
-
dispatch({ type: 'LOGIN_SUCCESS', payload: user });
|
|
1349
|
-
return user;
|
|
1350
|
-
} catch (error) {
|
|
1351
|
-
dispatch({ type: 'LOGIN_FAILURE', payload: error.message });
|
|
1352
|
-
throw error;
|
|
1353
|
-
}
|
|
1354
|
-
}, []);
|
|
1355
|
-
|
|
1356
|
-
const logout = useCallback(() => {
|
|
1357
|
-
authService.logout();
|
|
1358
|
-
dispatch({ type: 'LOGOUT' });
|
|
1359
|
-
}, []);
|
|
1360
|
-
|
|
1361
|
-
const value = {
|
|
1362
|
-
...state,
|
|
1363
|
-
login,
|
|
1364
|
-
logout
|
|
1365
|
-
};
|
|
1366
|
-
|
|
1367
|
-
return (
|
|
1368
|
-
<AuthContext.Provider value={value}>
|
|
1369
|
-
{children}
|
|
1370
|
-
</AuthContext.Provider>
|
|
1371
|
-
);
|
|
1372
|
-
};
|
|
1373
|
-
|
|
1374
|
-
// Custom hook for using auth context
|
|
1375
|
-
export const useAuth = () => {
|
|
1376
|
-
const context = useContext(AuthContext);
|
|
1377
|
-
if (!context) {
|
|
1378
|
-
throw new Error('useAuth must be used within an AuthProvider');
|
|
1379
|
-
}
|
|
1380
|
-
return context;
|
|
1381
|
-
};
|
|
1382
|
-
```
|
|
1383
|
-
|
|
1384
|
-
**Testing with React Testing Library:**
|
|
1385
|
-
```jsx
|
|
1386
|
-
import React from 'react';
|
|
1387
|
-
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
|
1388
|
-
import userEvent from '@testing-library/user-event';
|
|
1389
|
-
import { jest } from '@jest/globals';
|
|
1390
|
-
import UserProfile from '../UserProfile';
|
|
1391
|
-
import * as api from '../../services/api';
|
|
1392
|
-
|
|
1393
|
-
// Mock the API module
|
|
1394
|
-
jest.mock('../../services/api');
|
|
1395
|
-
|
|
1396
|
-
describe('UserProfile', () => {
|
|
1397
|
-
const mockUser = {
|
|
1398
|
-
id: '123',
|
|
1399
|
-
name: 'John Doe',
|
|
1400
|
-
email: 'john@example.com',
|
|
1401
|
-
posts: [{ id: 1, title: 'Test Post' }]
|
|
1402
|
-
};
|
|
1403
|
-
|
|
1404
|
-
beforeEach(() => {
|
|
1405
|
-
jest.clearAllMocks();
|
|
1406
|
-
});
|
|
1407
|
-
|
|
1408
|
-
test('renders user profile after loading', async () => {
|
|
1409
|
-
api.getUserById.mockResolvedValue(mockUser);
|
|
1410
|
-
|
|
1411
|
-
render(<UserProfile userId="123" />);
|
|
1412
|
-
|
|
1413
|
-
// Check loading state
|
|
1414
|
-
expect(screen.getByTestId('loading-spinner')).toBeInTheDocument();
|
|
1415
|
-
|
|
1416
|
-
// Wait for user data to load
|
|
1417
|
-
await waitFor(() => {
|
|
1418
|
-
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
|
1419
|
-
});
|
|
1420
|
-
|
|
1421
|
-
expect(screen.getByText('john@example.com')).toBeInTheDocument();
|
|
1422
|
-
expect(screen.getByText('1 Posts')).toBeInTheDocument();
|
|
1423
|
-
});
|
|
1424
|
-
|
|
1425
|
-
test('handles update user interaction', async () => {
|
|
1426
|
-
const user = userEvent.setup();
|
|
1427
|
-
const onUpdate = jest.fn();
|
|
1428
|
-
|
|
1429
|
-
api.getUserById.mockResolvedValue(mockUser);
|
|
1430
|
-
api.updateUser.mockResolvedValue({ ...mockUser, name: 'Jane Doe' });
|
|
1431
|
-
|
|
1432
|
-
render(<UserProfile userId="123" onUpdate={onUpdate} />);
|
|
1433
|
-
|
|
1434
|
-
await waitFor(() => {
|
|
1435
|
-
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
|
1436
|
-
});
|
|
1437
|
-
|
|
1438
|
-
const editButton = screen.getByRole('button', { name: /edit/i });
|
|
1439
|
-
await user.click(editButton);
|
|
1440
|
-
|
|
1441
|
-
const nameInput = screen.getByDisplayValue('John Doe');
|
|
1442
|
-
await user.clear(nameInput);
|
|
1443
|
-
await user.type(nameInput, 'Jane Doe');
|
|
1444
|
-
|
|
1445
|
-
const saveButton = screen.getByRole('button', { name: /save/i });
|
|
1446
|
-
await user.click(saveButton);
|
|
1447
|
-
|
|
1448
|
-
await waitFor(() => {
|
|
1449
|
-
expect(onUpdate).toHaveBeenCalledWith({ ...mockUser, name: 'Jane Doe' });
|
|
1450
|
-
});
|
|
1451
|
-
});
|
|
1452
|
-
|
|
1453
|
-
test('displays error message on API failure', async () => {
|
|
1454
|
-
api.getUserById.mockRejectedValue(new Error('Network error'));
|
|
1455
|
-
|
|
1456
|
-
render(<UserProfile userId="123" />);
|
|
1457
|
-
|
|
1458
|
-
await waitFor(() => {
|
|
1459
|
-
expect(screen.getByText(/network error/i)).toBeInTheDocument();
|
|
1460
|
-
});
|
|
1461
|
-
});
|
|
1462
|
-
});
|
|
1463
|
-
```
|
|
1464
|
-
|
|
1465
|
-
**Performance Optimization:**
|
|
1466
|
-
```jsx
|
|
1467
|
-
import React, { memo, lazy, Suspense } from 'react';
|
|
1468
|
-
|
|
1469
|
-
// Lazy loading for code splitting
|
|
1470
|
-
const LazyUserProfile = lazy(() => import('./UserProfile'));
|
|
1471
|
-
const LazyUserSettings = lazy(() => import('./UserSettings'));
|
|
1472
|
-
|
|
1473
|
-
// Memoized component to prevent unnecessary re-renders
|
|
1474
|
-
const UserCard = memo(({ user, onUpdate }) => {
|
|
1475
|
-
return (
|
|
1476
|
-
<div className="user-card">
|
|
1477
|
-
<h3>{user.name}</h3>
|
|
1478
|
-
<p>{user.email}</p>
|
|
1479
|
-
<button onClick={() => onUpdate(user.id)}>
|
|
1480
|
-
Update
|
|
1481
|
-
</button>
|
|
1482
|
-
</div>
|
|
1483
|
-
);
|
|
1484
|
-
});
|
|
1485
|
-
|
|
1486
|
-
// Main app with lazy loading
|
|
1487
|
-
const App = () => {
|
|
1488
|
-
return (
|
|
1489
|
-
<div className="app">
|
|
1490
|
-
<Suspense fallback={<div>Loading...</div>}>
|
|
1491
|
-
<Routes>
|
|
1492
|
-
<Route path="/profile" element={<LazyUserProfile />} />
|
|
1493
|
-
<Route path="/settings" element={<LazyUserSettings />} />
|
|
1494
|
-
</Routes>
|
|
1495
|
-
</Suspense>
|
|
1496
|
-
</div>
|
|
1497
|
-
);
|
|
1498
|
-
};
|
|
1499
|
-
```
|
|
252
|
+
[Single Message]:
|
|
253
|
+
// Step 1: Initialize swarm (REQUIRED for ALL multi-agent tasks)
|
|
254
|
+
mcp__claude-flow-novice__swarm_init({
|
|
255
|
+
topology: "mesh", // mesh (2-7 agents), hierarchical (8+)
|
|
256
|
+
maxAgents: 3, // Match your actual agent count
|
|
257
|
+
strategy: "balanced" // ensures agents coordinate and stay consistent
|
|
258
|
+
})
|
|
259
|
+
|
|
260
|
+
// Step 2 (Optional but recommended): Spawn coordination agent
|
|
261
|
+
mcp__claude-flow-novice__agent_spawn({
|
|
262
|
+
type: "coordinator",
|
|
263
|
+
name: "Swarm-Coordinator",
|
|
264
|
+
capabilities: ["consistency_enforcement", "method_coordination"]
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
// Step 3: Spawn working agents via Task tool
|
|
268
|
+
Task("Agent 1", "Instructions...", "type")
|
|
269
|
+
Task("Agent 2", "Instructions...", "type")
|
|
270
|
+
Task("Agent 3", "Instructions...", "type")
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
**WHY THIS MATTERS:**
|
|
274
|
+
- ✅ **Prevents inconsistency**: Without swarm, 3 agents fixing JWT secrets will use 3 different methods
|
|
275
|
+
- ✅ **Ensures coordination**: Agents share findings and agree on approach
|
|
276
|
+
- ✅ **Memory coordination**: Agents access shared context via SwarmMemory
|
|
277
|
+
- ✅ **Byzantine consensus**: Final validation ensures all agents agree
|
|
278
|
+
|
|
279
|
+
**TOPOLOGY SELECTION:**
|
|
280
|
+
- **2-7 agents**: Use `topology: "mesh"` (peer-to-peer, equal collaboration)
|
|
281
|
+
- **8+ agents**: Use `topology: "hierarchical"` (coordinator-led structure)
|
|
282
|
+
|
|
283
|
+
**MCP Integration Tools:**
|
|
284
|
+
- `mcp__claude-flow-novice__swarm_init` - Initialize swarm topology (REQUIRED for ALL multi-agent tasks)
|
|
285
|
+
- `mcp__claude-flow-novice__agent_spawn` - Spawn coordination agents (recommended for consistency)
|
|
286
|
+
- `mcp__claude-flow-novice__task_orchestrate` - Orchestrate high-level workflows
|
|
287
|
+
- **Monitoring**: `swarm_status`, `agent_metrics`, `task_results`
|
|
288
|
+
- **Memory**: `memory_usage`, `memory_search`
|
|
289
|
+
|
|
290
|
+
### ⚠️ REAL EXAMPLE: Why Swarm Init Matters
|
|
291
|
+
|
|
292
|
+
**WITHOUT swarm_init:**
|
|
293
|
+
```javascript
|
|
294
|
+
// ❌ BAD: Agents work independently with no coordination
|
|
295
|
+
[Single Message]:
|
|
296
|
+
Task("Agent 1", "Fix JWT secret issue", "coder")
|
|
297
|
+
Task("Agent 2", "Fix JWT secret issue", "coder")
|
|
298
|
+
Task("Agent 3", "Fix JWT secret issue", "coder")
|
|
1500
299
|
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
import { create } from 'zustand';
|
|
1504
|
-
import { devtools, persist } from 'zustand/middleware';
|
|
1505
|
-
|
|
1506
|
-
const useUserStore = create(
|
|
1507
|
-
devtools(
|
|
1508
|
-
persist(
|
|
1509
|
-
(set, get) => ({
|
|
1510
|
-
users: [],
|
|
1511
|
-
currentUser: null,
|
|
1512
|
-
loading: false,
|
|
1513
|
-
|
|
1514
|
-
fetchUsers: async () => {
|
|
1515
|
-
set({ loading: true });
|
|
1516
|
-
try {
|
|
1517
|
-
const users = await api.getUsers();
|
|
1518
|
-
set({ users, loading: false });
|
|
1519
|
-
} catch (error) {
|
|
1520
|
-
set({ loading: false });
|
|
1521
|
-
throw error;
|
|
1522
|
-
}
|
|
1523
|
-
},
|
|
1524
|
-
|
|
1525
|
-
setCurrentUser: (user) => set({ currentUser: user }),
|
|
1526
|
-
|
|
1527
|
-
updateUser: async (userId, updates) => {
|
|
1528
|
-
const updatedUser = await api.updateUser(userId, updates);
|
|
1529
|
-
set((state) => ({
|
|
1530
|
-
users: state.users.map((user) =>
|
|
1531
|
-
user.id === userId ? updatedUser : user
|
|
1532
|
-
),
|
|
1533
|
-
currentUser: state.currentUser?.id === userId ? updatedUser : state.currentUser
|
|
1534
|
-
}));
|
|
1535
|
-
return updatedUser;
|
|
1536
|
-
}
|
|
1537
|
-
}),
|
|
1538
|
-
{ name: 'user-store' }
|
|
1539
|
-
)
|
|
1540
|
-
)
|
|
1541
|
-
);
|
|
1542
|
-
|
|
1543
|
-
// Usage in component
|
|
1544
|
-
const UserList = () => {
|
|
1545
|
-
const { users, loading, fetchUsers } = useUserStore();
|
|
1546
|
-
|
|
1547
|
-
useEffect(() => {
|
|
1548
|
-
fetchUsers();
|
|
1549
|
-
}, [fetchUsers]);
|
|
1550
|
-
|
|
1551
|
-
if (loading) return <LoadingSpinner />;
|
|
1552
|
-
|
|
1553
|
-
return (
|
|
1554
|
-
<div>
|
|
1555
|
-
{users.map((user) => (
|
|
1556
|
-
<UserCard key={user.id} user={user} />
|
|
1557
|
-
))}
|
|
1558
|
-
</div>
|
|
1559
|
-
);
|
|
1560
|
-
};
|
|
1561
|
-
```
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
hooks/ # Custom hooks
|
|
1565
|
-
useApi.js
|
|
1566
|
-
useLocalStorage.js
|
|
1567
|
-
useAuth.js
|
|
1568
|
-
context/ # React context providers
|
|
1569
|
-
AuthContext.jsx
|
|
1570
|
-
ThemeContext.jsx
|
|
1571
|
-
services/ # API services
|
|
1572
|
-
api.js
|
|
1573
|
-
auth.js
|
|
1574
|
-
utils/ # Helper functions
|
|
1575
|
-
validators.js
|
|
1576
|
-
formatters.js
|
|
1577
|
-
styles/ # Global styles
|
|
1578
|
-
globals.css
|
|
1579
|
-
variables.css
|
|
300
|
+
// Result: 3 different solutions - environment variable, config file, hardcoded
|
|
301
|
+
// Problem: Inconsistent approach, wasted effort, conflicts
|
|
1580
302
|
```
|
|
1581
303
|
|
|
1582
|
-
**
|
|
1583
|
-
```
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
const [error, setError] = useState(null);
|
|
1592
|
-
|
|
1593
|
-
// Memoized expensive calculations
|
|
1594
|
-
const userStats = useMemo(() => {
|
|
1595
|
-
if (!user) return null;
|
|
1596
|
-
return {
|
|
1597
|
-
totalPosts: user.posts?.length || 0,
|
|
1598
|
-
joinedDate: new Date(user.createdAt).toLocaleDateString()
|
|
1599
|
-
};
|
|
1600
|
-
}, [user]);
|
|
1601
|
-
|
|
1602
|
-
// Memoized callbacks to prevent unnecessary re-renders
|
|
1603
|
-
const handleUpdateUser = useCallback(async (updates) => {
|
|
1604
|
-
try {
|
|
1605
|
-
const updatedUser = await updateUser(userId, updates);
|
|
1606
|
-
setUser(updatedUser);
|
|
1607
|
-
onUpdate?.(updatedUser);
|
|
1608
|
-
} catch (err) {
|
|
1609
|
-
setError(err.message);
|
|
1610
|
-
}
|
|
1611
|
-
}, [userId, onUpdate]);
|
|
1612
|
-
|
|
1613
|
-
useEffect(() => {
|
|
1614
|
-
let cancelled = false;
|
|
1615
|
-
|
|
1616
|
-
const fetchUser = async () => {
|
|
1617
|
-
try {
|
|
1618
|
-
setLoading(true);
|
|
1619
|
-
const userData = await getUserById(userId);
|
|
1620
|
-
if (!cancelled) {
|
|
1621
|
-
setUser(userData);
|
|
1622
|
-
}
|
|
1623
|
-
} catch (err) {
|
|
1624
|
-
if (!cancelled) {
|
|
1625
|
-
setError(err.message);
|
|
1626
|
-
}
|
|
1627
|
-
} finally {
|
|
1628
|
-
if (!cancelled) {
|
|
1629
|
-
setLoading(false);
|
|
1630
|
-
}
|
|
1631
|
-
}
|
|
1632
|
-
};
|
|
1633
|
-
|
|
1634
|
-
fetchUser();
|
|
1635
|
-
|
|
1636
|
-
return () => {
|
|
1637
|
-
cancelled = true;
|
|
1638
|
-
};
|
|
1639
|
-
}, [userId]);
|
|
1640
|
-
|
|
1641
|
-
if (loading) return <LoadingSpinner />;
|
|
1642
|
-
if (error) return <ErrorMessage message={error} />;
|
|
1643
|
-
if (!user) return <NotFound />;
|
|
1644
|
-
|
|
1645
|
-
return (
|
|
1646
|
-
<div className="user-profile">
|
|
1647
|
-
<ProfileHeader user={user} stats={userStats} />
|
|
1648
|
-
<ProfileContent user={user} onUpdate={handleUpdateUser} />
|
|
1649
|
-
</div>
|
|
1650
|
-
);
|
|
1651
|
-
};
|
|
1652
|
-
|
|
1653
|
-
UserProfile.propTypes = {
|
|
1654
|
-
userId: PropTypes.string.isRequired,
|
|
1655
|
-
onUpdate: PropTypes.func
|
|
1656
|
-
};
|
|
1657
|
-
|
|
1658
|
-
export default React.memo(UserProfile);
|
|
1659
|
-
```
|
|
304
|
+
**WITH swarm_init:**
|
|
305
|
+
```javascript
|
|
306
|
+
// ✅ GOOD: Agents coordinate through swarm
|
|
307
|
+
[Single Message]:
|
|
308
|
+
mcp__claude-flow-novice__swarm_init({
|
|
309
|
+
topology: "mesh",
|
|
310
|
+
maxAgents: 3,
|
|
311
|
+
strategy: "balanced"
|
|
312
|
+
})
|
|
1660
313
|
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
// Generic API hook
|
|
1666
|
-
export const useApi = (url, options = {}) => {
|
|
1667
|
-
const [data, setData] = useState(null);
|
|
1668
|
-
const [loading, setLoading] = useState(true);
|
|
1669
|
-
const [error, setError] = useState(null);
|
|
1670
|
-
|
|
1671
|
-
const fetchData = useCallback(async () => {
|
|
1672
|
-
try {
|
|
1673
|
-
setLoading(true);
|
|
1674
|
-
setError(null);
|
|
1675
|
-
const response = await fetch(url, options);
|
|
1676
|
-
|
|
1677
|
-
if (!response.ok) {
|
|
1678
|
-
throw new Error(`HTTP error! status: ${response.status}`);
|
|
1679
|
-
}
|
|
1680
|
-
|
|
1681
|
-
const result = await response.json();
|
|
1682
|
-
setData(result);
|
|
1683
|
-
} catch (err) {
|
|
1684
|
-
setError(err.message);
|
|
1685
|
-
} finally {
|
|
1686
|
-
setLoading(false);
|
|
1687
|
-
}
|
|
1688
|
-
}, [url, options]);
|
|
1689
|
-
|
|
1690
|
-
useEffect(() => {
|
|
1691
|
-
fetchData();
|
|
1692
|
-
}, [fetchData]);
|
|
1693
|
-
|
|
1694
|
-
const refetch = useCallback(() => {
|
|
1695
|
-
fetchData();
|
|
1696
|
-
}, [fetchData]);
|
|
1697
|
-
|
|
1698
|
-
return { data, loading, error, refetch };
|
|
1699
|
-
};
|
|
1700
|
-
|
|
1701
|
-
// Local storage hook
|
|
1702
|
-
export const useLocalStorage = (key, initialValue) => {
|
|
1703
|
-
const [storedValue, setStoredValue] = useState(() => {
|
|
1704
|
-
try {
|
|
1705
|
-
const item = window.localStorage.getItem(key);
|
|
1706
|
-
return item ? JSON.parse(item) : initialValue;
|
|
1707
|
-
} catch (error) {
|
|
1708
|
-
console.error(`Error reading localStorage key "${key}":`, error);
|
|
1709
|
-
return initialValue;
|
|
1710
|
-
}
|
|
1711
|
-
});
|
|
1712
|
-
|
|
1713
|
-
const setValue = useCallback((value) => {
|
|
1714
|
-
try {
|
|
1715
|
-
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
1716
|
-
setStoredValue(valueToStore);
|
|
1717
|
-
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
1718
|
-
} catch (error) {
|
|
1719
|
-
console.error(`Error setting localStorage key "${key}":`, error);
|
|
1720
|
-
}
|
|
1721
|
-
}, [key, storedValue]);
|
|
1722
|
-
|
|
1723
|
-
return [storedValue, setValue];
|
|
1724
|
-
};
|
|
1725
|
-
```
|
|
314
|
+
Task("Agent 1", "Fix JWT secret issue", "coder")
|
|
315
|
+
Task("Agent 2", "Fix JWT secret issue", "coder")
|
|
316
|
+
Task("Agent 3", "Fix JWT secret issue", "coder")
|
|
1726
317
|
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
import React, { createContext, useContext, useReducer, useCallback } from 'react';
|
|
1730
|
-
|
|
1731
|
-
// State and actions
|
|
1732
|
-
const initialState = {
|
|
1733
|
-
user: null,
|
|
1734
|
-
isAuthenticated: false,
|
|
1735
|
-
loading: false,
|
|
1736
|
-
error: null
|
|
1737
|
-
};
|
|
1738
|
-
|
|
1739
|
-
const authReducer = (state, action) => {
|
|
1740
|
-
switch (action.type) {
|
|
1741
|
-
case 'LOGIN_START':
|
|
1742
|
-
return { ...state, loading: true, error: null };
|
|
1743
|
-
case 'LOGIN_SUCCESS':
|
|
1744
|
-
return {
|
|
1745
|
-
...state,
|
|
1746
|
-
user: action.payload,
|
|
1747
|
-
isAuthenticated: true,
|
|
1748
|
-
loading: false,
|
|
1749
|
-
error: null
|
|
1750
|
-
};
|
|
1751
|
-
case 'LOGIN_FAILURE':
|
|
1752
|
-
return {
|
|
1753
|
-
...state,
|
|
1754
|
-
user: null,
|
|
1755
|
-
isAuthenticated: false,
|
|
1756
|
-
loading: false,
|
|
1757
|
-
error: action.payload
|
|
1758
|
-
};
|
|
1759
|
-
case 'LOGOUT':
|
|
1760
|
-
return initialState;
|
|
1761
|
-
default:
|
|
1762
|
-
return state;
|
|
1763
|
-
}
|
|
1764
|
-
};
|
|
1765
|
-
|
|
1766
|
-
// Context creation
|
|
1767
|
-
const AuthContext = createContext();
|
|
1768
|
-
|
|
1769
|
-
// Provider component
|
|
1770
|
-
export const AuthProvider = ({ children }) => {
|
|
1771
|
-
const [state, dispatch] = useReducer(authReducer, initialState);
|
|
1772
|
-
|
|
1773
|
-
const login = useCallback(async (credentials) => {
|
|
1774
|
-
dispatch({ type: 'LOGIN_START' });
|
|
1775
|
-
try {
|
|
1776
|
-
const user = await authService.login(credentials);
|
|
1777
|
-
dispatch({ type: 'LOGIN_SUCCESS', payload: user });
|
|
1778
|
-
return user;
|
|
1779
|
-
} catch (error) {
|
|
1780
|
-
dispatch({ type: 'LOGIN_FAILURE', payload: error.message });
|
|
1781
|
-
throw error;
|
|
1782
|
-
}
|
|
1783
|
-
}, []);
|
|
1784
|
-
|
|
1785
|
-
const logout = useCallback(() => {
|
|
1786
|
-
authService.logout();
|
|
1787
|
-
dispatch({ type: 'LOGOUT' });
|
|
1788
|
-
}, []);
|
|
1789
|
-
|
|
1790
|
-
const value = {
|
|
1791
|
-
...state,
|
|
1792
|
-
login,
|
|
1793
|
-
logout
|
|
1794
|
-
};
|
|
1795
|
-
|
|
1796
|
-
return (
|
|
1797
|
-
<AuthContext.Provider value={value}>
|
|
1798
|
-
{children}
|
|
1799
|
-
</AuthContext.Provider>
|
|
1800
|
-
);
|
|
1801
|
-
};
|
|
1802
|
-
|
|
1803
|
-
// Custom hook for using auth context
|
|
1804
|
-
export const useAuth = () => {
|
|
1805
|
-
const context = useContext(AuthContext);
|
|
1806
|
-
if (!context) {
|
|
1807
|
-
throw new Error('useAuth must be used within an AuthProvider');
|
|
1808
|
-
}
|
|
1809
|
-
return context;
|
|
1810
|
-
};
|
|
318
|
+
// Result: All 3 agents agree on environment variable approach
|
|
319
|
+
// Benefit: Consistent solution, shared context, coordinated implementation
|
|
1811
320
|
```
|
|
1812
321
|
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
import React from 'react';
|
|
1816
|
-
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
|
1817
|
-
import userEvent from '@testing-library/user-event';
|
|
1818
|
-
import { jest } from '@jest/globals';
|
|
1819
|
-
import UserProfile from '../UserProfile';
|
|
1820
|
-
import * as api from '../../services/api';
|
|
1821
|
-
|
|
1822
|
-
// Mock the API module
|
|
1823
|
-
jest.mock('../../services/api');
|
|
322
|
+
## File Organization
|
|
323
|
+
- **Never save working files to root**
|
|
1824
324
|
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
id: '123',
|
|
1828
|
-
name: 'John Doe',
|
|
1829
|
-
email: 'john@example.com',
|
|
1830
|
-
posts: [{ id: 1, title: 'Test Post' }]
|
|
1831
|
-
};
|
|
325
|
+
# Add MCP server
|
|
326
|
+
claude mcp add claude-flow-novice npx claude-flow-novice mcp start
|
|
1832
327
|
|
|
1833
|
-
beforeEach(() => {
|
|
1834
|
-
jest.clearAllMocks();
|
|
1835
|
-
});
|
|
1836
328
|
|
|
1837
|
-
|
|
1838
|
-
|
|
329
|
+
## Essential Commands
|
|
330
|
+
- `npx claude-flow-novice status` - System health
|
|
331
|
+
- `npx claude-flow-novice --help` - Available commands
|
|
332
|
+
- `/fullstack "goal"` - Launch full-stack development team with consensus validation
|
|
333
|
+
- `/swarm`, `/sparc`, `/hooks` - Other slash commands (auto-discovered)
|
|
1839
334
|
|
|
1840
|
-
|
|
335
|
+
## 🔄 MANDATORY DEVELOPMENT FLOW LOOP
|
|
1841
336
|
|
|
1842
|
-
|
|
1843
|
-
expect(screen.getByTestId('loading-spinner')).toBeInTheDocument();
|
|
337
|
+
**YOU MUST FOLLOW THIS LOOP FOR ALL NON-TRIVIAL WORK:**
|
|
1844
338
|
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
**
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
});
|
|
1914
|
-
|
|
1915
|
-
// Main app with lazy loading
|
|
1916
|
-
const App = () => {
|
|
1917
|
-
return (
|
|
1918
|
-
<div className="app">
|
|
1919
|
-
<Suspense fallback={<div>Loading...</div>}>
|
|
1920
|
-
<Routes>
|
|
1921
|
-
<Route path="/profile" element={<LazyUserProfile />} />
|
|
1922
|
-
<Route path="/settings" element={<LazyUserSettings />} />
|
|
1923
|
-
</Routes>
|
|
1924
|
-
</Suspense>
|
|
1925
|
-
</div>
|
|
1926
|
-
);
|
|
1927
|
-
};
|
|
1928
|
-
```
|
|
1929
|
-
|
|
1930
|
-
**State Management with Zustand:**
|
|
1931
|
-
```jsx
|
|
1932
|
-
import { create } from 'zustand';
|
|
1933
|
-
import { devtools, persist } from 'zustand/middleware';
|
|
1934
|
-
|
|
1935
|
-
const useUserStore = create(
|
|
1936
|
-
devtools(
|
|
1937
|
-
persist(
|
|
1938
|
-
(set, get) => ({
|
|
1939
|
-
users: [],
|
|
1940
|
-
currentUser: null,
|
|
1941
|
-
loading: false,
|
|
1942
|
-
|
|
1943
|
-
fetchUsers: async () => {
|
|
1944
|
-
set({ loading: true });
|
|
1945
|
-
try {
|
|
1946
|
-
const users = await api.getUsers();
|
|
1947
|
-
set({ users, loading: false });
|
|
1948
|
-
} catch (error) {
|
|
1949
|
-
set({ loading: false });
|
|
1950
|
-
throw error;
|
|
1951
|
-
}
|
|
1952
|
-
},
|
|
1953
|
-
|
|
1954
|
-
setCurrentUser: (user) => set({ currentUser: user }),
|
|
1955
|
-
|
|
1956
|
-
updateUser: async (userId, updates) => {
|
|
1957
|
-
const updatedUser = await api.updateUser(userId, updates);
|
|
1958
|
-
set((state) => ({
|
|
1959
|
-
users: state.users.map((user) =>
|
|
1960
|
-
user.id === userId ? updatedUser : user
|
|
1961
|
-
),
|
|
1962
|
-
currentUser: state.currentUser?.id === userId ? updatedUser : state.currentUser
|
|
1963
|
-
}));
|
|
1964
|
-
return updatedUser;
|
|
1965
|
-
}
|
|
1966
|
-
}),
|
|
1967
|
-
{ name: 'user-store' }
|
|
1968
|
-
)
|
|
1969
|
-
)
|
|
1970
|
-
);
|
|
1971
|
-
|
|
1972
|
-
// Usage in component
|
|
1973
|
-
const UserList = () => {
|
|
1974
|
-
const { users, loading, fetchUsers } = useUserStore();
|
|
1975
|
-
|
|
1976
|
-
useEffect(() => {
|
|
1977
|
-
fetchUsers();
|
|
1978
|
-
}, [fetchUsers]);
|
|
1979
|
-
|
|
1980
|
-
if (loading) return <LoadingSpinner />;
|
|
1981
|
-
|
|
1982
|
-
return (
|
|
1983
|
-
<div>
|
|
1984
|
-
{users.map((user) => (
|
|
1985
|
-
<UserCard key={user.id} user={user} />
|
|
1986
|
-
))}
|
|
1987
|
-
</div>
|
|
1988
|
-
);
|
|
1989
|
-
};
|
|
1990
|
-
```
|
|
339
|
+
### Step 1: Initialize Swarm (ALWAYS for multi-agent tasks)
|
|
340
|
+
```javascript
|
|
341
|
+
[Single Message]:
|
|
342
|
+
// ALWAYS initialize swarm when spawning multiple agents
|
|
343
|
+
mcp__claude-flow-novice__swarm_init({
|
|
344
|
+
topology: "mesh", // mesh for 2-7, hierarchical for 8+
|
|
345
|
+
maxAgents: 3, // match your actual agent count
|
|
346
|
+
strategy: "balanced" // ensures coordination and consistency
|
|
347
|
+
})
|
|
348
|
+
|
|
349
|
+
// Then spawn all agents - they will coordinate via swarm
|
|
350
|
+
Task("Agent 1", "Specific instructions", "type")
|
|
351
|
+
Task("Agent 2", "Specific instructions", "type")
|
|
352
|
+
Task("Agent 3", "Specific instructions", "type")
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
**CRITICAL**: Without swarm_init, agents work independently and produce inconsistent results!
|
|
356
|
+
|
|
357
|
+
### Step 2: Execute - Primary Swarm (3-20 agents)
|
|
358
|
+
- **Primary swarm** (3-8 agents minimum) produces deliverables with confidence scores
|
|
359
|
+
- **Each agent MUST** use enhanced post-edit pipeline after file edits:
|
|
360
|
+
```bash
|
|
361
|
+
npx enhanced-hooks post-edit "[file]" --memory-key "swarm/[agent]/[step]" --structured
|
|
362
|
+
```
|
|
363
|
+
- **Self-validation**: Each agent validates own work (confidence threshold: 0.75)
|
|
364
|
+
- **Cross-agent coordination**: Agents share findings via SwarmMemory
|
|
365
|
+
|
|
366
|
+
### Step 3: Self-Assessment Gate
|
|
367
|
+
- **If confidence scores ≥75%** → Proceed to Step 4 (Consensus Verification)
|
|
368
|
+
- **If confidence scores <75%** → Relaunch agents for Step 2 with feedback
|
|
369
|
+
- **Maximum iterations**: 3 attempts before escalation
|
|
370
|
+
|
|
371
|
+
### Step 4: Verify - Consensus Swarm (2-4 validators REQUIRED)
|
|
372
|
+
```javascript
|
|
373
|
+
// MANDATORY: Spawn consensus validation swarm
|
|
374
|
+
[Single Message]:
|
|
375
|
+
Task("Validator 1", "Comprehensive quality review", "reviewer")
|
|
376
|
+
Task("Validator 2", "Security and performance audit", "security-specialist")
|
|
377
|
+
Task("Validator 3", "Architecture validation", "system-architect")
|
|
378
|
+
Task("Validator 4", "Integration testing", "tester")
|
|
379
|
+
```
|
|
380
|
+
- **Byzantine consensus voting** across all validators
|
|
381
|
+
- **Multi-dimensional checks**: quality, security, performance, tests, docs
|
|
382
|
+
|
|
383
|
+
### Step 5: Decision Gate
|
|
384
|
+
- **PASS**: ≥90% validator agreement + all critical criteria met
|
|
385
|
+
- **FAIL**: <90% agreement OR any critical criterion failed
|
|
386
|
+
|
|
387
|
+
### Step 6: Action Based on Decision
|
|
388
|
+
- **PASS** →
|
|
389
|
+
1. Store results in SwarmMemory
|
|
390
|
+
2. Update documentation
|
|
391
|
+
3. Move to next task
|
|
392
|
+
|
|
393
|
+
- **FAIL** →
|
|
394
|
+
1. Round counter++
|
|
395
|
+
2. If Round < 10: Inject validator feedback → Return to Step 2
|
|
396
|
+
3. If Round ≥ 10: Escalate to human with comprehensive report
|
|
397
|
+
|
|
398
|
+
### 🚨 ENFORCEMENT CHECKPOINTS
|
|
399
|
+
|
|
400
|
+
**MANDATORY before proceeding:**
|
|
401
|
+
1. ✅ Agents spawned (minimum count met for task complexity)
|
|
402
|
+
2. ✅ Each file edit followed by enhanced post-edit hook
|
|
403
|
+
3. ✅ Self-validation confidence scores recorded
|
|
404
|
+
4. ✅ Consensus swarm spawned for verification
|
|
405
|
+
5. ✅ Byzantine voting completed
|
|
406
|
+
6. ✅ Results stored in SwarmMemory
|