claudify-agent 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.claude/QUICK-REFERENCE.md +213 -0
  2. package/.claude/cost-dashboard.md +162 -0
  3. package/.claude/docs/COST-OPTIMIZATION.md +403 -0
  4. package/.claude/docs/MCP-INTEGRATION-GUIDE.md +348 -0
  5. package/.claude/docs/PLAN-MODE-OPTIMIZATION.md +836 -0
  6. package/.claude/hooks/auto-learning-review.ts +195 -0
  7. package/.claude/hooks/auto-lint-fix.ts +104 -0
  8. package/.claude/hooks/auto-security-review.ts +354 -0
  9. package/.claude/hooks/auto-validate.ts +348 -0
  10. package/.claude/hooks/plan-quality-tracker.ts +719 -0
  11. package/.claude/rules/anti-patterns.md +22 -0
  12. package/.claude/rules/context-tier-1.md +41 -0
  13. package/.claude/rules/context-tier-2.md +285 -0
  14. package/.claude/rules/general.md +25 -0
  15. package/.claude/rules/mcp-auto-use.md +46 -0
  16. package/.claude/rules/parallel-exploration-auto.md +31 -0
  17. package/.claude/rules/plan-mode-execution.md +289 -0
  18. package/.claude/rules/plan-mode-research.md +34 -0
  19. package/.claude/rules/plan-mode-structure.md +166 -0
  20. package/.claude/rules/plan-mode-validation.md +130 -0
  21. package/.claude/rules/security-critical.md +19 -0
  22. package/.claude/rules/tool-auto-selection.md +45 -0
  23. package/.claude/rules/tool-strategy.md +22 -0
  24. package/.claude/scripts/auto-validate.js +69 -0
  25. package/.claude/scripts/security-scan.js +45 -0
  26. package/.claude/security-dashboard.md +142 -0
  27. package/.claude/skills/backend-concurrency/SKILL.md +203 -0
  28. package/.claude/skills/debug-optimizer/SKILL.md +399 -0
  29. package/.claude/skills/debug-optimizer.md +12 -0
  30. package/.claude/skills/golang-guide/SKILL.md +177 -0
  31. package/.claude/skills/learning-loop/SKILL.md +308 -0
  32. package/.claude/skills/mcp-mastery/SKILL.md +214 -0
  33. package/.claude/skills/nestjs-guide/SKILL.md +197 -0
  34. package/.claude/skills/nextjs-guide/SKILL.md +687 -0
  35. package/.claude/skills/nextjs.md +13 -0
  36. package/.claude/skills/parallel-exploration/SKILL.md +193 -0
  37. package/.claude/skills/plan-mode-mastery/SKILL.md +263 -0
  38. package/.claude/skills/python-guide/SKILL.md +822 -0
  39. package/.claude/skills/react-guide/SKILL.md +762 -0
  40. package/.claude/skills/react.md +12 -0
  41. package/.claude/skills/security.md +18 -0
  42. package/.claude/skills/solidity-guide/SKILL.md +32 -0
  43. package/.claude/skills/tool-selection/SKILL.md +428 -0
  44. package/.claude/skills/vite-guide/SKILL.md +445 -0
  45. package/CLAUDE.md +49 -0
  46. package/README.md +65 -2
  47. package/bin/cli.js +50 -0
  48. package/package.json +44 -4
