erosolar-cli 2.1.247 → 2.1.249

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.
@@ -5,14 +5,596 @@
5
5
  * - Government procedures (law enforcement, compliance)
6
6
  * - Infrastructure deployment (US, Ukraine, EU, Asia)
7
7
  * - Security deliverables (pentest reports, incident response)
8
- * - APT chain execution (kill-chain phases)
9
- * - Dual-RL refinement (self-improving execution)
8
+ * - Validation & error analysis (TypeScript, build, test, lint)
9
+ * - Hypothesis testing & failure recovery
10
+ * - Result verification (prevents hallucinated success)
10
11
  */
12
+ // ============================================================================
13
+ // TYPES - Error Analysis & Validation (from aiErrorFixer.ts, validationRunner.ts)
14
+ // ============================================================================
15
+ export var ErrorType;
16
+ (function (ErrorType) {
17
+ ErrorType["BUILD_ERROR"] = "build_error";
18
+ ErrorType["TEST_FAILURE"] = "test_failure";
19
+ ErrorType["TYPE_ERROR"] = "type_error";
20
+ ErrorType["LINT_ERROR"] = "lint_error";
21
+ ErrorType["IMPORT_ERROR"] = "import_error";
22
+ ErrorType["SYNTAX_ERROR"] = "syntax_error";
23
+ ErrorType["FILE_NOT_FOUND"] = "file_not_found";
24
+ ErrorType["PERMISSION_ERROR"] = "permission_error";
25
+ ErrorType["EDIT_CONFLICT"] = "edit_conflict";
26
+ ErrorType["NEWLINE_IN_STRING"] = "newline_in_string";
27
+ ErrorType["UNKNOWN"] = "unknown";
28
+ })(ErrorType || (ErrorType = {}));
29
+ // ============================================================================
30
+ // ERROR PATTERNS
31
+ // ============================================================================
32
+ const TS_ERROR_PATTERN = /([^\s:]+\.tsx?):(\d+):(\d+)\s*-\s*error\s+TS(\d+):\s*(.+)/gm;
33
+ const NPM_DEP_PATTERN = /(?:Cannot find|Module not found).*['"]([^'"]+)['"]/gm;
34
+ const TEST_FAIL_PATTERN = /FAIL\s+([^\n]+)/gm;
35
+ const FAILURE_INDICATORS = {
36
+ build: [/error\s+TS\d+/i, /SyntaxError/i, /Cannot find module/i, /error:\s+/i, /failed with exit code/i, /npm ERR!/i],
37
+ test: [/FAIL\s+/, /AssertionError/i, /Expected.*but got/i, /\d+ failing/i, /Error: expect/i],
38
+ runtime: [/TypeError:/i, /ReferenceError:/i, /RangeError:/i, /Uncaught/i, /ENOENT/i, /EACCES/i, /ETIMEDOUT/i],
39
+ userFeedback: [/doesn't work/i, /didn't work/i, /not working/i, /still broken/i, /wrong/i, /incorrect/i, /try again/i, /failed/i],
40
+ };
41
+ const OUTPUT_PATTERNS = {
42
+ git: {
43
+ success: [/\[.+\s+\w+\]/, /pushed/i, /merged/i, /On branch/i, /nothing to commit/i, /Already up to date/i],
44
+ failure: [/fatal:/i, /error:/i, /conflict/i, /rejected/i, /CONFLICT/, /Aborting/i],
45
+ },
46
+ npm: {
47
+ success: [/npm notice/i, /\+ .+@\d+\.\d+\.\d+/, /published/i],
48
+ failure: [/npm ERR!/i, /ERESOLVE/i, /E404/i, /EINTEGRITY/i],
49
+ },
50
+ command: {
51
+ success: [/^(success|completed|done|finished)/im, /successfully/i],
52
+ failure: [/^error/im, /^fatal/im, /failed/i, /command not found/i, /permission denied/i, /ENOENT/i, /EACCES/i],
53
+ },
54
+ };
55
+ // ============================================================================
56
+ // ERROR ANALYSIS CLASS (from aiErrorFixer.ts)
57
+ // ============================================================================
58
+ class ErrorAnalyzer {
59
+ analyzeOutput(output, command) {
60
+ const errors = [];
61
+ const outputType = this.detectOutputType(output, command);
62
+ if (outputType === 'typescript')
63
+ errors.push(...this.parseTypeScriptErrors(output));
64
+ else if (outputType === 'npm')
65
+ errors.push(...this.parseNpmErrors(output));
66
+ else if (outputType === 'test')
67
+ errors.push(...this.parseTestErrors(output));
68
+ else
69
+ errors.push(...this.parseGenericErrors(output));
70
+ for (const error of errors) {
71
+ error.suggestedFixes = this.generateFixes(error);
72
+ }
73
+ return errors;
74
+ }
75
+ formatForAI(errors) {
76
+ if (errors.length === 0)
77
+ return '';
78
+ const lines = ['', '═══ AI ERROR ANALYSIS ═══', ''];
79
+ for (let i = 0; i < Math.min(errors.length, 5); i++) {
80
+ const error = errors[i];
81
+ if (!error)
82
+ continue;
83
+ lines.push(`• ${error.errorType.toUpperCase()}: ${error.message.slice(0, 150)}`);
84
+ const loc = error.locations[0];
85
+ if (loc)
86
+ lines.push(` at ${loc.filePath}:${loc.lineNumber ?? '?'}`);
87
+ const bestFix = error.suggestedFixes[0];
88
+ if (bestFix)
89
+ lines.push(` FIX: ${bestFix.description}`);
90
+ lines.push('');
91
+ }
92
+ if (errors.length > 5)
93
+ lines.push(`... and ${errors.length - 5} more errors`);
94
+ return lines.join('\n');
95
+ }
96
+ detectOutputType(output, command) {
97
+ const outputLower = output.toLowerCase();
98
+ const commandLower = (command ?? '').toLowerCase();
99
+ if (commandLower.includes('tsc') || commandLower.includes('typescript'))
100
+ return 'typescript';
101
+ if (commandLower.includes('test') || commandLower.includes('jest'))
102
+ return 'test';
103
+ if (commandLower.includes('npm') || commandLower.includes('yarn'))
104
+ return 'npm';
105
+ if (outputLower.includes('error ts') || output.includes('.ts:'))
106
+ return 'typescript';
107
+ if (outputLower.includes('npm err!'))
108
+ return 'npm';
109
+ return 'generic';
110
+ }
111
+ parseTypeScriptErrors(output) {
112
+ const errors = [];
113
+ const regex = new RegExp(TS_ERROR_PATTERN.source, 'gm');
114
+ let match;
115
+ while ((match = regex.exec(output)) !== null) {
116
+ const [, file, line, col, code, msg] = match;
117
+ if (!file || !code || !msg)
118
+ continue;
119
+ errors.push({
120
+ errorType: ErrorType.TYPE_ERROR,
121
+ message: `TS${code}: ${msg}`,
122
+ rawOutput: match[0],
123
+ locations: [{ filePath: file, lineNumber: line ? parseInt(line, 10) : undefined, column: col ? parseInt(col, 10) : undefined }],
124
+ suggestedFixes: [],
125
+ relatedErrors: [],
126
+ metadata: { tsCode: code },
127
+ });
128
+ }
129
+ return errors;
130
+ }
131
+ parseNpmErrors(output) {
132
+ const errors = [];
133
+ const regex = new RegExp(NPM_DEP_PATTERN.source, 'gm');
134
+ let match;
135
+ while ((match = regex.exec(output)) !== null) {
136
+ const [, dep] = match;
137
+ if (!dep)
138
+ continue;
139
+ errors.push({
140
+ errorType: ErrorType.IMPORT_ERROR,
141
+ message: `Missing dependency: ${dep}`,
142
+ rawOutput: match[0],
143
+ locations: [],
144
+ suggestedFixes: [],
145
+ relatedErrors: [],
146
+ metadata: { missingDep: dep },
147
+ });
148
+ }
149
+ return errors;
150
+ }
151
+ parseTestErrors(output) {
152
+ const errors = [];
153
+ const regex = new RegExp(TEST_FAIL_PATTERN.source, 'gm');
154
+ let match;
155
+ while ((match = regex.exec(output)) !== null) {
156
+ const [, file] = match;
157
+ if (!file)
158
+ continue;
159
+ errors.push({
160
+ errorType: ErrorType.TEST_FAILURE,
161
+ message: `Test failed: ${file}`,
162
+ rawOutput: match[0],
163
+ locations: [{ filePath: file.trim() }],
164
+ suggestedFixes: [],
165
+ relatedErrors: [],
166
+ metadata: {},
167
+ });
168
+ }
169
+ return errors;
170
+ }
171
+ parseGenericErrors(output) {
172
+ const errors = [];
173
+ const errorLines = [];
174
+ for (const line of output.split('\n')) {
175
+ const lineLower = line.toLowerCase();
176
+ if (lineLower.includes('error:') || lineLower.includes('failed:') || lineLower.includes('exception:') || lineLower.includes('fatal:')) {
177
+ errorLines.push(line.trim());
178
+ }
179
+ }
180
+ if (errorLines.length > 0 && errorLines[0]) {
181
+ errors.push({
182
+ errorType: ErrorType.UNKNOWN,
183
+ message: errorLines[0].slice(0, 200),
184
+ rawOutput: errorLines.slice(0, 5).join('\n'),
185
+ locations: [],
186
+ suggestedFixes: [],
187
+ relatedErrors: errorLines.slice(1, 5),
188
+ metadata: {},
189
+ });
190
+ }
191
+ return errors;
192
+ }
193
+ generateFixes(error) {
194
+ const fixes = [];
195
+ const loc = error.locations[0];
196
+ if (error.errorType === ErrorType.TYPE_ERROR && loc) {
197
+ const tsCode = String(error.metadata['tsCode'] ?? '');
198
+ if (tsCode === '2304') {
199
+ const nameMatch = error.message.match(/Cannot find name '([^']+)'/);
200
+ if (nameMatch?.[1]) {
201
+ fixes.push({
202
+ description: `Add import for '${nameMatch[1]}'`,
203
+ filePath: loc.filePath,
204
+ oldContent: '',
205
+ newContent: `import { ${nameMatch[1]} } from './${nameMatch[1]}';`,
206
+ confidence: 0.6,
207
+ autoApplicable: false,
208
+ requiresConfirmation: true,
209
+ });
210
+ }
211
+ }
212
+ if (tsCode === '6133') {
213
+ const varMatch = error.message.match(/'([^']+)' is declared but/);
214
+ if (varMatch?.[1]) {
215
+ fixes.push({
216
+ description: `Prefix '${varMatch[1]}' with underscore`,
217
+ filePath: loc.filePath,
218
+ oldContent: varMatch[1],
219
+ newContent: `_${varMatch[1]}`,
220
+ confidence: 0.8,
221
+ autoApplicable: true,
222
+ requiresConfirmation: false,
223
+ });
224
+ }
225
+ }
226
+ }
227
+ if (error.errorType === ErrorType.IMPORT_ERROR) {
228
+ const missingDep = String(error.metadata['missingDep'] ?? '');
229
+ if (missingDep) {
230
+ fixes.push({
231
+ description: `Install: npm install ${missingDep}`,
232
+ filePath: 'package.json',
233
+ oldContent: '',
234
+ newContent: '',
235
+ confidence: 0.9,
236
+ autoApplicable: false,
237
+ requiresConfirmation: true,
238
+ });
239
+ }
240
+ }
241
+ return fixes;
242
+ }
243
+ }
244
+ // ============================================================================
245
+ // HYPOTHESIS ENGINE (from hypothesisEngine.ts)
246
+ // ============================================================================
247
+ class HypothesisEngine {
248
+ hypotheses = new Map();
249
+ maxHypotheses;
250
+ constructor(maxHypotheses = 5) {
251
+ this.maxHypotheses = maxHypotheses;
252
+ }
253
+ generateHypothesis(description, initialEvidence = []) {
254
+ const id = `hyp_${Date.now()}_${Math.random().toString(36).substring(7)}`;
255
+ const hypothesis = {
256
+ id,
257
+ description,
258
+ confidence: this.calculateConfidence(initialEvidence),
259
+ evidence: initialEvidence,
260
+ status: 'pending',
261
+ };
262
+ this.hypotheses.set(id, hypothesis);
263
+ this.pruneHypotheses();
264
+ return hypothesis;
265
+ }
266
+ addEvidence(hypothesisId, evidence) {
267
+ const hypothesis = this.hypotheses.get(hypothesisId);
268
+ if (!hypothesis)
269
+ throw new Error(`Hypothesis ${hypothesisId} not found`);
270
+ hypothesis.evidence.push(evidence);
271
+ hypothesis.confidence = this.calculateConfidence(hypothesis.evidence);
272
+ }
273
+ getBestHypothesis() {
274
+ let best = null;
275
+ let highestConfidence = -Infinity;
276
+ for (const hypothesis of this.hypotheses.values()) {
277
+ if (hypothesis.status !== 'rejected' && hypothesis.confidence > highestConfidence) {
278
+ highestConfidence = hypothesis.confidence;
279
+ best = hypothesis;
280
+ }
281
+ }
282
+ return best;
283
+ }
284
+ getAllHypotheses() {
285
+ return Array.from(this.hypotheses.values()).sort((a, b) => b.confidence - a.confidence);
286
+ }
287
+ clear() {
288
+ this.hypotheses.clear();
289
+ }
290
+ calculateConfidence(evidence) {
291
+ if (evidence.length === 0)
292
+ return 0.5;
293
+ const totalWeight = evidence.reduce((sum, e) => sum + Math.abs(e.weight), 0);
294
+ if (totalWeight === 0)
295
+ return 0.5;
296
+ const weightedSum = evidence.reduce((sum, e) => sum + e.weight, 0);
297
+ return Math.max(0, Math.min(1, 0.5 + (weightedSum / totalWeight) * 0.5));
298
+ }
299
+ pruneHypotheses() {
300
+ if (this.hypotheses.size <= this.maxHypotheses)
301
+ return;
302
+ const sorted = Array.from(this.hypotheses.entries()).sort(([, a], [, b]) => a.confidence - b.confidence);
303
+ const lowest = sorted[0];
304
+ if (lowest)
305
+ this.hypotheses.delete(lowest[0]);
306
+ }
307
+ }
308
+ // ============================================================================
309
+ // FAILURE DETECTION (from failureRecovery.ts)
310
+ // ============================================================================
311
+ function detectFailure(output, context) {
312
+ for (const pattern of FAILURE_INDICATORS.build) {
313
+ if (pattern.test(output)) {
314
+ return { type: 'build', severity: 'critical', message: extractErrorMessage(output, pattern), timestamp: new Date().toISOString() };
315
+ }
316
+ }
317
+ for (const pattern of FAILURE_INDICATORS.test) {
318
+ if (pattern.test(output)) {
319
+ return { type: 'test', severity: 'major', message: extractErrorMessage(output, pattern), timestamp: new Date().toISOString() };
320
+ }
321
+ }
322
+ for (const pattern of FAILURE_INDICATORS.runtime) {
323
+ if (pattern.test(output)) {
324
+ return { type: 'tool', severity: 'major', message: extractErrorMessage(output, pattern), timestamp: new Date().toISOString() };
325
+ }
326
+ }
327
+ if (context.userMessage) {
328
+ for (const pattern of FAILURE_INDICATORS.userFeedback) {
329
+ if (pattern.test(context.userMessage)) {
330
+ return { type: 'user-feedback', severity: 'major', message: context.userMessage.slice(0, 200), timestamp: new Date().toISOString() };
331
+ }
332
+ }
333
+ }
334
+ return null;
335
+ }
336
+ function extractErrorMessage(output, pattern) {
337
+ const match = output.match(pattern);
338
+ if (!match)
339
+ return 'Unknown error';
340
+ const lines = output.split('\n');
341
+ for (let i = 0; i < lines.length; i++) {
342
+ if (pattern.test(lines[i])) {
343
+ return lines.slice(i, Math.min(lines.length, i + 3)).join('\n').slice(0, 300);
344
+ }
345
+ }
346
+ return match[0].slice(0, 200);
347
+ }
348
+ // ============================================================================
349
+ // RESULT VERIFICATION (from resultVerification.ts)
350
+ // ============================================================================
351
+ function formatVerifiedResult(result) {
352
+ if (result.status === 'VERIFIED_SUCCESS')
353
+ return result.details || result.summary;
354
+ const lines = [];
355
+ switch (result.status) {
356
+ case 'VERIFIED_FAILURE':
357
+ lines.push('═══ FAILED ═══');
358
+ break;
359
+ case 'UNVERIFIED':
360
+ lines.push('═══ UNVERIFIED ═══');
361
+ break;
362
+ case 'PARTIAL_SUCCESS':
363
+ lines.push('═══ PARTIAL SUCCESS ═══');
364
+ break;
365
+ case 'REQUIRES_USER_ACTION':
366
+ lines.push('═══ ACTION REQUIRED ═══');
367
+ break;
368
+ }
369
+ lines.push('', result.summary, '');
370
+ if (result.verificationChecks) {
371
+ const failedChecks = result.verificationChecks.filter(c => !c.passed);
372
+ if (failedChecks.length > 0) {
373
+ lines.push('Failed checks:');
374
+ for (const check of failedChecks) {
375
+ lines.push(` ✗ ${check.check}${check.details ? `: ${check.details}` : ''}`);
376
+ }
377
+ lines.push('');
378
+ }
379
+ }
380
+ if (result.details)
381
+ lines.push(result.details, '');
382
+ if (result.suggestedActions?.length) {
383
+ lines.push('Suggested actions:');
384
+ for (const action of result.suggestedActions)
385
+ lines.push(` → ${action}`);
386
+ }
387
+ return lines.join('\n');
388
+ }
389
+ function analyzeOutput(output, patterns, exitCode) {
390
+ const normalizedOutput = output.normalize('NFC');
391
+ for (const pattern of patterns.failure) {
392
+ if (pattern.test(normalizedOutput))
393
+ return { isSuccess: false, isFailure: true, confidence: 'high' };
394
+ }
395
+ for (const pattern of patterns.success) {
396
+ if (pattern.test(normalizedOutput))
397
+ return { isSuccess: true, isFailure: false, confidence: 'high' };
398
+ }
399
+ if (exitCode !== undefined) {
400
+ if (exitCode !== 0)
401
+ return { isSuccess: false, isFailure: true, confidence: 'high' };
402
+ return { isSuccess: false, isFailure: false, confidence: 'low' };
403
+ }
404
+ return { isSuccess: false, isFailure: false, confidence: 'low' };
405
+ }
406
+ // ============================================================================
407
+ // TOOL CREATION
408
+ // ============================================================================
11
409
  function createOrchestrationTools(options = {}) {
12
410
  const enableAll = !options.enableGovernment && !options.enableInfrastructure &&
13
- !options.enableSecurity && !options.enableAPT;
411
+ !options.enableSecurity && !options.enableAPT &&
412
+ !options.enableValidation && !options.enableHypothesis && !options.enableRecovery;
14
413
  const tools = [];
15
- // Government procedures tool
414
+ // ====== VALIDATION & ERROR ANALYSIS TOOL ======
415
+ if (enableAll || options.enableValidation) {
416
+ const errorAnalyzer = new ErrorAnalyzer();
417
+ tools.push({
418
+ name: 'analyze_errors',
419
+ description: `Analyze command output for errors and generate fix suggestions.
420
+
421
+ Capabilities:
422
+ - Parse TypeScript, npm, test, and generic errors
423
+ - Extract error locations (file, line, column)
424
+ - Generate confidence-scored fix suggestions
425
+ - Format errors for AI consumption`,
426
+ parameters: {
427
+ type: 'object',
428
+ properties: {
429
+ output: { type: 'string', description: 'Command output to analyze' },
430
+ command: { type: 'string', description: 'Command that produced the output (for context)' },
431
+ format: { type: 'string', enum: ['detailed', 'ai', 'summary'], description: 'Output format' },
432
+ },
433
+ required: ['output'],
434
+ },
435
+ async handler(params) {
436
+ const output = params['output'];
437
+ const command = params['command'];
438
+ const format = params['format'] || 'detailed';
439
+ const errors = errorAnalyzer.analyzeOutput(output, command);
440
+ if (format === 'ai') {
441
+ return errorAnalyzer.formatForAI(errors);
442
+ }
443
+ else if (format === 'summary') {
444
+ return `Found ${errors.length} error(s):\n` +
445
+ errors.slice(0, 5).map(e => `• ${e.errorType}: ${e.message.slice(0, 80)}`).join('\n');
446
+ }
447
+ return JSON.stringify(errors, null, 2);
448
+ },
449
+ });
450
+ tools.push({
451
+ name: 'verify_result',
452
+ description: `Verify operation results to prevent hallucinated success.
453
+
454
+ Checks:
455
+ - Pattern matching against known success/failure indicators
456
+ - Exit code analysis
457
+ - Unicode normalization to prevent spoofing
458
+ - Negative context detection`,
459
+ parameters: {
460
+ type: 'object',
461
+ properties: {
462
+ output: { type: 'string', description: 'Operation output to verify' },
463
+ operation: { type: 'string', enum: ['git', 'npm', 'command'], description: 'Type of operation' },
464
+ exitCode: { type: 'number', description: 'Exit code if available' },
465
+ },
466
+ required: ['output', 'operation'],
467
+ },
468
+ async handler(params) {
469
+ const output = params['output'];
470
+ const operation = params['operation'];
471
+ const exitCode = params['exitCode'];
472
+ const patterns = OUTPUT_PATTERNS[operation] || OUTPUT_PATTERNS.command;
473
+ const analysis = analyzeOutput(output, patterns, exitCode);
474
+ const result = {
475
+ status: analysis.isSuccess ? 'VERIFIED_SUCCESS' :
476
+ analysis.isFailure ? 'VERIFIED_FAILURE' : 'UNVERIFIED',
477
+ summary: analysis.isSuccess ? 'Operation succeeded' :
478
+ analysis.isFailure ? 'Operation failed' : 'Cannot verify outcome',
479
+ details: output.slice(0, 500),
480
+ verifiedAt: new Date().toISOString(),
481
+ };
482
+ return formatVerifiedResult(result);
483
+ },
484
+ });
485
+ }
486
+ // ====== HYPOTHESIS TESTING TOOL ======
487
+ if (enableAll || options.enableHypothesis) {
488
+ const hypothesisEngine = new HypothesisEngine(10);
489
+ tools.push({
490
+ name: 'hypothesis',
491
+ description: `Multi-hypothesis reasoning for bug analysis and problem solving.
492
+
493
+ Operations:
494
+ - generate: Create a new hypothesis with initial evidence
495
+ - add_evidence: Add supporting/contradicting evidence
496
+ - get_best: Get highest-confidence hypothesis
497
+ - list_all: List all hypotheses sorted by confidence
498
+ - clear: Reset all hypotheses`,
499
+ parameters: {
500
+ type: 'object',
501
+ properties: {
502
+ action: { type: 'string', enum: ['generate', 'add_evidence', 'get_best', 'list_all', 'clear'] },
503
+ description: { type: 'string', description: 'Hypothesis description (for generate)' },
504
+ hypothesisId: { type: 'string', description: 'Hypothesis ID (for add_evidence)' },
505
+ evidence: {
506
+ type: 'object',
507
+ properties: {
508
+ type: { type: 'string', enum: ['observation', 'data', 'test_result', 'user_feedback'] },
509
+ content: { type: 'string' },
510
+ weight: { type: 'number', description: '-1 to 1, positive supports, negative contradicts' },
511
+ },
512
+ },
513
+ },
514
+ required: ['action'],
515
+ },
516
+ async handler(params) {
517
+ const action = params['action'];
518
+ switch (action) {
519
+ case 'generate': {
520
+ const description = params['description'];
521
+ if (!description)
522
+ return 'Error: description required';
523
+ const hypothesis = hypothesisEngine.generateHypothesis(description);
524
+ return JSON.stringify(hypothesis, null, 2);
525
+ }
526
+ case 'add_evidence': {
527
+ const id = params['hypothesisId'];
528
+ const evidenceData = params['evidence'];
529
+ if (!id || !evidenceData)
530
+ return 'Error: hypothesisId and evidence required';
531
+ const evidence = {
532
+ type: evidenceData.type,
533
+ content: evidenceData.content,
534
+ weight: evidenceData.weight,
535
+ timestamp: new Date(),
536
+ };
537
+ hypothesisEngine.addEvidence(id, evidence);
538
+ return `Evidence added to hypothesis ${id}`;
539
+ }
540
+ case 'get_best': {
541
+ const best = hypothesisEngine.getBestHypothesis();
542
+ return best ? JSON.stringify(best, null, 2) : 'No hypotheses available';
543
+ }
544
+ case 'list_all': {
545
+ const all = hypothesisEngine.getAllHypotheses();
546
+ return JSON.stringify(all, null, 2);
547
+ }
548
+ case 'clear': {
549
+ hypothesisEngine.clear();
550
+ return 'All hypotheses cleared';
551
+ }
552
+ default:
553
+ return `Unknown action: ${action}`;
554
+ }
555
+ },
556
+ });
557
+ }
558
+ // ====== FAILURE DETECTION & RECOVERY TOOL ======
559
+ if (enableAll || options.enableRecovery) {
560
+ tools.push({
561
+ name: 'detect_failure',
562
+ description: `Detect failures in output and suggest recovery strategies.
563
+
564
+ Detects:
565
+ - Build failures (TypeScript, syntax, module errors)
566
+ - Test failures (Jest, assertion errors)
567
+ - Runtime errors (TypeError, ReferenceError, etc.)
568
+ - User feedback indicating failure`,
569
+ parameters: {
570
+ type: 'object',
571
+ properties: {
572
+ output: { type: 'string', description: 'Output to analyze for failures' },
573
+ userMessage: { type: 'string', description: 'User message (for feedback detection)' },
574
+ },
575
+ required: ['output'],
576
+ },
577
+ async handler(params) {
578
+ const output = params['output'];
579
+ const userMessage = params['userMessage'];
580
+ const failure = detectFailure(output, { userMessage });
581
+ if (!failure) {
582
+ return JSON.stringify({ detected: false, message: 'No failure detected' });
583
+ }
584
+ return JSON.stringify({
585
+ detected: true,
586
+ failure,
587
+ suggestedRecovery: [
588
+ `Identify root cause of ${failure.type} failure`,
589
+ 'Review the error message for specific guidance',
590
+ 'Check for similar patterns in codebase',
591
+ 'Consider alternative approaches if current fails repeatedly',
592
+ ],
593
+ }, null, 2);
594
+ },
595
+ });
596
+ }
597
+ // ====== GOVERNMENT PROCEDURES TOOL ======
16
598
  if (enableAll || options.enableGovernment) {
17
599
  tools.push({
18
600
  name: 'gov_procedures',
@@ -29,29 +611,14 @@ Provides:
29
611
  properties: {
30
612
  action: {
31
613
  type: 'string',
32
- enum: [
33
- 'get_contacts', 'get_legal_frameworks', 'get_reporting_requirements',
34
- 'generate_incident_report', 'generate_evidence_form',
35
- ],
36
- description: 'Action to perform',
614
+ enum: ['get_contacts', 'get_legal_frameworks', 'get_reporting_requirements', 'generate_incident_report', 'generate_evidence_form'],
37
615
  },
38
616
  agencyType: {
39
617
  type: 'string',
40
- enum: [
41
- 'federal-le', 'state-le', 'local-le', 'intelligence',
42
- 'military', 'regulatory', 'international', 'cisa', 'nist', 'contractor',
43
- ],
44
- description: 'Type of agency',
45
- },
46
- incidentType: {
47
- type: 'string',
48
- description: 'Type of incident for reporting',
49
- },
50
- classification: {
51
- type: 'string',
52
- enum: ['unclassified', 'cui', 'confidential', 'secret', 'top-secret', 'ts-sci'],
53
- description: 'Classification level',
618
+ enum: ['federal-le', 'state-le', 'local-le', 'intelligence', 'military', 'regulatory', 'international', 'cisa', 'nist', 'contractor'],
54
619
  },
620
+ incidentType: { type: 'string' },
621
+ classification: { type: 'string', enum: ['unclassified', 'cui', 'confidential', 'secret', 'top-secret', 'ts-sci'] },
55
622
  },
56
623
  required: ['action'],
57
624
  },
@@ -88,7 +655,7 @@ Provides:
88
655
  },
89
656
  });
