@ipation/specbridge 2.4.5 → 2.4.7
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/CHANGELOG.md +38 -2
- package/README.md +1 -1
- package/dist/cli.js +156 -135
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +42 -12
- package/dist/index.js +103 -33
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/schemas/decision.schema.ts","../src/core/schemas/config.schema.ts","../src/core/errors/index.ts","../src/utils/fs.ts","../src/utils/yaml.ts","../src/config/loader.ts","../src/registry/loader.ts","../src/utils/glob.ts","../src/registry/registry.ts","../src/inference/scanner.ts","../src/inference/analyzers/base.ts","../src/inference/analyzers/naming.ts","../src/inference/analyzers/imports.ts","../src/inference/analyzers/structure.ts","../src/inference/analyzers/errors.ts","../src/inference/analyzers/index.ts","../src/inference/engine.ts","../src/verification/engine.ts","../src/verification/verifiers/base.ts","../src/verification/verifiers/naming.ts","../src/verification/verifiers/imports.ts","../src/verification/verifiers/errors.ts","../src/verification/verifiers/regex.ts","../src/verification/verifiers/dependencies.ts","../src/verification/verifiers/complexity.ts","../src/verification/verifiers/security.ts","../src/verification/verifiers/api.ts","../src/verification/plugins/loader.ts","../src/utils/logger.ts","../src/verification/verifiers/index.ts","../src/verification/cache.ts","../src/verification/results-cache.ts","../src/verification/applicability.ts","../src/verification/incremental.ts","../src/verification/autofix/engine.ts","../src/propagation/graph.ts","../src/propagation/engine.ts","../src/reporting/reporter.ts","../src/reporting/formats/console.ts","../src/reporting/formats/markdown.ts","../src/reporting/storage.ts","../src/reporting/drift.ts","../src/agent/context.generator.ts","../src/agent/templates.ts","../src/mcp/server.ts","../src/analytics/engine.ts","../src/dashboard/server.ts","../src/lsp/server.ts","../src/lsp/index.ts","../src/integrations/github.ts"],"sourcesContent":["/**\n * Zod schemas for decision YAML validation\n */\nimport { z } from 'zod';\n\n// Status lifecycle\nexport const DecisionStatusSchema = z.enum(['draft', 'active', 'deprecated', 'superseded']);\n\n// Constraint types\nexport const ConstraintTypeSchema = z.enum(['invariant', 'convention', 'guideline']);\n\n// Severity levels\nexport const SeveritySchema = z.enum(['critical', 'high', 'medium', 'low']);\n\n// Verification frequency\nexport const VerificationFrequencySchema = z.enum(['commit', 'pr', 'daily', 'weekly']);\n\n// Decision metadata\nexport const DecisionMetadataSchema = z.object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9-]+$/, 'ID must be lowercase alphanumeric with hyphens'),\n title: z.string().min(1).max(200),\n status: DecisionStatusSchema,\n owners: z.array(z.string().min(1)).min(1),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n supersededBy: z.string().optional(),\n tags: z.array(z.string()).optional(),\n});\n\n// Decision content\nexport const DecisionContentSchema = z.object({\n summary: z.string().min(1).max(500),\n rationale: z.string().min(1),\n context: z.string().optional(),\n consequences: z.array(z.string()).optional(),\n});\n\n// Constraint exception\nexport const ConstraintExceptionSchema = z.object({\n pattern: z.string().min(1),\n reason: z.string().min(1),\n approvedBy: z.string().optional(),\n expiresAt: z.string().datetime().optional(),\n});\n\n// Constraint check (structured verifier specification)\nexport const ConstraintCheckSchema = z.object({\n verifier: z.string().min(1),\n params: z.record(z.string(), z.unknown()).optional(),\n});\n\n// Single constraint\nexport const ConstraintSchema = z.object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9-]+$/, 'Constraint ID must be lowercase alphanumeric with hyphens'),\n type: ConstraintTypeSchema,\n rule: z.string().min(1),\n severity: SeveritySchema,\n scope: z.string().min(1),\n verifier: z.string().optional(),\n check: ConstraintCheckSchema.optional(),\n autofix: z.boolean().optional(),\n exceptions: z.array(ConstraintExceptionSchema).optional(),\n});\n\n// Verification config\nexport const VerificationConfigSchema = z.object({\n check: z.string().min(1),\n target: z.string().min(1),\n frequency: VerificationFrequencySchema,\n timeout: z.number().positive().optional(),\n});\n\n// Links\nexport const LinksSchema = z.object({\n related: z.array(z.string()).optional(),\n supersedes: z.array(z.string()).optional(),\n references: z.array(z.string().url()).optional(),\n});\n\n// Complete decision document\nexport const DecisionSchema = z.object({\n kind: z.literal('Decision'),\n metadata: DecisionMetadataSchema,\n decision: DecisionContentSchema,\n constraints: z.array(ConstraintSchema).min(1),\n verification: z\n .object({\n automated: z.array(VerificationConfigSchema).optional(),\n })\n .optional(),\n links: LinksSchema.optional(),\n});\n\n// Type exports (suffixed with Schema to avoid conflicts with core types)\nexport type DecisionStatusSchema_ = z.infer<typeof DecisionStatusSchema>;\nexport type ConstraintTypeSchema_ = z.infer<typeof ConstraintTypeSchema>;\nexport type SeveritySchema_ = z.infer<typeof SeveritySchema>;\nexport type VerificationFrequencySchema_ = z.infer<typeof VerificationFrequencySchema>;\nexport type DecisionMetadataSchema_ = z.infer<typeof DecisionMetadataSchema>;\nexport type DecisionContentSchema_ = z.infer<typeof DecisionContentSchema>;\nexport type ConstraintExceptionSchema_ = z.infer<typeof ConstraintExceptionSchema>;\nexport type ConstraintCheckSchema_ = z.infer<typeof ConstraintCheckSchema>;\nexport type ConstraintSchema_ = z.infer<typeof ConstraintSchema>;\nexport type VerificationConfigSchema_ = z.infer<typeof VerificationConfigSchema>;\nexport type DecisionTypeSchema = z.infer<typeof DecisionSchema>;\n\n/**\n * Validate a decision document\n */\nexport function validateDecision(\n data: unknown\n): { success: true; data: DecisionTypeSchema } | { success: false; errors: z.ZodError } {\n const result = DecisionSchema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, errors: result.error };\n}\n\n/**\n * Format Zod errors into human-readable messages\n */\nexport function formatValidationErrors(errors: z.ZodError): string[] {\n return errors.issues.map((err) => {\n const path = err.path.join('.');\n return `${path}: ${err.message}`;\n });\n}\n","/**\n * Zod schemas for SpecBridge configuration\n */\nimport { z } from 'zod';\n\n// Severity for level config\nconst SeveritySchema = z.enum(['critical', 'high', 'medium', 'low']);\n\n// Level configuration\nconst LevelConfigSchema = z.object({\n timeout: z.number().positive().optional(),\n severity: z.array(SeveritySchema).optional(),\n});\n\n// Project configuration\nconst ProjectConfigSchema = z.object({\n name: z.string().min(1),\n sourceRoots: z.array(z.string().min(1)).min(1),\n exclude: z.array(z.string()).optional(),\n});\n\n// Inference configuration\nconst InferenceConfigSchema = z.object({\n minConfidence: z.number().min(0).max(100).optional(),\n analyzers: z.array(z.string()).optional(),\n});\n\n// Verification configuration\nconst VerificationConfigSchema = z.object({\n levels: z\n .object({\n commit: LevelConfigSchema.optional(),\n pr: LevelConfigSchema.optional(),\n full: LevelConfigSchema.optional(),\n })\n .optional(),\n});\n\n// Agent configuration\nconst AgentConfigSchema = z.object({\n format: z.enum(['markdown', 'json', 'mcp']).optional(),\n includeRationale: z.boolean().optional(),\n});\n\n// Complete SpecBridge configuration\nexport const SpecBridgeConfigSchema = z.object({\n version: z.string().regex(/^\\d+\\.\\d+$/, 'Version must be in format X.Y'),\n project: ProjectConfigSchema,\n inference: InferenceConfigSchema.optional(),\n verification: VerificationConfigSchema.optional(),\n agent: AgentConfigSchema.optional(),\n});\n\nexport type SpecBridgeConfigType = z.infer<typeof SpecBridgeConfigSchema>;\n\n/**\n * Validate configuration\n */\nexport function validateConfig(\n data: unknown\n): { success: true; data: SpecBridgeConfigType } | { success: false; errors: z.ZodError } {\n const result = SpecBridgeConfigSchema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, errors: result.error };\n}\n\n/**\n * Default configuration\n */\nexport const defaultConfig: SpecBridgeConfigType = {\n version: '1.0',\n project: {\n name: 'my-project',\n sourceRoots: ['src/**/*.ts', 'src/**/*.tsx'],\n exclude: ['**/*.test.ts', '**/*.spec.ts', '**/node_modules/**', '**/dist/**'],\n },\n inference: {\n minConfidence: 70,\n analyzers: ['naming', 'structure', 'imports', 'errors'],\n },\n verification: {\n levels: {\n commit: {\n timeout: 5000,\n severity: ['critical'],\n },\n pr: {\n timeout: 60000,\n severity: ['critical', 'high'],\n },\n full: {\n timeout: 300000,\n severity: ['critical', 'high', 'medium', 'low'],\n },\n },\n },\n agent: {\n format: 'markdown',\n includeRationale: true,\n },\n};\n","/**\n * Custom error types for SpecBridge\n */\n\n/**\n * Base error for SpecBridge\n */\nexport class SpecBridgeError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n public readonly suggestion?: string\n ) {\n super(message);\n this.name = 'SpecBridgeError';\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Configuration errors\n */\nexport class ConfigError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'CONFIG_ERROR', details);\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Decision validation errors\n */\nexport class DecisionValidationError extends SpecBridgeError {\n constructor(\n message: string,\n public readonly decisionId: string,\n public readonly validationErrors: string[]\n ) {\n super(message, 'DECISION_VALIDATION_ERROR', { decisionId, validationErrors });\n this.name = 'DecisionValidationError';\n }\n}\n\n/**\n * Decision not found\n */\nexport class DecisionNotFoundError extends SpecBridgeError {\n constructor(decisionId: string) {\n super(`Decision not found: ${decisionId}`, 'DECISION_NOT_FOUND', { decisionId });\n this.name = 'DecisionNotFoundError';\n }\n}\n\n/**\n * Registry errors\n */\nexport class RegistryError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'REGISTRY_ERROR', details);\n this.name = 'RegistryError';\n }\n}\n\n/**\n * Verification errors\n */\nexport class VerificationError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'VERIFICATION_ERROR', details);\n this.name = 'VerificationError';\n }\n}\n\n/**\n * Inference errors\n */\nexport class InferenceError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'INFERENCE_ERROR', details);\n this.name = 'InferenceError';\n }\n}\n\n/**\n * File system errors\n */\nexport class FileSystemError extends SpecBridgeError {\n constructor(\n message: string,\n public readonly path: string\n ) {\n super(message, 'FILE_SYSTEM_ERROR', { path });\n this.name = 'FileSystemError';\n }\n}\n\n/**\n * Already initialized error\n */\nexport class AlreadyInitializedError extends SpecBridgeError {\n constructor(path: string) {\n super(`SpecBridge is already initialized at ${path}`, 'ALREADY_INITIALIZED', { path });\n this.name = 'AlreadyInitializedError';\n }\n}\n\n/**\n * Not initialized error\n */\nexport class NotInitializedError extends SpecBridgeError {\n constructor() {\n super(\n 'SpecBridge is not initialized. Run \"specbridge init\" first.',\n 'NOT_INITIALIZED',\n undefined,\n 'Run `specbridge init` in this directory to create .specbridge/'\n );\n this.name = 'NotInitializedError';\n }\n}\n\n/**\n * Verifier not found\n */\nexport class VerifierNotFoundError extends SpecBridgeError {\n constructor(verifierId: string) {\n super(`Verifier not found: ${verifierId}`, 'VERIFIER_NOT_FOUND', { verifierId });\n this.name = 'VerifierNotFoundError';\n }\n}\n\n/**\n * Analyzer not found\n */\nexport class AnalyzerNotFoundError extends SpecBridgeError {\n constructor(analyzerId: string) {\n super(`Analyzer not found: ${analyzerId}`, 'ANALYZER_NOT_FOUND', { analyzerId });\n this.name = 'AnalyzerNotFoundError';\n }\n}\n\n/**\n * Hook installation error\n */\nexport class HookError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'HOOK_ERROR', details);\n this.name = 'HookError';\n }\n}\n\n/**\n * Format error message for CLI output\n */\nexport function formatError(error: Error): string {\n if (error instanceof SpecBridgeError) {\n let message = `Error [${error.code}]: ${error.message}`;\n if (error.details) {\n const detailsStr = Object.entries(error.details)\n .filter(([key]) => key !== 'validationErrors')\n .map(([key, value]) => ` ${key}: ${value}`)\n .join('\\n');\n if (detailsStr) {\n message += `\\n${detailsStr}`;\n }\n }\n if (error instanceof DecisionValidationError && error.validationErrors.length > 0) {\n message +=\n '\\nValidation errors:\\n' + error.validationErrors.map((e) => ` - ${e}`).join('\\n');\n }\n if (error.suggestion) {\n message += `\\nSuggestion: ${error.suggestion}`;\n }\n return message;\n }\n return `Error: ${error.message}`;\n}\n","/**\n * File system utilities\n */\nimport { readFile, writeFile, mkdir, access, readdir, stat } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { constants } from 'node:fs';\n\n/**\n * Check if a path exists\n */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a path is a directory\n */\nexport async function isDirectory(path: string): Promise<boolean> {\n try {\n const stats = await stat(path);\n return stats.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a directory exists\n */\nexport async function ensureDir(path: string): Promise<void> {\n await mkdir(path, { recursive: true });\n}\n\n/**\n * Read a text file\n */\nexport async function readTextFile(path: string): Promise<string> {\n return readFile(path, 'utf-8');\n}\n\n/**\n * Write a text file, creating directories as needed\n */\nexport async function writeTextFile(path: string, content: string): Promise<void> {\n await ensureDir(dirname(path));\n await writeFile(path, content, 'utf-8');\n}\n\n/**\n * Read all files in a directory matching a pattern\n */\nexport async function readFilesInDir(\n dirPath: string,\n filter?: (filename: string) => boolean\n): Promise<string[]> {\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n const files = entries.filter((entry) => entry.isFile()).map((entry) => entry.name);\n\n if (filter) {\n return files.filter(filter);\n }\n return files;\n } catch {\n return [];\n }\n}\n\n/**\n * Get the .specbridge directory path\n */\nexport function getSpecBridgeDir(basePath: string = process.cwd()): string {\n return join(basePath, '.specbridge');\n}\n\n/**\n * Get the decisions directory path\n */\nexport function getDecisionsDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'decisions');\n}\n\n/**\n * Get the verifiers directory path\n */\nexport function getVerifiersDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'verifiers');\n}\n\n/**\n * Get the inferred patterns directory path\n */\nexport function getInferredDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'inferred');\n}\n\n/**\n * Get the reports directory path\n */\nexport function getReportsDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'reports');\n}\n\n/**\n * Get the config file path\n */\nexport function getConfigPath(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'config.yaml');\n}\n","/**\n * YAML utilities with comment preservation\n */\nimport { parse, stringify, Document, parseDocument } from 'yaml';\n\n/**\n * Parse YAML string to object\n */\nexport function parseYaml<T = unknown>(content: string): T {\n return parse(content) as T;\n}\n\n/**\n * Stringify object to YAML with nice formatting\n */\nexport function stringifyYaml(data: unknown, options?: { indent?: number }): string {\n return stringify(data, {\n indent: options?.indent ?? 2,\n lineWidth: 100,\n minContentWidth: 20,\n });\n}\n\n/**\n * Parse YAML preserving document structure (for editing)\n */\nexport function parseYamlDocument(content: string): Document {\n return parseDocument(content);\n}\n\n/**\n * Update YAML document preserving comments\n */\nexport function updateYamlDocument(doc: Document, path: string[], value: unknown): void {\n let current: unknown = doc.contents;\n\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n if (key && current && typeof current === 'object' && 'get' in current) {\n current = (current as { get: (key: string) => unknown }).get(key);\n }\n }\n\n const lastKey = path[path.length - 1];\n if (lastKey && current && typeof current === 'object' && 'set' in current) {\n (current as { set: (key: string, value: unknown) => void }).set(lastKey, value);\n }\n}\n","/**\n * Configuration loader\n */\nimport type { SpecBridgeConfig } from '../core/types/index.js';\nimport { validateConfig, defaultConfig } from '../core/schemas/config.schema.js';\nimport { ConfigError, NotInitializedError } from '../core/errors/index.js';\nimport { readTextFile, pathExists, getConfigPath, getSpecBridgeDir } from '../utils/fs.js';\nimport { parseYaml } from '../utils/yaml.js';\n\n/**\n * Load configuration from .specbridge/config.yaml\n */\nexport async function loadConfig(basePath: string = process.cwd()): Promise<SpecBridgeConfig> {\n const specbridgeDir = getSpecBridgeDir(basePath);\n const configPath = getConfigPath(basePath);\n\n // Check if specbridge is initialized\n if (!(await pathExists(specbridgeDir))) {\n throw new NotInitializedError();\n }\n\n // Check if config file exists\n if (!(await pathExists(configPath))) {\n // Return default config if no config file\n return defaultConfig;\n }\n\n // Load and parse config\n const content = await readTextFile(configPath);\n const parsed = parseYaml(content);\n\n // Validate config\n const result = validateConfig(parsed);\n if (!result.success) {\n const errors = result.errors.issues.map((e) => `${e.path.join('.')}: ${e.message}`);\n throw new ConfigError(`Invalid configuration in ${configPath}`, { errors });\n }\n\n return result.data as SpecBridgeConfig;\n}\n\n/**\n * Merge partial config with defaults\n */\nexport function mergeWithDefaults(partial: Partial<SpecBridgeConfig>): SpecBridgeConfig {\n return {\n ...defaultConfig,\n ...partial,\n project: {\n ...defaultConfig.project,\n ...partial.project,\n },\n inference: {\n ...defaultConfig.inference,\n ...partial.inference,\n },\n verification: {\n ...defaultConfig.verification,\n ...partial.verification,\n levels: {\n ...defaultConfig.verification?.levels,\n ...partial.verification?.levels,\n },\n },\n agent: {\n ...defaultConfig.agent,\n ...partial.agent,\n },\n };\n}\n","/**\n * Decision file loader\n */\nimport { join } from 'node:path';\nimport type { Decision } from '../core/types/index.js';\nimport { validateDecision, formatValidationErrors } from '../core/schemas/decision.schema.js';\nimport { DecisionValidationError, FileSystemError } from '../core/errors/index.js';\nimport { readTextFile, readFilesInDir, pathExists } from '../utils/fs.js';\nimport { parseYaml } from '../utils/yaml.js';\n\nexport interface LoadedDecision {\n decision: Decision;\n filePath: string;\n}\n\nexport interface LoadResult {\n decisions: LoadedDecision[];\n errors: LoadError[];\n}\n\nexport interface LoadError {\n filePath: string;\n error: string;\n}\n\n/**\n * Load a single decision file\n */\nexport async function loadDecisionFile(filePath: string): Promise<Decision> {\n if (!(await pathExists(filePath))) {\n throw new FileSystemError(`Decision file not found: ${filePath}`, filePath);\n }\n\n const content = await readTextFile(filePath);\n const parsed = parseYaml(content);\n\n const result = validateDecision(parsed);\n if (!result.success) {\n const errors = formatValidationErrors(result.errors);\n throw new DecisionValidationError(\n `Invalid decision file: ${filePath}`,\n typeof parsed === 'object' && parsed !== null && 'metadata' in parsed\n ? (parsed as { metadata?: { id?: string } }).metadata?.id || 'unknown'\n : 'unknown',\n errors\n );\n }\n\n return result.data as Decision;\n}\n\n/**\n * Load all decisions from a directory\n */\nexport async function loadDecisionsFromDir(dirPath: string): Promise<LoadResult> {\n const decisions: LoadedDecision[] = [];\n const errors: LoadError[] = [];\n\n if (!(await pathExists(dirPath))) {\n return { decisions, errors };\n }\n\n const files = await readFilesInDir(dirPath, (f) => f.endsWith('.decision.yaml'));\n\n for (const file of files) {\n const filePath = join(dirPath, file);\n try {\n const decision = await loadDecisionFile(filePath);\n decisions.push({ decision, filePath });\n } catch (error) {\n errors.push({\n filePath,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return { decisions, errors };\n}\n\n/**\n * Validate a decision file without loading it into registry\n */\nexport async function validateDecisionFile(filePath: string): Promise<{\n valid: boolean;\n errors: string[];\n}> {\n try {\n if (!(await pathExists(filePath))) {\n return { valid: false, errors: [`File not found: ${filePath}`] };\n }\n\n const content = await readTextFile(filePath);\n const parsed = parseYaml(content);\n\n const result = validateDecision(parsed);\n if (!result.success) {\n return { valid: false, errors: formatValidationErrors(result.errors) };\n }\n\n return { valid: true, errors: [] };\n } catch (error) {\n return {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n}\n","/**\n * Glob utilities for file matching\n */\nimport fg from 'fast-glob';\nimport { minimatch } from 'minimatch';\nimport { relative, isAbsolute } from 'node:path';\n\nexport interface GlobOptions {\n cwd?: string;\n ignore?: string[];\n absolute?: boolean;\n onlyFiles?: boolean;\n}\n\n/**\n * Find files matching glob patterns\n */\nexport async function glob(\n patterns: string | string[],\n options: GlobOptions = {}\n): Promise<string[]> {\n const { cwd = process.cwd(), ignore = [], absolute = false, onlyFiles = true } = options;\n\n return fg(patterns, {\n cwd,\n ignore,\n absolute,\n onlyFiles,\n dot: false,\n });\n}\n\n/**\n * Normalize a file path to be relative to a base directory\n * Handles both absolute and relative paths, cross-platform\n */\nexport function normalizePath(filePath: string, basePath: string = process.cwd()): string {\n let resultPath: string;\n\n if (!isAbsolute(filePath)) {\n // Already relative, use as-is\n resultPath = filePath;\n } else {\n // Convert absolute to relative from basePath\n resultPath = relative(basePath, filePath);\n }\n\n // Ensure forward slashes (handle both Unix and Windows separators)\n return resultPath.replace(/\\\\/g, '/');\n}\n\n/**\n * Check if a file path matches a glob pattern\n */\nexport function matchesPattern(\n filePath: string,\n pattern: string,\n options: { cwd?: string } = {}\n): boolean {\n const cwd = options.cwd || process.cwd();\n const normalizedPath = normalizePath(filePath, cwd);\n\n return minimatch(normalizedPath, pattern, { matchBase: true });\n}\n\n/**\n * Check if a file path matches any of the given patterns\n */\nexport function matchesAnyPattern(\n filePath: string,\n patterns: string[],\n options: { cwd?: string } = {}\n): boolean {\n return patterns.some((pattern) => matchesPattern(filePath, pattern, options));\n}\n\n// Re-export minimatch for advanced usage\nexport { minimatch };\n","/**\n * Decision Registry - Central store for architectural decisions\n */\nimport type { Decision, DecisionStatus, ConstraintType, Severity } from '../core/types/index.js';\nimport { DecisionNotFoundError, NotInitializedError } from '../core/errors/index.js';\nimport { loadDecisionsFromDir, type LoadedDecision, type LoadResult } from './loader.js';\nimport { getDecisionsDir, pathExists, getSpecBridgeDir } from '../utils/fs.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface RegistryOptions {\n basePath?: string;\n}\n\nexport interface DecisionFilter {\n status?: DecisionStatus[];\n tags?: string[];\n constraintType?: ConstraintType[];\n severity?: Severity[];\n}\n\nexport interface RegistryConstraintMatch {\n decisionId: string;\n decisionTitle: string;\n constraintId: string;\n type: ConstraintType;\n rule: string;\n severity: Severity;\n scope: string;\n}\n\n/**\n * Decision Registry class\n */\nexport class Registry {\n private decisions: Map<string, LoadedDecision> = new Map();\n private basePath: string;\n private loaded = false;\n\n constructor(options: RegistryOptions = {}) {\n this.basePath = options.basePath || process.cwd();\n }\n\n /**\n * Load all decisions from the decisions directory\n */\n async load(): Promise<LoadResult> {\n // Check if specbridge is initialized\n if (!(await pathExists(getSpecBridgeDir(this.basePath)))) {\n throw new NotInitializedError();\n }\n\n const decisionsDir = getDecisionsDir(this.basePath);\n const result = await loadDecisionsFromDir(decisionsDir);\n\n this.decisions.clear();\n for (const loaded of result.decisions) {\n this.decisions.set(loaded.decision.metadata.id, loaded);\n }\n\n this.loaded = true;\n return result;\n }\n\n /**\n * Ensure registry is loaded\n */\n private ensureLoaded(): void {\n if (!this.loaded) {\n throw new Error('Registry not loaded. Call load() first.');\n }\n }\n\n /**\n * Get all decisions\n */\n getAll(filter?: DecisionFilter): Decision[] {\n this.ensureLoaded();\n\n let decisions = Array.from(this.decisions.values()).map((d) => d.decision);\n\n if (filter) {\n decisions = this.applyFilter(decisions, filter);\n }\n\n return decisions;\n }\n\n /**\n * Get active decisions only\n */\n getActive(): Decision[] {\n return this.getAll({ status: ['active'] });\n }\n\n /**\n * Get a decision by ID\n */\n get(id: string): Decision {\n this.ensureLoaded();\n\n const loaded = this.decisions.get(id);\n if (!loaded) {\n throw new DecisionNotFoundError(id);\n }\n\n return loaded.decision;\n }\n\n /**\n * Get a decision with its file path\n */\n getWithPath(id: string): LoadedDecision {\n this.ensureLoaded();\n\n const loaded = this.decisions.get(id);\n if (!loaded) {\n throw new DecisionNotFoundError(id);\n }\n\n return loaded;\n }\n\n /**\n * Check if a decision exists\n */\n has(id: string): boolean {\n this.ensureLoaded();\n return this.decisions.has(id);\n }\n\n /**\n * Get all decision IDs\n */\n getIds(): string[] {\n this.ensureLoaded();\n return Array.from(this.decisions.keys());\n }\n\n /**\n * Get constraints applicable to a specific file\n */\n getConstraintsForFile(filePath: string, filter?: DecisionFilter): RegistryConstraintMatch[] {\n this.ensureLoaded();\n\n const applicable: RegistryConstraintMatch[] = [];\n let decisions = this.getActive();\n\n if (filter) {\n decisions = this.applyFilter(decisions, filter);\n }\n\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n if (matchesPattern(filePath, constraint.scope)) {\n applicable.push({\n decisionId: decision.metadata.id,\n decisionTitle: decision.metadata.title,\n constraintId: constraint.id,\n type: constraint.type,\n rule: constraint.rule,\n severity: constraint.severity,\n scope: constraint.scope,\n });\n }\n }\n }\n\n return applicable;\n }\n\n /**\n * Get decisions by tag\n */\n getByTag(tag: string): Decision[] {\n return this.getAll().filter((d) => d.metadata.tags?.includes(tag));\n }\n\n /**\n * Get decisions by owner\n */\n getByOwner(owner: string): Decision[] {\n return this.getAll().filter((d) => d.metadata.owners.includes(owner));\n }\n\n /**\n * Apply filter to decisions\n */\n private applyFilter(decisions: Decision[], filter: DecisionFilter): Decision[] {\n return decisions.filter((decision) => {\n // Filter by status\n if (filter.status && !filter.status.includes(decision.metadata.status)) {\n return false;\n }\n\n // Filter by tags\n if (filter.tags) {\n const hasTags = filter.tags.some((tag) => decision.metadata.tags?.includes(tag));\n if (!hasTags) return false;\n }\n\n // Filter by constraint type\n if (filter.constraintType) {\n const hasType = decision.constraints.some((c) => filter.constraintType?.includes(c.type));\n if (!hasType) return false;\n }\n\n // Filter by severity\n if (filter.severity) {\n const hasSeverity = decision.constraints.some((c) => filter.severity?.includes(c.severity));\n if (!hasSeverity) return false;\n }\n\n return true;\n });\n }\n\n /**\n * Get count of decisions by status\n */\n getStatusCounts(): Record<DecisionStatus, number> {\n this.ensureLoaded();\n\n const counts: Record<DecisionStatus, number> = {\n draft: 0,\n active: 0,\n deprecated: 0,\n superseded: 0,\n };\n\n for (const loaded of this.decisions.values()) {\n counts[loaded.decision.metadata.status]++;\n }\n\n return counts;\n }\n\n /**\n * Get total constraint count\n */\n getConstraintCount(): number {\n this.ensureLoaded();\n\n let count = 0;\n for (const loaded of this.decisions.values()) {\n count += loaded.decision.constraints.length;\n }\n\n return count;\n }\n}\n\n/**\n * Create a new registry instance\n */\nexport function createRegistry(options?: RegistryOptions): Registry {\n return new Registry(options);\n}\n","/**\n * Codebase scanner using ts-morph\n */\nimport { Project, SourceFile, Node, SyntaxKind } from 'ts-morph';\nimport { glob } from '../utils/glob.js';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\n\nexport interface ScanResult {\n files: ScannedFile[];\n totalFiles: number;\n totalLines: number;\n}\n\nexport interface ScannedFile {\n path: string;\n sourceFile: SourceFile;\n lines: number;\n}\n\nexport interface ScanOptions {\n sourceRoots: string[];\n exclude?: string[];\n cwd?: string;\n}\n\n/**\n * Scanner class for analyzing TypeScript/JavaScript codebases\n */\nexport class CodeScanner {\n private project: Project;\n private scannedFiles: Map<string, ScannedFile> = new Map();\n\n constructor() {\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n /**\n * Scan files matching the given patterns\n */\n async scan(options: ScanOptions): Promise<ScanResult> {\n const { sourceRoots, exclude = [], cwd = process.cwd() } = options;\n\n // Find files matching patterns\n const files = await glob(sourceRoots, {\n cwd,\n ignore: exclude,\n absolute: true,\n });\n\n // Add files to project\n for (const filePath of files) {\n try {\n const sourceFile = this.project.addSourceFileAtPath(filePath);\n const lines = sourceFile.getEndLineNumber();\n\n this.scannedFiles.set(filePath, {\n path: filePath,\n sourceFile,\n lines,\n });\n } catch {\n // Skip files that can't be parsed\n }\n }\n\n const scannedArray = Array.from(this.scannedFiles.values());\n const totalLines = scannedArray.reduce((sum, f) => sum + f.lines, 0);\n\n return {\n files: scannedArray,\n totalFiles: scannedArray.length,\n totalLines,\n };\n }\n\n /**\n * Get all scanned files\n */\n getFiles(): ScannedFile[] {\n return Array.from(this.scannedFiles.values());\n }\n\n /**\n * Get a specific file\n */\n getFile(path: string): ScannedFile | undefined {\n return this.scannedFiles.get(path);\n }\n\n /**\n * Get project instance for advanced analysis\n */\n getProject(): Project {\n return this.project;\n }\n\n /**\n * Find all classes in scanned files\n */\n findClasses(): { file: string; name: string; line: number }[] {\n const classes: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const classDecl of sourceFile.getClasses()) {\n const name = classDecl.getName();\n if (name) {\n classes.push({\n file: path,\n name,\n line: classDecl.getStartLineNumber(),\n });\n }\n }\n }\n\n return classes;\n }\n\n /**\n * Find all functions in scanned files\n */\n findFunctions(): { file: string; name: string; line: number; isExported: boolean }[] {\n const functions: { file: string; name: string; line: number; isExported: boolean }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n // Top-level functions\n for (const funcDecl of sourceFile.getFunctions()) {\n const name = funcDecl.getName();\n if (name) {\n functions.push({\n file: path,\n name,\n line: funcDecl.getStartLineNumber(),\n isExported: funcDecl.isExported(),\n });\n }\n }\n\n // Arrow functions assigned to variables\n for (const varDecl of sourceFile.getVariableDeclarations()) {\n const init = varDecl.getInitializer();\n if (init && Node.isArrowFunction(init)) {\n functions.push({\n file: path,\n name: varDecl.getName(),\n line: varDecl.getStartLineNumber(),\n isExported: varDecl.isExported(),\n });\n }\n }\n }\n\n return functions;\n }\n\n /**\n * Find all imports in scanned files\n */\n findImports(): { file: string; module: string; named: string[]; line: number }[] {\n const imports: { file: string; module: string; named: string[]; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const module = importDecl.getModuleSpecifierValue();\n const namedImports = importDecl.getNamedImports().map((n) => n.getName());\n\n imports.push({\n file: path,\n module,\n named: namedImports,\n line: importDecl.getStartLineNumber(),\n });\n }\n }\n\n return imports;\n }\n\n /**\n * Find all interfaces in scanned files\n */\n findInterfaces(): { file: string; name: string; line: number }[] {\n const interfaces: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n interfaces.push({\n file: path,\n name: interfaceDecl.getName(),\n line: interfaceDecl.getStartLineNumber(),\n });\n }\n }\n\n return interfaces;\n }\n\n /**\n * Find all type aliases in scanned files\n */\n findTypeAliases(): { file: string; name: string; line: number }[] {\n const types: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n types.push({\n file: path,\n name: typeAlias.getName(),\n line: typeAlias.getStartLineNumber(),\n });\n }\n }\n\n return types;\n }\n\n /**\n * Find try-catch blocks in scanned files\n */\n findTryCatchBlocks(): { file: string; line: number; hasThrow: boolean }[] {\n const blocks: { file: string; line: number; hasThrow: boolean }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isTryStatement(node)) {\n const catchClause = node.getCatchClause();\n const hasThrow = catchClause\n ? catchClause.getDescendantsOfKind(SyntaxKind.ThrowStatement).length > 0\n : false;\n\n blocks.push({\n file: path,\n line: node.getStartLineNumber(),\n hasThrow,\n });\n }\n });\n }\n\n return blocks;\n }\n}\n\n/**\n * Create a scanner from config\n */\nexport function createScannerFromConfig(_config: SpecBridgeConfig): CodeScanner {\n return new CodeScanner();\n}\n","/**\n * Base analyzer interface\n */\nimport type { Pattern, PatternExample } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\n\n/**\n * Analyzer interface - all analyzers must implement this\n */\nexport interface Analyzer {\n /**\n * Unique identifier for this analyzer\n */\n readonly id: string;\n\n /**\n * Human-readable name\n */\n readonly name: string;\n\n /**\n * Description of what this analyzer detects\n */\n readonly description: string;\n\n /**\n * Analyze the codebase and return detected patterns\n */\n analyze(scanner: CodeScanner): Promise<Pattern[]>;\n}\n\n/**\n * Helper to create a pattern with consistent structure\n */\nexport function createPattern(\n analyzer: string,\n params: {\n id: string;\n name: string;\n description: string;\n confidence: number;\n occurrences: number;\n examples: PatternExample[];\n suggestedConstraint?: Pattern['suggestedConstraint'];\n }\n): Pattern {\n return {\n analyzer,\n ...params,\n };\n}\n\n/**\n * Calculate confidence based on occurrence ratio\n */\nexport function calculateConfidence(\n occurrences: number,\n total: number,\n minOccurrences: number = 3\n): number {\n if (occurrences < minOccurrences) {\n return 0;\n }\n\n const ratio = occurrences / total;\n // Scale from 50 (at minOccurrences) to 100 (at 100%)\n return Math.min(100, Math.round(50 + ratio * 50));\n}\n\n/**\n * Extract a code snippet around a line\n */\nexport function extractSnippet(content: string, line: number, contextLines: number = 1): string {\n const lines = content.split('\\n');\n const start = Math.max(0, line - 1 - contextLines);\n const end = Math.min(lines.length, line + contextLines);\n\n return lines.slice(start, end).join('\\n');\n}\n","/**\n * Naming convention analyzer\n */\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\ninterface NamingPattern {\n convention: string;\n regex: RegExp;\n description: string;\n}\n\nconst CLASS_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Classes use PascalCase' },\n];\n\nconst FUNCTION_PATTERNS: NamingPattern[] = [\n { convention: 'camelCase', regex: /^[a-z][a-zA-Z0-9]*$/, description: 'Functions use camelCase' },\n { convention: 'snake_case', regex: /^[a-z][a-z0-9_]*$/, description: 'Functions use snake_case' },\n];\n\nconst INTERFACE_PATTERNS: NamingPattern[] = [\n {\n convention: 'PascalCase',\n regex: /^[A-Z][a-zA-Z0-9]*$/,\n description: 'Interfaces use PascalCase',\n },\n {\n convention: 'IPrefixed',\n regex: /^I[A-Z][a-zA-Z0-9]*$/,\n description: 'Interfaces are prefixed with I',\n },\n];\n\nconst TYPE_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Types use PascalCase' },\n {\n convention: 'TSuffixed',\n regex: /^[A-Z][a-zA-Z0-9]*Type$/,\n description: 'Types are suffixed with Type',\n },\n];\n\nexport class NamingAnalyzer implements Analyzer {\n readonly id = 'naming';\n readonly name = 'Naming Convention Analyzer';\n readonly description = 'Detects naming conventions for classes, functions, interfaces, and types';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze class naming\n const classPattern = this.analyzeClassNaming(scanner);\n if (classPattern) patterns.push(classPattern);\n\n // Analyze function naming\n const functionPattern = this.analyzeFunctionNaming(scanner);\n if (functionPattern) patterns.push(functionPattern);\n\n // Analyze interface naming\n const interfacePattern = this.analyzeInterfaceNaming(scanner);\n if (interfacePattern) patterns.push(interfacePattern);\n\n // Analyze type naming\n const typePattern = this.analyzeTypeNaming(scanner);\n if (typePattern) patterns.push(typePattern);\n\n return patterns;\n }\n\n private analyzeClassNaming(scanner: CodeScanner): Pattern | null {\n const classes = scanner.findClasses();\n if (classes.length < 3) return null;\n\n const matches = this.findBestMatch(\n classes.map((c) => c.name),\n CLASS_PATTERNS\n );\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-classes',\n name: 'Class Naming Convention',\n description: `Classes follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: classes.slice(0, 3).map((c) => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Classes should use ${matches.convention} naming convention`,\n severity: 'medium',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeFunctionNaming(scanner: CodeScanner): Pattern | null {\n const functions = scanner.findFunctions();\n if (functions.length < 3) return null;\n\n const matches = this.findBestMatch(\n functions.map((f) => f.name),\n FUNCTION_PATTERNS\n );\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-functions',\n name: 'Function Naming Convention',\n description: `Functions follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: functions.slice(0, 3).map((f) => ({\n file: f.file,\n line: f.line,\n snippet: `function ${f.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Functions should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeInterfaceNaming(scanner: CodeScanner): Pattern | null {\n const interfaces = scanner.findInterfaces();\n if (interfaces.length < 3) return null;\n\n const matches = this.findBestMatch(\n interfaces.map((i) => i.name),\n INTERFACE_PATTERNS\n );\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-interfaces',\n name: 'Interface Naming Convention',\n description: `Interfaces follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: interfaces.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `interface ${i.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Interfaces should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeTypeNaming(scanner: CodeScanner): Pattern | null {\n const types = scanner.findTypeAliases();\n if (types.length < 3) return null;\n\n const matches = this.findBestMatch(\n types.map((t) => t.name),\n TYPE_PATTERNS\n );\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-types',\n name: 'Type Alias Naming Convention',\n description: `Type aliases follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: types.slice(0, 3).map((t) => ({\n file: t.file,\n line: t.line,\n snippet: `type ${t.name}`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: `Type aliases should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private findBestMatch(\n names: string[],\n patterns: NamingPattern[]\n ): { convention: string; confidence: number; matchCount: number } | null {\n let bestMatch: { convention: string; matchCount: number } | null = null;\n\n for (const pattern of patterns) {\n const matchCount = names.filter((name) => pattern.regex.test(name)).length;\n if (!bestMatch || matchCount > bestMatch.matchCount) {\n bestMatch = { convention: pattern.convention, matchCount };\n }\n }\n\n if (!bestMatch || bestMatch.matchCount < 3) return null;\n\n const confidence = calculateConfidence(bestMatch.matchCount, names.length);\n if (confidence < 50) return null;\n\n return {\n convention: bestMatch.convention,\n confidence,\n matchCount: bestMatch.matchCount,\n };\n }\n}\n","/**\n * Import pattern analyzer\n */\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class ImportsAnalyzer implements Analyzer {\n readonly id = 'imports';\n readonly name = 'Import Pattern Analyzer';\n readonly description = 'Detects import organization patterns and module usage conventions';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze barrel imports\n const barrelPattern = this.analyzeBarrelImports(scanner);\n if (barrelPattern) patterns.push(barrelPattern);\n\n // Analyze relative vs absolute imports\n const relativePattern = this.analyzeRelativeImports(scanner);\n if (relativePattern) patterns.push(relativePattern);\n\n // Analyze commonly used modules\n const modulePatterns = this.analyzeCommonModules(scanner);\n patterns.push(...modulePatterns);\n\n return patterns;\n }\n\n private analyzeBarrelImports(scanner: CodeScanner): Pattern | null {\n const imports = scanner.findImports();\n const barrelImports = imports.filter((i) => {\n const modulePath = i.module;\n return (\n modulePath.startsWith('.') && !modulePath.includes('.js') && !modulePath.includes('.ts')\n );\n });\n\n // Check for index imports\n const indexImports = barrelImports.filter((i) => {\n return i.module.endsWith('/index') || !i.module.includes('/');\n });\n\n if (indexImports.length < 3) return null;\n\n const confidence = calculateConfidence(indexImports.length, barrelImports.length);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-barrel',\n name: 'Barrel Import Pattern',\n description: 'Modules are imported through barrel (index) files',\n confidence,\n occurrences: indexImports.length,\n examples: indexImports.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 3).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: 'Import from barrel (index) files rather than individual modules',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeRelativeImports(scanner: CodeScanner): Pattern | null {\n const imports = scanner.findImports();\n const relativeImports = imports.filter((i) => i.module.startsWith('.'));\n const absoluteImports = imports.filter(\n (i) => !i.module.startsWith('.') && !i.module.startsWith('@')\n );\n const aliasImports = imports.filter(\n (i) => i.module.startsWith('@/') || i.module.startsWith('~')\n );\n\n // Determine dominant pattern\n const total = relativeImports.length + absoluteImports.length + aliasImports.length;\n if (total < 10) return null;\n\n if (aliasImports.length > relativeImports.length && aliasImports.length >= 5) {\n const confidence = calculateConfidence(aliasImports.length, total);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-alias',\n name: 'Path Alias Import Pattern',\n description: 'Imports use path aliases (@ or ~) instead of relative paths',\n confidence,\n occurrences: aliasImports.length,\n examples: aliasImports.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: 'Use path aliases instead of relative imports',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n if (relativeImports.length > aliasImports.length * 2 && relativeImports.length >= 5) {\n const confidence = calculateConfidence(relativeImports.length, total);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-relative',\n name: 'Relative Import Pattern',\n description: 'Imports use relative paths',\n confidence,\n occurrences: relativeImports.length,\n examples: relativeImports.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Use relative imports for local modules',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeCommonModules(scanner: CodeScanner): Pattern[] {\n const patterns: Pattern[] = [];\n const imports = scanner.findImports();\n\n // Count external module usage\n const moduleCounts = new Map<string, { count: number; examples: typeof imports }>();\n\n for (const imp of imports) {\n // Skip relative imports\n if (imp.module.startsWith('.')) continue;\n\n // Get the package name (handle scoped packages)\n const parts = imp.module.split('/');\n const packageName =\n imp.module.startsWith('@') && parts.length > 1 ? `${parts[0]}/${parts[1]}` : parts[0];\n\n if (packageName) {\n const existing = moduleCounts.get(packageName) || { count: 0, examples: [] };\n existing.count++;\n existing.examples.push(imp);\n moduleCounts.set(packageName, existing);\n }\n }\n\n // Create patterns for commonly used modules\n for (const [packageName, data] of moduleCounts) {\n if (data.count >= 5) {\n const confidence = Math.min(100, 50 + data.count * 2);\n\n patterns.push(\n createPattern(this.id, {\n id: `imports-module-${packageName.replace(/[/@]/g, '-')}`,\n name: `${packageName} Usage`,\n description: `${packageName} is used across ${data.count} files`,\n confidence,\n occurrences: data.count,\n examples: data.examples.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ') || '...'} } from '${i.module}'`,\n })),\n })\n );\n }\n }\n\n return patterns;\n }\n}\n","/**\n * Code structure pattern analyzer\n */\nimport { basename, dirname } from 'node:path';\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner, ScannedFile } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class StructureAnalyzer implements Analyzer {\n readonly id = 'structure';\n readonly name = 'Code Structure Analyzer';\n readonly description = 'Detects file organization and directory structure patterns';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n const files = scanner.getFiles();\n\n // Analyze directory conventions\n const dirPatterns = this.analyzeDirectoryConventions(files);\n patterns.push(...dirPatterns);\n\n // Analyze file naming conventions\n const filePatterns = this.analyzeFileNaming(files);\n patterns.push(...filePatterns);\n\n // Analyze colocation patterns\n const colocationPattern = this.analyzeColocation(files);\n if (colocationPattern) patterns.push(colocationPattern);\n\n return patterns;\n }\n\n private analyzeDirectoryConventions(files: ScannedFile[]): Pattern[] {\n const patterns: Pattern[] = [];\n const dirCounts = new Map<string, number>();\n\n // Count files per directory name\n for (const file of files) {\n const dir = basename(dirname(file.path));\n dirCounts.set(dir, (dirCounts.get(dir) || 0) + 1);\n }\n\n // Check for common directory structures\n const commonDirs = [\n { name: 'components', description: 'UI components are organized in a components directory' },\n { name: 'hooks', description: 'Custom hooks are organized in a hooks directory' },\n { name: 'utils', description: 'Utility functions are organized in a utils directory' },\n { name: 'services', description: 'Service modules are organized in a services directory' },\n { name: 'types', description: 'Type definitions are organized in a types directory' },\n { name: 'api', description: 'API modules are organized in an api directory' },\n { name: 'lib', description: 'Library code is organized in a lib directory' },\n { name: 'core', description: 'Core modules are organized in a core directory' },\n ];\n\n for (const { name, description } of commonDirs) {\n const count = dirCounts.get(name);\n if (count && count >= 3) {\n const exampleFiles = files.filter((f) => basename(dirname(f.path)) === name).slice(0, 3);\n\n patterns.push(\n createPattern(this.id, {\n id: `structure-dir-${name}`,\n name: `${name}/ Directory Convention`,\n description,\n confidence: Math.min(100, 60 + count * 5),\n occurrences: count,\n examples: exampleFiles.map((f) => ({\n file: f.path,\n line: 1,\n snippet: basename(f.path),\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `${name.charAt(0).toUpperCase() + name.slice(1)} should be placed in the ${name}/ directory`,\n severity: 'low',\n scope: `src/**/${name}/**/*.ts`,\n },\n })\n );\n }\n }\n\n return patterns;\n }\n\n private analyzeFileNaming(files: ScannedFile[]): Pattern[] {\n const patterns: Pattern[] = [];\n\n // Check for suffix patterns\n const suffixPatterns: { suffix: string; pattern: RegExp; description: string }[] = [\n { suffix: '.test.ts', pattern: /\\.test\\.ts$/, description: 'Test files use .test.ts suffix' },\n { suffix: '.spec.ts', pattern: /\\.spec\\.ts$/, description: 'Test files use .spec.ts suffix' },\n {\n suffix: '.types.ts',\n pattern: /\\.types\\.ts$/,\n description: 'Type definition files use .types.ts suffix',\n },\n {\n suffix: '.utils.ts',\n pattern: /\\.utils\\.ts$/,\n description: 'Utility files use .utils.ts suffix',\n },\n {\n suffix: '.service.ts',\n pattern: /\\.service\\.ts$/,\n description: 'Service files use .service.ts suffix',\n },\n {\n suffix: '.controller.ts',\n pattern: /\\.controller\\.ts$/,\n description: 'Controller files use .controller.ts suffix',\n },\n {\n suffix: '.model.ts',\n pattern: /\\.model\\.ts$/,\n description: 'Model files use .model.ts suffix',\n },\n {\n suffix: '.schema.ts',\n pattern: /\\.schema\\.ts$/,\n description: 'Schema files use .schema.ts suffix',\n },\n ];\n\n for (const { suffix, pattern, description } of suffixPatterns) {\n const matchingFiles = files.filter((f) => pattern.test(f.path));\n\n if (matchingFiles.length >= 3) {\n const confidence = Math.min(100, 60 + matchingFiles.length * 3);\n\n patterns.push(\n createPattern(this.id, {\n id: `structure-suffix-${suffix.replace(/\\./g, '-')}`,\n name: `${suffix} File Naming`,\n description,\n confidence,\n occurrences: matchingFiles.length,\n examples: matchingFiles.slice(0, 3).map((f) => ({\n file: f.path,\n line: 1,\n snippet: basename(f.path),\n })),\n })\n );\n }\n }\n\n return patterns;\n }\n\n private analyzeColocation(files: ScannedFile[]): Pattern | null {\n // Check if test files are colocated with source files\n const testFiles = files.filter((f) => /\\.(test|spec)\\.tsx?$/.test(f.path));\n const sourceFiles = files.filter((f) => !/\\.(test|spec)\\.tsx?$/.test(f.path));\n\n if (testFiles.length < 3) return null;\n\n let colocatedCount = 0;\n const colocatedExamples: { file: string; line: number; snippet: string }[] = [];\n\n for (const testFile of testFiles) {\n const testDir = dirname(testFile.path);\n const testName = basename(testFile.path).replace(/\\.(test|spec)\\.tsx?$/, '');\n\n // Check if corresponding source file is in same directory\n const hasColocatedSource = sourceFiles.some(\n (s) => dirname(s.path) === testDir && basename(s.path).startsWith(testName)\n );\n\n if (hasColocatedSource) {\n colocatedCount++;\n if (colocatedExamples.length < 3) {\n colocatedExamples.push({\n file: testFile.path,\n line: 1,\n snippet: basename(testFile.path),\n });\n }\n }\n }\n\n const confidence = calculateConfidence(colocatedCount, testFiles.length);\n if (confidence < 60) return null;\n\n return createPattern(this.id, {\n id: 'structure-colocation',\n name: 'Test Colocation Pattern',\n description: 'Test files are colocated with their source files',\n confidence,\n occurrences: colocatedCount,\n examples: colocatedExamples,\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Test files should be colocated with their source files',\n severity: 'low',\n scope: 'src/**/*.test.ts',\n },\n });\n }\n}\n","/**\n * Error handling pattern analyzer\n */\nimport { Node } from 'ts-morph';\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class ErrorsAnalyzer implements Analyzer {\n readonly id = 'errors';\n readonly name = 'Error Handling Analyzer';\n readonly description = 'Detects error handling patterns and custom error class usage';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze custom error classes\n const errorClassPattern = this.analyzeCustomErrorClasses(scanner);\n if (errorClassPattern) patterns.push(errorClassPattern);\n\n // Analyze try-catch patterns\n const tryCatchPattern = this.analyzeTryCatchPatterns(scanner);\n if (tryCatchPattern) patterns.push(tryCatchPattern);\n\n // Analyze error throwing patterns\n const throwPattern = this.analyzeThrowPatterns(scanner);\n if (throwPattern) patterns.push(throwPattern);\n\n return patterns;\n }\n\n private analyzeCustomErrorClasses(scanner: CodeScanner): Pattern | null {\n const classes = scanner.findClasses();\n const errorClasses = classes.filter(\n (c) => c.name.endsWith('Error') || c.name.endsWith('Exception')\n );\n\n if (errorClasses.length < 2) return null;\n\n // Check if they extend a common base\n const files = scanner.getFiles();\n const baseCount: Map<string, number> = new Map();\n\n for (const errorClass of errorClasses) {\n const file = files.find((f) => f.path === errorClass.file);\n if (!file) continue;\n\n const classDecl = file.sourceFile.getClass(errorClass.name);\n if (!classDecl) continue;\n\n const extendClause = classDecl.getExtends();\n if (extendClause) {\n const baseName = extendClause.getText();\n if (baseName !== 'Error' && baseName.endsWith('Error')) {\n baseCount.set(baseName, (baseCount.get(baseName) || 0) + 1);\n }\n }\n }\n\n // Find the custom base with the most extending classes\n let customBaseName: string | null = null;\n let maxCount = 0;\n for (const [baseName, count] of baseCount.entries()) {\n if (count > maxCount) {\n maxCount = count;\n customBaseName = baseName;\n }\n }\n\n // Check for custom base pattern (requires >= 3 extending the same custom base)\n if (maxCount >= 3 && customBaseName) {\n const confidence = calculateConfidence(maxCount, errorClasses.length);\n\n return createPattern(this.id, {\n id: 'errors-custom-base',\n name: 'Custom Error Base Class',\n description: `Custom errors extend a common base class (${customBaseName})`,\n confidence,\n occurrences: maxCount,\n examples: errorClasses.slice(0, 3).map((c) => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name} extends ${customBaseName}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Custom error classes should extend ${customBaseName}`,\n severity: 'medium',\n scope: 'src/**/*.ts',\n verifier: 'errors',\n },\n });\n }\n\n // Fall back to generic custom error classes pattern (requires >= 3 error classes)\n if (errorClasses.length >= 3) {\n const confidence = Math.min(100, 50 + errorClasses.length * 5);\n\n return createPattern(this.id, {\n id: 'errors-custom-classes',\n name: 'Custom Error Classes',\n description: 'Custom error classes are used for domain-specific errors',\n confidence,\n occurrences: errorClasses.length,\n examples: errorClasses.slice(0, 3).map((c) => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name}`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Use custom error classes for domain-specific errors',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeTryCatchPatterns(scanner: CodeScanner): Pattern | null {\n const tryCatchBlocks = scanner.findTryCatchBlocks();\n\n if (tryCatchBlocks.length < 3) return null;\n\n // Check how many rethrow vs swallow\n const rethrowCount = tryCatchBlocks.filter((b) => b.hasThrow).length;\n const swallowCount = tryCatchBlocks.length - rethrowCount;\n\n if (rethrowCount >= 3 && rethrowCount > swallowCount) {\n const confidence = calculateConfidence(rethrowCount, tryCatchBlocks.length);\n\n return createPattern(this.id, {\n id: 'errors-rethrow',\n name: 'Error Rethrow Pattern',\n description: 'Caught errors are typically rethrown after handling',\n confidence,\n occurrences: rethrowCount,\n examples: tryCatchBlocks\n .filter((b) => b.hasThrow)\n .slice(0, 3)\n .map((b) => ({\n file: b.file,\n line: b.line,\n snippet: 'try { ... } catch (e) { ... throw ... }',\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Caught errors should be rethrown or wrapped after handling',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeThrowPatterns(scanner: CodeScanner): Pattern | null {\n const files = scanner.getFiles();\n let throwNewError = 0;\n let throwCustom = 0;\n const examples: { file: string; line: number; snippet: string }[] = [];\n\n for (const { path, sourceFile } of files) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isThrowStatement(node)) {\n const expression = node.getExpression();\n if (expression) {\n const text = expression.getText();\n if (text.startsWith('new Error(')) {\n throwNewError++;\n } else if (text.startsWith('new ') && text.includes('Error')) {\n throwCustom++;\n if (examples.length < 3) {\n const snippet = text.length > 50 ? text.slice(0, 50) + '...' : text;\n examples.push({\n file: path,\n line: node.getStartLineNumber(),\n snippet: `throw ${snippet}`,\n });\n }\n }\n }\n }\n });\n }\n\n if (throwCustom >= 3 && throwCustom > throwNewError) {\n const confidence = calculateConfidence(throwCustom, throwCustom + throwNewError);\n\n return createPattern(this.id, {\n id: 'errors-throw-custom',\n name: 'Custom Error Throwing',\n description: 'Custom error classes are thrown instead of generic Error',\n confidence,\n occurrences: throwCustom,\n examples,\n suggestedConstraint: {\n type: 'convention',\n rule: 'Throw custom error classes instead of generic Error',\n severity: 'medium',\n scope: 'src/**/*.ts',\n verifier: 'errors',\n },\n });\n }\n\n return null;\n }\n}\n","/**\n * Analyzer exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './structure.js';\nexport * from './errors.js';\n\nimport type { Analyzer } from './base.js';\nimport { NamingAnalyzer } from './naming.js';\nimport { ImportsAnalyzer } from './imports.js';\nimport { StructureAnalyzer } from './structure.js';\nimport { ErrorsAnalyzer } from './errors.js';\n\n/**\n * Built-in analyzers registry\n */\nexport const builtinAnalyzers: Record<string, () => Analyzer> = {\n naming: () => new NamingAnalyzer(),\n imports: () => new ImportsAnalyzer(),\n structure: () => new StructureAnalyzer(),\n errors: () => new ErrorsAnalyzer(),\n};\n\n/**\n * Get analyzer by ID\n */\nexport function getAnalyzer(id: string): Analyzer | null {\n const factory = builtinAnalyzers[id];\n return factory ? factory() : null;\n}\n\n/**\n * Get all analyzer IDs\n */\nexport function getAnalyzerIds(): string[] {\n return Object.keys(builtinAnalyzers);\n}\n","/**\n * Inference Engine - Orchestrates pattern detection\n */\nimport type { Pattern, InferenceResult, SpecBridgeConfig } from '../core/types/index.js';\nimport { AnalyzerNotFoundError } from '../core/errors/index.js';\nimport { CodeScanner } from './scanner.js';\nimport { getAnalyzer, getAnalyzerIds, type Analyzer } from './analyzers/index.js';\n\nexport interface InferenceOptions {\n analyzers?: string[];\n minConfidence?: number;\n sourceRoots?: string[];\n exclude?: string[];\n cwd?: string;\n}\n\n/**\n * Inference Engine class\n */\nexport class InferenceEngine {\n private scanner: CodeScanner;\n private analyzers: Analyzer[] = [];\n\n constructor() {\n this.scanner = new CodeScanner();\n }\n\n /**\n * Configure analyzers to use\n */\n configureAnalyzers(analyzerIds: string[]): void {\n this.analyzers = [];\n\n for (const id of analyzerIds) {\n const analyzer = getAnalyzer(id);\n if (!analyzer) {\n throw new AnalyzerNotFoundError(id);\n }\n this.analyzers.push(analyzer);\n }\n }\n\n /**\n * Run inference on the codebase\n */\n async infer(options: InferenceOptions): Promise<InferenceResult> {\n const startTime = Date.now();\n\n const {\n analyzers: analyzerIds = getAnalyzerIds(),\n minConfidence = 50,\n sourceRoots = ['src/**/*.ts', 'src/**/*.tsx'],\n exclude = ['**/*.test.ts', '**/*.spec.ts', '**/node_modules/**', '**/dist/**'],\n cwd = process.cwd(),\n } = options;\n\n // Configure analyzers\n this.configureAnalyzers(analyzerIds);\n\n // Scan codebase\n const scanResult = await this.scanner.scan({\n sourceRoots,\n exclude,\n cwd,\n });\n\n if (scanResult.totalFiles === 0) {\n return {\n patterns: [],\n analyzersRun: analyzerIds,\n filesScanned: 0,\n duration: Date.now() - startTime,\n };\n }\n\n // Run all analyzers\n const allPatterns: Pattern[] = [];\n\n for (const analyzer of this.analyzers) {\n try {\n const patterns = await analyzer.analyze(this.scanner);\n allPatterns.push(...patterns);\n } catch (error) {\n // Log but don't fail on individual analyzer errors\n console.warn(`Analyzer ${analyzer.id} failed:`, error);\n }\n }\n\n // Filter by minimum confidence\n const filteredPatterns = allPatterns.filter((p) => p.confidence >= minConfidence);\n\n // Sort by confidence (highest first)\n filteredPatterns.sort((a, b) => b.confidence - a.confidence);\n\n return {\n patterns: filteredPatterns,\n analyzersRun: analyzerIds,\n filesScanned: scanResult.totalFiles,\n duration: Date.now() - startTime,\n };\n }\n\n /**\n * Get scanner for direct access\n */\n getScanner(): CodeScanner {\n return this.scanner;\n }\n}\n\n/**\n * Create an inference engine from config\n */\nexport function createInferenceEngine(): InferenceEngine {\n return new InferenceEngine();\n}\n\n/**\n * Run inference with config\n */\nexport async function runInference(\n config: SpecBridgeConfig,\n options?: Partial<InferenceOptions>\n): Promise<InferenceResult> {\n const engine = createInferenceEngine();\n\n return engine.infer({\n analyzers: config.inference?.analyzers,\n minConfidence: config.inference?.minConfidence,\n sourceRoots: config.project.sourceRoots,\n exclude: config.project.exclude,\n ...options,\n });\n}\n","/**\n * Verification Engine - Orchestrates constraint checking\n */\nimport { Project } from 'ts-morph';\nimport type {\n Violation,\n VerificationResult,\n VerificationLevel,\n Severity,\n SpecBridgeConfig,\n Decision,\n VerificationWarning,\n VerificationIssue,\n} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport {\n selectVerifierForConstraint,\n getVerifierIds,\n type VerificationContext,\n} from './verifiers/index.js';\nimport { glob } from '../utils/glob.js';\nimport { AstCache } from './cache.js';\nimport { ResultsCache } from './results-cache.js';\nimport { shouldApplyConstraintToFile } from './applicability.js';\nimport { ExplainReporter } from './explain.js';\nimport { getPluginLoader } from './plugins/loader.js';\nimport { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { getLogger } from '../utils/logger.js';\n\nexport interface VerificationOptions {\n level?: VerificationLevel;\n files?: string[];\n decisions?: string[];\n severity?: Severity[];\n timeout?: number;\n cwd?: string;\n reporter?: ExplainReporter;\n}\n\n/**\n * Verification Engine class\n */\nexport class VerificationEngine {\n private registry: Registry;\n private project: Project;\n private astCache: AstCache;\n private resultsCache: ResultsCache;\n private pluginsLoaded = false;\n private logger = getLogger({ module: 'verification.engine' });\n\n constructor(registry?: Registry) {\n this.registry = registry || createRegistry();\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n this.astCache = new AstCache();\n this.resultsCache = new ResultsCache();\n }\n\n /**\n * Run verification\n */\n async verify(\n config: SpecBridgeConfig,\n options: VerificationOptions = {}\n ): Promise<VerificationResult> {\n const startTime = Date.now();\n\n const {\n level = 'full',\n files: specificFiles,\n decisions: decisionIds,\n cwd = process.cwd(),\n } = options;\n\n // Get level-specific settings\n const levelConfig = config.verification?.levels?.[level];\n const severityFilter = options.severity || levelConfig?.severity;\n const timeout = options.timeout || levelConfig?.timeout || 60000;\n\n // Load plugins once per engine instance\n if (!this.pluginsLoaded) {\n await getPluginLoader().loadPlugins(cwd);\n this.pluginsLoaded = true;\n }\n\n // Load registry if not already loaded\n await this.registry.load();\n\n // Get decisions to verify\n let decisions = this.registry.getActive();\n if (decisionIds && decisionIds.length > 0) {\n decisions = decisions.filter((d) => decisionIds.includes(d.metadata.id));\n }\n\n // Get files to verify\n const filesToVerify = specificFiles\n ? specificFiles\n : await glob(config.project.sourceRoots, {\n cwd,\n ignore: config.project.exclude,\n absolute: true,\n });\n\n if (filesToVerify.length === 0) {\n return {\n success: true,\n violations: [],\n checked: 0,\n passed: 0,\n failed: 0,\n skipped: 0,\n duration: Date.now() - startTime,\n warnings: [],\n errors: [],\n };\n }\n\n // Collect all violations, warnings, and errors\n const allViolations: Violation[] = [];\n const allWarnings: VerificationWarning[] = [];\n const allErrors: VerificationIssue[] = [];\n let checked = 0;\n let passed = 0;\n let failed = 0;\n const skipped = 0;\n\n // Create AbortController for cancellation support\n const abortController = new AbortController();\n\n // Process files with timeout\n let timeoutHandle: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<'timeout'>((resolve) => {\n timeoutHandle = setTimeout(() => {\n abortController.abort(); // Signal verifiers to stop\n resolve('timeout');\n }, timeout);\n // Use unref() so timeout doesn't prevent process exit if it's the only thing left\n timeoutHandle.unref();\n });\n\n const verificationPromise = this.verifyFiles(\n filesToVerify,\n decisions,\n severityFilter,\n cwd,\n options.reporter,\n abortController.signal,\n (violations, warnings, errors) => {\n allViolations.push(...violations);\n allWarnings.push(...warnings);\n allErrors.push(...errors);\n checked++;\n if (violations.length > 0) {\n failed++;\n } else {\n passed++;\n }\n }\n );\n\n let result: void | 'timeout';\n try {\n result = await Promise.race([verificationPromise, timeoutPromise]);\n\n if (result === 'timeout') {\n return {\n success: false,\n violations: allViolations,\n checked,\n passed,\n failed,\n skipped: filesToVerify.length - checked,\n duration: timeout,\n warnings: allWarnings,\n errors: allErrors,\n };\n }\n } finally {\n // Always clear the timeout to prevent event loop leak\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n timeoutHandle = null;\n }\n }\n\n // Determine success based on level\n const hasBlockingViolations = allViolations.some((v) => {\n if (level === 'commit') {\n return v.type === 'invariant' || v.severity === 'critical';\n }\n if (level === 'pr') {\n return v.type === 'invariant' || v.severity === 'critical' || v.severity === 'high';\n }\n return v.type === 'invariant';\n });\n\n return {\n success: !hasBlockingViolations,\n violations: allViolations,\n checked,\n passed,\n failed,\n skipped,\n duration: Date.now() - startTime,\n warnings: allWarnings,\n errors: allErrors,\n };\n }\n\n /**\n * Verify a single file\n */\n async verifyFile(\n filePath: string,\n decisions: Decision[],\n severityFilter?: Severity[],\n cwd: string = process.cwd(),\n reporter?: ExplainReporter,\n signal?: AbortSignal\n ): Promise<{\n violations: Violation[];\n warnings: VerificationWarning[];\n errors: VerificationIssue[];\n }> {\n const violations: Violation[] = [];\n const warnings: VerificationWarning[] = [];\n const errors: VerificationIssue[] = [];\n\n // Check if verification was aborted\n if (signal?.aborted) {\n return { violations, warnings, errors };\n }\n\n const sourceFile = await this.astCache.get(filePath, this.project);\n if (!sourceFile) return { violations, warnings, errors };\n\n // Compute file hash once for caching\n let fileHash: string | null = null;\n try {\n const content = await readFile(filePath, 'utf-8');\n fileHash = createHash('sha256').update(content).digest('hex');\n } catch {\n // If we can't read the file, skip caching\n fileHash = null;\n }\n\n // Check each decision's constraints\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n // Check if file matches constraint scope\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd, severityFilter })) {\n // Track skipped constraint in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: false,\n reason: 'File does not match scope pattern or severity filter',\n });\n }\n continue;\n }\n\n // Get appropriate verifier\n const verifier = selectVerifierForConstraint(\n constraint.rule,\n constraint.verifier,\n constraint.check\n );\n\n if (!verifier) {\n // Determine what was requested\n const requestedVerifier =\n constraint.check?.verifier || constraint.verifier || 'auto-detected';\n this.logger.warn(\n {\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n requestedVerifier,\n availableVerifiers: getVerifierIds(),\n },\n 'No verifier found for constraint'\n );\n\n warnings.push({\n type: 'missing_verifier',\n message: `No verifier found for constraint (requested: ${requestedVerifier})`,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n file: filePath,\n });\n\n // Track in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: false,\n reason: `No verifier found (requested: ${requestedVerifier})`,\n });\n }\n\n continue;\n }\n\n // Check results cache first\n let constraintViolations: Violation[];\n\n if (fileHash) {\n const cacheKey = {\n filePath,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n fileHash,\n };\n\n const cached = this.resultsCache.get(cacheKey);\n if (cached) {\n // Cache hit!\n constraintViolations = cached;\n violations.push(...constraintViolations);\n\n // Track in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope (cached)',\n selectedVerifier: verifier.id,\n });\n }\n\n continue;\n }\n }\n\n // Validate params if this is a custom plugin with paramsSchema\n if (constraint.check?.verifier && constraint.check?.params) {\n const pluginLoader = getPluginLoader();\n const validationResult = pluginLoader.validateParams(\n constraint.check.verifier,\n constraint.check.params\n );\n\n if (!validationResult.success) {\n warnings.push({\n type: 'invalid_params',\n message: validationResult.error,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n file: filePath,\n });\n\n // Track in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: false,\n reason: `Params validation failed: ${validationResult.error}`,\n });\n }\n\n continue;\n }\n }\n\n // Run verification\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n signal,\n };\n\n const verificationStart = Date.now();\n try {\n constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n\n // Cache results\n if (fileHash) {\n this.resultsCache.set(\n {\n filePath,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n fileHash,\n },\n constraintViolations\n );\n }\n\n // Track successful verification in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope',\n selectedVerifier: verifier.id,\n verifierOutput: {\n violations: constraintViolations.length,\n duration: Date.now() - verificationStart,\n },\n });\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack = error instanceof Error ? error.stack : undefined;\n this.logger.error(\n {\n verifierId: verifier.id,\n filePath,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n error: errorMessage,\n stack: errorStack,\n },\n 'Verifier execution failed'\n );\n\n errors.push({\n type: 'verifier_exception',\n message: `Verifier '${verifier.id}' failed: ${errorMessage}`,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n file: filePath,\n stack: errorStack,\n });\n\n // Track failed verification in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope',\n selectedVerifier: verifier.id,\n verifierOutput: {\n violations: 0,\n duration: Date.now() - verificationStart,\n error: errorMessage,\n },\n });\n }\n }\n }\n }\n\n return { violations, warnings, errors };\n }\n\n /**\n * Verify multiple files\n */\n private async verifyFiles(\n files: string[],\n decisions: Decision[],\n severityFilter: Severity[] | undefined,\n cwd: string,\n reporter: ExplainReporter | undefined,\n signal: AbortSignal,\n onFileVerified: (\n violations: Violation[],\n warnings: VerificationWarning[],\n errors: VerificationIssue[]\n ) => void\n ): Promise<void> {\n const BATCH_SIZE = 50; // Increased from 10 for better parallelism\n for (let i = 0; i < files.length; i += BATCH_SIZE) {\n // Check if aborted before processing next batch\n if (signal.aborted) {\n break;\n }\n\n const batch = files.slice(i, i + BATCH_SIZE);\n const results = await Promise.all(\n batch.map((file) => this.verifyFile(file, decisions, severityFilter, cwd, reporter, signal))\n );\n\n for (const result of results) {\n onFileVerified(result.violations, result.warnings, result.errors);\n }\n }\n }\n\n /**\n * Get registry\n */\n getRegistry(): Registry {\n return this.registry;\n }\n}\n\n/**\n * Create verification engine\n */\nexport function createVerificationEngine(registry?: Registry): VerificationEngine {\n return new VerificationEngine(registry);\n}\n","/**\n * Base verifier interface\n */\nimport type { Violation, Constraint, Severity } from '../../core/types/index.js';\nimport type { SourceFile } from 'ts-morph';\n\n/**\n * Context passed to verifiers\n */\nexport interface VerificationContext {\n filePath: string;\n sourceFile: SourceFile;\n constraint: Constraint;\n decisionId: string;\n /** Optional AbortSignal for cancellation support */\n signal?: AbortSignal;\n}\n\n/**\n * Verifier interface - all verifiers must implement this\n */\nexport interface Verifier {\n /**\n * Unique identifier for this verifier\n */\n readonly id: string;\n\n /**\n * Human-readable name\n */\n readonly name: string;\n\n /**\n * Description of what this verifier checks\n */\n readonly description: string;\n\n /**\n * Verify a file against a constraint\n */\n verify(ctx: VerificationContext): Promise<Violation[]>;\n}\n\n/**\n * Plugin metadata\n */\nexport interface VerifierPluginMetadata {\n /** Unique identifier matching /^[a-z][a-z0-9-]*$/ */\n id: string;\n /** Semver version string */\n version: string;\n /** Plugin author */\n author?: string;\n /** Brief description of what this verifier checks */\n description?: string;\n}\n\n/**\n * Verifier plugin interface\n * Custom verifiers must export a default object implementing this interface\n */\nexport interface VerifierPlugin {\n /** Plugin metadata */\n metadata: VerifierPluginMetadata;\n\n /** Factory function that creates a new verifier instance */\n createVerifier: () => Verifier;\n\n /** Optional Zod schema for validating constraint.check.params */\n paramsSchema?: unknown; // Will be validated as ZodSchema at runtime\n}\n\n/**\n * Helper to define a verifier plugin with type safety\n *\n * @example\n * ```typescript\n * import { defineVerifierPlugin, type Verifier } from '@ipation/specbridge';\n *\n * class MyVerifier implements Verifier {\n * readonly id = 'my-custom';\n * readonly name = 'My Custom Verifier';\n * readonly description = 'Checks custom patterns';\n *\n * async verify(ctx) {\n * // Implementation\n * return [];\n * }\n * }\n *\n * export default defineVerifierPlugin({\n * metadata: {\n * id: 'my-custom',\n * version: '1.0.0',\n * author: 'Your Name'\n * },\n * createVerifier: () => new MyVerifier()\n * });\n * ```\n */\nexport function defineVerifierPlugin(plugin: VerifierPlugin): VerifierPlugin {\n return plugin;\n}\n\n/**\n * Helper to create a violation\n */\nexport function createViolation(params: {\n decisionId: string;\n constraintId: string;\n type: Constraint['type'];\n severity: Severity;\n message: string;\n file: string;\n line?: number;\n column?: number;\n endLine?: number;\n endColumn?: number;\n suggestion?: string;\n autofix?: Violation['autofix'];\n}): Violation {\n return params;\n}\n","/**\n * Naming convention verifier\n */\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst NAMING_PATTERNS: Record<string, { regex: RegExp; description: string }> = {\n PascalCase: {\n regex: /^[A-Z][a-zA-Z0-9]*$/,\n description: 'PascalCase (e.g., MyClass)',\n },\n camelCase: {\n regex: /^[a-z][a-zA-Z0-9]*$/,\n description: 'camelCase (e.g., myFunction)',\n },\n UPPER_SNAKE_CASE: {\n regex: /^[A-Z][A-Z0-9_]*$/,\n description: 'UPPER_SNAKE_CASE (e.g., MAX_VALUE)',\n },\n snake_case: {\n regex: /^[a-z][a-z0-9_]*$/,\n description: 'snake_case (e.g., my_variable)',\n },\n 'kebab-case': {\n regex: /^[a-z][a-z0-9-]*$/,\n description: 'kebab-case (e.g., my-component)',\n },\n};\n\nexport class NamingVerifier implements Verifier {\n readonly id = 'naming';\n readonly name = 'Naming Convention Verifier';\n readonly description = 'Verifies naming conventions for classes, functions, and variables';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n\n // Parse constraint rule to extract target and convention\n // Expected format: \"Classes should use PascalCase\" or \"Functions should use camelCase\"\n const rule = constraint.rule.toLowerCase();\n let convention: string | null = null;\n let targetType: 'class' | 'function' | 'interface' | 'type' | null = null;\n\n // Detect convention\n for (const [name] of Object.entries(NAMING_PATTERNS)) {\n if (rule.includes(name.toLowerCase())) {\n convention = name;\n break;\n }\n }\n\n // Detect target type\n if (rule.includes('class')) targetType = 'class';\n else if (rule.includes('function')) targetType = 'function';\n else if (rule.includes('interface')) targetType = 'interface';\n else if (rule.includes('type')) targetType = 'type';\n\n if (!convention || !targetType) {\n // Can't parse rule, skip verification\n return violations;\n }\n\n const pattern = NAMING_PATTERNS[convention];\n if (!pattern) return violations;\n\n // Check based on target type\n if (targetType === 'class') {\n for (const classDecl of sourceFile.getClasses()) {\n const name = classDecl.getName();\n if (name && !pattern.regex.test(name)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Class \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: classDecl.getStartLineNumber(),\n column: classDecl.getStart() - classDecl.getStartLinePos(),\n suggestion: `Rename to follow ${pattern.description}`,\n })\n );\n }\n }\n }\n\n if (targetType === 'function') {\n for (const funcDecl of sourceFile.getFunctions()) {\n const name = funcDecl.getName();\n if (name && !pattern.regex.test(name)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: funcDecl.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n })\n );\n }\n }\n }\n\n if (targetType === 'interface') {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n const name = interfaceDecl.getName();\n if (!pattern.regex.test(name)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Interface \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: interfaceDecl.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n })\n );\n }\n }\n }\n\n if (targetType === 'type') {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const name = typeAlias.getName();\n if (!pattern.regex.test(name)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Type \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: typeAlias.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n })\n );\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Import pattern verifier\n */\nimport path from 'node:path';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nexport class ImportsVerifier implements Verifier {\n readonly id = 'imports';\n readonly name = 'Import Pattern Verifier';\n readonly description = 'Verifies import patterns like barrel imports, path aliases, etc.';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n // Check for required .js extensions in relative imports (ESM-friendly)\n if (\n (rule.includes('.js') && rule.includes('extension')) ||\n rule.includes('esm') ||\n rule.includes('add .js')\n ) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (!moduleSpec.startsWith('.')) continue;\n\n const ext = path.posix.extname(moduleSpec);\n let suggested: string | null = null;\n\n if (!ext) {\n suggested = `${moduleSpec}.js`;\n } else if (ext === '.ts' || ext === '.tsx' || ext === '.jsx') {\n suggested = moduleSpec.slice(0, -ext.length) + '.js';\n } else if (ext !== '.js') {\n continue;\n }\n\n if (!suggested || suggested === moduleSpec) continue;\n\n const ms = importDecl.getModuleSpecifier();\n const start = ms.getStart() + 1; // inside quotes\n const end = ms.getEnd() - 1;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Relative import \"${moduleSpec}\" should include a .js extension`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Update to \"${suggested}\"`,\n autofix: {\n description: 'Add/normalize .js extension in import specifier',\n edits: [{ start, end, text: suggested }],\n },\n })\n );\n }\n }\n\n // Check for barrel import requirement\n if (rule.includes('barrel') || rule.includes('index')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n\n // Skip external packages\n if (!moduleSpec.startsWith('.')) continue;\n\n // Check if importing specific file instead of barrel\n if (moduleSpec.match(/\\.(ts|js|tsx|jsx)$/) || moduleSpec.match(/\\/[^/]+$/)) {\n // Could be a direct file import - flag if not index\n if (!moduleSpec.endsWith('/index') && !moduleSpec.endsWith('index')) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Import from \"${moduleSpec}\" should use barrel (index) import`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Import from the parent directory index file instead',\n })\n );\n }\n }\n }\n }\n\n // Check for path alias requirement\n if (rule.includes('alias') || rule.includes('@/') || rule.includes('path alias')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n\n // Check for deeply nested relative imports\n if (moduleSpec.match(/^\\.\\.\\/\\.\\.\\/\\.\\.\\//)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Deep relative import \"${moduleSpec}\" should use path alias`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use path alias (e.g., @/module) for deep imports',\n })\n );\n }\n }\n }\n\n // Check for no circular imports (basic check)\n if (rule.includes('circular') || rule.includes('cycle')) {\n // This is a simplified check - a full cycle detection would need graph analysis\n // Check if any import matches the current file's exports\n // This is a very basic heuristic\n const currentFilename = filePath.replace(/\\.[jt]sx?$/, '');\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (moduleSpec.includes(currentFilename.split('/').pop() || '')) {\n // Potential self-reference, might indicate circular dependency\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible circular import detected: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Review import structure for circular dependencies',\n })\n );\n }\n }\n }\n\n // Check for no wildcard imports\n if (rule.includes('wildcard') || rule.includes('* as') || rule.includes('no namespace')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const namespaceImport = importDecl.getNamespaceImport();\n if (namespaceImport) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Namespace import \"* as ${namespaceImport.getText()}\" should use named imports`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use specific named imports instead of namespace import',\n })\n );\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Error handling verifier\n */\nimport { Node } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nexport class ErrorsVerifier implements Verifier {\n readonly id = 'errors';\n readonly name = 'Error Handling Verifier';\n readonly description = 'Verifies error handling patterns';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n // Check for custom error class extension\n if (rule.includes('extend') || rule.includes('base') || rule.includes('hierarchy')) {\n // Extract base class name from rule if mentioned\n const baseClassMatch = rule.match(/extend\\s+(\\w+)/i) || rule.match(/(\\w+Error)\\s+class/i);\n const requiredBase = baseClassMatch ? baseClassMatch[1] : null;\n\n for (const classDecl of sourceFile.getClasses()) {\n const className = classDecl.getName();\n if (!className?.endsWith('Error') && !className?.endsWith('Exception')) continue;\n\n const extendsClause = classDecl.getExtends();\n if (!extendsClause) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Error class \"${className}\" does not extend any base class`,\n file: filePath,\n line: classDecl.getStartLineNumber(),\n suggestion: requiredBase\n ? `Extend ${requiredBase}`\n : 'Extend a base error class for consistent error handling',\n })\n );\n } else if (requiredBase) {\n const baseName = extendsClause.getText();\n if (baseName !== requiredBase && baseName !== 'Error') {\n // Allow extending Error or the required base\n }\n }\n }\n }\n\n // Check for throwing custom errors vs generic Error\n if (rule.includes('custom error') || rule.includes('throw custom')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isThrowStatement(node)) {\n const expression = node.getExpression();\n if (expression) {\n const text = expression.getText();\n if (text.startsWith('new Error(')) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Throwing generic Error instead of custom error class',\n file: filePath,\n line: node.getStartLineNumber(),\n suggestion: 'Use a custom error class for better error handling',\n })\n );\n }\n }\n }\n });\n }\n\n // Check for empty catch blocks\n if (rule.includes('empty catch') || rule.includes('swallow') || rule.includes('handle')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isTryStatement(node)) {\n const catchClause = node.getCatchClause();\n if (catchClause) {\n const block = catchClause.getBlock();\n const statements = block.getStatements();\n\n // Check if catch block is empty or only has comments\n if (statements.length === 0) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Empty catch block swallows error without handling',\n file: filePath,\n line: catchClause.getStartLineNumber(),\n suggestion: 'Add error handling, logging, or rethrow the error',\n })\n );\n }\n }\n }\n });\n }\n\n // Check for console.error vs proper logging\n if (rule.includes('logging') || rule.includes('logger') || rule.includes('no console')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isCallExpression(node)) {\n const expression = node.getExpression();\n const text = expression.getText();\n if (text === 'console.error' || text === 'console.log') {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Using ${text} instead of proper logging`,\n file: filePath,\n line: node.getStartLineNumber(),\n suggestion: 'Use a proper logging library',\n })\n );\n }\n }\n });\n }\n\n return violations;\n }\n}\n","/**\n * Regex-based verifier for simple pattern matching\n */\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\n/**\n * A generic verifier that uses regex patterns from constraint rules\n * This handles constraints that specify patterns to match or avoid\n */\nexport class RegexVerifier implements Verifier {\n readonly id = 'regex';\n readonly name = 'Regex Pattern Verifier';\n readonly description = 'Verifies code against regex patterns specified in constraints';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n\n // Try to extract regex pattern from rule\n // Patterns like: \"must not contain /pattern/\" or \"should match /pattern/\"\n const mustNotMatch = rule.match(/must\\s+not\\s+(?:contain|match|use)\\s+\\/(.+?)\\//i);\n const shouldMatch = rule.match(/(?:should|must)\\s+(?:contain|match|use)\\s+\\/(.+?)\\//i);\n const forbiddenPattern = rule.match(/forbidden:\\s*\\/(.+?)\\//i);\n const requiredPattern = rule.match(/required:\\s*\\/(.+?)\\//i);\n\n const fileText = sourceFile.getFullText();\n\n // Handle \"must not contain\" patterns\n const patternToForbid = mustNotMatch?.[1] || forbiddenPattern?.[1];\n if (patternToForbid) {\n try {\n const regex = new RegExp(patternToForbid, 'g');\n let match: RegExpExecArray | null;\n\n while ((match = regex.exec(fileText)) !== null) {\n const beforeMatch = fileText.substring(0, match.index);\n const lineNumber = beforeMatch.split('\\n').length;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Found forbidden pattern: \"${match[0]}\"`,\n file: filePath,\n line: lineNumber,\n suggestion: `Remove or replace the pattern matching /${patternToForbid}/`,\n })\n );\n }\n } catch {\n // Invalid regex, skip\n }\n }\n\n // Handle \"should contain\" patterns (file-level check)\n const patternToRequire = shouldMatch?.[1] || requiredPattern?.[1];\n if (patternToRequire && !mustNotMatch) {\n try {\n const regex = new RegExp(patternToRequire);\n if (!regex.test(fileText)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `File does not contain required pattern: /${patternToRequire}/`,\n file: filePath,\n suggestion: `Add code matching /${patternToRequire}/`,\n })\n );\n }\n } catch {\n // Invalid regex, skip\n }\n }\n\n return violations;\n }\n}\n","/**\n * Dependency constraint verifier\n *\n * Supports rules like:\n * - \"No circular dependencies between modules\"\n * - \"Domain layer cannot depend on infrastructure layer\"\n * - \"No dependencies on package lodash\"\n * - \"Maximum import depth: 2\"\n */\nimport path from 'node:path';\nimport type { Project } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\ntype DependencyGraph = Map<string, Set<string>>;\n\nconst graphCache = new WeakMap<Project, { fileCount: number; graph: DependencyGraph }>();\n\nfunction normalizeFsPath(p: string): string {\n return p.replaceAll('\\\\', '/');\n}\n\nfunction joinLike(fromFilePath: string, relative: string): string {\n const fromNorm = normalizeFsPath(fromFilePath);\n const relNorm = normalizeFsPath(relative);\n\n if (path.isAbsolute(fromNorm)) {\n return normalizeFsPath(path.resolve(path.dirname(fromNorm), relNorm));\n }\n\n // In-memory ts-morph projects often use relative paths; keep them relative.\n const dir = path.posix.dirname(fromNorm);\n return path.posix.normalize(path.posix.join(dir, relNorm));\n}\n\nfunction resolveToSourceFilePath(\n project: Project,\n fromFilePath: string,\n moduleSpec: string\n): string | null {\n if (!moduleSpec.startsWith('.')) return null;\n\n const candidates: string[] = [];\n const raw = joinLike(fromFilePath, moduleSpec);\n\n const addCandidate = (p: string) => candidates.push(normalizeFsPath(p));\n\n // If an extension exists, try it and common TS/JS mappings.\n const ext = path.posix.extname(raw);\n if (ext) {\n addCandidate(raw);\n\n if (ext === '.js') addCandidate(raw.slice(0, -3) + '.ts');\n if (ext === '.jsx') addCandidate(raw.slice(0, -4) + '.tsx');\n if (ext === '.ts') addCandidate(raw.slice(0, -3) + '.js');\n if (ext === '.tsx') addCandidate(raw.slice(0, -4) + '.jsx');\n\n // Directory index variants.\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.ts'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.tsx'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.js'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.jsx'));\n } else {\n // No extension: try source extensions and index files.\n addCandidate(raw + '.ts');\n addCandidate(raw + '.tsx');\n addCandidate(raw + '.js');\n addCandidate(raw + '.jsx');\n\n addCandidate(path.posix.join(raw, 'index.ts'));\n addCandidate(path.posix.join(raw, 'index.tsx'));\n addCandidate(path.posix.join(raw, 'index.js'));\n addCandidate(path.posix.join(raw, 'index.jsx'));\n }\n\n for (const candidate of candidates) {\n const sf = project.getSourceFile(candidate);\n if (sf) return sf.getFilePath();\n }\n\n return null;\n}\n\nfunction buildDependencyGraph(project: Project): DependencyGraph {\n const cached = graphCache.get(project);\n const sourceFiles = project.getSourceFiles();\n if (cached && cached.fileCount === sourceFiles.length) {\n return cached.graph;\n }\n\n const graph: DependencyGraph = new Map();\n\n for (const sf of sourceFiles) {\n const from = normalizeFsPath(sf.getFilePath());\n if (!graph.has(from)) graph.set(from, new Set());\n\n for (const importDecl of sf.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n const resolved = resolveToSourceFilePath(project, from, moduleSpec);\n if (resolved) {\n const dependencies = graph.get(from);\n if (dependencies) {\n dependencies.add(normalizeFsPath(resolved));\n }\n }\n }\n }\n\n graphCache.set(project, { fileCount: sourceFiles.length, graph });\n return graph;\n}\n\nfunction tarjanScc(graph: DependencyGraph): string[][] {\n let index = 0;\n const stack: string[] = [];\n const onStack = new Set<string>();\n const indices = new Map<string, number>();\n const lowlink = new Map<string, number>();\n const result: string[][] = [];\n\n const strongConnect = (v: string) => {\n indices.set(v, index);\n lowlink.set(v, index);\n index++;\n stack.push(v);\n onStack.add(v);\n\n const edges = graph.get(v) || new Set<string>();\n for (const w of edges) {\n if (!indices.has(w)) {\n strongConnect(w);\n const currentLowlink = lowlink.get(v);\n const childLowlink = lowlink.get(w);\n if (currentLowlink !== undefined && childLowlink !== undefined) {\n lowlink.set(v, Math.min(currentLowlink, childLowlink));\n }\n } else if (onStack.has(w)) {\n const currentLowlink = lowlink.get(v);\n const childIndex = indices.get(w);\n if (currentLowlink !== undefined && childIndex !== undefined) {\n lowlink.set(v, Math.min(currentLowlink, childIndex));\n }\n }\n }\n\n if (lowlink.get(v) === indices.get(v)) {\n const scc: string[] = [];\n while (stack.length > 0) {\n const w = stack.pop();\n if (!w) break;\n onStack.delete(w);\n scc.push(w);\n if (w === v) break;\n }\n result.push(scc);\n }\n };\n\n for (const v of graph.keys()) {\n if (!indices.has(v)) strongConnect(v);\n }\n\n return result;\n}\n\nfunction parseMaxImportDepth(rule: string): number | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/maximum\\s{1,5}import\\s{1,5}depth\\s{0,5}[:=]?\\s{0,5}(\\d+)/i);\n const depthText = m?.[1];\n return depthText ? Number.parseInt(depthText, 10) : null;\n}\n\nfunction parseBannedDependency(rule: string): string | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/no\\s{1,5}dependencies?\\s{1,5}on\\s{1,5}(?:package\\s{1,5})?(.+?)(?:\\.|$)/i);\n const value = m?.[1]?.trim();\n if (!value) return null;\n return value.length > 0 ? value : null;\n}\n\nfunction parseLayerRule(rule: string): { fromLayer: string; toLayer: string } | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(\n /(\\w+)\\s{1,5}layer\\s{1,5}cannot\\s{1,5}depend\\s{1,5}on\\s{1,5}(\\w+)\\s{1,5}layer/i\n );\n const fromLayer = m?.[1]?.toLowerCase();\n const toLayer = m?.[2]?.toLowerCase();\n if (!fromLayer || !toLayer) return null;\n return { fromLayer, toLayer };\n}\n\nfunction fileInLayer(filePath: string, layer: string): boolean {\n const fp = normalizeFsPath(filePath).toLowerCase();\n return fp.includes(`/${layer}/`) || fp.endsWith(`/${layer}.ts`) || fp.endsWith(`/${layer}.tsx`);\n}\n\nexport class DependencyVerifier implements Verifier {\n readonly id = 'dependencies';\n readonly name = 'Dependency Verifier';\n readonly description = 'Checks dependency constraints, import depth, and circular dependencies';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n const lowerRule = rule.toLowerCase();\n const project = sourceFile.getProject();\n const projectFilePath = normalizeFsPath(sourceFile.getFilePath());\n\n // 1) Circular dependencies (across files)\n if (lowerRule.includes('circular') || lowerRule.includes('cycle')) {\n const graph = buildDependencyGraph(project);\n const sccs = tarjanScc(graph);\n const current = projectFilePath;\n\n for (const scc of sccs) {\n const first = scc[0];\n const hasSelfLoop =\n first !== undefined && scc.length === 1 && (graph.get(first)?.has(first) ?? false);\n const isCycle = scc.length > 1 || hasSelfLoop;\n if (!isCycle) continue;\n\n if (!scc.includes(current)) continue;\n\n // Avoid duplicate reporting: only report from lexicographically-smallest file in the SCC.\n const sorted = [...scc].sort();\n if (sorted[0] !== current) continue;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Circular dependency detected across: ${sorted.join(' -> ')}`,\n file: filePath,\n line: 1,\n suggestion:\n 'Break the cycle by extracting shared abstractions or reversing the dependency',\n })\n );\n }\n }\n\n // 2) Layer constraints (heuristic by folder name)\n const layerRule = parseLayerRule(rule);\n if (layerRule && fileInLayer(projectFilePath, layerRule.fromLayer)) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n const resolved = resolveToSourceFilePath(project, projectFilePath, moduleSpec);\n if (!resolved) continue;\n\n if (fileInLayer(resolved, layerRule.toLayer)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Layer violation: ${layerRule.fromLayer} depends on ${layerRule.toLayer} via import \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Refactor to remove dependency from ${layerRule.fromLayer} to ${layerRule.toLayer}`,\n })\n );\n }\n }\n }\n\n // 3) Banned dependency (package or internal)\n const banned = parseBannedDependency(rule);\n if (banned) {\n const bannedLower = banned.toLowerCase();\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (moduleSpec.toLowerCase().includes(bannedLower)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Banned dependency import detected: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Remove or replace dependency \"${banned}\"`,\n })\n );\n }\n }\n }\n\n // 4) Import depth limits (../ count)\n const maxDepth = parseMaxImportDepth(rule);\n if (maxDepth !== null) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (!moduleSpec.startsWith('.')) continue;\n const depth = (moduleSpec.match(/\\.\\.\\//g) || []).length;\n if (depth > maxDepth) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Import depth ${depth} exceeds maximum ${maxDepth}: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion:\n 'Use a shallower module boundary (or introduce a public entrypoint for this dependency)',\n })\n );\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Complexity constraint verifier\n *\n * Supports rules like:\n * - \"Cyclomatic complexity must not exceed 10\"\n * - \"File size must not exceed 300 lines\"\n * - \"Functions must have at most 4 parameters\"\n * - \"Nesting depth must not exceed 4\"\n */\nimport {\n Node,\n type ArrowFunction,\n type FunctionDeclaration,\n type FunctionExpression,\n type MethodDeclaration,\n} from 'ts-morph';\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nfunction parseLimit(rule: string, pattern: RegExp): number | null {\n const m = rule.match(pattern);\n const value = m?.[1];\n return value ? Number.parseInt(value, 10) : null;\n}\n\nfunction getFileLineCount(text: string): number {\n if (text.length === 0) return 0;\n return text.split('\\n').length;\n}\n\nfunction getDecisionPoints(fn: Node): number {\n let points = 0;\n for (const d of fn.getDescendants()) {\n switch (d.getKind()) {\n case SyntaxKind.IfStatement:\n case SyntaxKind.ForStatement:\n case SyntaxKind.ForInStatement:\n case SyntaxKind.ForOfStatement:\n case SyntaxKind.WhileStatement:\n case SyntaxKind.DoStatement:\n case SyntaxKind.CatchClause:\n case SyntaxKind.ConditionalExpression:\n case SyntaxKind.CaseClause:\n points++;\n break;\n case SyntaxKind.BinaryExpression: {\n // Count short-circuit operators (&&, ||)\n const text = d.getText();\n if (text.includes('&&') || text.includes('||')) points++;\n break;\n }\n default:\n break;\n }\n }\n return points;\n}\n\nfunction calculateCyclomaticComplexity(fn: Node): number {\n // Base complexity of 1 + number of decision points.\n return 1 + getDecisionPoints(fn);\n}\n\nfunction getFunctionDisplayName(fn: Node): string {\n // Best-effort name resolution.\n if (\n Node.isFunctionDeclaration(fn) ||\n Node.isMethodDeclaration(fn) ||\n Node.isFunctionExpression(fn)\n ) {\n const name = fn.getName();\n if (typeof name === 'string' && name.length > 0) {\n return name;\n }\n }\n\n // Variable = () => ...\n const parent = fn.getParent();\n if (parent && Node.isVariableDeclaration(parent)) {\n return parent.getName();\n }\n\n return '<anonymous>';\n}\n\nfunction maxNestingDepth(node: Node): number {\n let maxDepth = 0;\n\n const walk = (n: Node, depth: number) => {\n maxDepth = Math.max(maxDepth, depth);\n\n const kind = n.getKind();\n const isNestingNode =\n kind === SyntaxKind.IfStatement ||\n kind === SyntaxKind.ForStatement ||\n kind === SyntaxKind.ForInStatement ||\n kind === SyntaxKind.ForOfStatement ||\n kind === SyntaxKind.WhileStatement ||\n kind === SyntaxKind.DoStatement ||\n kind === SyntaxKind.SwitchStatement ||\n kind === SyntaxKind.TryStatement;\n\n for (const child of n.getChildren()) {\n // Skip nested function scopes for nesting depth.\n if (\n child.getKind() === SyntaxKind.FunctionDeclaration ||\n child.getKind() === SyntaxKind.FunctionExpression ||\n child.getKind() === SyntaxKind.ArrowFunction ||\n child.getKind() === SyntaxKind.MethodDeclaration\n ) {\n continue;\n }\n walk(child, isNestingNode ? depth + 1 : depth);\n }\n };\n\n walk(node, 0);\n return maxDepth;\n}\n\nexport class ComplexityVerifier implements Verifier {\n readonly id = 'complexity';\n readonly name = 'Complexity Verifier';\n readonly description = 'Checks cyclomatic complexity, file size, parameters, and nesting depth';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n\n const maxComplexity = parseLimit(rule, /complexity\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n const maxLines = parseLimit(rule, /file\\s+size\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)\\s+lines?/i);\n const maxParams =\n parseLimit(rule, /at\\s+most\\s+(\\d+)\\s+parameters?/i) ??\n parseLimit(rule, /parameters?\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n const maxNesting = parseLimit(rule, /nesting\\s+depth\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n\n if (maxLines !== null) {\n const lineCount = getFileLineCount(sourceFile.getFullText());\n if (lineCount > maxLines) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `File has ${lineCount} lines which exceeds maximum ${maxLines}`,\n file: filePath,\n line: 1,\n suggestion: 'Split the file into smaller modules',\n })\n );\n }\n }\n\n type FunctionLikeNode =\n | FunctionDeclaration\n | FunctionExpression\n | ArrowFunction\n | MethodDeclaration;\n const functionLikes: FunctionLikeNode[] = [\n ...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionExpression),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.ArrowFunction),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.MethodDeclaration),\n ];\n\n for (const fn of functionLikes) {\n const fnName = getFunctionDisplayName(fn);\n\n if (maxComplexity !== null) {\n const complexity = calculateCyclomaticComplexity(fn);\n if (complexity > maxComplexity) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has cyclomatic complexity ${complexity} which exceeds maximum ${maxComplexity}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Refactor to reduce branching or extract smaller functions',\n })\n );\n }\n }\n\n if (maxParams !== null) {\n const paramCount = fn.getParameters().length;\n if (paramCount > maxParams) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has ${paramCount} parameters which exceeds maximum ${maxParams}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Consider grouping parameters into an options object',\n })\n );\n }\n }\n\n if (maxNesting !== null) {\n const depth = maxNestingDepth(fn);\n if (depth > maxNesting) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has nesting depth ${depth} which exceeds maximum ${maxNesting}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Reduce nesting by using early returns or extracting functions',\n })\n );\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Security verifier (heuristic/static checks)\n *\n * Supports rules like:\n * - \"No hardcoded secrets\"\n * - \"Avoid eval / Function constructor\"\n * - \"Prevent SQL injection\"\n * - \"Avoid innerHTML / dangerouslySetInnerHTML\"\n */\nimport type { Node } from 'ts-morph';\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst SECRET_NAME_RE = /(api[_-]?key|password|secret|token)/i;\n\nfunction isStringLiteralLike(node: Node): boolean {\n const k = node.getKind();\n return k === SyntaxKind.StringLiteral || k === SyntaxKind.NoSubstitutionTemplateLiteral;\n}\n\nexport class SecurityVerifier implements Verifier {\n readonly id = 'security';\n readonly name = 'Security Verifier';\n readonly description =\n 'Detects common security footguns (secrets, eval, XSS/SQL injection heuristics)';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n const checkSecrets =\n rule.includes('secret') ||\n rule.includes('password') ||\n rule.includes('token') ||\n rule.includes('api key') ||\n rule.includes('hardcoded');\n const checkEval = rule.includes('eval') || rule.includes('function constructor');\n const checkXss =\n rule.includes('xss') ||\n rule.includes('innerhtml') ||\n rule.includes('dangerouslysetinnerhtml');\n const checkSql = rule.includes('sql') || rule.includes('injection');\n const checkProto = rule.includes('prototype pollution') || rule.includes('__proto__');\n\n if (checkSecrets) {\n for (const vd of sourceFile.getVariableDeclarations()) {\n const name = vd.getName();\n if (!SECRET_NAME_RE.test(name)) continue;\n\n const init = vd.getInitializer();\n if (!init || !isStringLiteralLike(init)) continue;\n\n const value = init.getText().slice(1, -1); // best-effort strip quotes\n if (value.length === 0) continue;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible hardcoded secret in variable \"${name}\"`,\n file: filePath,\n line: vd.getStartLineNumber(),\n suggestion: 'Move secrets to environment variables or a secret manager',\n })\n );\n }\n\n for (const pa of sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {\n const propName = pa.getNameNode().getText();\n if (!SECRET_NAME_RE.test(propName)) continue;\n\n const init = pa.getInitializer();\n if (!init || !isStringLiteralLike(init)) continue;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible hardcoded secret in object property ${propName}`,\n file: filePath,\n line: pa.getStartLineNumber(),\n suggestion: 'Move secrets to environment variables or a secret manager',\n })\n );\n }\n }\n\n if (checkEval) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const exprText = call.getExpression().getText();\n if (exprText === 'eval' || exprText === 'Function') {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Unsafe dynamic code execution via ${exprText}()`,\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Avoid eval/Function; use safer alternatives',\n })\n );\n }\n }\n }\n\n if (checkXss) {\n // innerHTML assignments\n for (const bin of sourceFile.getDescendantsOfKind(SyntaxKind.BinaryExpression)) {\n const left = bin.getLeft();\n const propertyAccess = left.asKind(SyntaxKind.PropertyAccessExpression);\n if (!propertyAccess) continue;\n if (propertyAccess.getName() === 'innerHTML') {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential XSS: assignment to innerHTML',\n file: filePath,\n line: bin.getStartLineNumber(),\n suggestion: 'Prefer textContent or a safe templating/escaping strategy',\n })\n );\n }\n }\n\n // React dangerouslySetInnerHTML usage\n if (sourceFile.getFullText().includes('dangerouslySetInnerHTML')) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential XSS: usage of dangerouslySetInnerHTML',\n file: filePath,\n line: 1,\n suggestion: 'Avoid dangerouslySetInnerHTML or ensure content is sanitized',\n })\n );\n }\n }\n\n if (checkSql) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n const propertyAccess = expr.asKind(SyntaxKind.PropertyAccessExpression);\n if (!propertyAccess) continue;\n const name = propertyAccess.getName();\n if (name !== 'query' && name !== 'execute') continue;\n\n const arg = call.getArguments()[0];\n if (!arg) continue;\n\n const isTemplate = arg.getKind() === SyntaxKind.TemplateExpression;\n const isConcat =\n arg.getKind() === SyntaxKind.BinaryExpression && arg.getText().includes('+');\n if (!isTemplate && !isConcat) continue;\n\n const text = arg.getText().toLowerCase();\n if (\n !text.includes('select') &&\n !text.includes('insert') &&\n !text.includes('update') &&\n !text.includes('delete')\n ) {\n continue;\n }\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential SQL injection: dynamically constructed SQL query',\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Use parameterized queries / prepared statements',\n })\n );\n }\n }\n\n if (checkProto) {\n const text = sourceFile.getFullText();\n if (text.includes('__proto__') || text.includes('constructor.prototype')) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential prototype pollution pattern detected',\n file: filePath,\n line: 1,\n suggestion: 'Avoid writing to __proto__/prototype; validate object keys',\n })\n );\n }\n }\n\n return violations;\n }\n}\n","/**\n * API consistency verifier (heuristic)\n *\n * Supports rules like:\n * - \"REST endpoints must use kebab-case\"\n */\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'all']);\n\nfunction isKebabPath(pathValue: string): boolean {\n const parts = pathValue.split('/').filter(Boolean);\n for (const part of parts) {\n if (part.startsWith(':')) continue; // path params\n if (!/^[a-z0-9-]+$/.test(part)) return false;\n }\n return true;\n}\n\nexport class ApiVerifier implements Verifier {\n readonly id = 'api';\n readonly name = 'API Consistency Verifier';\n readonly description = 'Checks basic REST endpoint naming conventions in common frameworks';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n const enforceKebab = rule.includes('kebab') || rule.includes('kebab-case');\n if (!enforceKebab) return violations;\n\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n const propertyAccess = expr.asKind(SyntaxKind.PropertyAccessExpression);\n if (!propertyAccess) continue;\n\n const method = propertyAccess.getName();\n if (!method || !HTTP_METHODS.has(String(method))) continue;\n\n const firstArg = call.getArguments()[0];\n const stringLiteral = firstArg?.asKind(SyntaxKind.StringLiteral);\n if (!stringLiteral) continue;\n\n const pathValue = stringLiteral.getLiteralValue();\n if (typeof pathValue !== 'string') continue;\n\n if (!isKebabPath(pathValue)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Endpoint path \"${pathValue}\" is not kebab-case`,\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Use lowercase and hyphens in static path segments (e.g., /user-settings)',\n })\n );\n }\n }\n\n return violations;\n }\n}\n","/**\n * Plugin loader for custom verifiers\n *\n * Dynamically loads verifier plugins from .specbridge/verifiers/\n */\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { pathToFileURL } from 'url';\nimport fg from 'fast-glob';\nimport type { Verifier, VerifierPlugin } from '../verifiers/base.js';\nimport { getLogger } from '../../utils/logger.js';\n\n/**\n * Manages loading and registry of custom verifier plugins\n */\nexport class PluginLoader {\n private plugins = new Map<string, VerifierPlugin>();\n private loaded = false;\n private loadErrors: Array<{ file: string; error: string }> = [];\n private logger = getLogger({ module: 'verification.plugins.loader' });\n\n /**\n * Load all plugins from the specified base path\n *\n * @param basePath - Project root directory (usually cwd)\n */\n async loadPlugins(basePath: string): Promise<void> {\n const verifiersDir = join(basePath, '.specbridge', 'verifiers');\n\n // Check if directory exists\n if (!existsSync(verifiersDir)) {\n this.loaded = true;\n return;\n }\n\n // Find all .ts and .js files (excluding tests and .d.ts)\n const files = await fg('**/*.{ts,js}', {\n cwd: verifiersDir,\n absolute: true,\n ignore: ['**/*.test.{ts,js}', '**/*.d.ts'],\n });\n\n // Load each plugin\n for (const file of files) {\n try {\n await this.loadPlugin(file);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.loadErrors.push({ file, error: message });\n this.logger.warn({ file, error: message }, 'Failed to load plugin');\n }\n }\n\n this.loaded = true;\n\n // Log summary\n if (this.plugins.size > 0) {\n this.logger.info({ count: this.plugins.size }, 'Loaded custom verifier plugins');\n }\n if (this.loadErrors.length > 0) {\n this.logger.warn({ count: this.loadErrors.length }, 'Plugin load failures');\n }\n }\n\n /**\n * Load a single plugin file\n */\n private async loadPlugin(filePath: string): Promise<void> {\n // Convert to file URL for ESM import\n const fileUrl = pathToFileURL(filePath).href;\n\n // Dynamic import\n const module = await import(fileUrl);\n\n // Extract plugin (default export or named 'plugin' export)\n const plugin: VerifierPlugin = module.default || module.plugin;\n\n if (!plugin) {\n throw new Error('Plugin must export a default or named \"plugin\" export');\n }\n\n // Validate plugin structure\n this.validatePlugin(plugin, filePath);\n\n // Check for ID conflicts\n if (this.plugins.has(plugin.metadata.id)) {\n throw new Error(\n `Plugin ID \"${plugin.metadata.id}\" is already registered. ` +\n `Each plugin must have a unique ID.`\n );\n }\n\n // Register full plugin (not just factory) to access paramsSchema\n this.plugins.set(plugin.metadata.id, plugin);\n }\n\n /**\n * Validate plugin structure and metadata\n */\n private validatePlugin(plugin: VerifierPlugin, _filePath: string): void {\n // Check required fields\n if (!plugin.metadata) {\n throw new Error('Plugin must have a \"metadata\" property');\n }\n\n if (!plugin.metadata.id || typeof plugin.metadata.id !== 'string') {\n throw new Error('Plugin metadata must have a string \"id\" property');\n }\n\n if (!plugin.metadata.version || typeof plugin.metadata.version !== 'string') {\n throw new Error('Plugin metadata must have a string \"version\" property');\n }\n\n // Validate ID format: lowercase alphanumeric with hyphens, must start with letter\n const idPattern = /^[a-z][a-z0-9-]*$/;\n if (!idPattern.test(plugin.metadata.id)) {\n throw new Error(\n `Plugin ID \"${plugin.metadata.id}\" is invalid. ` +\n `ID must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens.`\n );\n }\n\n // Check createVerifier is a function\n if (typeof plugin.createVerifier !== 'function') {\n throw new Error('Plugin must have a \"createVerifier\" function');\n }\n\n // Test that createVerifier returns a valid Verifier\n let verifier: Verifier;\n try {\n verifier = plugin.createVerifier();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`createVerifier() threw an error: ${message}`);\n }\n\n // Validate verifier interface\n if (!verifier || typeof verifier !== 'object') {\n throw new Error('createVerifier() must return an object');\n }\n\n if (!verifier.id || typeof verifier.id !== 'string') {\n throw new Error('Verifier must have a string \"id\" property');\n }\n\n if (!verifier.name || typeof verifier.name !== 'string') {\n throw new Error('Verifier must have a string \"name\" property');\n }\n\n if (!verifier.description || typeof verifier.description !== 'string') {\n throw new Error('Verifier must have a string \"description\" property');\n }\n\n if (typeof verifier.verify !== 'function') {\n throw new Error('Verifier must have a \"verify\" method');\n }\n\n // Verify that verifier.id matches plugin.metadata.id\n if (verifier.id !== plugin.metadata.id) {\n throw new Error(\n `Verifier ID \"${verifier.id}\" does not match plugin metadata ID \"${plugin.metadata.id}\". ` +\n `These must be identical.`\n );\n }\n }\n\n /**\n * Get a verifier instance by ID\n *\n * @param id - Verifier ID\n * @returns Verifier instance or null if not found\n */\n getVerifier(id: string): Verifier | null {\n const plugin = this.plugins.get(id);\n return plugin ? plugin.createVerifier() : null;\n }\n\n /**\n * Get a plugin by ID (includes paramsSchema)\n *\n * @param id - Plugin ID\n * @returns Plugin or null if not found\n */\n getPlugin(id: string): VerifierPlugin | null {\n return this.plugins.get(id) || null;\n }\n\n /**\n * Validate params against a plugin's paramsSchema\n *\n * @param id - Plugin ID\n * @param params - Parameters to validate\n * @returns Validation result with success flag and error message if failed\n */\n validateParams(\n id: string,\n params: Record<string, unknown> | undefined\n ): { success: true } | { success: false; error: string } {\n const plugin = this.plugins.get(id);\n\n if (!plugin) {\n return { success: false, error: `Plugin ${id} not found` };\n }\n\n // If no paramsSchema is defined, params validation is not required\n if (!plugin.paramsSchema) {\n return { success: true };\n }\n\n // If paramsSchema exists but no params provided, that's an error\n if (!params) {\n return { success: false, error: `Plugin ${id} requires params but none were provided` };\n }\n\n // Validate that paramsSchema is a Zod schema\n if (\n typeof plugin.paramsSchema !== 'object' ||\n !plugin.paramsSchema ||\n !('parse' in plugin.paramsSchema)\n ) {\n return {\n success: false,\n error: `Plugin ${id} has invalid paramsSchema (must be a Zod schema)`,\n };\n }\n\n // Narrow to a parse-capable schema after validating the contract at runtime.\n const schema = plugin.paramsSchema as {\n parse: (data: unknown) => unknown;\n safeParse?: (data: unknown) => {\n success: boolean;\n error?: { issues: Array<{ message: string; path: Array<string | number> }> };\n };\n };\n\n // Use safeParse if available, otherwise catch parse errors\n if (schema.safeParse) {\n const result = schema.safeParse(params);\n if (!result.success) {\n const errors =\n result.error?.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join(', ') || 'Validation failed';\n return { success: false, error: `Invalid params for ${id}: ${errors}` };\n }\n } else {\n try {\n schema.parse(params);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { success: false, error: `Invalid params for ${id}: ${message}` };\n }\n }\n\n return { success: true };\n }\n\n /**\n * Get all registered plugin IDs\n */\n getPluginIds(): string[] {\n return Array.from(this.plugins.keys());\n }\n\n /**\n * Check if plugins have been loaded\n */\n isLoaded(): boolean {\n return this.loaded;\n }\n\n /**\n * Get load errors (for diagnostics)\n */\n getLoadErrors(): Array<{ file: string; error: string }> {\n return [...this.loadErrors];\n }\n\n /**\n * Reset the loader (useful for testing)\n */\n reset(): void {\n this.plugins.clear();\n this.loaded = false;\n this.loadErrors = [];\n }\n}\n\n/**\n * Singleton plugin loader instance\n */\nlet pluginLoader: PluginLoader | null = null;\n\n/**\n * Get the global plugin loader instance\n */\nexport function getPluginLoader(): PluginLoader {\n if (!pluginLoader) {\n pluginLoader = new PluginLoader();\n }\n return pluginLoader;\n}\n\n/**\n * Reset the global plugin loader (for testing)\n */\nexport function resetPluginLoader(): void {\n if (pluginLoader) {\n pluginLoader.reset();\n }\n pluginLoader = null;\n}\n","import pino, { type Logger as PinoLogger, type LoggerOptions } from 'pino';\n\nexport type Logger = Pick<PinoLogger, 'debug' | 'info' | 'warn' | 'error' | 'child'>;\n\nconst defaultOptions: LoggerOptions = {\n level: process.env.SPECBRIDGE_LOG_LEVEL || 'info',\n timestamp: pino.stdTimeFunctions.isoTime,\n base: {\n service: 'specbridge',\n },\n};\n\nconst destination = pino.destination({\n fd: 2, // stderr\n sync: false,\n});\n\nconst rootLogger = pino(defaultOptions, destination);\n\nexport function getLogger(bindings?: Record<string, unknown>): Logger {\n if (!bindings) {\n return rootLogger;\n }\n return rootLogger.child(bindings);\n}\n\nexport const logger = getLogger();\n","/**\n * Verifier exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './errors.js';\nexport * from './regex.js';\nexport * from './dependencies.js';\nexport * from './complexity.js';\nexport * from './security.js';\nexport * from './api.js';\n\nimport type { Verifier } from './base.js';\nimport { NamingVerifier } from './naming.js';\nimport { ImportsVerifier } from './imports.js';\nimport { ErrorsVerifier } from './errors.js';\nimport { RegexVerifier } from './regex.js';\nimport { DependencyVerifier } from './dependencies.js';\nimport { ComplexityVerifier } from './complexity.js';\nimport { SecurityVerifier } from './security.js';\nimport { ApiVerifier } from './api.js';\nimport { getPluginLoader } from '../plugins/loader.js';\n\n/**\n * Built-in verifiers registry\n */\nexport const builtinVerifiers: Record<string, () => Verifier> = {\n naming: () => new NamingVerifier(),\n imports: () => new ImportsVerifier(),\n errors: () => new ErrorsVerifier(),\n regex: () => new RegexVerifier(),\n dependencies: () => new DependencyVerifier(),\n complexity: () => new ComplexityVerifier(),\n security: () => new SecurityVerifier(),\n api: () => new ApiVerifier(),\n};\n\n/**\n * Verifier instance pool (reuse instances instead of creating new ones)\n */\nconst verifierInstances = new Map<string, Verifier>();\n\n/**\n * Get verifier by ID\n * Checks custom plugins first, then built-in verifiers\n * Instances are pooled for performance\n */\nexport function getVerifier(id: string): Verifier | null {\n // Check instance pool first\n const pooled = verifierInstances.get(id);\n if (pooled) {\n return pooled;\n }\n\n // Priority 1: Custom plugins\n const pluginLoader = getPluginLoader();\n const customVerifier = pluginLoader.getVerifier(id);\n if (customVerifier) {\n verifierInstances.set(id, customVerifier);\n return customVerifier;\n }\n\n // Priority 2: Built-in verifiers\n const factory = builtinVerifiers[id];\n if (factory) {\n const verifier = factory();\n verifierInstances.set(id, verifier);\n return verifier;\n }\n\n return null;\n}\n\n/**\n * Get all verifier IDs (built-in + plugins)\n */\nexport function getVerifierIds(): string[] {\n const builtinIds = Object.keys(builtinVerifiers);\n const pluginIds = getPluginLoader().getPluginIds();\n return [...new Set([...builtinIds, ...pluginIds])];\n}\n\n/**\n * Clear the verifier instance pool (for testing)\n */\nexport function clearVerifierPool(): void {\n verifierInstances.clear();\n}\n\n/**\n * Select appropriate verifier based on constraint\n */\nexport function selectVerifierForConstraint(\n rule: string,\n specifiedVerifier?: string,\n check?: { verifier: string; params?: Record<string, unknown> }\n): Verifier | null {\n // Priority 1: Use check block verifier if present (new structured format)\n if (check?.verifier) {\n return getVerifier(check.verifier);\n }\n\n // Priority 2: Use legacy verifier field if specified\n if (specifiedVerifier) {\n return getVerifier(specifiedVerifier);\n }\n\n // Priority 3: Auto-select based on rule content\n const lowerRule = rule.toLowerCase();\n\n if (\n lowerRule.includes('dependency') ||\n lowerRule.includes('circular dependenc') ||\n lowerRule.includes('import depth') ||\n (lowerRule.includes('layer') && lowerRule.includes('depend on'))\n ) {\n return getVerifier('dependencies');\n }\n\n if (\n lowerRule.includes('cyclomatic') ||\n lowerRule.includes('complexity') ||\n lowerRule.includes('nesting') ||\n lowerRule.includes('parameters') ||\n lowerRule.includes('file size')\n ) {\n return getVerifier('complexity');\n }\n\n if (\n lowerRule.includes('security') ||\n lowerRule.includes('secret') ||\n lowerRule.includes('password') ||\n lowerRule.includes('token') ||\n lowerRule.includes('xss') ||\n lowerRule.includes('sql') ||\n lowerRule.includes('eval')\n ) {\n return getVerifier('security');\n }\n\n if (\n lowerRule.includes('endpoint') ||\n lowerRule.includes('rest') ||\n (lowerRule.includes('api') && lowerRule.includes('path'))\n ) {\n return getVerifier('api');\n }\n\n if (lowerRule.includes('naming') || lowerRule.includes('case')) {\n return getVerifier('naming');\n }\n\n if (lowerRule.includes('import') || lowerRule.includes('barrel') || lowerRule.includes('alias')) {\n return getVerifier('imports');\n }\n\n if (lowerRule.includes('error') || lowerRule.includes('throw') || lowerRule.includes('catch')) {\n return getVerifier('errors');\n }\n\n if (lowerRule.includes('/') || lowerRule.includes('pattern') || lowerRule.includes('regex')) {\n return getVerifier('regex');\n }\n\n // Default to regex verifier for pattern-based rules\n return getVerifier('regex');\n}\n","/**\n * AST parsing cache (per VerificationEngine instance)\n * Uses content hashing for better invalidation\n */\nimport { stat, readFile } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport type { Project, SourceFile } from 'ts-morph';\n\ninterface CacheEntry {\n sourceFile: SourceFile;\n hash: string;\n mtimeMs: number;\n}\n\nexport class AstCache {\n private cache = new Map<string, CacheEntry>();\n\n async get(filePath: string, project: Project): Promise<SourceFile | null> {\n try {\n const stats = await stat(filePath);\n const cached = this.cache.get(filePath);\n\n // Quick check: mtime hasn't changed\n if (cached && cached.mtimeMs >= stats.mtimeMs) {\n return cached.sourceFile;\n }\n\n // Read and hash content\n const content = await readFile(filePath, 'utf-8');\n const hash = createHash('sha256').update(content).digest('hex');\n\n // If hash matches, update mtime but keep AST\n if (cached && cached.hash === hash) {\n cached.mtimeMs = stats.mtimeMs;\n return cached.sourceFile;\n }\n\n // Re-parse: content has changed\n let sourceFile = project.getSourceFile(filePath);\n if (!sourceFile) {\n sourceFile = project.addSourceFileAtPath(filePath);\n } else {\n // Refresh from disk if the file changed\n sourceFile.refreshFromFileSystemSync();\n }\n\n this.cache.set(filePath, {\n sourceFile,\n hash,\n mtimeMs: stats.mtimeMs,\n });\n\n return sourceFile;\n } catch {\n return null;\n }\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n getStats() {\n return {\n entries: this.cache.size,\n memoryEstimate: this.cache.size * 50000, // Rough estimate: 50KB per AST\n };\n }\n}\n","/**\n * Results cache - Caches verification results by file hash + constraint\n *\n * Avoids re-running verifiers on unchanged files\n */\nimport type { Violation } from '../core/types/index.js';\n\nexport interface CacheKey {\n filePath: string;\n decisionId: string;\n constraintId: string;\n fileHash: string;\n}\n\n/**\n * Cache for verification results\n * Results are keyed by file path + decision + constraint + file hash\n */\nexport class ResultsCache {\n private cache = new Map<string, Violation[]>();\n\n /**\n * Generate cache key from components\n */\n private getCacheKey(key: CacheKey): string {\n return `${key.filePath}:${key.decisionId}:${key.constraintId}:${key.fileHash}`;\n }\n\n /**\n * Get cached violations for a specific verification\n *\n * @returns Violations if cached, null if not found\n */\n get(key: CacheKey): Violation[] | null {\n const cacheKey = this.getCacheKey(key);\n return this.cache.get(cacheKey) || null;\n }\n\n /**\n * Store verification results in cache\n */\n set(key: CacheKey, violations: Violation[]): void {\n const cacheKey = this.getCacheKey(key);\n this.cache.set(cacheKey, violations);\n }\n\n /**\n * Check if result is cached\n */\n has(key: CacheKey): boolean {\n const cacheKey = this.getCacheKey(key);\n return this.cache.has(cacheKey);\n }\n\n /**\n * Clear entire cache\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Clear cache entries for a specific file\n */\n clearFile(filePath: string): void {\n for (const key of this.cache.keys()) {\n if (key.startsWith(`${filePath}:`)) {\n this.cache.delete(key);\n }\n }\n }\n\n /**\n * Clear cache entries for a specific decision\n */\n clearDecision(decisionId: string): void {\n for (const key of this.cache.keys()) {\n if (key.includes(`:${decisionId}:`)) {\n this.cache.delete(key);\n }\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats() {\n return {\n entries: this.cache.size,\n memoryEstimate: this.cache.size * 1000, // Rough estimate: 1KB per result\n };\n }\n}\n","/**\n * Shared constraint applicability helpers\n */\nimport type { Constraint, Severity } from '../core/types/index.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport function isConstraintExcepted(\n filePath: string,\n constraint: Constraint,\n cwd: string\n): boolean {\n if (!constraint.exceptions) return false;\n\n return constraint.exceptions.some((exception) => {\n // Check if exception has expired\n if (exception.expiresAt) {\n const expiryDate = new Date(exception.expiresAt);\n if (expiryDate < new Date()) {\n return false;\n }\n }\n\n return matchesPattern(filePath, exception.pattern, { cwd });\n });\n}\n\nexport function shouldApplyConstraintToFile(params: {\n filePath: string;\n constraint: Constraint;\n cwd: string;\n severityFilter?: Severity[];\n}): boolean {\n const { filePath, constraint, cwd, severityFilter } = params;\n\n if (!matchesPattern(filePath, constraint.scope, { cwd })) return false;\n if (severityFilter && !severityFilter.includes(constraint.severity)) return false;\n if (isConstraintExcepted(filePath, constraint, cwd)) return false;\n\n return true;\n}\n","/**\n * Incremental verification helpers\n */\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { resolve } from 'node:path';\nimport { pathExists } from '../utils/fs.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport async function getChangedFiles(cwd: string): Promise<string[]> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['diff', '--name-only', '--diff-filter=AM', 'HEAD'],\n { cwd }\n );\n const rel = stdout\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean);\n\n const abs: string[] = [];\n for (const file of rel) {\n const full = resolve(cwd, file);\n if (await pathExists(full)) abs.push(full);\n }\n return abs;\n } catch {\n return [];\n }\n}\n","/**\n * Auto-fix engine\n */\nimport { readFile, writeFile } from 'node:fs/promises';\nimport readline from 'node:readline/promises';\nimport { stdin, stdout } from 'node:process';\nimport type { Violation, TextEdit } from '../../core/types/index.js';\n\nexport interface AutofixPatch {\n filePath: string;\n description: string;\n start: number;\n end: number;\n originalText: string;\n fixedText: string;\n}\n\nexport interface AutofixResult {\n applied: AutofixPatch[];\n skipped: number;\n}\n\ntype DescribedEdit = TextEdit & { description: string };\n\nfunction applyEdits(\n content: string,\n edits: DescribedEdit[]\n): { next: string; patches: AutofixPatch[]; skippedEdits: number } {\n const sorted = [...edits].sort((a, b) => b.start - a.start);\n\n let next = content;\n const patches: AutofixPatch[] = [];\n let skippedEdits = 0;\n let lastStart = Number.POSITIVE_INFINITY;\n\n for (const edit of sorted) {\n if (edit.start < 0 || edit.end < edit.start || edit.end > next.length) {\n skippedEdits++;\n continue;\n }\n\n // Overlap check (since edits are sorted by start descending)\n if (edit.end > lastStart) {\n skippedEdits++;\n continue;\n }\n lastStart = edit.start;\n\n const originalText = next.slice(edit.start, edit.end);\n next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);\n\n patches.push({\n filePath: '',\n description: edit.description,\n start: edit.start,\n end: edit.end,\n originalText,\n fixedText: edit.text,\n });\n }\n\n return { next, patches, skippedEdits };\n}\n\nasync function confirmFix(prompt: string): Promise<boolean> {\n const rl = readline.createInterface({ input: stdin, output: stdout });\n try {\n const answer = await rl.question(`${prompt} (y/N) `);\n return answer.trim().toLowerCase() === 'y';\n } finally {\n rl.close();\n }\n}\n\nexport class AutofixEngine {\n async applyFixes(\n violations: Violation[],\n options: { dryRun?: boolean; interactive?: boolean } = {}\n ): Promise<AutofixResult> {\n const fixable = violations.filter((v) => v.autofix && v.autofix.edits.length > 0);\n const byFile = new Map<string, Violation[]>();\n for (const v of fixable) {\n const list = byFile.get(v.file) ?? [];\n list.push(v);\n byFile.set(v.file, list);\n }\n\n const applied: AutofixPatch[] = [];\n let skippedViolations = 0;\n\n for (const [filePath, fileViolations] of byFile) {\n const original = await readFile(filePath, 'utf-8');\n\n const edits: DescribedEdit[] = [];\n for (const violation of fileViolations) {\n const fix = violation.autofix;\n if (!fix) {\n skippedViolations++;\n continue;\n }\n if (options.interactive) {\n const ok = await confirmFix(\n `Apply fix: ${fix.description} (${filePath}:${violation.line ?? 1})?`\n );\n if (!ok) {\n skippedViolations++;\n continue;\n }\n }\n for (const edit of fix.edits) {\n edits.push({ ...edit, description: fix.description });\n }\n }\n\n if (edits.length === 0) continue;\n\n const { next, patches, skippedEdits } = applyEdits(original, edits);\n skippedViolations += skippedEdits;\n\n if (!options.dryRun) {\n await writeFile(filePath, next, 'utf-8');\n }\n\n for (const patch of patches) {\n applied.push({ ...patch, filePath });\n }\n }\n\n return { applied, skipped: skippedViolations };\n }\n}\n","/**\n * Dependency graph for impact analysis\n */\nimport type { Decision } from '../core/types/index.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface GraphNode {\n type: 'decision' | 'constraint' | 'file';\n id: string;\n edges: string[];\n}\n\nexport interface DependencyGraph {\n nodes: Map<string, GraphNode>;\n decisionToFiles: Map<string, Set<string>>;\n fileToDecisions: Map<string, Set<string>>;\n}\n\nexport interface BuildDependencyGraphOptions {\n cwd?: string;\n}\n\n/**\n * Build dependency graph from decisions and file list\n */\nexport async function buildDependencyGraph(\n decisions: Decision[],\n files: string[],\n options: BuildDependencyGraphOptions = {}\n): Promise<DependencyGraph> {\n const { cwd } = options;\n const nodes = new Map<string, GraphNode>();\n const decisionToFiles = new Map<string, Set<string>>();\n const fileToDecisions = new Map<string, Set<string>>();\n\n // Add decision nodes\n for (const decision of decisions) {\n const decisionId = `decision:${decision.metadata.id}`;\n nodes.set(decisionId, {\n type: 'decision',\n id: decision.metadata.id,\n edges: decision.constraints.map((c) => `constraint:${decision.metadata.id}/${c.id}`),\n });\n\n // Add constraint nodes\n for (const constraint of decision.constraints) {\n const constraintId = `constraint:${decision.metadata.id}/${constraint.id}`;\n const matchingFiles: string[] = [];\n\n for (const file of files) {\n if (matchesPattern(file, constraint.scope, { cwd })) {\n matchingFiles.push(`file:${file}`);\n\n // Update file -> decision mapping\n const fileDecisions = fileToDecisions.get(file) || new Set();\n fileDecisions.add(decision.metadata.id);\n fileToDecisions.set(file, fileDecisions);\n\n // Update decision -> files mapping\n const decFiles = decisionToFiles.get(decision.metadata.id) || new Set();\n decFiles.add(file);\n decisionToFiles.set(decision.metadata.id, decFiles);\n }\n }\n\n nodes.set(constraintId, {\n type: 'constraint',\n id: `${decision.metadata.id}/${constraint.id}`,\n edges: matchingFiles,\n });\n }\n }\n\n // Add file nodes\n for (const file of files) {\n const fileId = `file:${file}`;\n if (!nodes.has(fileId)) {\n nodes.set(fileId, {\n type: 'file',\n id: file,\n edges: [],\n });\n }\n }\n\n return {\n nodes,\n decisionToFiles,\n fileToDecisions,\n };\n}\n\n/**\n * Get files affected by a decision\n */\nexport function getAffectedFiles(graph: DependencyGraph, decisionId: string): string[] {\n const files = graph.decisionToFiles.get(decisionId);\n return files ? Array.from(files) : [];\n}\n\n/**\n * Get decisions affecting a file\n */\nexport function getAffectingDecisions(graph: DependencyGraph, filePath: string): string[] {\n const decisions = graph.fileToDecisions.get(filePath);\n return decisions ? Array.from(decisions) : [];\n}\n\n/**\n * Calculate transitive closure for a node\n */\nexport function getTransitiveDependencies(\n graph: DependencyGraph,\n nodeId: string,\n visited: Set<string> = new Set()\n): string[] {\n if (visited.has(nodeId)) {\n return [];\n }\n\n visited.add(nodeId);\n const node = graph.nodes.get(nodeId);\n\n if (!node) {\n return [];\n }\n\n const deps: string[] = [nodeId];\n\n for (const edge of node.edges) {\n deps.push(...getTransitiveDependencies(graph, edge, visited));\n }\n\n return deps;\n}\n","/**\n * Propagation Engine - Analyze impact of decision changes\n */\nimport type {\n ImpactAnalysis,\n AffectedFile,\n MigrationStep,\n SpecBridgeConfig,\n} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { createVerificationEngine } from '../verification/engine.js';\nimport { buildDependencyGraph, getAffectedFiles, type DependencyGraph } from './graph.js';\nimport { glob } from '../utils/glob.js';\n\nexport interface PropagationOptions {\n cwd?: string;\n}\n\n/**\n * Propagation Engine class\n */\nexport class PropagationEngine {\n private registry: Registry;\n private graph: DependencyGraph | null = null;\n\n constructor(registry?: Registry) {\n this.registry = registry || createRegistry();\n }\n\n /**\n * Initialize the engine with current state\n */\n async initialize(config: SpecBridgeConfig, options: PropagationOptions = {}): Promise<void> {\n const { cwd = process.cwd() } = options;\n\n // Load registry\n await this.registry.load();\n\n // Get all files\n const files = await glob(config.project.sourceRoots, {\n cwd,\n ignore: config.project.exclude,\n absolute: true,\n });\n\n // Build dependency graph\n const decisions = this.registry.getActive();\n this.graph = await buildDependencyGraph(decisions, files, { cwd });\n }\n\n /**\n * Analyze impact of changing a decision\n */\n async analyzeImpact(\n decisionId: string,\n change: 'created' | 'modified' | 'deprecated',\n config: SpecBridgeConfig,\n options: PropagationOptions = {}\n ): Promise<ImpactAnalysis> {\n const { cwd = process.cwd() } = options;\n\n // Ensure initialized\n if (!this.graph) {\n await this.initialize(config, options);\n }\n const graph = this.graph;\n if (!graph) {\n return {\n decision: decisionId,\n change,\n affectedFiles: [],\n estimatedEffort: 'low',\n migrationSteps: [\n {\n order: 1,\n description: 'Run verification to confirm all violations resolved',\n files: [],\n automated: true,\n },\n ],\n };\n }\n\n // Get affected files\n const affectedFilePaths = getAffectedFiles(graph, decisionId);\n\n // Run verification on affected files\n const verificationEngine = createVerificationEngine(this.registry);\n const result = await verificationEngine.verify(config, {\n files: affectedFilePaths,\n decisions: [decisionId],\n cwd,\n });\n\n // Group violations by file\n const fileViolations = new Map<string, { total: number; autoFixable: number }>();\n for (const violation of result.violations) {\n const existing = fileViolations.get(violation.file) || { total: 0, autoFixable: 0 };\n existing.total++;\n if (violation.autofix) {\n existing.autoFixable++;\n }\n fileViolations.set(violation.file, existing);\n }\n\n // Build affected files list\n const affectedFiles: AffectedFile[] = affectedFilePaths.map((path) => ({\n path,\n violations: fileViolations.get(path)?.total || 0,\n autoFixable: fileViolations.get(path)?.autoFixable || 0,\n }));\n\n // Sort by violations (most first)\n affectedFiles.sort((a, b) => b.violations - a.violations);\n\n // Estimate effort\n const totalViolations = result.violations.length;\n const totalAutoFixable = result.violations.filter((v) => v.autofix).length;\n const manualFixes = totalViolations - totalAutoFixable;\n\n let estimatedEffort: 'low' | 'medium' | 'high';\n if (manualFixes === 0) {\n estimatedEffort = 'low';\n } else if (manualFixes <= 10) {\n estimatedEffort = 'medium';\n } else {\n estimatedEffort = 'high';\n }\n\n // Generate migration steps\n const migrationSteps = this.generateMigrationSteps(affectedFiles, totalAutoFixable > 0);\n\n return {\n decision: decisionId,\n change,\n affectedFiles,\n estimatedEffort,\n migrationSteps,\n };\n }\n\n /**\n * Generate migration steps\n */\n private generateMigrationSteps(\n affectedFiles: AffectedFile[],\n hasAutoFixes: boolean\n ): MigrationStep[] {\n const steps: MigrationStep[] = [];\n let order = 1;\n\n // Step 1: Run auto-fixes if available\n if (hasAutoFixes) {\n steps.push({\n order: order++,\n description: 'Run auto-fix for mechanical violations',\n files: affectedFiles.filter((f) => f.autoFixable > 0).map((f) => f.path),\n automated: true,\n });\n }\n\n // Step 2: Manual fixes for remaining violations\n const filesWithManualFixes = affectedFiles.filter((f) => f.violations > f.autoFixable);\n\n if (filesWithManualFixes.length > 0) {\n // Group by severity/priority\n const highPriority = filesWithManualFixes.filter((f) => f.violations > 5);\n const mediumPriority = filesWithManualFixes.filter(\n (f) => f.violations <= 5 && f.violations > 1\n );\n const lowPriority = filesWithManualFixes.filter((f) => f.violations === 1);\n\n if (highPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix high-violation files first',\n files: highPriority.map((f) => f.path),\n automated: false,\n });\n }\n\n if (mediumPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix medium-violation files',\n files: mediumPriority.map((f) => f.path),\n automated: false,\n });\n }\n\n if (lowPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix remaining files',\n files: lowPriority.map((f) => f.path),\n automated: false,\n });\n }\n }\n\n // Step 3: Verification\n steps.push({\n order: order++,\n description: 'Run verification to confirm all violations resolved',\n files: [],\n automated: true,\n });\n\n return steps;\n }\n\n /**\n * Get dependency graph\n */\n getGraph(): DependencyGraph | null {\n return this.graph;\n }\n}\n\n/**\n * Create propagation engine\n */\nexport function createPropagationEngine(registry?: Registry): PropagationEngine {\n return new PropagationEngine(registry);\n}\n","/**\n * Compliance reporter\n */\nimport type {\n ComplianceReport,\n DecisionCompliance,\n SpecBridgeConfig,\n Violation,\n} from '../core/types/index.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { createVerificationEngine } from '../verification/engine.js';\n\nexport interface ReportOptions {\n includeAll?: boolean;\n cwd?: string;\n /** Use v1.3 compliance formula instead of v2.0 severity-weighted formula */\n legacyCompliance?: boolean;\n}\n\n/**\n * Generic verification result shape for Reporter class\n * Supports various result formats from different verification engines\n */\nexport interface ReporterResult {\n violations?: Violation[];\n summary?: {\n totalViolations?: number;\n decisionsChecked?: number;\n filesChecked?: number;\n critical?: number;\n high?: number;\n medium?: number;\n low?: number;\n duration?: number;\n };\n}\n\n/**\n * Generate a compliance report\n */\nexport async function generateReport(\n config: SpecBridgeConfig,\n options: ReportOptions = {}\n): Promise<ComplianceReport> {\n const { includeAll = false, cwd = process.cwd() } = options;\n\n // Load registry\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n\n // Run full verification\n const engine = createVerificationEngine(registry);\n const result = await engine.verify(config, { level: 'full', cwd });\n\n // Get all decisions\n const decisions = includeAll ? registry.getAll() : registry.getActive();\n\n // Calculate per-decision compliance\n const byDecision: DecisionCompliance[] = [];\n\n for (const decision of decisions) {\n const decisionViolations = result.violations.filter(\n (v) => v.decisionId === decision.metadata.id\n );\n\n const constraintCount = decision.constraints.length;\n const violationCount = decisionViolations.length;\n\n // Calculate compliance based on mode\n let compliance: number;\n let violationsBySeverity: DecisionCompliance['violationsBySeverity'];\n let weightedScore: number | undefined;\n let coverageRate: number | undefined;\n\n if (options.legacyCompliance) {\n // v1.3 formula: Simple count-based\n compliance =\n violationCount === 0 ? 100 : Math.max(0, 100 - Math.min(violationCount * 10, 100));\n } else {\n // v2.0 formula: Severity-weighted with coverage penalty\n const weights = { critical: 40, high: 25, medium: 10, low: 2 };\n\n // Count violations by severity\n const bySeverity = {\n critical: decisionViolations.filter((v) => v.severity === 'critical').length,\n high: decisionViolations.filter((v) => v.severity === 'high').length,\n medium: decisionViolations.filter((v) => v.severity === 'medium').length,\n low: decisionViolations.filter((v) => v.severity === 'low').length,\n };\n\n // Calculate weighted score\n weightedScore = decisionViolations.reduce((score, v) => score + weights[v.severity], 0);\n\n // Base compliance\n compliance = Math.max(0, 100 - weightedScore);\n\n // Apply coverage penalty (up to 20% reduction)\n if (decisionViolations.length > 0 && constraintCount > 0) {\n const violationRate = decisionViolations.length / constraintCount;\n compliance = compliance * (1 - violationRate * 0.2);\n coverageRate = violationRate;\n }\n\n compliance = Math.round(compliance);\n violationsBySeverity = bySeverity;\n }\n\n byDecision.push({\n decisionId: decision.metadata.id,\n title: decision.metadata.title,\n status: decision.metadata.status,\n constraints: constraintCount,\n violations: violationCount,\n compliance,\n violationsBySeverity,\n weightedScore,\n coverageRate,\n });\n }\n\n // Sort by compliance (lowest first to highlight problems)\n byDecision.sort((a, b) => a.compliance - b.compliance);\n\n // Calculate summary\n const totalDecisions = decisions.length;\n const activeDecisions = decisions.filter((d) => d.metadata.status === 'active').length;\n const totalConstraints = decisions.reduce((sum, d) => sum + d.constraints.length, 0);\n\n const violationsBySeverity = {\n critical: result.violations.filter((v) => v.severity === 'critical').length,\n high: result.violations.filter((v) => v.severity === 'high').length,\n medium: result.violations.filter((v) => v.severity === 'medium').length,\n low: result.violations.filter((v) => v.severity === 'low').length,\n };\n\n // Overall compliance score\n const overallCompliance =\n byDecision.length > 0\n ? Math.round(byDecision.reduce((sum, d) => sum + d.compliance, 0) / byDecision.length)\n : 100;\n\n return {\n timestamp: new Date().toISOString(),\n project: config.project.name,\n summary: {\n totalDecisions,\n activeDecisions,\n totalConstraints,\n violations: violationsBySeverity,\n compliance: overallCompliance,\n },\n byDecision,\n };\n}\n\n/**\n * Check if compliance has degraded from previous report\n */\nexport function checkDegradation(\n current: ComplianceReport,\n previous: ComplianceReport | null\n): { degraded: boolean; details: string[] } {\n if (!previous) {\n return { degraded: false, details: [] };\n }\n\n const details: string[] = [];\n let degraded = false;\n\n // Check overall compliance\n if (current.summary.compliance < previous.summary.compliance) {\n degraded = true;\n details.push(\n `Overall compliance dropped from ${previous.summary.compliance}% to ${current.summary.compliance}%`\n );\n }\n\n // Check for new critical/high violations\n const newCritical = current.summary.violations.critical - previous.summary.violations.critical;\n const newHigh = current.summary.violations.high - previous.summary.violations.high;\n\n if (newCritical > 0) {\n degraded = true;\n details.push(`${newCritical} new critical violation(s)`);\n }\n\n if (newHigh > 0) {\n degraded = true;\n details.push(`${newHigh} new high severity violation(s)`);\n }\n\n return { degraded, details };\n}\n\n/**\n * Reporter class for formatting verification results\n */\nexport class Reporter {\n /**\n * Generate formatted report from verification result\n */\n generate(\n result: ReporterResult,\n options: {\n format?: 'table' | 'json' | 'markdown';\n includePassedChecks?: boolean;\n groupBy?: 'severity' | 'file';\n colorize?: boolean;\n } = {}\n ): string {\n const { format = 'table', groupBy } = options;\n\n switch (format) {\n case 'json':\n return JSON.stringify(result, null, 2);\n\n case 'markdown':\n return this.formatAsMarkdown(result);\n\n case 'table':\n default:\n return groupBy ? this.formatAsTableGrouped(result, groupBy) : this.formatAsTable(result);\n }\n }\n\n /**\n * Generate compliance overview from multiple results\n */\n generateComplianceReport(results: ReporterResult[]): string {\n const lines: string[] = [];\n lines.push('# Compliance Report\\n');\n\n if (results.length === 0) {\n lines.push('No results to report.\\n');\n return lines.join('\\n');\n }\n\n // Calculate overall stats\n const totalViolations = results.reduce(\n (sum, r) => sum + (r.summary?.totalViolations || r.violations?.length || 0),\n 0\n );\n const avgViolations = totalViolations / results.length;\n\n lines.push(`## Overall Statistics\\n`);\n lines.push(`- Total Results: ${results.length}`);\n lines.push(`- Total Violations: ${totalViolations}`);\n lines.push(`- Average Violations per Result: ${avgViolations.toFixed(1)}`);\n\n // Calculate compliance percentage (simplified)\n const complianceRate =\n results.length > 0\n ? (results.filter((r) => (r.violations?.length || 0) === 0).length / results.length) * 100\n : 100;\n lines.push(`- Compliance Rate: ${complianceRate.toFixed(1)}%\\n`);\n\n return lines.join('\\n');\n }\n\n private formatAsTable(result: ReporterResult): string {\n const lines: string[] = [];\n\n lines.push('Verification Report');\n lines.push('='.repeat(50));\n lines.push('');\n\n // Summary\n if (result.summary) {\n lines.push('Summary:');\n lines.push(` Decisions Checked: ${result.summary.decisionsChecked || 0}`);\n lines.push(` Files Checked: ${result.summary.filesChecked || 0}`);\n lines.push(\n ` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`\n );\n lines.push(` Critical: ${result.summary.critical || 0}`);\n lines.push(` High: ${result.summary.high || 0}`);\n lines.push(` Medium: ${result.summary.medium || 0}`);\n lines.push(` Low: ${result.summary.low || 0}`);\n lines.push(` Duration: ${result.summary.duration || 0}ms`);\n lines.push('');\n }\n\n // Violations\n const totalViolations = result.summary?.totalViolations ?? result.violations?.length ?? 0;\n if (totalViolations > 0 && result.violations && result.violations.length > 0) {\n lines.push('Violations:');\n lines.push('-'.repeat(50));\n\n result.violations.forEach((v: Violation) => {\n const severity = v.severity.toLowerCase();\n lines.push(\n ` [${v.severity.toUpperCase()}] ${v.decisionId} - ${v.constraintId} (${severity})`\n );\n lines.push(` ${v.message}`);\n const file = (v as { location?: { file: string } }).location?.file || v.file;\n const line = (v as { location?: { line?: number } }).location?.line || v.line || 0;\n const column = (v as { location?: { column?: number } }).location?.column || v.column || 0;\n lines.push(` Location: ${file}:${line}:${column}`);\n lines.push('');\n });\n } else {\n lines.push('No violations found.');\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private formatAsTableGrouped(result: ReporterResult, groupBy: 'severity' | 'file'): string {\n const lines: string[] = [];\n\n lines.push('Verification Report');\n lines.push('='.repeat(50));\n lines.push('');\n\n // Summary\n if (result.summary) {\n lines.push('Summary:');\n lines.push(\n ` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`\n );\n lines.push('');\n }\n\n // Group violations\n if (result.violations && result.violations.length > 0) {\n if (groupBy === 'severity') {\n const grouped = new Map<string, Violation[]>();\n result.violations.forEach((v: Violation) => {\n const key = v.severity;\n if (!grouped.has(key)) grouped.set(key, []);\n const bucket = grouped.get(key);\n if (bucket) {\n bucket.push(v);\n }\n });\n\n for (const [severity, violations] of grouped.entries()) {\n lines.push(`Severity: ${severity}`);\n lines.push('-'.repeat(30));\n violations.forEach((v) => {\n lines.push(` ${v.decisionId} - ${v.message}`);\n });\n lines.push('');\n }\n } else if (groupBy === 'file') {\n const grouped = new Map<string, Violation[]>();\n result.violations.forEach((v: Violation) => {\n const key = (v as { location?: { file: string } }).location?.file || v.file || 'unknown';\n if (!grouped.has(key)) grouped.set(key, []);\n const bucket = grouped.get(key);\n if (bucket) {\n bucket.push(v);\n }\n });\n\n for (const [file, violations] of grouped.entries()) {\n lines.push(`File: ${file}`);\n lines.push('-'.repeat(30));\n violations.forEach((v) => {\n lines.push(` [${v.severity}] ${v.message}`);\n });\n lines.push('');\n }\n }\n } else {\n lines.push('No violations found.');\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private formatAsMarkdown(result: ReporterResult): string {\n const lines: string[] = [];\n\n lines.push('## Verification Report\\n');\n\n // Summary\n if (result.summary) {\n lines.push('### Summary\\n');\n lines.push(`- **Decisions Checked:** ${result.summary.decisionsChecked || 0}`);\n lines.push(`- **Files Checked:** ${result.summary.filesChecked || 0}`);\n lines.push(\n `- **Total Violations:** ${result.summary.totalViolations || result.violations?.length || 0}`\n );\n lines.push(`- **Critical:** ${result.summary.critical || 0}`);\n lines.push(`- **High:** ${result.summary.high || 0}`);\n lines.push(`- **Medium:** ${result.summary.medium || 0}`);\n lines.push(`- **Low:** ${result.summary.low || 0}\\n`);\n }\n\n // Violations\n if (result.violations && result.violations.length > 0) {\n lines.push('### Violations\\n');\n\n result.violations.forEach((v: Violation) => {\n lines.push(`#### [${v.severity.toUpperCase()}] ${v.decisionId}`);\n lines.push(`**Message:** ${v.message}`);\n const file = (v as { location?: { file: string } }).location?.file || v.file;\n const line = (v as { location?: { line?: number } }).location?.line || v.line || 0;\n lines.push(`**Location:** \\`${file}:${line}\\`\\n`);\n });\n } else {\n lines.push('No violations found.\\n');\n }\n\n return lines.join('\\n');\n }\n}\n","/**\n * Console output format for reports\n */\nimport chalk from 'chalk';\nimport { table } from 'table';\nimport type { ComplianceReport } from '../../core/types/index.js';\n\n/**\n * Format report for console output\n */\nexport function formatConsoleReport(report: ComplianceReport): string {\n const lines: string[] = [];\n\n // Header\n lines.push('');\n lines.push(chalk.bold.blue('SpecBridge Compliance Report'));\n lines.push(chalk.dim(`Generated: ${new Date(report.timestamp).toLocaleString()}`));\n lines.push(chalk.dim(`Project: ${report.project}`));\n lines.push('');\n\n // Overall compliance\n const complianceColor = getComplianceColor(report.summary.compliance);\n lines.push(chalk.bold('Overall Compliance'));\n lines.push(\n ` ${complianceColor(formatComplianceBar(report.summary.compliance))} ${complianceColor(`${report.summary.compliance}%`)}`\n );\n lines.push('');\n\n // Summary stats\n lines.push(chalk.bold('Summary'));\n lines.push(\n ` Decisions: ${report.summary.activeDecisions} active / ${report.summary.totalDecisions} total`\n );\n lines.push(` Constraints: ${report.summary.totalConstraints}`);\n lines.push('');\n\n // Violations\n lines.push(chalk.bold('Violations'));\n const { violations } = report.summary;\n const violationParts: string[] = [];\n\n if (violations.critical > 0) {\n violationParts.push(chalk.red(`${violations.critical} critical`));\n }\n if (violations.high > 0) {\n violationParts.push(chalk.yellow(`${violations.high} high`));\n }\n if (violations.medium > 0) {\n violationParts.push(chalk.cyan(`${violations.medium} medium`));\n }\n if (violations.low > 0) {\n violationParts.push(chalk.dim(`${violations.low} low`));\n }\n\n if (violationParts.length > 0) {\n lines.push(` ${violationParts.join(' | ')}`);\n } else {\n lines.push(chalk.green(' No violations'));\n }\n lines.push('');\n\n // Per-decision breakdown\n if (report.byDecision.length > 0) {\n lines.push(chalk.bold('By Decision'));\n lines.push('');\n\n const tableData: string[][] = [\n [\n chalk.bold('Decision'),\n chalk.bold('Status'),\n chalk.bold('Constraints'),\n chalk.bold('Violations'),\n chalk.bold('Compliance'),\n ],\n ];\n\n for (const dec of report.byDecision) {\n const compColor = getComplianceColor(dec.compliance);\n const statusColor = getStatusColor(dec.status);\n\n tableData.push([\n truncate(dec.title, 40),\n statusColor(dec.status),\n String(dec.constraints),\n dec.violations > 0 ? chalk.red(String(dec.violations)) : chalk.green('0'),\n compColor(`${dec.compliance}%`),\n ]);\n }\n\n const tableOutput = table(tableData, {\n border: {\n topBody: '',\n topJoin: '',\n topLeft: '',\n topRight: '',\n bottomBody: '',\n bottomJoin: '',\n bottomLeft: '',\n bottomRight: '',\n bodyLeft: ' ',\n bodyRight: '',\n bodyJoin: ' ',\n joinBody: '',\n joinLeft: '',\n joinRight: '',\n joinJoin: '',\n },\n drawHorizontalLine: (index) => index === 1,\n });\n\n lines.push(tableOutput);\n }\n\n return lines.join('\\n');\n}\n\nfunction formatComplianceBar(compliance: number): string {\n const filled = Math.round(compliance / 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n}\n\nfunction getComplianceColor(compliance: number): (text: string) => string {\n if (compliance >= 90) return chalk.green;\n if (compliance >= 70) return chalk.yellow;\n if (compliance >= 50) return chalk.hex('#FFA500');\n return chalk.red;\n}\n\nfunction getStatusColor(status: string): (text: string) => string {\n switch (status) {\n case 'active':\n return chalk.green;\n case 'draft':\n return chalk.yellow;\n case 'deprecated':\n return chalk.gray;\n case 'superseded':\n return chalk.blue;\n default:\n return chalk.white;\n }\n}\n\nfunction truncate(str: string, length: number): string {\n if (str.length <= length) return str;\n return str.slice(0, length - 3) + '...';\n}\n","/**\n * Markdown format for reports\n */\nimport type { ComplianceReport } from '../../core/types/index.js';\n\n/**\n * Format report as Markdown\n */\nexport function formatMarkdownReport(report: ComplianceReport): string {\n const lines: string[] = [];\n\n // Header\n lines.push('# SpecBridge Compliance Report');\n lines.push('');\n lines.push(`**Project:** ${report.project}`);\n lines.push(`**Generated:** ${new Date(report.timestamp).toLocaleString()}`);\n lines.push('');\n\n // Overall compliance\n lines.push('## Overall Compliance');\n lines.push('');\n lines.push(`**Score:** ${report.summary.compliance}%`);\n lines.push('');\n lines.push(formatProgressBar(report.summary.compliance));\n lines.push('');\n\n // Summary\n lines.push('## Summary');\n lines.push('');\n lines.push(\n `- **Active Decisions:** ${report.summary.activeDecisions} / ${report.summary.totalDecisions}`\n );\n lines.push(`- **Total Constraints:** ${report.summary.totalConstraints}`);\n lines.push('');\n\n // Violations\n lines.push('### Violations');\n lines.push('');\n const { violations } = report.summary;\n const totalViolations =\n violations.critical + violations.high + violations.medium + violations.low;\n\n if (totalViolations === 0) {\n lines.push('No violations found.');\n } else {\n lines.push(`| Severity | Count |`);\n lines.push(`|----------|-------|`);\n lines.push(`| Critical | ${violations.critical} |`);\n lines.push(`| High | ${violations.high} |`);\n lines.push(`| Medium | ${violations.medium} |`);\n lines.push(`| Low | ${violations.low} |`);\n lines.push(`| **Total** | **${totalViolations}** |`);\n }\n lines.push('');\n\n // By Decision\n if (report.byDecision.length > 0) {\n lines.push('## By Decision');\n lines.push('');\n lines.push('| Decision | Status | Constraints | Violations | Compliance |');\n lines.push('|----------|--------|-------------|------------|------------|');\n\n for (const dec of report.byDecision) {\n const complianceEmoji = dec.compliance >= 90 ? '✅' : dec.compliance >= 70 ? '⚠️' : '❌';\n lines.push(\n `| ${dec.title} | ${dec.status} | ${dec.constraints} | ${dec.violations} | ${complianceEmoji} ${dec.compliance}% |`\n );\n }\n lines.push('');\n }\n\n // Footer\n lines.push('---');\n lines.push('');\n lines.push('*Generated by [SpecBridge](https://github.com/nouatzi/specbridge)*');\n\n return lines.join('\\n');\n}\n\nfunction formatProgressBar(percentage: number): string {\n const width = 20;\n const filled = Math.round((percentage / 100) * width);\n const empty = width - filled;\n const filledChar = '█';\n const emptyChar = '░';\n\n return `\\`${filledChar.repeat(filled)}${emptyChar.repeat(empty)}\\` ${percentage}%`;\n}\n","/**\n * Report storage - Save and load historical compliance reports\n */\nimport { join } from 'node:path';\nimport type { ComplianceReport } from '../core/types/index.js';\nimport {\n ensureDir,\n writeTextFile,\n readTextFile,\n readFilesInDir,\n pathExists,\n getSpecBridgeDir,\n} from '../utils/fs.js';\nimport { getLogger } from '../utils/logger.js';\n\nexport interface StoredReport {\n timestamp: string;\n report: ComplianceReport;\n}\n\n/**\n * ReportStorage - Handles persistence and retrieval of historical reports\n */\nexport class ReportStorage {\n private storageDir: string;\n private logger = getLogger({ module: 'reporting.storage' });\n\n constructor(basePath: string) {\n this.storageDir = join(getSpecBridgeDir(basePath), 'reports', 'history');\n }\n\n /**\n * Save a compliance report to storage\n */\n async save(report: ComplianceReport): Promise<string> {\n await ensureDir(this.storageDir);\n\n // Use date as filename (one report per day, overwrites if exists)\n const date = new Date(report.timestamp).toISOString().split('T')[0];\n const filename = `report-${date}.json`;\n const filepath = join(this.storageDir, filename);\n\n await writeTextFile(filepath, JSON.stringify(report, null, 2));\n\n return filepath;\n }\n\n /**\n * Load the most recent report\n */\n async loadLatest(): Promise<StoredReport | null> {\n if (!(await pathExists(this.storageDir))) {\n return null;\n }\n\n const files = await readFilesInDir(this.storageDir);\n if (files.length === 0) {\n return null;\n }\n\n // Sort files by date (descending)\n const sortedFiles = files\n .filter((f) => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n if (sortedFiles.length === 0) {\n return null;\n }\n\n const latestFile = sortedFiles[0];\n if (!latestFile) {\n return null;\n }\n\n const content = await readTextFile(join(this.storageDir, latestFile));\n const report = JSON.parse(content) as ComplianceReport;\n\n return {\n timestamp: latestFile.replace('report-', '').replace('.json', ''),\n report,\n };\n }\n\n /**\n * Load historical reports for the specified number of days\n * Uses parallel I/O for better performance\n */\n async loadHistory(days: number = 30): Promise<StoredReport[]> {\n if (!(await pathExists(this.storageDir))) {\n return [];\n }\n\n const files = await readFilesInDir(this.storageDir);\n\n // Filter report files and sort by date\n const reportFiles = files\n .filter((f) => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse(); // Most recent first\n\n // Take only the requested number of days\n const recentFiles = reportFiles.slice(0, days);\n\n // Load all reports in parallel\n const reportPromises = recentFiles.map(async (file) => {\n try {\n const content = await readTextFile(join(this.storageDir, file));\n const report = JSON.parse(content) as ComplianceReport;\n const timestamp = file.replace('report-', '').replace('.json', '');\n\n return { timestamp, report } as StoredReport;\n } catch (error) {\n // Skip corrupted files\n this.logger.warn({ file, error }, 'Failed to load report file');\n return null;\n }\n });\n\n const results = await Promise.all(reportPromises);\n\n // Filter out null results from failed loads\n return results.filter((r): r is StoredReport => r !== null);\n }\n\n /**\n * Load a specific report by date\n */\n async loadByDate(date: string): Promise<ComplianceReport | null> {\n const filepath = join(this.storageDir, `report-${date}.json`);\n\n if (!(await pathExists(filepath))) {\n return null;\n }\n\n const content = await readTextFile(filepath);\n return JSON.parse(content) as ComplianceReport;\n }\n\n /**\n * Get all available report dates\n */\n async getAvailableDates(): Promise<string[]> {\n if (!(await pathExists(this.storageDir))) {\n return [];\n }\n\n const files = await readFilesInDir(this.storageDir);\n\n return files\n .filter((f) => f.startsWith('report-') && f.endsWith('.json'))\n .map((f) => f.replace('report-', '').replace('.json', ''))\n .sort()\n .reverse();\n }\n\n /**\n * Clear old reports (keep only the most recent N days)\n */\n async cleanup(keepDays: number = 90): Promise<number> {\n if (!(await pathExists(this.storageDir))) {\n return 0;\n }\n\n const files = await readFilesInDir(this.storageDir);\n const reportFiles = files\n .filter((f) => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n // Delete files beyond the keep limit\n const filesToDelete = reportFiles.slice(keepDays);\n\n for (const file of filesToDelete) {\n try {\n const filepath = join(this.storageDir, file);\n const fs = await import('node:fs/promises');\n await fs.unlink(filepath);\n } catch (error) {\n this.logger.warn({ file, error }, 'Failed to delete old report file');\n }\n }\n\n return filesToDelete.length;\n }\n}\n","/**\n * Drift detection - Analyze compliance trends between reports\n */\nimport type { ComplianceReport, DecisionCompliance } from '../core/types/index.js';\n\nexport type TrendDirection = 'improving' | 'stable' | 'degrading';\n\nexport interface DriftAnalysis {\n decisionId: string;\n title: string;\n trend: TrendDirection;\n complianceChange: number; // percentage points\n newViolations: number;\n fixedViolations: number;\n currentCompliance: number;\n previousCompliance: number;\n}\n\nexport interface OverallDrift {\n trend: TrendDirection;\n complianceChange: number;\n summary: {\n newViolations: {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n };\n fixedViolations: {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n };\n };\n byDecision: DriftAnalysis[];\n mostImproved: DriftAnalysis[];\n mostDegraded: DriftAnalysis[];\n}\n\n/**\n * Detect drift between current and previous compliance reports\n */\nexport async function detectDrift(\n current: ComplianceReport,\n previous: ComplianceReport\n): Promise<OverallDrift> {\n const byDecision: DriftAnalysis[] = [];\n\n // Analyze per-decision drift\n for (const currDecision of current.byDecision) {\n const prevDecision = previous.byDecision.find((d) => d.decisionId === currDecision.decisionId);\n\n if (!prevDecision) {\n // New decision - treat as stable for now\n byDecision.push({\n decisionId: currDecision.decisionId,\n title: currDecision.title,\n trend: 'stable',\n complianceChange: 0,\n newViolations: currDecision.violations,\n fixedViolations: 0,\n currentCompliance: currDecision.compliance,\n previousCompliance: currDecision.compliance,\n });\n continue;\n }\n\n const complianceChange = currDecision.compliance - prevDecision.compliance;\n const violationDiff = currDecision.violations - prevDecision.violations;\n\n // Determine trend with threshold\n let trend: TrendDirection;\n if (complianceChange > 5) {\n trend = 'improving';\n } else if (complianceChange < -5) {\n trend = 'degrading';\n } else {\n trend = 'stable';\n }\n\n byDecision.push({\n decisionId: currDecision.decisionId,\n title: currDecision.title,\n trend,\n complianceChange,\n newViolations: Math.max(0, violationDiff),\n fixedViolations: Math.max(0, -violationDiff),\n currentCompliance: currDecision.compliance,\n previousCompliance: prevDecision.compliance,\n });\n }\n\n // Calculate overall drift\n const overallComplianceChange = current.summary.compliance - previous.summary.compliance;\n\n let overallTrend: TrendDirection;\n if (overallComplianceChange > 5) {\n overallTrend = 'improving';\n } else if (overallComplianceChange < -5) {\n overallTrend = 'degrading';\n } else {\n overallTrend = 'stable';\n }\n\n // Calculate violation changes by severity\n const newViolations = {\n critical: Math.max(\n 0,\n current.summary.violations.critical - previous.summary.violations.critical\n ),\n high: Math.max(0, current.summary.violations.high - previous.summary.violations.high),\n medium: Math.max(0, current.summary.violations.medium - previous.summary.violations.medium),\n low: Math.max(0, current.summary.violations.low - previous.summary.violations.low),\n total: 0,\n };\n newViolations.total =\n newViolations.critical + newViolations.high + newViolations.medium + newViolations.low;\n\n const fixedViolations = {\n critical: Math.max(\n 0,\n previous.summary.violations.critical - current.summary.violations.critical\n ),\n high: Math.max(0, previous.summary.violations.high - current.summary.violations.high),\n medium: Math.max(0, previous.summary.violations.medium - current.summary.violations.medium),\n low: Math.max(0, previous.summary.violations.low - current.summary.violations.low),\n total: 0,\n };\n fixedViolations.total =\n fixedViolations.critical + fixedViolations.high + fixedViolations.medium + fixedViolations.low;\n\n // Find most improved and most degraded\n const improving = byDecision.filter((d) => d.trend === 'improving');\n const degrading = byDecision.filter((d) => d.trend === 'degrading');\n\n const mostImproved = improving\n .sort((a, b) => b.complianceChange - a.complianceChange)\n .slice(0, 5);\n const mostDegraded = degrading\n .sort((a, b) => a.complianceChange - b.complianceChange)\n .slice(0, 5);\n\n return {\n trend: overallTrend,\n complianceChange: overallComplianceChange,\n summary: {\n newViolations,\n fixedViolations,\n },\n byDecision,\n mostImproved,\n mostDegraded,\n };\n}\n\n/**\n * Analyze compliance trend over multiple reports\n */\nexport interface TrendAnalysis {\n period: {\n start: string;\n end: string;\n days: number;\n };\n overall: {\n startCompliance: number;\n endCompliance: number;\n change: number;\n trend: TrendDirection;\n dataPoints: Array<{ date: string; compliance: number }>;\n };\n decisions: Array<{\n decisionId: string;\n title: string;\n startCompliance: number;\n endCompliance: number;\n change: number;\n trend: TrendDirection;\n dataPoints: Array<{ date: string; compliance: number }>;\n }>;\n}\n\nexport async function analyzeTrend(\n reports: Array<{ timestamp: string; report: ComplianceReport }>\n): Promise<TrendAnalysis> {\n if (reports.length === 0) {\n throw new Error('No reports provided for trend analysis');\n }\n\n // Sort by timestamp (oldest first)\n const sortedReports = reports.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n\n const firstReport = sortedReports[0]?.report;\n const lastReport = sortedReports[sortedReports.length - 1]?.report;\n\n if (!firstReport || !lastReport) {\n throw new Error('Invalid reports data');\n }\n\n // Overall trend\n const overallChange = lastReport.summary.compliance - firstReport.summary.compliance;\n let overallTrend: TrendDirection;\n if (overallChange > 5) {\n overallTrend = 'improving';\n } else if (overallChange < -5) {\n overallTrend = 'degrading';\n } else {\n overallTrend = 'stable';\n }\n\n const overallDataPoints = sortedReports.map((r) => ({\n date: r.timestamp,\n compliance: r.report.summary.compliance,\n }));\n\n // Per-decision trends\n const decisionMap = new Map<string, DecisionCompliance[]>();\n\n for (const { report } of sortedReports) {\n for (const decision of report.byDecision) {\n if (!decisionMap.has(decision.decisionId)) {\n decisionMap.set(decision.decisionId, []);\n }\n const decisionHistory = decisionMap.get(decision.decisionId);\n if (decisionHistory) {\n decisionHistory.push(decision);\n }\n }\n }\n\n const decisions = Array.from(decisionMap.entries()).map(([decisionId, data]) => {\n const first = data[0];\n const last = data[data.length - 1];\n\n if (!first || !last) {\n throw new Error(`Invalid decision data for ${decisionId}`);\n }\n\n const change = last.compliance - first.compliance;\n\n let trend: TrendDirection;\n if (change > 5) {\n trend = 'improving';\n } else if (change < -5) {\n trend = 'degrading';\n } else {\n trend = 'stable';\n }\n\n const dataPoints = sortedReports.map((r) => {\n const decision = r.report.byDecision.find((d) => d.decisionId === decisionId);\n return {\n date: r.timestamp,\n compliance: decision?.compliance ?? 0,\n };\n });\n\n return {\n decisionId,\n title: last.title,\n startCompliance: first.compliance,\n endCompliance: last.compliance,\n change,\n trend,\n dataPoints,\n };\n });\n\n const firstTimestamp = sortedReports[0]?.timestamp;\n const lastTimestamp = sortedReports[sortedReports.length - 1]?.timestamp;\n\n if (!firstTimestamp || !lastTimestamp) {\n throw new Error('Invalid report timestamps');\n }\n\n return {\n period: {\n start: firstTimestamp,\n end: lastTimestamp,\n days: sortedReports.length,\n },\n overall: {\n startCompliance: firstReport.summary.compliance,\n endCompliance: lastReport.summary.compliance,\n change: overallChange,\n trend: overallTrend,\n dataPoints: overallDataPoints,\n },\n decisions,\n };\n}\n","/**\n * Agent context generator\n */\nimport type {\n AgentContext,\n ApplicableDecision,\n ApplicableConstraint,\n SpecBridgeConfig,\n Decision,\n Constraint,\n} from '../core/types/index.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface ContextOptions {\n includeRationale?: boolean;\n format?: 'markdown' | 'json' | 'mcp';\n cwd?: string;\n}\n\n/**\n * Generate agent context for a file\n */\nexport async function generateContext(\n filePath: string,\n config: SpecBridgeConfig,\n options: ContextOptions = {}\n): Promise<AgentContext> {\n const { includeRationale = config.agent?.includeRationale ?? true, cwd = process.cwd() } =\n options;\n\n // Load registry\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n\n // Get active decisions\n const decisions = registry.getActive();\n\n // Find applicable decisions and constraints\n const applicableDecisions: ApplicableDecision[] = [];\n\n for (const decision of decisions) {\n const applicableConstraints: ApplicableConstraint[] = [];\n\n for (const constraint of decision.constraints) {\n if (matchesPattern(filePath, constraint.scope)) {\n applicableConstraints.push({\n id: constraint.id,\n type: constraint.type,\n rule: constraint.rule,\n severity: constraint.severity,\n });\n }\n }\n\n if (applicableConstraints.length > 0) {\n applicableDecisions.push({\n id: decision.metadata.id,\n title: decision.metadata.title,\n summary: includeRationale ? decision.decision.summary : '',\n constraints: applicableConstraints,\n });\n }\n }\n\n return {\n file: filePath,\n applicableDecisions,\n generatedAt: new Date().toISOString(),\n };\n}\n\n/**\n * Format context as Markdown for agent prompts\n */\nexport function formatContextAsMarkdown(context: AgentContext): string {\n const lines: string[] = [];\n\n lines.push('# Architectural Constraints');\n lines.push('');\n lines.push(`File: \\`${context.file}\\``);\n lines.push('');\n\n if (context.applicableDecisions.length === 0) {\n lines.push('No specific architectural constraints apply to this file.');\n return lines.join('\\n');\n }\n\n lines.push('The following architectural decisions apply to this file:');\n lines.push('');\n\n for (const decision of context.applicableDecisions) {\n lines.push(`## ${decision.title}`);\n lines.push('');\n\n if (decision.summary) {\n lines.push(decision.summary);\n lines.push('');\n }\n\n lines.push('### Constraints');\n lines.push('');\n\n for (const constraint of decision.constraints) {\n const typeEmoji =\n constraint.type === 'invariant' ? '🔒' : constraint.type === 'convention' ? '📋' : '💡';\n const severityBadge = `[${constraint.severity.toUpperCase()}]`;\n\n lines.push(`- ${typeEmoji} **${severityBadge}** ${constraint.rule}`);\n }\n\n lines.push('');\n }\n\n lines.push('---');\n lines.push('');\n lines.push('Please ensure your code complies with these constraints.');\n\n return lines.join('\\n');\n}\n\n/**\n * Format context as JSON\n */\nexport function formatContextAsJson(context: AgentContext): string {\n return JSON.stringify(context, null, 2);\n}\n\n/**\n * Format context for MCP (Model Context Protocol)\n */\nexport function formatContextAsMcp(context: AgentContext): object {\n return {\n type: 'architectural_context',\n version: '1.0',\n file: context.file,\n timestamp: context.generatedAt,\n decisions: context.applicableDecisions.map((d) => ({\n id: d.id,\n title: d.title,\n summary: d.summary,\n constraints: d.constraints.map((c) => ({\n id: c.id,\n type: c.type,\n severity: c.severity,\n rule: c.rule,\n })),\n })),\n };\n}\n\n/**\n * Generate context in specified format\n */\nexport async function generateFormattedContext(\n filePath: string,\n config: SpecBridgeConfig,\n options: ContextOptions = {}\n): Promise<string> {\n const context = await generateContext(filePath, config, options);\n const format = options.format || config.agent?.format || 'markdown';\n\n switch (format) {\n case 'json':\n return formatContextAsJson(context);\n case 'mcp':\n return JSON.stringify(formatContextAsMcp(context), null, 2);\n case 'markdown':\n default:\n return formatContextAsMarkdown(context);\n }\n}\n\n/**\n * AgentContextGenerator class for test compatibility\n */\nexport class AgentContextGenerator {\n /**\n * Generate context from decisions\n */\n generateContext(options: {\n decisions: Decision[];\n filePattern?: string;\n format?: 'markdown' | 'plain' | 'json';\n concise?: boolean;\n minSeverity?: string;\n includeExamples?: boolean;\n }): string {\n const { decisions, filePattern, format = 'markdown', concise = false, minSeverity } = options;\n\n // Filter deprecated decisions\n const activeDecisions = decisions.filter((d) => d.metadata.status !== 'deprecated');\n\n // Filter by file pattern if provided\n let filteredDecisions = activeDecisions;\n if (filePattern) {\n filteredDecisions = activeDecisions.filter((d) =>\n d.constraints.some((c: Constraint) => matchesPattern(filePattern, c.scope))\n );\n }\n\n // Filter by severity if provided\n if (minSeverity) {\n const severityOrder = { low: 0, medium: 1, high: 2, critical: 3 };\n const minLevel = severityOrder[minSeverity as keyof typeof severityOrder] || 0;\n\n filteredDecisions = filteredDecisions\n .map((d) => ({\n ...d,\n constraints: d.constraints.filter((c: Constraint) => {\n const level = severityOrder[c.severity as keyof typeof severityOrder] || 0;\n return level >= minLevel;\n }),\n }))\n .filter((d) => d.constraints.length > 0);\n }\n\n // Format output\n if (filteredDecisions.length === 0) {\n return 'No architectural decisions apply.';\n }\n\n if (format === 'json') {\n return JSON.stringify({ decisions: filteredDecisions }, null, 2);\n }\n\n const lines: string[] = [];\n\n if (format === 'markdown') {\n lines.push('# Architectural Decisions\\n');\n for (const decision of filteredDecisions) {\n lines.push(`## ${decision.metadata.title}`);\n if (!concise && decision.decision.summary) {\n lines.push(`\\n${decision.decision.summary}\\n`);\n }\n lines.push('### Constraints\\n');\n for (const constraint of decision.constraints) {\n lines.push(`- **[${constraint.severity.toUpperCase()}]** ${constraint.rule}`);\n }\n lines.push('');\n }\n } else {\n // Plain text format\n for (const decision of filteredDecisions) {\n lines.push(`${decision.metadata.title}`);\n if (!concise && decision.decision.summary) {\n lines.push(`${decision.decision.summary}`);\n }\n for (const constraint of decision.constraints) {\n lines.push(` - ${constraint.rule}`);\n }\n lines.push('');\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Generate prompt suffix for AI agents\n */\n generatePromptSuffix(options: { decisions: Decision[] }): string {\n const { decisions } = options;\n\n if (decisions.length === 0) {\n return 'No architectural decisions to follow.';\n }\n\n const lines: string[] = [];\n lines.push('Please follow these architectural decisions and constraints:');\n lines.push('');\n\n for (const decision of decisions) {\n lines.push(`- ${decision.metadata.title}`);\n for (const constraint of decision.constraints) {\n lines.push(` - ${constraint.rule}`);\n }\n }\n\n lines.push('');\n lines.push('Ensure your code complies with all constraints listed above.');\n\n return lines.join('\\n');\n }\n\n /**\n * Extract relevant decisions for a specific file\n */\n extractRelevantDecisions(options: { decisions: Decision[]; filePath: string }): Decision[] {\n const { decisions, filePath } = options;\n\n return decisions.filter((d) =>\n d.constraints.some((c: Constraint) => matchesPattern(filePath, c.scope))\n );\n }\n}\n","/**\n * Prompt templates for AI agents\n */\nimport type { AgentContext } from '../core/types/index.js';\nimport { formatContextAsMarkdown } from './context.generator.js';\n\nexport interface PromptTemplate {\n name: string;\n description: string;\n generate: (context: AgentContext, options?: Record<string, unknown>) => string;\n}\n\nexport const templates: Record<string, PromptTemplate> = {\n 'code-review': {\n name: 'Code Review',\n description: 'Review code for architectural compliance',\n generate: (context) => {\n return [\n 'You are reviewing code for architectural compliance.',\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Identify violations of the constraints above.',\n '- Suggest concrete changes to achieve compliance.',\n ].join('\\n');\n },\n },\n\n refactoring: {\n name: 'Refactoring Guidance',\n description: 'Guide refactoring to meet constraints',\n generate: (context) => {\n return [\n 'You are helping refactor code to meet architectural constraints.',\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Propose a step-by-step refactoring plan to satisfy all invariants first, then conventions/guidelines.',\n '- Highlight risky changes and suggest safe incremental steps.',\n ].join('\\n');\n },\n },\n\n migration: {\n name: 'Migration Plan',\n description: 'Generate a migration plan for a new/changed decision',\n generate: (context, options) => {\n const decisionId = String(options?.decisionId ?? '');\n return [\n `A new architectural decision has been introduced: ${decisionId || '<decision-id>'}`,\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Provide an impact analysis.',\n '- Produce a step-by-step migration plan.',\n '- Include a checklist for completion.',\n ].join('\\n');\n },\n },\n};\n","/**\n * SpecBridge MCP Server (Model Context Protocol)\n */\nimport { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { generateFormattedContext } from '../agent/context.generator.js';\nimport { createVerificationEngine } from '../verification/engine.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { formatConsoleReport } from '../reporting/formats/console.js';\nimport { formatMarkdownReport } from '../reporting/formats/markdown.js';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\n\nexport interface McpServerOptions {\n cwd: string;\n version: string;\n}\n\nexport class SpecBridgeMcpServer {\n private server: McpServer;\n private cwd: string;\n private config: SpecBridgeConfig | null = null;\n private registry: Registry | null = null;\n\n constructor(options: McpServerOptions) {\n this.cwd = options.cwd;\n this.server = new McpServer({ name: 'specbridge', version: options.version });\n }\n\n async initialize(): Promise<void> {\n this.config = await loadConfig(this.cwd);\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n\n this.registerResources();\n this.registerTools();\n }\n\n async startStdio(): Promise<void> {\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n }\n\n private getReady(): { config: SpecBridgeConfig; registry: Registry } {\n if (!this.config || !this.registry) {\n throw new Error('SpecBridge MCP server not initialized. Call initialize() first.');\n }\n return { config: this.config, registry: this.registry };\n }\n\n private registerResources(): void {\n const { config, registry } = this.getReady();\n\n // List all decisions\n this.server.registerResource(\n 'decisions',\n 'decision:///',\n {\n title: 'Architectural Decisions',\n description: 'List of all architectural decisions',\n mimeType: 'application/json',\n },\n async (uri: URL) => {\n const decisions = registry.getAll();\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(decisions, null, 2),\n },\n ],\n };\n }\n );\n\n // Read a specific decision\n this.server.registerResource(\n 'decision',\n new ResourceTemplate('decision://{id}', { list: undefined }),\n {\n title: 'Architectural Decision',\n description: 'A specific architectural decision by id',\n mimeType: 'application/json',\n },\n async (uri: URL, variables: Record<string, string | string[]>) => {\n const raw = variables.id;\n const decisionId = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '');\n const decision = registry.get(String(decisionId));\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(decision, null, 2),\n },\n ],\n };\n }\n );\n\n // Latest compliance report\n this.server.registerResource(\n 'latest_report',\n 'report:///latest',\n {\n title: 'Latest Compliance Report',\n description: 'Most recent compliance report (generated on demand)',\n mimeType: 'application/json',\n },\n async (uri: URL) => {\n const report = await generateReport(config, { cwd: this.cwd });\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n }\n );\n }\n\n private registerTools(): void {\n const { config } = this.getReady();\n\n this.server.registerTool(\n 'generate_context',\n {\n title: 'Generate architectural context',\n description: 'Generate architectural context for a file from applicable decisions',\n inputSchema: {\n filePath: z.string().describe('Path to the file to analyze'),\n includeRationale: z.boolean().optional().default(true),\n format: z.enum(['markdown', 'json', 'mcp']).optional().default('markdown'),\n },\n },\n async (args: {\n filePath: string;\n includeRationale?: boolean;\n format?: 'markdown' | 'json' | 'mcp';\n }) => {\n const text = await generateFormattedContext(args.filePath, config, {\n includeRationale: args.includeRationale,\n format: args.format,\n cwd: this.cwd,\n });\n\n return { content: [{ type: 'text', text }] };\n }\n );\n\n this.server.registerTool(\n 'verify_compliance',\n {\n title: 'Verify compliance',\n description: 'Verify code compliance against constraints',\n inputSchema: {\n level: z.enum(['commit', 'pr', 'full']).optional().default('full'),\n files: z.array(z.string()).optional(),\n decisions: z.array(z.string()).optional(),\n severity: z.array(z.enum(['critical', 'high', 'medium', 'low'])).optional(),\n },\n },\n async (args: {\n level?: 'commit' | 'pr' | 'full';\n files?: string[];\n decisions?: string[];\n severity?: ('critical' | 'high' | 'medium' | 'low')[];\n }) => {\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level: args.level,\n files: args.files,\n decisions: args.decisions,\n severity: args.severity,\n cwd: this.cwd,\n });\n\n return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };\n }\n );\n\n this.server.registerTool(\n 'get_report',\n {\n title: 'Get compliance report',\n description: 'Generate a compliance report for the current workspace',\n inputSchema: {\n format: z.enum(['summary', 'detailed', 'json', 'markdown']).optional().default('summary'),\n includeAll: z.boolean().optional().default(false),\n },\n },\n async (args: {\n format?: 'summary' | 'detailed' | 'json' | 'markdown';\n includeAll?: boolean;\n }) => {\n const report = await generateReport(config, { cwd: this.cwd, includeAll: args.includeAll });\n\n if (args.format === 'json') {\n return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }] };\n }\n\n if (args.format === 'markdown') {\n return { content: [{ type: 'text', text: formatMarkdownReport(report) }] };\n }\n\n if (args.format === 'detailed') {\n return { content: [{ type: 'text', text: formatConsoleReport(report) }] };\n }\n\n // summary\n const summary = {\n timestamp: report.timestamp,\n project: report.project,\n compliance: report.summary.compliance,\n violations: report.summary.violations,\n decisions: report.summary.activeDecisions,\n };\n return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] };\n }\n );\n }\n}\n","/**\n * Analytics engine - Provide insights into compliance trends and decision impact\n */\nimport type { DecisionCompliance, Severity } from '../core/types/index.js';\nimport type { StoredReport } from '../reporting/storage.js';\n\nexport interface DecisionMetrics {\n decisionId: string;\n title: string;\n totalViolations: number;\n violationsByFile: Map<string, number>;\n violationsBySeverity: Record<Severity, number>;\n mostViolatedConstraint: { id: string; count: number } | null;\n averageComplianceScore: number;\n trendDirection: 'up' | 'down' | 'stable';\n history: Array<{\n date: string;\n compliance: number;\n violations: number;\n }>;\n}\n\nexport interface Insight {\n type: 'warning' | 'info' | 'success';\n category: 'compliance' | 'trend' | 'hotspot' | 'suggestion';\n message: string;\n details?: string;\n decisionId?: string;\n}\n\nexport interface AnalyticsSummary {\n totalDecisions: number;\n averageCompliance: number;\n overallTrend: 'up' | 'down' | 'stable';\n criticalIssues: number;\n topDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n bottomDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n insights: Insight[];\n}\n\n/**\n * Analytics engine for compliance data\n */\nexport class AnalyticsEngine {\n /**\n * Analyze a specific decision across historical reports\n */\n async analyzeDecision(decisionId: string, history: StoredReport[]): Promise<DecisionMetrics> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n // Extract decision data from each report\n const decisionHistory: Array<{\n date: string;\n data: DecisionCompliance;\n }> = [];\n\n for (const { timestamp, report } of history) {\n const decision = report.byDecision.find((d) => d.decisionId === decisionId);\n if (decision) {\n decisionHistory.push({ date: timestamp, data: decision });\n }\n }\n\n if (decisionHistory.length === 0) {\n throw new Error(`Decision ${decisionId} not found in any report`);\n }\n\n // Get latest data\n const latestEntry = decisionHistory[decisionHistory.length - 1];\n if (!latestEntry) {\n throw new Error(`No data found for decision ${decisionId}`);\n }\n const latest = latestEntry.data;\n\n // Calculate averages\n const averageCompliance =\n decisionHistory.reduce((sum, h) => sum + h.data.compliance, 0) / decisionHistory.length;\n\n // Determine trend\n let trendDirection: 'up' | 'down' | 'stable' = 'stable';\n if (decisionHistory.length >= 2) {\n const firstEntry = decisionHistory[0];\n if (!firstEntry) {\n throw new Error('Invalid decision history');\n }\n const first = firstEntry.data.compliance;\n const last = latest.compliance;\n const change = last - first;\n\n if (change > 5) {\n trendDirection = 'up';\n } else if (change < -5) {\n trendDirection = 'down';\n }\n }\n\n // Build history summary\n const historyData = decisionHistory.map((h) => ({\n date: h.date,\n compliance: h.data.compliance,\n violations: h.data.violations,\n }));\n\n return {\n decisionId,\n title: latest.title,\n totalViolations: latest.violations,\n violationsByFile: new Map(), // Would need violation details to populate\n violationsBySeverity: {\n critical: 0,\n high: 0,\n medium: 0,\n low: 0,\n }, // Would need violation details to populate\n mostViolatedConstraint: null, // Would need constraint details to populate\n averageComplianceScore: averageCompliance,\n trendDirection,\n history: historyData,\n };\n }\n\n /**\n * Generate insights from historical data\n */\n async generateInsights(history: StoredReport[]): Promise<Insight[]> {\n if (history.length === 0) {\n return [];\n }\n\n const insights: Insight[] = [];\n\n // Sort by date (oldest first)\n const sorted = history.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n const latestEntry = sorted[sorted.length - 1];\n if (!latestEntry) {\n throw new Error('No reports in history');\n }\n const latest = latestEntry.report;\n\n // Insight: Overall compliance trend\n if (sorted.length >= 2) {\n const firstEntry = sorted[0];\n if (!firstEntry) {\n return insights;\n }\n const first = firstEntry.report;\n const complianceChange = latest.summary.compliance - first.summary.compliance;\n\n if (complianceChange > 10) {\n insights.push({\n type: 'success',\n category: 'trend',\n message: `Compliance has improved by ${complianceChange.toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n } else if (complianceChange < -10) {\n insights.push({\n type: 'warning',\n category: 'trend',\n message: `Compliance has dropped by ${Math.abs(complianceChange).toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n }\n }\n\n // Insight: Critical violations\n if (latest.summary.violations.critical > 0) {\n insights.push({\n type: 'warning',\n category: 'compliance',\n message: `${latest.summary.violations.critical} critical violation(s) require immediate attention`,\n details: 'Critical violations block deployments and should be resolved as soon as possible',\n });\n }\n\n // Insight: Decision-specific issues\n const problematicDecisions = latest.byDecision.filter((d) => d.compliance < 50);\n if (problematicDecisions.length > 0) {\n insights.push({\n type: 'warning',\n category: 'hotspot',\n message: `${problematicDecisions.length} decision(s) have less than 50% compliance`,\n details: problematicDecisions.map((d) => `${d.title} (${d.compliance}%)`).join(', '),\n });\n }\n\n // Insight: High compliance decisions\n const excellentDecisions = latest.byDecision.filter((d) => d.compliance === 100);\n if (excellentDecisions.length > 0) {\n insights.push({\n type: 'success',\n category: 'compliance',\n message: `${excellentDecisions.length} decision(s) have 100% compliance`,\n details: excellentDecisions.map((d) => d.title).join(', '),\n });\n }\n\n // Insight: Compare to average\n const avgCompliance = latest.summary.compliance;\n const decisionsAboveAvg = latest.byDecision.filter((d) => d.compliance > avgCompliance);\n const decisionsBelowAvg = latest.byDecision.filter((d) => d.compliance < avgCompliance);\n\n if (decisionsBelowAvg.length > decisionsAboveAvg.length) {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: `${decisionsBelowAvg.length} decisions are below average compliance`,\n details: 'Consider focusing improvement efforts on these lower-performing decisions',\n });\n }\n\n // Insight: Violation distribution\n const totalViolations =\n latest.summary.violations.critical +\n latest.summary.violations.high +\n latest.summary.violations.medium +\n latest.summary.violations.low;\n\n if (totalViolations > 0) {\n const criticalPercent = (latest.summary.violations.critical / totalViolations) * 100;\n const highPercent = (latest.summary.violations.high / totalViolations) * 100;\n\n if (criticalPercent + highPercent > 60) {\n insights.push({\n type: 'warning',\n category: 'suggestion',\n message: 'Most violations are high severity',\n details: `${criticalPercent.toFixed(0)}% critical, ${highPercent.toFixed(0)}% high. Prioritize these for the biggest impact.`,\n });\n } else {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: 'Most violations are lower severity',\n details: 'Consider addressing high-severity issues first for maximum impact',\n });\n }\n }\n\n return insights;\n }\n\n /**\n * Generate analytics summary\n */\n async generateSummary(history: StoredReport[]): Promise<AnalyticsSummary> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n const latestEntry = history[history.length - 1];\n if (!latestEntry) {\n throw new Error('Invalid history data');\n }\n const latest = latestEntry.report;\n\n // Calculate overall trend\n let overallTrend: 'up' | 'down' | 'stable' = 'stable';\n if (history.length >= 2) {\n const firstEntry = history[0];\n if (!firstEntry) {\n throw new Error('Invalid history data');\n }\n const first = firstEntry.report;\n const change = latest.summary.compliance - first.summary.compliance;\n\n if (change > 5) {\n overallTrend = 'up';\n } else if (change < -5) {\n overallTrend = 'down';\n }\n }\n\n // Find top and bottom performers\n const sortedByCompliance = [...latest.byDecision].sort((a, b) => b.compliance - a.compliance);\n\n const topDecisions = sortedByCompliance.slice(0, 5).map((d) => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n const bottomDecisions = sortedByCompliance\n .slice(-5)\n .reverse()\n .map((d) => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n // Generate insights\n const insights = await this.generateInsights(history);\n\n return {\n totalDecisions: latest.byDecision.length,\n averageCompliance: latest.summary.compliance,\n overallTrend,\n criticalIssues: latest.summary.violations.critical,\n topDecisions,\n bottomDecisions,\n insights,\n };\n }\n}\n","/**\n * Dashboard server - Compliance dashboard backend with REST API\n */\nimport express, { type Request, type Response, type Application } from 'express';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { SpecBridgeConfig, ComplianceReport } from '../core/types/index.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { ReportStorage } from '../reporting/storage.js';\nimport { AnalyticsEngine } from '../analytics/engine.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { detectDrift, analyzeTrend } from '../reporting/drift.js';\nimport { DecisionNotFoundError } from '../core/errors/index.js';\nimport { getLogger } from '../utils/logger.js';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\ninterface DashboardOptions {\n cwd: string;\n config: SpecBridgeConfig;\n}\n\n/**\n * Dashboard Server with caching\n */\nclass DashboardServer {\n private app: Application;\n private cwd: string;\n private config: SpecBridgeConfig;\n private registry: Registry;\n private reportStorage: ReportStorage;\n\n // Caching infrastructure\n private cachedReport: ComplianceReport | null = null;\n private cacheTimestamp: number = 0;\n private readonly CACHE_TTL = 60000; // 1 minute\n private refreshInterval: NodeJS.Timeout | null = null;\n private logger = getLogger({ module: 'dashboard.server' });\n\n constructor(options: DashboardOptions) {\n this.cwd = options.cwd;\n this.config = options.config;\n this.app = express();\n this.registry = createRegistry({ basePath: this.cwd });\n this.reportStorage = new ReportStorage(this.cwd);\n\n this.setupMiddleware();\n this.setupRoutes();\n }\n\n /**\n * Start the server with background cache refresh\n */\n async start(): Promise<void> {\n // Load registry once\n await this.registry.load();\n\n // Initial cache population\n await this.refreshCache();\n\n // Background refresh\n this.refreshInterval = setInterval(() => {\n void this.refreshCache().catch((error: unknown) => {\n this.logger.error({ error }, 'Background cache refresh failed');\n });\n }, this.CACHE_TTL);\n }\n\n /**\n * Stop the server and clear intervals\n */\n stop(): void {\n if (this.refreshInterval) {\n clearInterval(this.refreshInterval);\n this.refreshInterval = null;\n }\n }\n\n /**\n * Refresh the cached report\n */\n private async refreshCache(): Promise<void> {\n try {\n const report = await generateReport(this.config, { cwd: this.cwd });\n\n this.cachedReport = report;\n this.cacheTimestamp = Date.now();\n\n // Persist to disk\n await this.reportStorage.save(report);\n } catch (error) {\n this.logger.error({ error }, 'Cache refresh failed');\n\n // Fallback: Load last saved report if cache is empty\n if (!this.cachedReport) {\n try {\n const stored = await this.reportStorage.loadLatest();\n if (stored) {\n this.cachedReport = stored.report;\n }\n } catch (fallbackError) {\n this.logger.error({ error: fallbackError }, 'Failed to load fallback report');\n }\n }\n }\n }\n\n /**\n * Get the Express app instance\n */\n getApp(): Application {\n return this.app;\n }\n\n /**\n * Setup middleware\n */\n private setupMiddleware(): void {\n this.app.use(express.json());\n\n // CORS for development\n this.app.use((_req, res, next) => {\n res.header('Access-Control-Allow-Origin', '*');\n res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.header('Access-Control-Allow-Headers', 'Content-Type');\n next();\n });\n }\n\n /**\n * Setup all routes\n */\n private setupRoutes(): void {\n this.setupReportRoutes();\n this.setupDecisionRoutes();\n this.setupAnalyticsRoutes();\n this.setupHealthRoute();\n this.setupStaticFiles();\n }\n\n /**\n * Setup report-related routes\n */\n private setupReportRoutes(): void {\n // GET /api/report/latest - Serve cached report\n this.app.get('/api/report/latest', (_req: Request, res: Response) => {\n if (!this.cachedReport) {\n res.status(503).json({ error: 'Report not ready' });\n return;\n }\n\n res.json({\n ...this.cachedReport,\n cached: true,\n cacheAge: Date.now() - this.cacheTimestamp,\n });\n });\n\n // GET /api/report/history?days=30\n this.app.get('/api/report/history', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const history = await this.reportStorage.loadHistory(days);\n res.json(history);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load history',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/report/dates\n this.app.get('/api/report/dates', async (_req: Request, res: Response) => {\n try {\n const dates = await this.reportStorage.getAvailableDates();\n res.json(dates);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load dates',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/report/:date\n this.app.get('/api/report/:date', async (req: Request, res: Response) => {\n try {\n const dateParam = req.params.date;\n const date = Array.isArray(dateParam) ? dateParam[0] : dateParam;\n if (!date) {\n res.status(400).json({ error: 'Date parameter required' });\n return;\n }\n\n const report = await this.reportStorage.loadByDate(date);\n\n if (!report) {\n res.status(404).json({ error: 'Report not found' });\n return;\n }\n\n res.json(report);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load report',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup decision-related routes\n */\n private setupDecisionRoutes(): void {\n // GET /api/decisions\n this.app.get('/api/decisions', async (_req: Request, res: Response) => {\n try {\n const decisions = this.registry.getAll();\n res.json(decisions);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load decisions',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/decisions/:id\n this.app.get('/api/decisions/:id', async (req: Request, res: Response) => {\n try {\n const idParam = req.params.id;\n const id = Array.isArray(idParam) ? idParam[0] : idParam;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const decision = this.registry.get(id);\n\n if (!decision) {\n res.status(404).json({ error: 'Decision not found' });\n return;\n }\n\n res.json(decision);\n } catch (error) {\n if (error instanceof DecisionNotFoundError) {\n res.status(404).json({ error: 'Decision not found' });\n return;\n }\n\n res.status(500).json({\n error: 'Failed to load decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup analytics-related routes\n */\n private setupAnalyticsRoutes(): void {\n // GET /api/analytics/summary?days=90\n this.app.get('/api/analytics/summary', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 90;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const summary = await engine.generateSummary(history);\n res.json(summary);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to generate analytics',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/analytics/decision/:id?days=90\n this.app.get('/api/analytics/decision/:id', async (req: Request, res: Response) => {\n try {\n const idParam = req.params.id;\n const id = Array.isArray(idParam) ? idParam[0] : idParam;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const days = parseInt(req.query.days as string) || 90;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const metrics = await engine.analyzeDecision(id, history);\n res.json(metrics);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/drift?days=2\n this.app.get('/api/drift', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 2;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for drift analysis' });\n return;\n }\n\n const currentEntry = history[0];\n const previousEntry = history[1];\n\n if (!currentEntry || !previousEntry) {\n res.status(400).json({ error: 'Invalid history data' });\n return;\n }\n\n const drift = await detectDrift(currentEntry.report, previousEntry.report);\n res.json(drift);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze drift',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/trend?days=30\n this.app.get('/api/trend', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for trend analysis' });\n return;\n }\n\n const trend = await analyzeTrend(history);\n res.json(trend);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze trend',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup health check route\n */\n private setupHealthRoute(): void {\n this.app.get('/api/health', (_req: Request, res: Response) => {\n res.json({\n status: 'ok',\n timestamp: new Date().toISOString(),\n project: this.config.project.name,\n cache: {\n loaded: this.cachedReport !== null,\n age: Date.now() - this.cacheTimestamp,\n nextRefresh: this.CACHE_TTL - (Date.now() - this.cacheTimestamp),\n },\n });\n });\n }\n\n /**\n * Setup static file serving\n */\n private setupStaticFiles(): void {\n // Serve static frontend files\n const publicDir = join(__dirname, 'public');\n this.app.use(\n express.static(publicDir, {\n maxAge: '1h', // Cache static assets\n etag: true,\n })\n );\n\n // Fallback to index.html for SPA routing\n this.app.get('/{*path}', (_req: Request, res: Response) => {\n res.sendFile(join(publicDir, 'index.html'));\n });\n }\n}\n\n/**\n * Create and configure the dashboard server (factory function)\n * @returns DashboardServer instance\n */\nexport function createDashboardServer(options: DashboardOptions): DashboardServer {\n return new DashboardServer(options);\n}\n\n// Export the class for advanced usage\nexport { DashboardServer };\n","/**\n * SpecBridge Language Server (LSP)\n */\nimport {\n createConnection,\n ProposedFeatures,\n TextDocuments,\n TextDocumentSyncKind,\n DiagnosticSeverity,\n CodeActionKind,\n} from 'vscode-languageserver/node.js';\nimport { TextDocument } from 'vscode-languageserver-textdocument';\nimport { fileURLToPath } from 'node:url';\nimport path from 'node:path';\nimport { Project } from 'ts-morph';\nimport chalk from 'chalk';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { getSpecBridgeDir, pathExists } from '../utils/fs.js';\nimport {\n selectVerifierForConstraint,\n type VerificationContext,\n} from '../verification/verifiers/index.js';\nimport { shouldApplyConstraintToFile } from '../verification/applicability.js';\nimport { getPluginLoader } from '../verification/plugins/loader.js';\nimport type { Decision, Violation, Severity } from '../core/types/index.js';\nimport { NotInitializedError } from '../core/errors/index.js';\n\nexport interface LspServerOptions {\n cwd: string;\n verbose?: boolean;\n}\n\nfunction severityToDiagnostic(severity: Severity): DiagnosticSeverity {\n switch (severity) {\n case 'critical':\n return DiagnosticSeverity.Error;\n case 'high':\n return DiagnosticSeverity.Warning;\n case 'medium':\n return DiagnosticSeverity.Information;\n case 'low':\n return DiagnosticSeverity.Hint;\n default:\n return DiagnosticSeverity.Information;\n }\n}\n\nfunction uriToFilePath(uri: string): string {\n if (uri.startsWith('file://')) return fileURLToPath(uri);\n // Fallback: treat as plain path\n return uri;\n}\n\nfunction violationToRange(doc: TextDocument, v: Violation) {\n // Prefer autofix ranges when available, otherwise line/column best-effort.\n const edit = v.autofix?.edits?.[0];\n if (edit) {\n return {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n };\n }\n\n const line = Math.max(0, (v.line ?? 1) - 1);\n const char = Math.max(0, (v.column ?? 1) - 1);\n return {\n start: { line, character: char },\n end: { line, character: char + 1 },\n };\n}\n\nexport class SpecBridgeLspServer {\n private connection = createConnection(ProposedFeatures.all);\n private documents = new TextDocuments(TextDocument);\n\n private options: LspServerOptions;\n private registry: Registry | null = null;\n private decisions: Decision[] = [];\n private cwd: string;\n private project: Project;\n private cache = new Map<string, Violation[]>();\n private initError: string | null = null;\n\n constructor(options: LspServerOptions) {\n this.options = options;\n this.cwd = options.cwd;\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n async initialize(): Promise<void> {\n this.connection.onInitialize(async () => {\n await this.initializeWorkspace();\n\n return {\n capabilities: {\n textDocumentSync: TextDocumentSyncKind.Incremental,\n codeActionProvider: true,\n },\n };\n });\n\n this.documents.onDidOpen((e) => {\n void this.validateDocument(e.document);\n });\n\n this.documents.onDidChangeContent((change) => {\n void this.validateDocument(change.document);\n });\n\n this.documents.onDidClose((e) => {\n this.cache.delete(e.document.uri);\n this.connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });\n });\n\n this.connection.onCodeAction((params) => {\n const violations = this.cache.get(params.textDocument.uri) || [];\n const doc = this.documents.get(params.textDocument.uri);\n if (!doc) return [];\n\n return violations\n .filter((v) => v.autofix && v.autofix.edits.length > 0)\n .map((v) => {\n const autofix = v.autofix;\n if (!autofix) {\n return null;\n }\n\n const edits = autofix.edits.map((edit) => ({\n range: {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n },\n newText: edit.text,\n }));\n\n return {\n title: autofix.description,\n kind: CodeActionKind.QuickFix,\n edit: {\n changes: {\n [params.textDocument.uri]: edits,\n },\n },\n };\n })\n .filter((action): action is NonNullable<typeof action> => action !== null);\n });\n\n this.documents.listen(this.connection);\n this.connection.listen();\n }\n\n private async initializeWorkspace(): Promise<void> {\n // Ensure initialized (but keep server alive if not).\n if (!(await pathExists(getSpecBridgeDir(this.cwd)))) {\n const err = new NotInitializedError();\n this.initError = err.message;\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n return;\n }\n\n try {\n const config = await loadConfig(this.cwd);\n\n // Load custom verifier plugins (best-effort). This must not write to stdout.\n try {\n await getPluginLoader().loadPlugins(this.cwd);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (this.options.verbose)\n this.connection.console.error(chalk.red(`Plugin load failed: ${msg}`));\n }\n\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n this.decisions = this.registry.getActive();\n\n // Prime project with source roots (best-effort). This enables verifiers that depend on import graph.\n for (const root of config.project.sourceRoots) {\n // ts-morph doesn't support globs directly; add root folders when possible.\n const rootPath = path.isAbsolute(root) ? root : path.join(this.cwd, root);\n // If root is a glob, fall back to adding the directory portion.\n const dir = rootPath.includes('*') ? rootPath.split('*')[0] : rootPath;\n if (dir && (await pathExists(dir))) {\n this.project.addSourceFilesAtPaths(path.join(dir, '**/*.{ts,tsx,js,jsx}'));\n }\n }\n\n if (this.options.verbose) {\n this.connection.console.log(\n chalk.dim(`Loaded ${this.decisions.length} active decision(s)`)\n );\n }\n } catch (error) {\n this.initError = error instanceof Error ? error.message : String(error);\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n }\n }\n\n private async verifyTextDocument(doc: TextDocument): Promise<Violation[]> {\n if (this.initError) {\n throw new Error(this.initError);\n }\n if (!this.registry) return [];\n\n const filePath = uriToFilePath(doc.uri);\n const sourceFile = this.project.createSourceFile(filePath, doc.getText(), { overwrite: true });\n\n const violations: Violation[] = [];\n\n for (const decision of this.decisions) {\n for (const constraint of decision.constraints) {\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd: this.cwd })) continue;\n\n const verifier = selectVerifierForConstraint(\n constraint.rule,\n constraint.verifier,\n constraint.check\n );\n if (!verifier) continue;\n\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n };\n\n try {\n const constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n } catch {\n // Ignore verifier errors (LSP should stay responsive)\n }\n }\n }\n\n return violations;\n }\n\n private async validateDocument(doc: TextDocument): Promise<void> {\n try {\n const violations = await this.verifyTextDocument(doc);\n this.cache.set(doc.uri, violations);\n\n const diagnostics = violations.map((v) => ({\n range: violationToRange(doc, v),\n severity: severityToDiagnostic(v.severity),\n message: v.message,\n source: 'specbridge',\n }));\n\n this.connection.sendDiagnostics({ uri: doc.uri, diagnostics });\n } catch (error) {\n // If workspace isn't initialized, surface a single diagnostic.\n const msg = error instanceof Error ? error.message : String(error);\n this.connection.sendDiagnostics({\n uri: doc.uri,\n diagnostics: [\n {\n range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },\n severity: DiagnosticSeverity.Error,\n message: msg,\n source: 'specbridge',\n },\n ],\n });\n }\n }\n}\n","import { SpecBridgeLspServer, type LspServerOptions } from './server.js';\n\nexport async function startLspServer(options: LspServerOptions): Promise<void> {\n const server = new SpecBridgeLspServer(options);\n await server.initialize();\n}\n","/**\n * GitHub integration helpers (optional)\n */\nimport type { Violation } from '../core/types/index.js';\n\nexport interface GitHubPrCommentOptions {\n repo: string; // owner/repo\n pr: number;\n token: string;\n}\n\nfunction toMdTable(rows: string[][]): string {\n const header = rows[0];\n if (!header) {\n return '';\n }\n const body = rows.slice(1);\n const sep = header.map(() => '---');\n const lines = [\n `| ${header.join(' | ')} |`,\n `| ${sep.join(' | ')} |`,\n ...body.map((r) => `| ${r.join(' | ')} |`),\n ];\n return lines.join('\\n');\n}\n\nexport function formatViolationsForGitHub(violations: Violation[], limit: number = 50): string {\n if (violations.length === 0) {\n return '## SpecBridge\\n\\n✅ No violations found.';\n }\n\n const rows: string[][] = [['Severity', 'Type', 'File', 'Decision/Constraint', 'Message']];\n\n for (const v of violations.slice(0, limit)) {\n const loc = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n rows.push([\n v.severity,\n v.type,\n `${v.file}${loc}`,\n `${v.decisionId}/${v.constraintId}`,\n // Escape all markdown special characters to prevent table breaking\n v.message\n .replace(/\\\\/g, '\\\\\\\\') // Backslash first\n .replace(/\\|/g, '\\\\|') // Pipe\n .replace(/\\[/g, '\\\\[') // Brackets\n .replace(/\\]/g, '\\\\]')\n .replace(/\\*/g, '\\\\*') // Asterisk\n .replace(/_/g, '\\\\_') // Underscore\n .replace(/`/g, '\\\\`'), // Backtick\n ]);\n }\n\n const extra = violations.length > limit ? `\\n\\n…and ${violations.length - limit} more.` : '';\n return `## SpecBridge\\n\\n${toMdTable(rows)}${extra}`;\n}\n\nexport async function postPrComment(\n violations: Violation[],\n options: GitHubPrCommentOptions\n): Promise<void> {\n const body = formatViolationsForGitHub(violations);\n\n const res = await fetch(\n `https://api.github.com/repos/${options.repo}/issues/${options.pr}/comments`,\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${options.token}`,\n Accept: 'application/vnd.github+json',\n 'Content-Type': 'application/json',\n 'User-Agent': 'specbridge',\n },\n body: JSON.stringify({ body }),\n }\n );\n\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(\n `GitHub comment failed: ${res.status} ${res.statusText}${text ? ` - ${text}` : ''}`\n );\n }\n}\n"],"mappings":";AAGA,SAAS,SAAS;AAGX,IAAM,uBAAuB,EAAE,KAAK,CAAC,SAAS,UAAU,cAAc,YAAY,CAAC;AAGnF,IAAM,uBAAuB,EAAE,KAAK,CAAC,aAAa,cAAc,WAAW,CAAC;AAG5E,IAAM,iBAAiB,EAAE,KAAK,CAAC,YAAY,QAAQ,UAAU,KAAK,CAAC;AAGnE,IAAM,8BAA8B,EAAE,KAAK,CAA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AS,IAAI,EAAE,MAAM,KAAK,EAAE,KAAK;AACrE,SAAK,KAAK;AAAA,MACR,EAAE;AAAA,MACF,EAAE;AAAA,MACF,GAAG,EAAE,IAAI,GAAG,GAAG;AAAA,MACf,GAAG,EAAE,UAAU,IAAI,EAAE,YAAY;AAAA;AAAA,MAEjC,EAAE,QACC,QAAQ,OAAO,MAAM,EACrB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK,EACpB,QAAQ,MAAM,KAAK,EACnB,QAAQ,MAAM,KAAK;AAAA;AAAA,IACxB,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ,WAAW,SAAS,QAAQ;AAAA;AAAA,YAAY,WAAW,SAAS,KAAK,WAAW;AAC1F,SAAO;AAAA;AAAA,EAAoB,UAAU,IAAI,CAAC,GAAG,KAAK;AACpD;AAEA,eAAsB,cACpB,YACA,SACe;AACf,QAAM,OAAO,0BAA0B,UAAU;AAEjD,QAAM,MAAM,MAAM;AAAA,IAChB,gCAAgC,QAAQ,IAAI,WAAW,QAAQ,EAAE;AAAA,IACjE;AAAA,MACE,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,eAAe,UAAU,QAAQ,KAAK;AAAA,QACtC,QAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,cAAc;AAAA,MAChB;AAAA,MACA,MAAM,KAAK,UAAU,EAAE,KAAK,CAAC;AAAA,IAC/B;AAAA,EACF;AAEA,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AAC5C,UAAM,IAAI;AAAA,MACR,0BAA0B,IAAI,MAAM,IAAI,IAAI,UAAU,GAAG,OAAO,MAAM,IAAI,KAAK,EAAE;AAAA,IACnF;AAAA,EACF;AACF;","names":["path","z","SeveritySchema","VerificationConfigSchema","path","path","path","join","join","path","dirname","dirname","Node","path","Node","Project","Node","Node","path","relative","path","Node","SyntaxKind","SyntaxKind","Node","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","join","fg","join","fg","pluginLoader","stat","readFile","createHash","readFile","Project","resolve","readFile","createHash","pluginLoader","stdout","readFile","writeFile","buildDependencyGraph","buildDependencyGraph","path","violationsBySeverity","join","join","z","z","join","dirname","dirname","join","fileURLToPath","path","Project","chalk","fileURLToPath","Project","chalk","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/schemas/decision.schema.ts","../src/core/schemas/config.schema.ts","../src/core/errors/index.ts","../src/utils/fs.ts","../src/utils/yaml.ts","../src/config/loader.ts","../src/registry/loader.ts","../src/utils/glob.ts","../src/registry/registry.ts","../src/inference/scanner.ts","../src/inference/analyzers/base.ts","../src/inference/analyzers/naming.ts","../src/inference/analyzers/imports.ts","../src/inference/analyzers/structure.ts","../src/inference/analyzers/errors.ts","../src/inference/analyzers/index.ts","../src/inference/engine.ts","../src/verification/engine.ts","../src/verification/verifiers/base.ts","../src/verification/verifiers/naming.ts","../src/verification/verifiers/imports.ts","../src/verification/verifiers/errors.ts","../src/verification/verifiers/regex.ts","../src/verification/verifiers/dependencies.ts","../src/verification/verifiers/complexity.ts","../src/verification/verifiers/security.ts","../src/verification/verifiers/api.ts","../src/verification/plugins/loader.ts","../src/utils/logger.ts","../src/verification/verifiers/index.ts","../src/verification/cache.ts","../src/verification/results-cache.ts","../src/verification/applicability.ts","../src/verification/incremental.ts","../src/verification/explain.ts","../src/verification/autofix/engine.ts","../src/propagation/graph.ts","../src/propagation/engine.ts","../src/reporting/reporter.ts","../src/reporting/formats/console.ts","../src/reporting/formats/markdown.ts","../src/reporting/storage.ts","../src/reporting/drift.ts","../src/agent/context.generator.ts","../src/agent/templates.ts","../src/mcp/server.ts","../src/analytics/engine.ts","../src/dashboard/server.ts","../src/lsp/server.ts","../src/lsp/index.ts","../src/integrations/github.ts"],"sourcesContent":["/**\n * Zod schemas for decision YAML validation\n */\nimport { z } from 'zod';\n\n// Status lifecycle\nexport const DecisionStatusSchema = z.enum(['draft', 'active', 'deprecated', 'superseded']);\n\n// Constraint types\nexport const ConstraintTypeSchema = z.enum(['invariant', 'convention', 'guideline']);\n\n// Severity levels\nexport const SeveritySchema = z.enum(['critical', 'high', 'medium', 'low']);\n\n// Verification frequency\nexport const VerificationFrequencySchema = z.enum(['commit', 'pr', 'daily', 'weekly']);\n\n// Decision metadata\nexport const DecisionMetadataSchema = z.object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9-]+$/, 'ID must be lowercase alphanumeric with hyphens'),\n title: z.string().min(1).max(200),\n status: DecisionStatusSchema,\n owners: z.array(z.string().min(1)).min(1),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n supersededBy: z.string().optional(),\n tags: z.array(z.string()).optional(),\n});\n\n// Decision content\nexport const DecisionContentSchema = z.object({\n summary: z.string().min(1).max(500),\n rationale: z.string().min(1),\n context: z.string().optional(),\n consequences: z.array(z.string()).optional(),\n});\n\n// Constraint exception\nexport const ConstraintExceptionSchema = z.object({\n pattern: z.string().min(1),\n reason: z.string().min(1),\n approvedBy: z.string().optional(),\n expiresAt: z.string().datetime().optional(),\n});\n\n// Constraint check (structured verifier specification)\nexport const ConstraintCheckSchema = z.object({\n verifier: z.string().min(1),\n params: z.record(z.string(), z.unknown()).optional(),\n});\n\n// Single constraint\nexport const ConstraintSchema = z.object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9-]+$/, 'Constraint ID must be lowercase alphanumeric with hyphens'),\n type: ConstraintTypeSchema,\n rule: z.string().min(1),\n severity: SeveritySchema,\n scope: z.string().min(1),\n verifier: z.string().optional(),\n check: ConstraintCheckSchema.optional(),\n autofix: z.boolean().optional(),\n exceptions: z.array(ConstraintExceptionSchema).optional(),\n});\n\n// Verification config\nexport const VerificationConfigSchema = z.object({\n check: z.string().min(1),\n target: z.string().min(1),\n frequency: VerificationFrequencySchema,\n timeout: z.number().positive().optional(),\n});\n\n// Links\nexport const LinksSchema = z.object({\n related: z.array(z.string()).optional(),\n supersedes: z.array(z.string()).optional(),\n references: z.array(z.string().url()).optional(),\n});\n\n// Complete decision document\nexport const DecisionSchema = z.object({\n kind: z.literal('Decision'),\n metadata: DecisionMetadataSchema,\n decision: DecisionContentSchema,\n constraints: z.array(ConstraintSchema).min(1),\n verification: z\n .object({\n automated: z.array(VerificationConfigSchema).optional(),\n })\n .optional(),\n links: LinksSchema.optional(),\n});\n\n// Type exports (suffixed with Schema to avoid conflicts with core types)\nexport type DecisionStatusSchema_ = z.infer<typeof DecisionStatusSchema>;\nexport type ConstraintTypeSchema_ = z.infer<typeof ConstraintTypeSchema>;\nexport type SeveritySchema_ = z.infer<typeof SeveritySchema>;\nexport type VerificationFrequencySchema_ = z.infer<typeof VerificationFrequencySchema>;\nexport type DecisionMetadataSchema_ = z.infer<typeof DecisionMetadataSchema>;\nexport type DecisionContentSchema_ = z.infer<typeof DecisionContentSchema>;\nexport type ConstraintExceptionSchema_ = z.infer<typeof ConstraintExceptionSchema>;\nexport type ConstraintCheckSchema_ = z.infer<typeof ConstraintCheckSchema>;\nexport type ConstraintSchema_ = z.infer<typeof ConstraintSchema>;\nexport type VerificationConfigSchema_ = z.infer<typeof VerificationConfigSchema>;\nexport type DecisionTypeSchema = z.infer<typeof DecisionSchema>;\n\n/**\n * Validate a decision document\n */\nexport function validateDecision(\n data: unknown\n): { success: true; data: DecisionTypeSchema } | { success: false; errors: z.ZodError } {\n const result = DecisionSchema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, errors: result.error };\n}\n\n/**\n * Format Zod errors into human-readable messages\n */\nexport function formatValidationErrors(errors: z.ZodError): string[] {\n return errors.issues.map((err) => {\n const path = err.path.join('.');\n return `${path}: ${err.message}`;\n });\n}\n","/**\n * Zod schemas for SpecBridge configuration\n */\nimport { z } from 'zod';\n\n// Severity for level config\nconst SeveritySchema = z.enum(['critical', 'high', 'medium', 'low']);\n\n// Level configuration\nconst LevelConfigSchema = z.object({\n timeout: z.number().positive().optional(),\n severity: z.array(SeveritySchema).optional(),\n});\n\n// Project configuration\nconst ProjectConfigSchema = z.object({\n name: z.string().min(1),\n sourceRoots: z.array(z.string().min(1)).min(1),\n exclude: z.array(z.string()).optional(),\n});\n\n// Inference configuration\nconst InferenceConfigSchema = z.object({\n minConfidence: z.number().min(0).max(100).optional(),\n analyzers: z.array(z.string()).optional(),\n});\n\n// Verification configuration\nconst VerificationConfigSchema = z.object({\n levels: z\n .object({\n commit: LevelConfigSchema.optional(),\n pr: LevelConfigSchema.optional(),\n full: LevelConfigSchema.optional(),\n })\n .optional(),\n});\n\n// Agent configuration\nconst AgentConfigSchema = z.object({\n format: z.enum(['markdown', 'json', 'mcp']).optional(),\n includeRationale: z.boolean().optional(),\n});\n\n// Complete SpecBridge configuration\nexport const SpecBridgeConfigSchema = z.object({\n version: z.string().regex(/^\\d+\\.\\d+$/, 'Version must be in format X.Y'),\n project: ProjectConfigSchema,\n inference: InferenceConfigSchema.optional(),\n verification: VerificationConfigSchema.optional(),\n agent: AgentConfigSchema.optional(),\n});\n\nexport type SpecBridgeConfigType = z.infer<typeof SpecBridgeConfigSchema>;\n\n/**\n * Validate configuration\n */\nexport function validateConfig(\n data: unknown\n): { success: true; data: SpecBridgeConfigType } | { success: false; errors: z.ZodError } {\n const result = SpecBridgeConfigSchema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, errors: result.error };\n}\n\n/**\n * Default configuration\n */\nexport const defaultConfig: SpecBridgeConfigType = {\n version: '1.0',\n project: {\n name: 'my-project',\n sourceRoots: ['src/**/*.ts', 'src/**/*.tsx'],\n exclude: ['**/*.test.ts', '**/*.spec.ts', '**/node_modules/**', '**/dist/**'],\n },\n inference: {\n minConfidence: 70,\n analyzers: ['naming', 'structure', 'imports', 'errors'],\n },\n verification: {\n levels: {\n commit: {\n timeout: 5000,\n severity: ['critical'],\n },\n pr: {\n timeout: 60000,\n severity: ['critical', 'high'],\n },\n full: {\n timeout: 300000,\n severity: ['critical', 'high', 'medium', 'low'],\n },\n },\n },\n agent: {\n format: 'markdown',\n includeRationale: true,\n },\n};\n","/**\n * Custom error types for SpecBridge\n */\n\n/**\n * Base error for SpecBridge\n */\nexport class SpecBridgeError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n public readonly suggestion?: string\n ) {\n super(message);\n this.name = 'SpecBridgeError';\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Configuration errors\n */\nexport class ConfigError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'CONFIG_ERROR', details);\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Decision validation errors\n */\nexport class DecisionValidationError extends SpecBridgeError {\n constructor(\n message: string,\n public readonly decisionId: string,\n public readonly validationErrors: string[]\n ) {\n super(message, 'DECISION_VALIDATION_ERROR', { decisionId, validationErrors });\n this.name = 'DecisionValidationError';\n }\n}\n\n/**\n * Decision not found\n */\nexport class DecisionNotFoundError extends SpecBridgeError {\n constructor(decisionId: string) {\n super(`Decision not found: ${decisionId}`, 'DECISION_NOT_FOUND', { decisionId });\n this.name = 'DecisionNotFoundError';\n }\n}\n\n/**\n * Registry errors\n */\nexport class RegistryError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'REGISTRY_ERROR', details);\n this.name = 'RegistryError';\n }\n}\n\n/**\n * Verification errors\n */\nexport class VerificationError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'VERIFICATION_ERROR', details);\n this.name = 'VerificationError';\n }\n}\n\n/**\n * Inference errors\n */\nexport class InferenceError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'INFERENCE_ERROR', details);\n this.name = 'InferenceError';\n }\n}\n\n/**\n * File system errors\n */\nexport class FileSystemError extends SpecBridgeError {\n constructor(\n message: string,\n public readonly path: string\n ) {\n super(message, 'FILE_SYSTEM_ERROR', { path });\n this.name = 'FileSystemError';\n }\n}\n\n/**\n * Already initialized error\n */\nexport class AlreadyInitializedError extends SpecBridgeError {\n constructor(path: string) {\n super(`SpecBridge is already initialized at ${path}`, 'ALREADY_INITIALIZED', { path });\n this.name = 'AlreadyInitializedError';\n }\n}\n\n/**\n * Not initialized error\n */\nexport class NotInitializedError extends SpecBridgeError {\n constructor() {\n super(\n 'SpecBridge is not initialized. Run \"specbridge init\" first.',\n 'NOT_INITIALIZED',\n undefined,\n 'Run `specbridge init` in this directory to create .specbridge/'\n );\n this.name = 'NotInitializedError';\n }\n}\n\n/**\n * Verifier not found\n */\nexport class VerifierNotFoundError extends SpecBridgeError {\n constructor(verifierId: string) {\n super(`Verifier not found: ${verifierId}`, 'VERIFIER_NOT_FOUND', { verifierId });\n this.name = 'VerifierNotFoundError';\n }\n}\n\n/**\n * Analyzer not found\n */\nexport class AnalyzerNotFoundError extends SpecBridgeError {\n constructor(analyzerId: string) {\n super(`Analyzer not found: ${analyzerId}`, 'ANALYZER_NOT_FOUND', { analyzerId });\n this.name = 'AnalyzerNotFoundError';\n }\n}\n\n/**\n * Hook installation error\n */\nexport class HookError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'HOOK_ERROR', details);\n this.name = 'HookError';\n }\n}\n\n/**\n * Format error message for CLI output\n */\nexport function formatError(error: Error): string {\n if (error instanceof SpecBridgeError) {\n let message = `Error [${error.code}]: ${error.message}`;\n if (error.details) {\n const detailsStr = Object.entries(error.details)\n .filter(([key]) => key !== 'validationErrors')\n .map(([key, value]) => ` ${key}: ${value}`)\n .join('\\n');\n if (detailsStr) {\n message += `\\n${detailsStr}`;\n }\n }\n if (error instanceof DecisionValidationError && error.validationErrors.length > 0) {\n message +=\n '\\nValidation errors:\\n' + error.validationErrors.map((e) => ` - ${e}`).join('\\n');\n }\n if (error.suggestion) {\n message += `\\nSuggestion: ${error.suggestion}`;\n }\n return message;\n }\n return `Error: ${error.message}`;\n}\n","/**\n * File system utilities\n */\nimport { readFile, writeFile, mkdir, access, readdir, stat } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { constants } from 'node:fs';\n\n/**\n * Check if a path exists\n */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a path is a directory\n */\nexport async function isDirectory(path: string): Promise<boolean> {\n try {\n const stats = await stat(path);\n return stats.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a directory exists\n */\nexport async function ensureDir(path: string): Promise<void> {\n await mkdir(path, { recursive: true });\n}\n\n/**\n * Read a text file\n */\nexport async function readTextFile(path: string): Promise<string> {\n return readFile(path, 'utf-8');\n}\n\n/**\n * Write a text file, creating directories as needed\n */\nexport async function writeTextFile(path: string, content: string): Promise<void> {\n await ensureDir(dirname(path));\n await writeFile(path, content, 'utf-8');\n}\n\n/**\n * Read all files in a directory matching a pattern\n */\nexport async function readFilesInDir(\n dirPath: string,\n filter?: (filename: string) => boolean\n): Promise<string[]> {\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n const files = entries.filter((entry) => entry.isFile()).map((entry) => entry.name);\n\n if (filter) {\n return files.filter(filter);\n }\n return files;\n } catch {\n return [];\n }\n}\n\n/**\n * Get the .specbridge directory path\n */\nexport function getSpecBridgeDir(basePath: string = process.cwd()): string {\n return join(basePath, '.specbridge');\n}\n\n/**\n * Get the decisions directory path\n */\nexport function getDecisionsDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'decisions');\n}\n\n/**\n * Get the verifiers directory path\n */\nexport function getVerifiersDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'verifiers');\n}\n\n/**\n * Get the inferred patterns directory path\n */\nexport function getInferredDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'inferred');\n}\n\n/**\n * Get the reports directory path\n */\nexport function getReportsDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'reports');\n}\n\n/**\n * Get the config file path\n */\nexport function getConfigPath(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'config.yaml');\n}\n","/**\n * YAML utilities with comment preservation\n */\nimport { parse, stringify, Document, parseDocument } from 'yaml';\n\n/**\n * Parse YAML string to object\n */\nexport function parseYaml<T = unknown>(content: string): T {\n return parse(content) as T;\n}\n\n/**\n * Stringify object to YAML with nice formatting\n */\nexport function stringifyYaml(data: unknown, options?: { indent?: number }): string {\n return stringify(data, {\n indent: options?.indent ?? 2,\n lineWidth: 100,\n minContentWidth: 20,\n });\n}\n\n/**\n * Parse YAML preserving document structure (for editing)\n */\nexport function parseYamlDocument(content: string): Document {\n return parseDocument(content);\n}\n\n/**\n * Update YAML document preserving comments\n */\nexport function updateYamlDocument(doc: Document, path: string[], value: unknown): void {\n let current: unknown = doc.contents;\n\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n if (key && current && typeof current === 'object' && 'get' in current) {\n current = (current as { get: (key: string) => unknown }).get(key);\n }\n }\n\n const lastKey = path[path.length - 1];\n if (lastKey && current && typeof current === 'object' && 'set' in current) {\n (current as { set: (key: string, value: unknown) => void }).set(lastKey, value);\n }\n}\n","/**\n * Configuration loader\n */\nimport type { SpecBridgeConfig } from '../core/types/index.js';\nimport { validateConfig, defaultConfig } from '../core/schemas/config.schema.js';\nimport { ConfigError, NotInitializedError } from '../core/errors/index.js';\nimport { readTextFile, pathExists, getConfigPath, getSpecBridgeDir } from '../utils/fs.js';\nimport { parseYaml } from '../utils/yaml.js';\n\n/**\n * Load configuration from .specbridge/config.yaml\n */\nexport async function loadConfig(basePath: string = process.cwd()): Promise<SpecBridgeConfig> {\n const specbridgeDir = getSpecBridgeDir(basePath);\n const configPath = getConfigPath(basePath);\n\n // Check if specbridge is initialized\n if (!(await pathExists(specbridgeDir))) {\n throw new NotInitializedError();\n }\n\n // Check if config file exists\n if (!(await pathExists(configPath))) {\n // Return default config if no config file\n return defaultConfig;\n }\n\n // Load and parse config\n const content = await readTextFile(configPath);\n const parsed = parseYaml(content);\n\n // Validate config\n const result = validateConfig(parsed);\n if (!result.success) {\n const errors = result.errors.issues.map((e) => `${e.path.join('.')}: ${e.message}`);\n throw new ConfigError(`Invalid configuration in ${configPath}`, { errors });\n }\n\n return result.data as SpecBridgeConfig;\n}\n\n/**\n * Merge partial config with defaults\n */\nexport function mergeWithDefaults(partial: Partial<SpecBridgeConfig>): SpecBridgeConfig {\n return {\n ...defaultConfig,\n ...partial,\n project: {\n ...defaultConfig.project,\n ...partial.project,\n },\n inference: {\n ...defaultConfig.inference,\n ...partial.inference,\n },\n verification: {\n ...defaultConfig.verification,\n ...partial.verification,\n levels: {\n ...defaultConfig.verification?.levels,\n ...partial.verification?.levels,\n },\n },\n agent: {\n ...defaultConfig.agent,\n ...partial.agent,\n },\n };\n}\n","/**\n * Decision file loader\n */\nimport { join } from 'node:path';\nimport type { Decision } from '../core/types/index.js';\nimport { validateDecision, formatValidationErrors } from '../core/schemas/decision.schema.js';\nimport { DecisionValidationError, FileSystemError } from '../core/errors/index.js';\nimport { readTextFile, readFilesInDir, pathExists } from '../utils/fs.js';\nimport { parseYaml } from '../utils/yaml.js';\n\nexport interface LoadedDecision {\n decision: Decision;\n filePath: string;\n}\n\nexport interface LoadResult {\n decisions: LoadedDecision[];\n errors: LoadError[];\n}\n\nexport interface LoadError {\n filePath: string;\n error: string;\n}\n\n/**\n * Load a single decision file\n */\nexport async function loadDecisionFile(filePath: string): Promise<Decision> {\n if (!(await pathExists(filePath))) {\n throw new FileSystemError(`Decision file not found: ${filePath}`, filePath);\n }\n\n const content = await readTextFile(filePath);\n const parsed = parseYaml(content);\n\n const result = validateDecision(parsed);\n if (!result.success) {\n const errors = formatValidationErrors(result.errors);\n throw new DecisionValidationError(\n `Invalid decision file: ${filePath}`,\n typeof parsed === 'object' && parsed !== null && 'metadata' in parsed\n ? (parsed as { metadata?: { id?: string } }).metadata?.id || 'unknown'\n : 'unknown',\n errors\n );\n }\n\n return result.data as Decision;\n}\n\n/**\n * Load all decisions from a directory\n */\nexport async function loadDecisionsFromDir(dirPath: string): Promise<LoadResult> {\n const decisions: LoadedDecision[] = [];\n const errors: LoadError[] = [];\n\n if (!(await pathExists(dirPath))) {\n return { decisions, errors };\n }\n\n const files = await readFilesInDir(dirPath, (f) => f.endsWith('.decision.yaml'));\n\n for (const file of files) {\n const filePath = join(dirPath, file);\n try {\n const decision = await loadDecisionFile(filePath);\n decisions.push({ decision, filePath });\n } catch (error) {\n errors.push({\n filePath,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return { decisions, errors };\n}\n\n/**\n * Validate a decision file without loading it into registry\n */\nexport async function validateDecisionFile(filePath: string): Promise<{\n valid: boolean;\n errors: string[];\n}> {\n try {\n if (!(await pathExists(filePath))) {\n return { valid: false, errors: [`File not found: ${filePath}`] };\n }\n\n const content = await readTextFile(filePath);\n const parsed = parseYaml(content);\n\n const result = validateDecision(parsed);\n if (!result.success) {\n return { valid: false, errors: formatValidationErrors(result.errors) };\n }\n\n return { valid: true, errors: [] };\n } catch (error) {\n return {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n}\n","/**\n * Glob utilities for file matching\n */\nimport fg from 'fast-glob';\nimport { minimatch } from 'minimatch';\nimport { relative, isAbsolute } from 'node:path';\n\nexport interface GlobOptions {\n cwd?: string;\n ignore?: string[];\n absolute?: boolean;\n onlyFiles?: boolean;\n}\n\n/**\n * Find files matching glob patterns\n */\nexport async function glob(\n patterns: string | string[],\n options: GlobOptions = {}\n): Promise<string[]> {\n const { cwd = process.cwd(), ignore = [], absolute = false, onlyFiles = true } = options;\n\n return fg(patterns, {\n cwd,\n ignore,\n absolute,\n onlyFiles,\n dot: false,\n });\n}\n\n/**\n * Normalize a file path to be relative to a base directory\n * Handles both absolute and relative paths, cross-platform\n */\nexport function normalizePath(filePath: string, basePath: string = process.cwd()): string {\n let resultPath: string;\n\n if (!isAbsolute(filePath)) {\n // Already relative, use as-is\n resultPath = filePath;\n } else {\n // Convert absolute to relative from basePath\n resultPath = relative(basePath, filePath);\n }\n\n // Ensure forward slashes (handle both Unix and Windows separators)\n return resultPath.replace(/\\\\/g, '/');\n}\n\n/**\n * Check if a file path matches a glob pattern\n */\nexport function matchesPattern(\n filePath: string,\n pattern: string,\n options: { cwd?: string } = {}\n): boolean {\n const cwd = options.cwd || process.cwd();\n const normalizedPath = normalizePath(filePath, cwd);\n\n return minimatch(normalizedPath, pattern, { matchBase: true });\n}\n\n/**\n * Check if a file path matches any of the given patterns\n */\nexport function matchesAnyPattern(\n filePath: string,\n patterns: string[],\n options: { cwd?: string } = {}\n): boolean {\n return patterns.some((pattern) => matchesPattern(filePath, pattern, options));\n}\n\n// Re-export minimatch for advanced usage\nexport { minimatch };\n","/**\n * Decision Registry - Central store for architectural decisions\n */\nimport type { Decision, DecisionStatus, ConstraintType, Severity } from '../core/types/index.js';\nimport { DecisionNotFoundError, NotInitializedError } from '../core/errors/index.js';\nimport { loadDecisionsFromDir, type LoadedDecision, type LoadResult } from './loader.js';\nimport { getDecisionsDir, pathExists, getSpecBridgeDir } from '../utils/fs.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface RegistryOptions {\n basePath?: string;\n}\n\nexport interface DecisionFilter {\n status?: DecisionStatus[];\n tags?: string[];\n constraintType?: ConstraintType[];\n severity?: Severity[];\n}\n\nexport interface RegistryConstraintMatch {\n decisionId: string;\n decisionTitle: string;\n constraintId: string;\n type: ConstraintType;\n rule: string;\n severity: Severity;\n scope: string;\n}\n\n/**\n * Decision Registry class\n */\nexport class Registry {\n private decisions: Map<string, LoadedDecision> = new Map();\n private basePath: string;\n private loaded = false;\n\n constructor(options: RegistryOptions = {}) {\n this.basePath = options.basePath || process.cwd();\n }\n\n /**\n * Load all decisions from the decisions directory\n */\n async load(): Promise<LoadResult> {\n // Check if specbridge is initialized\n if (!(await pathExists(getSpecBridgeDir(this.basePath)))) {\n throw new NotInitializedError();\n }\n\n const decisionsDir = getDecisionsDir(this.basePath);\n const result = await loadDecisionsFromDir(decisionsDir);\n\n this.decisions.clear();\n for (const loaded of result.decisions) {\n this.decisions.set(loaded.decision.metadata.id, loaded);\n }\n\n this.loaded = true;\n return result;\n }\n\n /**\n * Ensure registry is loaded\n */\n private ensureLoaded(): void {\n if (!this.loaded) {\n throw new Error('Registry not loaded. Call load() first.');\n }\n }\n\n /**\n * Get all decisions\n */\n getAll(filter?: DecisionFilter): Decision[] {\n this.ensureLoaded();\n\n let decisions = Array.from(this.decisions.values()).map((d) => d.decision);\n\n if (filter) {\n decisions = this.applyFilter(decisions, filter);\n }\n\n return decisions;\n }\n\n /**\n * Get active decisions only\n */\n getActive(): Decision[] {\n return this.getAll({ status: ['active'] });\n }\n\n /**\n * Get a decision by ID\n */\n get(id: string): Decision {\n this.ensureLoaded();\n\n const loaded = this.decisions.get(id);\n if (!loaded) {\n throw new DecisionNotFoundError(id);\n }\n\n return loaded.decision;\n }\n\n /**\n * Get a decision with its file path\n */\n getWithPath(id: string): LoadedDecision {\n this.ensureLoaded();\n\n const loaded = this.decisions.get(id);\n if (!loaded) {\n throw new DecisionNotFoundError(id);\n }\n\n return loaded;\n }\n\n /**\n * Check if a decision exists\n */\n has(id: string): boolean {\n this.ensureLoaded();\n return this.decisions.has(id);\n }\n\n /**\n * Get all decision IDs\n */\n getIds(): string[] {\n this.ensureLoaded();\n return Array.from(this.decisions.keys());\n }\n\n /**\n * Get constraints applicable to a specific file\n */\n getConstraintsForFile(filePath: string, filter?: DecisionFilter): RegistryConstraintMatch[] {\n this.ensureLoaded();\n\n const applicable: RegistryConstraintMatch[] = [];\n let decisions = this.getActive();\n\n if (filter) {\n decisions = this.applyFilter(decisions, filter);\n }\n\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n if (matchesPattern(filePath, constraint.scope)) {\n applicable.push({\n decisionId: decision.metadata.id,\n decisionTitle: decision.metadata.title,\n constraintId: constraint.id,\n type: constraint.type,\n rule: constraint.rule,\n severity: constraint.severity,\n scope: constraint.scope,\n });\n }\n }\n }\n\n return applicable;\n }\n\n /**\n * Get decisions by tag\n */\n getByTag(tag: string): Decision[] {\n return this.getAll().filter((d) => d.metadata.tags?.includes(tag));\n }\n\n /**\n * Get decisions by owner\n */\n getByOwner(owner: string): Decision[] {\n return this.getAll().filter((d) => d.metadata.owners.includes(owner));\n }\n\n /**\n * Apply filter to decisions\n */\n private applyFilter(decisions: Decision[], filter: DecisionFilter): Decision[] {\n return decisions.filter((decision) => {\n // Filter by status\n if (filter.status && !filter.status.includes(decision.metadata.status)) {\n return false;\n }\n\n // Filter by tags\n if (filter.tags) {\n const hasTags = filter.tags.some((tag) => decision.metadata.tags?.includes(tag));\n if (!hasTags) return false;\n }\n\n // Filter by constraint type\n if (filter.constraintType) {\n const hasType = decision.constraints.some((c) => filter.constraintType?.includes(c.type));\n if (!hasType) return false;\n }\n\n // Filter by severity\n if (filter.severity) {\n const hasSeverity = decision.constraints.some((c) => filter.severity?.includes(c.severity));\n if (!hasSeverity) return false;\n }\n\n return true;\n });\n }\n\n /**\n * Get count of decisions by status\n */\n getStatusCounts(): Record<DecisionStatus, number> {\n this.ensureLoaded();\n\n const counts: Record<DecisionStatus, number> = {\n draft: 0,\n active: 0,\n deprecated: 0,\n superseded: 0,\n };\n\n for (const loaded of this.decisions.values()) {\n counts[loaded.decision.metadata.status]++;\n }\n\n return counts;\n }\n\n /**\n * Get total constraint count\n */\n getConstraintCount(): number {\n this.ensureLoaded();\n\n let count = 0;\n for (const loaded of this.decisions.values()) {\n count += loaded.decision.constraints.length;\n }\n\n return count;\n }\n}\n\n/**\n * Create a new registry instance\n */\nexport function createRegistry(options?: RegistryOptions): Registry {\n return new Registry(options);\n}\n","/**\n * Codebase scanner using ts-morph\n */\nimport { Project, SourceFile, Node, SyntaxKind } from 'ts-morph';\nimport { glob } from '../utils/glob.js';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\n\nexport interface ScanResult {\n files: ScannedFile[];\n totalFiles: number;\n totalLines: number;\n}\n\nexport interface ScannedFile {\n path: string;\n sourceFile: SourceFile;\n lines: number;\n}\n\nexport interface ScanOptions {\n sourceRoots: string[];\n exclude?: string[];\n cwd?: string;\n}\n\n/**\n * Scanner class for analyzing TypeScript/JavaScript codebases\n */\nexport class CodeScanner {\n private project: Project;\n private scannedFiles: Map<string, ScannedFile> = new Map();\n\n constructor() {\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n /**\n * Scan files matching the given patterns\n */\n async scan(options: ScanOptions): Promise<ScanResult> {\n const { sourceRoots, exclude = [], cwd = process.cwd() } = options;\n\n // Find files matching patterns\n const files = await glob(sourceRoots, {\n cwd,\n ignore: exclude,\n absolute: true,\n });\n\n // Add files to project\n for (const filePath of files) {\n try {\n const sourceFile = this.project.addSourceFileAtPath(filePath);\n const lines = sourceFile.getEndLineNumber();\n\n this.scannedFiles.set(filePath, {\n path: filePath,\n sourceFile,\n lines,\n });\n } catch {\n // Skip files that can't be parsed\n }\n }\n\n const scannedArray = Array.from(this.scannedFiles.values());\n const totalLines = scannedArray.reduce((sum, f) => sum + f.lines, 0);\n\n return {\n files: scannedArray,\n totalFiles: scannedArray.length,\n totalLines,\n };\n }\n\n /**\n * Get all scanned files\n */\n getFiles(): ScannedFile[] {\n return Array.from(this.scannedFiles.values());\n }\n\n /**\n * Get a specific file\n */\n getFile(path: string): ScannedFile | undefined {\n return this.scannedFiles.get(path);\n }\n\n /**\n * Get project instance for advanced analysis\n */\n getProject(): Project {\n return this.project;\n }\n\n /**\n * Find all classes in scanned files\n */\n findClasses(): { file: string; name: string; line: number }[] {\n const classes: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const classDecl of sourceFile.getClasses()) {\n const name = classDecl.getName();\n if (name) {\n classes.push({\n file: path,\n name,\n line: classDecl.getStartLineNumber(),\n });\n }\n }\n }\n\n return classes;\n }\n\n /**\n * Find all functions in scanned files\n */\n findFunctions(): { file: string; name: string; line: number; isExported: boolean }[] {\n const functions: { file: string; name: string; line: number; isExported: boolean }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n // Top-level functions\n for (const funcDecl of sourceFile.getFunctions()) {\n const name = funcDecl.getName();\n if (name) {\n functions.push({\n file: path,\n name,\n line: funcDecl.getStartLineNumber(),\n isExported: funcDecl.isExported(),\n });\n }\n }\n\n // Arrow functions assigned to variables\n for (const varDecl of sourceFile.getVariableDeclarations()) {\n const init = varDecl.getInitializer();\n if (init && Node.isArrowFunction(init)) {\n functions.push({\n file: path,\n name: varDecl.getName(),\n line: varDecl.getStartLineNumber(),\n isExported: varDecl.isExported(),\n });\n }\n }\n }\n\n return functions;\n }\n\n /**\n * Find all imports in scanned files\n */\n findImports(): { file: string; module: string; named: string[]; line: number }[] {\n const imports: { file: string; module: string; named: string[]; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const module = importDecl.getModuleSpecifierValue();\n const namedImports = importDecl.getNamedImports().map((n) => n.getName());\n\n imports.push({\n file: path,\n module,\n named: namedImports,\n line: importDecl.getStartLineNumber(),\n });\n }\n }\n\n return imports;\n }\n\n /**\n * Find all interfaces in scanned files\n */\n findInterfaces(): { file: string; name: string; line: number }[] {\n const interfaces: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n interfaces.push({\n file: path,\n name: interfaceDecl.getName(),\n line: interfaceDecl.getStartLineNumber(),\n });\n }\n }\n\n return interfaces;\n }\n\n /**\n * Find all type aliases in scanned files\n */\n findTypeAliases(): { file: string; name: string; line: number }[] {\n const types: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n types.push({\n file: path,\n name: typeAlias.getName(),\n line: typeAlias.getStartLineNumber(),\n });\n }\n }\n\n return types;\n }\n\n /**\n * Find try-catch blocks in scanned files\n */\n findTryCatchBlocks(): { file: string; line: number; hasThrow: boolean }[] {\n const blocks: { file: string; line: number; hasThrow: boolean }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isTryStatement(node)) {\n const catchClause = node.getCatchClause();\n const hasThrow = catchClause\n ? catchClause.getDescendantsOfKind(SyntaxKind.ThrowStatement).length > 0\n : false;\n\n blocks.push({\n file: path,\n line: node.getStartLineNumber(),\n hasThrow,\n });\n }\n });\n }\n\n return blocks;\n }\n}\n\n/**\n * Create a scanner from config\n */\nexport function createScannerFromConfig(_config: SpecBridgeConfig): CodeScanner {\n return new CodeScanner();\n}\n","/**\n * Base analyzer interface\n */\nimport type { Pattern, PatternExample } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\n\n/**\n * Analyzer interface - all analyzers must implement this\n */\nexport interface Analyzer {\n /**\n * Unique identifier for this analyzer\n */\n readonly id: string;\n\n /**\n * Human-readable name\n */\n readonly name: string;\n\n /**\n * Description of what this analyzer detects\n */\n readonly description: string;\n\n /**\n * Analyze the codebase and return detected patterns\n */\n analyze(scanner: CodeScanner): Promise<Pattern[]>;\n}\n\n/**\n * Helper to create a pattern with consistent structure\n */\nexport function createPattern(\n analyzer: string,\n params: {\n id: string;\n name: string;\n description: string;\n confidence: number;\n occurrences: number;\n examples: PatternExample[];\n suggestedConstraint?: Pattern['suggestedConstraint'];\n }\n): Pattern {\n return {\n analyzer,\n ...params,\n };\n}\n\n/**\n * Calculate confidence based on occurrence ratio\n */\nexport function calculateConfidence(\n occurrences: number,\n total: number,\n minOccurrences: number = 3\n): number {\n if (occurrences < minOccurrences) {\n return 0;\n }\n\n const ratio = occurrences / total;\n // Scale from 50 (at minOccurrences) to 100 (at 100%)\n return Math.min(100, Math.round(50 + ratio * 50));\n}\n\n/**\n * Extract a code snippet around a line\n */\nexport function extractSnippet(content: string, line: number, contextLines: number = 1): string {\n const lines = content.split('\\n');\n const start = Math.max(0, line - 1 - contextLines);\n const end = Math.min(lines.length, line + contextLines);\n\n return lines.slice(start, end).join('\\n');\n}\n","/**\n * Naming convention analyzer\n */\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\ninterface NamingPattern {\n convention: string;\n regex: RegExp;\n description: string;\n}\n\nconst CLASS_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Classes use PascalCase' },\n];\n\nconst FUNCTION_PATTERNS: NamingPattern[] = [\n { convention: 'camelCase', regex: /^[a-z][a-zA-Z0-9]*$/, description: 'Functions use camelCase' },\n { convention: 'snake_case', regex: /^[a-z][a-z0-9_]*$/, description: 'Functions use snake_case' },\n];\n\nconst INTERFACE_PATTERNS: NamingPattern[] = [\n {\n convention: 'PascalCase',\n regex: /^[A-Z][a-zA-Z0-9]*$/,\n description: 'Interfaces use PascalCase',\n },\n {\n convention: 'IPrefixed',\n regex: /^I[A-Z][a-zA-Z0-9]*$/,\n description: 'Interfaces are prefixed with I',\n },\n];\n\nconst TYPE_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Types use PascalCase' },\n {\n convention: 'TSuffixed',\n regex: /^[A-Z][a-zA-Z0-9]*Type$/,\n description: 'Types are suffixed with Type',\n },\n];\n\nexport class NamingAnalyzer implements Analyzer {\n readonly id = 'naming';\n readonly name = 'Naming Convention Analyzer';\n readonly description = 'Detects naming conventions for classes, functions, interfaces, and types';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze class naming\n const classPattern = this.analyzeClassNaming(scanner);\n if (classPattern) patterns.push(classPattern);\n\n // Analyze function naming\n const functionPattern = this.analyzeFunctionNaming(scanner);\n if (functionPattern) patterns.push(functionPattern);\n\n // Analyze interface naming\n const interfacePattern = this.analyzeInterfaceNaming(scanner);\n if (interfacePattern) patterns.push(interfacePattern);\n\n // Analyze type naming\n const typePattern = this.analyzeTypeNaming(scanner);\n if (typePattern) patterns.push(typePattern);\n\n return patterns;\n }\n\n private analyzeClassNaming(scanner: CodeScanner): Pattern | null {\n const classes = scanner.findClasses();\n if (classes.length < 3) return null;\n\n const matches = this.findBestMatch(\n classes.map((c) => c.name),\n CLASS_PATTERNS\n );\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-classes',\n name: 'Class Naming Convention',\n description: `Classes follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: classes.slice(0, 3).map((c) => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Classes should use ${matches.convention} naming convention`,\n severity: 'medium',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeFunctionNaming(scanner: CodeScanner): Pattern | null {\n const functions = scanner.findFunctions();\n if (functions.length < 3) return null;\n\n const matches = this.findBestMatch(\n functions.map((f) => f.name),\n FUNCTION_PATTERNS\n );\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-functions',\n name: 'Function Naming Convention',\n description: `Functions follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: functions.slice(0, 3).map((f) => ({\n file: f.file,\n line: f.line,\n snippet: `function ${f.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Functions should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeInterfaceNaming(scanner: CodeScanner): Pattern | null {\n const interfaces = scanner.findInterfaces();\n if (interfaces.length < 3) return null;\n\n const matches = this.findBestMatch(\n interfaces.map((i) => i.name),\n INTERFACE_PATTERNS\n );\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-interfaces',\n name: 'Interface Naming Convention',\n description: `Interfaces follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: interfaces.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `interface ${i.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Interfaces should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeTypeNaming(scanner: CodeScanner): Pattern | null {\n const types = scanner.findTypeAliases();\n if (types.length < 3) return null;\n\n const matches = this.findBestMatch(\n types.map((t) => t.name),\n TYPE_PATTERNS\n );\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-types',\n name: 'Type Alias Naming Convention',\n description: `Type aliases follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: types.slice(0, 3).map((t) => ({\n file: t.file,\n line: t.line,\n snippet: `type ${t.name}`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: `Type aliases should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private findBestMatch(\n names: string[],\n patterns: NamingPattern[]\n ): { convention: string; confidence: number; matchCount: number } | null {\n let bestMatch: { convention: string; matchCount: number } | null = null;\n\n for (const pattern of patterns) {\n const matchCount = names.filter((name) => pattern.regex.test(name)).length;\n if (!bestMatch || matchCount > bestMatch.matchCount) {\n bestMatch = { convention: pattern.convention, matchCount };\n }\n }\n\n if (!bestMatch || bestMatch.matchCount < 3) return null;\n\n const confidence = calculateConfidence(bestMatch.matchCount, names.length);\n if (confidence < 50) return null;\n\n return {\n convention: bestMatch.convention,\n confidence,\n matchCount: bestMatch.matchCount,\n };\n }\n}\n","/**\n * Import pattern analyzer\n */\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class ImportsAnalyzer implements Analyzer {\n readonly id = 'imports';\n readonly name = 'Import Pattern Analyzer';\n readonly description = 'Detects import organization patterns and module usage conventions';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze barrel imports\n const barrelPattern = this.analyzeBarrelImports(scanner);\n if (barrelPattern) patterns.push(barrelPattern);\n\n // Analyze relative vs absolute imports\n const relativePattern = this.analyzeRelativeImports(scanner);\n if (relativePattern) patterns.push(relativePattern);\n\n // Analyze commonly used modules\n const modulePatterns = this.analyzeCommonModules(scanner);\n patterns.push(...modulePatterns);\n\n return patterns;\n }\n\n private analyzeBarrelImports(scanner: CodeScanner): Pattern | null {\n const imports = scanner.findImports();\n const barrelImports = imports.filter((i) => {\n const modulePath = i.module;\n return (\n modulePath.startsWith('.') && !modulePath.includes('.js') && !modulePath.includes('.ts')\n );\n });\n\n // Check for index imports\n const indexImports = barrelImports.filter((i) => {\n return i.module.endsWith('/index') || !i.module.includes('/');\n });\n\n if (indexImports.length < 3) return null;\n\n const confidence = calculateConfidence(indexImports.length, barrelImports.length);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-barrel',\n name: 'Barrel Import Pattern',\n description: 'Modules are imported through barrel (index) files',\n confidence,\n occurrences: indexImports.length,\n examples: indexImports.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 3).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: 'Import from barrel (index) files rather than individual modules',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeRelativeImports(scanner: CodeScanner): Pattern | null {\n const imports = scanner.findImports();\n const relativeImports = imports.filter((i) => i.module.startsWith('.'));\n const absoluteImports = imports.filter(\n (i) => !i.module.startsWith('.') && !i.module.startsWith('@')\n );\n const aliasImports = imports.filter(\n (i) => i.module.startsWith('@/') || i.module.startsWith('~')\n );\n\n // Determine dominant pattern\n const total = relativeImports.length + absoluteImports.length + aliasImports.length;\n if (total < 10) return null;\n\n if (aliasImports.length > relativeImports.length && aliasImports.length >= 5) {\n const confidence = calculateConfidence(aliasImports.length, total);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-alias',\n name: 'Path Alias Import Pattern',\n description: 'Imports use path aliases (@ or ~) instead of relative paths',\n confidence,\n occurrences: aliasImports.length,\n examples: aliasImports.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: 'Use path aliases instead of relative imports',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n if (relativeImports.length > aliasImports.length * 2 && relativeImports.length >= 5) {\n const confidence = calculateConfidence(relativeImports.length, total);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-relative',\n name: 'Relative Import Pattern',\n description: 'Imports use relative paths',\n confidence,\n occurrences: relativeImports.length,\n examples: relativeImports.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Use relative imports for local modules',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeCommonModules(scanner: CodeScanner): Pattern[] {\n const patterns: Pattern[] = [];\n const imports = scanner.findImports();\n\n // Count external module usage\n const moduleCounts = new Map<string, { count: number; examples: typeof imports }>();\n\n for (const imp of imports) {\n // Skip relative imports\n if (imp.module.startsWith('.')) continue;\n\n // Get the package name (handle scoped packages)\n const parts = imp.module.split('/');\n const packageName =\n imp.module.startsWith('@') && parts.length > 1 ? `${parts[0]}/${parts[1]}` : parts[0];\n\n if (packageName) {\n const existing = moduleCounts.get(packageName) || { count: 0, examples: [] };\n existing.count++;\n existing.examples.push(imp);\n moduleCounts.set(packageName, existing);\n }\n }\n\n // Create patterns for commonly used modules\n for (const [packageName, data] of moduleCounts) {\n if (data.count >= 5) {\n const confidence = Math.min(100, 50 + data.count * 2);\n\n patterns.push(\n createPattern(this.id, {\n id: `imports-module-${packageName.replace(/[/@]/g, '-')}`,\n name: `${packageName} Usage`,\n description: `${packageName} is used across ${data.count} files`,\n confidence,\n occurrences: data.count,\n examples: data.examples.slice(0, 3).map((i) => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ') || '...'} } from '${i.module}'`,\n })),\n })\n );\n }\n }\n\n return patterns;\n }\n}\n","/**\n * Code structure pattern analyzer\n */\nimport { basename, dirname } from 'node:path';\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner, ScannedFile } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class StructureAnalyzer implements Analyzer {\n readonly id = 'structure';\n readonly name = 'Code Structure Analyzer';\n readonly description = 'Detects file organization and directory structure patterns';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n const files = scanner.getFiles();\n\n // Analyze directory conventions\n const dirPatterns = this.analyzeDirectoryConventions(files);\n patterns.push(...dirPatterns);\n\n // Analyze file naming conventions\n const filePatterns = this.analyzeFileNaming(files);\n patterns.push(...filePatterns);\n\n // Analyze colocation patterns\n const colocationPattern = this.analyzeColocation(files);\n if (colocationPattern) patterns.push(colocationPattern);\n\n return patterns;\n }\n\n private analyzeDirectoryConventions(files: ScannedFile[]): Pattern[] {\n const patterns: Pattern[] = [];\n const dirCounts = new Map<string, number>();\n\n // Count files per directory name\n for (const file of files) {\n const dir = basename(dirname(file.path));\n dirCounts.set(dir, (dirCounts.get(dir) || 0) + 1);\n }\n\n // Check for common directory structures\n const commonDirs = [\n { name: 'components', description: 'UI components are organized in a components directory' },\n { name: 'hooks', description: 'Custom hooks are organized in a hooks directory' },\n { name: 'utils', description: 'Utility functions are organized in a utils directory' },\n { name: 'services', description: 'Service modules are organized in a services directory' },\n { name: 'types', description: 'Type definitions are organized in a types directory' },\n { name: 'api', description: 'API modules are organized in an api directory' },\n { name: 'lib', description: 'Library code is organized in a lib directory' },\n { name: 'core', description: 'Core modules are organized in a core directory' },\n ];\n\n for (const { name, description } of commonDirs) {\n const count = dirCounts.get(name);\n if (count && count >= 3) {\n const exampleFiles = files.filter((f) => basename(dirname(f.path)) === name).slice(0, 3);\n\n patterns.push(\n createPattern(this.id, {\n id: `structure-dir-${name}`,\n name: `${name}/ Directory Convention`,\n description,\n confidence: Math.min(100, 60 + count * 5),\n occurrences: count,\n examples: exampleFiles.map((f) => ({\n file: f.path,\n line: 1,\n snippet: basename(f.path),\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `${name.charAt(0).toUpperCase() + name.slice(1)} should be placed in the ${name}/ directory`,\n severity: 'low',\n scope: `src/**/${name}/**/*.ts`,\n },\n })\n );\n }\n }\n\n return patterns;\n }\n\n private analyzeFileNaming(files: ScannedFile[]): Pattern[] {\n const patterns: Pattern[] = [];\n\n // Check for suffix patterns\n const suffixPatterns: { suffix: string; pattern: RegExp; description: string }[] = [\n { suffix: '.test.ts', pattern: /\\.test\\.ts$/, description: 'Test files use .test.ts suffix' },\n { suffix: '.spec.ts', pattern: /\\.spec\\.ts$/, description: 'Test files use .spec.ts suffix' },\n {\n suffix: '.types.ts',\n pattern: /\\.types\\.ts$/,\n description: 'Type definition files use .types.ts suffix',\n },\n {\n suffix: '.utils.ts',\n pattern: /\\.utils\\.ts$/,\n description: 'Utility files use .utils.ts suffix',\n },\n {\n suffix: '.service.ts',\n pattern: /\\.service\\.ts$/,\n description: 'Service files use .service.ts suffix',\n },\n {\n suffix: '.controller.ts',\n pattern: /\\.controller\\.ts$/,\n description: 'Controller files use .controller.ts suffix',\n },\n {\n suffix: '.model.ts',\n pattern: /\\.model\\.ts$/,\n description: 'Model files use .model.ts suffix',\n },\n {\n suffix: '.schema.ts',\n pattern: /\\.schema\\.ts$/,\n description: 'Schema files use .schema.ts suffix',\n },\n ];\n\n for (const { suffix, pattern, description } of suffixPatterns) {\n const matchingFiles = files.filter((f) => pattern.test(f.path));\n\n if (matchingFiles.length >= 3) {\n const confidence = Math.min(100, 60 + matchingFiles.length * 3);\n\n patterns.push(\n createPattern(this.id, {\n id: `structure-suffix-${suffix.replace(/\\./g, '-')}`,\n name: `${suffix} File Naming`,\n description,\n confidence,\n occurrences: matchingFiles.length,\n examples: matchingFiles.slice(0, 3).map((f) => ({\n file: f.path,\n line: 1,\n snippet: basename(f.path),\n })),\n })\n );\n }\n }\n\n return patterns;\n }\n\n private analyzeColocation(files: ScannedFile[]): Pattern | null {\n // Check if test files are colocated with source files\n const testFiles = files.filter((f) => /\\.(test|spec)\\.tsx?$/.test(f.path));\n const sourceFiles = files.filter((f) => !/\\.(test|spec)\\.tsx?$/.test(f.path));\n\n if (testFiles.length < 3) return null;\n\n let colocatedCount = 0;\n const colocatedExamples: { file: string; line: number; snippet: string }[] = [];\n\n for (const testFile of testFiles) {\n const testDir = dirname(testFile.path);\n const testName = basename(testFile.path).replace(/\\.(test|spec)\\.tsx?$/, '');\n\n // Check if corresponding source file is in same directory\n const hasColocatedSource = sourceFiles.some(\n (s) => dirname(s.path) === testDir && basename(s.path).startsWith(testName)\n );\n\n if (hasColocatedSource) {\n colocatedCount++;\n if (colocatedExamples.length < 3) {\n colocatedExamples.push({\n file: testFile.path,\n line: 1,\n snippet: basename(testFile.path),\n });\n }\n }\n }\n\n const confidence = calculateConfidence(colocatedCount, testFiles.length);\n if (confidence < 60) return null;\n\n return createPattern(this.id, {\n id: 'structure-colocation',\n name: 'Test Colocation Pattern',\n description: 'Test files are colocated with their source files',\n confidence,\n occurrences: colocatedCount,\n examples: colocatedExamples,\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Test files should be colocated with their source files',\n severity: 'low',\n scope: 'src/**/*.test.ts',\n },\n });\n }\n}\n","/**\n * Error handling pattern analyzer\n */\nimport { Node } from 'ts-morph';\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class ErrorsAnalyzer implements Analyzer {\n readonly id = 'errors';\n readonly name = 'Error Handling Analyzer';\n readonly description = 'Detects error handling patterns and custom error class usage';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze custom error classes\n const errorClassPattern = this.analyzeCustomErrorClasses(scanner);\n if (errorClassPattern) patterns.push(errorClassPattern);\n\n // Analyze try-catch patterns\n const tryCatchPattern = this.analyzeTryCatchPatterns(scanner);\n if (tryCatchPattern) patterns.push(tryCatchPattern);\n\n // Analyze error throwing patterns\n const throwPattern = this.analyzeThrowPatterns(scanner);\n if (throwPattern) patterns.push(throwPattern);\n\n return patterns;\n }\n\n private analyzeCustomErrorClasses(scanner: CodeScanner): Pattern | null {\n const classes = scanner.findClasses();\n const errorClasses = classes.filter(\n (c) => c.name.endsWith('Error') || c.name.endsWith('Exception')\n );\n\n if (errorClasses.length < 2) return null;\n\n // Check if they extend a common base\n const files = scanner.getFiles();\n const baseCount: Map<string, number> = new Map();\n\n for (const errorClass of errorClasses) {\n const file = files.find((f) => f.path === errorClass.file);\n if (!file) continue;\n\n const classDecl = file.sourceFile.getClass(errorClass.name);\n if (!classDecl) continue;\n\n const extendClause = classDecl.getExtends();\n if (extendClause) {\n const baseName = extendClause.getText();\n if (baseName !== 'Error' && baseName.endsWith('Error')) {\n baseCount.set(baseName, (baseCount.get(baseName) || 0) + 1);\n }\n }\n }\n\n // Find the custom base with the most extending classes\n let customBaseName: string | null = null;\n let maxCount = 0;\n for (const [baseName, count] of baseCount.entries()) {\n if (count > maxCount) {\n maxCount = count;\n customBaseName = baseName;\n }\n }\n\n // Check for custom base pattern (requires >= 3 extending the same custom base)\n if (maxCount >= 3 && customBaseName) {\n const confidence = calculateConfidence(maxCount, errorClasses.length);\n\n return createPattern(this.id, {\n id: 'errors-custom-base',\n name: 'Custom Error Base Class',\n description: `Custom errors extend a common base class (${customBaseName})`,\n confidence,\n occurrences: maxCount,\n examples: errorClasses.slice(0, 3).map((c) => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name} extends ${customBaseName}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Custom error classes should extend ${customBaseName}`,\n severity: 'medium',\n scope: 'src/**/*.ts',\n verifier: 'errors',\n },\n });\n }\n\n // Fall back to generic custom error classes pattern (requires >= 3 error classes)\n if (errorClasses.length >= 3) {\n const confidence = Math.min(100, 50 + errorClasses.length * 5);\n\n return createPattern(this.id, {\n id: 'errors-custom-classes',\n name: 'Custom Error Classes',\n description: 'Custom error classes are used for domain-specific errors',\n confidence,\n occurrences: errorClasses.length,\n examples: errorClasses.slice(0, 3).map((c) => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name}`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Use custom error classes for domain-specific errors',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeTryCatchPatterns(scanner: CodeScanner): Pattern | null {\n const tryCatchBlocks = scanner.findTryCatchBlocks();\n\n if (tryCatchBlocks.length < 3) return null;\n\n // Check how many rethrow vs swallow\n const rethrowCount = tryCatchBlocks.filter((b) => b.hasThrow).length;\n const swallowCount = tryCatchBlocks.length - rethrowCount;\n\n if (rethrowCount >= 3 && rethrowCount > swallowCount) {\n const confidence = calculateConfidence(rethrowCount, tryCatchBlocks.length);\n\n return createPattern(this.id, {\n id: 'errors-rethrow',\n name: 'Error Rethrow Pattern',\n description: 'Caught errors are typically rethrown after handling',\n confidence,\n occurrences: rethrowCount,\n examples: tryCatchBlocks\n .filter((b) => b.hasThrow)\n .slice(0, 3)\n .map((b) => ({\n file: b.file,\n line: b.line,\n snippet: 'try { ... } catch (e) { ... throw ... }',\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Caught errors should be rethrown or wrapped after handling',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeThrowPatterns(scanner: CodeScanner): Pattern | null {\n const files = scanner.getFiles();\n let throwNewError = 0;\n let throwCustom = 0;\n const examples: { file: string; line: number; snippet: string }[] = [];\n\n for (const { path, sourceFile } of files) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isThrowStatement(node)) {\n const expression = node.getExpression();\n if (expression) {\n const text = expression.getText();\n if (text.startsWith('new Error(')) {\n throwNewError++;\n } else if (text.startsWith('new ') && text.includes('Error')) {\n throwCustom++;\n if (examples.length < 3) {\n const snippet = text.length > 50 ? text.slice(0, 50) + '...' : text;\n examples.push({\n file: path,\n line: node.getStartLineNumber(),\n snippet: `throw ${snippet}`,\n });\n }\n }\n }\n }\n });\n }\n\n if (throwCustom >= 3 && throwCustom > throwNewError) {\n const confidence = calculateConfidence(throwCustom, throwCustom + throwNewError);\n\n return createPattern(this.id, {\n id: 'errors-throw-custom',\n name: 'Custom Error Throwing',\n description: 'Custom error classes are thrown instead of generic Error',\n confidence,\n occurrences: throwCustom,\n examples,\n suggestedConstraint: {\n type: 'convention',\n rule: 'Throw custom error classes instead of generic Error',\n severity: 'medium',\n scope: 'src/**/*.ts',\n verifier: 'errors',\n },\n });\n }\n\n return null;\n }\n}\n","/**\n * Analyzer exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './structure.js';\nexport * from './errors.js';\n\nimport type { Analyzer } from './base.js';\nimport { NamingAnalyzer } from './naming.js';\nimport { ImportsAnalyzer } from './imports.js';\nimport { StructureAnalyzer } from './structure.js';\nimport { ErrorsAnalyzer } from './errors.js';\n\n/**\n * Built-in analyzers registry\n */\nexport const builtinAnalyzers: Record<string, () => Analyzer> = {\n naming: () => new NamingAnalyzer(),\n imports: () => new ImportsAnalyzer(),\n structure: () => new StructureAnalyzer(),\n errors: () => new ErrorsAnalyzer(),\n};\n\n/**\n * Get analyzer by ID\n */\nexport function getAnalyzer(id: string): Analyzer | null {\n const factory = builtinAnalyzers[id];\n return factory ? factory() : null;\n}\n\n/**\n * Get all analyzer IDs\n */\nexport function getAnalyzerIds(): string[] {\n return Object.keys(builtinAnalyzers);\n}\n","/**\n * Inference Engine - Orchestrates pattern detection\n */\nimport type { Pattern, InferenceResult, SpecBridgeConfig } from '../core/types/index.js';\nimport { AnalyzerNotFoundError } from '../core/errors/index.js';\nimport { CodeScanner } from './scanner.js';\nimport { getAnalyzer, getAnalyzerIds, type Analyzer } from './analyzers/index.js';\n\nexport interface InferenceOptions {\n analyzers?: string[];\n minConfidence?: number;\n sourceRoots?: string[];\n exclude?: string[];\n cwd?: string;\n}\n\n/**\n * Inference Engine class\n */\nexport class InferenceEngine {\n private scanner: CodeScanner;\n private analyzers: Analyzer[] = [];\n\n constructor() {\n this.scanner = new CodeScanner();\n }\n\n /**\n * Configure analyzers to use\n */\n configureAnalyzers(analyzerIds: string[]): void {\n this.analyzers = [];\n\n for (const id of analyzerIds) {\n const analyzer = getAnalyzer(id);\n if (!analyzer) {\n throw new AnalyzerNotFoundError(id);\n }\n this.analyzers.push(analyzer);\n }\n }\n\n /**\n * Run inference on the codebase\n */\n async infer(options: InferenceOptions): Promise<InferenceResult> {\n const startTime = Date.now();\n\n const {\n analyzers: analyzerIds = getAnalyzerIds(),\n minConfidence = 50,\n sourceRoots = ['src/**/*.ts', 'src/**/*.tsx'],\n exclude = ['**/*.test.ts', '**/*.spec.ts', '**/node_modules/**', '**/dist/**'],\n cwd = process.cwd(),\n } = options;\n\n // Configure analyzers\n this.configureAnalyzers(analyzerIds);\n\n // Scan codebase\n const scanResult = await this.scanner.scan({\n sourceRoots,\n exclude,\n cwd,\n });\n\n if (scanResult.totalFiles === 0) {\n return {\n patterns: [],\n analyzersRun: analyzerIds,\n filesScanned: 0,\n duration: Date.now() - startTime,\n };\n }\n\n // Run all analyzers\n const allPatterns: Pattern[] = [];\n\n for (const analyzer of this.analyzers) {\n try {\n const patterns = await analyzer.analyze(this.scanner);\n allPatterns.push(...patterns);\n } catch (error) {\n // Log but don't fail on individual analyzer errors\n console.warn(`Analyzer ${analyzer.id} failed:`, error);\n }\n }\n\n // Filter by minimum confidence\n const filteredPatterns = allPatterns.filter((p) => p.confidence >= minConfidence);\n\n // Sort by confidence (highest first)\n filteredPatterns.sort((a, b) => b.confidence - a.confidence);\n\n return {\n patterns: filteredPatterns,\n analyzersRun: analyzerIds,\n filesScanned: scanResult.totalFiles,\n duration: Date.now() - startTime,\n };\n }\n\n /**\n * Get scanner for direct access\n */\n getScanner(): CodeScanner {\n return this.scanner;\n }\n}\n\n/**\n * Create an inference engine from config\n */\nexport function createInferenceEngine(): InferenceEngine {\n return new InferenceEngine();\n}\n\n/**\n * Run inference with config\n */\nexport async function runInference(\n config: SpecBridgeConfig,\n options?: Partial<InferenceOptions>\n): Promise<InferenceResult> {\n const engine = createInferenceEngine();\n\n return engine.infer({\n analyzers: config.inference?.analyzers,\n minConfidence: config.inference?.minConfidence,\n sourceRoots: config.project.sourceRoots,\n exclude: config.project.exclude,\n ...options,\n });\n}\n","/**\n * Verification Engine - Orchestrates constraint checking\n */\nimport { Project } from 'ts-morph';\nimport type {\n Violation,\n Severity,\n SpecBridgeConfig,\n Decision,\n VerificationWarning,\n VerificationIssue,\n} from '../core/types/index.js';\nimport type {\n VerificationRunRequest,\n VerificationRunResult,\n} from '../core/types/verification-contracts.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport {\n selectVerifierForConstraint,\n getVerifierIds,\n type VerificationContext,\n} from './verifiers/index.js';\nimport { glob } from '../utils/glob.js';\nimport { AstCache } from './cache.js';\nimport { ResultsCache } from './results-cache.js';\nimport { shouldApplyConstraintToFile } from './applicability.js';\nimport { ExplainReporter } from './explain.js';\nimport { getPluginLoader } from './plugins/loader.js';\nimport { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { getLogger } from '../utils/logger.js';\n\nexport interface VerificationOptions extends VerificationRunRequest {\n reporter?: ExplainReporter;\n}\n\n/**\n * Verification Engine class\n */\nexport class VerificationEngine {\n private registry: Registry;\n private project: Project;\n private astCache: AstCache;\n private resultsCache: ResultsCache;\n private pluginsLoaded = false;\n private logger = getLogger({ module: 'verification.engine' });\n\n constructor(registry?: Registry) {\n this.registry = registry || createRegistry();\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n this.astCache = new AstCache();\n this.resultsCache = new ResultsCache();\n }\n\n /**\n * Run verification\n */\n async verify(\n config: SpecBridgeConfig,\n options: VerificationOptions = {}\n ): Promise<VerificationRunResult> {\n const startTime = Date.now();\n\n const {\n level = 'full',\n files: specificFiles,\n decisions: decisionIds,\n cwd = process.cwd(),\n } = options;\n\n // Get level-specific settings\n const levelConfig = config.verification?.levels?.[level];\n const severityFilter = options.severity || levelConfig?.severity;\n const timeout = options.timeout || levelConfig?.timeout || 60000;\n\n // Load plugins once per engine instance\n if (!this.pluginsLoaded) {\n await getPluginLoader().loadPlugins(cwd);\n this.pluginsLoaded = true;\n }\n\n // Load registry if not already loaded\n await this.registry.load();\n\n // Get decisions to verify\n let decisions = this.registry.getActive();\n if (decisionIds && decisionIds.length > 0) {\n decisions = decisions.filter((d) => decisionIds.includes(d.metadata.id));\n }\n\n // Get files to verify\n const filesToVerify = specificFiles\n ? specificFiles\n : await glob(config.project.sourceRoots, {\n cwd,\n ignore: config.project.exclude,\n absolute: true,\n });\n\n if (filesToVerify.length === 0) {\n return {\n success: true,\n violations: [],\n checked: 0,\n passed: 0,\n failed: 0,\n skipped: 0,\n duration: Date.now() - startTime,\n warnings: [],\n errors: [],\n };\n }\n\n // Collect all violations, warnings, and errors\n const allViolations: Violation[] = [];\n const allWarnings: VerificationWarning[] = [];\n const allErrors: VerificationIssue[] = [];\n let checked = 0;\n let passed = 0;\n let failed = 0;\n const skipped = 0;\n\n // Create AbortController for cancellation support\n const abortController = new AbortController();\n\n // Process files with timeout\n let timeoutHandle: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<'timeout'>((resolve) => {\n timeoutHandle = setTimeout(() => {\n abortController.abort(); // Signal verifiers to stop\n resolve('timeout');\n }, timeout);\n // Use unref() so timeout doesn't prevent process exit if it's the only thing left\n timeoutHandle.unref();\n });\n\n const verificationPromise = this.verifyFiles(\n filesToVerify,\n decisions,\n severityFilter,\n cwd,\n options.reporter,\n abortController.signal,\n (violations, warnings, errors) => {\n allViolations.push(...violations);\n allWarnings.push(...warnings);\n allErrors.push(...errors);\n checked++;\n if (violations.length > 0) {\n failed++;\n } else {\n passed++;\n }\n }\n );\n\n let result: void | 'timeout';\n try {\n result = await Promise.race([verificationPromise, timeoutPromise]);\n\n if (result === 'timeout') {\n return {\n success: false,\n violations: allViolations,\n checked,\n passed,\n failed,\n skipped: filesToVerify.length - checked,\n duration: timeout,\n warnings: allWarnings,\n errors: allErrors,\n };\n }\n } finally {\n // Always clear the timeout to prevent event loop leak\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n timeoutHandle = null;\n }\n }\n\n // Determine success based on level\n const hasBlockingViolations = allViolations.some((v) => {\n if (level === 'commit') {\n return v.type === 'invariant' || v.severity === 'critical';\n }\n if (level === 'pr') {\n return v.type === 'invariant' || v.severity === 'critical' || v.severity === 'high';\n }\n return v.type === 'invariant';\n });\n\n return {\n success: !hasBlockingViolations,\n violations: allViolations,\n checked,\n passed,\n failed,\n skipped,\n duration: Date.now() - startTime,\n warnings: allWarnings,\n errors: allErrors,\n };\n }\n\n /**\n * Verify a single file\n */\n async verifyFile(\n filePath: string,\n decisions: Decision[],\n severityFilter?: Severity[],\n cwd: string = process.cwd(),\n reporter?: ExplainReporter,\n signal?: AbortSignal\n ): Promise<{\n violations: Violation[];\n warnings: VerificationWarning[];\n errors: VerificationIssue[];\n }> {\n const violations: Violation[] = [];\n const warnings: VerificationWarning[] = [];\n const errors: VerificationIssue[] = [];\n\n // Check if verification was aborted\n if (signal?.aborted) {\n return { violations, warnings, errors };\n }\n\n const sourceFile = await this.astCache.get(filePath, this.project);\n if (!sourceFile) return { violations, warnings, errors };\n\n // Compute file hash once for caching\n let fileHash: string | null = null;\n try {\n const content = await readFile(filePath, 'utf-8');\n fileHash = createHash('sha256').update(content).digest('hex');\n } catch {\n // If we can't read the file, skip caching\n fileHash = null;\n }\n\n // Check each decision's constraints\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n // Check if file matches constraint scope\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd, severityFilter })) {\n // Track skipped constraint in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: false,\n reason: 'File does not match scope pattern or severity filter',\n });\n }\n continue;\n }\n\n // Get appropriate verifier\n const verifier = selectVerifierForConstraint(\n constraint.rule,\n constraint.verifier,\n constraint.check\n );\n\n if (!verifier) {\n // Determine what was requested\n const requestedVerifier =\n constraint.check?.verifier || constraint.verifier || 'auto-detected';\n this.logger.warn(\n {\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n requestedVerifier,\n availableVerifiers: getVerifierIds(),\n },\n 'No verifier found for constraint'\n );\n\n warnings.push({\n type: 'missing_verifier',\n message: `No verifier found for constraint (requested: ${requestedVerifier})`,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n file: filePath,\n });\n\n // Track in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: false,\n reason: `No verifier found (requested: ${requestedVerifier})`,\n });\n }\n\n continue;\n }\n\n // Check results cache first\n let constraintViolations: Violation[];\n\n if (fileHash) {\n const cacheKey = {\n filePath,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n fileHash,\n };\n\n const cached = this.resultsCache.get(cacheKey);\n if (cached) {\n // Cache hit!\n constraintViolations = cached;\n violations.push(...constraintViolations);\n\n // Track in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope (cached)',\n selectedVerifier: verifier.id,\n });\n }\n\n continue;\n }\n }\n\n // Validate params if this is a custom plugin with paramsSchema\n if (constraint.check?.verifier && constraint.check?.params) {\n const pluginLoader = getPluginLoader();\n const validationResult = pluginLoader.validateParams(\n constraint.check.verifier,\n constraint.check.params\n );\n\n if (!validationResult.success) {\n warnings.push({\n type: 'invalid_params',\n message: validationResult.error,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n file: filePath,\n });\n\n // Track in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: false,\n reason: `Params validation failed: ${validationResult.error}`,\n });\n }\n\n continue;\n }\n }\n\n // Run verification\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n signal,\n };\n\n const verificationStart = Date.now();\n try {\n constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n\n // Cache results\n if (fileHash) {\n this.resultsCache.set(\n {\n filePath,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n fileHash,\n },\n constraintViolations\n );\n }\n\n // Track successful verification in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope',\n selectedVerifier: verifier.id,\n verifierOutput: {\n violations: constraintViolations.length,\n duration: Date.now() - verificationStart,\n },\n });\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack = error instanceof Error ? error.stack : undefined;\n this.logger.error(\n {\n verifierId: verifier.id,\n filePath,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n error: errorMessage,\n stack: errorStack,\n },\n 'Verifier execution failed'\n );\n\n errors.push({\n type: 'verifier_exception',\n message: `Verifier '${verifier.id}' failed: ${errorMessage}`,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n file: filePath,\n stack: errorStack,\n });\n\n // Track failed verification in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope',\n selectedVerifier: verifier.id,\n verifierOutput: {\n violations: 0,\n duration: Date.now() - verificationStart,\n error: errorMessage,\n },\n });\n }\n }\n }\n }\n\n return { violations, warnings, errors };\n }\n\n /**\n * Verify multiple files\n */\n private async verifyFiles(\n files: string[],\n decisions: Decision[],\n severityFilter: Severity[] | undefined,\n cwd: string,\n reporter: ExplainReporter | undefined,\n signal: AbortSignal,\n onFileVerified: (\n violations: Violation[],\n warnings: VerificationWarning[],\n errors: VerificationIssue[]\n ) => void\n ): Promise<void> {\n const BATCH_SIZE = 50; // Increased from 10 for better parallelism\n for (let i = 0; i < files.length; i += BATCH_SIZE) {\n // Check if aborted before processing next batch\n if (signal.aborted) {\n break;\n }\n\n const batch = files.slice(i, i + BATCH_SIZE);\n const results = await Promise.all(\n batch.map((file) => this.verifyFile(file, decisions, severityFilter, cwd, reporter, signal))\n );\n\n for (const result of results) {\n onFileVerified(result.violations, result.warnings, result.errors);\n }\n }\n }\n\n /**\n * Get registry\n */\n getRegistry(): Registry {\n return this.registry;\n }\n}\n\n/**\n * Create verification engine\n */\nexport function createVerificationEngine(registry?: Registry): VerificationEngine {\n return new VerificationEngine(registry);\n}\n","/**\n * Base verifier interface\n */\nimport type { Violation, Constraint, Severity } from '../../core/types/index.js';\nimport type { SourceFile } from 'ts-morph';\n\n/**\n * Context passed to verifiers\n */\nexport interface VerificationContext {\n filePath: string;\n sourceFile: SourceFile;\n constraint: Constraint;\n decisionId: string;\n /** Optional AbortSignal for cancellation support */\n signal?: AbortSignal;\n}\n\n/**\n * Verifier interface - all verifiers must implement this\n */\nexport interface Verifier {\n /**\n * Unique identifier for this verifier\n */\n readonly id: string;\n\n /**\n * Human-readable name\n */\n readonly name: string;\n\n /**\n * Description of what this verifier checks\n */\n readonly description: string;\n\n /**\n * Verify a file against a constraint\n */\n verify(ctx: VerificationContext): Promise<Violation[]>;\n}\n\n/**\n * Plugin metadata\n */\nexport interface VerifierPluginMetadata {\n /** Unique identifier matching /^[a-z][a-z0-9-]*$/ */\n id: string;\n /** Semver version string */\n version: string;\n /** Plugin author */\n author?: string;\n /** Brief description of what this verifier checks */\n description?: string;\n}\n\n/**\n * Verifier plugin interface\n * Custom verifiers must export a default object implementing this interface\n */\nexport interface VerifierPlugin {\n /** Plugin metadata */\n metadata: VerifierPluginMetadata;\n\n /** Factory function that creates a new verifier instance */\n createVerifier: () => Verifier;\n\n /** Optional Zod schema for validating constraint.check.params */\n paramsSchema?: unknown; // Will be validated as ZodSchema at runtime\n}\n\n/**\n * Helper to define a verifier plugin with type safety\n *\n * @example\n * ```typescript\n * import { defineVerifierPlugin, type Verifier } from '@ipation/specbridge';\n *\n * class MyVerifier implements Verifier {\n * readonly id = 'my-custom';\n * readonly name = 'My Custom Verifier';\n * readonly description = 'Checks custom patterns';\n *\n * async verify(ctx) {\n * // Implementation\n * return [];\n * }\n * }\n *\n * export default defineVerifierPlugin({\n * metadata: {\n * id: 'my-custom',\n * version: '1.0.0',\n * author: 'Your Name'\n * },\n * createVerifier: () => new MyVerifier()\n * });\n * ```\n */\nexport function defineVerifierPlugin(plugin: VerifierPlugin): VerifierPlugin {\n return plugin;\n}\n\n/**\n * Helper to create a violation\n */\nexport function createViolation(params: {\n decisionId: string;\n constraintId: string;\n type: Constraint['type'];\n severity: Severity;\n message: string;\n file: string;\n line?: number;\n column?: number;\n endLine?: number;\n endColumn?: number;\n suggestion?: string;\n autofix?: Violation['autofix'];\n}): Violation {\n return params;\n}\n","/**\n * Naming convention verifier\n */\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst NAMING_PATTERNS: Record<string, { regex: RegExp; description: string }> = {\n PascalCase: {\n regex: /^[A-Z][a-zA-Z0-9]*$/,\n description: 'PascalCase (e.g., MyClass)',\n },\n camelCase: {\n regex: /^[a-z][a-zA-Z0-9]*$/,\n description: 'camelCase (e.g., myFunction)',\n },\n UPPER_SNAKE_CASE: {\n regex: /^[A-Z][A-Z0-9_]*$/,\n description: 'UPPER_SNAKE_CASE (e.g., MAX_VALUE)',\n },\n snake_case: {\n regex: /^[a-z][a-z0-9_]*$/,\n description: 'snake_case (e.g., my_variable)',\n },\n 'kebab-case': {\n regex: /^[a-z][a-z0-9-]*$/,\n description: 'kebab-case (e.g., my-component)',\n },\n};\n\nexport class NamingVerifier implements Verifier {\n readonly id = 'naming';\n readonly name = 'Naming Convention Verifier';\n readonly description = 'Verifies naming conventions for classes, functions, and variables';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n\n // Parse constraint rule to extract target and convention\n // Expected format: \"Classes should use PascalCase\" or \"Functions should use camelCase\"\n const rule = constraint.rule.toLowerCase();\n let convention: string | null = null;\n let targetType: 'class' | 'function' | 'interface' | 'type' | null = null;\n\n // Detect convention\n for (const [name] of Object.entries(NAMING_PATTERNS)) {\n if (rule.includes(name.toLowerCase())) {\n convention = name;\n break;\n }\n }\n\n // Detect target type\n if (rule.includes('class')) targetType = 'class';\n else if (rule.includes('function')) targetType = 'function';\n else if (rule.includes('interface')) targetType = 'interface';\n else if (rule.includes('type')) targetType = 'type';\n\n if (!convention || !targetType) {\n // Can't parse rule, skip verification\n return violations;\n }\n\n const pattern = NAMING_PATTERNS[convention];\n if (!pattern) return violations;\n\n // Check based on target type\n if (targetType === 'class') {\n for (const classDecl of sourceFile.getClasses()) {\n const name = classDecl.getName();\n if (name && !pattern.regex.test(name)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Class \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: classDecl.getStartLineNumber(),\n column: classDecl.getStart() - classDecl.getStartLinePos(),\n suggestion: `Rename to follow ${pattern.description}`,\n })\n );\n }\n }\n }\n\n if (targetType === 'function') {\n for (const funcDecl of sourceFile.getFunctions()) {\n const name = funcDecl.getName();\n if (name && !pattern.regex.test(name)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: funcDecl.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n })\n );\n }\n }\n }\n\n if (targetType === 'interface') {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n const name = interfaceDecl.getName();\n if (!pattern.regex.test(name)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Interface \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: interfaceDecl.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n })\n );\n }\n }\n }\n\n if (targetType === 'type') {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const name = typeAlias.getName();\n if (!pattern.regex.test(name)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Type \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: typeAlias.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n })\n );\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Import pattern verifier\n */\nimport path from 'node:path';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nexport class ImportsVerifier implements Verifier {\n readonly id = 'imports';\n readonly name = 'Import Pattern Verifier';\n readonly description = 'Verifies import patterns like barrel imports, path aliases, etc.';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n // Check for required .js extensions in relative imports (ESM-friendly)\n if (\n (rule.includes('.js') && rule.includes('extension')) ||\n rule.includes('esm') ||\n rule.includes('add .js')\n ) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (!moduleSpec.startsWith('.')) continue;\n\n const ext = path.posix.extname(moduleSpec);\n let suggested: string | null = null;\n\n if (!ext) {\n suggested = `${moduleSpec}.js`;\n } else if (ext === '.ts' || ext === '.tsx' || ext === '.jsx') {\n suggested = moduleSpec.slice(0, -ext.length) + '.js';\n } else if (ext !== '.js') {\n continue;\n }\n\n if (!suggested || suggested === moduleSpec) continue;\n\n const ms = importDecl.getModuleSpecifier();\n const start = ms.getStart() + 1; // inside quotes\n const end = ms.getEnd() - 1;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Relative import \"${moduleSpec}\" should include a .js extension`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Update to \"${suggested}\"`,\n autofix: {\n description: 'Add/normalize .js extension in import specifier',\n edits: [{ start, end, text: suggested }],\n },\n })\n );\n }\n }\n\n // Check for barrel import requirement\n if (rule.includes('barrel') || rule.includes('index')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n\n // Skip external packages\n if (!moduleSpec.startsWith('.')) continue;\n\n // Check if importing specific file instead of barrel\n if (moduleSpec.match(/\\.(ts|js|tsx|jsx)$/) || moduleSpec.match(/\\/[^/]+$/)) {\n // Could be a direct file import - flag if not index\n if (!moduleSpec.endsWith('/index') && !moduleSpec.endsWith('index')) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Import from \"${moduleSpec}\" should use barrel (index) import`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Import from the parent directory index file instead',\n })\n );\n }\n }\n }\n }\n\n // Check for path alias requirement\n if (rule.includes('alias') || rule.includes('@/') || rule.includes('path alias')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n\n // Check for deeply nested relative imports\n if (moduleSpec.match(/^\\.\\.\\/\\.\\.\\/\\.\\.\\//)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Deep relative import \"${moduleSpec}\" should use path alias`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use path alias (e.g., @/module) for deep imports',\n })\n );\n }\n }\n }\n\n // Check for no circular imports (basic check)\n if (rule.includes('circular') || rule.includes('cycle')) {\n // This is a simplified check - a full cycle detection would need graph analysis\n // Check if any import matches the current file's exports\n // This is a very basic heuristic\n const currentFilename = filePath.replace(/\\.[jt]sx?$/, '');\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (moduleSpec.includes(currentFilename.split('/').pop() || '')) {\n // Potential self-reference, might indicate circular dependency\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible circular import detected: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Review import structure for circular dependencies',\n })\n );\n }\n }\n }\n\n // Check for no wildcard imports\n if (rule.includes('wildcard') || rule.includes('* as') || rule.includes('no namespace')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const namespaceImport = importDecl.getNamespaceImport();\n if (namespaceImport) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Namespace import \"* as ${namespaceImport.getText()}\" should use named imports`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use specific named imports instead of namespace import',\n })\n );\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Error handling verifier\n */\nimport { Node } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nexport class ErrorsVerifier implements Verifier {\n readonly id = 'errors';\n readonly name = 'Error Handling Verifier';\n readonly description = 'Verifies error handling patterns';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n // Check for custom error class extension\n if (rule.includes('extend') || rule.includes('base') || rule.includes('hierarchy')) {\n // Extract base class name from rule if mentioned\n const baseClassMatch = rule.match(/extend\\s+(\\w+)/i) || rule.match(/(\\w+Error)\\s+class/i);\n const requiredBase = baseClassMatch ? baseClassMatch[1] : null;\n\n for (const classDecl of sourceFile.getClasses()) {\n const className = classDecl.getName();\n if (!className?.endsWith('Error') && !className?.endsWith('Exception')) continue;\n\n const extendsClause = classDecl.getExtends();\n if (!extendsClause) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Error class \"${className}\" does not extend any base class`,\n file: filePath,\n line: classDecl.getStartLineNumber(),\n suggestion: requiredBase\n ? `Extend ${requiredBase}`\n : 'Extend a base error class for consistent error handling',\n })\n );\n } else if (requiredBase) {\n const baseName = extendsClause.getText();\n if (baseName !== requiredBase && baseName !== 'Error') {\n // Allow extending Error or the required base\n }\n }\n }\n }\n\n // Check for throwing custom errors vs generic Error\n if (rule.includes('custom error') || rule.includes('throw custom')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isThrowStatement(node)) {\n const expression = node.getExpression();\n if (expression) {\n const text = expression.getText();\n if (text.startsWith('new Error(')) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Throwing generic Error instead of custom error class',\n file: filePath,\n line: node.getStartLineNumber(),\n suggestion: 'Use a custom error class for better error handling',\n })\n );\n }\n }\n }\n });\n }\n\n // Check for empty catch blocks\n if (rule.includes('empty catch') || rule.includes('swallow') || rule.includes('handle')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isTryStatement(node)) {\n const catchClause = node.getCatchClause();\n if (catchClause) {\n const block = catchClause.getBlock();\n const statements = block.getStatements();\n\n // Check if catch block is empty or only has comments\n if (statements.length === 0) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Empty catch block swallows error without handling',\n file: filePath,\n line: catchClause.getStartLineNumber(),\n suggestion: 'Add error handling, logging, or rethrow the error',\n })\n );\n }\n }\n }\n });\n }\n\n // Check for console.error vs proper logging\n if (rule.includes('logging') || rule.includes('logger') || rule.includes('no console')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isCallExpression(node)) {\n const expression = node.getExpression();\n const text = expression.getText();\n if (text === 'console.error' || text === 'console.log') {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Using ${text} instead of proper logging`,\n file: filePath,\n line: node.getStartLineNumber(),\n suggestion: 'Use a proper logging library',\n })\n );\n }\n }\n });\n }\n\n return violations;\n }\n}\n","/**\n * Regex-based verifier for simple pattern matching\n */\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\n/**\n * A generic verifier that uses regex patterns from constraint rules\n * This handles constraints that specify patterns to match or avoid\n */\nexport class RegexVerifier implements Verifier {\n readonly id = 'regex';\n readonly name = 'Regex Pattern Verifier';\n readonly description = 'Verifies code against regex patterns specified in constraints';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n\n // Try to extract regex pattern from rule\n // Patterns like: \"must not contain /pattern/\" or \"should match /pattern/\"\n const mustNotMatch = rule.match(/must\\s+not\\s+(?:contain|match|use)\\s+\\/(.+?)\\//i);\n const shouldMatch = rule.match(/(?:should|must)\\s+(?:contain|match|use)\\s+\\/(.+?)\\//i);\n const forbiddenPattern = rule.match(/forbidden:\\s*\\/(.+?)\\//i);\n const requiredPattern = rule.match(/required:\\s*\\/(.+?)\\//i);\n\n const fileText = sourceFile.getFullText();\n\n // Handle \"must not contain\" patterns\n const patternToForbid = mustNotMatch?.[1] || forbiddenPattern?.[1];\n if (patternToForbid) {\n try {\n const regex = new RegExp(patternToForbid, 'g');\n let match: RegExpExecArray | null;\n\n while ((match = regex.exec(fileText)) !== null) {\n const beforeMatch = fileText.substring(0, match.index);\n const lineNumber = beforeMatch.split('\\n').length;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Found forbidden pattern: \"${match[0]}\"`,\n file: filePath,\n line: lineNumber,\n suggestion: `Remove or replace the pattern matching /${patternToForbid}/`,\n })\n );\n }\n } catch {\n // Invalid regex, skip\n }\n }\n\n // Handle \"should contain\" patterns (file-level check)\n const patternToRequire = shouldMatch?.[1] || requiredPattern?.[1];\n if (patternToRequire && !mustNotMatch) {\n try {\n const regex = new RegExp(patternToRequire);\n if (!regex.test(fileText)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `File does not contain required pattern: /${patternToRequire}/`,\n file: filePath,\n suggestion: `Add code matching /${patternToRequire}/`,\n })\n );\n }\n } catch {\n // Invalid regex, skip\n }\n }\n\n return violations;\n }\n}\n","/**\n * Dependency constraint verifier\n *\n * Supports rules like:\n * - \"No circular dependencies between modules\"\n * - \"Domain layer cannot depend on infrastructure layer\"\n * - \"No dependencies on package lodash\"\n * - \"Maximum import depth: 2\"\n */\nimport path from 'node:path';\nimport type { Project } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\ntype DependencyGraph = Map<string, Set<string>>;\n\nconst graphCache = new WeakMap<Project, { fileCount: number; graph: DependencyGraph }>();\n\nfunction normalizeFsPath(p: string): string {\n return p.replaceAll('\\\\', '/');\n}\n\nfunction joinLike(fromFilePath: string, relative: string): string {\n const fromNorm = normalizeFsPath(fromFilePath);\n const relNorm = normalizeFsPath(relative);\n\n if (path.isAbsolute(fromNorm)) {\n return normalizeFsPath(path.resolve(path.dirname(fromNorm), relNorm));\n }\n\n // In-memory ts-morph projects often use relative paths; keep them relative.\n const dir = path.posix.dirname(fromNorm);\n return path.posix.normalize(path.posix.join(dir, relNorm));\n}\n\nfunction resolveToSourceFilePath(\n project: Project,\n fromFilePath: string,\n moduleSpec: string\n): string | null {\n if (!moduleSpec.startsWith('.')) return null;\n\n const candidates: string[] = [];\n const raw = joinLike(fromFilePath, moduleSpec);\n\n const addCandidate = (p: string) => candidates.push(normalizeFsPath(p));\n\n // If an extension exists, try it and common TS/JS mappings.\n const ext = path.posix.extname(raw);\n if (ext) {\n addCandidate(raw);\n\n if (ext === '.js') addCandidate(raw.slice(0, -3) + '.ts');\n if (ext === '.jsx') addCandidate(raw.slice(0, -4) + '.tsx');\n if (ext === '.ts') addCandidate(raw.slice(0, -3) + '.js');\n if (ext === '.tsx') addCandidate(raw.slice(0, -4) + '.jsx');\n\n // Directory index variants.\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.ts'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.tsx'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.js'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.jsx'));\n } else {\n // No extension: try source extensions and index files.\n addCandidate(raw + '.ts');\n addCandidate(raw + '.tsx');\n addCandidate(raw + '.js');\n addCandidate(raw + '.jsx');\n\n addCandidate(path.posix.join(raw, 'index.ts'));\n addCandidate(path.posix.join(raw, 'index.tsx'));\n addCandidate(path.posix.join(raw, 'index.js'));\n addCandidate(path.posix.join(raw, 'index.jsx'));\n }\n\n for (const candidate of candidates) {\n const sf = project.getSourceFile(candidate);\n if (sf) return sf.getFilePath();\n }\n\n return null;\n}\n\nfunction buildDependencyGraph(project: Project): DependencyGraph {\n const cached = graphCache.get(project);\n const sourceFiles = project.getSourceFiles();\n if (cached && cached.fileCount === sourceFiles.length) {\n return cached.graph;\n }\n\n const graph: DependencyGraph = new Map();\n\n for (const sf of sourceFiles) {\n const from = normalizeFsPath(sf.getFilePath());\n if (!graph.has(from)) graph.set(from, new Set());\n\n for (const importDecl of sf.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n const resolved = resolveToSourceFilePath(project, from, moduleSpec);\n if (resolved) {\n const dependencies = graph.get(from);\n if (dependencies) {\n dependencies.add(normalizeFsPath(resolved));\n }\n }\n }\n }\n\n graphCache.set(project, { fileCount: sourceFiles.length, graph });\n return graph;\n}\n\nfunction tarjanScc(graph: DependencyGraph): string[][] {\n let index = 0;\n const stack: string[] = [];\n const onStack = new Set<string>();\n const indices = new Map<string, number>();\n const lowlink = new Map<string, number>();\n const result: string[][] = [];\n\n const strongConnect = (v: string) => {\n indices.set(v, index);\n lowlink.set(v, index);\n index++;\n stack.push(v);\n onStack.add(v);\n\n const edges = graph.get(v) || new Set<string>();\n for (const w of edges) {\n if (!indices.has(w)) {\n strongConnect(w);\n const currentLowlink = lowlink.get(v);\n const childLowlink = lowlink.get(w);\n if (currentLowlink !== undefined && childLowlink !== undefined) {\n lowlink.set(v, Math.min(currentLowlink, childLowlink));\n }\n } else if (onStack.has(w)) {\n const currentLowlink = lowlink.get(v);\n const childIndex = indices.get(w);\n if (currentLowlink !== undefined && childIndex !== undefined) {\n lowlink.set(v, Math.min(currentLowlink, childIndex));\n }\n }\n }\n\n if (lowlink.get(v) === indices.get(v)) {\n const scc: string[] = [];\n while (stack.length > 0) {\n const w = stack.pop();\n if (!w) break;\n onStack.delete(w);\n scc.push(w);\n if (w === v) break;\n }\n result.push(scc);\n }\n };\n\n for (const v of graph.keys()) {\n if (!indices.has(v)) strongConnect(v);\n }\n\n return result;\n}\n\nfunction parseMaxImportDepth(rule: string): number | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/maximum\\s{1,5}import\\s{1,5}depth\\s{0,5}[:=]?\\s{0,5}(\\d+)/i);\n const depthText = m?.[1];\n return depthText ? Number.parseInt(depthText, 10) : null;\n}\n\nfunction parseBannedDependency(rule: string): string | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/no\\s{1,5}dependencies?\\s{1,5}on\\s{1,5}(?:package\\s{1,5})?(.+?)(?:\\.|$)/i);\n const value = m?.[1]?.trim();\n if (!value) return null;\n return value.length > 0 ? value : null;\n}\n\nfunction parseLayerRule(rule: string): { fromLayer: string; toLayer: string } | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(\n /(\\w+)\\s{1,5}layer\\s{1,5}cannot\\s{1,5}depend\\s{1,5}on\\s{1,5}(\\w+)\\s{1,5}layer/i\n );\n const fromLayer = m?.[1]?.toLowerCase();\n const toLayer = m?.[2]?.toLowerCase();\n if (!fromLayer || !toLayer) return null;\n return { fromLayer, toLayer };\n}\n\nfunction fileInLayer(filePath: string, layer: string): boolean {\n const fp = normalizeFsPath(filePath).toLowerCase();\n return fp.includes(`/${layer}/`) || fp.endsWith(`/${layer}.ts`) || fp.endsWith(`/${layer}.tsx`);\n}\n\nexport class DependencyVerifier implements Verifier {\n readonly id = 'dependencies';\n readonly name = 'Dependency Verifier';\n readonly description = 'Checks dependency constraints, import depth, and circular dependencies';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n const lowerRule = rule.toLowerCase();\n const project = sourceFile.getProject();\n const projectFilePath = normalizeFsPath(sourceFile.getFilePath());\n\n // 1) Circular dependencies (across files)\n if (lowerRule.includes('circular') || lowerRule.includes('cycle')) {\n const graph = buildDependencyGraph(project);\n const sccs = tarjanScc(graph);\n const current = projectFilePath;\n\n for (const scc of sccs) {\n const first = scc[0];\n const hasSelfLoop =\n first !== undefined && scc.length === 1 && (graph.get(first)?.has(first) ?? false);\n const isCycle = scc.length > 1 || hasSelfLoop;\n if (!isCycle) continue;\n\n if (!scc.includes(current)) continue;\n\n // Avoid duplicate reporting: only report from lexicographically-smallest file in the SCC.\n const sorted = [...scc].sort();\n if (sorted[0] !== current) continue;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Circular dependency detected across: ${sorted.join(' -> ')}`,\n file: filePath,\n line: 1,\n suggestion:\n 'Break the cycle by extracting shared abstractions or reversing the dependency',\n })\n );\n }\n }\n\n // 2) Layer constraints (heuristic by folder name)\n const layerRule = parseLayerRule(rule);\n if (layerRule && fileInLayer(projectFilePath, layerRule.fromLayer)) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n const resolved = resolveToSourceFilePath(project, projectFilePath, moduleSpec);\n if (!resolved) continue;\n\n if (fileInLayer(resolved, layerRule.toLayer)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Layer violation: ${layerRule.fromLayer} depends on ${layerRule.toLayer} via import \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Refactor to remove dependency from ${layerRule.fromLayer} to ${layerRule.toLayer}`,\n })\n );\n }\n }\n }\n\n // 3) Banned dependency (package or internal)\n const banned = parseBannedDependency(rule);\n if (banned) {\n const bannedLower = banned.toLowerCase();\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (moduleSpec.toLowerCase().includes(bannedLower)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Banned dependency import detected: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Remove or replace dependency \"${banned}\"`,\n })\n );\n }\n }\n }\n\n // 4) Import depth limits (../ count)\n const maxDepth = parseMaxImportDepth(rule);\n if (maxDepth !== null) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (!moduleSpec.startsWith('.')) continue;\n const depth = (moduleSpec.match(/\\.\\.\\//g) || []).length;\n if (depth > maxDepth) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Import depth ${depth} exceeds maximum ${maxDepth}: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion:\n 'Use a shallower module boundary (or introduce a public entrypoint for this dependency)',\n })\n );\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Complexity constraint verifier\n *\n * Supports rules like:\n * - \"Cyclomatic complexity must not exceed 10\"\n * - \"File size must not exceed 300 lines\"\n * - \"Functions must have at most 4 parameters\"\n * - \"Nesting depth must not exceed 4\"\n */\nimport {\n Node,\n type ArrowFunction,\n type FunctionDeclaration,\n type FunctionExpression,\n type MethodDeclaration,\n} from 'ts-morph';\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nfunction parseLimit(rule: string, pattern: RegExp): number | null {\n const m = rule.match(pattern);\n const value = m?.[1];\n return value ? Number.parseInt(value, 10) : null;\n}\n\nfunction getFileLineCount(text: string): number {\n if (text.length === 0) return 0;\n return text.split('\\n').length;\n}\n\nfunction getDecisionPoints(fn: Node): number {\n let points = 0;\n for (const d of fn.getDescendants()) {\n switch (d.getKind()) {\n case SyntaxKind.IfStatement:\n case SyntaxKind.ForStatement:\n case SyntaxKind.ForInStatement:\n case SyntaxKind.ForOfStatement:\n case SyntaxKind.WhileStatement:\n case SyntaxKind.DoStatement:\n case SyntaxKind.CatchClause:\n case SyntaxKind.ConditionalExpression:\n case SyntaxKind.CaseClause:\n points++;\n break;\n case SyntaxKind.BinaryExpression: {\n // Count short-circuit operators (&&, ||)\n const text = d.getText();\n if (text.includes('&&') || text.includes('||')) points++;\n break;\n }\n default:\n break;\n }\n }\n return points;\n}\n\nfunction calculateCyclomaticComplexity(fn: Node): number {\n // Base complexity of 1 + number of decision points.\n return 1 + getDecisionPoints(fn);\n}\n\nfunction getFunctionDisplayName(fn: Node): string {\n // Best-effort name resolution.\n if (\n Node.isFunctionDeclaration(fn) ||\n Node.isMethodDeclaration(fn) ||\n Node.isFunctionExpression(fn)\n ) {\n const name = fn.getName();\n if (typeof name === 'string' && name.length > 0) {\n return name;\n }\n }\n\n // Variable = () => ...\n const parent = fn.getParent();\n if (parent && Node.isVariableDeclaration(parent)) {\n return parent.getName();\n }\n\n return '<anonymous>';\n}\n\nfunction maxNestingDepth(node: Node): number {\n let maxDepth = 0;\n\n const walk = (n: Node, depth: number) => {\n maxDepth = Math.max(maxDepth, depth);\n\n const kind = n.getKind();\n const isNestingNode =\n kind === SyntaxKind.IfStatement ||\n kind === SyntaxKind.ForStatement ||\n kind === SyntaxKind.ForInStatement ||\n kind === SyntaxKind.ForOfStatement ||\n kind === SyntaxKind.WhileStatement ||\n kind === SyntaxKind.DoStatement ||\n kind === SyntaxKind.SwitchStatement ||\n kind === SyntaxKind.TryStatement;\n\n for (const child of n.getChildren()) {\n // Skip nested function scopes for nesting depth.\n if (\n child.getKind() === SyntaxKind.FunctionDeclaration ||\n child.getKind() === SyntaxKind.FunctionExpression ||\n child.getKind() === SyntaxKind.ArrowFunction ||\n child.getKind() === SyntaxKind.MethodDeclaration\n ) {\n continue;\n }\n walk(child, isNestingNode ? depth + 1 : depth);\n }\n };\n\n walk(node, 0);\n return maxDepth;\n}\n\nexport class ComplexityVerifier implements Verifier {\n readonly id = 'complexity';\n readonly name = 'Complexity Verifier';\n readonly description = 'Checks cyclomatic complexity, file size, parameters, and nesting depth';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n\n const maxComplexity = parseLimit(rule, /complexity\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n const maxLines = parseLimit(rule, /file\\s+size\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)\\s+lines?/i);\n const maxParams =\n parseLimit(rule, /at\\s+most\\s+(\\d+)\\s+parameters?/i) ??\n parseLimit(rule, /parameters?\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n const maxNesting = parseLimit(rule, /nesting\\s+depth\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n\n if (maxLines !== null) {\n const lineCount = getFileLineCount(sourceFile.getFullText());\n if (lineCount > maxLines) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `File has ${lineCount} lines which exceeds maximum ${maxLines}`,\n file: filePath,\n line: 1,\n suggestion: 'Split the file into smaller modules',\n })\n );\n }\n }\n\n type FunctionLikeNode =\n | FunctionDeclaration\n | FunctionExpression\n | ArrowFunction\n | MethodDeclaration;\n const functionLikes: FunctionLikeNode[] = [\n ...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionExpression),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.ArrowFunction),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.MethodDeclaration),\n ];\n\n for (const fn of functionLikes) {\n const fnName = getFunctionDisplayName(fn);\n\n if (maxComplexity !== null) {\n const complexity = calculateCyclomaticComplexity(fn);\n if (complexity > maxComplexity) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has cyclomatic complexity ${complexity} which exceeds maximum ${maxComplexity}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Refactor to reduce branching or extract smaller functions',\n })\n );\n }\n }\n\n if (maxParams !== null) {\n const paramCount = fn.getParameters().length;\n if (paramCount > maxParams) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has ${paramCount} parameters which exceeds maximum ${maxParams}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Consider grouping parameters into an options object',\n })\n );\n }\n }\n\n if (maxNesting !== null) {\n const depth = maxNestingDepth(fn);\n if (depth > maxNesting) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has nesting depth ${depth} which exceeds maximum ${maxNesting}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Reduce nesting by using early returns or extracting functions',\n })\n );\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Security verifier (heuristic/static checks)\n *\n * Supports rules like:\n * - \"No hardcoded secrets\"\n * - \"Avoid eval / Function constructor\"\n * - \"Prevent SQL injection\"\n * - \"Avoid innerHTML / dangerouslySetInnerHTML\"\n */\nimport type { Node } from 'ts-morph';\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst SECRET_NAME_RE = /(api[_-]?key|password|secret|token)/i;\n\nfunction isStringLiteralLike(node: Node): boolean {\n const k = node.getKind();\n return k === SyntaxKind.StringLiteral || k === SyntaxKind.NoSubstitutionTemplateLiteral;\n}\n\nexport class SecurityVerifier implements Verifier {\n readonly id = 'security';\n readonly name = 'Security Verifier';\n readonly description =\n 'Detects common security footguns (secrets, eval, XSS/SQL injection heuristics)';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n const checkSecrets =\n rule.includes('secret') ||\n rule.includes('password') ||\n rule.includes('token') ||\n rule.includes('api key') ||\n rule.includes('hardcoded');\n const checkEval = rule.includes('eval') || rule.includes('function constructor');\n const checkXss =\n rule.includes('xss') ||\n rule.includes('innerhtml') ||\n rule.includes('dangerouslysetinnerhtml');\n const checkSql = rule.includes('sql') || rule.includes('injection');\n const checkProto = rule.includes('prototype pollution') || rule.includes('__proto__');\n\n if (checkSecrets) {\n for (const vd of sourceFile.getVariableDeclarations()) {\n const name = vd.getName();\n if (!SECRET_NAME_RE.test(name)) continue;\n\n const init = vd.getInitializer();\n if (!init || !isStringLiteralLike(init)) continue;\n\n const value = init.getText().slice(1, -1); // best-effort strip quotes\n if (value.length === 0) continue;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible hardcoded secret in variable \"${name}\"`,\n file: filePath,\n line: vd.getStartLineNumber(),\n suggestion: 'Move secrets to environment variables or a secret manager',\n })\n );\n }\n\n for (const pa of sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {\n const propName = pa.getNameNode().getText();\n if (!SECRET_NAME_RE.test(propName)) continue;\n\n const init = pa.getInitializer();\n if (!init || !isStringLiteralLike(init)) continue;\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible hardcoded secret in object property ${propName}`,\n file: filePath,\n line: pa.getStartLineNumber(),\n suggestion: 'Move secrets to environment variables or a secret manager',\n })\n );\n }\n }\n\n if (checkEval) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const exprText = call.getExpression().getText();\n if (exprText === 'eval' || exprText === 'Function') {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Unsafe dynamic code execution via ${exprText}()`,\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Avoid eval/Function; use safer alternatives',\n })\n );\n }\n }\n }\n\n if (checkXss) {\n // innerHTML assignments\n for (const bin of sourceFile.getDescendantsOfKind(SyntaxKind.BinaryExpression)) {\n const left = bin.getLeft();\n const propertyAccess = left.asKind(SyntaxKind.PropertyAccessExpression);\n if (!propertyAccess) continue;\n if (propertyAccess.getName() === 'innerHTML') {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential XSS: assignment to innerHTML',\n file: filePath,\n line: bin.getStartLineNumber(),\n suggestion: 'Prefer textContent or a safe templating/escaping strategy',\n })\n );\n }\n }\n\n // React dangerouslySetInnerHTML usage\n if (sourceFile.getFullText().includes('dangerouslySetInnerHTML')) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential XSS: usage of dangerouslySetInnerHTML',\n file: filePath,\n line: 1,\n suggestion: 'Avoid dangerouslySetInnerHTML or ensure content is sanitized',\n })\n );\n }\n }\n\n if (checkSql) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n const propertyAccess = expr.asKind(SyntaxKind.PropertyAccessExpression);\n if (!propertyAccess) continue;\n const name = propertyAccess.getName();\n if (name !== 'query' && name !== 'execute') continue;\n\n const arg = call.getArguments()[0];\n if (!arg) continue;\n\n const isTemplate = arg.getKind() === SyntaxKind.TemplateExpression;\n const isConcat =\n arg.getKind() === SyntaxKind.BinaryExpression && arg.getText().includes('+');\n if (!isTemplate && !isConcat) continue;\n\n const text = arg.getText().toLowerCase();\n if (\n !text.includes('select') &&\n !text.includes('insert') &&\n !text.includes('update') &&\n !text.includes('delete')\n ) {\n continue;\n }\n\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential SQL injection: dynamically constructed SQL query',\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Use parameterized queries / prepared statements',\n })\n );\n }\n }\n\n if (checkProto) {\n const text = sourceFile.getFullText();\n if (text.includes('__proto__') || text.includes('constructor.prototype')) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential prototype pollution pattern detected',\n file: filePath,\n line: 1,\n suggestion: 'Avoid writing to __proto__/prototype; validate object keys',\n })\n );\n }\n }\n\n return violations;\n }\n}\n","/**\n * API consistency verifier (heuristic)\n *\n * Supports rules like:\n * - \"REST endpoints must use kebab-case\"\n */\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'all']);\n\nfunction isKebabPath(pathValue: string): boolean {\n const parts = pathValue.split('/').filter(Boolean);\n for (const part of parts) {\n if (part.startsWith(':')) continue; // path params\n if (!/^[a-z0-9-]+$/.test(part)) return false;\n }\n return true;\n}\n\nexport class ApiVerifier implements Verifier {\n readonly id = 'api';\n readonly name = 'API Consistency Verifier';\n readonly description = 'Checks basic REST endpoint naming conventions in common frameworks';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n const enforceKebab = rule.includes('kebab') || rule.includes('kebab-case');\n if (!enforceKebab) return violations;\n\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n const propertyAccess = expr.asKind(SyntaxKind.PropertyAccessExpression);\n if (!propertyAccess) continue;\n\n const method = propertyAccess.getName();\n if (!method || !HTTP_METHODS.has(String(method))) continue;\n\n const firstArg = call.getArguments()[0];\n const stringLiteral = firstArg?.asKind(SyntaxKind.StringLiteral);\n if (!stringLiteral) continue;\n\n const pathValue = stringLiteral.getLiteralValue();\n if (typeof pathValue !== 'string') continue;\n\n if (!isKebabPath(pathValue)) {\n violations.push(\n createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Endpoint path \"${pathValue}\" is not kebab-case`,\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Use lowercase and hyphens in static path segments (e.g., /user-settings)',\n })\n );\n }\n }\n\n return violations;\n }\n}\n","/**\n * Plugin loader for custom verifiers\n *\n * Dynamically loads verifier plugins from .specbridge/verifiers/\n */\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { pathToFileURL } from 'url';\nimport fg from 'fast-glob';\nimport type { Verifier, VerifierPlugin } from '../verifiers/base.js';\nimport { getLogger } from '../../utils/logger.js';\n\n/**\n * Manages loading and registry of custom verifier plugins\n */\nexport class PluginLoader {\n private plugins = new Map<string, VerifierPlugin>();\n private loaded = false;\n private loadErrors: Array<{ file: string; error: string }> = [];\n private logger = getLogger({ module: 'verification.plugins.loader' });\n\n /**\n * Load all plugins from the specified base path\n *\n * @param basePath - Project root directory (usually cwd)\n */\n async loadPlugins(basePath: string): Promise<void> {\n const verifiersDir = join(basePath, '.specbridge', 'verifiers');\n\n // Check if directory exists\n if (!existsSync(verifiersDir)) {\n this.loaded = true;\n return;\n }\n\n // Find all .ts and .js files (excluding tests and .d.ts)\n const files = await fg('**/*.{ts,js}', {\n cwd: verifiersDir,\n absolute: true,\n ignore: ['**/*.test.{ts,js}', '**/*.d.ts'],\n });\n\n // Load each plugin\n for (const file of files) {\n try {\n await this.loadPlugin(file);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.loadErrors.push({ file, error: message });\n this.logger.warn({ file, error: message }, 'Failed to load plugin');\n }\n }\n\n this.loaded = true;\n\n // Log summary\n if (this.plugins.size > 0) {\n this.logger.info({ count: this.plugins.size }, 'Loaded custom verifier plugins');\n }\n if (this.loadErrors.length > 0) {\n this.logger.warn({ count: this.loadErrors.length }, 'Plugin load failures');\n }\n }\n\n /**\n * Load a single plugin file\n */\n private async loadPlugin(filePath: string): Promise<void> {\n // Convert to file URL for ESM import\n const fileUrl = pathToFileURL(filePath).href;\n\n // Dynamic import\n const module = await import(fileUrl);\n\n // Extract plugin (default export or named 'plugin' export)\n const plugin: VerifierPlugin = module.default || module.plugin;\n\n if (!plugin) {\n throw new Error('Plugin must export a default or named \"plugin\" export');\n }\n\n // Validate plugin structure\n this.validatePlugin(plugin, filePath);\n\n // Check for ID conflicts\n if (this.plugins.has(plugin.metadata.id)) {\n throw new Error(\n `Plugin ID \"${plugin.metadata.id}\" is already registered. ` +\n `Each plugin must have a unique ID.`\n );\n }\n\n // Register full plugin (not just factory) to access paramsSchema\n this.plugins.set(plugin.metadata.id, plugin);\n }\n\n /**\n * Validate plugin structure and metadata\n */\n private validatePlugin(plugin: VerifierPlugin, _filePath: string): void {\n // Check required fields\n if (!plugin.metadata) {\n throw new Error('Plugin must have a \"metadata\" property');\n }\n\n if (!plugin.metadata.id || typeof plugin.metadata.id !== 'string') {\n throw new Error('Plugin metadata must have a string \"id\" property');\n }\n\n if (!plugin.metadata.version || typeof plugin.metadata.version !== 'string') {\n throw new Error('Plugin metadata must have a string \"version\" property');\n }\n\n // Validate ID format: lowercase alphanumeric with hyphens, must start with letter\n const idPattern = /^[a-z][a-z0-9-]*$/;\n if (!idPattern.test(plugin.metadata.id)) {\n throw new Error(\n `Plugin ID \"${plugin.metadata.id}\" is invalid. ` +\n `ID must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens.`\n );\n }\n\n // Check createVerifier is a function\n if (typeof plugin.createVerifier !== 'function') {\n throw new Error('Plugin must have a \"createVerifier\" function');\n }\n\n // Test that createVerifier returns a valid Verifier\n let verifier: Verifier;\n try {\n verifier = plugin.createVerifier();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`createVerifier() threw an error: ${message}`);\n }\n\n // Validate verifier interface\n if (!verifier || typeof verifier !== 'object') {\n throw new Error('createVerifier() must return an object');\n }\n\n if (!verifier.id || typeof verifier.id !== 'string') {\n throw new Error('Verifier must have a string \"id\" property');\n }\n\n if (!verifier.name || typeof verifier.name !== 'string') {\n throw new Error('Verifier must have a string \"name\" property');\n }\n\n if (!verifier.description || typeof verifier.description !== 'string') {\n throw new Error('Verifier must have a string \"description\" property');\n }\n\n if (typeof verifier.verify !== 'function') {\n throw new Error('Verifier must have a \"verify\" method');\n }\n\n // Verify that verifier.id matches plugin.metadata.id\n if (verifier.id !== plugin.metadata.id) {\n throw new Error(\n `Verifier ID \"${verifier.id}\" does not match plugin metadata ID \"${plugin.metadata.id}\". ` +\n `These must be identical.`\n );\n }\n }\n\n /**\n * Get a verifier instance by ID\n *\n * @param id - Verifier ID\n * @returns Verifier instance or null if not found\n */\n getVerifier(id: string): Verifier | null {\n const plugin = this.plugins.get(id);\n return plugin ? plugin.createVerifier() : null;\n }\n\n /**\n * Get a plugin by ID (includes paramsSchema)\n *\n * @param id - Plugin ID\n * @returns Plugin or null if not found\n */\n getPlugin(id: string): VerifierPlugin | null {\n return this.plugins.get(id) || null;\n }\n\n /**\n * Validate params against a plugin's paramsSchema\n *\n * @param id - Plugin ID\n * @param params - Parameters to validate\n * @returns Validation result with success flag and error message if failed\n */\n validateParams(\n id: string,\n params: Record<string, unknown> | undefined\n ): { success: true } | { success: false; error: string } {\n const plugin = this.plugins.get(id);\n\n if (!plugin) {\n return { success: false, error: `Plugin ${id} not found` };\n }\n\n // If no paramsSchema is defined, params validation is not required\n if (!plugin.paramsSchema) {\n return { success: true };\n }\n\n // If paramsSchema exists but no params provided, that's an error\n if (!params) {\n return { success: false, error: `Plugin ${id} requires params but none were provided` };\n }\n\n // Validate that paramsSchema is a Zod schema\n if (\n typeof plugin.paramsSchema !== 'object' ||\n !plugin.paramsSchema ||\n !('parse' in plugin.paramsSchema)\n ) {\n return {\n success: false,\n error: `Plugin ${id} has invalid paramsSchema (must be a Zod schema)`,\n };\n }\n\n // Narrow to a parse-capable schema after validating the contract at runtime.\n const schema = plugin.paramsSchema as {\n parse: (data: unknown) => unknown;\n safeParse?: (data: unknown) => {\n success: boolean;\n error?: { issues: Array<{ message: string; path: Array<string | number> }> };\n };\n };\n\n // Use safeParse if available, otherwise catch parse errors\n if (schema.safeParse) {\n const result = schema.safeParse(params);\n if (!result.success) {\n const errors =\n result.error?.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join(', ') || 'Validation failed';\n return { success: false, error: `Invalid params for ${id}: ${errors}` };\n }\n } else {\n try {\n schema.parse(params);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { success: false, error: `Invalid params for ${id}: ${message}` };\n }\n }\n\n return { success: true };\n }\n\n /**\n * Get all registered plugin IDs\n */\n getPluginIds(): string[] {\n return Array.from(this.plugins.keys());\n }\n\n /**\n * Check if plugins have been loaded\n */\n isLoaded(): boolean {\n return this.loaded;\n }\n\n /**\n * Get load errors (for diagnostics)\n */\n getLoadErrors(): Array<{ file: string; error: string }> {\n return [...this.loadErrors];\n }\n\n /**\n * Reset the loader (useful for testing)\n */\n reset(): void {\n this.plugins.clear();\n this.loaded = false;\n this.loadErrors = [];\n }\n}\n\n/**\n * Singleton plugin loader instance\n */\nlet pluginLoader: PluginLoader | null = null;\n\n/**\n * Get the global plugin loader instance\n */\nexport function getPluginLoader(): PluginLoader {\n if (!pluginLoader) {\n pluginLoader = new PluginLoader();\n }\n return pluginLoader;\n}\n\n/**\n * Reset the global plugin loader (for testing)\n */\nexport function resetPluginLoader(): void {\n if (pluginLoader) {\n pluginLoader.reset();\n }\n pluginLoader = null;\n}\n","import pino, { type Logger as PinoLogger, type LoggerOptions } from 'pino';\n\nexport type Logger = Pick<PinoLogger, 'debug' | 'info' | 'warn' | 'error' | 'child'>;\n\nconst defaultOptions: LoggerOptions = {\n level: process.env.SPECBRIDGE_LOG_LEVEL || 'info',\n timestamp: pino.stdTimeFunctions.isoTime,\n base: {\n service: 'specbridge',\n },\n};\n\nconst destination = pino.destination({\n fd: 2, // stderr\n sync: false,\n});\n\nconst rootLogger = pino(defaultOptions, destination);\n\nexport function getLogger(bindings?: Record<string, unknown>): Logger {\n if (!bindings) {\n return rootLogger;\n }\n return rootLogger.child(bindings);\n}\n\nexport const logger = getLogger();\n","/**\n * Verifier exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './errors.js';\nexport * from './regex.js';\nexport * from './dependencies.js';\nexport * from './complexity.js';\nexport * from './security.js';\nexport * from './api.js';\n\nimport type { Verifier } from './base.js';\nimport { NamingVerifier } from './naming.js';\nimport { ImportsVerifier } from './imports.js';\nimport { ErrorsVerifier } from './errors.js';\nimport { RegexVerifier } from './regex.js';\nimport { DependencyVerifier } from './dependencies.js';\nimport { ComplexityVerifier } from './complexity.js';\nimport { SecurityVerifier } from './security.js';\nimport { ApiVerifier } from './api.js';\nimport { getPluginLoader } from '../plugins/loader.js';\n\n/**\n * Built-in verifiers registry\n */\nexport const builtinVerifiers: Record<string, () => Verifier> = {\n naming: () => new NamingVerifier(),\n imports: () => new ImportsVerifier(),\n errors: () => new ErrorsVerifier(),\n regex: () => new RegexVerifier(),\n dependencies: () => new DependencyVerifier(),\n complexity: () => new ComplexityVerifier(),\n security: () => new SecurityVerifier(),\n api: () => new ApiVerifier(),\n};\n\n/**\n * Verifier instance pool (reuse instances instead of creating new ones)\n */\nconst verifierInstances = new Map<string, Verifier>();\n\n/**\n * Get verifier by ID\n * Checks custom plugins first, then built-in verifiers\n * Instances are pooled for performance\n */\nexport function getVerifier(id: string): Verifier | null {\n // Check instance pool first\n const pooled = verifierInstances.get(id);\n if (pooled) {\n return pooled;\n }\n\n // Priority 1: Custom plugins\n const pluginLoader = getPluginLoader();\n const customVerifier = pluginLoader.getVerifier(id);\n if (customVerifier) {\n verifierInstances.set(id, customVerifier);\n return customVerifier;\n }\n\n // Priority 2: Built-in verifiers\n const factory = builtinVerifiers[id];\n if (factory) {\n const verifier = factory();\n verifierInstances.set(id, verifier);\n return verifier;\n }\n\n return null;\n}\n\n/**\n * Get all verifier IDs (built-in + plugins)\n */\nexport function getVerifierIds(): string[] {\n const builtinIds = Object.keys(builtinVerifiers);\n const pluginIds = getPluginLoader().getPluginIds();\n return [...new Set([...builtinIds, ...pluginIds])];\n}\n\n/**\n * Clear the verifier instance pool (for testing)\n */\nexport function clearVerifierPool(): void {\n verifierInstances.clear();\n}\n\n/**\n * Select appropriate verifier based on constraint\n */\nexport function selectVerifierForConstraint(\n rule: string,\n specifiedVerifier?: string,\n check?: { verifier: string; params?: Record<string, unknown> }\n): Verifier | null {\n // Priority 1: Use check block verifier if present (new structured format)\n if (check?.verifier) {\n return getVerifier(check.verifier);\n }\n\n // Priority 2: Use legacy verifier field if specified\n if (specifiedVerifier) {\n return getVerifier(specifiedVerifier);\n }\n\n // Priority 3: Auto-select based on rule content\n const lowerRule = rule.toLowerCase();\n\n if (\n lowerRule.includes('dependency') ||\n lowerRule.includes('circular dependenc') ||\n lowerRule.includes('import depth') ||\n (lowerRule.includes('layer') && lowerRule.includes('depend on'))\n ) {\n return getVerifier('dependencies');\n }\n\n if (\n lowerRule.includes('cyclomatic') ||\n lowerRule.includes('complexity') ||\n lowerRule.includes('nesting') ||\n lowerRule.includes('parameters') ||\n lowerRule.includes('file size')\n ) {\n return getVerifier('complexity');\n }\n\n if (\n lowerRule.includes('security') ||\n lowerRule.includes('secret') ||\n lowerRule.includes('password') ||\n lowerRule.includes('token') ||\n lowerRule.includes('xss') ||\n lowerRule.includes('sql') ||\n lowerRule.includes('eval')\n ) {\n return getVerifier('security');\n }\n\n if (\n lowerRule.includes('endpoint') ||\n lowerRule.includes('rest') ||\n (lowerRule.includes('api') && lowerRule.includes('path'))\n ) {\n return getVerifier('api');\n }\n\n if (lowerRule.includes('naming') || lowerRule.includes('case')) {\n return getVerifier('naming');\n }\n\n if (lowerRule.includes('import') || lowerRule.includes('barrel') || lowerRule.includes('alias')) {\n return getVerifier('imports');\n }\n\n if (lowerRule.includes('error') || lowerRule.includes('throw') || lowerRule.includes('catch')) {\n return getVerifier('errors');\n }\n\n if (lowerRule.includes('/') || lowerRule.includes('pattern') || lowerRule.includes('regex')) {\n return getVerifier('regex');\n }\n\n // Default to regex verifier for pattern-based rules\n return getVerifier('regex');\n}\n","/**\n * AST parsing cache (per VerificationEngine instance)\n * Uses content hashing for better invalidation\n */\nimport { stat, readFile } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport type { Project, SourceFile } from 'ts-morph';\n\ninterface CacheEntry {\n sourceFile: SourceFile;\n hash: string;\n mtimeMs: number;\n}\n\nexport class AstCache {\n private cache = new Map<string, CacheEntry>();\n\n async get(filePath: string, project: Project): Promise<SourceFile | null> {\n try {\n const stats = await stat(filePath);\n const cached = this.cache.get(filePath);\n\n // Quick check: mtime hasn't changed\n if (cached && cached.mtimeMs >= stats.mtimeMs) {\n return cached.sourceFile;\n }\n\n // Read and hash content\n const content = await readFile(filePath, 'utf-8');\n const hash = createHash('sha256').update(content).digest('hex');\n\n // If hash matches, update mtime but keep AST\n if (cached && cached.hash === hash) {\n cached.mtimeMs = stats.mtimeMs;\n return cached.sourceFile;\n }\n\n // Re-parse: content has changed\n let sourceFile = project.getSourceFile(filePath);\n if (!sourceFile) {\n sourceFile = project.addSourceFileAtPath(filePath);\n } else {\n // Refresh from disk if the file changed\n sourceFile.refreshFromFileSystemSync();\n }\n\n this.cache.set(filePath, {\n sourceFile,\n hash,\n mtimeMs: stats.mtimeMs,\n });\n\n return sourceFile;\n } catch {\n return null;\n }\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n getStats() {\n return {\n entries: this.cache.size,\n memoryEstimate: this.cache.size * 50000, // Rough estimate: 50KB per AST\n };\n }\n}\n","/**\n * Results cache - Caches verification results by file hash + constraint\n *\n * Avoids re-running verifiers on unchanged files\n */\nimport type { Violation } from '../core/types/index.js';\n\nexport interface CacheKey {\n filePath: string;\n decisionId: string;\n constraintId: string;\n fileHash: string;\n}\n\n/**\n * Cache for verification results\n * Results are keyed by file path + decision + constraint + file hash\n */\nexport class ResultsCache {\n private cache = new Map<string, Violation[]>();\n\n /**\n * Generate cache key from components\n */\n private getCacheKey(key: CacheKey): string {\n return `${key.filePath}:${key.decisionId}:${key.constraintId}:${key.fileHash}`;\n }\n\n /**\n * Get cached violations for a specific verification\n *\n * @returns Violations if cached, null if not found\n */\n get(key: CacheKey): Violation[] | null {\n const cacheKey = this.getCacheKey(key);\n return this.cache.get(cacheKey) || null;\n }\n\n /**\n * Store verification results in cache\n */\n set(key: CacheKey, violations: Violation[]): void {\n const cacheKey = this.getCacheKey(key);\n this.cache.set(cacheKey, violations);\n }\n\n /**\n * Check if result is cached\n */\n has(key: CacheKey): boolean {\n const cacheKey = this.getCacheKey(key);\n return this.cache.has(cacheKey);\n }\n\n /**\n * Clear entire cache\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Clear cache entries for a specific file\n */\n clearFile(filePath: string): void {\n for (const key of this.cache.keys()) {\n if (key.startsWith(`${filePath}:`)) {\n this.cache.delete(key);\n }\n }\n }\n\n /**\n * Clear cache entries for a specific decision\n */\n clearDecision(decisionId: string): void {\n for (const key of this.cache.keys()) {\n if (key.includes(`:${decisionId}:`)) {\n this.cache.delete(key);\n }\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats() {\n return {\n entries: this.cache.size,\n memoryEstimate: this.cache.size * 1000, // Rough estimate: 1KB per result\n };\n }\n}\n","/**\n * Shared constraint applicability helpers\n */\nimport type { Constraint, Severity } from '../core/types/index.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport function isConstraintExcepted(\n filePath: string,\n constraint: Constraint,\n cwd: string\n): boolean {\n if (!constraint.exceptions) return false;\n\n return constraint.exceptions.some((exception) => {\n // Check if exception has expired\n if (exception.expiresAt) {\n const expiryDate = new Date(exception.expiresAt);\n if (expiryDate < new Date()) {\n return false;\n }\n }\n\n return matchesPattern(filePath, exception.pattern, { cwd });\n });\n}\n\nexport function shouldApplyConstraintToFile(params: {\n filePath: string;\n constraint: Constraint;\n cwd: string;\n severityFilter?: Severity[];\n}): boolean {\n const { filePath, constraint, cwd, severityFilter } = params;\n\n if (!matchesPattern(filePath, constraint.scope, { cwd })) return false;\n if (severityFilter && !severityFilter.includes(constraint.severity)) return false;\n if (isConstraintExcepted(filePath, constraint, cwd)) return false;\n\n return true;\n}\n","/**\n * Incremental verification helpers\n */\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { resolve } from 'node:path';\nimport { pathExists } from '../utils/fs.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport async function getChangedFiles(cwd: string): Promise<string[]> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['diff', '--name-only', '--diff-filter=AM', 'HEAD'],\n { cwd }\n );\n const rel = stdout\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean);\n\n const abs: string[] = [];\n for (const file of rel) {\n const full = resolve(cwd, file);\n if (await pathExists(full)) abs.push(full);\n }\n return abs;\n } catch {\n return [];\n }\n}\n","/**\n * Explain Reporter - Provides detailed explanation of verification process\n */\nimport chalk from 'chalk';\nimport type { Decision, Constraint } from '../core/types/index.js';\n\n/**\n * Entry in the explanation trace\n */\nexport interface ExplanationEntry {\n file: string;\n decision: Decision;\n constraint: Constraint;\n applied: boolean;\n reason: string;\n selectedVerifier?: string;\n verifierOutput?: {\n violations: number;\n duration: number;\n error?: string;\n };\n}\n\n/**\n * Reporter for --explain mode\n */\nexport class ExplainReporter {\n private entries: ExplanationEntry[] = [];\n\n /**\n * Add an entry to the explanation trace\n */\n add(entry: ExplanationEntry): void {\n this.entries.push(entry);\n }\n\n /**\n * Print the explanation trace\n */\n print(): void {\n if (this.entries.length === 0) {\n console.log(chalk.dim('No constraints were evaluated.'));\n return;\n }\n\n console.log(chalk.bold('\\n=== Verification Explanation ===\\n'));\n\n // Group by file\n const byFile = new Map<string, ExplanationEntry[]>();\n for (const entry of this.entries) {\n const existing = byFile.get(entry.file) || [];\n existing.push(entry);\n byFile.set(entry.file, existing);\n }\n\n // Print grouped by file\n for (const [file, entries] of byFile) {\n console.log(chalk.underline(file));\n\n for (const entry of entries) {\n const icon = entry.applied ? chalk.green('✓') : chalk.dim('⊘');\n const constraintId = `${entry.decision.metadata.id}/${entry.constraint.id}`;\n\n console.log(` ${icon} ${constraintId}`);\n console.log(chalk.dim(` ${entry.reason}`));\n\n if (entry.applied && entry.selectedVerifier) {\n console.log(chalk.dim(` Verifier: ${entry.selectedVerifier}`));\n\n if (entry.verifierOutput) {\n if (entry.verifierOutput.error) {\n console.log(chalk.red(` Error: ${entry.verifierOutput.error}`));\n } else {\n const violationText =\n entry.verifierOutput.violations === 1\n ? '1 violation'\n : `${entry.verifierOutput.violations} violations`;\n const resultColor = entry.verifierOutput.violations > 0 ? chalk.red : chalk.green;\n console.log(\n chalk.dim(` Result: `) +\n resultColor(violationText) +\n chalk.dim(` in ${entry.verifierOutput.duration}ms`)\n );\n }\n }\n }\n\n console.log('');\n }\n }\n\n // Summary\n const applied = this.entries.filter((e) => e.applied).length;\n const skipped = this.entries.filter((e) => !e.applied).length;\n\n console.log(chalk.bold('Summary:'));\n console.log(` Constraints Applied: ${chalk.green(applied)}`);\n console.log(` Constraints Skipped: ${chalk.dim(skipped)}`);\n }\n\n /**\n * Get all entries\n */\n getEntries(): ExplanationEntry[] {\n return [...this.entries];\n }\n\n /**\n * Clear all entries\n */\n clear(): void {\n this.entries = [];\n }\n}\n","/**\n * Auto-fix engine\n */\nimport { readFile, writeFile } from 'node:fs/promises';\nimport readline from 'node:readline/promises';\nimport { stdin, stdout } from 'node:process';\nimport type { Violation, TextEdit } from '../../core/types/index.js';\n\nexport interface AutofixPatch {\n filePath: string;\n description: string;\n start: number;\n end: number;\n originalText: string;\n fixedText: string;\n}\n\nexport interface AutofixResult {\n applied: AutofixPatch[];\n skipped: number;\n}\n\ntype DescribedEdit = TextEdit & { description: string };\n\nfunction applyEdits(\n content: string,\n edits: DescribedEdit[]\n): { next: string; patches: AutofixPatch[]; skippedEdits: number } {\n const sorted = [...edits].sort((a, b) => b.start - a.start);\n\n let next = content;\n const patches: AutofixPatch[] = [];\n let skippedEdits = 0;\n let lastStart = Number.POSITIVE_INFINITY;\n\n for (const edit of sorted) {\n if (edit.start < 0 || edit.end < edit.start || edit.end > next.length) {\n skippedEdits++;\n continue;\n }\n\n // Overlap check (since edits are sorted by start descending)\n if (edit.end > lastStart) {\n skippedEdits++;\n continue;\n }\n lastStart = edit.start;\n\n const originalText = next.slice(edit.start, edit.end);\n next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);\n\n patches.push({\n filePath: '',\n description: edit.description,\n start: edit.start,\n end: edit.end,\n originalText,\n fixedText: edit.text,\n });\n }\n\n return { next, patches, skippedEdits };\n}\n\nasync function confirmFix(prompt: string): Promise<boolean> {\n const rl = readline.createInterface({ input: stdin, output: stdout });\n try {\n const answer = await rl.question(`${prompt} (y/N) `);\n return answer.trim().toLowerCase() === 'y';\n } finally {\n rl.close();\n }\n}\n\nexport class AutofixEngine {\n async applyFixes(\n violations: Violation[],\n options: { dryRun?: boolean; interactive?: boolean } = {}\n ): Promise<AutofixResult> {\n const fixable = violations.filter((v) => v.autofix && v.autofix.edits.length > 0);\n const byFile = new Map<string, Violation[]>();\n for (const v of fixable) {\n const list = byFile.get(v.file) ?? [];\n list.push(v);\n byFile.set(v.file, list);\n }\n\n const applied: AutofixPatch[] = [];\n let skippedViolations = 0;\n\n for (const [filePath, fileViolations] of byFile) {\n const original = await readFile(filePath, 'utf-8');\n\n const edits: DescribedEdit[] = [];\n for (const violation of fileViolations) {\n const fix = violation.autofix;\n if (!fix) {\n skippedViolations++;\n continue;\n }\n if (options.interactive) {\n const ok = await confirmFix(\n `Apply fix: ${fix.description} (${filePath}:${violation.line ?? 1})?`\n );\n if (!ok) {\n skippedViolations++;\n continue;\n }\n }\n for (const edit of fix.edits) {\n edits.push({ ...edit, description: fix.description });\n }\n }\n\n if (edits.length === 0) continue;\n\n const { next, patches, skippedEdits } = applyEdits(original, edits);\n skippedViolations += skippedEdits;\n\n if (!options.dryRun) {\n await writeFile(filePath, next, 'utf-8');\n }\n\n for (const patch of patches) {\n applied.push({ ...patch, filePath });\n }\n }\n\n return { applied, skipped: skippedViolations };\n }\n}\n","/**\n * Dependency graph for impact analysis\n */\nimport type { Decision } from '../core/types/index.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface GraphNode {\n type: 'decision' | 'constraint' | 'file';\n id: string;\n edges: string[];\n}\n\nexport interface DependencyGraph {\n nodes: Map<string, GraphNode>;\n decisionToFiles: Map<string, Set<string>>;\n fileToDecisions: Map<string, Set<string>>;\n}\n\nexport interface BuildDependencyGraphOptions {\n cwd?: string;\n}\n\n/**\n * Build dependency graph from decisions and file list\n */\nexport async function buildDependencyGraph(\n decisions: Decision[],\n files: string[],\n options: BuildDependencyGraphOptions = {}\n): Promise<DependencyGraph> {\n const { cwd } = options;\n const nodes = new Map<string, GraphNode>();\n const decisionToFiles = new Map<string, Set<string>>();\n const fileToDecisions = new Map<string, Set<string>>();\n\n // Add decision nodes\n for (const decision of decisions) {\n const decisionId = `decision:${decision.metadata.id}`;\n nodes.set(decisionId, {\n type: 'decision',\n id: decision.metadata.id,\n edges: decision.constraints.map((c) => `constraint:${decision.metadata.id}/${c.id}`),\n });\n\n // Add constraint nodes\n for (const constraint of decision.constraints) {\n const constraintId = `constraint:${decision.metadata.id}/${constraint.id}`;\n const matchingFiles: string[] = [];\n\n for (const file of files) {\n if (matchesPattern(file, constraint.scope, { cwd })) {\n matchingFiles.push(`file:${file}`);\n\n // Update file -> decision mapping\n const fileDecisions = fileToDecisions.get(file) || new Set();\n fileDecisions.add(decision.metadata.id);\n fileToDecisions.set(file, fileDecisions);\n\n // Update decision -> files mapping\n const decFiles = decisionToFiles.get(decision.metadata.id) || new Set();\n decFiles.add(file);\n decisionToFiles.set(decision.metadata.id, decFiles);\n }\n }\n\n nodes.set(constraintId, {\n type: 'constraint',\n id: `${decision.metadata.id}/${constraint.id}`,\n edges: matchingFiles,\n });\n }\n }\n\n // Add file nodes\n for (const file of files) {\n const fileId = `file:${file}`;\n if (!nodes.has(fileId)) {\n nodes.set(fileId, {\n type: 'file',\n id: file,\n edges: [],\n });\n }\n }\n\n return {\n nodes,\n decisionToFiles,\n fileToDecisions,\n };\n}\n\n/**\n * Get files affected by a decision\n */\nexport function getAffectedFiles(graph: DependencyGraph, decisionId: string): string[] {\n const files = graph.decisionToFiles.get(decisionId);\n return files ? Array.from(files) : [];\n}\n\n/**\n * Get decisions affecting a file\n */\nexport function getAffectingDecisions(graph: DependencyGraph, filePath: string): string[] {\n const decisions = graph.fileToDecisions.get(filePath);\n return decisions ? Array.from(decisions) : [];\n}\n\n/**\n * Calculate transitive closure for a node\n */\nexport function getTransitiveDependencies(\n graph: DependencyGraph,\n nodeId: string,\n visited: Set<string> = new Set()\n): string[] {\n if (visited.has(nodeId)) {\n return [];\n }\n\n visited.add(nodeId);\n const node = graph.nodes.get(nodeId);\n\n if (!node) {\n return [];\n }\n\n const deps: string[] = [nodeId];\n\n for (const edge of node.edges) {\n deps.push(...getTransitiveDependencies(graph, edge, visited));\n }\n\n return deps;\n}\n","/**\n * Propagation Engine - Analyze impact of decision changes\n */\nimport type {\n ImpactAnalysis,\n AffectedFile,\n MigrationStep,\n SpecBridgeConfig,\n} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { createVerificationEngine } from '../verification/engine.js';\nimport { buildDependencyGraph, getAffectedFiles, type DependencyGraph } from './graph.js';\nimport { glob } from '../utils/glob.js';\n\nexport interface PropagationOptions {\n cwd?: string;\n}\n\n/**\n * Propagation Engine class\n */\nexport class PropagationEngine {\n private registry: Registry;\n private graph: DependencyGraph | null = null;\n\n constructor(registry?: Registry) {\n this.registry = registry || createRegistry();\n }\n\n /**\n * Initialize the engine with current state\n */\n async initialize(config: SpecBridgeConfig, options: PropagationOptions = {}): Promise<void> {\n const { cwd = process.cwd() } = options;\n\n // Load registry\n await this.registry.load();\n\n // Get all files\n const files = await glob(config.project.sourceRoots, {\n cwd,\n ignore: config.project.exclude,\n absolute: true,\n });\n\n // Build dependency graph\n const decisions = this.registry.getActive();\n this.graph = await buildDependencyGraph(decisions, files, { cwd });\n }\n\n /**\n * Analyze impact of changing a decision\n */\n async analyzeImpact(\n decisionId: string,\n change: 'created' | 'modified' | 'deprecated',\n config: SpecBridgeConfig,\n options: PropagationOptions = {}\n ): Promise<ImpactAnalysis> {\n const { cwd = process.cwd() } = options;\n\n // Ensure initialized\n if (!this.graph) {\n await this.initialize(config, options);\n }\n const graph = this.graph;\n if (!graph) {\n return {\n decision: decisionId,\n change,\n affectedFiles: [],\n estimatedEffort: 'low',\n migrationSteps: [\n {\n order: 1,\n description: 'Run verification to confirm all violations resolved',\n files: [],\n automated: true,\n },\n ],\n };\n }\n\n // Get affected files\n const affectedFilePaths = getAffectedFiles(graph, decisionId);\n\n // Run verification on affected files\n const verificationEngine = createVerificationEngine(this.registry);\n const result = await verificationEngine.verify(config, {\n files: affectedFilePaths,\n decisions: [decisionId],\n cwd,\n });\n\n // Group violations by file\n const fileViolations = new Map<string, { total: number; autoFixable: number }>();\n for (const violation of result.violations) {\n const existing = fileViolations.get(violation.file) || { total: 0, autoFixable: 0 };\n existing.total++;\n if (violation.autofix) {\n existing.autoFixable++;\n }\n fileViolations.set(violation.file, existing);\n }\n\n // Build affected files list\n const affectedFiles: AffectedFile[] = affectedFilePaths.map((path) => ({\n path,\n violations: fileViolations.get(path)?.total || 0,\n autoFixable: fileViolations.get(path)?.autoFixable || 0,\n }));\n\n // Sort by violations (most first)\n affectedFiles.sort((a, b) => b.violations - a.violations);\n\n // Estimate effort\n const totalViolations = result.violations.length;\n const totalAutoFixable = result.violations.filter((v) => v.autofix).length;\n const manualFixes = totalViolations - totalAutoFixable;\n\n let estimatedEffort: 'low' | 'medium' | 'high';\n if (manualFixes === 0) {\n estimatedEffort = 'low';\n } else if (manualFixes <= 10) {\n estimatedEffort = 'medium';\n } else {\n estimatedEffort = 'high';\n }\n\n // Generate migration steps\n const migrationSteps = this.generateMigrationSteps(affectedFiles, totalAutoFixable > 0);\n\n return {\n decision: decisionId,\n change,\n affectedFiles,\n estimatedEffort,\n migrationSteps,\n };\n }\n\n /**\n * Generate migration steps\n */\n private generateMigrationSteps(\n affectedFiles: AffectedFile[],\n hasAutoFixes: boolean\n ): MigrationStep[] {\n const steps: MigrationStep[] = [];\n let order = 1;\n\n // Step 1: Run auto-fixes if available\n if (hasAutoFixes) {\n steps.push({\n order: order++,\n description: 'Run auto-fix for mechanical violations',\n files: affectedFiles.filter((f) => f.autoFixable > 0).map((f) => f.path),\n automated: true,\n });\n }\n\n // Step 2: Manual fixes for remaining violations\n const filesWithManualFixes = affectedFiles.filter((f) => f.violations > f.autoFixable);\n\n if (filesWithManualFixes.length > 0) {\n // Group by severity/priority\n const highPriority = filesWithManualFixes.filter((f) => f.violations > 5);\n const mediumPriority = filesWithManualFixes.filter(\n (f) => f.violations <= 5 && f.violations > 1\n );\n const lowPriority = filesWithManualFixes.filter((f) => f.violations === 1);\n\n if (highPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix high-violation files first',\n files: highPriority.map((f) => f.path),\n automated: false,\n });\n }\n\n if (mediumPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix medium-violation files',\n files: mediumPriority.map((f) => f.path),\n automated: false,\n });\n }\n\n if (lowPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix remaining files',\n files: lowPriority.map((f) => f.path),\n automated: false,\n });\n }\n }\n\n // Step 3: Verification\n steps.push({\n order: order++,\n description: 'Run verification to confirm all violations resolved',\n files: [],\n automated: true,\n });\n\n return steps;\n }\n\n /**\n * Get dependency graph\n */\n getGraph(): DependencyGraph | null {\n return this.graph;\n }\n}\n\n/**\n * Create propagation engine\n */\nexport function createPropagationEngine(registry?: Registry): PropagationEngine {\n return new PropagationEngine(registry);\n}\n","/**\n * Compliance reporter\n */\nimport type {\n ComplianceReport,\n DecisionCompliance,\n SpecBridgeConfig,\n Violation,\n} from '../core/types/index.js';\nimport type { VerificationRunResult } from '../core/types/verification-contracts.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { createVerificationEngine } from '../verification/engine.js';\n\nexport interface ReportOptions {\n includeAll?: boolean;\n cwd?: string;\n /** Use v1.3 compliance formula instead of v2.0 severity-weighted formula */\n legacyCompliance?: boolean;\n}\n\n/**\n * Generic verification result shape for Reporter class\n * Supports various result formats from different verification engines\n */\nexport interface ReporterResult extends Partial<VerificationRunResult> {\n summary?: {\n totalViolations?: number;\n decisionsChecked?: number;\n filesChecked?: number;\n critical?: number;\n high?: number;\n medium?: number;\n low?: number;\n duration?: number;\n };\n}\n\n/**\n * Generate a compliance report\n */\nexport async function generateReport(\n config: SpecBridgeConfig,\n options: ReportOptions = {}\n): Promise<ComplianceReport> {\n const { includeAll = false, cwd = process.cwd() } = options;\n\n // Load registry\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n\n // Run full verification\n const engine = createVerificationEngine(registry);\n const result = await engine.verify(config, { level: 'full', cwd });\n\n // Get all decisions\n const decisions = includeAll ? registry.getAll() : registry.getActive();\n\n // Calculate per-decision compliance\n const byDecision: DecisionCompliance[] = [];\n\n for (const decision of decisions) {\n const decisionViolations = result.violations.filter(\n (v) => v.decisionId === decision.metadata.id\n );\n\n const constraintCount = decision.constraints.length;\n const violationCount = decisionViolations.length;\n\n // Calculate compliance based on mode\n let compliance: number;\n let violationsBySeverity: DecisionCompliance['violationsBySeverity'];\n let weightedScore: number | undefined;\n let coverageRate: number | undefined;\n\n if (options.legacyCompliance) {\n // v1.3 formula: Simple count-based\n compliance =\n violationCount === 0 ? 100 : Math.max(0, 100 - Math.min(violationCount * 10, 100));\n } else {\n // v2.0 formula: Severity-weighted with coverage penalty\n const weights = { critical: 40, high: 25, medium: 10, low: 2 };\n\n // Count violations by severity\n const bySeverity = {\n critical: decisionViolations.filter((v) => v.severity === 'critical').length,\n high: decisionViolations.filter((v) => v.severity === 'high').length,\n medium: decisionViolations.filter((v) => v.severity === 'medium').length,\n low: decisionViolations.filter((v) => v.severity === 'low').length,\n };\n\n // Calculate weighted score\n weightedScore = decisionViolations.reduce((score, v) => score + weights[v.severity], 0);\n\n // Base compliance\n compliance = Math.max(0, 100 - weightedScore);\n\n // Apply coverage penalty (up to 20% reduction)\n if (decisionViolations.length > 0 && constraintCount > 0) {\n const violationRate = decisionViolations.length / constraintCount;\n compliance = compliance * (1 - violationRate * 0.2);\n coverageRate = violationRate;\n }\n\n compliance = Math.round(compliance);\n violationsBySeverity = bySeverity;\n }\n\n byDecision.push({\n decisionId: decision.metadata.id,\n title: decision.metadata.title,\n status: decision.metadata.status,\n constraints: constraintCount,\n violations: violationCount,\n compliance,\n violationsBySeverity,\n weightedScore,\n coverageRate,\n });\n }\n\n // Sort by compliance (lowest first to highlight problems)\n byDecision.sort((a, b) => a.compliance - b.compliance);\n\n // Calculate summary\n const totalDecisions = decisions.length;\n const activeDecisions = decisions.filter((d) => d.metadata.status === 'active').length;\n const totalConstraints = decisions.reduce((sum, d) => sum + d.constraints.length, 0);\n\n const violationsBySeverity = {\n critical: result.violations.filter((v) => v.severity === 'critical').length,\n high: result.violations.filter((v) => v.severity === 'high').length,\n medium: result.violations.filter((v) => v.severity === 'medium').length,\n low: result.violations.filter((v) => v.severity === 'low').length,\n };\n\n // Overall compliance score\n const overallCompliance =\n byDecision.length > 0\n ? Math.round(byDecision.reduce((sum, d) => sum + d.compliance, 0) / byDecision.length)\n : 100;\n\n return {\n timestamp: new Date().toISOString(),\n project: config.project.name,\n summary: {\n totalDecisions,\n activeDecisions,\n totalConstraints,\n violations: violationsBySeverity,\n compliance: overallCompliance,\n },\n byDecision,\n };\n}\n\n/**\n * Check if compliance has degraded from previous report\n */\nexport function checkDegradation(\n current: ComplianceReport,\n previous: ComplianceReport | null\n): { degraded: boolean; details: string[] } {\n if (!previous) {\n return { degraded: false, details: [] };\n }\n\n const details: string[] = [];\n let degraded = false;\n\n // Check overall compliance\n if (current.summary.compliance < previous.summary.compliance) {\n degraded = true;\n details.push(\n `Overall compliance dropped from ${previous.summary.compliance}% to ${current.summary.compliance}%`\n );\n }\n\n // Check for new critical/high violations\n const newCritical = current.summary.violations.critical - previous.summary.violations.critical;\n const newHigh = current.summary.violations.high - previous.summary.violations.high;\n\n if (newCritical > 0) {\n degraded = true;\n details.push(`${newCritical} new critical violation(s)`);\n }\n\n if (newHigh > 0) {\n degraded = true;\n details.push(`${newHigh} new high severity violation(s)`);\n }\n\n return { degraded, details };\n}\n\n/**\n * Reporter class for formatting verification results\n */\nexport class Reporter {\n /**\n * Generate formatted report from verification result\n */\n generate(\n result: ReporterResult,\n options: {\n format?: 'table' | 'json' | 'markdown';\n includePassedChecks?: boolean;\n groupBy?: 'severity' | 'file';\n colorize?: boolean;\n } = {}\n ): string {\n const { format = 'table', groupBy } = options;\n\n switch (format) {\n case 'json':\n return JSON.stringify(result, null, 2);\n\n case 'markdown':\n return this.formatAsMarkdown(result);\n\n case 'table':\n default:\n return groupBy ? this.formatAsTableGrouped(result, groupBy) : this.formatAsTable(result);\n }\n }\n\n /**\n * Generate compliance overview from multiple results\n */\n generateComplianceReport(results: ReporterResult[]): string {\n const lines: string[] = [];\n lines.push('# Compliance Report\\n');\n\n if (results.length === 0) {\n lines.push('No results to report.\\n');\n return lines.join('\\n');\n }\n\n // Calculate overall stats\n const totalViolations = results.reduce(\n (sum, r) => sum + (r.summary?.totalViolations || r.violations?.length || 0),\n 0\n );\n const avgViolations = totalViolations / results.length;\n\n lines.push(`## Overall Statistics\\n`);\n lines.push(`- Total Results: ${results.length}`);\n lines.push(`- Total Violations: ${totalViolations}`);\n lines.push(`- Average Violations per Result: ${avgViolations.toFixed(1)}`);\n\n // Calculate compliance percentage (simplified)\n const complianceRate =\n results.length > 0\n ? (results.filter((r) => (r.violations?.length || 0) === 0).length / results.length) * 100\n : 100;\n lines.push(`- Compliance Rate: ${complianceRate.toFixed(1)}%\\n`);\n\n return lines.join('\\n');\n }\n\n private formatAsTable(result: ReporterResult): string {\n const lines: string[] = [];\n\n lines.push('Verification Report');\n lines.push('='.repeat(50));\n lines.push('');\n\n // Summary\n if (result.summary) {\n lines.push('Summary:');\n lines.push(` Decisions Checked: ${result.summary.decisionsChecked || 0}`);\n lines.push(` Files Checked: ${result.summary.filesChecked || 0}`);\n lines.push(\n ` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`\n );\n lines.push(` Critical: ${result.summary.critical || 0}`);\n lines.push(` High: ${result.summary.high || 0}`);\n lines.push(` Medium: ${result.summary.medium || 0}`);\n lines.push(` Low: ${result.summary.low || 0}`);\n lines.push(` Duration: ${result.summary.duration || 0}ms`);\n lines.push('');\n }\n\n // Violations\n const totalViolations = result.summary?.totalViolations ?? result.violations?.length ?? 0;\n if (totalViolations > 0 && result.violations && result.violations.length > 0) {\n lines.push('Violations:');\n lines.push('-'.repeat(50));\n\n result.violations.forEach((v: Violation) => {\n const severity = v.severity.toLowerCase();\n lines.push(\n ` [${v.severity.toUpperCase()}] ${v.decisionId} - ${v.constraintId} (${severity})`\n );\n lines.push(` ${v.message}`);\n const file = (v as { location?: { file: string } }).location?.file || v.file;\n const line = (v as { location?: { line?: number } }).location?.line || v.line || 0;\n const column = (v as { location?: { column?: number } }).location?.column || v.column || 0;\n lines.push(` Location: ${file}:${line}:${column}`);\n lines.push('');\n });\n } else {\n lines.push('No violations found.');\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private formatAsTableGrouped(result: ReporterResult, groupBy: 'severity' | 'file'): string {\n const lines: string[] = [];\n\n lines.push('Verification Report');\n lines.push('='.repeat(50));\n lines.push('');\n\n // Summary\n if (result.summary) {\n lines.push('Summary:');\n lines.push(\n ` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`\n );\n lines.push('');\n }\n\n // Group violations\n if (result.violations && result.violations.length > 0) {\n if (groupBy === 'severity') {\n const grouped = new Map<string, Violation[]>();\n result.violations.forEach((v: Violation) => {\n const key = v.severity;\n if (!grouped.has(key)) grouped.set(key, []);\n const bucket = grouped.get(key);\n if (bucket) {\n bucket.push(v);\n }\n });\n\n for (const [severity, violations] of grouped.entries()) {\n lines.push(`Severity: ${severity}`);\n lines.push('-'.repeat(30));\n violations.forEach((v) => {\n lines.push(` ${v.decisionId} - ${v.message}`);\n });\n lines.push('');\n }\n } else if (groupBy === 'file') {\n const grouped = new Map<string, Violation[]>();\n result.violations.forEach((v: Violation) => {\n const key = (v as { location?: { file: string } }).location?.file || v.file || 'unknown';\n if (!grouped.has(key)) grouped.set(key, []);\n const bucket = grouped.get(key);\n if (bucket) {\n bucket.push(v);\n }\n });\n\n for (const [file, violations] of grouped.entries()) {\n lines.push(`File: ${file}`);\n lines.push('-'.repeat(30));\n violations.forEach((v) => {\n lines.push(` [${v.severity}] ${v.message}`);\n });\n lines.push('');\n }\n }\n } else {\n lines.push('No violations found.');\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private formatAsMarkdown(result: ReporterResult): string {\n const lines: string[] = [];\n\n lines.push('## Verification Report\\n');\n\n // Summary\n if (result.summary) {\n lines.push('### Summary\\n');\n lines.push(`- **Decisions Checked:** ${result.summary.decisionsChecked || 0}`);\n lines.push(`- **Files Checked:** ${result.summary.filesChecked || 0}`);\n lines.push(\n `- **Total Violations:** ${result.summary.totalViolations || result.violations?.length || 0}`\n );\n lines.push(`- **Critical:** ${result.summary.critical || 0}`);\n lines.push(`- **High:** ${result.summary.high || 0}`);\n lines.push(`- **Medium:** ${result.summary.medium || 0}`);\n lines.push(`- **Low:** ${result.summary.low || 0}\\n`);\n }\n\n // Violations\n if (result.violations && result.violations.length > 0) {\n lines.push('### Violations\\n');\n\n result.violations.forEach((v: Violation) => {\n lines.push(`#### [${v.severity.toUpperCase()}] ${v.decisionId}`);\n lines.push(`**Message:** ${v.message}`);\n const file = (v as { location?: { file: string } }).location?.file || v.file;\n const line = (v as { location?: { line?: number } }).location?.line || v.line || 0;\n lines.push(`**Location:** \\`${file}:${line}\\`\\n`);\n });\n } else {\n lines.push('No violations found.\\n');\n }\n\n return lines.join('\\n');\n }\n}\n","/**\n * Console output format for reports\n */\nimport chalk from 'chalk';\nimport { table } from 'table';\nimport type { ComplianceReport } from '../../core/types/index.js';\n\n/**\n * Format report for console output\n */\nexport function formatConsoleReport(report: ComplianceReport): string {\n const lines: string[] = [];\n\n // Header\n lines.push('');\n lines.push(chalk.bold.blue('SpecBridge Compliance Report'));\n lines.push(chalk.dim(`Generated: ${new Date(report.timestamp).toLocaleString()}`));\n lines.push(chalk.dim(`Project: ${report.project}`));\n lines.push('');\n\n // Overall compliance\n const complianceColor = getComplianceColor(report.summary.compliance);\n lines.push(chalk.bold('Overall Compliance'));\n lines.push(\n ` ${complianceColor(formatComplianceBar(report.summary.compliance))} ${complianceColor(`${report.summary.compliance}%`)}`\n );\n lines.push('');\n\n // Summary stats\n lines.push(chalk.bold('Summary'));\n lines.push(\n ` Decisions: ${report.summary.activeDecisions} active / ${report.summary.totalDecisions} total`\n );\n lines.push(` Constraints: ${report.summary.totalConstraints}`);\n lines.push('');\n\n // Violations\n lines.push(chalk.bold('Violations'));\n const { violations } = report.summary;\n const violationParts: string[] = [];\n\n if (violations.critical > 0) {\n violationParts.push(chalk.red(`${violations.critical} critical`));\n }\n if (violations.high > 0) {\n violationParts.push(chalk.yellow(`${violations.high} high`));\n }\n if (violations.medium > 0) {\n violationParts.push(chalk.cyan(`${violations.medium} medium`));\n }\n if (violations.low > 0) {\n violationParts.push(chalk.dim(`${violations.low} low`));\n }\n\n if (violationParts.length > 0) {\n lines.push(` ${violationParts.join(' | ')}`);\n } else {\n lines.push(chalk.green(' No violations'));\n }\n lines.push('');\n\n // Per-decision breakdown\n if (report.byDecision.length > 0) {\n lines.push(chalk.bold('By Decision'));\n lines.push('');\n\n const tableData: string[][] = [\n [\n chalk.bold('Decision'),\n chalk.bold('Status'),\n chalk.bold('Constraints'),\n chalk.bold('Violations'),\n chalk.bold('Compliance'),\n ],\n ];\n\n for (const dec of report.byDecision) {\n const compColor = getComplianceColor(dec.compliance);\n const statusColor = getStatusColor(dec.status);\n\n tableData.push([\n truncate(dec.title, 40),\n statusColor(dec.status),\n String(dec.constraints),\n dec.violations > 0 ? chalk.red(String(dec.violations)) : chalk.green('0'),\n compColor(`${dec.compliance}%`),\n ]);\n }\n\n const tableOutput = table(tableData, {\n border: {\n topBody: '',\n topJoin: '',\n topLeft: '',\n topRight: '',\n bottomBody: '',\n bottomJoin: '',\n bottomLeft: '',\n bottomRight: '',\n bodyLeft: ' ',\n bodyRight: '',\n bodyJoin: ' ',\n joinBody: '',\n joinLeft: '',\n joinRight: '',\n joinJoin: '',\n },\n drawHorizontalLine: (index) => index === 1,\n });\n\n lines.push(tableOutput);\n }\n\n return lines.join('\\n');\n}\n\nfunction formatComplianceBar(compliance: number): string {\n const filled = Math.round(compliance / 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n}\n\nfunction getComplianceColor(compliance: number): (text: string) => string {\n if (compliance >= 90) return chalk.green;\n if (compliance >= 70) return chalk.yellow;\n if (compliance >= 50) return chalk.hex('#FFA500');\n return chalk.red;\n}\n\nfunction getStatusColor(status: string): (text: string) => string {\n switch (status) {\n case 'active':\n return chalk.green;\n case 'draft':\n return chalk.yellow;\n case 'deprecated':\n return chalk.gray;\n case 'superseded':\n return chalk.blue;\n default:\n return chalk.white;\n }\n}\n\nfunction truncate(str: string, length: number): string {\n if (str.length <= length) return str;\n return str.slice(0, length - 3) + '...';\n}\n","/**\n * Markdown format for reports\n */\nimport type { ComplianceReport } from '../../core/types/index.js';\n\n/**\n * Format report as Markdown\n */\nexport function formatMarkdownReport(report: ComplianceReport): string {\n const lines: string[] = [];\n\n // Header\n lines.push('# SpecBridge Compliance Report');\n lines.push('');\n lines.push(`**Project:** ${report.project}`);\n lines.push(`**Generated:** ${new Date(report.timestamp).toLocaleString()}`);\n lines.push('');\n\n // Overall compliance\n lines.push('## Overall Compliance');\n lines.push('');\n lines.push(`**Score:** ${report.summary.compliance}%`);\n lines.push('');\n lines.push(formatProgressBar(report.summary.compliance));\n lines.push('');\n\n // Summary\n lines.push('## Summary');\n lines.push('');\n lines.push(\n `- **Active Decisions:** ${report.summary.activeDecisions} / ${report.summary.totalDecisions}`\n );\n lines.push(`- **Total Constraints:** ${report.summary.totalConstraints}`);\n lines.push('');\n\n // Violations\n lines.push('### Violations');\n lines.push('');\n const { violations } = report.summary;\n const totalViolations =\n violations.critical + violations.high + violations.medium + violations.low;\n\n if (totalViolations === 0) {\n lines.push('No violations found.');\n } else {\n lines.push(`| Severity | Count |`);\n lines.push(`|----------|-------|`);\n lines.push(`| Critical | ${violations.critical} |`);\n lines.push(`| High | ${violations.high} |`);\n lines.push(`| Medium | ${violations.medium} |`);\n lines.push(`| Low | ${violations.low} |`);\n lines.push(`| **Total** | **${totalViolations}** |`);\n }\n lines.push('');\n\n // By Decision\n if (report.byDecision.length > 0) {\n lines.push('## By Decision');\n lines.push('');\n lines.push('| Decision | Status | Constraints | Violations | Compliance |');\n lines.push('|----------|--------|-------------|------------|------------|');\n\n for (const dec of report.byDecision) {\n const complianceEmoji = dec.compliance >= 90 ? '✅' : dec.compliance >= 70 ? '⚠️' : '❌';\n lines.push(\n `| ${dec.title} | ${dec.status} | ${dec.constraints} | ${dec.violations} | ${complianceEmoji} ${dec.compliance}% |`\n );\n }\n lines.push('');\n }\n\n // Footer\n lines.push('---');\n lines.push('');\n lines.push('*Generated by [SpecBridge](https://github.com/nouatzi/specbridge)*');\n\n return lines.join('\\n');\n}\n\nfunction formatProgressBar(percentage: number): string {\n const width = 20;\n const filled = Math.round((percentage / 100) * width);\n const empty = width - filled;\n const filledChar = '█';\n const emptyChar = '░';\n\n return `\\`${filledChar.repeat(filled)}${emptyChar.repeat(empty)}\\` ${percentage}%`;\n}\n","/**\n * Report storage - Save and load historical compliance reports\n */\nimport { join } from 'node:path';\nimport type { ComplianceReport } from '../core/types/index.js';\nimport {\n ensureDir,\n writeTextFile,\n readTextFile,\n readFilesInDir,\n pathExists,\n getSpecBridgeDir,\n} from '../utils/fs.js';\nimport { getLogger } from '../utils/logger.js';\n\nexport interface StoredReport {\n timestamp: string;\n report: ComplianceReport;\n}\n\n/**\n * ReportStorage - Handles persistence and retrieval of historical reports\n */\nexport class ReportStorage {\n private storageDir: string;\n private logger = getLogger({ module: 'reporting.storage' });\n\n constructor(basePath: string) {\n this.storageDir = join(getSpecBridgeDir(basePath), 'reports', 'history');\n }\n\n /**\n * Save a compliance report to storage\n */\n async save(report: ComplianceReport): Promise<string> {\n await ensureDir(this.storageDir);\n\n // Use date as filename (one report per day, overwrites if exists)\n const date = new Date(report.timestamp).toISOString().split('T')[0];\n const filename = `report-${date}.json`;\n const filepath = join(this.storageDir, filename);\n\n await writeTextFile(filepath, JSON.stringify(report, null, 2));\n\n return filepath;\n }\n\n /**\n * Load the most recent report\n */\n async loadLatest(): Promise<StoredReport | null> {\n if (!(await pathExists(this.storageDir))) {\n return null;\n }\n\n const files = await readFilesInDir(this.storageDir);\n if (files.length === 0) {\n return null;\n }\n\n // Sort files by date (descending)\n const sortedFiles = files\n .filter((f) => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n if (sortedFiles.length === 0) {\n return null;\n }\n\n const latestFile = sortedFiles[0];\n if (!latestFile) {\n return null;\n }\n\n const content = await readTextFile(join(this.storageDir, latestFile));\n const report = JSON.parse(content) as ComplianceReport;\n\n return {\n timestamp: latestFile.replace('report-', '').replace('.json', ''),\n report,\n };\n }\n\n /**\n * Load historical reports for the specified number of days\n * Uses parallel I/O for better performance\n */\n async loadHistory(days: number = 30): Promise<StoredReport[]> {\n if (!(await pathExists(this.storageDir))) {\n return [];\n }\n\n const files = await readFilesInDir(this.storageDir);\n\n // Filter report files and sort by date\n const reportFiles = files\n .filter((f) => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse(); // Most recent first\n\n // Take only the requested number of days\n const recentFiles = reportFiles.slice(0, days);\n\n // Load all reports in parallel\n const reportPromises = recentFiles.map(async (file) => {\n try {\n const content = await readTextFile(join(this.storageDir, file));\n const report = JSON.parse(content) as ComplianceReport;\n const timestamp = file.replace('report-', '').replace('.json', '');\n\n return { timestamp, report } as StoredReport;\n } catch (error) {\n // Skip corrupted files\n this.logger.warn({ file, error }, 'Failed to load report file');\n return null;\n }\n });\n\n const results = await Promise.all(reportPromises);\n\n // Filter out null results from failed loads\n return results.filter((r): r is StoredReport => r !== null);\n }\n\n /**\n * Load a specific report by date\n */\n async loadByDate(date: string): Promise<ComplianceReport | null> {\n const filepath = join(this.storageDir, `report-${date}.json`);\n\n if (!(await pathExists(filepath))) {\n return null;\n }\n\n const content = await readTextFile(filepath);\n return JSON.parse(content) as ComplianceReport;\n }\n\n /**\n * Get all available report dates\n */\n async getAvailableDates(): Promise<string[]> {\n if (!(await pathExists(this.storageDir))) {\n return [];\n }\n\n const files = await readFilesInDir(this.storageDir);\n\n return files\n .filter((f) => f.startsWith('report-') && f.endsWith('.json'))\n .map((f) => f.replace('report-', '').replace('.json', ''))\n .sort()\n .reverse();\n }\n\n /**\n * Clear old reports (keep only the most recent N days)\n */\n async cleanup(keepDays: number = 90): Promise<number> {\n if (!(await pathExists(this.storageDir))) {\n return 0;\n }\n\n const files = await readFilesInDir(this.storageDir);\n const reportFiles = files\n .filter((f) => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n // Delete files beyond the keep limit\n const filesToDelete = reportFiles.slice(keepDays);\n\n for (const file of filesToDelete) {\n try {\n const filepath = join(this.storageDir, file);\n const fs = await import('node:fs/promises');\n await fs.unlink(filepath);\n } catch (error) {\n this.logger.warn({ file, error }, 'Failed to delete old report file');\n }\n }\n\n return filesToDelete.length;\n }\n}\n","/**\n * Drift detection - Analyze compliance trends between reports\n */\nimport type { ComplianceReport, DecisionCompliance } from '../core/types/index.js';\n\nexport type TrendDirection = 'improving' | 'stable' | 'degrading';\n\nexport interface DriftAnalysis {\n decisionId: string;\n title: string;\n trend: TrendDirection;\n complianceChange: number; // percentage points\n newViolations: number;\n fixedViolations: number;\n currentCompliance: number;\n previousCompliance: number;\n}\n\nexport interface OverallDrift {\n trend: TrendDirection;\n complianceChange: number;\n summary: {\n newViolations: {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n };\n fixedViolations: {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n };\n };\n byDecision: DriftAnalysis[];\n mostImproved: DriftAnalysis[];\n mostDegraded: DriftAnalysis[];\n}\n\n/**\n * Detect drift between current and previous compliance reports\n */\nexport async function detectDrift(\n current: ComplianceReport,\n previous: ComplianceReport\n): Promise<OverallDrift> {\n const byDecision: DriftAnalysis[] = [];\n\n // Analyze per-decision drift\n for (const currDecision of current.byDecision) {\n const prevDecision = previous.byDecision.find((d) => d.decisionId === currDecision.decisionId);\n\n if (!prevDecision) {\n // New decision - treat as stable for now\n byDecision.push({\n decisionId: currDecision.decisionId,\n title: currDecision.title,\n trend: 'stable',\n complianceChange: 0,\n newViolations: currDecision.violations,\n fixedViolations: 0,\n currentCompliance: currDecision.compliance,\n previousCompliance: currDecision.compliance,\n });\n continue;\n }\n\n const complianceChange = currDecision.compliance - prevDecision.compliance;\n const violationDiff = currDecision.violations - prevDecision.violations;\n\n // Determine trend with threshold\n let trend: TrendDirection;\n if (complianceChange > 5) {\n trend = 'improving';\n } else if (complianceChange < -5) {\n trend = 'degrading';\n } else {\n trend = 'stable';\n }\n\n byDecision.push({\n decisionId: currDecision.decisionId,\n title: currDecision.title,\n trend,\n complianceChange,\n newViolations: Math.max(0, violationDiff),\n fixedViolations: Math.max(0, -violationDiff),\n currentCompliance: currDecision.compliance,\n previousCompliance: prevDecision.compliance,\n });\n }\n\n // Calculate overall drift\n const overallComplianceChange = current.summary.compliance - previous.summary.compliance;\n\n let overallTrend: TrendDirection;\n if (overallComplianceChange > 5) {\n overallTrend = 'improving';\n } else if (overallComplianceChange < -5) {\n overallTrend = 'degrading';\n } else {\n overallTrend = 'stable';\n }\n\n // Calculate violation changes by severity\n const newViolations = {\n critical: Math.max(\n 0,\n current.summary.violations.critical - previous.summary.violations.critical\n ),\n high: Math.max(0, current.summary.violations.high - previous.summary.violations.high),\n medium: Math.max(0, current.summary.violations.medium - previous.summary.violations.medium),\n low: Math.max(0, current.summary.violations.low - previous.summary.violations.low),\n total: 0,\n };\n newViolations.total =\n newViolations.critical + newViolations.high + newViolations.medium + newViolations.low;\n\n const fixedViolations = {\n critical: Math.max(\n 0,\n previous.summary.violations.critical - current.summary.violations.critical\n ),\n high: Math.max(0, previous.summary.violations.high - current.summary.violations.high),\n medium: Math.max(0, previous.summary.violations.medium - current.summary.violations.medium),\n low: Math.max(0, previous.summary.violations.low - current.summary.violations.low),\n total: 0,\n };\n fixedViolations.total =\n fixedViolations.critical + fixedViolations.high + fixedViolations.medium + fixedViolations.low;\n\n // Find most improved and most degraded\n const improving = byDecision.filter((d) => d.trend === 'improving');\n const degrading = byDecision.filter((d) => d.trend === 'degrading');\n\n const mostImproved = improving\n .sort((a, b) => b.complianceChange - a.complianceChange)\n .slice(0, 5);\n const mostDegraded = degrading\n .sort((a, b) => a.complianceChange - b.complianceChange)\n .slice(0, 5);\n\n return {\n trend: overallTrend,\n complianceChange: overallComplianceChange,\n summary: {\n newViolations,\n fixedViolations,\n },\n byDecision,\n mostImproved,\n mostDegraded,\n };\n}\n\n/**\n * Analyze compliance trend over multiple reports\n */\nexport interface TrendAnalysis {\n period: {\n start: string;\n end: string;\n days: number;\n };\n overall: {\n startCompliance: number;\n endCompliance: number;\n change: number;\n trend: TrendDirection;\n dataPoints: Array<{ date: string; compliance: number }>;\n };\n decisions: Array<{\n decisionId: string;\n title: string;\n startCompliance: number;\n endCompliance: number;\n change: number;\n trend: TrendDirection;\n dataPoints: Array<{ date: string; compliance: number }>;\n }>;\n}\n\nexport async function analyzeTrend(\n reports: Array<{ timestamp: string; report: ComplianceReport }>\n): Promise<TrendAnalysis> {\n if (reports.length === 0) {\n throw new Error('No reports provided for trend analysis');\n }\n\n // Sort by timestamp (oldest first)\n const sortedReports = reports.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n\n const firstReport = sortedReports[0]?.report;\n const lastReport = sortedReports[sortedReports.length - 1]?.report;\n\n if (!firstReport || !lastReport) {\n throw new Error('Invalid reports data');\n }\n\n // Overall trend\n const overallChange = lastReport.summary.compliance - firstReport.summary.compliance;\n let overallTrend: TrendDirection;\n if (overallChange > 5) {\n overallTrend = 'improving';\n } else if (overallChange < -5) {\n overallTrend = 'degrading';\n } else {\n overallTrend = 'stable';\n }\n\n const overallDataPoints = sortedReports.map((r) => ({\n date: r.timestamp,\n compliance: r.report.summary.compliance,\n }));\n\n // Per-decision trends\n const decisionMap = new Map<string, DecisionCompliance[]>();\n\n for (const { report } of sortedReports) {\n for (const decision of report.byDecision) {\n if (!decisionMap.has(decision.decisionId)) {\n decisionMap.set(decision.decisionId, []);\n }\n const decisionHistory = decisionMap.get(decision.decisionId);\n if (decisionHistory) {\n decisionHistory.push(decision);\n }\n }\n }\n\n const decisions = Array.from(decisionMap.entries()).map(([decisionId, data]) => {\n const first = data[0];\n const last = data[data.length - 1];\n\n if (!first || !last) {\n throw new Error(`Invalid decision data for ${decisionId}`);\n }\n\n const change = last.compliance - first.compliance;\n\n let trend: TrendDirection;\n if (change > 5) {\n trend = 'improving';\n } else if (change < -5) {\n trend = 'degrading';\n } else {\n trend = 'stable';\n }\n\n const dataPoints = sortedReports.map((r) => {\n const decision = r.report.byDecision.find((d) => d.decisionId === decisionId);\n return {\n date: r.timestamp,\n compliance: decision?.compliance ?? 0,\n };\n });\n\n return {\n decisionId,\n title: last.title,\n startCompliance: first.compliance,\n endCompliance: last.compliance,\n change,\n trend,\n dataPoints,\n };\n });\n\n const firstTimestamp = sortedReports[0]?.timestamp;\n const lastTimestamp = sortedReports[sortedReports.length - 1]?.timestamp;\n\n if (!firstTimestamp || !lastTimestamp) {\n throw new Error('Invalid report timestamps');\n }\n\n return {\n period: {\n start: firstTimestamp,\n end: lastTimestamp,\n days: sortedReports.length,\n },\n overall: {\n startCompliance: firstReport.summary.compliance,\n endCompliance: lastReport.summary.compliance,\n change: overallChange,\n trend: overallTrend,\n dataPoints: overallDataPoints,\n },\n decisions,\n };\n}\n","/**\n * Agent context generator\n */\nimport type {\n AgentContext,\n ApplicableDecision,\n ApplicableConstraint,\n SpecBridgeConfig,\n Decision,\n Constraint,\n} from '../core/types/index.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface ContextOptions {\n includeRationale?: boolean;\n format?: 'markdown' | 'json' | 'mcp';\n cwd?: string;\n}\n\n/**\n * Generate agent context for a file\n */\nexport async function generateContext(\n filePath: string,\n config: SpecBridgeConfig,\n options: ContextOptions = {}\n): Promise<AgentContext> {\n const { includeRationale = config.agent?.includeRationale ?? true, cwd = process.cwd() } =\n options;\n\n // Load registry\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n\n // Get active decisions\n const decisions = registry.getActive();\n\n // Find applicable decisions and constraints\n const applicableDecisions: ApplicableDecision[] = [];\n\n for (const decision of decisions) {\n const applicableConstraints: ApplicableConstraint[] = [];\n\n for (const constraint of decision.constraints) {\n if (matchesPattern(filePath, constraint.scope)) {\n applicableConstraints.push({\n id: constraint.id,\n type: constraint.type,\n rule: constraint.rule,\n severity: constraint.severity,\n });\n }\n }\n\n if (applicableConstraints.length > 0) {\n applicableDecisions.push({\n id: decision.metadata.id,\n title: decision.metadata.title,\n summary: includeRationale ? decision.decision.summary : '',\n constraints: applicableConstraints,\n });\n }\n }\n\n return {\n file: filePath,\n applicableDecisions,\n generatedAt: new Date().toISOString(),\n };\n}\n\n/**\n * Format context as Markdown for agent prompts\n */\nexport function formatContextAsMarkdown(context: AgentContext): string {\n const lines: string[] = [];\n\n lines.push('# Architectural Constraints');\n lines.push('');\n lines.push(`File: \\`${context.file}\\``);\n lines.push('');\n\n if (context.applicableDecisions.length === 0) {\n lines.push('No specific architectural constraints apply to this file.');\n return lines.join('\\n');\n }\n\n lines.push('The following architectural decisions apply to this file:');\n lines.push('');\n\n for (const decision of context.applicableDecisions) {\n lines.push(`## ${decision.title}`);\n lines.push('');\n\n if (decision.summary) {\n lines.push(decision.summary);\n lines.push('');\n }\n\n lines.push('### Constraints');\n lines.push('');\n\n for (const constraint of decision.constraints) {\n const typeEmoji =\n constraint.type === 'invariant' ? '🔒' : constraint.type === 'convention' ? '📋' : '💡';\n const severityBadge = `[${constraint.severity.toUpperCase()}]`;\n\n lines.push(`- ${typeEmoji} **${severityBadge}** ${constraint.rule}`);\n }\n\n lines.push('');\n }\n\n lines.push('---');\n lines.push('');\n lines.push('Please ensure your code complies with these constraints.');\n\n return lines.join('\\n');\n}\n\n/**\n * Format context as JSON\n */\nexport function formatContextAsJson(context: AgentContext): string {\n return JSON.stringify(context, null, 2);\n}\n\n/**\n * Format context for MCP (Model Context Protocol)\n */\nexport function formatContextAsMcp(context: AgentContext): object {\n return {\n type: 'architectural_context',\n version: '1.0',\n file: context.file,\n timestamp: context.generatedAt,\n decisions: context.applicableDecisions.map((d) => ({\n id: d.id,\n title: d.title,\n summary: d.summary,\n constraints: d.constraints.map((c) => ({\n id: c.id,\n type: c.type,\n severity: c.severity,\n rule: c.rule,\n })),\n })),\n };\n}\n\n/**\n * Generate context in specified format\n */\nexport async function generateFormattedContext(\n filePath: string,\n config: SpecBridgeConfig,\n options: ContextOptions = {}\n): Promise<string> {\n const context = await generateContext(filePath, config, options);\n const format = options.format || config.agent?.format || 'markdown';\n\n switch (format) {\n case 'json':\n return formatContextAsJson(context);\n case 'mcp':\n return JSON.stringify(formatContextAsMcp(context), null, 2);\n case 'markdown':\n default:\n return formatContextAsMarkdown(context);\n }\n}\n\n/**\n * AgentContextGenerator class for test compatibility\n */\nexport class AgentContextGenerator {\n /**\n * Generate context from decisions\n */\n generateContext(options: {\n decisions: Decision[];\n filePattern?: string;\n format?: 'markdown' | 'plain' | 'json';\n concise?: boolean;\n minSeverity?: string;\n includeExamples?: boolean;\n }): string {\n const { decisions, filePattern, format = 'markdown', concise = false, minSeverity } = options;\n\n // Filter deprecated decisions\n const activeDecisions = decisions.filter((d) => d.metadata.status !== 'deprecated');\n\n // Filter by file pattern if provided\n let filteredDecisions = activeDecisions;\n if (filePattern) {\n filteredDecisions = activeDecisions.filter((d) =>\n d.constraints.some((c: Constraint) => matchesPattern(filePattern, c.scope))\n );\n }\n\n // Filter by severity if provided\n if (minSeverity) {\n const severityOrder = { low: 0, medium: 1, high: 2, critical: 3 };\n const minLevel = severityOrder[minSeverity as keyof typeof severityOrder] || 0;\n\n filteredDecisions = filteredDecisions\n .map((d) => ({\n ...d,\n constraints: d.constraints.filter((c: Constraint) => {\n const level = severityOrder[c.severity as keyof typeof severityOrder] || 0;\n return level >= minLevel;\n }),\n }))\n .filter((d) => d.constraints.length > 0);\n }\n\n // Format output\n if (filteredDecisions.length === 0) {\n return 'No architectural decisions apply.';\n }\n\n if (format === 'json') {\n return JSON.stringify({ decisions: filteredDecisions }, null, 2);\n }\n\n const lines: string[] = [];\n\n if (format === 'markdown') {\n lines.push('# Architectural Decisions\\n');\n for (const decision of filteredDecisions) {\n lines.push(`## ${decision.metadata.title}`);\n if (!concise && decision.decision.summary) {\n lines.push(`\\n${decision.decision.summary}\\n`);\n }\n lines.push('### Constraints\\n');\n for (const constraint of decision.constraints) {\n lines.push(`- **[${constraint.severity.toUpperCase()}]** ${constraint.rule}`);\n }\n lines.push('');\n }\n } else {\n // Plain text format\n for (const decision of filteredDecisions) {\n lines.push(`${decision.metadata.title}`);\n if (!concise && decision.decision.summary) {\n lines.push(`${decision.decision.summary}`);\n }\n for (const constraint of decision.constraints) {\n lines.push(` - ${constraint.rule}`);\n }\n lines.push('');\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Generate prompt suffix for AI agents\n */\n generatePromptSuffix(options: { decisions: Decision[] }): string {\n const { decisions } = options;\n\n if (decisions.length === 0) {\n return 'No architectural decisions to follow.';\n }\n\n const lines: string[] = [];\n lines.push('Please follow these architectural decisions and constraints:');\n lines.push('');\n\n for (const decision of decisions) {\n lines.push(`- ${decision.metadata.title}`);\n for (const constraint of decision.constraints) {\n lines.push(` - ${constraint.rule}`);\n }\n }\n\n lines.push('');\n lines.push('Ensure your code complies with all constraints listed above.');\n\n return lines.join('\\n');\n }\n\n /**\n * Extract relevant decisions for a specific file\n */\n extractRelevantDecisions(options: { decisions: Decision[]; filePath: string }): Decision[] {\n const { decisions, filePath } = options;\n\n return decisions.filter((d) =>\n d.constraints.some((c: Constraint) => matchesPattern(filePath, c.scope))\n );\n }\n}\n","/**\n * Prompt templates for AI agents\n */\nimport type { AgentContext } from '../core/types/index.js';\nimport { formatContextAsMarkdown } from './context.generator.js';\n\nexport interface PromptTemplate {\n name: string;\n description: string;\n generate: (context: AgentContext, options?: Record<string, unknown>) => string;\n}\n\nexport const templates: Record<string, PromptTemplate> = {\n 'code-review': {\n name: 'Code Review',\n description: 'Review code for architectural compliance',\n generate: (context) => {\n return [\n 'You are reviewing code for architectural compliance.',\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Identify violations of the constraints above.',\n '- Suggest concrete changes to achieve compliance.',\n ].join('\\n');\n },\n },\n\n refactoring: {\n name: 'Refactoring Guidance',\n description: 'Guide refactoring to meet constraints',\n generate: (context) => {\n return [\n 'You are helping refactor code to meet architectural constraints.',\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Propose a step-by-step refactoring plan to satisfy all invariants first, then conventions/guidelines.',\n '- Highlight risky changes and suggest safe incremental steps.',\n ].join('\\n');\n },\n },\n\n migration: {\n name: 'Migration Plan',\n description: 'Generate a migration plan for a new/changed decision',\n generate: (context, options) => {\n const decisionId = String(options?.decisionId ?? '');\n return [\n `A new architectural decision has been introduced: ${decisionId || '<decision-id>'}`,\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Provide an impact analysis.',\n '- Produce a step-by-step migration plan.',\n '- Include a checklist for completion.',\n ].join('\\n');\n },\n },\n};\n","/**\n * SpecBridge MCP Server (Model Context Protocol)\n */\nimport { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { generateFormattedContext } from '../agent/context.generator.js';\nimport { createVerificationEngine } from '../verification/engine.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { formatConsoleReport } from '../reporting/formats/console.js';\nimport { formatMarkdownReport } from '../reporting/formats/markdown.js';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\n\nexport interface McpServerOptions {\n cwd: string;\n version: string;\n}\n\nexport class SpecBridgeMcpServer {\n private server: McpServer;\n private cwd: string;\n private config: SpecBridgeConfig | null = null;\n private registry: Registry | null = null;\n\n constructor(options: McpServerOptions) {\n this.cwd = options.cwd;\n this.server = new McpServer({ name: 'specbridge', version: options.version });\n }\n\n async initialize(): Promise<void> {\n this.config = await loadConfig(this.cwd);\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n\n this.registerResources();\n this.registerTools();\n }\n\n async startStdio(): Promise<void> {\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n }\n\n private getReady(): { config: SpecBridgeConfig; registry: Registry } {\n if (!this.config || !this.registry) {\n throw new Error('SpecBridge MCP server not initialized. Call initialize() first.');\n }\n return { config: this.config, registry: this.registry };\n }\n\n private registerResources(): void {\n const { config, registry } = this.getReady();\n\n // List all decisions\n this.server.registerResource(\n 'decisions',\n 'decision:///',\n {\n title: 'Architectural Decisions',\n description: 'List of all architectural decisions',\n mimeType: 'application/json',\n },\n async (uri: URL) => {\n const decisions = registry.getAll();\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(decisions, null, 2),\n },\n ],\n };\n }\n );\n\n // Read a specific decision\n this.server.registerResource(\n 'decision',\n new ResourceTemplate('decision://{id}', { list: undefined }),\n {\n title: 'Architectural Decision',\n description: 'A specific architectural decision by id',\n mimeType: 'application/json',\n },\n async (uri: URL, variables: Record<string, string | string[]>) => {\n const raw = variables.id;\n const decisionId = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '');\n const decision = registry.get(String(decisionId));\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(decision, null, 2),\n },\n ],\n };\n }\n );\n\n // Latest compliance report\n this.server.registerResource(\n 'latest_report',\n 'report:///latest',\n {\n title: 'Latest Compliance Report',\n description: 'Most recent compliance report (generated on demand)',\n mimeType: 'application/json',\n },\n async (uri: URL) => {\n const report = await generateReport(config, { cwd: this.cwd });\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n }\n );\n }\n\n private registerTools(): void {\n const { config } = this.getReady();\n\n this.server.registerTool(\n 'generate_context',\n {\n title: 'Generate architectural context',\n description: 'Generate architectural context for a file from applicable decisions',\n inputSchema: {\n filePath: z.string().describe('Path to the file to analyze'),\n includeRationale: z.boolean().optional().default(true),\n format: z.enum(['markdown', 'json', 'mcp']).optional().default('markdown'),\n },\n },\n async (args: {\n filePath: string;\n includeRationale?: boolean;\n format?: 'markdown' | 'json' | 'mcp';\n }) => {\n const text = await generateFormattedContext(args.filePath, config, {\n includeRationale: args.includeRationale,\n format: args.format,\n cwd: this.cwd,\n });\n\n return { content: [{ type: 'text', text }] };\n }\n );\n\n this.server.registerTool(\n 'verify_compliance',\n {\n title: 'Verify compliance',\n description: 'Verify code compliance against constraints',\n inputSchema: {\n level: z.enum(['commit', 'pr', 'full']).optional().default('full'),\n files: z.array(z.string()).optional(),\n decisions: z.array(z.string()).optional(),\n severity: z.array(z.enum(['critical', 'high', 'medium', 'low'])).optional(),\n },\n },\n async (args: {\n level?: 'commit' | 'pr' | 'full';\n files?: string[];\n decisions?: string[];\n severity?: ('critical' | 'high' | 'medium' | 'low')[];\n }) => {\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level: args.level,\n files: args.files,\n decisions: args.decisions,\n severity: args.severity,\n cwd: this.cwd,\n });\n\n return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };\n }\n );\n\n this.server.registerTool(\n 'get_report',\n {\n title: 'Get compliance report',\n description: 'Generate a compliance report for the current workspace',\n inputSchema: {\n format: z.enum(['summary', 'detailed', 'json', 'markdown']).optional().default('summary'),\n includeAll: z.boolean().optional().default(false),\n },\n },\n async (args: {\n format?: 'summary' | 'detailed' | 'json' | 'markdown';\n includeAll?: boolean;\n }) => {\n const report = await generateReport(config, { cwd: this.cwd, includeAll: args.includeAll });\n\n if (args.format === 'json') {\n return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }] };\n }\n\n if (args.format === 'markdown') {\n return { content: [{ type: 'text', text: formatMarkdownReport(report) }] };\n }\n\n if (args.format === 'detailed') {\n return { content: [{ type: 'text', text: formatConsoleReport(report) }] };\n }\n\n // summary\n const summary = {\n timestamp: report.timestamp,\n project: report.project,\n compliance: report.summary.compliance,\n violations: report.summary.violations,\n decisions: report.summary.activeDecisions,\n };\n return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] };\n }\n );\n }\n}\n","/**\n * Analytics engine - Provide insights into compliance trends and decision impact\n */\nimport type { DecisionCompliance, Severity } from '../core/types/index.js';\nimport type { StoredReport } from '../reporting/storage.js';\n\nexport interface DecisionMetrics {\n decisionId: string;\n title: string;\n totalViolations: number;\n violationsByFile: Map<string, number>;\n violationsBySeverity: Record<Severity, number>;\n mostViolatedConstraint: { id: string; count: number } | null;\n averageComplianceScore: number;\n trendDirection: 'up' | 'down' | 'stable';\n history: Array<{\n date: string;\n compliance: number;\n violations: number;\n }>;\n}\n\nexport interface Insight {\n type: 'warning' | 'info' | 'success';\n category: 'compliance' | 'trend' | 'hotspot' | 'suggestion';\n message: string;\n details?: string;\n decisionId?: string;\n}\n\nexport interface AnalyticsSummary {\n totalDecisions: number;\n averageCompliance: number;\n overallTrend: 'up' | 'down' | 'stable';\n criticalIssues: number;\n topDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n bottomDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n insights: Insight[];\n}\n\n/**\n * Analytics engine for compliance data\n */\nexport class AnalyticsEngine {\n /**\n * Analyze a specific decision across historical reports\n */\n async analyzeDecision(decisionId: string, history: StoredReport[]): Promise<DecisionMetrics> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n // Extract decision data from each report\n const decisionHistory: Array<{\n date: string;\n data: DecisionCompliance;\n }> = [];\n\n for (const { timestamp, report } of history) {\n const decision = report.byDecision.find((d) => d.decisionId === decisionId);\n if (decision) {\n decisionHistory.push({ date: timestamp, data: decision });\n }\n }\n\n if (decisionHistory.length === 0) {\n throw new Error(`Decision ${decisionId} not found in any report`);\n }\n\n // Get latest data\n const latestEntry = decisionHistory[decisionHistory.length - 1];\n if (!latestEntry) {\n throw new Error(`No data found for decision ${decisionId}`);\n }\n const latest = latestEntry.data;\n\n // Calculate averages\n const averageCompliance =\n decisionHistory.reduce((sum, h) => sum + h.data.compliance, 0) / decisionHistory.length;\n\n // Determine trend\n let trendDirection: 'up' | 'down' | 'stable' = 'stable';\n if (decisionHistory.length >= 2) {\n const firstEntry = decisionHistory[0];\n if (!firstEntry) {\n throw new Error('Invalid decision history');\n }\n const first = firstEntry.data.compliance;\n const last = latest.compliance;\n const change = last - first;\n\n if (change > 5) {\n trendDirection = 'up';\n } else if (change < -5) {\n trendDirection = 'down';\n }\n }\n\n // Build history summary\n const historyData = decisionHistory.map((h) => ({\n date: h.date,\n compliance: h.data.compliance,\n violations: h.data.violations,\n }));\n\n return {\n decisionId,\n title: latest.title,\n totalViolations: latest.violations,\n violationsByFile: new Map(), // Would need violation details to populate\n violationsBySeverity: {\n critical: 0,\n high: 0,\n medium: 0,\n low: 0,\n }, // Would need violation details to populate\n mostViolatedConstraint: null, // Would need constraint details to populate\n averageComplianceScore: averageCompliance,\n trendDirection,\n history: historyData,\n };\n }\n\n /**\n * Generate insights from historical data\n */\n async generateInsights(history: StoredReport[]): Promise<Insight[]> {\n if (history.length === 0) {\n return [];\n }\n\n const insights: Insight[] = [];\n\n // Sort by date (oldest first)\n const sorted = history.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n const latestEntry = sorted[sorted.length - 1];\n if (!latestEntry) {\n throw new Error('No reports in history');\n }\n const latest = latestEntry.report;\n\n // Insight: Overall compliance trend\n if (sorted.length >= 2) {\n const firstEntry = sorted[0];\n if (!firstEntry) {\n return insights;\n }\n const first = firstEntry.report;\n const complianceChange = latest.summary.compliance - first.summary.compliance;\n\n if (complianceChange > 10) {\n insights.push({\n type: 'success',\n category: 'trend',\n message: `Compliance has improved by ${complianceChange.toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n } else if (complianceChange < -10) {\n insights.push({\n type: 'warning',\n category: 'trend',\n message: `Compliance has dropped by ${Math.abs(complianceChange).toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n }\n }\n\n // Insight: Critical violations\n if (latest.summary.violations.critical > 0) {\n insights.push({\n type: 'warning',\n category: 'compliance',\n message: `${latest.summary.violations.critical} critical violation(s) require immediate attention`,\n details: 'Critical violations block deployments and should be resolved as soon as possible',\n });\n }\n\n // Insight: Decision-specific issues\n const problematicDecisions = latest.byDecision.filter((d) => d.compliance < 50);\n if (problematicDecisions.length > 0) {\n insights.push({\n type: 'warning',\n category: 'hotspot',\n message: `${problematicDecisions.length} decision(s) have less than 50% compliance`,\n details: problematicDecisions.map((d) => `${d.title} (${d.compliance}%)`).join(', '),\n });\n }\n\n // Insight: High compliance decisions\n const excellentDecisions = latest.byDecision.filter((d) => d.compliance === 100);\n if (excellentDecisions.length > 0) {\n insights.push({\n type: 'success',\n category: 'compliance',\n message: `${excellentDecisions.length} decision(s) have 100% compliance`,\n details: excellentDecisions.map((d) => d.title).join(', '),\n });\n }\n\n // Insight: Compare to average\n const avgCompliance = latest.summary.compliance;\n const decisionsAboveAvg = latest.byDecision.filter((d) => d.compliance > avgCompliance);\n const decisionsBelowAvg = latest.byDecision.filter((d) => d.compliance < avgCompliance);\n\n if (decisionsBelowAvg.length > decisionsAboveAvg.length) {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: `${decisionsBelowAvg.length} decisions are below average compliance`,\n details: 'Consider focusing improvement efforts on these lower-performing decisions',\n });\n }\n\n // Insight: Violation distribution\n const totalViolations =\n latest.summary.violations.critical +\n latest.summary.violations.high +\n latest.summary.violations.medium +\n latest.summary.violations.low;\n\n if (totalViolations > 0) {\n const criticalPercent = (latest.summary.violations.critical / totalViolations) * 100;\n const highPercent = (latest.summary.violations.high / totalViolations) * 100;\n\n if (criticalPercent + highPercent > 60) {\n insights.push({\n type: 'warning',\n category: 'suggestion',\n message: 'Most violations are high severity',\n details: `${criticalPercent.toFixed(0)}% critical, ${highPercent.toFixed(0)}% high. Prioritize these for the biggest impact.`,\n });\n } else {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: 'Most violations are lower severity',\n details: 'Consider addressing high-severity issues first for maximum impact',\n });\n }\n }\n\n return insights;\n }\n\n /**\n * Generate analytics summary\n */\n async generateSummary(history: StoredReport[]): Promise<AnalyticsSummary> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n const latestEntry = history[history.length - 1];\n if (!latestEntry) {\n throw new Error('Invalid history data');\n }\n const latest = latestEntry.report;\n\n // Calculate overall trend\n let overallTrend: 'up' | 'down' | 'stable' = 'stable';\n if (history.length >= 2) {\n const firstEntry = history[0];\n if (!firstEntry) {\n throw new Error('Invalid history data');\n }\n const first = firstEntry.report;\n const change = latest.summary.compliance - first.summary.compliance;\n\n if (change > 5) {\n overallTrend = 'up';\n } else if (change < -5) {\n overallTrend = 'down';\n }\n }\n\n // Find top and bottom performers\n const sortedByCompliance = [...latest.byDecision].sort((a, b) => b.compliance - a.compliance);\n\n const topDecisions = sortedByCompliance.slice(0, 5).map((d) => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n const bottomDecisions = sortedByCompliance\n .slice(-5)\n .reverse()\n .map((d) => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n // Generate insights\n const insights = await this.generateInsights(history);\n\n return {\n totalDecisions: latest.byDecision.length,\n averageCompliance: latest.summary.compliance,\n overallTrend,\n criticalIssues: latest.summary.violations.critical,\n topDecisions,\n bottomDecisions,\n insights,\n };\n }\n}\n","/**\n * Dashboard server - Compliance dashboard backend with REST API\n */\nimport express, { type Request, type Response, type Application } from 'express';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { SpecBridgeConfig, ComplianceReport } from '../core/types/index.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { ReportStorage } from '../reporting/storage.js';\nimport { AnalyticsEngine } from '../analytics/engine.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { detectDrift, analyzeTrend } from '../reporting/drift.js';\nimport { DecisionNotFoundError } from '../core/errors/index.js';\nimport { getLogger } from '../utils/logger.js';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\ninterface DashboardOptions {\n cwd: string;\n config: SpecBridgeConfig;\n}\n\n/**\n * Dashboard Server with caching\n */\nclass DashboardServer {\n private app: Application;\n private cwd: string;\n private config: SpecBridgeConfig;\n private registry: Registry;\n private reportStorage: ReportStorage;\n\n // Caching infrastructure\n private cachedReport: ComplianceReport | null = null;\n private cacheTimestamp: number = 0;\n private readonly CACHE_TTL = 60000; // 1 minute\n private refreshInterval: NodeJS.Timeout | null = null;\n private logger = getLogger({ module: 'dashboard.server' });\n\n constructor(options: DashboardOptions) {\n this.cwd = options.cwd;\n this.config = options.config;\n this.app = express();\n this.registry = createRegistry({ basePath: this.cwd });\n this.reportStorage = new ReportStorage(this.cwd);\n\n this.setupMiddleware();\n this.setupRoutes();\n }\n\n /**\n * Start the server with background cache refresh\n */\n async start(): Promise<void> {\n // Load registry once\n await this.registry.load();\n\n // Initial cache population\n await this.refreshCache();\n\n // Background refresh\n this.refreshInterval = setInterval(() => {\n void this.refreshCache().catch((error: unknown) => {\n this.logger.error({ error }, 'Background cache refresh failed');\n });\n }, this.CACHE_TTL);\n }\n\n /**\n * Stop the server and clear intervals\n */\n stop(): void {\n if (this.refreshInterval) {\n clearInterval(this.refreshInterval);\n this.refreshInterval = null;\n }\n }\n\n /**\n * Refresh the cached report\n */\n private async refreshCache(): Promise<void> {\n try {\n const report = await generateReport(this.config, { cwd: this.cwd });\n\n this.cachedReport = report;\n this.cacheTimestamp = Date.now();\n\n // Persist to disk\n await this.reportStorage.save(report);\n } catch (error) {\n this.logger.error({ error }, 'Cache refresh failed');\n\n // Fallback: Load last saved report if cache is empty\n if (!this.cachedReport) {\n try {\n const stored = await this.reportStorage.loadLatest();\n if (stored) {\n this.cachedReport = stored.report;\n }\n } catch (fallbackError) {\n this.logger.error({ error: fallbackError }, 'Failed to load fallback report');\n }\n }\n }\n }\n\n /**\n * Get the Express app instance\n */\n getApp(): Application {\n return this.app;\n }\n\n /**\n * Setup middleware\n */\n private setupMiddleware(): void {\n this.app.use(express.json());\n\n // CORS for development\n this.app.use((_req, res, next) => {\n res.header('Access-Control-Allow-Origin', '*');\n res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.header('Access-Control-Allow-Headers', 'Content-Type');\n next();\n });\n }\n\n /**\n * Setup all routes\n */\n private setupRoutes(): void {\n this.setupReportRoutes();\n this.setupDecisionRoutes();\n this.setupAnalyticsRoutes();\n this.setupHealthRoute();\n this.setupStaticFiles();\n }\n\n /**\n * Setup report-related routes\n */\n private setupReportRoutes(): void {\n // GET /api/report/latest - Serve cached report\n this.app.get('/api/report/latest', (_req: Request, res: Response) => {\n if (!this.cachedReport) {\n res.status(503).json({ error: 'Report not ready' });\n return;\n }\n\n res.json({\n ...this.cachedReport,\n cached: true,\n cacheAge: Date.now() - this.cacheTimestamp,\n });\n });\n\n // GET /api/report/history?days=30\n this.app.get('/api/report/history', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const history = await this.reportStorage.loadHistory(days);\n res.json(history);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load history',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/report/dates\n this.app.get('/api/report/dates', async (_req: Request, res: Response) => {\n try {\n const dates = await this.reportStorage.getAvailableDates();\n res.json(dates);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load dates',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/report/:date\n this.app.get('/api/report/:date', async (req: Request, res: Response) => {\n try {\n const dateParam = req.params.date;\n const date = Array.isArray(dateParam) ? dateParam[0] : dateParam;\n if (!date) {\n res.status(400).json({ error: 'Date parameter required' });\n return;\n }\n\n const report = await this.reportStorage.loadByDate(date);\n\n if (!report) {\n res.status(404).json({ error: 'Report not found' });\n return;\n }\n\n res.json(report);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load report',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup decision-related routes\n */\n private setupDecisionRoutes(): void {\n // GET /api/decisions\n this.app.get('/api/decisions', async (_req: Request, res: Response) => {\n try {\n const decisions = this.registry.getAll();\n res.json(decisions);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load decisions',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/decisions/:id\n this.app.get('/api/decisions/:id', async (req: Request, res: Response) => {\n try {\n const idParam = req.params.id;\n const id = Array.isArray(idParam) ? idParam[0] : idParam;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const decision = this.registry.get(id);\n\n if (!decision) {\n res.status(404).json({ error: 'Decision not found' });\n return;\n }\n\n res.json(decision);\n } catch (error) {\n if (error instanceof DecisionNotFoundError) {\n res.status(404).json({ error: 'Decision not found' });\n return;\n }\n\n res.status(500).json({\n error: 'Failed to load decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup analytics-related routes\n */\n private setupAnalyticsRoutes(): void {\n // GET /api/analytics/summary?days=90\n this.app.get('/api/analytics/summary', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 90;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const summary = await engine.generateSummary(history);\n res.json(summary);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to generate analytics',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/analytics/decision/:id?days=90\n this.app.get('/api/analytics/decision/:id', async (req: Request, res: Response) => {\n try {\n const idParam = req.params.id;\n const id = Array.isArray(idParam) ? idParam[0] : idParam;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const days = parseInt(req.query.days as string) || 90;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const metrics = await engine.analyzeDecision(id, history);\n res.json(metrics);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/drift?days=2\n this.app.get('/api/drift', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 2;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for drift analysis' });\n return;\n }\n\n const currentEntry = history[0];\n const previousEntry = history[1];\n\n if (!currentEntry || !previousEntry) {\n res.status(400).json({ error: 'Invalid history data' });\n return;\n }\n\n const drift = await detectDrift(currentEntry.report, previousEntry.report);\n res.json(drift);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze drift',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/trend?days=30\n this.app.get('/api/trend', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for trend analysis' });\n return;\n }\n\n const trend = await analyzeTrend(history);\n res.json(trend);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze trend',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup health check route\n */\n private setupHealthRoute(): void {\n this.app.get('/api/health', (_req: Request, res: Response) => {\n res.json({\n status: 'ok',\n timestamp: new Date().toISOString(),\n project: this.config.project.name,\n cache: {\n loaded: this.cachedReport !== null,\n age: Date.now() - this.cacheTimestamp,\n nextRefresh: this.CACHE_TTL - (Date.now() - this.cacheTimestamp),\n },\n });\n });\n }\n\n /**\n * Setup static file serving\n */\n private setupStaticFiles(): void {\n // Serve static frontend files\n const publicDir = join(__dirname, 'public');\n this.app.use(\n express.static(publicDir, {\n maxAge: '1h', // Cache static assets\n etag: true,\n })\n );\n\n // Fallback to index.html for SPA routing\n this.app.get('/{*path}', (_req: Request, res: Response) => {\n res.sendFile(join(publicDir, 'index.html'));\n });\n }\n}\n\n/**\n * Create and configure the dashboard server (factory function)\n * @returns DashboardServer instance\n */\nexport function createDashboardServer(options: DashboardOptions): DashboardServer {\n return new DashboardServer(options);\n}\n\n// Export the class for advanced usage\nexport { DashboardServer };\n","/**\n * SpecBridge Language Server (LSP)\n */\nimport {\n createConnection,\n ProposedFeatures,\n TextDocuments,\n TextDocumentSyncKind,\n DiagnosticSeverity,\n CodeActionKind,\n} from 'vscode-languageserver/node.js';\nimport { TextDocument } from 'vscode-languageserver-textdocument';\nimport { fileURLToPath } from 'node:url';\nimport path from 'node:path';\nimport { Project } from 'ts-morph';\nimport chalk from 'chalk';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { getSpecBridgeDir, pathExists } from '../utils/fs.js';\nimport {\n selectVerifierForConstraint,\n type VerificationContext,\n} from '../verification/verifiers/index.js';\nimport { shouldApplyConstraintToFile } from '../verification/applicability.js';\nimport { getPluginLoader } from '../verification/plugins/loader.js';\nimport type { Decision, Violation, Severity } from '../core/types/index.js';\nimport { NotInitializedError } from '../core/errors/index.js';\n\nexport interface LspServerOptions {\n cwd: string;\n verbose?: boolean;\n}\n\nfunction severityToDiagnostic(severity: Severity): DiagnosticSeverity {\n switch (severity) {\n case 'critical':\n return DiagnosticSeverity.Error;\n case 'high':\n return DiagnosticSeverity.Warning;\n case 'medium':\n return DiagnosticSeverity.Information;\n case 'low':\n return DiagnosticSeverity.Hint;\n default:\n return DiagnosticSeverity.Information;\n }\n}\n\nfunction uriToFilePath(uri: string): string {\n if (uri.startsWith('file://')) return fileURLToPath(uri);\n // Fallback: treat as plain path\n return uri;\n}\n\nfunction violationToRange(doc: TextDocument, v: Violation) {\n // Prefer autofix ranges when available, otherwise line/column best-effort.\n const edit = v.autofix?.edits?.[0];\n if (edit) {\n return {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n };\n }\n\n const line = Math.max(0, (v.line ?? 1) - 1);\n const char = Math.max(0, (v.column ?? 1) - 1);\n return {\n start: { line, character: char },\n end: { line, character: char + 1 },\n };\n}\n\nexport class SpecBridgeLspServer {\n private connection = createConnection(ProposedFeatures.all);\n private documents = new TextDocuments(TextDocument);\n\n private options: LspServerOptions;\n private registry: Registry | null = null;\n private decisions: Decision[] = [];\n private cwd: string;\n private project: Project;\n private cache = new Map<string, Violation[]>();\n private initError: string | null = null;\n\n constructor(options: LspServerOptions) {\n this.options = options;\n this.cwd = options.cwd;\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n async initialize(): Promise<void> {\n this.connection.onInitialize(async () => {\n await this.initializeWorkspace();\n\n return {\n capabilities: {\n textDocumentSync: TextDocumentSyncKind.Incremental,\n codeActionProvider: true,\n },\n };\n });\n\n this.documents.onDidOpen((e) => {\n void this.validateDocument(e.document);\n });\n\n this.documents.onDidChangeContent((change) => {\n void this.validateDocument(change.document);\n });\n\n this.documents.onDidClose((e) => {\n this.cache.delete(e.document.uri);\n this.connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });\n });\n\n this.connection.onCodeAction((params) => {\n const violations = this.cache.get(params.textDocument.uri) || [];\n const doc = this.documents.get(params.textDocument.uri);\n if (!doc) return [];\n\n return violations\n .filter((v) => v.autofix && v.autofix.edits.length > 0)\n .map((v) => {\n const autofix = v.autofix;\n if (!autofix) {\n return null;\n }\n\n const edits = autofix.edits.map((edit) => ({\n range: {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n },\n newText: edit.text,\n }));\n\n return {\n title: autofix.description,\n kind: CodeActionKind.QuickFix,\n edit: {\n changes: {\n [params.textDocument.uri]: edits,\n },\n },\n };\n })\n .filter((action): action is NonNullable<typeof action> => action !== null);\n });\n\n this.documents.listen(this.connection);\n this.connection.listen();\n }\n\n private async initializeWorkspace(): Promise<void> {\n // Ensure initialized (but keep server alive if not).\n if (!(await pathExists(getSpecBridgeDir(this.cwd)))) {\n const err = new NotInitializedError();\n this.initError = err.message;\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n return;\n }\n\n try {\n const config = await loadConfig(this.cwd);\n\n // Load custom verifier plugins (best-effort). This must not write to stdout.\n try {\n await getPluginLoader().loadPlugins(this.cwd);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (this.options.verbose)\n this.connection.console.error(chalk.red(`Plugin load failed: ${msg}`));\n }\n\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n this.decisions = this.registry.getActive();\n\n // Prime project with source roots (best-effort). This enables verifiers that depend on import graph.\n for (const root of config.project.sourceRoots) {\n // ts-morph doesn't support globs directly; add root folders when possible.\n const rootPath = path.isAbsolute(root) ? root : path.join(this.cwd, root);\n // If root is a glob, fall back to adding the directory portion.\n const dir = rootPath.includes('*') ? rootPath.split('*')[0] : rootPath;\n if (dir && (await pathExists(dir))) {\n this.project.addSourceFilesAtPaths(path.join(dir, '**/*.{ts,tsx,js,jsx}'));\n }\n }\n\n if (this.options.verbose) {\n this.connection.console.log(\n chalk.dim(`Loaded ${this.decisions.length} active decision(s)`)\n );\n }\n } catch (error) {\n this.initError = error instanceof Error ? error.message : String(error);\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n }\n }\n\n private async verifyTextDocument(doc: TextDocument): Promise<Violation[]> {\n if (this.initError) {\n throw new Error(this.initError);\n }\n if (!this.registry) return [];\n\n const filePath = uriToFilePath(doc.uri);\n const sourceFile = this.project.createSourceFile(filePath, doc.getText(), { overwrite: true });\n\n const violations: Violation[] = [];\n\n for (const decision of this.decisions) {\n for (const constraint of decision.constraints) {\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd: this.cwd })) continue;\n\n const verifier = selectVerifierForConstraint(\n constraint.rule,\n constraint.verifier,\n constraint.check\n );\n if (!verifier) continue;\n\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n };\n\n try {\n const constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n } catch {\n // Ignore verifier errors (LSP should stay responsive)\n }\n }\n }\n\n return violations;\n }\n\n private async validateDocument(doc: TextDocument): Promise<void> {\n try {\n const violations = await this.verifyTextDocument(doc);\n this.cache.set(doc.uri, violations);\n\n const diagnostics = violations.map((v) => ({\n range: violationToRange(doc, v),\n severity: severityToDiagnostic(v.severity),\n message: v.message,\n source: 'specbridge',\n }));\n\n this.connection.sendDiagnostics({ uri: doc.uri, diagnostics });\n } catch (error) {\n // If workspace isn't initialized, surface a single diagnostic.\n const msg = error instanceof Error ? error.message : String(error);\n this.connection.sendDiagnostics({\n uri: doc.uri,\n diagnostics: [\n {\n range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },\n severity: DiagnosticSeverity.Error,\n message: msg,\n source: 'specbridge',\n },\n ],\n });\n }\n }\n}\n","import { SpecBridgeLspServer, type LspServerOptions } from './server.js';\n\nexport async function startLspServer(options: LspServerOptions): Promise<void> {\n const server = new SpecBridgeLspServer(options);\n await server.initialize();\n}\n","/**\n * GitHub integration helpers (optional)\n */\nimport type { Violation } from '../core/types/index.js';\n\nexport interface GitHubPrCommentOptions {\n repo: string; // owner/repo\n pr: number;\n token: string;\n}\n\nfunction toMdTable(rows: string[][]): string {\n const header = rows[0];\n if (!header) {\n return '';\n }\n const body = rows.slice(1);\n const sep = header.map(() => '---');\n const lines = [\n `| ${header.join(' | ')} |`,\n `| ${sep.join(' | ')} |`,\n ...body.map((r) => `| ${r.join(' | ')} |`),\n ];\n return lines.join('\\n');\n}\n\nexport function formatViolationsForGitHub(violations: Violation[], limit: number = 50): string {\n if (violations.length === 0) {\n return '## SpecBridge\\n\\n✅ No violations found.';\n }\n\n const rows: string[][] = [['Severity', 'Type', 'File', 'Decision/Constraint', 'Message']];\n\n for (const v of violations.slice(0, limit)) {\n const loc = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n rows.push([\n v.severity,\n v.type,\n `${v.file}${loc}`,\n `${v.decisionId}/${v.constraintId}`,\n // Escape all markdown special characters to prevent table breaking\n v.message\n .replace(/\\\\/g, '\\\\\\\\') // Backslash first\n .replace(/\\|/g, '\\\\|') // Pipe\n .replace(/\\[/g, '\\\\[') // Brackets\n .replace(/\\]/g, '\\\\]')\n .replace(/\\*/g, '\\\\*') // Asterisk\n .replace(/_/g, '\\\\_') // Underscore\n .replace(/`/g, '\\\\`'), // Backtick\n ]);\n }\n\n const extra = violations.length > limit ? `\\n\\n…and ${violations.length - limit} more.` : '';\n return `## SpecBridge\\n\\n${toMdTable(rows)}${extra}`;\n}\n\nexport async function postPrComment(\n violations: Violation[],\n options: GitHubPrCommentOptions\n): Promise<void> {\n const body = formatViolationsForGitHub(violations);\n\n const res = await fetch(\n `https://api.github.com/repos/${options.repo}/issues/${options.pr}/comments`,\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${options.token}`,\n Accept: 'application/vnd.github+json',\n 'Content-Type': 'application/json',\n 'User-Agent': 'specbridge',\n },\n body: JSON.stringify({ body }),\n }\n );\n\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(\n `GitHub comment failed: ${res.status} ${res.statusText}${text ? ` - ${text}` : ''}`\n );\n }\n}\n"],"mappings":";AAGA,SAAS,SAAS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,QACC,QAAQ,OAAO,MAAM,EACrB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK,EACpB,QAAQ,MAAM,KAAK,EACnB,QAAQ,MAAM,KAAK;AAAA;AAAA,IACxB,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ,WAAW,SAAS,QAAQ;AAAA;AAAA,YAAY,WAAW,SAAS,KAAK,WAAW;AAC1F,SAAO;AAAA;AAAA,EAAoB,UAAU,IAAI,CAAC,GAAG,KAAK;AACpD;AAEA,eAAsB,cACpB,YACA,SACe;AACf,QAAM,OAAO,0BAA0B,UAAU;AAEjD,QAAM,MAAM,MAAM;AAAA,IAChB,gCAAgC,QAAQ,IAAI,WAAW,QAAQ,EAAE;AAAA,IACjE;AAAA,MACE,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,eAAe,UAAU,QAAQ,KAAK;AAAA,QACtC,QAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,cAAc;AAAA,MAChB;AAAA,MACA,MAAM,KAAK,UAAU,EAAE,KAAK,CAAC;AAAA,IAC/B;AAAA,EACF;AAEA,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AAC5C,UAAM,IAAI;AAAA,MACR,0BAA0B,IAAI,MAAM,IAAI,IAAI,UAAU,GAAG,OAAO,MAAM,IAAI,KAAK,EAAE;AAAA,IACnF;AAAA,EACF;AACF;","names":["path","z","SeveritySchema","VerificationConfigSchema","path","path","path","join","join","path","dirname","dirname","Node","path","Node","Project","Node","Node","path","relative","path","Node","SyntaxKind","SyntaxKind","Node","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","join","fg","join","fg","pluginLoader","stat","readFile","createHash","readFile","Project","resolve","readFile","createHash","pluginLoader","stdout","readFile","writeFile","buildDependencyGraph","buildDependencyGraph","path","violationsBySeverity","chalk","join","join","z","z","join","dirname","dirname","join","fileURLToPath","path","Project","chalk","fileURLToPath","Project","chalk","path"]}
|