opencroc 0.6.1 → 1.3.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.
package/dist/index.d.ts CHANGED
@@ -15,6 +15,10 @@ interface OpenCrocConfig {
15
15
  steps?: PipelineStep[];
16
16
  /** Self-healing configuration */
17
17
  selfHealing?: SelfHealingConfig;
18
+ /** Test execution hooks (setup/auth/teardown) */
19
+ execution?: ExecutionConfig;
20
+ /** Runtime infrastructure generation config */
21
+ runtime?: RuntimeConfig;
18
22
  /** Report configuration */
19
23
  report?: ReportConfig;
20
24
  }
@@ -33,12 +37,62 @@ interface PlaywrightOverrides {
33
37
  baseURL?: string;
34
38
  headless?: boolean;
35
39
  timeout?: number;
40
+ /** Number of parallel workers (default: 2, CI: 4) */
41
+ workers?: number;
42
+ /** Retry count on failure (default: 0, CI: 1) */
43
+ retries?: number;
44
+ /** Action timeout in ms (default: 10000) */
45
+ actionTimeout?: number;
46
+ /** Navigation timeout in ms */
47
+ navigationTimeout?: number;
48
+ }
49
+ interface RuntimeConfig {
50
+ /** Authentication strategy */
51
+ auth?: {
52
+ /** Login API URL for credential-based auth */
53
+ loginUrl?: string;
54
+ /** Credentials for automatic auth setup */
55
+ username?: string;
56
+ password?: string;
57
+ /** Storage state file path (default: playwright/.auth/user.json) */
58
+ storageStatePath?: string;
59
+ };
60
+ /** Database seed/cleanup configuration */
61
+ db?: {
62
+ /** Backend seed endpoint (e.g. /internal/e2e/seed) */
63
+ seedEndpoint?: string;
64
+ /** Backend cleanup endpoint (e.g. /internal/e2e/cleanup) */
65
+ cleanupEndpoint?: string;
66
+ /** SQL file to execute for seeding */
67
+ seedFile?: string;
68
+ /** SQL file to execute for cleanup */
69
+ cleanupFile?: string;
70
+ };
71
+ /** Test log management endpoint */
72
+ logEndpoint?: string;
73
+ /** Additional Playwright projects beyond the defaults */
74
+ extraProjects?: Array<{
75
+ name: string;
76
+ testMatch: string;
77
+ dependencies?: string[];
78
+ useAuth?: boolean;
79
+ }>;
36
80
  }
37
81
  interface SelfHealingConfig {
38
82
  enabled?: boolean;
39
83
  maxIterations?: number;
40
84
  mode?: 'config-only' | 'config-and-source';
41
85
  }
