trinity-method-sdk 2.0.8 → 2.1.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 (123) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/README.md +34 -35
  3. package/dist/cli/commands/deploy/agents.js +1 -1
  4. package/dist/cli/commands/deploy/claude-setup.js +28 -35
  5. package/dist/cli/commands/deploy/index.js +1 -1
  6. package/dist/cli/commands/deploy/knowledge-base.js +1 -1
  7. package/dist/cli/commands/deploy/root-files.js +1 -1
  8. package/dist/cli/commands/deploy/sdk-install.js +1 -1
  9. package/dist/cli/commands/deploy/templates.js +29 -16
  10. package/dist/cli/commands/update/agents.js +1 -1
  11. package/dist/cli/commands/update/commands.d.ts +1 -0
  12. package/dist/cli/commands/update/commands.js +18 -45
  13. package/dist/cli/commands/update/knowledge-base.js +1 -1
  14. package/dist/cli/commands/update/templates.js +34 -12
  15. package/dist/cli/utils/deploy-linting.js +1 -1
  16. package/dist/cli/utils/template-processor.js +1 -1
  17. package/dist/templates/{claude → .claude}/EMPLOYEE-DIRECTORY.md.template +1 -1
  18. package/dist/templates/{agents → .claude/agents}/aj-team/apo-documentation-specialist.md.template +3 -3
  19. package/dist/templates/{agents → .claude/agents}/aj-team/bas-quality-gate.md.template +6 -8
  20. package/dist/templates/{agents → .claude/agents}/aj-team/bon-dependency-manager.md.template +8 -8
  21. package/dist/templates/{agents → .claude/agents}/aj-team/cap-configuration-specialist.md.template +3 -3
  22. package/dist/templates/{agents → .claude/agents}/aj-team/dra-code-reviewer.md.template +5 -7
  23. package/dist/templates/{agents → .claude/agents}/aj-team/kil-task-executor.md.template +5 -7
  24. package/dist/templates/{agents → .claude/agents}/aj-team/uro-refactoring-specialist.md.template +3 -3
  25. package/dist/templates/{agents → .claude/agents}/audit/juno-auditor.md.template +7 -2
  26. package/dist/templates/{agents → .claude/agents}/deployment/ein-cicd.md.template +3 -4
  27. package/dist/templates/{agents → .claude/agents}/deployment/ino-context.md.template +6 -3
  28. package/dist/templates/{agents → .claude/agents}/deployment/tan-structure.md.template +4 -1
  29. package/dist/templates/{agents → .claude/agents}/deployment/zen-knowledge.md.template +11 -5
  30. package/dist/templates/{agents → .claude/agents}/leadership/aj-cc.md.template +7 -2
  31. package/dist/templates/{agents → .claude/agents}/leadership/aj-maestro.md.template +4 -0
  32. package/dist/templates/{agents → .claude/agents}/leadership/aly-cto.md.template +5 -1
  33. package/dist/templates/{agents → .claude/agents}/planning/eus-decomposer.md.template +4 -0
  34. package/dist/templates/{agents → .claude/agents}/planning/mon-requirements.md.template +4 -0
  35. package/dist/templates/{agents → .claude/agents}/planning/ror-design.md.template +4 -0
  36. package/dist/templates/{agents → .claude/agents}/planning/tra-planner.md.template +6 -0
  37. package/dist/templates/{shared/claude-commands → .claude/commands/execution}/trinity-audit.md.template +6 -6
  38. package/dist/templates/{shared/claude-commands → .claude/commands/execution}/trinity-orchestrate.md.template +5 -5
  39. package/dist/templates/{shared/claude-commands → .claude/commands/infrastructure}/trinity-init.md.template +12 -11
  40. package/dist/templates/{shared/claude-commands → .claude/commands/investigation}/trinity-create-investigation.md.template +8 -2
  41. package/dist/templates/{shared/claude-commands → .claude/commands/investigation}/trinity-investigate-templates.md.template +9 -5
  42. package/dist/templates/{shared/claude-commands → .claude/commands/investigation}/trinity-plan-investigation.md.template +11 -5
  43. package/dist/templates/{shared/claude-commands → .claude/commands/maintenance}/trinity-changelog.md.template +5 -4
  44. package/dist/templates/.claude/commands/maintenance/trinity-docs-update.md.template +279 -0
  45. package/dist/templates/.claude/commands/maintenance/trinity-docs.md.template +2828 -0
  46. package/dist/templates/{shared/claude-commands → .claude/commands/maintenance}/trinity-readme.md.template +144 -35
  47. package/dist/templates/{shared/claude-commands → .claude/commands/planning}/trinity-decompose.md.template +6 -4
  48. package/dist/templates/{shared/claude-commands → .claude/commands/planning}/trinity-design.md.template +6 -4
  49. package/dist/templates/{shared/claude-commands → .claude/commands/planning}/trinity-plan.md.template +7 -5
  50. package/dist/templates/{shared/claude-commands → .claude/commands/planning}/trinity-requirements.md.template +6 -4
  51. package/dist/templates/{shared/claude-commands → .claude/commands/session}/trinity-continue.md.template +9 -3
  52. package/dist/templates/{shared/claude-commands → .claude/commands/session}/trinity-end.md.template +8 -2
  53. package/dist/templates/{shared/claude-commands → .claude/commands/session}/trinity-start.md.template +8 -2
  54. package/dist/templates/{shared/claude-commands → .claude/commands/utility}/trinity-agents.md.template +8 -2
  55. package/dist/templates/{shared/claude-commands → .claude/commands/utility}/trinity-verify.md.template +9 -4
  56. package/dist/templates/{shared/claude-commands → .claude/commands/utility}/trinity-workorder.md.template +8 -4
  57. package/dist/templates/root/TRINITY.md.template +1 -1
  58. package/dist/templates/source/base-CLAUDE.md.template +310 -310
  59. package/dist/templates/source/flutter-CLAUDE.md.template +593 -593
  60. package/dist/templates/source/nodejs-CLAUDE.md.template +531 -531
  61. package/dist/templates/source/python-CLAUDE.md.template +510 -510
  62. package/dist/templates/source/react-CLAUDE.md.template +513 -513
  63. package/dist/templates/source/rust-CLAUDE.md.template +653 -653
  64. package/dist/templates/{knowledge-base → trinity/knowledge-base}/AI-DEVELOPMENT-GUIDE.md.template +1 -1
  65. package/dist/templates/{knowledge-base → trinity/knowledge-base}/ARCHITECTURE.md.template +3 -3
  66. package/dist/templates/{knowledge-base → trinity/knowledge-base}/CODING-PRINCIPLES.md.template +1 -1
  67. package/dist/templates/{knowledge-base → trinity/knowledge-base}/DOCUMENTATION-CRITERIA.md.template +1 -1
  68. package/dist/templates/{knowledge-base → trinity/knowledge-base}/ISSUES.md.template +3 -3
  69. package/dist/templates/{knowledge-base → trinity/knowledge-base}/TESTING-PRINCIPLES.md.template +1 -1
  70. package/dist/templates/{knowledge-base → trinity/knowledge-base}/Technical-Debt.md.template +3 -3
  71. package/dist/templates/{knowledge-base → trinity/knowledge-base}/To-do.md.template +3 -3
  72. package/dist/templates/{knowledge-base → trinity/knowledge-base}/Trinity.md.template +4 -3
  73. package/dist/templates/{documentation → trinity/templates/documentation}/SUBDIRECTORY-README.md.template +1 -1
  74. package/dist/templates/trinity/templates/documentation/api-docs/README.md.template +218 -0
  75. package/dist/templates/trinity/templates/documentation/configuration/documentation-structure.md.template +71 -0
  76. package/dist/templates/trinity/templates/documentation/configuration/env-example-generator.md.template +387 -0
  77. package/dist/templates/trinity/templates/documentation/discovery/api-endpoint-scanner.md.template +343 -0
  78. package/dist/templates/trinity/templates/documentation/discovery/component-discovery.md.template +254 -0
  79. package/dist/templates/trinity/templates/documentation/discovery/env-variable-extraction.md.template +316 -0
  80. package/dist/templates/trinity/templates/documentation/discovery/framework-detection.md.template +205 -0
  81. package/dist/templates/trinity/templates/documentation/guides/api-development.md.template +375 -0
  82. package/dist/templates/trinity/templates/documentation/guides/contributing.md.template +488 -0
  83. package/dist/templates/trinity/templates/documentation/guides/deployment.md.template +565 -0
  84. package/dist/templates/trinity/templates/documentation/guides/getting-started.md.template +118 -0
  85. package/dist/templates/trinity/templates/documentation/mermaid-diagrams/api-endpoint-map.md.template +56 -0
  86. package/dist/templates/trinity/templates/documentation/mermaid-diagrams/component-hierarchy.md.template +60 -0
  87. package/dist/templates/trinity/templates/documentation/mermaid-diagrams/database-er.md.template +49 -0
  88. package/dist/templates/trinity/templates/documentation/mermaid-diagrams/mvc-flow.md.template +41 -0
  89. package/dist/templates/trinity/templates/documentation/processes/error-handling-protocol.md.template +166 -0
  90. package/dist/templates/trinity/templates/documentation/processes/fallback-mechanism.md.template +88 -0
  91. package/dist/templates/trinity/templates/documentation/reports/apo-docs-update-checklist.md.template +343 -0
  92. package/dist/templates/trinity/templates/documentation/reports/juno-docs-update-checklist.md.template +1337 -0
  93. package/dist/templates/trinity/templates/documentation/reports/juno-final-report.md.template +237 -0
  94. package/dist/templates/trinity/templates/documentation/reports/juno-internal-report.md.template +461 -0
  95. package/dist/templates/trinity/templates/documentation/validation/documentation-verification-rules.md.template +379 -0
  96. package/dist/templates/trinity/templates/documentation/validation/juno-quality-gates.md.template +282 -0
  97. package/dist/templates/{investigations → trinity/templates/investigations}/bug.md.template +2 -2
  98. package/dist/templates/{investigations → trinity/templates/investigations}/feature.md.template +2 -2
  99. package/dist/templates/{investigations → trinity/templates/investigations}/performance.md.template +2 -2
  100. package/dist/templates/{investigations → trinity/templates/investigations}/security.md.template +2 -2
  101. package/dist/templates/{investigations → trinity/templates/investigations}/technical.md.template +2 -2
  102. package/dist/templates/{work-orders → trinity/templates/work-orders}/ANALYSIS-TEMPLATE.md.template +0 -3
  103. package/dist/templates/{work-orders → trinity/templates/work-orders}/AUDIT-TEMPLATE.md.template +0 -16
  104. package/dist/templates/{work-orders → trinity/templates/work-orders}/IMPLEMENTATION-TEMPLATE.md.template +0 -16
  105. package/dist/templates/{work-orders → trinity/templates/work-orders}/INVESTIGATION-TEMPLATE.md.template +0 -15
  106. package/dist/templates/{work-orders → trinity/templates/work-orders}/PATTERN-TEMPLATE.md.template +0 -16
  107. package/dist/templates/{work-orders → trinity/templates/work-orders}/VERIFICATION-TEMPLATE.md.template +0 -16
  108. package/package.json +1 -1
  109. package/dist/templates/shared/claude-commands/trinity-docs.md.template +0 -2208
  110. /package/dist/templates/{linting → root/linting}/flutter/.pre-commit-config.yaml.template +0 -0
  111. /package/dist/templates/{linting → root/linting}/flutter/analysis_options.yaml.template +0 -0
  112. /package/dist/templates/{linting → root/linting}/nodejs/.eslintrc-commonjs.json.template +0 -0
  113. /package/dist/templates/{linting → root/linting}/nodejs/.eslintrc-esm.json.template +0 -0
  114. /package/dist/templates/{linting → root/linting}/nodejs/.eslintrc-typescript.json.template +0 -0
  115. /package/dist/templates/{linting → root/linting}/nodejs/.pre-commit-config.yaml.template +0 -0
  116. /package/dist/templates/{linting → root/linting}/nodejs/.prettierrc.json.template +0 -0
  117. /package/dist/templates/{linting → root/linting}/python/.flake8.template +0 -0
  118. /package/dist/templates/{linting → root/linting}/python/.pre-commit-config.yaml.template +0 -0
  119. /package/dist/templates/{linting → root/linting}/python/pyproject.toml.template +0 -0
  120. /package/dist/templates/{linting → root/linting}/rust/.pre-commit-config.yaml.template +0 -0
  121. /package/dist/templates/{linting → root/linting}/rust/clippy.toml.template +0 -0
  122. /package/dist/templates/{linting → root/linting}/rust/rustfmt.toml.template +0 -0
  123. /package/dist/templates/{documentation → trinity/templates/documentation}/ROOT-README.md.template +0 -0
