claudify-agent 0.0.0-stage → 1.0.1
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/QUICK-REFERENCE.md +213 -0
- package/.claude/cost-dashboard.md +162 -0
- package/.claude/docs/COST-OPTIMIZATION.md +403 -0
- package/.claude/docs/MCP-INTEGRATION-GUIDE.md +348 -0
- package/.claude/docs/PLAN-MODE-OPTIMIZATION.md +836 -0
- package/.claude/hooks/auto-learning-review.ts +195 -0
- package/.claude/hooks/auto-lint-fix.ts +104 -0
- package/.claude/hooks/auto-security-review.ts +354 -0
- package/.claude/hooks/auto-validate.ts +348 -0
- package/.claude/hooks/plan-quality-tracker.ts +719 -0
- package/.claude/rules/anti-patterns.md +22 -0
- package/.claude/rules/context-tier-1.md +41 -0
- package/.claude/rules/context-tier-2.md +285 -0
- package/.claude/rules/general.md +25 -0
- package/.claude/rules/mcp-auto-use.md +46 -0
- package/.claude/rules/parallel-exploration-auto.md +31 -0
- package/.claude/rules/plan-mode-execution.md +289 -0
- package/.claude/rules/plan-mode-research.md +34 -0
- package/.claude/rules/plan-mode-structure.md +166 -0
- package/.claude/rules/plan-mode-validation.md +130 -0
- package/.claude/rules/security-critical.md +19 -0
- package/.claude/rules/tool-auto-selection.md +45 -0
- package/.claude/rules/tool-strategy.md +22 -0
- package/.claude/scripts/auto-validate.js +69 -0
- package/.claude/scripts/security-scan.js +45 -0
- package/.claude/security-dashboard.md +142 -0
- package/.claude/skills/backend-concurrency/SKILL.md +203 -0
- package/.claude/skills/debug-optimizer/SKILL.md +399 -0
- package/.claude/skills/debug-optimizer.md +12 -0
- package/.claude/skills/golang-guide/SKILL.md +177 -0
- package/.claude/skills/learning-loop/SKILL.md +308 -0
- package/.claude/skills/mcp-mastery/SKILL.md +214 -0
- package/.claude/skills/nestjs-guide/SKILL.md +197 -0
- package/.claude/skills/nextjs-guide/SKILL.md +687 -0
- package/.claude/skills/nextjs.md +13 -0
- package/.claude/skills/parallel-exploration/SKILL.md +193 -0
- package/.claude/skills/plan-mode-mastery/SKILL.md +263 -0
- package/.claude/skills/python-guide/SKILL.md +822 -0
- package/.claude/skills/react-guide/SKILL.md +762 -0
- package/.claude/skills/react.md +12 -0
- package/.claude/skills/security.md +18 -0
- package/.claude/skills/solidity-guide/SKILL.md +32 -0
- package/.claude/skills/tool-selection/SKILL.md +428 -0
- package/.claude/skills/vite-guide/SKILL.md +445 -0
- package/CLAUDE.md +49 -0
- package/README.md +65 -2
- package/bin/cli.js +50 -0
- package/package.json +44 -4
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
# SKILL.md: Debug Mode Optimizer
|
|
2
|
+
|
|
3
|
+
## Description
|
|
4
|
+
Automatic optimization of debug mode workflows for maximum efficiency. Activates automatically in debug mode to coordinate tools, MCPs, skills, hooks, and rules.
|
|
5
|
+
|
|
6
|
+
## When to Use (Automatic Activation)
|
|
7
|
+
**This skill activates AUTOMATICALLY in debug mode for ALL tasks.**
|
|
8
|
+
|
|
9
|
+
**Purpose**: Coordinate all optimization mechanisms to minimize task completion time and token usage while maximizing quality.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Automatic Optimizations
|
|
14
|
+
|
|
15
|
+
### 1. Tool Selection Optimization
|
|
16
|
+
**Automatic Triggers**:
|
|
17
|
+
```
|
|
18
|
+
Task analysis → Select optimal tools based on:
|
|
19
|
+
- Task type (exploration, implementation, validation)
|
|
20
|
+
- Complexity (number of files, steps)
|
|
21
|
+
- Required precision (exact vs conceptual)
|
|
22
|
+
- Cost hierarchy (Tier 1 → Tier 4)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
**Optimization Rules**:
|
|
26
|
+
```
|
|
27
|
+
✓ ALWAYS start with Tier 1 tools (Read, Glob, Grep)
|
|
28
|
+
✓ Escalate one tier at a time only if needed
|
|
29
|
+
✓ NEVER use expensive tools when cheap tools work
|
|
30
|
+
✓ Track tool effectiveness for future optimization
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
### 2. MCP Server Optimization
|
|
36
|
+
**Automatic Triggers**:
|
|
37
|
+
```
|
|
38
|
+
File patterns + Keywords + Task type → Select optimal MCPs:
|
|
39
|
+
- components/**, "UI" → cursor-ide-browser
|
|
40
|
+
- __tests__/**, "E2E" → user-playwright
|
|
41
|
+
- "PR", "issue" → user-github
|
|
42
|
+
- "lint" → user-ESLint
|
|
43
|
+
- "docs", "how to" → user-context7
|
|
44
|
+
- "performance" → user-chrome-devtools
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**Optimization Rules**:
|
|
48
|
+
```
|
|
49
|
+
✓ ALWAYS run user-ESLint after code changes (cheap, high value)
|
|
50
|
+
✓ ALWAYS fetch user-context7 before library implementation (prevents errors)
|
|
51
|
+
✓ Use cursor-ide-browser ONLY when visual verification essential
|
|
52
|
+
✓ Chain MCPs automatically for complex workflows
|
|
53
|
+
✓ Track MCP usage and cost for optimization
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
### 3. Parallel Subagent Optimization
|
|
59
|
+
**Automatic Triggers**:
|
|
60
|
+
```
|
|
61
|
+
Task complexity analysis → Launch parallel subagents:
|
|
62
|
+
- >3 areas mentioned → Launch 4 subagents
|
|
63
|
+
- >10 steps → Launch 3 subagents
|
|
64
|
+
- Bug investigation → Launch 4 subagents
|
|
65
|
+
- Large refactor (>5 files) → Launch 4 subagents
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Configuration** (Automatic):
|
|
69
|
+
```yaml
|
|
70
|
+
model: "fast" # Cost optimization
|
|
71
|
+
readonly: true # Safety
|
|
72
|
+
run_in_background: true # Non-blocking
|
|
73
|
+
timeout: 120s # Time-box per subagent
|
|
74
|
+
max_parallel: 4 # Diminishing returns after 4
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
### 4. Context Engineering Optimization
|
|
80
|
+
**Automatic Triggers**:
|
|
81
|
+
```
|
|
82
|
+
Task keywords + File patterns → Load relevant Tier 2 context:
|
|
83
|
+
- "test" → Testing context
|
|
84
|
+
- "API" → API development context
|
|
85
|
+
- "UI", "component" → UI/Styling context
|
|
86
|
+
- "performance" → Performance context
|
|
87
|
+
- "database" → Database context
|
|
88
|
+
- "security" → Security context
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**Optimization Rules**:
|
|
92
|
+
```
|
|
93
|
+
✓ Load ONLY relevant context (avoid over-specification)
|
|
94
|
+
✓ Use Tier 1 (minimal) + Tier 2 (task-specific) injection
|
|
95
|
+
✓ Prune context after task completion
|
|
96
|
+
✓ Agent discovers details via search tools (not context)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
### 5. Hook-Based Validation Optimization
|
|
102
|
+
**Automatic Triggers**:
|
|
103
|
+
```
|
|
104
|
+
After code changes (after_code_change hook):
|
|
105
|
+
- auto-lint-fix → Fix lint issues first
|
|
106
|
+
- auto-validate → Unified validation (lint + typecheck + tests + MCP)
|
|
107
|
+
|
|
108
|
+
After plan mode (plan_mode_exit hook):
|
|
109
|
+
- plan-quality-tracker → Track metrics and provide feedback
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
**Validation Pipeline** (Automatic):
|
|
113
|
+
```
|
|
114
|
+
1. Code change detected
|
|
115
|
+
2. after_code_change hook triggers
|
|
116
|
+
3. auto-lint-fix: Run ESLint, auto-fix
|
|
117
|
+
4. auto-validate:
|
|
118
|
+
- Lint check
|
|
119
|
+
- Typecheck
|
|
120
|
+
- Run tests
|
|
121
|
+
- Validate MCP tools
|
|
122
|
+
5. Report results to user
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
---
|
|
126
|
+
|
|
127
|
+
## Debug-Specific Workflows
|
|
128
|
+
|
|
129
|
+
### Workflow 1: Feature Implementation (Optimized)
|
|
130
|
+
```
|
|
131
|
+
User: "Add user authentication with JWT"
|
|
132
|
+
|
|
133
|
+
Automatic Optimizations:
|
|
134
|
+
1. **Parallel Exploration** (4 subagents, 60s):
|
|
135
|
+
- Find auth patterns
|
|
136
|
+
- Find JWT libraries
|
|
137
|
+
- Find existing auth code
|
|
138
|
+
- Find auth tests
|
|
139
|
+
|
|
140
|
+
2. **Context Loading** (Tier 2):
|
|
141
|
+
- Security context
|
|
142
|
+
- API context
|
|
143
|
+
|
|
144
|
+
3. **MCP Chain**:
|
|
145
|
+
- user-context7: Fetch JWT library docs
|
|
146
|
+
- Implement feature
|
|
147
|
+
- user-ESLint: Auto-lint
|
|
148
|
+
- user-github: Create PR
|
|
149
|
+
|
|
150
|
+
4. **Validation Hooks**:
|
|
151
|
+
- auto-lint-fix: Fix issues
|
|
152
|
+
- auto-validate: Unified validation (includes MCP validation + tests)
|
|
153
|
+
|
|
154
|
+
Time: 5-7 minutes (vs 15-20 manual)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
### Workflow 2: Bug Fix (Optimized)
|
|
160
|
+
```
|
|
161
|
+
User: "Fix checkout bug #456"
|
|
162
|
+
|
|
163
|
+
Automatic Optimizations:
|
|
164
|
+
1. **Parallel Exploration** (4 subagents, 90s):
|
|
165
|
+
- Find checkout code
|
|
166
|
+
- Find payment code
|
|
167
|
+
- Find recent changes
|
|
168
|
+
- Find similar issues
|
|
169
|
+
|
|
170
|
+
2. **Context Loading** (Tier 2):
|
|
171
|
+
- API context (if API-related)
|
|
172
|
+
- Database context (if DB-related)
|
|
173
|
+
|
|
174
|
+
3. **MCP Chain**:
|
|
175
|
+
- user-github: Fetch issue #456
|
|
176
|
+
- user-context7: Check payment docs (if needed)
|
|
177
|
+
- Implement fix
|
|
178
|
+
- user-ESLint: Auto-lint
|
|
179
|
+
- user-github: Create PR
|
|
180
|
+
|
|
181
|
+
4. **Validation Hooks**:
|
|
182
|
+
- auto-lint-fix: Fix issues
|
|
183
|
+
- auto-validate: Unified validation (includes MCP validation + tests)
|
|
184
|
+
|
|
185
|
+
Time: 3-5 minutes (vs 10-15 manual)
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
### Workflow 3: Large Refactor (Optimized)
|
|
191
|
+
```
|
|
192
|
+
User: "Migrate from Prisma to Drizzle"
|
|
193
|
+
|
|
194
|
+
Automatic Optimizations:
|
|
195
|
+
1. **Parallel Exploration** (4 subagents, 120s):
|
|
196
|
+
- Find all Prisma usage
|
|
197
|
+
- Find all queries
|
|
198
|
+
- Find all migrations
|
|
199
|
+
- Find all tests
|
|
200
|
+
|
|
201
|
+
2. **Context Loading** (Tier 2):
|
|
202
|
+
- Database context
|
|
203
|
+
- Testing context
|
|
204
|
+
|
|
205
|
+
3. **MCP Chain**:
|
|
206
|
+
- user-context7: Fetch Drizzle docs
|
|
207
|
+
- Implement migration (incremental)
|
|
208
|
+
- user-ESLint: Auto-lint after each change
|
|
209
|
+
- test-runner: Run tests after each change
|
|
210
|
+
|
|
211
|
+
4. **Validation Hooks** (after each step):
|
|
212
|
+
- auto-lint-fix: Fix issues
|
|
213
|
+
- auto-validate: Run unified validation (includes tests)
|
|
214
|
+
|
|
215
|
+
Time: 20-30 minutes (vs 60-90 manual)
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
---
|
|
219
|
+
|
|
220
|
+
## Error Pattern Recognition
|
|
221
|
+
|
|
222
|
+
### Automatic Error Detection
|
|
223
|
+
```
|
|
224
|
+
Monitor for error patterns:
|
|
225
|
+
- ESLint errors → Trigger auto-lint-fix
|
|
226
|
+
- Test failures → Trigger auto-validate with debug mode
|
|
227
|
+
- Build errors → Fetch build docs via user-context7
|
|
228
|
+
- Runtime errors → Trigger browser debugging
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### Automatic Recovery
|
|
232
|
+
```
|
|
233
|
+
Error detected → Automatic response:
|
|
234
|
+
1. Identify error type
|
|
235
|
+
2. Fetch relevant docs (user-context7)
|
|
236
|
+
3. Implement fix
|
|
237
|
+
4. Validate (lint + tests)
|
|
238
|
+
5. If still failing → Escalate to human
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
243
|
+
## Performance Metrics (Automatic Tracking)
|
|
244
|
+
|
|
245
|
+
### Track Per Task
|
|
246
|
+
```
|
|
247
|
+
- Task completion time
|
|
248
|
+
- Token consumption
|
|
249
|
+
- Tool calls count
|
|
250
|
+
- MCP calls count
|
|
251
|
+
- Validation gate pass rate
|
|
252
|
+
- User satisfaction (manual rating)
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
### Weekly Optimization Review
|
|
256
|
+
```
|
|
257
|
+
Analyze metrics:
|
|
258
|
+
- Which optimizations saved most time?
|
|
259
|
+
- Which tools/MCPs most effective?
|
|
260
|
+
- Where are bottlenecks?
|
|
261
|
+
- What can be further automated?
|
|
262
|
+
- Adjust rules and triggers accordingly
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
---
|
|
266
|
+
|
|
267
|
+
## Cost Optimization (Enforced)
|
|
268
|
+
|
|
269
|
+
### Token Budget Allocation
|
|
270
|
+
```
|
|
271
|
+
Tier 1 tools (Read, Glob, Grep): 40% of budget
|
|
272
|
+
Tier 2 tools (SemanticSearch, StrReplace): 30% of budget
|
|
273
|
+
Tier 3 tools (Task, Shell, ReadLints): 20% of budget
|
|
274
|
+
Tier 4 tools (Parallel subagents, Browser MCP): 10% of budget
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
### Automatic Cost Control
|
|
278
|
+
```
|
|
279
|
+
If task exceeds budget:
|
|
280
|
+
1. Warn user
|
|
281
|
+
2. Suggest scope reduction
|
|
282
|
+
3. Offer to continue with approval
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
---
|
|
286
|
+
|
|
287
|
+
## Examples
|
|
288
|
+
|
|
289
|
+
### Example 1: Add Dark Mode (Optimized)
|
|
290
|
+
User: "Add dark mode toggle to settings page"
|
|
291
|
+
|
|
292
|
+
**Automatic Optimizations**:
|
|
293
|
+
```
|
|
294
|
+
1. Parallel subagents (2, 45s):
|
|
295
|
+
- "Find settings page structure"
|
|
296
|
+
- "Find Tailwind dark mode examples"
|
|
297
|
+
|
|
298
|
+
2. Context loaded: UI/Styling
|
|
299
|
+
|
|
300
|
+
3. MCP chain:
|
|
301
|
+
- user-context7: Tailwind dark mode docs
|
|
302
|
+
- cursor-ide-browser: Verify UI
|
|
303
|
+
- user-ESLint: Auto-lint
|
|
304
|
+
|
|
305
|
+
4. Hooks:
|
|
306
|
+
- auto-lint-fix: ✅ Passed
|
|
307
|
+
- auto-validate: ✅ All validations passed
|
|
308
|
+
|
|
309
|
+
Result: 4 minutes, 100% quality gates pass
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
---
|
|
313
|
+
|
|
314
|
+
### Example 2: Performance Audit (Optimized)
|
|
315
|
+
User: "Audit and improve dashboard performance"
|
|
316
|
+
|
|
317
|
+
**Automatic Optimizations**:
|
|
318
|
+
```
|
|
319
|
+
1. Parallel subagents (3, 90s):
|
|
320
|
+
- "Find dashboard code"
|
|
321
|
+
- "Find performance bottlenecks"
|
|
322
|
+
- "Find optimization patterns"
|
|
323
|
+
|
|
324
|
+
2. Context loaded: Performance
|
|
325
|
+
|
|
326
|
+
3. MCP chain:
|
|
327
|
+
- user-chrome-devtools: Lighthouse audit
|
|
328
|
+
- cursor-ide-browser: CPU profiling
|
|
329
|
+
- user-context7: React optimization docs
|
|
330
|
+
- Implement optimizations
|
|
331
|
+
- user-chrome-devtools: Re-audit
|
|
332
|
+
|
|
333
|
+
4. Hooks:
|
|
334
|
+
- auto-validate: ✅ All validations passed (MCP + tests)
|
|
335
|
+
|
|
336
|
+
Result: 8 minutes, Lighthouse score 92 (from 67)
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
---
|
|
340
|
+
|
|
341
|
+
### Example 3: Security Review (Optimized)
|
|
342
|
+
User: "Review authentication for vulnerabilities"
|
|
343
|
+
|
|
344
|
+
**Automatic Optimizations**:
|
|
345
|
+
```
|
|
346
|
+
1. Parallel subagents (4, 90s):
|
|
347
|
+
- "Find auth code"
|
|
348
|
+
- "Find token validation"
|
|
349
|
+
- "Find password handling"
|
|
350
|
+
- "Find input validation"
|
|
351
|
+
|
|
352
|
+
2. Context loaded: Security
|
|
353
|
+
|
|
354
|
+
3. MCP chain:
|
|
355
|
+
- user-context7: OWASP auth guidelines
|
|
356
|
+
- Implement security fixes
|
|
357
|
+
- user-ESLint: Auto-lint
|
|
358
|
+
- test-runner: Run security tests
|
|
359
|
+
|
|
360
|
+
4. Hooks:
|
|
361
|
+
- auto-lint-fix: ✅ Fixed 3 issues
|
|
362
|
+
- test-runner: ✅ All tests pass
|
|
363
|
+
|
|
364
|
+
Result: 6 minutes, 5 vulnerabilities fixed
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
---
|
|
368
|
+
|
|
369
|
+
## Anti-Patterns (Automatically Avoided)
|
|
370
|
+
|
|
371
|
+
### ❌ Over-Automation
|
|
372
|
+
**Prevention**: Start with minimal automation, add only when pain points observed
|
|
373
|
+
|
|
374
|
+
### ❌ Context Bloat
|
|
375
|
+
**Prevention**: Enforce 20-line max per context file, use references over content
|
|
376
|
+
|
|
377
|
+
### ❌ MCP Cost Explosion
|
|
378
|
+
**Prevention**: Cost-awareness rules, prefer cheaper tools first, track usage
|
|
379
|
+
|
|
380
|
+
### ❌ Hook Failures Blocking Progress
|
|
381
|
+
**Prevention**: Hooks exit gracefully, agent continues if hooks fail
|
|
382
|
+
|
|
383
|
+
---
|
|
384
|
+
|
|
385
|
+
## Integration with Other Skills
|
|
386
|
+
|
|
387
|
+
### Works with:
|
|
388
|
+
- **mcp-mastery**: Coordinates MCP selection
|
|
389
|
+
- **tool-selection**: Optimizes tool choices
|
|
390
|
+
- **parallel-exploration**: Launches subagents efficiently
|
|
391
|
+
|
|
392
|
+
### Coordinates with:
|
|
393
|
+
- **Rules**: Enforces tool-auto-selection, parallel-exploration-auto, context tiers
|
|
394
|
+
- **Hooks**: Triggers validation pipeline
|
|
395
|
+
- **MCPs**: Chains multiple servers for complex workflows
|
|
396
|
+
|
|
397
|
+
---
|
|
398
|
+
|
|
399
|
+
**Note**: This skill activates automatically in debug mode. No manual intervention needed. All optimizations applied transparently to maximize efficiency.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Root Cause Debugging & Troubleshooting
|
|
2
|
+
|
|
3
|
+
## 4-Step Systematic Debugging Protocol
|
|
4
|
+
1. **Reproduce & Isolate:** Recreate the exact failure case with minimal reproduction code or single targeted test.
|
|
5
|
+
2. **Inspect & Trace:** Check actual runtime logs, stack traces, and variable states instead of guessing.
|
|
6
|
+
3. **Hypothesize & Form Minimal Fix:** Identify the root mechanism causing the breakdown. Form the smallest possible diff that completely fixes the issue.
|
|
7
|
+
4. **Regression Prevention:** Add a targeted regression test confirming the bug is dead and adjacent modules remain intact.
|
|
8
|
+
|
|
9
|
+
## Anti-Patterns
|
|
10
|
+
- ❌ Do NOT randomly wrap code in `try-catch` blocks without handling or logging errors.
|
|
11
|
+
- ❌ Do NOT suppress TypeScript compiler errors with `@ts-ignore` or `as any`.
|
|
12
|
+
- ❌ Do NOT write sprawling test fixtures when a focused unit test suffices.
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: golang-guide
|
|
3
|
+
description: Comprehensive architecture, concurrency patterns, error handling, clean architecture, and performance guidelines for production Golang backends.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Golang Production Backend Engineering Guide
|
|
7
|
+
|
|
8
|
+
## Quick Start
|
|
9
|
+
When writing or reviewing Go backend services:
|
|
10
|
+
1. **Explicit Error Wrapping**: Always wrap errors with context: `fmt.Errorf("orderservice.CreateOrder: %w", err)`.
|
|
11
|
+
2. **Context Propagation**: Pass `ctx context.Context` as the first argument in every I/O-bound function.
|
|
12
|
+
3. **No Goroutine Leaks**: Every spawned goroutine must have a deterministic termination condition via context or channel close.
|
|
13
|
+
4. **Interface Segregation**: Accept interfaces, return structs. Define interfaces at consumption boundaries.
|
|
14
|
+
5. **Zero Allocations in Hot Paths**: Pre-allocate slice capacity `make([]T, 0, expectedCap)` and reuse buffers via `sync.Pool`.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 1. Project Architecture (Standard Go Layout)
|
|
19
|
+
|
|
20
|
+
Follow the idiomatic Go enterprise layout:
|
|
21
|
+
|
|
22
|
+
```text
|
|
23
|
+
my-go-service/
|
|
24
|
+
├── cmd/
|
|
25
|
+
│ └── api/
|
|
26
|
+
│ └── main.go # Application bootstrap & dependency wiring
|
|
27
|
+
├── internal/ # Private application code (enforced by Go compiler)
|
|
28
|
+
│ ├── domain/ # Core business models & repository interfaces (Pure Go, 0 external deps)
|
|
29
|
+
│ │ ├── order.go
|
|
30
|
+
│ │ └── customer.go
|
|
31
|
+
│ ├── usecase/ # Application business logic orchestrators
|
|
32
|
+
│ │ └── order_service.go
|
|
33
|
+
│ ├── repository/ # Database implementations (Postgres, GORM, Redis)
|
|
34
|
+
│ │ ├── postgres_order.go
|
|
35
|
+
│ │ └── redis_cache.go
|
|
36
|
+
│ └── transport/ # Inbound adapters (HTTP handlers, gRPC servers, Kafka consumers)
|
|
37
|
+
│ ├── http/
|
|
38
|
+
│ │ ├── handler.go
|
|
39
|
+
│ │ └── router.go
|
|
40
|
+
│ └── grpc/
|
|
41
|
+
├── pkg/ # Public reusable utilities (logging, metrics, crypto)
|
|
42
|
+
├── go.mod
|
|
43
|
+
└── go.sum
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 2. Idiomatic Error Handling
|
|
49
|
+
|
|
50
|
+
Go does not use exceptions. Errors are normal values and must be explicitly handled.
|
|
51
|
+
|
|
52
|
+
### Error Wrapping & Inspection
|
|
53
|
+
```go
|
|
54
|
+
package service
|
|
55
|
+
|
|
56
|
+
import (
|
|
57
|
+
"errors"
|
|
58
|
+
"fmt"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
var (
|
|
62
|
+
ErrNotFound = errors.New("record not found")
|
|
63
|
+
ErrUnauthorized = errors.New("unauthorized operation")
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
func (s *OrderService) GetOrder(ctx context.Context, id string) (*domain.Order, error) {
|
|
67
|
+
order, err := s.repo.FindByID(ctx, id)
|
|
68
|
+
if err != nil {
|
|
69
|
+
if errors.Is(err, repository.ErrNotFound) {
|
|
70
|
+
// Map internal DB error to domain error with wrapping
|
|
71
|
+
return nil, fmt.Errorf("%w: order id %s", ErrNotFound, id)
|
|
72
|
+
}
|
|
73
|
+
// Preserve stack context without losing root cause
|
|
74
|
+
return nil, fmt.Errorf("failed fetching order from repository: %w", err)
|
|
75
|
+
}
|
|
76
|
+
return order, nil
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## 3. Concurrency Patterns & Safe Goroutines
|
|
83
|
+
|
|
84
|
+
### Worker Pool Pattern (Rate-Limited Parallel Execution)
|
|
85
|
+
Prevent spawning millions of goroutines that crash memory:
|
|
86
|
+
|
|
87
|
+
```go
|
|
88
|
+
func ProcessJobs(ctx context.Context, jobs []Job, concurrency int) error {
|
|
89
|
+
jobsChan := make(chan Job, len(jobs))
|
|
90
|
+
errGroup, ctx := errgroup.WithContext(ctx)
|
|
91
|
+
|
|
92
|
+
// Feed jobs
|
|
93
|
+
for _, job := range jobs {
|
|
94
|
+
jobsChan <- job
|
|
95
|
+
}
|
|
96
|
+
close(jobsChan)
|
|
97
|
+
|
|
98
|
+
// Spawn fixed worker pool
|
|
99
|
+
for i := 0; i < concurrency; i++ {
|
|
100
|
+
errGroup.Go(func() error {
|
|
101
|
+
for {
|
|
102
|
+
select {
|
|
103
|
+
case <-ctx.Done():
|
|
104
|
+
return ctx.Err()
|
|
105
|
+
case job, ok := <-jobsChan:
|
|
106
|
+
if !ok {
|
|
107
|
+
return nil // Channel drained
|
|
108
|
+
}
|
|
109
|
+
if err := job.Execute(ctx); err != nil {
|
|
110
|
+
return fmt.Errorf("job %s failed: %w", job.ID, err)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return errGroup.Wait()
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Mutex Safety & Avoiding Data Races
|
|
122
|
+
```go
|
|
123
|
+
type SafeCache struct {
|
|
124
|
+
mu sync.RWMutex
|
|
125
|
+
store map[string]string
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
func (c *SafeCache) Get(key string) (string, bool) {
|
|
129
|
+
c.mu.RLock()
|
|
130
|
+
defer c.mu.RUnlock()
|
|
131
|
+
val, ok := c.store[key]
|
|
132
|
+
return val, ok
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
func (c *SafeCache) Set(key, value string) {
|
|
136
|
+
c.mu.Lock()
|
|
137
|
+
defer c.mu.Unlock()
|
|
138
|
+
c.store[key] = value
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## 4. Database Interactions (Clean Context-Aware SQL)
|
|
145
|
+
|
|
146
|
+
Always use transactions with timeouts:
|
|
147
|
+
|
|
148
|
+
```go
|
|
149
|
+
func (r *PostgresOrderRepo) DeductBalance(ctx context.Context, accountID int64, amount float64) error {
|
|
150
|
+
// 1. Enforce operation timeout
|
|
151
|
+
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
|
152
|
+
defer cancel()
|
|
153
|
+
|
|
154
|
+
tx, err := r.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
|
155
|
+
if err != nil {
|
|
156
|
+
return fmt.Errorf("failed starting tx: %w", err)
|
|
157
|
+
}
|
|
158
|
+
defer tx.Rollback()
|
|
159
|
+
|
|
160
|
+
// 2. Atomic mutation
|
|
161
|
+
query := `UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1`
|
|
162
|
+
res, err := tx.ExecContext(ctx, query, amount, accountID)
|
|
163
|
+
if err != nil {
|
|
164
|
+
return fmt.Errorf("db update error: %w", err)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
rows, err := res.RowsAffected()
|
|
168
|
+
if err != nil {
|
|
169
|
+
return err
|
|
170
|
+
}
|
|
171
|
+
if rows == 0 {
|
|
172
|
+
return errors.New("insufficient balance or account does not exist")
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return tx.Commit()
|
|
176
|
+
}
|
|
177
|
+
```
|