86
+ type HookConfig = string | {
87
+ command: string;
88
+ args?: string[];
89
+ cwd?: string;
90
+ };
91
+ interface ExecutionConfig {
92
+ setupHook?: HookConfig;
93
+ authHook?: HookConfig;
94
+ teardownHook?: HookConfig;
95
+ }
42
96
  interface ReportConfig {
43
97
  format?: ('html' | 'json' | 'markdown')[];
44
98
  outputDir?: string;
@@ -193,6 +247,264 @@ interface FixOutcome {
193
247
  fixedItems: string[];
194
248
  rolledBack: boolean;
195
249
  }
250
+ type FixScope = 'config-only' | 'config-and-source';
251
+ interface DialogLoopConfig {
252
+ maxIterations?: number;
253
+ pollIntervalMs?: number;
254
+ sameErrorThreshold?: number;
255
+ autoRerunOnFix?: boolean;
256
+ }
257
+ interface TestFailureInfo {
258
+ title: string;
259
+ error: string;
260
+ attribution?: AIAttributionResult;
261
+ }
262
+ interface IterationResult {
263
+ iteration: number;
264
+ totalTests: number;
265
+ passed: number;
266
+ failed: number;
267
+ failedTests: string[];
268
+ fixesApplied: string[];
269
+ durationMs: number;
270
+ }
271
+ interface DialogLoopSummary {
272
+ iterations: IterationResult[];
273
+ finalPassed: number;
274
+ finalFailed: number;
275
+ totalFixesApplied: number;
276
+ success: boolean;
277
+ }
278
+ interface ControlledFixOptions {
279
+ scope?: FixScope;
280
+ dryRun?: boolean;
281
+ verify?: boolean;
282
+ reportDir?: string;
283
+ }
284
+ interface ControlledFixOutcome {
285
+ success: boolean;
286
+ scope: FixScope;
287
+ fixedItems: string[];
288
+ rolledBack: boolean;
289
+ prUrl?: string;
290
+ error?: string;
291
+ }
292
+ interface AIAttributionResult {
293
+ testName: string;
294
+ rootCause: string;
295
+ category: 'frontend' | 'backend' | 'network' | 'environment' | 'test-script';
296
+ severity: 'critical' | 'high' | 'medium' | 'low';
297
+ fixSuggestion: {
298
+ description: string;
299
+ filePath: string;
300
+ codePatch: string;
301
+ };
302
+ confidence: number;
303
+ }
304
+ interface AutoFixPROptions {
305
+ branchPrefix?: string;
306
+ baseBranch?: string;
307
+ draftOnly?: boolean;
308
+ }
309
+ interface AutoFixPRResult {
310
+ prUrl: string;
311
+ branch: string;
312
+ patchFile: string;
313
+ }
314
+ type FailureCategory = 'backend-5xx' | 'mixed-5xx' | 'slow-api' | 'log-fail' | 'log-timeout' | 'frontend-load' | 'other';
315
+ interface TestResultRecord {
316
+ title: string;
317
+ status: 'passed' | 'failed' | 'skipped' | 'timedOut';
318
+ duration: number;
319
+ error?: string;
320
+ logCompletion?: LogCompletionRecord;
321
+ }
322
+ interface LogCompletionRecord {
323
+ candidateCount: number;
324
+ succeeded: Array<{
325
+ method: string;
326
+ path: string;
327
+ }>;
328
+ failed: Array<{
329
+ method: string;
330
+ path: string;
331
+ }>;
332
+ timedOut: Array<{
333
+ method: string;
334
+ path: string;
335
+ }>;
336
+ }
337
+ interface FailureSummary {
338
+ totalFailed: number;
339
+ backend5xx: number;
340
+ mixed5xx: number;
341
+ slowApi: number;
342
+ logFail: number;
343
+ logTimeout: number;
344
+ frontendLoad: number;
345
+ other: number;
346
+ }
347
+ interface BackendDomainItem {
348
+ domain: string;
349
+ tests: string[];
350
+ endpoints: string[];
351
+ }
352
+ interface LogCompletionSummary {
353
+ totalCandidates: number;
354
+ succeeded: number;
355
+ failed: number;
356
+ timedOut: number;
357
+ matchRate: number;
358
+ effectiveRate: number;
359
+ timedOutTop5: Array<{
360
+ method: string;
361
+ path: string;
362
+ occurrences: number;
363
+ }>;
364
+ }
365
+ interface WorkorderItem {
366
+ index: number;
367
+ domain: string;
368
+ priority: 'P0' | 'P1' | 'P2';
369
+ tests: string[];
370
+ endpoints: string[];
371
+ objective: string;
372
+ acceptanceCriteria: string[];
373
+ }
374
+ interface TokenUsageEntry {
375
+ category: string;
376
+ model: string;
377
+ promptTokens: number;
378
+ completionTokens: number;
379
+ latencyMs: number;
380
+ estimatedCost: number;
381
+ }
382
+ interface TokenUsageSummary {
383
+ totalRequests: number;
384
+ totalTokens: number;
385
+ totalPromptTokens: number;
386
+ totalCompletionTokens: number;
387
+ totalEstimatedCost: number;
388
+ avgLatencyMs: number;
389
+ byCategory: Record<string, {
390
+ requests: number;
391
+ promptTokens: number;
392
+ completionTokens: number;
393
+ totalTokens: number;
394
+ estimatedCost: number;
395
+ }>;
396
+ byModel: Record<string, {
397
+ requests: number;
398
+ totalTokens: number;
399
+ estimatedCost: number;
400
+ }>;
401
+ budgetUsedPercent: number | null;
402
+ budgetExceeded: boolean;
403
+ }
404
+ interface ModuleTestConfig {
405
+ moduleName: string;
406
+ version: string;
407
+ generatedAt: string;
408
+ bodyTemplates: Record<string, Record<string, unknown>>;
409
+ paramRewrites: Record<string, Record<string, string>>;
410
+ idAliases: Array<{
411
+ pathPattern: string;
412
+ alias: string;
413
+ }>;
414
+ specialUrls: Record<string, string>;
415
+ seed: SeedStep[];
416
+ }
417
+ interface SeedStep {
418
+ step: number;
419
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
420
+ path: string;
421
+ body?: Record<string, unknown>;
422
+ captureAs?: string;
423
+ required: boolean;
424
+ dependsOn?: string[];
425
+ failureMessage?: string;
426
+ }
427
+ type ModuleConfigErrorType = 'missing-field' | 'invalid-type' | 'invalid-format' | 'interface-not-found' | 'field-missing' | 'type-mismatch' | 'dependency-cycle' | 'dependency-missing' | 'seed-order-invalid' | 'param-mapping-invalid' | 'compile-error' | 'unknown';
428
+ interface ModuleConfigValidationError {
429
+ layer: 'schema' | 'semantic' | 'dryrun';
430
+ type: ModuleConfigErrorType;
431
+ path: string;
432
+ message: string;
433
+ suggestion?: string;
434
+ }
435
+ interface ModuleConfigValidationWarning {
436
+ layer: 'schema' | 'semantic' | 'dryrun';
437
+ path: string;
438
+ message: string;
439
+ }
440
+ interface LayerValidationResult {
441
+ passed: boolean;
442
+ layer: 'schema' | 'semantic' | 'dryrun';
443
+ errors: ModuleConfigValidationError[];
444
+ warnings: ModuleConfigValidationWarning[];
445
+ }
446
+ interface ModuleConfigValidationResult {
447
+ passed: boolean;
448
+ lastPassedLayer?: 'schema' | 'semantic' | 'dryrun';
449
+ failedAtLayer?: 'schema' | 'semantic' | 'dryrun';
450
+ schemaResult?: LayerValidationResult;
451
+ semanticResult?: LayerValidationResult;
452
+ dryrunResult?: LayerValidationResult;
453
+ errors: ModuleConfigValidationError[];
454
+ warnings: ModuleConfigValidationWarning[];
455
+ }
456
+ /** DTO (TypeScript interface) information */
457
+ interface DTOInfo {
458
+ name: string;
459
+ sourcePath?: string;
460
+ fields: DTOFieldInfo[];
461
+ extends?: string;
462
+ }
463
+ interface DTOFieldInfo {
464
+ name: string;
465
+ type: string;
466
+ required: boolean;
467
+ enumValues?: string[];
468
+ isSystemField?: boolean;
469
+ }
470
+ /** express-validator rule */
471
+ interface ValidatorRule {
472
+ field: string;
473
+ source: 'body' | 'param' | 'query';
474
+ rules: string[];
475
+ }
476
+ /** Module metadata from DTO scanning */
477
+ interface ModuleMetadata {
478
+ moduleName: string;
479
+ dtos: DTOInfo[];
480
+ validatorRules: Map<string, ValidatorRule[]>;
481
+ timestamp: string;
482
+ }
483
+ interface ModuleConfigValidationContext {
484
+ endpoints: ApiEndpoint[];
485
+ dtos: DTOInfo[];
486
+ }
487
+ interface FixContext {
488
+ endpoints: ApiEndpoint[];
489
+ dtos: DTOInfo[];
490
+ }
491
+ interface FixHistoryEntry {
492
+ timestamp: string;
493
+ attempt: number;
494
+ errorType: string;
495
+ errorPath: string;
496
+ errorMessage: string;
497
+ fixerUsed: string;
498
+ changedKeys: string[];
499
+ validationPassedAfterFix: boolean;
500
+ }
501
+ interface FixResult {
502
+ success: boolean;
503
+ config: ModuleTestConfig;
504
+ totalAttempts: number;
505
+ history: FixHistoryEntry[];
506
+ remainingErrors: ModuleConfigValidationError[];
507
+ }
196
508
  interface BackendAdapter {
197
509
  name: string;
198
510
  parseModels(dir: string): Promise<TableSchema[]>;
@@ -279,6 +591,37 @@ declare function buildClassToTableMap(modelDir: string): Map<string, string>;
279
591
  declare function classNameToTableName(className: string): string;
280
592
  declare function createAssociationParser(): AssociationParser;
281
593
 
594
+ /**
595
+ * DTO / TypeScript Interface Parser
596
+ *
597
+ * Uses ts-morph to parse TypeScript interfaces from Service and Model files,
598
+ * extracting field info (name, type, required, enum values) and
599
+ * express-validator rules from Controller files.
600
+ */
601
+
602
+ /**
603
+ * Parse DTOs (TypeScript interfaces) from Service and Model files.
604
+ *
605
+ * @param filePaths Files to scan (Service / Model .ts files)
606
+ * @param options.dtoNamePatterns Regex patterns to match DTO interface names
607
+ */
608
+ declare function parseDTOs(filePaths: string[], options?: {
609
+ dtoNamePatterns?: RegExp[];
610
+ }): DTOInfo[];
611
+ /**
612
+ * Parse express-validator rules from Controller files.
613
+ *
614
+ * Scans router.get/post/put/delete calls for middleware arrays containing
615
+ * body('field').notEmpty(), param('field').isInt(), etc.
616
+ *
617
+ * @returns Map<routeKey, ValidatorRule[]> routeKey = "METHOD /path"
618
+ */
619
+ declare function parseValidatorRules(controllerPaths: string[]): Map<string, ValidatorRule[]>;
620
+ /**
621
+ * Scan a module comprehensively, returning enhanced ModuleMetadata.
622
+ */
623
+ declare function scanModuleMetadata(moduleName: string, servicePaths: string[], controllerPaths: string[], modelDir?: string): ModuleMetadata;
624
+
282
625
  interface TestCodeGenerator {
283
626
  generate(chains: TestChain[]): GeneratedTestFile[];
284
627
  }
@@ -325,11 +668,369 @@ interface ImpactReporter {
325
668
  }
326
669
  declare function createImpactReporter(): ImpactReporter;
327
670
 
671
+ /**
672
+ * Chain Planner
673
+ *
674
+ * Rule-based test chain planning:
675
+ * - Groups endpoints by resource path
676
+ * - Applies chain templates (CRUD, nested, batch, status, error handling)
677
+ * - Uses greedy algorithm for optimal coverage selection
678
+ * - Detects shared setup steps
679
+ */
680
+
681
+ interface ChainPlanner {
682
+ planForModule(moduleName: string, analysis: ApiChainAnalysisResult): ChainPlanResult;
683
+ }
684
+ declare function createChainPlanner(): ChainPlanner;
685
+ interface LlmChainPlanner extends ChainPlanner {
686
+ planForModuleWithLLM(moduleName: string, analysis: ApiChainAnalysisResult, llmProvider: LlmProvider): Promise<ChainPlanResult>;
687
+ }
688
+ /**
689
+ * Create a chain planner with optional LLM constraint reasoning.
690
+ *
691
+ * The LLM is used to:
692
+ * 1. Infer business constraints that rule-based templates cannot detect
693
+ * 2. Prioritize chains based on domain understanding
694
+ * 3. Suggest additional edge-case chains
695
+ */
696
+ declare function createLlmChainPlanner(): LlmChainPlanner;
697
+
328
698
  /**
329
699
  * Validate an OpenCroc configuration object.
330
700
  * Returns an array of ValidationErrors (empty = valid).
331
701
  */
332
702
  declare function validateConfig(config: Record<string, unknown>): ValidationError[];
703
+ interface ValidateModuleConfigOptions {
704
+ stopOnFailure?: boolean;
705
+ skipLayers?: Array<'schema' | 'semantic' | 'dryrun'>;
706
+ }
707
+ declare function validateModuleConfig(config: unknown, context?: ModuleConfigValidationContext, options?: ValidateModuleConfigOptions): ModuleConfigValidationResult;
708
+ declare function formatValidationResult(result: ModuleConfigValidationResult): string;
709
+
710
+ /**
711
+ * Schema Validator — Layer 1 of three-layer module config validation.
712
+ * Checks structural integrity, field types, format conventions.
713
+ */
714
+
715
+ declare function validateSchema(config: unknown): LayerValidationResult;
716
+
717
+ /**
718
+ * Semantic Validator — Layer 2 of three-layer module config validation.
719
+ * Checks that config matches actual source code (routes, DTO fields, dependencies).
720
+ */
721
+
722
+ declare function validateSemantic(config: ModuleTestConfig, context: ModuleConfigValidationContext): LayerValidationResult;
723
+
724
+ /**
725
+ * Dry-run Validator — Layer 3 of three-layer module config validation.
726
+ * Generates temporary TypeScript code from config and runs ts-morph compile check.
727
+ */
728
+
729
+ declare function validateDryrun(config: ModuleTestConfig, _context: ModuleConfigValidationContext): LayerValidationResult;
730
+
731
+ /**
732
+ * AI Config Suggester — AI-driven module test config generation.
733
+ *
734
+ * Uses LlmProvider to analyze parsed API endpoints and generate:
735
+ * - bodyTemplates (request body for POST/PUT/PATCH endpoints)
736
+ * - paramRewrites (semantic parameter name mapping)
737
+ * - seed steps (data setup sequence with dependency ordering)
738
+ */
739
+
740
+ interface GenerateConfigOptions {
741
+ moduleName: string;
742
+ endpoints: ApiEndpoint[];
743
+ llmProvider: LlmProvider;
744
+ /** Max validation+fix retries (default 3) */
745
+ maxRetries?: number;
746
+ /** Dry-run: don't write to disk */
747
+ dryRun?: boolean;
748
+ /** Validation context for semantic checking */
749
+ validationContext?: ModuleConfigValidationContext;
750
+ }
751
+ interface GenerateConfigResult {
752
+ success: boolean;
753
+ config?: ModuleTestConfig;
754
+ error?: string;
755
+ retries: number;
756
+ }
757
+ declare function recoverJSON(text: string): string;
758
+ /**
759
+ * Generate a module test config using AI analysis of endpoints.
760
+ */
761
+ declare function generateModuleConfig(options: GenerateConfigOptions): Promise<GenerateConfigResult>;
762
+ /**
763
+ * Batch generate configs for multiple modules.
764
+ */
765
+ declare function generateAllModuleConfigs(moduleNames: string[], endpoints: Map<string, ApiEndpoint[]>, llmProvider: LlmProvider, options?: Partial<GenerateConfigOptions>): Promise<Map<string, GenerateConfigResult>>;
766
+
767
+ /**
768
+ * Enhanced AI Config Suggester — improved config generation with:
769
+ * - Richer prompts using DTO field info and validation rules
770
+ * - JSON recovery with fallback strategies
771
+ * - Retry with previous failure context
772
+ * - Three-layer validation integration
773
+ */
774
+
775
+ interface EnhancedGenerateOptions {
776
+ moduleName: string;
777
+ endpoints: ApiEndpoint[];
778
+ llmProvider: LlmProvider;
779
+ /** DTO info for richer prompts */
780
+ dtos?: DTOInfo[];
781
+ /** Example config for few-shot learning */
782
+ exampleConfig?: ModuleTestConfig;
783
+ /** Temperature (default 0.1) */
784
+ temperature?: number;
785
+ /** Max retries per phase (default 3) */
786
+ maxRetries?: number;
787
+ /** Single call timeout in ms (default 30000) */
788
+ timeout?: number;
789
+ /** Dry-run: preview only */
790
+ dryRun?: boolean;
791
+ }
792
+ interface EnhancedGenerateResult {
793
+ success: boolean;
794
+ config?: ModuleTestConfig;
795
+ attempts: AttemptRecord$1[];
796
+ error?: string;
797
+ }
798
+ interface AttemptRecord$1 {
799
+ attempt: number;
800
+ phase: 'body' | 'param' | 'seed' | 'full';
801
+ rawResponse?: string;
802
+ parsedJson?: unknown;
803
+ error?: string;
804
+ durationMs: number;
805
+ }
806
+ /**
807
+ * Generate module test config with enhanced prompts and retry logic.
808
+ */
809
+ declare function generateEnhancedConfig(options: EnhancedGenerateOptions): Promise<EnhancedGenerateResult>;
810
+
811
+ /**
812
+ * Auto-Fixer — automatic config repair based on validation errors.
813
+ *
814
+ * Four fix strategies:
815
+ * 1. InterfacePathMismatchFixer: find the closest matching real route
816
+ * 2. MissingDtoFieldFixer: fill in missing required fields from DTO
817
+ * 3. SeedDependencyOrderFixer: topological sort of seed steps
818
+ * 4. ParamMappingFixer: regenerate paramRewrites from actual routes
819
+ */
820
+
821
+ /**
822
+ * Run automatic fix loop on a module test config.
823
+ */
824
+ declare function autoFix(config: ModuleTestConfig, initialErrors: ModuleConfigValidationError[], context: FixContext, validationContext?: ModuleConfigValidationContext, maxAttempts?: number): FixResult;
825
+
826
+ /**
827
+ * Baseline Comparator — compare AI-generated test runs against hardcoded baselines.
828
+ *
829
+ * Workflow:
830
+ * 1. Parse Playwright JSON reports from both baseline and AI-config runs
831
+ * 2. Diff each test case: regression / improvement / unchanged / new / removed
832
+ * 3. Generate prompt optimization suggestions from failure patterns
833
+ * 4. Output formatted comparison report
834
+ */
835
+ interface TestCaseResult {
836
+ title: string;
837
+ file: string;
838
+ suite: string;
839
+ status: 'passed' | 'failed' | 'skipped' | 'timedOut';
840
+ durationMs: number;
841
+ error?: string;
842
+ }
843
+ interface TestRunSummary {
844
+ label: string;
845
+ timestamp: string;
846
+ modules: string[];
847
+ total: number;
848
+ passed: number;
849
+ failed: number;
850
+ skipped: number;
851
+ timedOut: number;
852
+ passRate: number;
853
+ totalDurationMs: number;
854
+ avgDurationMs: number;
855
+ cases: TestCaseResult[];
856
+ }
857
+ interface CaseDiff {
858
+ title: string;
859
+ file: string;
860
+ change: 'regression' | 'improvement' | 'unchanged' | 'new' | 'removed';
861
+ baselineStatus: TestCaseResult['status'] | null;
862
+ aiConfigStatus: TestCaseResult['status'] | null;
863
+ durationDiffMs: number;
864
+ error?: string;
865
+ }
866
+ interface PromptOptimization {
867
+ category: 'seed-config' | 'body-template' | 'param-rewrite' | 'id-alias' | 'general';
868
+ issue: string;
869
+ suggestion: string;
870
+ relatedCases: string[];
871
+ }
872
+ interface ComparisonReport {
873
+ baseline: TestRunSummary;
874
+ aiConfig: TestRunSummary;
875
+ passRateDiff: number;
876
+ /** AI pass rate >= 85% of baseline */
877
+ meetsThreshold: boolean;
878
+ durationChangePercent: number;
879
+ /** Duration change within ±10% */
880
+ durationAcceptable: boolean;
881
+ diffs: CaseDiff[];
882
+ regressions: CaseDiff[];
883
+ improvements: CaseDiff[];
884
+ promptOptimizations: PromptOptimization[];
885
+ }
886
+ /**
887
+ * Parse a Playwright `--reporter=json` output into a TestRunSummary.
888
+ */
889
+ declare function parsePlaywrightReport(reportJson: Record<string, unknown>, label: string, modules: string[]): TestRunSummary;
890
+ /**
891
+ * Build a TestRunSummary from raw test case results.
892
+ */
893
+ declare function buildTestRunSummary(label: string, modules: string[], cases: TestCaseResult[]): TestRunSummary;
894
+ /**
895
+ * Compare two test runs and produce a detailed comparison report.
896
+ */
897
+ declare function compareTestRuns(baseline: TestRunSummary, aiConfig: TestRunSummary): ComparisonReport;
898
+ /**
899
+ * Format a ComparisonReport into human-readable text.
900
+ */
901
+ declare function formatComparisonReport(report: ComparisonReport): string;
902
+
903
+ /**
904
+ * Module Config Preset Loader
905
+ *
906
+ * Loads pre-generated module test configs (JSON) from a directory,
907
+ * validates them, and provides lookup by module name.
908
+ *
909
+ * This supports the 70 module configs migrated from dynamic-gen/module-configs/.
910
+ */
911
+
912
+ interface PresetLoadResult {
913
+ configs: Map<string, ModuleTestConfig>;
914
+ errors: Array<{
915
+ file: string;
916
+ error: string;
917
+ }>;
918
+ totalLoaded: number;
919
+ totalFailed: number;
920
+ }
921
+ /**
922
+ * Load all module config presets from a directory.
923
+ *
924
+ * @param configDir - Path to directory containing *.json module configs
925
+ * @param options.validate - Run schema validation on each config (default: true)
926
+ * @returns Loaded configs indexed by moduleName
927
+ */
928
+ declare function loadModulePresets(configDir: string, options?: {
929
+ validate?: boolean;
930
+ }): PresetLoadResult;
931
+ /**
932
+ * Get a single module config by name from a preset directory.
933
+ */
934
+ declare function getModulePreset(configDir: string, moduleName: string): ModuleTestConfig | null;
935
+ /**
936
+ * List all available module preset names from a directory.
937
+ */
938
+ declare function listModulePresets(configDir: string): string[];
939
+
940
+ /**
941
+ * Dialog Loop Runner — multi-iteration self-healing loop.
942
+ *
943
+ * Runs tests, parses results, applies controlled fixes, and reruns
944
+ * until all tests pass or the maximum iteration count is reached.
945
+ * Tracks error history to avoid infinite loops on recurring failures.
946
+ */
947
+
948
+ interface TestRunner {
949
+ run(): Promise<{
950
+ stdout: string;
951
+ exitCode: number;
952
+ }>;
953
+ }
954
+ interface ResultParser {
955
+ parse(stdout: string): TestFailureInfo[];
956
+ countTotal(stdout: string): number;
957
+ }
958
+ interface FixApplier {
959
+ apply(failure: TestFailureInfo): Promise<ControlledFixOutcome>;
960
+ }
961
+ declare function createJsonResultParser(): ResultParser;
962
+ interface DialogLoopOptions {
963
+ runner: TestRunner;
964
+ parser: ResultParser;
965
+ fixer: FixApplier;
966
+ config?: DialogLoopConfig;
967
+ onIteration?: (result: IterationResult) => void;
968
+ }
969
+ declare function runDialogLoop(options: DialogLoopOptions): Promise<DialogLoopSummary>;
970
+
971
+ /**
972
+ * Controlled Fixer — two-phase fix engine with safety guarantees.
973
+ *
974
+ * Phase A (config-only): backup → validate → fix → dry-run → write → verify → cleanup.
975
+ * Phase B (config-and-source): generates a draft PR with the AI-suggested code patch.
976
+ *
977
+ * All mutations are reversible — failures trigger automatic rollback.
978
+ */
979
+
980
+ interface ConfigValidator {
981
+ validate(configContent: string): {
982
+ passed: boolean;
983
+ errors: string[];
984
+ };
985
+ }
986
+ interface ConfigFixer {
987
+ fix(configContent: string, errors: string[]): {
988
+ success: boolean;
989
+ fixedContent: string;
990
+ fixedItems: string[];
991
+ remainingErrors: string[];
992
+ };
993
+ }
994
+ interface PRGenerator {
995
+ generate(attribution: AIAttributionResult): Promise<string>;
996
+ }
997
+ interface FsOps {
998
+ exists(path: string): boolean;
999
+ read(path: string): string;
1000
+ write(path: string, content: string): void;
1001
+ copy(src: string, dest: string): void;
1002
+ remove(path: string): void;
1003
+ mkdirp(dir: string): void;
1004
+ }
1005
+ interface ControlledFixerOptions {
1006
+ configPath: string;
1007
+ validator: ConfigValidator;
1008
+ fixer: ConfigFixer;
1009
+ prGenerator?: PRGenerator;
1010
+ attribution?: AIAttributionResult;
1011
+ fs?: FsOps;
1012
+ options?: ControlledFixOptions;
1013
+ }
1014
+ declare function applyControlledFix(opts: ControlledFixerOptions): Promise<ControlledFixOutcome>;
1015
+
1016
+ /**
1017
+ * Auto-Fix PR Generator — creates draft PRs from AI attribution results.
1018
+ *
1019
+ * Flow: create branch → write patch → git apply → commit → push → gh pr create --draft.
1020
+ * All PRs are draft-only as a safety invariant.
1021
+ */
1022
+
1023
+ interface GitExecutor {
1024
+ exec(command: string, args: string[]): Promise<{
1025
+ stdout: string;
1026
+ exitCode: number;
1027
+ }>;
1028
+ }
1029
+ interface PatchWriter {
1030
+ write(path: string, content: string): Promise<void>;
1031
+ mkdir(dir: string): Promise<void>;
1032
+ }
1033
+ declare function generateFixPR(attribution: AIAttributionResult, git: GitExecutor, patchWriter: PatchWriter, options?: AutoFixPROptions): Promise<AutoFixPRResult>;
333
1034
 
334
1035
  interface SelfHealingLoop {
335
1036
  run(testResultsDir: string): Promise<SelfHealingResult>;
@@ -374,7 +1075,7 @@ declare function createLlmProvider(config: LlmConfig): LlmProvider;
374
1075
  /**
375
1076
  * Token usage tracker — accumulates tokens across multiple LLM calls.
376
1077
  */
377
- interface TokenTracker {
1078
+ interface TokenTracker$1 {
378
1079
  track(text: string): void;
379
1080
  trackChat(messages: Array<{
380
1081
  role: string;
@@ -383,7 +1084,7 @@ interface TokenTracker {
383
1084
  total: number;
384
1085
  reset(): void;
385
1086
  }
386
- declare function createTokenTracker(provider: LlmProvider): TokenTracker;
1087
+ declare function createTokenTracker(provider: LlmProvider): TokenTracker$1;
387
1088
  /**
388
1089
  * System prompts for different LLM use cases in OpenCroc.
389
1090
  */
@@ -516,6 +1217,57 @@ declare function listCiPlatforms(): string[];
516
1217
  */
517
1218
  declare function generateCiTemplate(platform: string, opts?: CiTemplateOptions): string;
518
1219
 
1220
+ /**
1221
+ * Checklist Reporter — generates backend fix checklists from test results.
1222
+ *
1223
+ * Groups failures by API domain, lists affected tests and endpoints,
1224
+ * and produces both structured data and Markdown output.
1225
+ */
1226
+
1227
+ declare function classifyFailure(error?: string): FailureCategory;
1228
+ declare function buildFailureSummary(records: TestResultRecord[]): FailureSummary;
1229
+ declare function aggregateLogCompletion(records: TestResultRecord[]): LogCompletionSummary;
1230
+ declare function parseApiDomain(urlStr: string): string | null;
1231
+ declare function buildBackendChecklist(records: TestResultRecord[]): BackendDomainItem[];
1232
+ declare function renderChecklistMarkdown(items: BackendDomainItem[], summary: FailureSummary, logSummary?: LogCompletionSummary): string;
1233
+
1234
+ /**
1235
+ * Workorder Reporter — auto-generates prioritized backend work orders.
1236
+ *
1237
+ * Priority rules:
1238
+ * - P0: ≥3 affected tests OR log completion rate < 90%
1239
+ * - P1: 2 affected tests
1240
+ * - P2: 1 affected test
1241
+ *
1242
+ * Each workorder includes objective, affected scope, and acceptance criteria.
1243
+ */
1244
+
1245
+ interface BuildWorkordersOptions {
1246
+ checklist: BackendDomainItem[];
1247
+ summary: FailureSummary;
1248
+ logSummary?: LogCompletionSummary;
1249
+ logRateThreshold?: number;
1250
+ }
1251
+ declare function buildWorkorders(opts: BuildWorkordersOptions): WorkorderItem[];
1252
+ declare function renderWorkordersMarkdown(workorders: WorkorderItem[], summary: FailureSummary, logSummary?: LogCompletionSummary): string;
1253
+
1254
+ /**
1255
+ * Token Usage Reporter — tracks and reports LLM token consumption.
1256
+ *
1257
+ * Aggregates usage entries by category and model, computes costs,
1258
+ * tracks budget utilization, and renders both structured data and Markdown.
1259
+ */
1260
+
1261
+ declare class TokenTracker {
1262
+ private entries;
1263
+ private budget;
1264
+ setBudget(maxTokens: number): void;
1265
+ record(entry: TokenUsageEntry): void;
1266
+ reset(): void;
1267
+ getSummary(): TokenUsageSummary;
1268
+ }
1269
+ declare function renderTokenReportMarkdown(summary: TokenUsageSummary): string;
1270
+
519
1271
  interface ReportOutput {
520
1272
  format: 'html' | 'json' | 'markdown';
521
1273
  content: string;
@@ -611,4 +1363,437 @@ declare function generateExtensionManifest(): Record<string, unknown>;
611
1363
  */
612
1364
  declare function generateExtensionEntrypoint(): string;
613
1365
 
614
- export { type ApiChainAnalysisResult, type ApiDependency, type ApiEndpoint, type BackendAdapter, type ChainFailureResult, type ChainPlanResult, type DashboardData, type DashboardOutput, type DirectedAcyclicGraph, type ERDiagramResult, type FieldSchema, type FixOutcome, type ForeignKeyRelation, type GeneratedTestFile, type ImpactReport, type IndexSchema, type LlmProvider, type ModuleDefinition, type OpenCrocConfig, type OpenCrocPlugin, type PipelineRunResult, type PluginRegistry, type ReportOutput, type ResolvedConfig, type RouteEntry, SYSTEM_PROMPTS, type SelfHealingResult, type TableSchema, type TestChain, type TestStep, COMMANDS as VSCODE_COMMANDS, type ValidationError, analyzeFailureWithLLM, buildClassToTableMap, buildDashboardDataFromPipeline, buildDashboardDataFromReportJson, buildGraph, buildModuleTree, buildStatusTree, categorizeFailure, classNameToTableName, createAdapter, createApiChainAnalyzer, createAssociationParser, createControllerParser, createDrizzleAdapter, createERDiagramGenerator, createImpactReporter, createLlmProvider, createMockDataGenerator, createModelParser, createOllamaProvider, createOpenAIProvider, createPipeline, createPluginRegistry, createPrismaAdapter, createSelfHealingLoop, createSequelizeAdapter, createTestCodeGenerator, createTokenTracker, createTypeORMAdapter, defineConfig, definePlugin, detectAdapter, detectCycles, generateCiTemplate, generateExtensionEntrypoint, generateExtensionManifest, generateGitHubActionsTemplate, generateGitLabCITemplate, generateHtmlReport, generateJsonReport, generateMarkdownReport, generateReports, generateVisualDashboard, generateVisualDashboardHtml, inferDependencies, inferRelatedTables, listCiPlatforms, parseAssociationFile, parseControllerDirectory, parseControllerFile, parseDrizzleDirectory, parseDrizzleFile, parseModelFile, parseModuleModels, resolveAdapter, topologicalSort, validateConfig };
1366
+ /**
1367
+ * Generate playwright.config.ts content based on OpenCroc config.
1368
+ */
1369
+ declare function generatePlaywrightConfig(config: OpenCrocConfig): string;
1370
+
1371
+ /**
1372
+ * Generate global-setup.ts content for Playwright.
1373
+ * Handles backend readiness probe, seed endpoint call, and log cleanup.
1374
+ */
1375
+ declare function generateGlobalSetup(config: OpenCrocConfig): string;
1376
+
1377
+ /**
1378
+ * Generate global-teardown.ts content for Playwright.
1379
+ * Handles cleanup endpoint call and optional SQL cleanup.
1380
+ */
1381
+ declare function generateGlobalTeardown(config: OpenCrocConfig): string;
1382
+
1383
+ /**
1384
+ * Generate auth.setup.ts content for Playwright.
1385
+ * Creates an authentication setup project that stores state for reuse.
1386
+ */
1387
+ declare function generateAuthSetup(config: OpenCrocConfig): string;
1388
+
1389
+ /**
1390
+ * Resilient HTTP fetch with exponential backoff retry.
1391
+ * Framework-level utility — no Playwright dependency required.
1392
+ */
1393
+ interface AttemptRecord {
1394
+ attempt: number;
1395
+ status: number;
1396
+ url: string;
1397
+ method: string;
1398
+ latencyMs: number;
1399
+ error?: string;
1400
+ }
1401
+ interface ResilientFetchOptions {
1402
+ /** HTTP method */
1403
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
1404
+ /** Request body (will be JSON-stringified if object) */
1405
+ body?: string | Record<string, unknown>;
1406
+ /** Request headers */
1407
+ headers?: Record<string, string>;
1408
+ /** Max retry count (default: 3) */
1409
+ maxRetries?: number;
1410
+ /** Base delay in ms for exponential backoff (default: 1000) */
1411
+ baseDelayMs?: number;
1412
+ /** Per-request timeout in ms (default: 10000) */
1413
+ timeoutMs?: number;
1414
+ /** If true, throw on final failure; if false, return error result (default: false) */
1415
+ throwOnFailure?: boolean;
1416
+ }
1417
+ interface ResilientFetchResult {
1418
+ ok: boolean;
1419
+ status: number;
1420
+ data: unknown;
1421
+ attempts: AttemptRecord[];
1422
+ }
1423
+ /**
1424
+ * Make an HTTP request with automatic retry and exponential backoff.
1425
+ *
1426
+ * Retries on: network errors, 408, 429, 5xx.
1427
+ * Does NOT retry on: 4xx (except 408/429).
1428
+ */
1429
+ declare function resilientFetch(url: string, options?: ResilientFetchOptions): Promise<ResilientFetchResult>;
1430
+ /**
1431
+ * Wait for a backend to become healthy by polling a health endpoint.
1432
+ */
1433
+ declare function waitForBackend(baseUrl: string, options?: {
1434
+ timeoutMs?: number;
1435
+ intervalMs?: number;
1436
+ healthPath?: string;
1437
+ }): Promise<void>;
1438
+
1439
+ /**
1440
+ * Playwright network request/response monitor.
1441
+ * Attaches to a Page and records API calls, errors, and response times.
1442
+ */
1443
+ interface NetworkError {
1444
+ url: string;
1445
+ status: number;
1446
+ method: string;
1447
+ responseBody: string;
1448
+ requestPayload?: string;
1449
+ timestamp: string;
1450
+ pageUrl: string;
1451
+ }
1452
+ interface ApiRecord {
1453
+ url: string;
1454
+ status: number;
1455
+ method: string;
1456
+ durationMs: number;
1457
+ timestamp: string;
1458
+ pageUrl: string;
1459
+ }
1460
+ interface NetworkMonitorOptions {
1461
+ /** URL pattern to track (default: '/api/') */
1462
+ apiPattern?: string;
1463
+ /** Whether to capture response bodies for errors (default: true) */
1464
+ captureErrorBody?: boolean;
1465
+ }
1466
+ /** Minimal Playwright Page interface — avoids hard dependency on @playwright/test */
1467
+ interface PlaywrightPage {
1468
+ url(): string;
1469
+ on(event: 'request', handler: (req: PlaywrightRequest) => void): void;
1470
+ on(event: 'response', handler: (res: PlaywrightResponse) => void): void;
1471
+ }
1472
+ interface PlaywrightRequest {
1473
+ url(): string;
1474
+ method(): string;
1475
+ postData(): string | null;
1476
+ }
1477
+ interface PlaywrightResponse {
1478
+ url(): string;
1479
+ status(): number;
1480
+ request(): PlaywrightRequest;
1481
+ text(): Promise<string>;
1482
+ }
1483
+ declare class NetworkMonitor {
1484
+ private errors;
1485
+ private records;
1486
+ private requestStarts;
1487
+ private readonly apiPattern;
1488
+ private readonly captureErrorBody;
1489
+ constructor(options?: NetworkMonitorOptions);
1490
+ /**
1491
+ * Attach the monitor to a Playwright Page.
1492
+ * Call this once per page — typically in a test fixture or beforeEach.
1493
+ */
1494
+ attach(page: PlaywrightPage): void;
1495
+ /** All captured API records. */
1496
+ getRecords(): ApiRecord[];
1497
+ /** All captured network errors (status >= 400). */
1498
+ getErrors(): NetworkError[];
1499
+ /** API calls slower than the given threshold. */
1500
+ getSlowRequests(thresholdMs: number): ApiRecord[];
1501
+ /** 5xx server errors. */
1502
+ get5xxErrors(): NetworkError[];
1503
+ /** 4xx client errors. */
1504
+ get4xxErrors(): NetworkError[];
1505
+ /** Whether any network errors have been captured. */
1506
+ hasErrors(): boolean;
1507
+ /** Reset all captured data. */
1508
+ clear(): void;
1509
+ }
1510
+
1511
+ /**
1512
+ * Dynamic route parameter resolver.
1513
+ * Extracts path parameters by matching URL templates against actual hrefs.
1514
+ * Framework-level utility — no app-specific dependencies.
1515
+ */
1516
+ interface ResolvedRoute {
1517
+ /** Original path template (e.g. '/users/:id/detail') */
1518
+ originalPath: string;
1519
+ /** Resolved path with actual values (e.g. '/users/42/detail') */
1520
+ resolvedPath: string;
1521
+ /** Extracted parameter map (e.g. { id: '42' }) */
1522
+ params: Record<string, string>;
1523
+ /** How the parameters were resolved */
1524
+ resolveMethod: 'href-extraction' | 'seed-data' | 'text-extraction';
1525
+ }
1526
+ /**
1527
+ * Extract parameter names from a path template.
1528
+ * @example extractParamNames('/users/:id/posts/:postId') → ['id', 'postId']
1529
+ */
1530
+ declare function extractParamNames(pathTemplate: string): string[];
1531
+ /**
1532
+ * Extract parameter values by matching a URL template against an actual href.
1533
+ * Returns null if the href doesn't match the template structure.
1534
+ *
1535
+ * @example
1536
+ * extractParamsFromHref('/users/:id/detail', '/users/42/detail')
1537
+ * // → { id: '42' }
1538
+ */
1539
+ declare function extractParamsFromHref(pathTemplate: string, href: string): Record<string, string> | null;
1540
+ /**
1541
+ * Build a concrete path from a template and parameter values.
1542
+ *
1543
+ * @example
1544
+ * buildPath('/users/:id/posts/:postId', { id: '42', postId: '7' })
1545
+ * // → '/users/42/posts/7'
1546
+ */
1547
+ declare function buildPath(pathTemplate: string, params: Record<string, string>): string;
1548
+ /**
1549
+ * Try to extract an ID-like value from a text string.
1550
+ * Matches numeric IDs and UUIDs.
1551
+ */
1552
+ declare function extractIdFromText(text: string): string | null;
1553
+ /**
1554
+ * Resolve dynamic route parameters from a seed data map.
1555
+ *
1556
+ * @param pathTemplate - URL template with :params
1557
+ * @param seedData - Map of route keys to param objects
1558
+ * @param routeKey - Optional explicit key; defaults to normalized path
1559
+ */
1560
+ declare function resolveFromSeedData(pathTemplate: string, seedData: Record<string, Record<string, string>>, routeKey?: string): ResolvedRoute | null;
1561
+
1562
+ /**
1563
+ * Log-driven API completion detection.
1564
+ *
1565
+ * Polls a backend log endpoint to verify that API requests have fully completed
1566
+ * (not just returned HTTP 200, but the backend has finished all processing).
1567
+ * This closes the gap between "HTTP response received" and "backend actually done".
1568
+ */
1569
+ interface CandidateApiRequest {
1570
+ /** Backend-assigned request ID (if available) */
1571
+ requestId?: string;
1572
+ /** HTTP method */
1573
+ method: string;
1574
+ /** API path (e.g. /api/users) */
1575
+ path: string;
1576
+ /** Full URL */
1577
+ url: string;
1578
+ }
1579
+ interface LogCompletionResult {
1580
+ /** Total candidates being tracked */
1581
+ candidateCount: number;
1582
+ /** Requests confirmed completed successfully */
1583
+ succeeded: CandidateApiRequest[];
1584
+ /** Requests confirmed completed with failure */
1585
+ failed: Array<{
1586
+ request: CandidateApiRequest;
1587
+ reason: string;
1588
+ }>;
1589
+ /** Requests that never got a completion log within timeout */
1590
+ timedOut: CandidateApiRequest[];
1591
+ /** Number of poll iterations performed */
1592
+ pollCount: number;
1593
+ /** Total elapsed ms */
1594
+ elapsedMs: number;
1595
+ }
1596
+ interface LogEntry {
1597
+ /** Backend-assigned request ID */
1598
+ requestId?: string;
1599
+ /** HTTP method */
1600
+ method?: string;
1601
+ /** API path */
1602
+ apiPath?: string;
1603
+ /** Event phase: 'start' | 'end' */
1604
+ eventPhase?: string;
1605
+ /** Event status: 'success' | 'fail' */
1606
+ eventStatus?: string;
1607
+ /** HTTP status code */
1608
+ status?: number;
1609
+ /** Nested metadata (some backends put fields here) */
1610
+ meta?: Record<string, unknown>;
1611
+ }
1612
+ interface LogPollerOptions {
1613
+ /** Function that fetches end-phase logs from the backend. Return parsed log entries. */
1614
+ fetchLogs: () => Promise<LogEntry[]>;
1615
+ /** Timeout in ms (default: 25000) */
1616
+ timeoutMs?: number;
1617
+ /** Initial poll delay in ms (default: 200) */
1618
+ initialDelayMs?: number;
1619
+ /** Max poll delay in ms (default: 2000) */
1620
+ maxDelayMs?: number;
1621
+ }
1622
+ interface ApiResponseRecord {
1623
+ url: string;
1624
+ method: string;
1625
+ requestId?: string;
1626
+ }
1627
+ /**
1628
+ * Select candidate API requests from network-captured responses.
1629
+ * Deduplicates by requestId or method+path.
1630
+ */
1631
+ declare function selectCandidates(responses: ApiResponseRecord[], maxCount?: number): CandidateApiRequest[];
1632
+ /**
1633
+ * Select candidates from start-phase log entries.
1634
+ */
1635
+ declare function selectCandidatesFromLogs(logs: LogEntry[], maxCount?: number): CandidateApiRequest[];
1636
+ /**
1637
+ * Merge multiple candidate lists, deduplicating by key.
1638
+ */
1639
+ declare function mergeCandidates(...groups: CandidateApiRequest[][]): CandidateApiRequest[];
1640
+ /**
1641
+ * Poll backend logs until all candidate API requests have completion entries,
1642
+ * or the timeout is reached.
1643
+ *
1644
+ * @example
1645
+ * ```ts
1646
+ * const result = await waitForLogCompletion(candidates, {
1647
+ * fetchLogs: async () => {
1648
+ * const resp = await fetch(`${origin}/internal/test-logs?eventPhase=end&since=${since}`);
1649
+ * const body = await resp.json();
1650
+ * return body.data ?? [];
1651
+ * },
1652
+ * timeoutMs: 20_000,
1653
+ * });
1654
+ * ```
1655
+ */
1656
+ declare function waitForLogCompletion(candidates: CandidateApiRequest[], options: LogPollerOptions): Promise<LogCompletionResult>;
1657
+
1658
+ /**
1659
+ * Critical API rules engine.
1660
+ *
1661
+ * Define per-endpoint validation rules with performance thresholds and
1662
+ * behavior flags. Evaluate captured API records against rules to surface
1663
+ * violations (slow responses, unexpected empty data, fatal timeouts).
1664
+ */
1665
+ interface CriticalApiRule {
1666
+ /** Route path this rule applies to (e.g. '/users/list') */
1667
+ routePath: string;
1668
+ /** Human-readable name */
1669
+ name: string;
1670
+ /** URL substring to match against captured API URLs */
1671
+ urlIncludes: string;
1672
+ /** HTTP method filter (optional; matches all if omitted) */
1673
+ method?: string;
1674
+ /** Whether an empty/null response body is acceptable (default: false) */
1675
+ allowEmpty?: boolean;
1676
+ /** Response time warning threshold in ms */
1677
+ warnMs?: number;
1678
+ /** Response time fatal threshold in ms */
1679
+ fatalMs?: number;
1680
+ }
1681
+ interface ApiRuleViolation {
1682
+ rule: CriticalApiRule;
1683
+ /** 'warn' for exceeded warnMs, 'fatal' for exceeded fatalMs, 'empty' for unexpected empty response */
1684
+ severity: 'warn' | 'fatal' | 'empty';
1685
+ /** Actual duration in ms (for timing violations) */
1686
+ actualMs?: number;
1687
+ /** Description of the violation */
1688
+ message: string;
1689
+ }
1690
+ interface ApiRecordForRules {
1691
+ url: string;
1692
+ method: string;
1693
+ durationMs: number;
1694
+ /** Response body (for empty checks) */
1695
+ responseBody?: string | null;
1696
+ }
1697
+ /**
1698
+ * Create a rules engine that evaluates API records against a set of critical rules.
1699
+ */
1700
+ declare function createRulesEngine(rules: CriticalApiRule[]): {
1701
+ /** Get all rules. */
1702
+ getRules(): CriticalApiRule[];
1703
+ /** Get rules matching a specific route path. */
1704
+ getRulesByRoute(routePath: string): CriticalApiRule[];
1705
+ /** Get rules matching a specific URL. */
1706
+ getRulesByUrl(url: string): CriticalApiRule[];
1707
+ /**
1708
+ * Evaluate a single API record against all matching rules.
1709
+ * Returns violations (empty array if all rules pass).
1710
+ */
1711
+ evaluate(record: ApiRecordForRules): ApiRuleViolation[];
1712
+ /**
1713
+ * Evaluate multiple API records and return all violations.
1714
+ */
1715
+ evaluateAll(records: ApiRecordForRules[]): ApiRuleViolation[];
1716
+ /**
1717
+ * Summary: group violations by severity.
1718
+ */
1719
+ summarize(violations: ApiRuleViolation[]): {
1720
+ fatal: number;
1721
+ warn: number;
1722
+ empty: number;
1723
+ };
1724
+ };
1725
+
1726
+ /**
1727
+ * Full orchestration engine: generate → execute → analyze → heal → report.
1728
+ *
1729
+ * Runs a multi-phase pipeline with per-phase tracking, failure detection,
1730
+ * token budget management, and structured result reporting.
1731
+ */
1732
+
1733
+ type PhaseStatus = 'success' | 'warn' | 'error' | 'skipped';
1734
+ interface PhaseResult<T = unknown> {
1735
+ phase: string;
1736
+ status: PhaseStatus;
1737
+ output?: T;
1738
+ error?: string;
1739
+ durationMs: number;
1740
+ }
1741
+ interface OrchestrationOptions {
1742
+ /** Which phases to run (default: all) */
1743
+ phases?: OrchestrationPhase[];
1744
+ /** Enable self-healing phase (default: false) */
1745
+ selfHeal?: boolean;
1746
+ /** Max self-healing iterations */
1747
+ maxHealIterations?: number;
1748
+ /** Report formats to generate */
1749
+ reportFormats?: ('html' | 'json' | 'markdown')[];
1750
+ /** Run Playwright in headed mode */
1751
+ headed?: boolean;
1752
+ /** Module filter */
1753
+ module?: string;
1754
+ /** LLM token budget (0 = unlimited) */
1755
+ tokenBudget?: number;
1756
+ /** Abort on phase error (default: false — continue where possible) */
1757
+ abortOnError?: boolean;
1758
+ }
1759
+ type OrchestrationPhase = 'generate' | 'execute' | 'analyze' | 'heal' | 'report';
1760
+ interface ExecutionMetrics {
1761
+ passed: number;
1762
+ failed: number;
1763
+ skipped: number;
1764
+ timedOut: number;
1765
+ }
1766
+ interface OrchestrationSummary {
1767
+ overallStatus: 'success' | 'partial-fail' | 'fatal-fail';
1768
+ phases: PhaseResult[];
1769
+ totalDurationMs: number;
1770
+ modules: string[];
1771
+ executionMetrics?: ExecutionMetrics;
1772
+ reports?: ReportOutput[];
1773
+ healingResult?: SelfHealingResult;
1774
+ recommendation?: string;
1775
+ }
1776
+ declare function createOrchestrator(config: OpenCrocConfig, options?: OrchestrationOptions): {
1777
+ run(): Promise<OrchestrationSummary>;
1778
+ };
1779
+
1780
+ /**
1781
+ * Orchestration summary reporter.
1782
+ * Writes phase-by-phase JSON and a human-readable console summary.
1783
+ */
1784
+
1785
+ interface OrchestrationReportOptions {
1786
+ outputDir: string;
1787
+ module?: string;
1788
+ }
1789
+ /**
1790
+ * Write the orchestration summary to a JSON file.
1791
+ * Returns the written file path.
1792
+ */
1793
+ declare function writeOrchestrationSummary(summary: OrchestrationSummary, options: OrchestrationReportOptions): string;
1794
+ /**
1795
+ * Print a human-readable console summary.
1796
+ */
1797
+ declare function printOrchestrationSummary(summary: OrchestrationSummary): string[];
1798
+
1799
+ export { type AIAttributionResult, type ApiChainAnalysisResult, type ApiDependency, type ApiEndpoint, type ApiRecord, type ApiRecordForRules, type ApiRuleViolation, type AttemptRecord, type AutoFixPROptions, type AutoFixPRResult, type BackendAdapter, type BackendDomainItem, type BuildWorkordersOptions, type CandidateApiRequest, type ChainFailureResult, type ChainPlanResult, type ConfigFixer, type ConfigValidator, type ControlledFixOptions, type ControlledFixOutcome, type ControlledFixerOptions, type CriticalApiRule, type DTOFieldInfo, type DTOInfo, type DashboardData, type DashboardOutput, type DialogLoopConfig, type DialogLoopOptions, type DialogLoopSummary, type DirectedAcyclicGraph, type ERDiagramResult, type ExecutionConfig, type ExecutionMetrics, type FailureCategory, type FailureSummary, type FieldSchema, type FixApplier, type FixContext, type FixHistoryEntry, type FixOutcome, type FixResult, type FixScope, type ForeignKeyRelation, type FsOps, type GeneratedTestFile, type GitExecutor, type HookConfig, type ImpactReport, type IndexSchema, type IterationResult, type LayerValidationResult, type LlmProvider, type LogCompletionRecord, type LogCompletionResult, type LogCompletionSummary, type LogEntry, type LogPollerOptions, type ModuleConfigErrorType, type ModuleConfigValidationContext, type ModuleConfigValidationError, type ModuleConfigValidationResult, type ModuleConfigValidationWarning, type ModuleDefinition, type ModuleMetadata, type ModuleTestConfig, type NetworkError, NetworkMonitor, type NetworkMonitorOptions, type OpenCrocConfig, type OpenCrocPlugin, type OrchestrationOptions, type OrchestrationPhase, type OrchestrationReportOptions, type OrchestrationSummary, type PRGenerator, type PatchWriter, type PhaseResult, type PhaseStatus, type PipelineRunResult, type PluginRegistry, type ReportOutput, type ResilientFetchOptions, type ResilientFetchResult, type ResolvedConfig, type ResolvedRoute, type ResultParser, type RouteEntry, type RuntimeConfig, SYSTEM_PROMPTS, type SeedStep, type SelfHealingResult, type TableSchema, type TestChain, type TestFailureInfo, type TestResultRecord, type TestRunner, type TestStep, TokenTracker, type TokenUsageEntry, type TokenUsageSummary, COMMANDS as VSCODE_COMMANDS, type ValidationError, type ValidatorRule, type WorkorderItem, aggregateLogCompletion, analyzeFailureWithLLM, applyControlledFix, autoFix, buildBackendChecklist, buildClassToTableMap, buildDashboardDataFromPipeline, buildDashboardDataFromReportJson, buildFailureSummary, buildGraph, buildModuleTree, buildPath, buildStatusTree, buildTestRunSummary, buildWorkorders, categorizeFailure, classNameToTableName, classifyFailure, compareTestRuns, createAdapter, createApiChainAnalyzer, createAssociationParser, createChainPlanner, createControllerParser, createDrizzleAdapter, createERDiagramGenerator, createImpactReporter, createJsonResultParser, createLlmChainPlanner, createLlmProvider, createMockDataGenerator, createModelParser, createOllamaProvider, createOpenAIProvider, createOrchestrator, createPipeline, createPluginRegistry, createPrismaAdapter, createRulesEngine, createSelfHealingLoop, createSequelizeAdapter, createTestCodeGenerator, createTokenTracker, createTypeORMAdapter, defineConfig, definePlugin, detectAdapter, detectCycles, extractIdFromText, extractParamNames, extractParamsFromHref, formatComparisonReport, formatValidationResult, generateAllModuleConfigs, generateAuthSetup, generateCiTemplate, generateEnhancedConfig, generateExtensionEntrypoint, generateExtensionManifest, generateFixPR, generateGitHubActionsTemplate, generateGitLabCITemplate, generateGlobalSetup, generateGlobalTeardown, generateHtmlReport, generateJsonReport, generateMarkdownReport, generateModuleConfig, generatePlaywrightConfig, generateReports, generateVisualDashboard, generateVisualDashboardHtml, getModulePreset, inferDependencies, inferRelatedTables, listCiPlatforms, listModulePresets, loadModulePresets, mergeCandidates, parseApiDomain, parseAssociationFile, parseControllerDirectory, parseControllerFile, parseDTOs, parseDrizzleDirectory, parseDrizzleFile, parseModelFile, parseModuleModels, parsePlaywrightReport, parseValidatorRules, printOrchestrationSummary, recoverJSON, renderChecklistMarkdown, renderTokenReportMarkdown, renderWorkordersMarkdown, resilientFetch, resolveAdapter, resolveFromSeedData, runDialogLoop, scanModuleMetadata, selectCandidates, selectCandidatesFromLogs, topologicalSort, validateConfig, validateDryrun, validateModuleConfig, validateSchema, validateSemantic, waitForBackend, waitForLogCompletion, writeOrchestrationSummary };