claude-flow-novice 1.5.14 → 1.5.16

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.
@@ -2,7 +2,7 @@
2
2
  * Dynamic Agent Loader - Reads agent definitions from .claude/agents/ directory
3
3
  * This is the single source of truth for all agent types in the system
4
4
  */ import { readFileSync, existsSync } from 'node:fs';
5
- import glob from 'glob';
5
+ import { glob } from 'glob';
6
6
  import { resolve, dirname } from 'node:path';
7
7
  import { parse as parseYaml } from 'yaml';
8
8
  // Legacy agent type mapping for backward compatibility
@@ -45,24 +45,44 @@ export class AgentLoader {
45
45
  */ parseAgentFile(filePath) {
46
46
  try {
47
47
  const content = readFileSync(filePath, 'utf-8');
48
- // Split frontmatter and content
49
- const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
48
+ // Split frontmatter and content (handle both \n and \r\n line endings)
49
+ const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);
50
50
  if (!frontmatterMatch) {
51
51
  console.warn(`No frontmatter found in ${filePath}`);
52
52
  return null;
53
53
  }
54
54
  const [, yamlContent, markdownContent] = frontmatterMatch;
55
55
  const frontmatter = parseYaml(yamlContent);
56
- if (!frontmatter.name || !frontmatter.metadata?.description) {
57
- console.warn(`Missing required fields (name, metadata.description) in ${filePath}`);
56
+ // Support both formats: direct fields and metadata-wrapped fields
57
+ const description = frontmatter.description || frontmatter.metadata?.description;
58
+ const capabilities = frontmatter.capabilities || frontmatter.metadata?.capabilities || [];
59
+ // Parse tools - can be in multiple locations and formats
60
+ let tools = [];
61
+ // Check direct tools field first
62
+ if (frontmatter.tools) {
63
+ if (Array.isArray(frontmatter.tools)) {
64
+ tools = frontmatter.tools;
65
+ } else if (typeof frontmatter.tools === 'string') {
66
+ // Split by comma or space, trim, and filter empty
67
+ tools = frontmatter.tools.split(/[,\s]+/).map((t)=>t.trim()).filter((t)=>t.length > 0);
68
+ }
69
+ } else if (frontmatter.capabilities?.tools) {
70
+ if (Array.isArray(frontmatter.capabilities.tools)) {
71
+ tools = frontmatter.capabilities.tools;
72
+ }
73
+ }
74
+ if (!frontmatter.name || !description) {
75
+ console.warn(`Missing required fields (name, description) in ${filePath}`);
58
76
  return null;
59
77
  }
60
78
  return {
61
79
  name: frontmatter.name,
62
80
  type: frontmatter.type,
63
81
  color: frontmatter.color,
64
- description: frontmatter.metadata.description,
65
- capabilities: frontmatter.metadata.capabilities || frontmatter.capabilities || [],
82
+ model: frontmatter.model,
83
+ description,
84
+ tools,
85
+ capabilities,
66
86
  priority: frontmatter.priority || 'medium',
67
87
  hooks: frontmatter.hooks,
68
88
  content: markdownContent.trim()
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/agents/agent-loader.ts"],"names":["readFileSync","existsSync","glob","resolve","dirname","parse","parseYaml","LEGACY_AGENT_MAPPING","analyst","coordinator","optimizer","documenter","monitor","specialist","architect","resolveLegacyAgentType","legacyType","AgentLoader","agentCache","Map","categoriesCache","lastLoadTime","cacheExpiry","getAgentsDirectory","currentDir","process","cwd","claudeAgentsPath","parseAgentFile","filePath","content","frontmatterMatch","match","console","warn","yamlContent","markdownContent","frontmatter","name","metadata","description","type","color","capabilities","priority","hooks","trim","error","loadAgents","agentsDir","agentFiles","ignore","absolute","clear","categoryMap","agent","set","relativePath","replace","pathParts","split","category","has","get","push","Array","from","entries","map","agents","sort","a","b","localeCompare","Date","now","needsRefresh","ensureLoaded","size","getAvailableAgentTypes","currentTypes","keys","legacyTypes","Object","combined","uniqueTypes","Set","getAgent","getAllAgents","values","getAgentCategories","searchAgents","query","lowerQuery","toLowerCase","filter","includes","some","cap","isValidAgentType","getAgentsByCategory","categories","found","find","cat","refresh","agentLoader","refreshAgents"],"mappings":"AAAA;;;CAGC,GAED,SAASA,YAAY,EAAEC,UAAU,QAAQ,UAAU;AACnD,OAAOC,UAAU,OAAO;AACxB,SAASC,OAAO,EAAEC,OAAO,QAAQ,YAAY;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e;QACtC,MAAM,IAAI,CAAC2B,UAAU;IACvB;AACF;AAEA,qBAAqB;AACrB,OAAO,MAAM0D,cAAc,IAAIzF,cAAc;AAE7C,wBAAwB;AACxB,OAAO,MAAM8D,yBAAyB,IAAM2B,YAAY3B,sBAAsB,GAAG;AACjF,OAAO,MAAMQ,WAAW,CAACjD,OAAiBoE,YAAYnB,QAAQ,CAACjD,MAAM;AACrE,OAAO,MAAMkD,eAAe,IAAMkB,YAAYlB,YAAY,GAAG;AAC7D,OAAO,MAAME,qBAAqB,IAAMgB,YAAYhB,kBAAkB,GAAG;AACzE,OAAO,MAAMC,eAAe,CAACC,QAAkBc,YAAYf,YAAY,CAACC,OAAO;AAC/E,OAAO,MAAMO,mBAAmB,CAAC7D,OAAiBoE,YAAYP,gBAAgB,CAAC7D,MAAM;AACrF,OAAO,MAAM8D,sBAAsB,CAACvC,WAAqB6C,YAAYN,mBAAmB,CAACvC,UAAU;AACnG,OAAO,MAAM8C,gBAAgB,IAAMD,YAAYD,OAAO,GAAG;AAEzD,kCAAkC;AAClC,SAAS1F,sBAAsB,EAAER,oBAAoB,GAAG"}
1
+ {"version":3,"sources":["../../../../src/agents/agent-loader.ts"],"names":["readFileSync","existsSync","glob","resolve","dirname","parse","parseYaml","LEGACY_AGENT_MAPPING","analyst","coordinator","optimizer","documenter","monitor","specialist","architect","resolveLegacyAgentType","legacyType","AgentLoader","agentCache","Map","categoriesCache","lastLoadTime","cacheExpiry","getAgentsDirectory","currentDir","process","cwd","claudeAgentsPath","parseAgentFile","filePath","content","frontmatterMatch","match","console","warn","yamlContent","markdownContent","frontmatter","description","metadata","capabilities","tools","Array","isArray","split","map","t","trim","filter","length","name","type","color","model","priority","hooks","error","loadAgents","agentsDir","agentFiles","ignore","absolute","clear","categoryMap","agent","set","relativePath","replace","pathParts","category","has","get","push","from","entries","agents","sort","a","b","localeCompare","Date","now","needsRefresh","ensureLoaded","size","getAvailableAgentTypes","currentTypes","keys","legacyTypes","Object","combined","uniqueTypes","Set","getAgent","getAllAgents","values","getAgentCategories","searchAgents","query","lowerQuery","toLowerCase","includes","some","cap","isValidAgentType","getAgentsByCategory","categories","found","find","cat","refresh","agentLoader","refreshAgents"],"mappings":"AAAA;;;CAGC,GAED,SAASA,YAAY,EAAEC,UAAU,QAAQ,UAAU;AACnD,SAASC,IAAI,QAAQ,OAAO;AAC5B,SAASC,OAAO,EAAEC,OAAO,QAAQ,YAAY;AAC7C,SAASC,SAASC,SAAS,QAAQ,OAAO;AAE1C,uDAAuD;AACvD,MAAMC,uBAAuB;IAC3BC,SAAS;IACTC,aAAa;IACbC,WAAW;IACXC,YAAY;IACZC,SAAS;IACTC,YAAY;IACZC,WAAW;AACb;AAEA;;CAEC,GACD,SAASC,uBAAuBC,UAAkB;IAChD,OAAOT,oBAAoB,CAACS,WAAgD,IAAIA;AAClF;AAwCA,OAAO,MAAMC;IACHC,aAA2C,IAAIC,MAAM;IACrDC,kBAAmC,EAAE,CAAC;IACtCC,eAAe,EAAE;IACjBC,cAAc,MAAM;IAE5B;;GAEC,GACD,AAAQC,qBAA6B;QACnC,0EAA0E;QAC1E,IAAIC,aAAaC,QAAQC,GAAG;QAE5B,MAAOF,eAAe,IAAK;YACzB,MAAMG,mBAAmBxB,QAAQqB,YAAY,WAAW;YACxD,IAAIvB,WAAW0B,mBAAmB;gBAChC,OAAOA;YACT;YACAH,aAAapB,QAAQoB;QACvB;QAEA,4BAA4B;QAC5B,OAAOrB,QAAQsB,QAAQC,GAAG,IAAI,WAAW;IAC3C;IAEA;;GAEC,GACD,AAAQE,eAAeC,QAAgB,EAA0B;QAC/D,IAAI;YACF,MAAMC,UAAU9B,aAAa6B,UAAU;YAEvC,uEAAuE;YACvE,MAAME,mBAAmBD,QAAQE,KAAK,CAAC;YACvC,IAAI,CAACD,kBAAkB;gBACrBE,QAAQC,IAAI,CAAC,CAAC,wBAAwB,EAAEL,UAAU;gBAClD,OAAO;YACT;YAEA,MAAM,GAAGM,aAAaC,gBAAgB,GAAGL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qBAAqB,IAAMe,YAAYf,kBAAkB,GAAG;AACzE,OAAO,MAAMC,eAAe,CAACC,QAAkBa,YAAYd,YAAY,CAACC,OAAO;AAC/E,OAAO,MAAMM,mBAAmB,CAACtD,OAAiB6D,YAAYP,gBAAgB,CAACtD,MAAM;AACrF,OAAO,MAAMuD,sBAAsB,CAACpC,WAAqB0C,YAAYN,mBAAmB,CAACpC,UAAU;AACnG,OAAO,MAAM2C,gBAAgB,IAAMD,YAAYD,OAAO,GAAG;AAEzD,kCAAkC;AAClC,SAAS/F,sBAAsB,EAAER,oBAAoB,GAAG"}
@@ -15,6 +15,8 @@
15
15
  6. **NEVER SAVE TO ROOT** - Organize files in appropriate subdirectories
16
16
  7. **USE CLAUDE CODE'S TASK TOOL** - For spawning agents concurrently, not just MCP
17
17
  8. **USE THE CFN LOOP** - For a self correcting dev loop that saves time and resources
18
+ 9. **DO NOT CREATE GUIDES, SUMMARIES, OR REPORT FILES** - unless specifically asked.
19
+ 10. **USE SPARTAN LANGUAGE** - no fluff encouraged
18
20
 
19
21
  ### 🚫 WHEN YOU MUST USE AGENTS (MANDATORY)
20
22
 
@@ -58,6 +60,7 @@
58
60
  - ❌ Writing code without a tester agent
59
61
  - ❌ Making architectural decisions without an architect agent
60
62
  - ❌ Deploying without security review from security-specialist agent
63
+ - ❌ Creating reports documents, summary documents, or guides unless explicity asked
61
64
 
62
65
  ## 🎯 Claude Code vs MCP Tools
63
66
 
@@ -95,88 +98,29 @@ npx claude-flow-novice hooks pre-command --command "[command]" --validate-safety
95
98
  npx claude-flow-novice hooks pre-edit --file "[file]" --auto-assign-agents true --load-context true
96
99
  ```
97
100
 
98
- #### Post-Task Hooks (Validation & Quality)
101
+ #### Post-Edit Hook (MANDATORY After Every File Edit)
99
102
  ```bash
100
- # Track metrics and store results
101
- npx claude-flow-novice hooks post-command --command "[command]" --track-metrics true --store-results true
103
+ # Unified pipeline: standard validation + TDD + Rust quality
104
+ node config/hooks/post-edit-pipeline.js "[FILE]" --memory-key "swarm/[agent]/[step]"
102
105
 
103
- # Enhanced post-edit pipeline with comprehensive TDD validation
104
- npx enhanced-hooks post-edit "[file]" --memory-key "swarm/[agent]/[step]" --minimum-coverage 80 --structured
106
+ # Enable TDD mode (single-file testing, coverage, phase detection)
107
+ node config/hooks/post-edit-pipeline.js "[FILE]" --tdd-mode --minimum-coverage 80
105
108
 
106
- # Manual hook execution (guaranteed working)
107
- node src/hooks/enhanced-hooks-cli.js post-edit "[file]" --memory-key "[key]" --structured
109
+ # Enable Rust strict mode (unwrap/expect/panic detection)
110
+ node config/hooks/post-edit-pipeline.js "[FILE]" --rust-strict
108
111
 
109
- # Validates: formatting, linting, type checking, dependencies, security, tests, TDD compliance
110
- # Progressive validation: graceful degradation when dependencies missing (beginner-friendly)
112
+ # Full mode: TDD + Rust + coverage threshold
113
+ node config/hooks/post-edit-pipeline.js "[FILE]" --tdd-mode --rust-strict --minimum-coverage 90
111
114
  ```
112
115
 
113
- ## 🎯 **Enhanced Post-Edit Hook System**
114
-
115
- ### **🚨 MANDATORY: Manual Hook Execution After Every File Edit**
116
-
117
- **CRITICAL RULE**: After **EVERY** file edit operation, you **MUST** run the enhanced post-edit hook:
118
-
119
- ```bash
120
- # After editing any file, IMMEDIATELY run:
121
- npx enhanced-hooks post-edit "[FILE_PATH]" --memory-key "swarm/[AGENT]/[STEP]" --minimum-coverage 80 --structured
122
-
123
- # Or via slash command:
124
- /hooks post-edit [FILE_PATH] --memory-key "[CONTEXT]" --structured
125
- ```
126
-
127
- **⚠️ NO EXCEPTIONS**: This applies to:
128
- - All JavaScript/TypeScript files
129
- - All Rust files
130
- - All Python files
131
- - All configuration files
132
- - ALL file modifications
133
-
134
- ### **Enhanced Post-Edit Pipeline Features:**
135
- - **🧪 TDD Testing**: Single-file testing without full system compilation
136
- - **📊 Real-time Coverage**: Coverage analysis with configurable thresholds (default: 80%)
137
- - **🌐 Multi-Language Support**:
138
- - **JavaScript/TypeScript**: Jest, Mocha, Prettier, ESLint integration
139
- - **Rust**: cargo check, cargo test, cargo-tarpaulin, rustfmt
140
- - **Python**: pytest, unittest, black, pylint
141
- - **Go**: go test, go fmt, go vet
142
- - **Java**: JUnit, TestNG, google-java-format
143
- - **C/C++**: GTest, Catch2, clang-format
144
- - **🎨 Formatting**: Prettier, Black, RustFmt, GoFmt with diff preview
145
- - **🔒 Security Analysis**: XSS, eval(), hardcoded credentials, SQL injection detection
146
- - **✅ TDD Compliance**: Red-Green-Refactor phase detection and enforcement
147
- - **🔍 Framework Detection**: Automatic test framework identification
148
- - **🤖 Agent Feedback**: Structured JSON with actionable recommendations
149
- - **💾 Memory Coordination**: Cross-agent state sharing and enhanced persistence
150
- - **🚫 Blocking Mechanisms**: Quality gates for critical validation failures
151
-
152
- ### **Usage Examples:**
153
- ```bash
154
- # For JavaScript/TypeScript files
155
- npx enhanced-hooks post-edit "src/components/Button.tsx" --memory-key "frontend/button" --structured
156
-
157
- # For Rust files (full cargo integration)
158
- npx enhanced-hooks post-edit "src/lib.rs" --memory-key "backend/rust" --minimum-coverage 90 --structured
159
-
160
- # Via slash commands in Claude Code
161
- /hooks post-edit your-file.js --memory-key "agent-memory-key" --structured
162
- ```
163
-
164
- ### **Response Structure:**
165
- ```json
166
- {
167
- "success": true,
168
- "file": "src/component.js",
169
- "validation": { "passed": true, "issues": [], "coverage": "advanced" },
170
- "formatting": { "needed": true, "changes": 12, "formatter": "prettier" },
171
- "testing": { "executed": true, "framework": "jest", "results": {...} },
172
- "tddCompliance": { "hasTests": true, "coverage": 85, "recommendations": [...] },
173
- "recommendations": [
174
- { "type": "security", "priority": "high", "message": "...", "action": "..." },
175
- { "type": "formatting", "priority": "medium", "action": "prettier file.js" }
176
- ],
177
- "memory": { "stored": true, "enhancedStore": true }
178
- }
179
- ```
116
+ **Features (all languages):**
117
+ - Formatting, linting, type checking, security, dependencies
118
+ - Single-file testing (1-5s vs 10-60s full suite)
119
+ - Real-time coverage (Jest, pytest, cargo-tarpaulin)
120
+ - TDD compliance (Red-Green-Refactor detection)
121
+ - Rust quality (unwrap/expect/panic with line numbers)
122
+ - Comment-aware validation, structured JSON output
123
+ - Logs to `post-edit-pipeline.log` (500 entries max)
180
124
 
181
125
  #### Session Management
182
126
  ```bash
@@ -261,7 +205,7 @@ npx claude-flow-novice hooks session-end --generate-summary true --persist-state
261
205
  **After completion:**
262
206
  - ✅ Consensus validation achieved (≥90% agreement)
263
207
  - ✅ Results stored in memory
264
- - ✅ Next steps provided with claude code continuing to the next documented phase or next steps provided to user if no todos left
208
+ - ✅ Next steps determined
265
209
 
266
210
  ### Agent Selection Guide
267
211
 
@@ -352,7 +296,7 @@ claude mcp add claude-flow-novice npx claude-flow-novice mcp start
352
296
  ### Step 3: Self-Assessment Gate
353
297
  - **If confidence scores ≥75%** → Proceed to Step 4 (Consensus Verification)
354
298
  - **If confidence scores <75%** → Relaunch agents for Step 2 with feedback
355
- - **Maximum iterations**: 3 attempts before escalation
299
+ - **Maximum iterations**: 3 attempts before escalation using next steps guidance
356
300
 
357
301
  ### Step 4: Verify - Consensus Swarm (2-4 validators REQUIRED)
358
302
  ```javascript
@@ -373,13 +317,13 @@ claude mcp add claude-flow-novice npx claude-flow-novice mcp start
373
317
  ### Step 6: Action Based on Decision
374
318
  - **PASS** →
375
319
  1. Store results in SwarmMemory
376
- 2. Update documentation
320
+ 2. Update documentation if asked to do so
377
321
  3. Update todos and move to next task
378
322
 
379
323
  - **FAIL** →
380
324
  1. Round counter++
381
325
  2. If Round < 10: Inject validator feedback → Return to Step 2
382
- 3. If Round ≥ 10: Escalate to human with comprehensive report
326
+ 3. If Round ≥ 10: Escalate to human with next steps guidance
383
327
 
384
328
  ### 🚨 ENFORCEMENT CHECKPOINTS
385
329
 
@@ -393,9 +337,7 @@ claude mcp add claude-flow-novice npx claude-flow-novice mcp start
393
337
 
394
338
  ---
395
339
 
396
- ## 🎯 MANDATORY: NEXT STEPS GUIDANCE
397
-
398
- **After completing ANY task, you MUST provide:**
340
+ ## NEXT STEPS GUIDANCE
399
341
 
400
342
  1. **✅ What was completed**: Brief summary of delivered work
401
343
  2. **📊 Validation results**: Confidence scores, test coverage, consensus approval
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Enhanced Hooks CLI for Claude Flow Novice
5
+ *
6
+ * Wrapper for the unified post-edit-pipeline.js
7
+ * Provides backward compatibility with enhanced-hooks command
8
+ */
9
+
10
+ import { spawn } from 'child_process';
11
+ import { fileURLToPath } from 'url';
12
+ import { dirname, join } from 'path';
13
+
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = dirname(__filename);
16
+
17
+ // Enhanced hooks CLI interface
18
+ export async function enhancedHooksCLI() {
19
+ const args = process.argv.slice(2);
20
+ const command = args[0];
21
+
22
+ if (!command || command === '--help' || command === '-h') {
23
+ console.log(`
24
+ 🚀 Enhanced Hooks CLI for Claude Flow Novice - v2.0.0
25
+
26
+ Available commands:
27
+ post-edit <file> [options] Enhanced post-edit with TDD testing
28
+ enhanced-post-edit <file> [options] Alias for post-edit
29
+
30
+ Options:
31
+ --memory-key <key> Store results with specific memory key
32
+ --format Analyze formatting (default: true)
33
+ --validate Run validation (default: true)
34
+ --enable-tdd Enable TDD testing (default: true)
35
+ --minimum-coverage <percent> Minimum coverage threshold (default: 80)
36
+ --block-on-critical Block execution on critical errors
37
+ --structured Return structured JSON data
38
+ --generate-recommendations Generate actionable recommendations (default: true)
39
+
40
+ Examples:
41
+ npx claude-flow-novice enhanced-hooks post-edit src/app.js --memory-key "swarm/coder/step-1"
42
+ npx claude-flow-novice enhanced-hooks post-edit test.js --minimum-coverage 90 --structured
43
+
44
+ Enhanced Features:
45
+ ✅ TDD testing with single-file execution
46
+ ✅ Real-time coverage analysis and diff reporting
47
+ ✅ Advanced multi-language validation with error locations
48
+ ✅ Formatting diff preview and change detection
49
+ ✅ Actionable recommendations by category
50
+ ✅ Blocking mechanisms for critical failures
51
+ ✅ Enhanced memory store with versioning
52
+ `);
53
+ return;
54
+ }
55
+
56
+ if (command === 'post-edit' || command === 'enhanced-post-edit') {
57
+ const file = args[1];
58
+ if (!file) {
59
+ console.log('❌ File path required for post-edit hook');
60
+ return;
61
+ }
62
+
63
+ // Build unified pipeline command with TDD mode enabled by default
64
+ // Use process.cwd() to find config/hooks in the actual project, not dist
65
+ const pipelinePath = join(process.cwd(), 'config/hooks/post-edit-pipeline.js');
66
+ const pipelineArgs = [file, '--tdd-mode'];
67
+
68
+ // Pass through all relevant flags
69
+ if (args.includes('--memory-key')) {
70
+ const idx = args.indexOf('--memory-key');
71
+ pipelineArgs.push('--memory-key', args[idx + 1]);
72
+ }
73
+ if (args.includes('--minimum-coverage')) {
74
+ const idx = args.indexOf('--minimum-coverage');
75
+ pipelineArgs.push('--minimum-coverage', args[idx + 1]);
76
+ }
77
+ if (args.includes('--block-on-critical')) {
78
+ pipelineArgs.push('--block-on-tdd-violations');
79
+ }
80
+ if (args.includes('--structured')) {
81
+ // Structured output is default in unified pipeline
82
+ }
83
+
84
+ // Execute unified pipeline
85
+ const proc = spawn('node', [pipelinePath, ...pipelineArgs], {
86
+ stdio: 'inherit',
87
+ cwd: process.cwd()
88
+ });
89
+
90
+ proc.on('close', (code) => {
91
+ process.exit(code || 0);
92
+ });
93
+
94
+ proc.on('error', (error) => {
95
+ console.error(`❌ Failed to execute unified pipeline: ${error.message}`);
96
+ process.exit(1);
97
+ });
98
+
99
+ } else {
100
+ console.log(`❌ Unknown command: ${command}`);
101
+ console.log('Use --help for available commands');
102
+ process.exit(1);
103
+ }
104
+ }
105
+
106
+ // Enhanced hooks function for programmatic use (delegates to unified pipeline)
107
+ export async function enhancedPostEdit(file, memoryKey = null, options = {}) {
108
+ return new Promise((resolve, reject) => {
109
+ const pipelinePath = join(process.cwd(), 'config/hooks/post-edit-pipeline.js');
110
+ const args = [file, '--tdd-mode'];
111
+
112
+ if (memoryKey) args.push('--memory-key', memoryKey);
113
+ if (options.minimumCoverage) args.push('--minimum-coverage', options.minimumCoverage.toString());
114
+ if (options.blockOnCritical) args.push('--block-on-tdd-violations');
115
+
116
+ const proc = spawn('node', [pipelinePath, ...args], {
117
+ stdio: 'pipe',
118
+ cwd: process.cwd()
119
+ });
120
+
121
+ let stdout = '';
122
+ let stderr = '';
123
+
124
+ proc.stdout.on('data', (data) => stdout += data.toString());
125
+ proc.stderr.on('data', (data) => stderr += data.toString());
126
+
127
+ proc.on('close', (code) => {
128
+ resolve({
129
+ success: code === 0,
130
+ file,
131
+ memoryKey,
132
+ timestamp: new Date().toISOString(),
133
+ output: stdout,
134
+ error: stderr,
135
+ exitCode: code
136
+ });
137
+ });
138
+
139
+ proc.on('error', (error) => {
140
+ reject(error);
141
+ });
142
+ });
143
+ }
144
+
145
+ // Backward compatibility function (delegates to unified pipeline)
146
+ export async function legacyPostEditHook(file, memoryKey = null, options = {}) {
147
+ const result = await enhancedPostEdit(file, memoryKey, options);
148
+
149
+ return {
150
+ success: result.success,
151
+ file: result.file,
152
+ timestamp: result.timestamp,
153
+ formatted: true,
154
+ validated: result.success,
155
+ recommendations: 0,
156
+ enhanced: true,
157
+ legacy: true,
158
+ unified: true
159
+ };
160
+ }
161
+
162
+ // Run CLI if called directly
163
+ if (import.meta.url === `file://${process.argv[1]}`) {
164
+ enhancedHooksCLI().catch(error => {
165
+ console.error(`💥 Fatal error: ${error.message}`);
166
+ process.exit(1);
167
+ });
168
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * User Preference Manager - Usage Examples
3
+ *
4
+ * This file demonstrates how to use the UserPreferenceManager
5
+ * in different scenarios.
6
+ */ import { UserPreferenceManager, getDefaultPreferenceManager, createPreferenceManager, PreferenceError } from "./user-preference-manager";
7
+ /**
8
+ * Example 1: Basic Usage
9
+ */ async function basicUsageExample() {
10
+ console.log("=== Example 1: Basic Usage ===\n");
11
+ const prefs = new UserPreferenceManager();
12
+ // Initialize the preference manager
13
+ await prefs.initialize();
14
+ console.log("✓ Preference manager initialized");
15
+ // Set preferences
16
+ await prefs.setPreference("theme", "dark");
17
+ console.log("✓ Set theme to 'dark'");
18
+ await prefs.setPreference("language", "es");
19
+ console.log("✓ Set language to 'es'");
20
+ // Get preferences
21
+ const theme = prefs.getPreference("theme");
22
+ console.log(`✓ Retrieved theme: ${theme}`);
23
+ // Get with default value
24
+ const fontSize = prefs.getPreference("fontSize", 14);
25
+ console.log(`✓ Retrieved fontSize with default: ${fontSize}`);
26
+ console.log("\n");
27
+ }
28
+ /**
29
+ * Example 2: Using the Singleton Pattern
30
+ */ async function singletonExample() {
31
+ console.log("=== Example 2: Singleton Pattern ===\n");
32
+ const prefs1 = getDefaultPreferenceManager();
33
+ await prefs1.initialize();
34
+ await prefs1.setPreference("theme", "dark");
35
+ // Get the same instance elsewhere
36
+ const prefs2 = getDefaultPreferenceManager();
37
+ const theme = prefs2.getPreference("theme");
38
+ console.log(`✓ Retrieved theme from singleton: ${theme}`);
39
+ console.log("✓ Both instances share the same data");
40
+ console.log("\n");
41
+ }
42
+ /**
43
+ * Example 3: Event Handling
44
+ */ async function eventHandlingExample() {
45
+ console.log("=== Example 3: Event Handling ===\n");
46
+ const prefs = new UserPreferenceManager();
47
+ // Set up event listeners
48
+ prefs.on("initialized", (data)=>{
49
+ console.log(`✓ Event: initialized at ${data.timestamp}`);
50
+ });
51
+ prefs.on("preferenceChanged", (data)=>{
52
+ console.log(`✓ Event: ${data.key} changed from ${data.oldValue} to ${data.newValue}`);
53
+ });
54
+ prefs.on("preferencesSaved", (data)=>{
55
+ console.log(`✓ Event: Saved ${data.count} preferences to ${data.path}`);
56
+ });
57
+ await prefs.initialize();
58
+ await prefs.setPreference("theme", "dark");
59
+ await prefs.setPreference("theme", "light"); // Will trigger change event
60
+ console.log("\n");
61
+ }
62
+ /**
63
+ * Example 4: Error Handling
64
+ */ async function errorHandlingExample() {
65
+ console.log("=== Example 4: Error Handling ===\n");
66
+ const prefs = new UserPreferenceManager();
67
+ try {
68
+ // This will throw - not initialized
69
+ prefs.getPreference("theme");
70
+ } catch (error) {
71
+ if (error instanceof PreferenceError) {
72
+ console.log(`✓ Caught expected error: ${error.message}`);
73
+ }
74
+ }
75
+ await prefs.initialize();
76
+ try {
77
+ // This will throw - invalid key
78
+ await prefs.setPreference("", "value");
79
+ } catch (error) {
80
+ if (error instanceof PreferenceError) {
81
+ console.log(`✓ Caught expected error: ${error.message}`);
82
+ }
83
+ }
84
+ try {
85
+ // This will throw - undefined value
86
+ await prefs.setPreference("test", undefined);
87
+ } catch (error) {
88
+ if (error instanceof PreferenceError) {
89
+ console.log(`✓ Caught expected error: ${error.message}`);
90
+ }
91
+ }
92
+ console.log("\n");
93
+ }
94
+ /**
95
+ * Example 5: Custom Storage Path
96
+ */ async function customStorageExample() {
97
+ console.log("=== Example 5: Custom Storage Path ===\n");
98
+ const prefs = createPreferenceManager({
99
+ storagePath: "/tmp/custom-preferences.json",
100
+ autoSave: true,
101
+ cacheEnabled: true
102
+ });
103
+ await prefs.initialize();
104
+ console.log(`✓ Custom storage path: ${prefs.getStoragePath()}`);
105
+ await prefs.setPreference("customSetting", "value");
106
+ console.log("✓ Set custom preference (auto-saved)");
107
+ console.log("\n");
108
+ }
109
+ /**
110
+ * Example 6: Bulk Operations
111
+ */ async function bulkOperationsExample() {
112
+ console.log("=== Example 6: Bulk Operations ===\n");
113
+ const prefs = new UserPreferenceManager();
114
+ await prefs.initialize();
115
+ // Set multiple preferences
116
+ await prefs.setPreference("theme", "dark");
117
+ await prefs.setPreference("language", "en");
118
+ await prefs.setPreference("notifications", false);
119
+ // Get all preferences
120
+ const allPrefs = prefs.getAllPreferences();
121
+ console.log("✓ All preferences:", allPrefs);
122
+ // Check preference count
123
+ console.log(`✓ Total preferences: ${prefs.getPreferenceCount()}`);
124
+ // Check if preference exists
125
+ console.log(`✓ Has 'theme': ${prefs.hasPreference("theme")}`);
126
+ console.log(`✓ Has 'unknown': ${prefs.hasPreference("unknown")}`);
127
+ console.log("\n");
128
+ }
129
+ /**
130
+ * Example 7: Reset and Defaults
131
+ */ async function resetExample() {
132
+ console.log("=== Example 7: Reset and Defaults ===\n");
133
+ const prefs = new UserPreferenceManager();
134
+ await prefs.initialize();
135
+ // Modify some preferences
136
+ await prefs.setPreference("theme", "dark");
137
+ await prefs.setPreference("language", "es");
138
+ console.log("✓ Modified preferences");
139
+ console.log(` - Theme: ${prefs.getPreference("theme")}`);
140
+ console.log(` - Language: ${prefs.getPreference("language")}`);
141
+ // Reset to defaults
142
+ await prefs.reset();
143
+ console.log("✓ Reset to defaults");
144
+ console.log(` - Theme: ${prefs.getPreference("theme")}`);
145
+ console.log(` - Language: ${prefs.getPreference("language")}`);
146
+ console.log("\n");
147
+ }
148
+ /**
149
+ * Example 8: Manual Save/Load
150
+ */ async function manualSaveLoadExample() {
151
+ console.log("=== Example 8: Manual Save/Load ===\n");
152
+ // Create with auto-save disabled
153
+ const prefs = createPreferenceManager({
154
+ autoSave: false
155
+ });
156
+ await prefs.initialize();
157
+ // Set preferences (not auto-saved)
158
+ await prefs.setPreference("theme", "dark");
159
+ await prefs.setPreference("language", "es");
160
+ console.log("✓ Set preferences (not auto-saved)");
161
+ // Manually save
162
+ await prefs.save();
163
+ console.log("✓ Manually saved preferences");
164
+ // Create new instance and load
165
+ const prefs2 = createPreferenceManager({
166
+ storagePath: prefs.getStoragePath()
167
+ });
168
+ await prefs2.load();
169
+ console.log("✓ Loaded preferences into new instance");
170
+ console.log(` - Theme: ${prefs2.getPreference("theme")}`);
171
+ console.log(` - Language: ${prefs2.getPreference("language")}`);
172
+ console.log("\n");
173
+ }
174
+ /**
175
+ * Run all examples
176
+ */ async function runAllExamples() {
177
+ console.log("\n╔═══════════════════════════════════════════════╗");
178
+ console.log("║ User Preference Manager - Usage Examples ║");
179
+ console.log("╚═══════════════════════════════════════════════╝\n");
180
+ try {
181
+ await basicUsageExample();
182
+ await singletonExample();
183
+ await eventHandlingExample();
184
+ await errorHandlingExample();
185
+ await customStorageExample();
186
+ await bulkOperationsExample();
187
+ await resetExample();
188
+ await manualSaveLoadExample();
189
+ console.log("╔═══════════════════════════════════════════════╗");
190
+ console.log("║ All examples completed! ✓ ║");
191
+ console.log("╚═══════════════════════════════════════════════╝\n");
192
+ } catch (error) {
193
+ console.error("Error running examples:", error);
194
+ }
195
+ }
196
+ // Run examples if this file is executed directly
197
+ if (require.main === module) {
198
+ runAllExamples();
199
+ }
200
+ // Export for use in other modules
201
+ export { basicUsageExample, singletonExample, eventHandlingExample, errorHandlingExample, customStorageExample, bulkOperationsExample, resetExample, manualSaveLoadExample };
202
+
203
+ //# sourceMappingURL=example.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/preferences/example.ts"],"names":["UserPreferenceManager","getDefaultPreferenceManager","createPreferenceManager","PreferenceError","basicUsageExample","console","log","prefs","initialize","setPreference","theme","getPreference","fontSize","singletonExample","prefs1","prefs2","eventHandlingExample","on","data","timestamp","key","oldValue","newValue","count","path","errorHandlingExample","error","message","undefined","customStorageExample","storagePath","autoSave","cacheEnabled","getStoragePath","bulkOperationsExample","allPrefs","getAllPreferences","getPreferenceCount","hasPreference","resetExample","reset","manualSaveLoadExample","save","load","runAllExamples","require","main","module"],"mappings":"AAAA;;;;;CAKC,GAED,SACEA,qBAAqB,EACrBC,2BAA2B,EAC3BC,uBAAuB,EACvBC,eAAe,QACV,4BAA4B;AAEnC;;CAEC,GACD,eAAeC;IACbC,QAAQC,GAAG,CAAC;IAEZ,MAAMC,QAAQ,IAAIP;IAElB,oCAAoC;IACpC,MAAMO,MAAMC,UAAU;IACtBH,QAAQC,GAAG,CAAC;IAEZ,kBAAkB;IAClB,MAAMC,MAAME,aAAa,CAAC,SAAS;IACnCJ,QAAQC,GAAG,CAAC;IAEZ,MAAMC,MAAME,aAAa,CAAC,YAAY;IACtCJ,QAAQC,GAAG,CAAC;IAEZ,kBAAkB;IAClB,MAAMI,QAAQH,MAAMI,aAAa,CAAS;IAC1CN,QAAQC,GAAG,CAAC,CAAC,mBAAmB,EAAEI,OAAO;IAEzC,yBAAyB;IACzB,MAAME,WAAWL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