@@ -0,0 +1,308 @@
1
+ # SKILL.md: Learning Loop
2
+
3
+ ## Description
4
+ Analyzes plan metrics to identify patterns, detect repeated mistakes, and suggest continuous improvements based on historical execution data.
5
+
6
+ ## When to Use
7
+ - Weekly review of plan performance
8
+ - After detecting repeated failures
9
+ - When plan accuracy drops below threshold
10
+ - Proactive optimization of workflows
11
+
12
+ ## Capabilities
13
+ - Pattern recognition from metrics
14
+ - Anti-pattern detection
15
+ - Repeated mistake identification
16
+ - Trend analysis
17
+ - Improvement recommendations
18
+ - Rule update suggestions
19
+
20
+ ## Commands
21
+ /learning-loop-analyze: Full pattern analysis
22
+ /learning-loop-weekly: Weekly performance review
23
+ /learning-loop-suggest: Generate improvement suggestions
24
+ /learning-loop-patterns: Show detected anti-patterns
25
+
26
+ ## Workflows
27
+
28
+ ### Weekly Analysis Workflow
29
+
30
+ 1. **Load Metrics** (30s)
31
+ ```bash
32
+ Read: .cursor/plan-metrics.json
33
+ ```
34
+ - Last 10-20 plan executions
35
+ - Extract key metrics
36
+
37
+ 2. **Pattern Detection** (60s)
38
+ - Run anti-pattern detection rules
39
+ - Identify repeated mistakes
40
+ - Calculate trends
41
+
42
+ 3. **Analysis Report** (30s)
43
+ ```markdown
44
+ ## Weekly Learning Report
45
+
46
+ ### Performance Summary
47
+ - Avg Accuracy: X% (trend: ↑/↓/→)
48
+ - Avg Iterations: X (target: <2)
49
+ - Tool Efficiency: X% (target: >70%)
50
+
51
+ ### Detected Anti-Patterns
52
+ 1. [SEVERITY] Pattern name
53
+ - Suggestion: ...
54
+
55
+ ### Repeated Mistakes
56
+ - Mistake 1 (count: X)
57
+ - Mistake 2 (count: X)
58
+
59
+ ### Top 3 Improvements
60
+ 1. [Action item]
61
+ 2. [Action item]
62
+ 3. [Action item]
63
+
64
+ ### Rule Update Suggestions
65
+ - Suggest updating: .cursor/rules/[file]
66
+ - Reason: [pattern detected]
67
+ ```
68
+
69
+ 4. **Action Items** (30s)
70
+ - Prioritize top 3 improvements
71
+ - Create tasks for rule updates
72
+ - Schedule follow-up review
73
+
74
+ ### Anti-Pattern Detection
75
+
76
+ The skill detects these anti-patterns automatically:
77
+
78
+ 1. **Over-Engineering** (High)
79
+ - Using expensive tools when cheap alternatives work
80
+ - Detection: avg tool efficiency < 50% over 3 plans
81
+ - Fix: Follow tool escalation protocol
82
+
83
+ 2. **Planning Without Research** (Critical)
84
+ - Creating plans without SemanticSearch
85
+ - Detection: No SemanticSearch in last 3 plans
86
+ - Fix: Always research before planning
87
+
88
+ 3. **Repeated Execution Failures** (Critical)
89
+ - Multiple consecutive low-accuracy plans
90
+ - Detection: 2+ plans with <60% accuracy
91
+ - Fix: Improve validation process
92
+
93
+ 4. **MCP Overuse** (Medium)
94
+ - Using MCP tools unnecessarily
95
+ - Detection: High MCP usage + low accuracy
96
+ - Fix: Use MCP only when essential
97
+
98
+ 5. **Skipping Validation** (High)
99
+ - Not running ReadLints/tests
100
+ - Detection: No validation tools in 3 plans
101
+ - Fix: Auto-validate after changes
102
+
103
+ 6. **Context Bloat** (Medium)
104
+ - Loading too much context
105
+ - Detection: Low efficiency + high iterations
106
+ - Fix: Apply tiered injection, minimalism
107
+
108
+ ### Trend Analysis
109
+
110
+ Analyzes performance trends:
111
+
112
+ ```typescript
113
+ if (secondHalfAvg > firstHalfAvg + 5) {
114
+ trend = "improving";
115
+ // Reinforce what's working
116
+ } else if (secondHalfAvg < firstHalfAvg - 5) {
117
+ trend = "declining";
118
+ // Investigate root causes
119
+ } else {
120
+ trend = "stable";
121
+ // Look for optimization opportunities
122
+ }
123
+ ```
124
+
125
+ ## Examples
126
+
127
+ ### Example 1: Weekly Review
128
+
129
+ User: "/learning-loop-weekly"
130
+
131
+ Agent analyzes last 10 plans:
132
+
133
+ ```markdown
134
+ ## Weekly Learning Report (Mar 23-30, 2026)
135
+
136
+ ### Performance Summary
137
+ - Avg Accuracy: 82.5% (↑ +5.2% from last week)
138
+ - Avg Iterations: 1.8 (↓ -0.5, improving)
139
+ - Tool Efficiency: 75.0% (→ stable)
140
+ - Avg Parallel Subagents: 2.3
141
+
142
+ ### Wins This Week
143
+ ✅ Accuracy improved above 80% threshold
144
+ ✅ Iteration count decreasing
145
+ ✅ MCP usage correlated with success
146
+
147
+ ### Detected Anti-Patterns
148
+ 1. [MEDIUM] MCP Overuse (2 occurrences)
149
+ - Suggestion: Use MCP tools only when essential
150
+
151
+ ### Repeated Mistakes
152
+ - None detected this week 🎉
153
+
154
+ ### Top 3 Improvements
155
+ 1. Continue current research practices
156
+ 2. Reduce MCP usage for simple tasks
157
+ 3. Document successful patterns
158
+
159
+ ### Rule Updates
160
+ No updates needed this week
161
+ ```
162
+
163
+ ### Example 2: Pattern Detection
164
+
165
+ User: "/learning-loop-patterns"
166
+
167
+ Agent detects patterns:
168
+
169
+ ```markdown
170
+ ## Detected Anti-Patterns
171
+
172
+ ### 1. [CRITICAL] Planning Without Research
173
+ **Occurrences**: 3 times in last 5 plans
174
+ **Impact**: Avg accuracy 58% (vs 82% when researched)
175
+ **Suggestion**: Always use SemanticSearch before planning
176
+
177
+ ### 2. [HIGH] Skipping Validation
178
+ **Occurrences**: 4 times in last 5 plans
179
+ **Impact**: 75% of unvalidated plans had lints
180
+ **Suggestion**: Enable auto-validate hook
181
+
182
+ ### Recommended Actions
183
+ 1. Add rule: "Always research before planning"
184
+ 2. Enable auto-validate in hooks.config.json
185
+ 3. Create checklist for plan creation
186
+ ```
187
+
188
+ ### Example 3: Improvement Suggestions
189
+
190
+ User: "/learning-loop-suggest"
191
+
192
+ Agent generates suggestions:
193
+
194
+ ```markdown
195
+ ## Improvement Suggestions
196
+
197
+ ### Immediate (This Week)
198
+ 1. **Add pre-plan research step**
199
+ - Time cost: +2 min per plan
200
+ - Benefit: +20% accuracy improvement
201
+
202
+ 2. **Enable automatic validation**
203
+ - Already configured, just use it
204
+ - Benefit: Catch 100% of lint issues
205
+
206
+ 3. **Reduce MCP tool usage**
207
+ - Current: 4.2 MCP tools/plan
208
+ - Target: 2.0 MCP tools/plan
209
+ - Savings: ~30% token cost
210
+
211
+ ### Medium-term (This Month)
212
+ 1. Create validation checklist
213
+ 2. Document successful patterns
214
+ 3. Update anti-pattern detection rules
215
+
216
+ ### Long-term (This Quarter)
217
+ 1. Integrate with CI/CD metrics
218
+ 2. A/B test different workflows
219
+ 3. Build pattern recognition dashboard
220
+ ```
221
+
222
+ ## Best Practices
223
+
224
+ ### 1. Review Weekly
225
+ - Schedule fixed time (e.g., Friday 4pm)
226
+ - Review last 10 plans
227
+ - Identify top 3 improvements
228
+ - Update rules if needed
229
+
230
+ ### 2. Act on Patterns
231
+ - Don't just detect - fix
232
+ - Prioritize critical patterns first
233
+ - Track improvement over time
234
+
235
+ ### 3. Keep Rules Minimal
236
+ - Only add rules for repeated patterns
237
+ - Keep rules under 20 lines
238
+ - Use references over content
239
+
240
+ ### 4. Measure Impact
241
+ - Before/after comparisons
242
+ - Track metric changes
243
+ - Adjust based on data
244
+
245
+ ## Anti-Patterns
246
+
247
+ ### ❌ Ignoring Detected Patterns
248
+ Bad: Detect patterns but don't act
249
+ Good: Create action items, track fixes
250
+
251
+ ### ❌ Over-Analyzing
252
+ Bad: Analyze every single plan
253
+ Good: Weekly batch analysis
254
+
255
+ ### ❌ Too Many Rules
256
+ Bad: Add rule for every mistake
257
+ Good: Only for repeated patterns (3+ occurrences)
258
+
259
+ ### ❌ No Follow-up
260
+ Bad: Generate suggestions, forget them
261
+ Good: Schedule follow-up review
262
+
263
+ ## Troubleshooting
264
+
265
+ ### Not Enough Data
266
+ **Problem**: Less than 3 plans to analyze
267
+
268
+ **Solution**:
269
+ - Wait for more data
270
+ - Run analysis after 10+ plans
271
+ - Use qualitative feedback initially
272
+
273
+ ### False Positive Patterns
274
+ **Problem**: Pattern detected but not actually an issue
275
+
276
+ **Solution**:
277
+ - Adjust detection thresholds
278
+ - Add exception rules
279
+ - Manual review before acting
280
+
281
+ ### No Patterns Detected
282
+ **Problem**: Analysis shows no patterns
283
+
284
+ **Solution**:
285
+ - Check if thresholds too strict
286
+ - Look for subtle patterns
287
+ - Consider qualitative feedback
288
+
289
+ ## Metrics Reference
290
+
291
+ ### Key Metrics Tracked
292
+ - `plan_accuracy`: % of plan followed correctly
293
+ - `iteration_count`: Number of /grind loops
294
+ - `tool_efficiency`: Cost-weighted tool score
295
+ - `parallel_subagents`: Number of parallel explorations
296
+ - `mcp_usage`: MCP server utilization
297
+ - `cost_estimate`: Estimated token consumption
298
+
299
+ ### Thresholds
300
+ - **Excellent**: Accuracy >90%, Iterations <2, Efficiency >80%
301
+ - **Good**: Accuracy 70-90%, Iterations 2-3, Efficiency 60-80%
302
+ - **Needs Work**: Accuracy <70%, Iterations >3, Efficiency <60%
303
+
304
+ ## Related Documentation
305
+ - `AGENT-INSTRUCTION-BEST-PRACTICES.md` - Core research
306
+ - `.cursor/hooks.config.json` - Configuration
307
+ - `.cursor/plan-metrics.json` - Historical data
308
+ - `.cursor/docs/PLAN-MODE-OPTIMIZATION.md` - Plan mode guide
@@ -0,0 +1,214 @@
1
+ # SKILL.md: MCP Server Mastery
2
+
3
+ ## Description
4
+ Automatic selection and optimal use of available MCP servers for maximum efficiency. Activates automatically based on task analysis in debug mode.
5
+
6
+ ## When to Use (Automatic Triggers)
7
+ **This skill activates AUTOMATICALLY when**:
8
+ - Any task involving browser automation
9
+ - GitHub operations (PRs, issues)
10
+ - Code quality checks
11
+ - Library/framework documentation needs
12
+ - Performance optimization tasks
13
+ - E2E testing requirements
14
+
15
+ **No manual activation needed** - MCP selection happens automatically based on:
16
+ - User request keywords
17
+ - File patterns being modified
18
+ - Task complexity and type
19
+ - Error patterns detected
20
+
21
+ ## Available MCP Servers
22
+
23
+ ### 1. cursor-ide-browser
24
+ **Capabilities**:
25
+ - Browser automation (navigate, click, fill, scroll)
26
+ - Visual verification (screenshots, snapshots)
27
+ - Performance profiling (CPU, timing)
28
+ - Console/network inspection
29
+
30
+ **Automatic Triggers**:
31
+ - User mentions: "UI", "visual", "frontend", "browser test"
32
+ - Changes to: `components/`, `app/`, `pages/`
33
+ - Task involves: Design matching, E2E testing
34
+
35
+ **Optimal Usage Pattern**:
36
+ ```
37
+ 1. browser_snapshot (take_screenshot: true)
38
+ 2. Identify refs from snapshot
39
+ 3. Interact via refs (browser_click, browser_fill)
40
+ 4. browser_take_screenshot (verify)
41
+ 5. Use performance profiling if optimization mentioned
42
+ ```
43
+
44
+ **Cost**: High → Use sparingly, only when visual verification needed
45
+
46
+ ### 2. user-github
47
+ **Capabilities**:
48
+ - Issue/PR management
49
+ - Repository operations
50
+ - Code review automation
51
+ - Branch management
52
+
53
+ **Automatic Triggers**:
54
+ - User mentions: "PR", "issue", "branch", "commit"
55
+ - Commands: `/pr`, `/fix-issue`, `/review`
56
+
57
+ **Optimal Usage Pattern**:
58
+ ```
59
+ 1. Fetch issue/PR details
60
+ 2. Implement changes
61
+ 3. Run tests/lints
62
+ 4. Create/update PR automatically
63
+ 5. Link issues
64
+ ```
65
+
66
+ **Cost**: Moderate → Use for all git operations
67
+
68
+ ### 3. user-ESLint
69
+ **Capabilities**:
70
+ - Automatic linting
71
+ - Auto-fix issues
72
+ - Quality reporting
73
+
74
+ **Automatic Triggers**:
75
+ - After EVERY substantive code change
76
+ - User mentions: "lint", "quality", "errors"
77
+
78
+ **Optimal Usage Pattern**:
79
+ ```
80
+ 1. Run ESLint on changed files (automatic)
81
+ 2. Apply auto-fixes
82
+ 3. Report remaining issues
83
+ 4. Fix before committing
84
+ ```
85
+
86
+ **Cost**: Low → Run automatically after all edits
87
+
88
+ ### 4. user-context7
89
+ **Capabilities**:
90
+ - Fetch current library docs
91
+ - API syntax verification
92
+ - Setup/configuration guides
93
+ - Version-specific information
94
+
95
+ **Automatic Triggers**:
96
+ - Questions about libraries/frameworks
97
+ - Setup/configuration needed
98
+ - API syntax uncertain
99
+
100
+ **Optimal Usage Pattern**:
101
+ ```
102
+ 1. Fetch docs BEFORE implementing
103
+ 2. Verify current best practices
104
+ 3. Apply to implementation
105
+ 4. Cite doc source
106
+ ```
107
+
108
+ **Cost**: Low → Fetch proactively for library work
109
+
110
+ ### 5. user-chrome-devtools
111
+ **Capabilities**:
112
+ - Lighthouse audits
113
+ - Performance metrics
114
+ - Accessibility checks
115
+
116
+ **Automatic Triggers**:
117
+ - User mentions: "performance", "lighthouse", "accessibility"
118
+ - Optimization tasks
119
+
120
+ **Cost**: Moderate → Use for performance audits
121
+
122
+ ### 6. user-playwright / user-selenium
123
+ **Capabilities**:
124
+ - Cross-browser testing
125
+ - E2E automation
126
+ - Accessibility testing
127
+
128
+ **Automatic Triggers**:
129
+ - E2E testing needed
130
+ - Cross-browser verification
131
+ - Accessibility compliance
132
+
133
+ **Cost**: High → Use for comprehensive testing
134
+
135
+ ## MCP Selection Decision Tree
136
+
137
+ ```
138
+ Task involves browser/UI?
139
+ ├─ Yes → cursor-ide-browser
140
+ │ └─ Performance audit? → user-chrome-devtools
141
+ │ └─ E2E tests? → user-playwright
142
+ └─ No
143
+ ├─ GitHub operations? → user-github
144
+ ├─ Code quality? → user-ESLint (automatic)
145
+ ├─ Library docs? → user-context7
146
+ └─ None → Standard tools only
147
+ ```
148
+
149
+ ## Cost Optimization Rules (Automatically Enforced)
150
+
151
+ 1. **Always run user-ESLint** after code changes (low cost, high value)
152
+ 2. **Fetch user-context7** before library implementation (prevents errors)
153
+ 3. **Use cursor-ide-browser** only when visual verification essential
154
+ 4. **Prefer user-github** over manual git commands (automation)
155
+ 5. **Run performance audits** only when performance mentioned
156
+ 6. **Start with Tier 1 MCPs** (cheap) before Tier 2-3 (expensive)
157
+ 7. **Chain MCPs automatically** for complex workflows (see examples)
158
+ 8. **Track MCP usage** in .cursor/mcp-usage-log.md for optimization
159
+
160
+ ## Debug Mode Auto-Triggers
161
+
162
+ **In debug mode, these triggers are AUTOMATICALLY monitored**:
163
+
164
+ ```
165
+ File Change Detection:
166
+ - components/**, app/**, pages/** → cursor-ide-browser
167
+ - __tests__/**, e2e/** → user-playwright
168
+ - *.ts, *.tsx → user-ESLint (after changes)
169
+
170
+ Keyword Detection:
171
+ - "PR", "issue", "branch" → user-github
172
+ - "lint", "quality" → user-ESLint
173
+ - "how to", "docs", "API" → user-context7
174
+ - "performance", "optimize" → user-chrome-devtools + cursor-ide-browser
175
+
176
+ Error Detection:
177
+ - ESLint errors → user-ESLint (auto-fix mode)
178
+ - Test failures → user-playwright (debug mode)
179
+ - Build errors → user-context7 (fetch build docs)
180
+ ```
181
+
182
+ ## Examples
183
+
184
+ ### Example 1: UI Feature Development
185
+
186
+ User: "Add dark mode toggle to settings"
187
+
188
+ MCP Sequence:
189
+ 1. **user-context7**: Fetch Tailwind dark mode docs
190
+ 2. **cursor-ide-browser**:
191
+ - Navigate to settings page
192
+ - Verify toggle renders correctly
193
+ - Screenshot for confirmation
194
+ 3. **user-ESLint**: Check code quality (automatic)
195
+
196
+ ### Example 2: Bug Fix Workflow
197
+
198
+ User: "Fix checkout issue #456"
199
+
200
+ MCP Sequence:
201
+ 1. **user-github**: Fetch issue #456 details
202
+ 2. **user-context7**: Check payment library docs
203
+ 3. **user-ESLint**: Verify fix quality (automatic)
204
+ 4. **user-github**: Create PR linking issue
205
+
206
+ ### Example 3: Performance Optimization
207
+
208
+ User: "Optimize dashboard loading"
209
+
210
+ MCP Sequence:
211
+ 1. **user-chrome-devtools**: Run Lighthouse audit
212
+ 2. **cursor-ide-browser**: Profile CPU usage
213
+ 3. **user-context7**: Fetch React optimization docs
214
+ 4. **user-chrome-devtools**: Re-run audit to verify improvement
@@ -0,0 +1,197 @@
1
+ ---
2
+ name: nestjs-guide
3
+ description: Comprehensive enterprise guide for NestJS backends covering modular architecture, TypeORM/Prisma transactions, dependency injection, validation pipes, guards, interceptors, and error handling.
4
+ ---
5
+
6
+ # NestJS Enterprise Backend Engineering Guide
7
+
8
+ ## Quick Start
9
+ When architecting NestJS microservices and APIs:
10
+ 1. **Modules as Domain Boundaries**: Separate features cleanly (`UsersModule`, `PaymentsModule`). Never dump everything into `AppModule`.
11
+ 2. **DTO Validation**: Enforce strict `ValidationPipe` with `whitelist: true` and `forbidNonWhitelisted: true`.
12
+ 3. **Stateless Services**: Default to `Scope.DEFAULT` (Singleton). Never store user request state inside service instance properties.
13
+ 4. **Transactions via QueryRunner / $transaction**: Always handle atomic operations explicitly. Never leave transactions dangling without rollback.
14
+ 5. **Thin Controllers, Rich Services**: Controllers handle HTTP protocol concerns only. Business logic belongs strictly in Services.
15
+
16
+ ---
17
+
18
+ ## 1. Enterprise Module Architecture
19
+
20
+ ```text
21
+ src/
22
+ ├── common/ # Cross-cutting concerns
23
+ │ ├── decorators/ # Custom parameter decorators (@CurrentUser(), @Public())
24
+ │ ├── filters/ # Global HttpExceptionFilter
25
+ │ ├── guards/ # AuthGuard, RolesGuard
26
+ │ ├── interceptors/ # LoggingInterceptor, TransformInterceptor
27
+ │ └── pipes/ # Custom validation/parse pipes
28
+ ├── modules/
29
+ │ ├── auth/
30
+ │ │ ├── dto/
31
+ │ │ ├── guards/
32
+ │ │ ├── auth.controller.ts
33
+ │ │ ├── auth.service.ts
34
+ │ │ └── auth.module.ts
35
+ │ └── orders/
36
+ │ ├── dto/
37
+ │ │ ├── create-order.dto.ts
38
+ │ │ └── order-response.dto.ts
39
+ │ ├── entities/
40
+ │ │ └── order.entity.ts
41
+ │ ├── orders.controller.ts
42
+ │ ├── orders.service.ts
43
+ │ └── orders.module.ts
44
+ ├── config/ # Configuration namespaces via @nestjs/config
45
+ ├── app.module.ts
46
+ └── main.go / main.ts
47
+ ```
48
+
49
+ ---
50
+
51
+ ## 2. Robust Input Validation (Zero-Trust Boundaries)
52
+
53
+ ```typescript
54
+ // src/modules/orders/dto/create-order.dto.ts
55
+ import { IsUUID, IsNumber, Min, IsArray, ValidateNested, ArrayMinSize } from 'class-validator';
56
+ import { Type } from 'class-transformer';
57
+
58
+ export class OrderItemDto {
59
+ @IsUUID('4')
60
+ productId: string;
61
+
62
+ @IsNumber({ maxDecimalPlaces: 0 })
63
+ @Min(1)
64
+ quantity: number;
65
+
66
+ @IsNumber({ maxDecimalPlaces: 2 })
67
+ @Min(0)
68
+ unitPrice: number;
69
+ }
70
+
71
+ export class CreateOrderDto {
72
+ @IsUUID('4')
73
+ customerId: string;
74
+
75
+ @IsArray()
76
+ @ArrayMinSize(1)
77
+ @ValidateNested({ each: true })
78
+ @Type(() => OrderItemDto)
79
+ items: OrderItemDto[];
80
+ }
81
+ ```
82
+
83
+ ### Main.ts Bootstrap Guard
84
+ ```typescript
85
+ import { NestFactory } from '@nestjs/core';
86
+ import { ValidationPipe, Logger } from '@nestjs/common';
87
+ import { AppModule } from './app.module';
88
+
89
+ async function bootstrap() {
90
+ const app = await NestFactory.create(AppModule);
91
+
92
+ app.useGlobalPipes(
93
+ new ValidationPipe({
94
+ whitelist: true, // Strips unexpected payload keys
95
+ forbidNonWhitelisted: true, // Throws 400 if malicious unexpected fields are sent
96
+ transform: true, // Automatically maps incoming JSON into TS DTO instances
97
+ transformOptions: { enableImplicitConversion: true },
98
+ }),
99
+ );
100
+
101
+ await app.listen(process.env.PORT ?? 3000);
102
+ Logger.log(`Application is running on: ${await app.getUrl()}`);
103
+ }
104
+ bootstrap();
105
+ ```
106
+
107
+ ---
108
+
109
+ ## 3. Database Transactions with Pessimistic Locking (TypeORM)
110
+
111
+ ```typescript
112
+ @Injectable()
113
+ export class OrdersService {
114
+ constructor(private readonly dataSource: DataSource) {}
115
+
116
+ async processOrderPayment(orderId: string, amount: number): Promise<void> {
117
+ const queryRunner = this.dataSource.createQueryRunner();
118
+ await queryRunner.connect();
119
+ await queryRunner.startTransaction();
120
+
121
+ try {
122
+ // 1. Lock the order row exclusively to prevent concurrent double-payments
123
+ const order = await queryRunner.manager.findOne(OrderEntity, {
124
+ where: { id: orderId },
125
+ lock: { mode: 'pessimistic_write' },
126
+ });
127
+
128
+ if (!order) {
129
+ throw new NotFoundException(`Order with ID ${orderId} not found`);
130
+ }
131
+
132
+ if (order.status === OrderStatus.PAID) {
133
+ throw new ConflictException(`Order ${orderId} has already been settled`);
134
+ }
135
+
136
+ // 2. Perform state changes
137
+ order.status = OrderStatus.PAID;
138
+ order.paidAt = new Date();
139
+ await queryRunner.manager.save(order);
140
+
141
+ // 3. Record ledger entry
142
+ const ledgerEntry = queryRunner.manager.create(PaymentLedgerEntity, {
143
+ orderId,
144
+ amount,
145
+ status: 'SUCCESS',
146
+ });
147
+ await queryRunner.manager.save(ledgerEntry);
148
+
149
+ // 4. Commit all operations atomically
150
+ await queryRunner.commitTransaction();
151
+ } catch (err) {
152
+ // Rollback on any failure
153
+ await queryRunner.rollbackTransaction();
154
+ throw err;
155
+ } finally {
156
+ // Always release query runner back to the connection pool
157
+ await queryRunner.release();
158
+ }
159
+ }
160
+ }
161
+ ```
162
+
163
+ ---
164
+
165
+ ## 4. Global Exception Filter (Consistent Error Responses)
166
+
167
+ ```typescript
168
+ @Catch()
169
+ export class AllExceptionsFilter implements ExceptionFilter {
170
+ private readonly logger = new Logger(AllExceptionsFilter.name);
171
+
172
+ catch(exception: unknown, host: ArgumentsHost) {
173
+ const ctx = host.switchToHttp();
174
+ const response = ctx.getResponse<Response>();
175
+ const request = ctx.getRequest<Request>();
176
+
177
+ const status =
178
+ exception instanceof HttpException
179
+ ? exception.getStatus()
180
+ : HttpStatus.INTERNAL_SERVER_ERROR;
181
+
182
+ const message =
183
+ exception instanceof HttpException
184
+ ? exception.getResponse()
185
+ : 'Internal server error';
186
+
187
+ this.logger.error(`HTTP Status: ${status} Error Message: ${JSON.stringify(message)}`);
188
+
189
+ response.status(status).json({
190
+ statusCode: status,
191
+ timestamp: new Date().toISOString(),
192
+ path: request.url,
193
+ error: typeof message === 'object' ? message : { message },
194
+ });
195
+ }
196
+ }
197
+ ```