90
657
  }
91
- // Infrastructure deployment tool
658
+ // ====== INFRASTRUCTURE DEPLOYMENT TOOL ======
92
659
  if (enableAll || options.enableInfrastructure) {
93
660
  tools.push({
94
661
  name: 'infrastructure',
@@ -104,27 +671,10 @@ Includes:
104
671
  parameters: {
105
672
  type: 'object',
106
673
  properties: {
107
- action: {
108
- type: 'string',
109
- enum: [
110
- 'get_stack', 'list_templates', 'generate_deployment',
111
- 'generate_teardown', 'generate_opsec_checklist',
112
- ],
113
- description: 'Action to perform',
114
- },
115
- region: {
116
- type: 'string',
117
- enum: ['us', 'ukraine', 'eu', 'asia', 'global'],
118
- description: 'Operational region',
119
- },
120
- stackId: {
121
- type: 'string',
122
- description: 'Infrastructure stack ID',
123
- },
124
- templateId: {
125
- type: 'string',
126
- description: 'Auto-execution template ID',
127
- },
674
+ action: { type: 'string', enum: ['get_stack', 'list_templates', 'generate_deployment', 'generate_teardown', 'generate_opsec_checklist'] },
675
+ region: { type: 'string', enum: ['us', 'ukraine', 'eu', 'asia', 'global'] },
676
+ stackId: { type: 'string' },
677
+ templateId: { type: 'string' },
128
678
  },
129
679
  required: ['action'],
130
680
  },
@@ -165,7 +715,7 @@ Includes:
165
715
  },
166
716
  });