@@ -1,531 +1,531 @@
1
- # CLAUDE.md - Node.js Technology-Specific Rules
2
- ## {{PROJECT_NAME}} - Node.js Implementation
3
-
4
- **Framework:** {{FRAMEWORK}}
5
- **Language:** JavaScript/TypeScript
6
- **Source Directory:** {{SOURCE_DIR}}
7
- **Runtime:** Node.js
8
-
9
- ---
10
-
11
- ## Technology Stack Behavioral Modifications
12
-
13
- ### Node.js Specific Requirements
14
- - **Async/Await Patterns**: All asynchronous operations must use async/await syntax for better error handling
15
- - **Event Loop Optimization**: Monitor and prevent blocking operations
16
- - **Memory Management**: Implement garbage collection awareness and monitor heap usage
17
- - **Process Management**: Handle graceful shutdowns and restarts
18
- - **Module System**: Use ES6 modules where possible, CommonJS for compatibility
19
-
20
- ### Framework-Specific Adaptations
21
- - **Event-Driven Architecture**: Leverage Node.js event system
22
- - **Stream Processing**: Use streams for large data processing
23
- - **Cluster Mode**: Implement clustering for production deployments
24
- - **Worker Threads**: Use worker threads for CPU-intensive tasks
25
- - **Child Processes**: Spawn child processes when needed
26
-
27
- ---
28
-
29
- ## Technology Debugging Standards
30
-
31
- ### Node.js Debugging Framework
32
- ```javascript
33
- // Standard debugging format for Node.js applications
34
- const createDebugLogger = (moduleName) => {
35
- return {
36
- entry: (functionName, params) => {
37
- console.log(`[ENTRY] ${moduleName}.${functionName}`, {
38
- params: params,
39
- timestamp: new Date().toISOString(),
40
- module: moduleName,
41
- stack: 'Node.js',
42
- pid: process.pid,
43
- memory: process.memoryUsage()
44
- });
45
- },
46
- exit: (functionName, result, startTime) => {
47
- console.log(`[EXIT] ${moduleName}.${functionName}`, {
48
- result: result,
49
- duration: Date.now() - startTime,
50
- timestamp: new Date().toISOString(),
51
- memory: process.memoryUsage()
52
- });
53
- },
54
- error: (functionName, error, context) => {
55
- console.error(`[ERROR] ${moduleName}.${functionName}`, {
56
- error: error.message,
57
- stack: error.stack,
58
- context: context,
59
- timestamp: new Date().toISOString(),
60
- module: moduleName,
61
- pid: process.pid
62
- });
63
- }
64
- };
65
- };
66
-
67
- // Usage example
68
- const logger = createDebugLogger('UserService');
69
-
70
- async function processUser(userId) {
71
- const startTime = Date.now();
72
- logger.entry('processUser', { userId });
73
-
74
- try {
75
- // Implementation...
76
- const result = await performOperation(userId);
77
-
78
- logger.exit('processUser', result, startTime);
79
- return result;
80
- } catch (error) {
81
- logger.error('processUser', error, { userId });
82
- throw error;
83
- }
84
- }
85
- ```
86
-
87
- ### Event Emitter Debugging
88
- ```javascript
89
- // Debug event emitters
90
- const EventEmitter = require('events');
91
-
92
- class DebuggedEmitter extends EventEmitter {
93
- emit(eventName, ...args) {
94
- console.log(`[EVENT] ${eventName}`, {
95
- args: args,
96
- timestamp: new Date().toISOString(),
97
- listeners: this.listenerCount(eventName)
98
- });
99
- return super.emit(eventName, ...args);
100
- }
101
- }
102
- ```
103
-
104
- ---
105
-
106
- ## Performance Optimization Rules
107
-
108
- ### Node.js Performance Monitoring
109
- ```javascript
110
- // Performance monitoring utilities
111
- class PerformanceMonitor {
112
- static measureAsync(name, asyncFunction) {
113
- return async (...args) => {
114
- const startTime = process.hrtime.bigint();
115
- const startMemory = process.memoryUsage();
116
-
117
- try {
118
- const result = await asyncFunction(...args);
119
-
120
- const endTime = process.hrtime.bigint();
121
- const endMemory = process.memoryUsage();
122
-
123
- console.log(`[PERF] ${name}`, {
124
- duration: Number(endTime - startTime) / 1000000, // Convert to ms
125
- memoryDelta: {
126
- heapUsed: endMemory.heapUsed - startMemory.heapUsed,
127
- heapTotal: endMemory.heapTotal - startMemory.heapTotal,
128
- rss: endMemory.rss - startMemory.rss
129
- },
130
- timestamp: new Date().toISOString()
131
- });
132
-
133
- return result;
134
- } catch (error) {
135
- console.error(`[PERF-ERROR] ${name}`, {
136
- error: error.message,
137
- duration: Number(process.hrtime.bigint() - startTime) / 1000000
138
- });
139
- throw error;
140
- }
141
- };
142
- }
143
-
144
- static measureSync(name, syncFunction) {
145
- return (...args) => {
146
- const startTime = process.hrtime.bigint();
147
-
148
- try {
149
- const result = syncFunction(...args);
150
- const endTime = process.hrtime.bigint();
151
-
152
- console.log(`[PERF-SYNC] ${name}`, {
153
- duration: Number(endTime - startTime) / 1000000
154
- });
155
-
156
- return result;
157
- } catch (error) {
158
- console.error(`[PERF-SYNC-ERROR] ${name}`, {
159
- error: error.message
160
- });
161
- throw error;
162
- }
163
- };
164
- }
165
- }
166
-
167
- // Usage
168
- const monitoredFunction = PerformanceMonitor.measureAsync(
169
- 'databaseQuery',
170
- originalQueryFunction
171
- );
172
- ```
173
-
174
- ### Memory Leak Detection
175
- ```javascript
176
- // Monitor for memory leaks
177
- setInterval(() => {
178
- const usage = process.memoryUsage();
179
- console.log('[MEMORY]', {
180
- heapUsed: (usage.heapUsed / 1024 / 1024).toFixed(2) + ' MB',
181
- heapTotal: (usage.heapTotal / 1024 / 1024).toFixed(2) + ' MB',
182
- rss: (usage.rss / 1024 / 1024).toFixed(2) + ' MB',
183
- external: (usage.external / 1024 / 1024).toFixed(2) + ' MB',
184
- timestamp: new Date().toISOString()
185
- });
186
- }, 60000); // Every minute
187
- ```
188
-
189
- ---
190
-
191
- ## Security Best Practices
192
-
193
- ### Input Validation
194
- ```javascript
195
- // Input sanitization and validation
196
- const validator = require('validator');
197
-
198
- function validateUserInput(input) {
199
- // String sanitization
200
- if (typeof input === 'string') {
201
- input = validator.escape(input);
202
- input = validator.trim(input);
203
- }
204
-
205
- // SQL injection prevention
206
- // XSS prevention
207
- // Command injection prevention
208
-
209
- return input;
210
- }
211
- ```
212
-
213
- ### Environment Variables
214
- ```javascript
215
- // Secure environment variable handling
216
- require('dotenv').config();
217
-
218
- const config = {
219
- dbPassword: process.env.DB_PASSWORD,
220
- apiKey: process.env.API_KEY,
221
- secret: process.env.SESSION_SECRET
222
- };
223
-
224
- // Never log sensitive environment variables
225
- console.log('[CONFIG] Loaded configuration (sensitive values hidden)');
226
- ```
227
-
228
- ---
229
-
230
- ## Testing Requirements
231
-
232
- ### Jest Testing Patterns
233
- ```javascript
234
- // Jest testing for Node.js
235
- describe('UserService', () => {
236
- beforeEach(() => {
237
- // Setup
238
- });
239
-
240
- afterEach(() => {
241
- // Cleanup
242
- });
243
-
244
- it('should create user successfully', async () => {
245
- const userData = { username: 'test', email: 'test@example.com' };
246
- const result = await userService.createUser(userData);
247
-
248
- expect(result).toBeDefined();
249
- expect(result.username).toBe('test');
250
- });
251
-
252
- it('should handle errors gracefully', async () => {
253
- await expect(userService.createUser(null))
254
- .rejects
255
- .toThrow('Invalid user data');
256
- });
257
- });
258
- ```
259
-
260
- ### Integration Testing
261
- ```javascript
262
- // Integration test example
263
- const request = require('supertest');
264
- const app = require('../app');
265
-
266
- describe('API Endpoints', () => {
267
- it('GET /api/users should return users', async () => {
268
- const response = await request(app)
269
- .get('/api/users')
270
- .expect('Content-Type', /json/)
271
- .expect(200);
272
-
273
- expect(Array.isArray(response.body)).toBe(true);
274
- });
275
- });
276
- ```
277
-
278
- ---
279
-
280
- ## Framework Best Practices
281
-
282
- ### Express.js Patterns (if applicable)
283
- ```javascript
284
- // Express middleware pattern
285
- const express = require('express');
286
- const app = express();
287
-
288
- // Request logging middleware
289
- app.use((req, res, next) => {
290
- console.log('[HTTP]', {
291
- method: req.method,
292
- path: req.path,
293
- timestamp: new Date().toISOString(),
294
- ip: req.ip
295
- });
296
- next();
297
- });
298
-
299
- // Error handling middleware
300
- app.use((error, req, res, next) => {
301
- console.error('[HTTP-ERROR]', {
302
- error: error.message,
303
- stack: error.stack,
304
- path: req.path,
305
- method: req.method
306
- });
307
-
308
- res.status(500).json({
309
- error: 'Internal server error',
310
- message: process.env.NODE_ENV === 'development' ? error.message : undefined
311
- });
312
- });
313
- ```
314
-
315
- ### Database Integration Patterns
316
- ```javascript
317
- // Database operation logging
318
- const dbLogger = createDebugLogger('Database');
319
-
320
- class DatabaseManager {
321
- static async query(model, operation, params) {
322
- const startTime = Date.now();
323
- dbLogger.entry('query', {
324
- model: model.name,
325
- operation: operation,
326
- params: params
327
- });
328
-
329
- try {
330
- const result = await model[operation](params);
331
-
332
- dbLogger.exit('query', {
333
- rowCount: Array.isArray(result) ? result.length : 1,
334
- success: true
335
- }, startTime);
336
-
337
- return result;
338
- } catch (error) {
339
- dbLogger.error('query', error, {
340
- model: model.name,
341
- operation: operation
342
- });
343
- throw error;
344
- }
345
- }
346
- }
347
- ```
348
-
349
- ---
350
-
351
- ## Error Handling Patterns
352
-
353
- ### Comprehensive Error Handling
354
- ```javascript
355
- // Custom error classes
356
- class ApplicationError extends Error {
357
- constructor(message, statusCode = 500, context = {}) {
358
- super(message);
359
- this.name = this.constructor.name;
360
- this.statusCode = statusCode;
361
- this.context = context;
362
- Error.captureStackTrace(this, this.constructor);
363
- }
364
- }
365
-
366
- class ValidationError extends ApplicationError {
367
- constructor(message, context) {
368
- super(message, 400, context);
369
- }
370
- }
371
-
372
- class DatabaseError extends ApplicationError {
373
- constructor(message, context) {
374
- super(message, 500, context);
375
- }
376
- }
377
-
378
- // Error handling function
379
- async function safeOperation(operation, context) {
380
- try {
381
- return await operation();
382
- } catch (error) {
383
- console.error(`[ERROR] ${context}`, {
384
- error: error.message,
385
- stack: error.stack,
386
- context: context,
387
- timestamp: new Date().toISOString()
388
- });
389
-
390
- if (error.code === 'ECONNREFUSED') {
391
- throw new DatabaseError('Database connection failed', { context });
392
- }
393
-
394
- throw error;
395
- }
396
- }
397
- ```
398
-
399
- ### Global Error Handlers
400
- ```javascript
401
- // Global error handlers
402
- process.on('uncaughtException', (error) => {
403
- console.error('[UNCAUGHT-EXCEPTION]', {
404
- error: error.message,
405
- stack: error.stack,
406
- timestamp: new Date().toISOString()
407
- });
408
-
409
- // Graceful shutdown
410
- process.exit(1);
411
- });
412
-
413
- process.on('unhandledRejection', (reason, promise) => {
414
- console.error('[UNHANDLED-REJECTION]', {
415
- reason: reason,
416
- promise: promise,
417
- timestamp: new Date().toISOString()
418
- });
419
- });
420
-
421
- process.on('SIGINT', () => {
422
- console.log('[SHUTDOWN] Received SIGINT, shutting down gracefully');
423
- // Cleanup logic
424
- process.exit(0);
425
- });
426
-
427
- process.on('SIGTERM', () => {
428
- console.log('[SHUTDOWN] Received SIGTERM, shutting down gracefully');
429
- // Cleanup logic
430
- process.exit(0);
431
- });
432
- ```
433
-
434
- ---
435
-
436
- ## Technology-Specific Command References
437
-
438
- ### Development Commands
439
- ```bash
440
- # Node.js Development
441
- node {{SOURCE_DIR}}/index.js # Start application
442
- node --inspect {{SOURCE_DIR}}/index.js # Start with debugger
443
- npm start # Start with package.json script
444
- npm run dev # Development mode with hot reload
445
-
446
- # Package Management
447
- npm install # Install dependencies
448
- npm install --production # Production dependencies only
449
- npm audit # Security audit
450
- npm update # Update dependencies
451
- ```
452
-
453
- ### Testing Commands
454
- ```bash
455
- # Testing
456
- npm test # Run test suite
457
- npm run test:watch # Watch mode
458
- npm run test:coverage # Generate coverage report
459
- node --inspect-brk node_modules/.bin/jest # Debug tests
460
- ```
461
-
462
- ### Deployment Commands
463
- ```bash
464
- # Production Deployment
465
- NODE_ENV=production node {{SOURCE_DIR}}/index.js
466
- pm2 start {{SOURCE_DIR}}/index.js --name {{PROJECT_NAME}}
467
- pm2 logs {{PROJECT_NAME}}
468
- pm2 restart {{PROJECT_NAME}}
469
- ```
470
-
471
- ---
472
-
473
- ## Component-Level Customizations
474
-
475
- ### Module Organization
476
- ```
477
- {{SOURCE_DIR}}/
478
- ├── controllers/ # Request handlers
479
- ├── services/ # Business logic
480
- ├── models/ # Data models
481
- ├── middleware/ # Express middleware
482
- ├── utils/ # Utility functions
483
- ├── config/ # Configuration
484
- └── tests/ # Test files
485
- ```
486
-
487
- ### Configuration Management
488
- ```javascript
489
- // config/index.js
490
- const config = {
491
- development: {
492
- port: 3000,
493
- database: {
494
- host: 'localhost',
495
- port: 5432
496
- }
497
- },
498
- production: {
499
- port: process.env.PORT || 8080,
500
- database: {
501
- host: process.env.DB_HOST,
502
- port: process.env.DB_PORT
503
- }
504
- }
505
- };
506
-
507
- module.exports = config[process.env.NODE_ENV || 'development'];
508
- ```
509
-
510
- ---
511
-
512
- ## Reference to Parent Context
513
-
514
- This file extends the Trinity Method protocols defined in `../trinity/CLAUDE.md` and global requirements from `../CLAUDE.md`. Node.js implementations must comply with:
515
-
516
- - Trinity Method investigation requirements ([../trinity/CLAUDE.md](../trinity/CLAUDE.md))
517
- - Global performance baselines ([../trinity/knowledge-base/ARCHITECTURE.md](../trinity/knowledge-base/ARCHITECTURE.md#performance-baseline))
518
- - Quality gate standards (BAS 6-phase) ([../trinity/CLAUDE.md](../trinity/CLAUDE.md#quality-standards))
519
- - Crisis management protocols ([../trinity/CLAUDE.md](../trinity/CLAUDE.md#crisis-management))
520
-
521
- All Node.js code must implement the debugging frameworks, error handling patterns, and performance monitoring specified in this document.
522
-
523
- ---
524
-
525
- **Technology Context**: Node.js Implementation
526
- **Parent References**:
527
- - `../CLAUDE.md` - Global project requirements
528
- - `../trinity/CLAUDE.md` - Trinity Method enforcement
529
-
530
- **Last Updated**: {{CURRENT_DATE}}
531
- **Trinity Version**: {{TRINITY_VERSION}}
1
+ # CLAUDE.md - Node.js Technology-Specific Rules
2
+ ## {{PROJECT_NAME}} - Node.js Implementation
3
+
4
+ **Framework:** {{FRAMEWORK}}
5
+ **Language:** JavaScript/TypeScript
6
+ **Source Directory:** {{SOURCE_DIR}}
7
+ **Runtime:** Node.js
8
+
9
+ ---
10
+
11
+ ## Technology Stack Behavioral Modifications
12
+
13
+ ### Node.js Specific Requirements
14
+ - **Async/Await Patterns**: All asynchronous operations must use async/await syntax for better error handling
15
+ - **Event Loop Optimization**: Monitor and prevent blocking operations
16
+ - **Memory Management**: Implement garbage collection awareness and monitor heap usage
17
+ - **Process Management**: Handle graceful shutdowns and restarts
18
+ - **Module System**: Use ES6 modules where possible, CommonJS for compatibility
19
+
20
+ ### Framework-Specific Adaptations
21
+ - **Event-Driven Architecture**: Leverage Node.js event system
22
+ - **Stream Processing**: Use streams for large data processing
23
+ - **Cluster Mode**: Implement clustering for production deployments
24
+ - **Worker Threads**: Use worker threads for CPU-intensive tasks
25
+ - **Child Processes**: Spawn child processes when needed
26
+
27
+ ---
28
+
29
+ ## Technology Debugging Standards
30
+
31
+ ### Node.js Debugging Framework
32
+ ```javascript
33
+ // Standard debugging format for Node.js applications
34
+ const createDebugLogger = (moduleName) => {
35
+ return {
36
+ entry: (functionName, params) => {
37
+ console.log(`[ENTRY] ${moduleName}.${functionName}`, {
38
+ params: params,
39
+ timestamp: new Date().toISOString(),
40
+ module: moduleName,
41
+ stack: 'Node.js',
42
+ pid: process.pid,
43
+ memory: process.memoryUsage()
44
+ });
45
+ },
46
+ exit: (functionName, result, startTime) => {
47
+ console.log(`[EXIT] ${moduleName}.${functionName}`, {
48
+ result: result,
49
+ duration: Date.now() - startTime,
50
+ timestamp: new Date().toISOString(),
51
+ memory: process.memoryUsage()
52
+ });
53
+ },
54
+ error: (functionName, error, context) => {
55
+ console.error(`[ERROR] ${moduleName}.${functionName}`, {
56
+ error: error.message,
57
+ stack: error.stack,
58
+ context: context,
59
+ timestamp: new Date().toISOString(),
60
+ module: moduleName,
61
+ pid: process.pid
62
+ });
63
+ }
64
+ };
65
+ };
66
+
67
+ // Usage example
68
+ const logger = createDebugLogger('UserService');
69
+
70
+ async function processUser(userId) {
71
+ const startTime = Date.now();
72
+ logger.entry('processUser', { userId });
73
+
74
+ try {
75
+ // Implementation...
76
+ const result = await performOperation(userId);
77
+
78
+ logger.exit('processUser', result, startTime);
79
+ return result;
80
+ } catch (error) {
81
+ logger.error('processUser', error, { userId });
82
+ throw error;
83
+ }
84
+ }
85
+ ```
86
+
87
+ ### Event Emitter Debugging
88
+ ```javascript
89
+ // Debug event emitters
90
+ const EventEmitter = require('events');
91
+
92
+ class DebuggedEmitter extends EventEmitter {
93
+ emit(eventName, ...args) {
94
+ console.log(`[EVENT] ${eventName}`, {
95
+ args: args,
96
+ timestamp: new Date().toISOString(),
97
+ listeners: this.listenerCount(eventName)
98
+ });
99
+ return super.emit(eventName, ...args);
100
+ }
101
+ }
102
+ ```
103
+
104
+ ---
105
+
106
+ ## Performance Optimization Rules
107
+
108
+ ### Node.js Performance Monitoring
109
+ ```javascript
110
+ // Performance monitoring utilities
111
+ class PerformanceMonitor {
112
+ static measureAsync(name, asyncFunction) {
113
+ return async (...args) => {
114
+ const startTime = process.hrtime.bigint();
115
+ const startMemory = process.memoryUsage();
116
+
117
+ try {
118
+ const result = await asyncFunction(...args);
119
+
120
+ const endTime = process.hrtime.bigint();
121
+ const endMemory = process.memoryUsage();
122
+
123
+ console.log(`[PERF] ${name}`, {
124
+ duration: Number(endTime - startTime) / 1000000, // Convert to ms
125
+ memoryDelta: {
126
+ heapUsed: endMemory.heapUsed - startMemory.heapUsed,
127
+ heapTotal: endMemory.heapTotal - startMemory.heapTotal,
128
+ rss: endMemory.rss - startMemory.rss
129
+ },
130
+ timestamp: new Date().toISOString()
131
+ });
132
+
133
+ return result;
134
+ } catch (error) {
135
+ console.error(`[PERF-ERROR] ${name}`, {
136
+ error: error.message,
137
+ duration: Number(process.hrtime.bigint() - startTime) / 1000000
138
+ });
139
+ throw error;
140
+ }
141
+ };
142
+ }
143
+
144
+ static measureSync(name, syncFunction) {
145
+ return (...args) => {
146
+ const startTime = process.hrtime.bigint();
147
+
148
+ try {
149
+ const result = syncFunction(...args);
150
+ const endTime = process.hrtime.bigint();
151
+
152
+ console.log(`[PERF-SYNC] ${name}`, {
153
+ duration: Number(endTime - startTime) / 1000000
154
+ });
155
+
156
+ return result;
157
+ } catch (error) {
158
+ console.error(`[PERF-SYNC-ERROR] ${name}`, {
159
+ error: error.message
160
+ });
161
+ throw error;
162
+ }
163
+ };
164
+ }
165
+ }
166
+
167
+ // Usage
168
+ const monitoredFunction = PerformanceMonitor.measureAsync(
169
+ 'databaseQuery',
170
+ originalQueryFunction
171
+ );
172
+ ```
173
+
174
+ ### Memory Leak Detection
175
+ ```javascript
176
+ // Monitor for memory leaks
177
+ setInterval(() => {
178
+ const usage = process.memoryUsage();
179
+ console.log('[MEMORY]', {
180
+ heapUsed: (usage.heapUsed / 1024 / 1024).toFixed(2) + ' MB',
181
+ heapTotal: (usage.heapTotal / 1024 / 1024).toFixed(2) + ' MB',
182
+ rss: (usage.rss / 1024 / 1024).toFixed(2) + ' MB',
183
+ external: (usage.external / 1024 / 1024).toFixed(2) + ' MB',
184
+ timestamp: new Date().toISOString()
185
+ });
186
+ }, 60000); // Every minute
187
+ ```
188
+
189
+ ---
190
+
191
+ ## Security Best Practices
192
+
193
+ ### Input Validation
194
+ ```javascript
195
+ // Input sanitization and validation
196
+ const validator = require('validator');
197
+
198
+ function validateUserInput(input) {
199
+ // String sanitization
200
+ if (typeof input === 'string') {
201
+ input = validator.escape(input);
202
+ input = validator.trim(input);
203
+ }
204
+
205
+ // SQL injection prevention
206
+ // XSS prevention
207
+ // Command injection prevention
208
+
209
+ return input;
210
+ }
211
+ ```
212
+
213
+ ### Environment Variables
214
+ ```javascript
215
+ // Secure environment variable handling
216
+ require('dotenv').config();
217
+
218
+ const config = {
219
+ dbPassword: process.env.DB_PASSWORD,
220
+ apiKey: process.env.API_KEY,
221
+ secret: process.env.SESSION_SECRET
222
+ };
223
+
224
+ // Never log sensitive environment variables
225
+ console.log('[CONFIG] Loaded configuration (sensitive values hidden)');
226
+ ```
227
+
228
+ ---
229
+
230
+ ## Testing Requirements
231
+
232
+ ### Jest Testing Patterns
233
+ ```javascript
234
+ // Jest testing for Node.js
235
+ describe('UserService', () => {
236
+ beforeEach(() => {
237
+ // Setup
238
+ });
239
+
240
+ afterEach(() => {
241
+ // Cleanup
242
+ });
243
+
244
+ it('should create user successfully', async () => {
245
+ const userData = { username: 'test', email: 'test@example.com' };
246
+ const result = await userService.createUser(userData);
247
+
248
+ expect(result).toBeDefined();
249
+ expect(result.username).toBe('test');
250
+ });
251
+
252
+ it('should handle errors gracefully', async () => {
253
+ await expect(userService.createUser(null))
254
+ .rejects
255
+ .toThrow('Invalid user data');
256
+ });
257
+ });
258
+ ```
259
+
260
+ ### Integration Testing
261
+ ```javascript
262
+ // Integration test example
263
+ const request = require('supertest');
264
+ const app = require('../app');
265
+
266
+ describe('API Endpoints', () => {
267
+ it('GET /api/users should return users', async () => {
268
+ const response = await request(app)
269
+ .get('/api/users')
270
+ .expect('Content-Type', /json/)
271
+ .expect(200);
272
+
273
+ expect(Array.isArray(response.body)).toBe(true);
274
+ });
275
+ });
276
+ ```
277
+
278
+ ---
279
+
280
+ ## Framework Best Practices
281
+
282
+ ### Express.js Patterns (if applicable)
283
+ ```javascript
284
+ // Express middleware pattern
285
+ const express = require('express');
286
+ const app = express();
287
+
288
+ // Request logging middleware
289
+ app.use((req, res, next) => {
290
+ console.log('[HTTP]', {
291
+ method: req.method,
292
+ path: req.path,
293
+ timestamp: new Date().toISOString(),
294
+ ip: req.ip
295
+ });
296
+ next();
297
+ });
298
+
299
+ // Error handling middleware
300
+ app.use((error, req, res, next) => {
301
+ console.error('[HTTP-ERROR]', {
302
+ error: error.message,
303
+ stack: error.stack,
304
+ path: req.path,
305
+ method: req.method
306
+ });
307
+
308
+ res.status(500).json({
309
+ error: 'Internal server error',
310
+ message: process.env.NODE_ENV === 'development' ? error.message : undefined
311
+ });
312
+ });
313
+ ```
314
+
315
+ ### Database Integration Patterns
316
+ ```javascript
317
+ // Database operation logging
318
+ const dbLogger = createDebugLogger('Database');
319
+
320
+ class DatabaseManager {
321
+ static async query(model, operation, params) {
322
+ const startTime = Date.now();
323
+ dbLogger.entry('query', {
324
+ model: model.name,
325
+ operation: operation,
326
+ params: params
327
+ });
328
+
329
+ try {
330
+ const result = await model[operation](params);
331
+
332
+ dbLogger.exit('query', {
333
+ rowCount: Array.isArray(result) ? result.length : 1,
334
+ success: true
335
+ }, startTime);
336
+
337
+ return result;
338
+ } catch (error) {
339
+ dbLogger.error('query', error, {
340
+ model: model.name,
341
+ operation: operation
342
+ });
343
+ throw error;
344
+ }
345
+ }
346
+ }
347
+ ```
348
+
349
+ ---
350
+
351
+ ## Error Handling Patterns
352
+
353
+ ### Comprehensive Error Handling
354
+ ```javascript
355
+ // Custom error classes
356
+ class ApplicationError extends Error {
357
+ constructor(message, statusCode = 500, context = {}) {
358
+ super(message);
359
+ this.name = this.constructor.name;
360
+ this.statusCode = statusCode;
361
+ this.context = context;
362
+ Error.captureStackTrace(this, this.constructor);
363
+ }
364
+ }
365
+
366
+ class ValidationError extends ApplicationError {
367
+ constructor(message, context) {
368
+ super(message, 400, context);
369
+ }
370
+ }
371
+
372
+ class DatabaseError extends ApplicationError {
373
+ constructor(message, context) {
374
+ super(message, 500, context);
375
+ }
376
+ }
377
+
378
+ // Error handling function
379
+ async function safeOperation(operation, context) {
380
+ try {
381
+ return await operation();
382
+ } catch (error) {
383
+ console.error(`[ERROR] ${context}`, {
384
+ error: error.message,
385
+ stack: error.stack,
386
+ context: context,
387
+ timestamp: new Date().toISOString()
388
+ });
389
+
390
+ if (error.code === 'ECONNREFUSED') {
391
+ throw new DatabaseError('Database connection failed', { context });
392
+ }
393
+
394
+ throw error;
395
+ }
396
+ }
397
+ ```
398
+
399
+ ### Global Error Handlers
400
+ ```javascript
401
+ // Global error handlers
402
+ process.on('uncaughtException', (error) => {
403
+ console.error('[UNCAUGHT-EXCEPTION]', {
404
+ error: error.message,
405
+ stack: error.stack,
406
+ timestamp: new Date().toISOString()
407
+ });
408
+
409
+ // Graceful shutdown
410
+ process.exit(1);
411
+ });
412
+
413
+ process.on('unhandledRejection', (reason, promise) => {
414
+ console.error('[UNHANDLED-REJECTION]', {
415
+ reason: reason,
416
+ promise: promise,
417
+ timestamp: new Date().toISOString()
418
+ });
419
+ });
420
+
421
+ process.on('SIGINT', () => {
422
+ console.log('[SHUTDOWN] Received SIGINT, shutting down gracefully');
423
+ // Cleanup logic
424
+ process.exit(0);
425
+ });
426
+
427
+ process.on('SIGTERM', () => {
428
+ console.log('[SHUTDOWN] Received SIGTERM, shutting down gracefully');
429
+ // Cleanup logic
430
+ process.exit(0);
431
+ });
432
+ ```
433
+
434
+ ---
435
+
436
+ ## Technology-Specific Command References
437
+
438
+ ### Development Commands
439
+ ```bash
440
+ # Node.js Development
441
+ node {{SOURCE_DIR}}/index.js # Start application
442
+ node --inspect {{SOURCE_DIR}}/index.js # Start with debugger
443
+ npm start # Start with package.json script
444
+ npm run dev # Development mode with hot reload
445
+
446
+ # Package Management
447
+ npm install # Install dependencies
448
+ npm install --production # Production dependencies only
449
+ npm audit # Security audit
450
+ npm update # Update dependencies
451
+ ```
452
+
453
+ ### Testing Commands
454
+ ```bash
455
+ # Testing
456
+ npm test # Run test suite
457
+ npm run test:watch # Watch mode
458
+ npm run test:coverage # Generate coverage report
459
+ node --inspect-brk node_modules/.bin/jest # Debug tests
460
+ ```
461
+
462
+ ### Deployment Commands
463
+ ```bash
464
+ # Production Deployment
465
+ NODE_ENV=production node {{SOURCE_DIR}}/index.js
466
+ pm2 start {{SOURCE_DIR}}/index.js --name {{PROJECT_NAME}}
467
+ pm2 logs {{PROJECT_NAME}}
468
+ pm2 restart {{PROJECT_NAME}}
469
+ ```
470
+
471
+ ---
472
+
473
+ ## Component-Level Customizations
474
+
475
+ ### Module Organization
476
+ ```
477
+ {{SOURCE_DIR}}/
478
+ ├── controllers/ # Request handlers
479
+ ├── services/ # Business logic
480
+ ├── models/ # Data models
481
+ ├── middleware/ # Express middleware
482
+ ├── utils/ # Utility functions
483
+ ├── config/ # Configuration
484
+ └── tests/ # Test files
485
+ ```
486
+
487
+ ### Configuration Management
488
+ ```javascript
489
+ // config/index.js
490
+ const config = {
491
+ development: {
492
+ port: 3000,
493
+ database: {
494
+ host: 'localhost',
495
+ port: 5432
496
+ }
497
+ },
498
+ production: {
499
+ port: process.env.PORT || 8080,
500
+ database: {
501
+ host: process.env.DB_HOST,
502
+ port: process.env.DB_PORT
503
+ }
504
+ }
505
+ };
506
+
507
+ module.exports = config[process.env.NODE_ENV || 'development'];
508
+ ```
509
+
510
+ ---
511
+
512
+ ## Reference to Parent Context
513
+
514
+ This file extends the Trinity Method protocols defined in `../trinity/CLAUDE.md` and global requirements from `../CLAUDE.md`. Node.js implementations must comply with:
515
+
516
+ - Trinity Method investigation requirements ([../trinity/CLAUDE.md](../trinity/CLAUDE.md))
517
+ - Global performance baselines ([../trinity/knowledge-base/ARCHITECTURE.md](../trinity/knowledge-base/ARCHITECTURE.md#performance-baseline))
518
+ - Quality gate standards (BAS 6-phase) ([../trinity/CLAUDE.md](../trinity/CLAUDE.md#quality-standards))
519
+ - Crisis management protocols ([../trinity/CLAUDE.md](../trinity/CLAUDE.md#crisis-management))
520
+
521
+ All Node.js code must implement the debugging frameworks, error handling patterns, and performance monitoring specified in this document.
522
+
523
+ ---
524
+
525
+ **Technology Context**: Node.js Implementation
526
+ **Parent References**:
527
+ - `../CLAUDE.md` - Global project requirements
528
+ - `../trinity/CLAUDE.md` - Trinity Method enforcement
529
+
530
+ **Last Updated**: {{CURRENT_DATE}}
531
+ **Trinity Version**: {{TRINITY_VERSION}}