/** * Type definitions for the code auditor * Generic types that work with any TypeScript/JavaScript project */ export type Severity = 'critical' | 'warning' | 'suggestion' | 'off'; export type ReportFormat = 'html' | 'json' | 'csv' | 'sarif'; export type RenderType = 'client' | 'server' | 'unknown'; export type DataFetchingMethod = 'server' | 'client' | 'none'; export interface QueryInfo { type: string; tables: string[]; line: number; hasJoins?: boolean; complexity?: 'simple' | 'moderate' | 'complex'; hasOrganizationFilter?: boolean; } export interface SecurityViolation extends Violation { type: 'security'; category: string; } export interface ArchitectureViolation extends Violation { type: 'architecture'; category: string; } /** * Audit scope applied to a result. * - `full` – a complete audit (scope was `all`) * - `scoped` – audit was scoped to a subset of files; the result does NOT * replace the most recent full-audit result in storage. */ export type AuditResultScope = 'full' | 'scoped'; export interface Violation { file: string; line?: number; column?: number; severity: Severity; message: string; details?: string | Record; snippet?: string; suggestion?: string; /** Path profile that matched this file (last matching profile wins). */ profile?: string; /** Hotspot score [0,1] — churn percentile × complexity percentile. */ hotspot?: number; [key: string]: any; } export interface AnalyzerResult { violations: Violation[]; filesProcessed: number; executionTime: number; errors?: Array<{ file: string; error: string; }>; analyzerName?: string; [key: string]: any; } export interface AuditOptions { includePaths?: string[]; excludePaths?: string[]; fileExtensions?: string[]; minSeverity?: Severity; enabledAnalyzers?: string[]; outputFormats?: ReportFormat[]; outputDir?: string; failOnCritical?: boolean; duplicateThreshold?: number; verbose?: boolean; configFile?: string; thresholds?: { maxCritical?: number; maxWarnings?: number; maxSuggestions?: number; minHealthScore?: number; }; unusedImportsConfig?: { checkLevel?: 'function' | 'file'; includeTypeOnlyImports?: boolean; ignorePatterns?: string[]; }; /** Per-rule severity overrides applied globally (before per-file path profile caps). */ severityOverrides?: Record; } export interface ProgressCallback { (progress: { current: number; total: number; analyzer: string; file?: string; phase?: string; }): void; } export type AnalyzerFunction = (files: string[], config: any, options?: AuditOptions, progressCallback?: ProgressCallback) => Promise; export interface AnalyzerDefinition { name: string; analyze: AnalyzerFunction; defaultConfig?: any; description?: string; category?: string; } export interface AuditSummary { totalFiles: number; totalViolations: number; criticalIssues: number; warnings: number; suggestions: number; violationsByCategory: Record; topIssues: Array<{ type: string; count: number; }>; } export interface AuditResult { timestamp: Date; summary: AuditSummary; analyzerResults: Record; recommendations: Recommendation[]; metadata: { auditDuration: number; filesAnalyzed: number; analyzersRun: string[]; configUsed?: AuditOptions; collectedFunctions?: FunctionMetadata[]; fileToFunctionsMap?: Record; scope?: AuditResultScope; /** Milliseconds spent inside buildProvenanceContext() across all files (Spec 21 — hook-latency measurement). */ provenanceResolutionMs?: number; /** Blast radius impact for changed functions (Spec 14 R6 — scoped audits only). */ blastRadius?: BlastRadiusImpact; baseline?: { present: boolean; hash?: string; newCount: number; fixedCount: number; knownCount: number; previousKnownCount?: number; }; }; } /** Thrown when an in-process audit is stopped via AbortSignal (parent cancel or soft budget). */ export declare class AuditAbortedError extends Error { readonly name = "AuditAbortedError"; constructor(message?: string); } /** * Thrown when a shard processed a file chunk and more files remain. * Parent should queue a new worker task (e.g. with explicitFiles) to continue. */ export declare class AuditHandoffError extends Error { readonly name = "AuditHandoffError"; readonly partialResult: AuditResult; readonly remainingFiles: string[]; constructor(message: string, partialResult: AuditResult, remainingFiles: string[]); } export interface ComponentAnalysis { filePath: string; renderType: RenderType; hasErrorBoundary: boolean; dataFetchingMethod?: DataFetchingMethod; violations: Violation[]; suggestions: string[]; imports: string[]; exports: string[]; hasAppShell?: boolean; hasPageHeader?: boolean; } export interface SecurityAnalysis { filePath: string; httpMethods: string[]; authPattern?: string; authWrapper?: string; rateLimiting?: boolean; hasErrorHandling: boolean; usesStandardResponses?: boolean; organizationFiltering?: boolean; violations: Violation[]; } export interface SOLIDViolation extends Violation { principle: 'single-responsibility' | 'open-closed' | 'liskov-substitution' | 'interface-segregation' | 'dependency-inversion'; className?: string; methodName?: string; } export interface DRYViolation extends Violation { type: 'exact-duplicate' | 'pattern-duplication' | 'similar-logic'; similarity?: number; locations?: Array<{ file: string; line: number; }>; metrics?: { duplicateLines: number; totalLines: number; }; } export interface DataAccessPattern { source: 'component' | 'api' | 'service'; filePath: string; database?: string; databaseType?: string; tables: string[]; queries: QueryInfo[]; performanceRisk: 'low' | 'medium' | 'high'; hasOrganizationFilter?: boolean; hasSqlInjectionRisk?: boolean; } export interface DataAccessViolation extends Violation { pattern: 'raw-sql' | 'missing-validation' | 'no-pooling' | 'performance-issue'; query?: string; risk?: 'sql-injection' | 'performance' | 'security' | 'data-leak'; } export interface SecurityPatternIssue extends Violation { pattern: 'missing-auth' | 'inconsistent-auth' | 'missing-validation' | 'security-bypass'; expectedPattern?: string; } export interface ReportGenerator { generate(result: AuditResult, format: ReportFormat): string; } export interface Recommendation { title: string; description: string; priority: 'high' | 'medium' | 'low'; effort: 'small' | 'medium' | 'large'; category: string; affectedFiles: string[]; exampleImplementation?: string; } export interface PathProfile { /** Unique name for this profile (used in attribution and built-in replacement). */ name: string; /** Glob patterns matching file paths relative to project root. */ paths: string[]; /** Analyzer config overrides applied to files matching this profile. */ overrides: Record; /** Set to false to replace a built-in profile of the same name. */ builtin?: boolean; } export interface AuditConfig { includePaths?: string[]; excludePaths?: string[]; enabledAnalyzers?: string[]; outputFormats?: ReportFormat[]; outputDir?: string; outputDirectory?: string; minSeverity?: Severity; failOnCritical?: boolean; showProgress?: boolean; parallel?: boolean; thresholds?: { maxCritical?: number; maxWarnings?: number; maxSuggestions?: number; minHealthScore?: number; }; /** Per-directory config overrides. Ordered array — later matching profiles win on merge. */ pathProfiles?: PathProfile[]; /** Set to false to disable all built-in profiles. */ builtin?: boolean; /** Per-rule severity overrides applied globally (before per-file path profile caps). */ severityOverrides?: Record; /** Spec 13 — Churn extraction config. */ churn?: ChurnConfig; /** Spec 13 — Diverging-clone detection config. */ divergence?: DivergenceConfig; /** Spec 15 — Cross-domain analysis config. */ crossDomain?: CrossDomainConfig; analyzerOptions?: Record; } export type PageAnalysis = ComponentAnalysis; export type RouteAnalysis = SecurityAnalysis; export type AuthWrapper = string; export type AuthPatternIssue = SecurityPatternIssue; export type DatabaseType = string; export type SeverityLevel = Severity; export type RecommendationPriority = 'high' | 'medium' | 'low'; export interface AuditMetadata { auditDuration: number; filesAnalyzed: number; analyzersRun: string[]; configUsed?: AuditOptions; reports?: string[]; } export interface BaseAnalyzerOptions { verbose?: boolean; configFile?: string; } export interface FileInfo { path: string; size: number; lastModified: Date; } export interface ImportInfo { moduleSpecifier: string; importedNames: string[]; isTypeOnly: boolean; line: number; } export interface ExportInfo { name: string; isDefault: boolean; isTypeOnly: boolean; line: number; } export interface AuditProgress { current: number; total: number; analyzer: string; file?: string; phase?: string; message?: string; } export interface AnalyzerConfigDocument { $loki?: number; meta?: any; analyzerName: string; projectPath?: string | null; config: Record; isGlobal: boolean; version?: string; createdAt: Date; updatedAt: Date; createdBy: 'system' | 'user'; metadata?: { description?: string; category?: string; dependencies?: string[]; }; } /** * Audit scope — controls which files are analyzed. * * - `all` – default; discover and analyze everything * - `changed` – re-parse indexed files and only analyze functions whose * content_hash differs from stored, plus new/deleted functions * - `git:` – git diff --name-only (plus untracked), then * function-level narrowing as in `changed` * - `string[]` – explicit list of file paths/globs (the `files` scope) */ export type AuditScope = 'all' | 'changed' | `git:${string}` | string[]; export interface AuditRunnerOptions extends AuditOptions { progressCallback?: (progress: AuditProgress) => void; errorCallback?: (error: Error, context: string) => void; outputDirectory?: string; configName?: string; projectRoot?: string; analyzerConfigs?: Record; indexFunctions?: boolean; analyzerConcurrency?: number; /** Cooperative cancel (MCP parent or worker soft budget). Checked between analyzers and on progress. */ abortSignal?: AbortSignal; /** Skip glob discovery; analyze exactly these absolute paths. */ explicitFiles?: string[]; /** * If more files match than this limit, the runner completes one chunk and throws AuditHandoffError * with partialResult and remainingFiles so another worker can continue. */ maxFilesPerRun?: number; /** Worker IPC only: soft wall-clock budget for a forked shard (not used by in-process runs). */ shardSoftBudgetMs?: number; /** Audit scope: controls which files are analyzed. Default: 'all'. */ scope?: AuditScope; /** Path profiles from config (Spec-20). */ pathProfiles?: PathProfile[]; } export interface FunctionMetadata { name: string; filePath: string; lineNumber?: number; startLine?: number; endLine?: number; language?: string; dependencies: string[]; purpose: string; context: string; metadata?: Record; } export interface EnhancedFunctionMetadata extends FunctionMetadata { signature: string; parameters: Array<{ name: string; type?: string; description?: string; optional?: boolean; defaultValue?: string; }>; returnType?: string; jsDoc?: { description?: string; examples?: string[]; tags?: Record; }; typeInfo?: { generics?: string[]; interfaces?: string[]; types?: string[]; }; complexity?: number; tokens?: string[]; tokenizedName?: string; lastModified?: Date; body?: string; content_hash?: string; metadata?: { entityType?: 'function' | 'component'; componentType?: 'functional' | 'class' | 'memo' | 'forwardRef'; hooks?: HookUsage[]; props?: PropDefinition[]; functionCalls?: string[]; calledBy?: string[]; usedImports?: string[]; unusedImports?: string[]; importUsage?: ImportUsageInfo[]; dependencyDepth?: number; body?: string; contentMatches?: Array<{ term: string; line: number; column: number; }>; matchContexts?: Array<{ match: { term: string; line: number; column: number; }; context: { before: string[]; line: string; after: string[]; }; }>; }; } export interface ParsedQuery { terms: string[]; originalTerms?: string[]; phrases: string[]; excludedTerms: string[]; filters: { filePath?: string; fileType?: string; language?: string; hasJsDoc?: boolean; isExported?: boolean; complexity?: { min?: number; max?: number; }; dateRange?: { start?: Date; end?: Date; }; metadata?: { entityType?: string; componentType?: string; hasHook?: string; hasProp?: string; usesDependency?: string; callsFunction?: string; calledByFunction?: string; dependsOnModule?: string; hasUnusedImports?: boolean; cssProperty?: string; cssValue?: string; styleMechanism?: string; styleToken?: string; }; }; fuzzy?: boolean; stemming?: boolean; searchFields?: string[]; } export interface SearchOptions { query?: string; parsedQuery?: ParsedQuery; filters?: { language?: string; filePath?: string; hasAnyDependency?: string[]; fileType?: string; hasJsDoc?: boolean; isExported?: boolean; complexity?: { min?: number; max?: number; }; dateRange?: { start?: Date; end?: Date; }; metadata?: { entityType?: string; componentType?: string; hasHook?: string; hasProp?: string; usesDependency?: string; callsFunction?: string; calledByFunction?: string; dependsOnModule?: string; hasUnusedImports?: boolean; }; }; searchStrategy?: 'exact' | 'fuzzy' | 'semantic'; searchFields?: Array<'name' | 'signature' | 'jsDoc' | 'parameters' | 'returnType' | 'purpose' | 'context'>; searchMode?: 'metadata' | 'content' | 'both'; scoringWeights?: { nameMatch?: number; signatureMatch?: number; jsDocMatch?: number; parameterMatch?: number; purposeMatch?: number; contextMatch?: number; }; limit?: number; offset?: number; includeSnippets?: boolean; highlightMatches?: boolean; } export interface RegisterResult { success: boolean; registered: number; failed: number; errors?: Array<{ function: string; error: string; }>; } export interface SearchResult { functions: Array; matchContexts?: Array<{ match: { term: string; line: number; column: number; }; context: { before: string[]; line: string; after: string[]; }; }>; }>; totalCount: number; query?: string; parsedQuery?: ParsedQuery; executionTime: number; facets?: { languages?: Record; fileTypes?: Record; complexityRanges?: Record; }; suggestions?: string[]; } export interface IndexStats { totalFunctions: number; languages: Record; topDependencies: Array<{ name: string; count: number; }>; filesIndexed: number; lastUpdated: Date; } export interface ComponentMetadata extends FunctionMetadata { entityType: 'component'; componentType: 'functional' | 'class' | 'memo' | 'forwardRef'; props?: PropDefinition[]; hooks?: HookUsage[]; jsxElements?: string[]; imports?: ComponentImport[]; hasErrorBoundary?: boolean; complexity?: number; isExported: boolean; } export interface PropDefinition { name: string; type?: string; required: boolean; hasDefault: boolean; } export interface HookUsage { name: string; line: number; customHook: boolean; } export interface ComponentImport { name: string; path: string; isDefault: boolean; } export declare enum ResponsibilityType { DataFetching = "data-fetching", FormHandling = "form-handling", UIState = "ui-state", BusinessLogic = "business-logic", SideEffects = "side-effects", EventHandling = "event-handling", Routing = "routing", Authentication = "authentication", Layout = "layout-styling", DataTransformation = "data-transformation", Subscriptions = "subscriptions", ErrorHandling = "error-handling", StateManagement = "state-management" } export interface ComponentResponsibility { type: ResponsibilityType; indicators: string[]; severity: 'related' | 'unrelated' | 'mixed'; line?: number; column?: number; details?: string; } export interface ComponentPattern { name: string; indicators: PatternIndicator[]; allowedResponsibilities: ResponsibilityType[]; relatedResponsibilities?: ResponsibilityType[][]; complexityMultiplier: number; description: string; } export interface PatternIndicator { type: 'name' | 'path' | 'hooks' | 'props' | 'imports'; pattern: RegExp | string; weight?: number; } export interface ComponentPatternConfig { patterns: ComponentPattern[]; customPatterns?: ComponentPattern[]; enablePatternDetection: boolean; } export interface RefactoringSuggestion { pattern: 'extract-hook' | 'split-component' | 'container-presenter' | 'compose-components' | 'extract-service'; description: string; example?: string; relatedResponsibilities: ResponsibilityType[]; } export interface ComponentRelationship { parentComponent: string; childComponent: string; usageCount: number; importPath: string; } export interface ReactViolation extends Violation { componentName?: string; violationType: 'missing-props' | 'hooks-violation' | 'no-error-boundary' | 'complexity' | 'performance' | 'accessibility' | 'raw-element'; } export interface ReactAnalyzerConfig { detectFunctionalComponents: boolean; detectClassComponents: boolean; detectMemoComponents: boolean; requirePropTypes: boolean; requireErrorBoundaries: boolean; checkHooksRules: boolean; maxComponentComplexity: number; checkUnnecessaryRerenders: boolean; requireMemoization: boolean; checkAccessibility: boolean; preventDirectDOMAccess: boolean; requireKeyProps: boolean; rawElementCheck?: boolean; /** Mapping of intrinsic element names to wrapper component names (e.g. {"button": "Button"}). */ componentMap?: Record; /** Minimum call sites before a raw-element usage becomes a finding. Default 5. */ wrapperMinUsages?: number; /** Intrinsic elements that trigger raw-element detection. Default ['button', 'input', 'select', 'textarea', 'table']. */ rawElementWatchList?: string[]; } export interface ComponentScanResult { filePath: string; components: ComponentMetadata[]; imports: ComponentImport[]; fileHash?: string; parseErrors?: string[]; } export interface FunctionCall { callee: string; callType: 'direct' | 'method' | 'dynamic'; line: number; column: number; arguments?: number; } export interface ImportMapping { localName: string; importedName: string; modulePath: string; importType: 'named' | 'default' | 'namespace'; isTypeOnly: boolean; } export interface DependencyInfo { imports: ImportMapping[]; functionCalls: FunctionCall[]; identifierUsage: Map; } export interface UsageInfo { usageType: 'direct' | 'type' | 'reexport'; usageCount: number; lineNumbers: number[]; } export interface ImportUsageInfo { importPath: string; usageType: 'direct' | 'type' | 'reexport'; usageCount: number; lineNumbers: number[]; } export interface SchemaColumn { name: string; type: string; nullable?: boolean; primaryKey?: boolean; defaultValue?: string | number | boolean | null; unique?: boolean; indexed?: boolean; length?: number; precision?: number; scale?: number; description?: string; enum?: string[]; } export interface SchemaReference { foreignKey: string; referencedTable: string; referencedColumn: string; onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION'; onUpdate?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION'; description?: string; } export interface SchemaIndex { name: string; columns: string[]; unique?: boolean; type?: 'btree' | 'hash' | 'gin' | 'gist' | 'text' | 'compound'; description?: string; } export interface SchemaTable { name: string; type: 'table' | 'collection' | 'view'; database?: string; schema?: string; columns: SchemaColumn[]; references: SchemaReference[]; indexes?: SchemaIndex[]; constraints?: string[]; description?: string; tags?: string[]; estimatedRows?: number; isTemporary?: boolean; partitionKey?: string; } export interface DatabaseSchema { name: string; type: 'postgresql' | 'mysql' | 'mongodb' | 'sqlite' | 'redis' | 'dynamodb' | 'other'; version?: string; host?: string; port?: number; database?: string; schemas?: string[]; tables: SchemaTable[]; relationships?: SchemaRelationship[]; description?: string; createdAt?: Date; updatedAt?: Date; metadata?: { environment?: 'development' | 'staging' | 'production'; migrations?: string[]; seeds?: string[]; backupFrequency?: string; }; } export interface SchemaRelationship { id: string; type: 'one-to-one' | 'one-to-many' | 'many-to-many'; fromTable: string; toTable: string; fromColumn: string; toColumn: string; description?: string; bidirectional?: boolean; } export interface SchemaDefinition { version: string; name: string; description?: string; databases: DatabaseSchema[]; globalReferences?: SchemaReference[]; metadata?: { author?: string; createdAt?: Date; updatedAt?: Date; tags?: string[]; environment?: string; }; } export interface SchemaViolation extends Violation { schemaType: 'missing-reference' | 'orphaned-table' | 'naming-convention' | 'missing-index' | 'circular-dependency'; tableName?: string; columnName?: string; expectedSchema?: string; actualSchema?: string; } export interface SchemaPattern { pattern: 'entity-table' | 'junction-table' | 'audit-table' | 'lookup-table' | 'temporal-table'; tableNames: string[]; confidence: number; description: string; } export interface SchemaUsage { tableName: string; filePath: string; functionName: string; usageType: 'select' | 'insert' | 'update' | 'delete' | 'create' | 'reference'; line: number; column?: number; rawQuery?: string; parameters?: string[]; } export interface SchemaIndexMetadata { schemaId: string; schemaName: string; indexedAt: Date; tableCount: number; relationshipCount: number; usagePatterns: SchemaUsage[]; discoveredPatterns: SchemaPattern[]; violations: SchemaViolation[]; lastAnalyzed?: Date; } export interface SchemaAwareFunctionMetadata extends EnhancedFunctionMetadata { schemaUsage?: SchemaUsage[]; affectedTables?: string[]; schemaPatterns?: string[]; } export interface StylesAnalyzerConfig { /** Minimum declarations per property before histogram analysis runs. Default 20. */ minCorpus: number; /** Delta-E threshold for color drift detection. Default 2.0. */ colorDeltaE: number; /** Maximum share for outlier values before flagging. Default 0.05. */ outlierMaxShare: number; /** Minimum count for modal value before outliers are flagged. Default 10. */ modeMinCount: number; /** Properties that take scale-family values (margin, padding, gap, font-size). */ scaleProperties: string[]; /** Maximum distinct z-index values before flagging. Default 6. */ zIndexMaxDistinct: number; /** Minimum number of mechanisms before fragmentation is flagged. Default 3. */ mechanismFragmentationMinMechanisms: number; /** Minimum declarations in a rule block for similarity analysis. Default 5. */ declarationSetMinDeclarations: number; /** Jaccard similarity threshold for declaration-set matching. Default 0.9. */ declarationSetSimilarityThreshold: number; /** CSS properties excluded from value-drift detection (categorical domains). Spec 22 R3. */ categoricalPropertyExclusions?: string[]; /** Known Tailwind utility class names for the undefined-class detector. * When provided, these seed the expander's validation cache, bypassing * the compile-probe (useful in test environments without tailwindcss * installed). In production, the compile-probe is always preferred. */ tailwindClasses?: string[]; } /** A mined convention stored in the conventions table. */ export interface Convention { id?: number; domain: 'usage-pair' | 'import-form' | 'error-handling' | 'export-shape' | 'naming'; rule_id: string; antecedent: string | null; consequent: string | null; pattern: string | null; directory: string | null; file_path: string | null; line: number | null; support: number; total_cases: number; confidence: number; exemplar_file: string | null; exemplar_line: number | null; /** For naming conventions: the sub-population (react-component, hook, function). */ export_kind?: string | null; hash: string | null; created_at?: string; } /** Thresholds for the convention miner. */ export interface ConventionMiningConfig { /** Minimum cases for a convention to be established. Default 20. */ minCorpus: number; /** Usage-pair co-occurrence confidence threshold. Default 0.9. */ pairConfidence: number; /** Minimum share for a mode to be considered dominant. Default 0.8. */ modeShare: number; /** Cap to avoid unbounded output per domain. Default 200. */ maxConventionsPerDomain: number; } /** Config for the UniversalConventionsAnalyzer (mirrors mining config). */ export interface ConventionsAnalyzerConfig { minCorpus: number; pairConfidence: number; modeShare: number; maxConventionsPerDomain: number; } /** Config for git churn extraction. */ export interface ChurnConfig { /** Lookback window for git history in months. Default 12. */ churnWindowMonths: number; } /** A single hotspot entry — file or function with its churn×complexity score. */ export interface HotspotEntry { /** File path (repo-relative) or function identifier. */ target: string; /** Type discriminator: 'file' or 'function'. */ type: 'file' | 'function'; /** Hotspot score [0,1] — product of churn and complexity percentiles. */ score: number; /** File churn percentile [0,1]. */ churnPercentile: number; /** Complexity percentile [0,1]. */ complexityPercentile: number; /** Number of commits touching this target. */ commitCount: number; /** Number of distinct authors. */ distinctAuthors: number; /** Author with the most commits. */ dominantAuthor: string; /** Share of commits by the dominant author [0,1]. */ dominantAuthorShare: number; /** Bus-factor risk: true if dominant_author_share ≥ 0.9. */ busFactorRisk: boolean; /** Complexity value (raw, not percentile). */ complexity: number; } /** Summary of trend changes between two full-audit runs of the same target. */ export interface TrendSummary { /** The target directory these trends are for. */ target: string; /** Time range covered — [earliest run timestamp, latest run timestamp]. */ range: [string, string]; /** Run IDs used for comparison (ordered oldest→newest). */ comparedRunIds: string[]; /** Per-rule trend counts. */ rules: Record; } /** Config for diverging-clone detection (R5). */ export interface DivergenceConfig { /** Minimum similarity drop to flag divergence. Default 0.05. */ divergenceThreshold: number; /** Number of consecutive declining runs before flagging. Default 2. */ divergenceRuns: number; /** Minimum Jaccard similarity to seed a pair for tracking. Default 0.5. */ minPairSimilarity: number; } /** Detection mode for DB/validator receiver identification (Spec 21 R3). */ export type DetectionMode = 'hybrid' | 'provenance' | 'names'; /** Shared detection config consumed by provenance module, schema, and data-access analyzers. */ export interface DetectionConfig { mode: DetectionMode; } /** Per-function risk ranking entry (Spec 14 R2). */ export interface RiskEntry { functionName: string; filePath: string; pageRankPercentile: number; betweennessPercentile: number; complexityPercentile: number; untested: boolean; riskScore: number; } /** Directory-level community purity (Spec 14 R3). */ export interface DirectoryPurity { directory: string; totalFiles: number; pluralityCommunity: number; pluralityCount: number; purity: number; } /** Martin metrics per directory/package (Spec 14 R4). */ export interface MartinEntry { directory: string; ce: number; ca: number; instability: number; abstractness: number; distanceFromMain: number; } /** Blast-radius impact estimate for hook path (Spec 14 R6). */ export interface BlastRadiusImpact { editedFunctionCount: number; transitiveCallers: number; reachableExports: number; depthReached: number; latencyMs: number; } /** Summarized graph statistics (Spec 14 R1). */ export interface GraphStats { callNodes: number; callEdges: number; unresolvedCalls: number; unresolvedShare: number; importNodes: number; importEdges: number; } /** Extracted table reference from ORM adapter (feeds schema_usage). */ export interface OrmTableReference { tableName: string; usageType: 'select' | 'insert' | 'update' | 'delete' | 'create' | 'reference'; filePath: string; functionName?: string; line: number; column?: number; rawQuery?: string; parameters?: string[]; } /** ORM adapter contract — same shape as LanguageAdapter registry. */ export interface OrmAdapter { /** Unique adapter name (e.g. "drizzle", "prisma"). */ readonly name: string; /** File globs this adapter handles. */ readonly filePatterns: string[]; /** Extract table references from source code (query-builder patterns). */ extractTableReferences(source: string, filePath: string): OrmTableReference[]; /** Extract schema definitions from source code (schema/model declarations). */ extractSchemaDefinitions(source: string, filePath: string): SchemaTable[]; } /** Config for schema lifecycle detectors (R1). */ export interface SchemaLifecycleConfig { /** Enable written-never-read detection. Default true. */ enableWrittenNeverRead: boolean; /** Enable read-never-written detection. Default true. */ enableReadNeverWritten: boolean; /** Enable transaction-boundary risk detection. Default true. */ enableTransactionBoundaryRisk: boolean; /** Max distinct tables a function can write before flagging txn-boundary risk. Default 4. */ txnTableMax: number; } /** Config for validation-bypass detection (R3). */ export interface ValidatorBypassConfig { /** User-configured validator function names or "path#name". */ validators: string[]; /** Minimum share of peer writers that must reach a validator. Default 0.8. */ modeShare: number; /** Minimum directory corpus size before detection activates. Default 20. */ minCorpus: number; /** BFS depth limit in call graph for validator reach. Default 3. */ depth: number; } /** Config for coverage-by-importance (R4). */ export interface CoverageConfig { /** Glob patterns identifying test files. Default ['**\/*.test.*', '**\/*.spec.*', '**\/__tests__/**']. */ testGlobs: string[]; /** BFS depth from test files for static-reach coverage. Default 2. */ staticReachDepth: number; /** Fraction of top-risk functions to flag when untested. Default 0.1. */ topRiskDecile: number; } /** Aggregate config for the cross-domain analyzer (R1+R3+R4). */ export interface CrossDomainConfig { schemaLifecycle: SchemaLifecycleConfig; validatorBypass: ValidatorBypassConfig; coverage: CoverageConfig; } /** A row in the coverage_data table. */ export interface CoverageEntry { functionName: string; filePath: string; lineNumber: number; /** Which coverage basis was used. */ basis: 'static-reach' | 'measured'; /** Whether this function is covered. */ covered: boolean; /** For measured coverage: source file path (lcov .info or istanbul JSON). */ source?: string; /** When this entry was imported (measured basis only). */ importedAt?: string; } /** Coverage report returned by coverage --by-risk (R4). */ export interface CoverageReport { totalFunctions: number; coveredFunctions: number; coverageRate: number; byRiskDecile: Array<{ decile: number; covered: number; total: number; rate: number; }>; untestedTopDecile: Array<{ functionName: string; filePath: string; riskScore: number; basis: 'static-reach' | 'measured'; }>; /** Whether imported coverage data is stale (older than last full sync). */ staleImport: boolean; } /** Validator set entry for config inspectability (R3). */ export interface ValidatorEntry { /** Function name or "file#name". */ name: string; /** How this validator was discovered. */ basis: 'user-config' | 'provenance' | 'heuristic-match'; /** For provenance basis: the package that sourced it (e.g. "zod"). */ source?: string; /** For heuristic-match basis: confidence is "downgraded". */ confidence?: 'high' | 'downgraded'; /** File path where this validator is defined. */ filePath?: string; } export * from './types/whitelist.js'; //# sourceMappingURL=types.d.ts.map