167
717
  }
168
- // Security deliverables tool
718
+ // ====== SECURITY DELIVERABLES TOOL ======
169
719
  if (enableAll || options.enableSecurity) {
170
720
  tools.push({
171
721
  name: 'security_deliverable',
@@ -185,32 +735,12 @@ Types:
185
735
  properties: {
186
736
  type: {
187
737
  type: 'string',
188
- enum: [
189
- 'pentest-report', 'incident-response', 'security-controls',
190
- 'training-module', 'compliance-audit', 'threat-assessment',
191
- 'apt-analysis', 'vulnerability-report', 'infrastructure-assessment',
192
- 'persistence-procedures', 'red-team-playbook',
193
- ],
194
- description: 'Type of deliverable',
195
- },
196
- title: {
197
- type: 'string',
198
- description: 'Title for the deliverable',
199
- },
200
- scope: {
201
- type: 'string',
202
- description: 'Scope description',
203
- },
204
- findings: {
205
- type: 'array',
206
- items: { type: 'string' },
207
- description: 'List of findings to include',
208
- },
209
- format: {
210
- type: 'string',
211
- enum: ['markdown', 'json', 'html'],
212
- description: 'Output format',
738
+ enum: ['pentest-report', 'incident-response', 'security-controls', 'training-module', 'compliance-audit', 'threat-assessment', 'apt-analysis', 'vulnerability-report', 'infrastructure-assessment', 'persistence-procedures', 'red-team-playbook'],
213
739
  },
740
+ title: { type: 'string' },
741
+ scope: { type: 'string' },
742
+ findings: { type: 'array', items: { type: 'string' } },
743
+ format: { type: 'string', enum: ['markdown', 'json', 'html'] },
214
744
  },
215
745
  required: ['type'],
216
746
  },
@@ -221,7 +751,6 @@ Types:
221
751
  const title = params['title'];
222
752
  const scope = params['scope'];
223
753
  const format = params['format'];
224
- // Generate deliverable with minimal context
225
754
  const deliverable = await generator.generate(deliverableType, {
226
755
  exitReason: 'complete',
227
756
  finalResponse: title || 'Generated Deliverable',
@@ -253,31 +782,27 @@ Types:
253
782
  },
254
783
  limitations: [],
255
784
  recommendations: [],
256
- }, [], {
257
- customTitle: title,
258
- constraints: scope ? [scope] : undefined,
259
- });
260
- // Export in requested format
785
+ }, [], { customTitle: title, constraints: scope ? [scope] : undefined });
261
786
  switch (format || 'markdown') {
262
- case 'json':
263
- return sec.exportToJSON(deliverable);
264
- case 'html':
265
- return sec.exportToHTML(deliverable);
266
- default:
267
- return sec.exportToMarkdown(deliverable);
787
+ case 'json': return sec.exportToJSON(deliverable);
788
+ case 'html': return sec.exportToHTML(deliverable);
789
+ default: return sec.exportToMarkdown(deliverable);
268
790
  }
269
791
  },
270
792
  });
271
793
  }
272
794
  return {
273
795
  id: 'orchestration-tools',
274
- description: 'Unified orchestration for government, infrastructure, security, and APT operations',
796
+ description: 'Unified orchestration: gov, infra, security, validation, hypothesis, recovery',
275
797
  tools,
276
798
  };
277
799
  }
800
+ // ============================================================================
801
+ // CAPABILITY MODULE
802
+ // ============================================================================
278
803
  export class OrchestrationCapabilityModule {
279
804
  id = 'capability.orchestration';
280
- description = 'Unified orchestration for government, infrastructure, security, and APT operations';
805
+ description = 'Unified orchestration for gov, infra, security, validation, hypothesis testing, and failure recovery';
281
806
  options;
282
807
  constructor(options = {}) {
283
808
  this.options = options;
@@ -295,4 +820,8 @@ export class OrchestrationCapabilityModule {
295
820
  };
296
821
  }
297
822
  }
823
+ // ============================================================================
824
+ // EXPORTS - For direct usage
825
+ // ============================================================================
826
+ export { ErrorAnalyzer, HypothesisEngine, detectFailure, formatVerifiedResult, analyzeOutput };
298
827
  //# sourceMappingURL=orchestrationCapability.js.map