@ipation/specbridge 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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/verifiers/index.ts","../src/verification/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/agent/context.generator.ts","../src/agent/templates.ts","../src/mcp/server.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.string().min(1).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// Single constraint\nexport const ConstraintSchema = z.object({\n id: z.string().min(1).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 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.object({\n automated: z.array(VerificationConfigSchema).optional(),\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 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(data: unknown): { 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.errors.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.object({\n commit: LevelConfigSchema.optional(),\n pr: LevelConfigSchema.optional(),\n full: LevelConfigSchema.optional(),\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(data: unknown): { 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(message: string, public readonly path: string) {\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 += '\\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\n .filter((entry) => entry.isFile())\n .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.errors.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 {\n cwd = process.cwd(),\n ignore = [],\n absolute = false,\n onlyFiles = true,\n } = 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(\n (d) => d.metadata.tags?.includes(tag)\n );\n }\n\n /**\n * Get decisions by owner\n */\n getByOwner(owner: string): Decision[] {\n return this.getAll().filter(\n (d) => d.metadata.owners.includes(owner)\n );\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) =>\n decision.metadata.tags?.includes(tag)\n );\n if (!hasTags) return false;\n }\n\n // Filter by constraint type\n if (filter.constraintType) {\n const hasType = decision.constraints.some((c) =>\n filter.constraintType?.includes(c.type)\n );\n if (!hasType) return false;\n }\n\n // Filter by severity\n if (filter.severity) {\n const hasSeverity = decision.constraints.some((c) =>\n filter.severity?.includes(c.severity)\n );\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\n .getNamedImports()\n .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(\n content: string,\n line: number,\n contextLines: number = 1\n): 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 { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Interfaces use PascalCase' },\n { convention: 'IPrefixed', regex: /^I[A-Z][a-zA-Z0-9]*$/, description: 'Interfaces are prefixed with I' },\n];\n\nconst TYPE_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Types use PascalCase' },\n { convention: 'TSuffixed', regex: /^[A-Z][a-zA-Z0-9]*Type$/, description: 'Types are suffixed with Type' },\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(classes.map(c => c.name), CLASS_PATTERNS);\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(functions.map(f => f.name), FUNCTION_PATTERNS);\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(interfaces.map(i => i.name), INTERFACE_PATTERNS);\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(types.map(t => t.name), TYPE_PATTERNS);\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 modulePath.startsWith('.') && !modulePath.includes('.js') && !modulePath.includes('.ts');\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(i => !i.module.startsWith('.') && !i.module.startsWith('@'));\n const aliasImports = imports.filter(i => i.module.startsWith('@/') || i.module.startsWith('~'));\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 = imp.module.startsWith('@') && parts.length > 1\n ? `${parts[0]}/${parts[1]}`\n : 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(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 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\n .filter(f => basename(dirname(f.path)) === name)\n .slice(0, 3);\n\n patterns.push(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 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 { suffix: '.types.ts', pattern: /\\.types\\.ts$/, description: 'Type definition files use .types.ts suffix' },\n { suffix: '.utils.ts', pattern: /\\.utils\\.ts$/, description: 'Utility files use .utils.ts suffix' },\n { suffix: '.service.ts', pattern: /\\.service\\.ts$/, description: 'Service files use .service.ts suffix' },\n { suffix: '.controller.ts', pattern: /\\.controller\\.ts$/, description: 'Controller files use .controller.ts suffix' },\n { suffix: '.model.ts', pattern: /\\.model\\.ts$/, description: 'Model files use .model.ts suffix' },\n { suffix: '.schema.ts', pattern: /\\.schema\\.ts$/, description: 'Schema files use .schema.ts suffix' },\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(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 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(c =>\n 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} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { selectVerifierForConstraint, type VerificationContext } from './verifiers/index.js';\nimport { glob } from '../utils/glob.js';\nimport { AstCache } from './cache.js';\nimport { shouldApplyConstraintToFile } from './applicability.js';\n\nexport interface VerificationOptions {\n level?: VerificationLevel;\n files?: string[];\n decisions?: string[];\n severity?: Severity[];\n timeout?: number;\n cwd?: string;\n}\n\n/**\n * Verification Engine class\n */\nexport class VerificationEngine {\n private registry: Registry;\n private project: Project;\n private astCache: AstCache;\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 }\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 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 };\n }\n\n // Collect all violations\n const allViolations: Violation[] = [];\n let checked = 0;\n let passed = 0;\n let failed = 0;\n const skipped = 0;\n\n // Process files with timeout\n let timeoutHandle: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<'timeout'>((resolve) => {\n timeoutHandle = setTimeout(() => resolve('timeout'), 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 (violations) => {\n allViolations.push(...violations);\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 };\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 };\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 ): Promise<Violation[]> {\n const violations: Violation[] = [];\n\n const sourceFile = await this.astCache.get(filePath, this.project);\n if (!sourceFile) return violations;\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 continue;\n }\n\n // Get appropriate verifier\n const verifier = selectVerifierForConstraint(constraint.rule, constraint.verifier);\n if (!verifier) {\n continue;\n }\n\n // Run verification\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 // Verifier failed, skip\n }\n }\n }\n\n return violations;\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 onFileVerified: (violations: Violation[]) => void\n ): Promise<void> {\n const BATCH_SIZE = 10;\n for (let i = 0; i < files.length; i += BATCH_SIZE) {\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))\n );\n\n for (const violations of results) {\n onFileVerified(violations);\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}\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 * 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(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 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(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 if (targetType === 'interface') {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n const name = interfaceDecl.getName();\n if (!pattern.regex.test(name)) {\n violations.push(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 if (targetType === 'type') {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const name = typeAlias.getName();\n if (!pattern.regex.test(name)) {\n violations.push(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 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 ((rule.includes('.js') && rule.includes('extension')) || rule.includes('esm') || rule.includes('add .js')) {\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(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 // 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(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 // 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(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 // 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(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 // 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(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 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(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 } 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(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 // 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(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 // 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(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 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(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 } 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(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 } 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(project: Project, fromFilePath: string, moduleSpec: string): 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 graph.get(from)!.add(normalizeFsPath(resolved));\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 lowlink.set(v, Math.min(lowlink.get(v)!, lowlink.get(w)!));\n } else if (onStack.has(w)) {\n lowlink.set(v, Math.min(lowlink.get(v)!, indices.get(w)!));\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 return m ? Number.parseInt(m[1]!, 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 if (!m) return null;\n const value = m[1]!.trim();\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(/(\\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 if (!m) return null;\n return { fromLayer: m[1]!.toLowerCase(), toLayer: m[2]!.toLowerCase() };\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 hasSelfLoop = scc.length === 1 && (graph.get(scc[0]!)?.has(scc[0]!) ?? 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(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: 'Break the cycle by extracting shared abstractions or reversing the dependency',\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(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 // 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(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 // 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(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: 'Use a shallower module boundary (or introduce a public entrypoint for this dependency)',\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 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\nfunction parseLimit(rule: string, pattern: RegExp): number | null {\n const m = rule.match(pattern);\n return m ? Number.parseInt(m[1]!, 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 ('getName' in (fn as any) && typeof (fn as any).getName === 'function') {\n const name = (fn as any).getName();\n if (typeof name === 'string' && name.length > 0) return name;\n }\n\n // Variable = () => ...\n const parent = fn.getParent();\n if (parent?.getKind() === SyntaxKind.VariableDeclaration) {\n const vd: any = parent;\n if (typeof vd.getName === 'function') return vd.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 = parseLimit(rule, /at\\s+most\\s+(\\d+)\\s+parameters?/i) ?? 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(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 const functionLikes = [\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(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 if (maxParams !== null && 'getParameters' in (fn as any)) {\n const params = (fn as any).getParameters();\n const paramCount = Array.isArray(params) ? params.length : 0;\n if (paramCount > maxParams) {\n violations.push(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 if (maxNesting !== null) {\n const depth = maxNestingDepth(fn);\n if (depth > maxNesting) {\n violations.push(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 return violations;\n }\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 = '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 = rule.includes('secret') || rule.includes('password') || rule.includes('token') || rule.includes('api key') || rule.includes('hardcoded');\n const checkEval = rule.includes('eval') || rule.includes('function constructor');\n const checkXss = rule.includes('xss') || rule.includes('innerhtml') || 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(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 for (const pa of sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {\n const nameNode: any = pa.getNameNode?.();\n const propName = nameNode?.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(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 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(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 if (checkXss) {\n // innerHTML assignments\n for (const bin of sourceFile.getDescendantsOfKind(SyntaxKind.BinaryExpression)) {\n const left = bin.getLeft();\n if (left.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n const pa: any = left;\n if (pa.getName?.() === 'innerHTML') {\n violations.push(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 // React dangerouslySetInnerHTML usage\n if (sourceFile.getFullText().includes('dangerouslySetInnerHTML')) {\n violations.push(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 if (checkSql) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n const name = (expr as any).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 = arg.getKind() === SyntaxKind.BinaryExpression && arg.getText().includes('+');\n if (!isTemplate && !isConcat) continue;\n\n const text = arg.getText().toLowerCase();\n if (!text.includes('select') && !text.includes('insert') && !text.includes('update') && !text.includes('delete')) {\n continue;\n }\n\n violations.push(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 if (checkProto) {\n const text = sourceFile.getFullText();\n if (text.includes('__proto__') || text.includes('constructor.prototype')) {\n violations.push(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 return violations;\n }\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 if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const method = (expr as any).getName?.();\n if (!method || !HTTP_METHODS.has(String(method))) continue;\n\n const firstArg = call.getArguments()[0];\n if (!firstArg || firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const pathValue = (firstArg as any).getLiteralValue?.() ?? firstArg.getText().slice(1, -1);\n if (typeof pathValue !== 'string') continue;\n\n if (!isKebabPath(pathValue)) {\n violations.push(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 return violations;\n }\n}\n\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';\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 * Get verifier by ID\n */\nexport function getVerifier(id: string): Verifier | null {\n const factory = builtinVerifiers[id];\n return factory ? factory() : null;\n}\n\n/**\n * Get all verifier IDs\n */\nexport function getVerifierIds(): string[] {\n return Object.keys(builtinVerifiers);\n}\n\n/**\n * Select appropriate verifier based on constraint rule\n */\nexport function selectVerifierForConstraint(rule: string, specifiedVerifier?: string): Verifier | null {\n // If verifier is explicitly specified, use it\n if (specifiedVerifier) {\n return getVerifier(specifiedVerifier);\n }\n\n // Auto-select based on rule content\n const lowerRule = rule.toLowerCase();\n\n if (lowerRule.includes('dependency') || lowerRule.includes('circular dependenc') || lowerRule.includes('import depth') || (lowerRule.includes('layer') && lowerRule.includes('depend on'))) {\n return getVerifier('dependencies');\n }\n\n if (lowerRule.includes('cyclomatic') || lowerRule.includes('complexity') || lowerRule.includes('nesting') || lowerRule.includes('parameters') || lowerRule.includes('file size')) {\n return getVerifier('complexity');\n }\n\n if (lowerRule.includes('security') || lowerRule.includes('secret') || lowerRule.includes('password') || lowerRule.includes('token') || lowerRule.includes('xss') || lowerRule.includes('sql') || lowerRule.includes('eval')) {\n return getVerifier('security');\n }\n\n if (lowerRule.includes('endpoint') || lowerRule.includes('rest') || (lowerRule.includes('api') && lowerRule.includes('path'))) {\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 */\nimport { stat } from 'node:fs/promises';\nimport type { Project, SourceFile } from 'ts-morph';\n\nexport class AstCache {\n private cache = new Map<string, { sourceFile: SourceFile; mtimeMs: number }>();\n\n async get(filePath: string, project: Project): Promise<SourceFile | null> {\n try {\n const info = await stat(filePath);\n const cached = this.cache.get(filePath);\n\n if (cached && cached.mtimeMs >= info.mtimeMs) {\n return cached.sourceFile;\n }\n\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, { sourceFile, mtimeMs: info.mtimeMs });\n return sourceFile;\n } catch {\n return null;\n }\n }\n\n clear(): void {\n this.cache.clear();\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(filePath: string, constraint: Constraint, cwd: string): 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","/**\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('git', ['diff', '--name-only', '--diff-filter=AM', 'HEAD'], { cwd });\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","/**\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 (options.interactive) {\n const ok = await confirmFix(`Apply fix: ${fix.description} (${filePath}:${violation.line ?? 1})?`);\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\n/**\n * Build dependency graph from decisions and file list\n */\nexport async function buildDependencyGraph(\n decisions: Decision[],\n files: string[]\n): Promise<DependencyGraph> {\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)) {\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(\n graph: DependencyGraph,\n decisionId: string\n): 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(\n graph: DependencyGraph,\n filePath: string\n): 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);\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\n // Get affected files\n const affectedFilePaths = getAffectedFiles(this.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(\n affectedFiles,\n totalAutoFixable > 0\n );\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(\n f => f.violations > f.autoFixable\n );\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} 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}\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 // Simple compliance calculation\n // In a real system, this would be based on files checked\n const compliance = violationCount === 0\n ? 100\n : Math.max(0, 100 - Math.min(violationCount * 10, 100));\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 });\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 = 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: any,\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: any[]): 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 = 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: any): 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(` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`);\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: any) => {\n const severity = v.severity.toLowerCase();\n lines.push(` [${v.severity.toUpperCase()}] ${v.decisionId} - ${v.constraintId} (${severity})`);\n lines.push(` ${v.message}`);\n lines.push(` Location: ${v.location?.file || v.file}:${v.location?.line || 0}:${v.location?.column || 0}`);\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: any, 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(` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`);\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, any[]>();\n result.violations.forEach((v: any) => {\n const key = v.severity;\n if (!grouped.has(key)) grouped.set(key, []);\n grouped.get(key)!.push(v);\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, any[]>();\n result.violations.forEach((v: any) => {\n const key = v.location?.file || v.file || 'unknown';\n if (!grouped.has(key)) grouped.set(key, []);\n grouped.get(key)!.push(v);\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: any): 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(`- **Total Violations:** ${result.summary.totalViolations || result.violations?.length || 0}`);\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: any) => {\n lines.push(`#### [${v.severity.toUpperCase()}] ${v.decisionId}`);\n lines.push(`**Message:** ${v.message}`);\n lines.push(`**Location:** \\`${v.location?.file || v.file}:${v.location?.line || 0}\\`\\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(` ${complianceColor(formatComplianceBar(report.summary.compliance))} ${complianceColor(`${report.summary.compliance}%`)}`);\n lines.push('');\n\n // Summary stats\n lines.push(chalk.bold('Summary'));\n lines.push(` Decisions: ${report.summary.activeDecisions} active / ${report.summary.totalDecisions} total`);\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(`- **Active Decisions:** ${report.summary.activeDecisions} / ${report.summary.totalDecisions}`);\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 = 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 * Agent context generator\n */\nimport type {\n AgentContext,\n ApplicableDecision,\n ApplicableConstraint,\n SpecBridgeConfig,\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() } = 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 = constraint.type === 'invariant' ? '🔒' :\n 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: any[];\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: any) => 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.map(d => ({\n ...d,\n constraints: d.constraints.filter((c: any) => {\n const level = severityOrder[c.severity as keyof typeof severityOrder] || 0;\n return level >= minLevel;\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: any[] }): 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: {\n decisions: any[];\n filePath: string;\n }): any[] {\n const { decisions, filePath } = options;\n\n return decisions.filter(d =>\n d.constraints.some((c: any) => 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","/**\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: { filePath: string; includeRationale?: boolean; format?: 'markdown' | 'json' | 'mcp' }) => {\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: { format?: 'summary' | 'detailed' | 'json' | 'markdown'; includeAll?: boolean }) => {\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"],"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,CAAC,UA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O;AAAA,UAClB,SAAS,OAAO;AAAA,UAChB,YAAY,OAAO,QAAQ;AAAA,UAC3B,YAAY,OAAO,QAAQ;AAAA,UAC3B,WAAW,OAAO,QAAQ;AAAA,QAC5B;AACA,eAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE,CAAC,EAAE;AAAA,MAC/E;AAAA,IACF;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","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","stat","Project","resolve","stdout","readFile","writeFile","buildDependencyGraph","buildDependencyGraph","path","z","z"]}
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/verifiers/index.ts","../src/verification/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"],"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.string().min(1).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// Single constraint\nexport const ConstraintSchema = z.object({\n id: z.string().min(1).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 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.object({\n automated: z.array(VerificationConfigSchema).optional(),\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 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(data: unknown): { 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.errors.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.object({\n commit: LevelConfigSchema.optional(),\n pr: LevelConfigSchema.optional(),\n full: LevelConfigSchema.optional(),\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(data: unknown): { 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(message: string, public readonly path: string) {\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 += '\\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\n .filter((entry) => entry.isFile())\n .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.errors.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 {\n cwd = process.cwd(),\n ignore = [],\n absolute = false,\n onlyFiles = true,\n } = 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(\n (d) => d.metadata.tags?.includes(tag)\n );\n }\n\n /**\n * Get decisions by owner\n */\n getByOwner(owner: string): Decision[] {\n return this.getAll().filter(\n (d) => d.metadata.owners.includes(owner)\n );\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) =>\n decision.metadata.tags?.includes(tag)\n );\n if (!hasTags) return false;\n }\n\n // Filter by constraint type\n if (filter.constraintType) {\n const hasType = decision.constraints.some((c) =>\n filter.constraintType?.includes(c.type)\n );\n if (!hasType) return false;\n }\n\n // Filter by severity\n if (filter.severity) {\n const hasSeverity = decision.constraints.some((c) =>\n filter.severity?.includes(c.severity)\n );\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\n .getNamedImports()\n .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(\n content: string,\n line: number,\n contextLines: number = 1\n): 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 { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Interfaces use PascalCase' },\n { convention: 'IPrefixed', regex: /^I[A-Z][a-zA-Z0-9]*$/, description: 'Interfaces are prefixed with I' },\n];\n\nconst TYPE_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Types use PascalCase' },\n { convention: 'TSuffixed', regex: /^[A-Z][a-zA-Z0-9]*Type$/, description: 'Types are suffixed with Type' },\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(classes.map(c => c.name), CLASS_PATTERNS);\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(functions.map(f => f.name), FUNCTION_PATTERNS);\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(interfaces.map(i => i.name), INTERFACE_PATTERNS);\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(types.map(t => t.name), TYPE_PATTERNS);\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 modulePath.startsWith('.') && !modulePath.includes('.js') && !modulePath.includes('.ts');\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(i => !i.module.startsWith('.') && !i.module.startsWith('@'));\n const aliasImports = imports.filter(i => i.module.startsWith('@/') || i.module.startsWith('~'));\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 = imp.module.startsWith('@') && parts.length > 1\n ? `${parts[0]}/${parts[1]}`\n : 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(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 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\n .filter(f => basename(dirname(f.path)) === name)\n .slice(0, 3);\n\n patterns.push(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 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 { suffix: '.types.ts', pattern: /\\.types\\.ts$/, description: 'Type definition files use .types.ts suffix' },\n { suffix: '.utils.ts', pattern: /\\.utils\\.ts$/, description: 'Utility files use .utils.ts suffix' },\n { suffix: '.service.ts', pattern: /\\.service\\.ts$/, description: 'Service files use .service.ts suffix' },\n { suffix: '.controller.ts', pattern: /\\.controller\\.ts$/, description: 'Controller files use .controller.ts suffix' },\n { suffix: '.model.ts', pattern: /\\.model\\.ts$/, description: 'Model files use .model.ts suffix' },\n { suffix: '.schema.ts', pattern: /\\.schema\\.ts$/, description: 'Schema files use .schema.ts suffix' },\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(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 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(c =>\n 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} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { selectVerifierForConstraint, type VerificationContext } from './verifiers/index.js';\nimport { glob } from '../utils/glob.js';\nimport { AstCache } from './cache.js';\nimport { shouldApplyConstraintToFile } from './applicability.js';\n\nexport interface VerificationOptions {\n level?: VerificationLevel;\n files?: string[];\n decisions?: string[];\n severity?: Severity[];\n timeout?: number;\n cwd?: string;\n}\n\n/**\n * Verification Engine class\n */\nexport class VerificationEngine {\n private registry: Registry;\n private project: Project;\n private astCache: AstCache;\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 }\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 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 };\n }\n\n // Collect all violations\n const allViolations: Violation[] = [];\n let checked = 0;\n let passed = 0;\n let failed = 0;\n const skipped = 0;\n\n // Process files with timeout\n let timeoutHandle: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<'timeout'>((resolve) => {\n timeoutHandle = setTimeout(() => resolve('timeout'), 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 (violations) => {\n allViolations.push(...violations);\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 };\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 };\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 ): Promise<Violation[]> {\n const violations: Violation[] = [];\n\n const sourceFile = await this.astCache.get(filePath, this.project);\n if (!sourceFile) return violations;\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 continue;\n }\n\n // Get appropriate verifier\n const verifier = selectVerifierForConstraint(constraint.rule, constraint.verifier);\n if (!verifier) {\n continue;\n }\n\n // Run verification\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 // Verifier failed, skip\n }\n }\n }\n\n return violations;\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 onFileVerified: (violations: Violation[]) => void\n ): Promise<void> {\n const BATCH_SIZE = 10;\n for (let i = 0; i < files.length; i += BATCH_SIZE) {\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))\n );\n\n for (const violations of results) {\n onFileVerified(violations);\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}\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 * 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(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 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(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 if (targetType === 'interface') {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n const name = interfaceDecl.getName();\n if (!pattern.regex.test(name)) {\n violations.push(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 if (targetType === 'type') {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const name = typeAlias.getName();\n if (!pattern.regex.test(name)) {\n violations.push(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 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 ((rule.includes('.js') && rule.includes('extension')) || rule.includes('esm') || rule.includes('add .js')) {\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(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 // 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(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 // 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(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 // 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(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 // 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(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 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(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 } 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(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 // 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(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 // 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(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 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(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 } 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(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 } 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(project: Project, fromFilePath: string, moduleSpec: string): 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 graph.get(from)!.add(normalizeFsPath(resolved));\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 lowlink.set(v, Math.min(lowlink.get(v)!, lowlink.get(w)!));\n } else if (onStack.has(w)) {\n lowlink.set(v, Math.min(lowlink.get(v)!, indices.get(w)!));\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 return m ? Number.parseInt(m[1]!, 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 if (!m) return null;\n const value = m[1]!.trim();\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(/(\\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 if (!m) return null;\n return { fromLayer: m[1]!.toLowerCase(), toLayer: m[2]!.toLowerCase() };\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 hasSelfLoop = scc.length === 1 && (graph.get(scc[0]!)?.has(scc[0]!) ?? 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(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: 'Break the cycle by extracting shared abstractions or reversing the dependency',\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(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 // 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(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 // 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(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: 'Use a shallower module boundary (or introduce a public entrypoint for this dependency)',\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 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\nfunction parseLimit(rule: string, pattern: RegExp): number | null {\n const m = rule.match(pattern);\n return m ? Number.parseInt(m[1]!, 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 ('getName' in (fn as any) && typeof (fn as any).getName === 'function') {\n const name = (fn as any).getName();\n if (typeof name === 'string' && name.length > 0) return name;\n }\n\n // Variable = () => ...\n const parent = fn.getParent();\n if (parent?.getKind() === SyntaxKind.VariableDeclaration) {\n const vd: any = parent;\n if (typeof vd.getName === 'function') return vd.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 = parseLimit(rule, /at\\s+most\\s+(\\d+)\\s+parameters?/i) ?? 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(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 const functionLikes = [\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(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 if (maxParams !== null && 'getParameters' in (fn as any)) {\n const params = (fn as any).getParameters();\n const paramCount = Array.isArray(params) ? params.length : 0;\n if (paramCount > maxParams) {\n violations.push(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 if (maxNesting !== null) {\n const depth = maxNestingDepth(fn);\n if (depth > maxNesting) {\n violations.push(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 return violations;\n }\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 = '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 = rule.includes('secret') || rule.includes('password') || rule.includes('token') || rule.includes('api key') || rule.includes('hardcoded');\n const checkEval = rule.includes('eval') || rule.includes('function constructor');\n const checkXss = rule.includes('xss') || rule.includes('innerhtml') || 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(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 for (const pa of sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {\n const nameNode: any = pa.getNameNode?.();\n const propName = nameNode?.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(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 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(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 if (checkXss) {\n // innerHTML assignments\n for (const bin of sourceFile.getDescendantsOfKind(SyntaxKind.BinaryExpression)) {\n const left = bin.getLeft();\n if (left.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n const pa: any = left;\n if (pa.getName?.() === 'innerHTML') {\n violations.push(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 // React dangerouslySetInnerHTML usage\n if (sourceFile.getFullText().includes('dangerouslySetInnerHTML')) {\n violations.push(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 if (checkSql) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n const name = (expr as any).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 = arg.getKind() === SyntaxKind.BinaryExpression && arg.getText().includes('+');\n if (!isTemplate && !isConcat) continue;\n\n const text = arg.getText().toLowerCase();\n if (!text.includes('select') && !text.includes('insert') && !text.includes('update') && !text.includes('delete')) {\n continue;\n }\n\n violations.push(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 if (checkProto) {\n const text = sourceFile.getFullText();\n if (text.includes('__proto__') || text.includes('constructor.prototype')) {\n violations.push(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 return violations;\n }\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 if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const method = (expr as any).getName?.();\n if (!method || !HTTP_METHODS.has(String(method))) continue;\n\n const firstArg = call.getArguments()[0];\n if (!firstArg || firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const pathValue = (firstArg as any).getLiteralValue?.() ?? firstArg.getText().slice(1, -1);\n if (typeof pathValue !== 'string') continue;\n\n if (!isKebabPath(pathValue)) {\n violations.push(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 return violations;\n }\n}\n\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';\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 * Get verifier by ID\n */\nexport function getVerifier(id: string): Verifier | null {\n const factory = builtinVerifiers[id];\n return factory ? factory() : null;\n}\n\n/**\n * Get all verifier IDs\n */\nexport function getVerifierIds(): string[] {\n return Object.keys(builtinVerifiers);\n}\n\n/**\n * Select appropriate verifier based on constraint rule\n */\nexport function selectVerifierForConstraint(rule: string, specifiedVerifier?: string): Verifier | null {\n // If verifier is explicitly specified, use it\n if (specifiedVerifier) {\n return getVerifier(specifiedVerifier);\n }\n\n // Auto-select based on rule content\n const lowerRule = rule.toLowerCase();\n\n if (lowerRule.includes('dependency') || lowerRule.includes('circular dependenc') || lowerRule.includes('import depth') || (lowerRule.includes('layer') && lowerRule.includes('depend on'))) {\n return getVerifier('dependencies');\n }\n\n if (lowerRule.includes('cyclomatic') || lowerRule.includes('complexity') || lowerRule.includes('nesting') || lowerRule.includes('parameters') || lowerRule.includes('file size')) {\n return getVerifier('complexity');\n }\n\n if (lowerRule.includes('security') || lowerRule.includes('secret') || lowerRule.includes('password') || lowerRule.includes('token') || lowerRule.includes('xss') || lowerRule.includes('sql') || lowerRule.includes('eval')) {\n return getVerifier('security');\n }\n\n if (lowerRule.includes('endpoint') || lowerRule.includes('rest') || (lowerRule.includes('api') && lowerRule.includes('path'))) {\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 */\nimport { stat } from 'node:fs/promises';\nimport type { Project, SourceFile } from 'ts-morph';\n\nexport class AstCache {\n private cache = new Map<string, { sourceFile: SourceFile; mtimeMs: number }>();\n\n async get(filePath: string, project: Project): Promise<SourceFile | null> {\n try {\n const info = await stat(filePath);\n const cached = this.cache.get(filePath);\n\n if (cached && cached.mtimeMs >= info.mtimeMs) {\n return cached.sourceFile;\n }\n\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, { sourceFile, mtimeMs: info.mtimeMs });\n return sourceFile;\n } catch {\n return null;\n }\n }\n\n clear(): void {\n this.cache.clear();\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(filePath: string, constraint: Constraint, cwd: string): 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","/**\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('git', ['diff', '--name-only', '--diff-filter=AM', 'HEAD'], { cwd });\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","/**\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 (options.interactive) {\n const ok = await confirmFix(`Apply fix: ${fix.description} (${filePath}:${violation.line ?? 1})?`);\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\n/**\n * Build dependency graph from decisions and file list\n */\nexport async function buildDependencyGraph(\n decisions: Decision[],\n files: string[]\n): Promise<DependencyGraph> {\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)) {\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(\n graph: DependencyGraph,\n decisionId: string\n): 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(\n graph: DependencyGraph,\n filePath: string\n): 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);\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\n // Get affected files\n const affectedFilePaths = getAffectedFiles(this.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(\n affectedFiles,\n totalAutoFixable > 0\n );\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(\n f => f.violations > f.autoFixable\n );\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} 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}\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 // Simple compliance calculation\n // In a real system, this would be based on files checked\n const compliance = violationCount === 0\n ? 100\n : Math.max(0, 100 - Math.min(violationCount * 10, 100));\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 });\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 = 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: any,\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: any[]): 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 = 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: any): 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(` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`);\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: any) => {\n const severity = v.severity.toLowerCase();\n lines.push(` [${v.severity.toUpperCase()}] ${v.decisionId} - ${v.constraintId} (${severity})`);\n lines.push(` ${v.message}`);\n lines.push(` Location: ${v.location?.file || v.file}:${v.location?.line || 0}:${v.location?.column || 0}`);\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: any, 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(` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`);\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, any[]>();\n result.violations.forEach((v: any) => {\n const key = v.severity;\n if (!grouped.has(key)) grouped.set(key, []);\n grouped.get(key)!.push(v);\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, any[]>();\n result.violations.forEach((v: any) => {\n const key = v.location?.file || v.file || 'unknown';\n if (!grouped.has(key)) grouped.set(key, []);\n grouped.get(key)!.push(v);\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: any): 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(`- **Total Violations:** ${result.summary.totalViolations || result.violations?.length || 0}`);\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: any) => {\n lines.push(`#### [${v.severity.toUpperCase()}] ${v.decisionId}`);\n lines.push(`**Message:** ${v.message}`);\n lines.push(`**Location:** \\`${v.location?.file || v.file}:${v.location?.line || 0}\\`\\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(` ${complianceColor(formatComplianceBar(report.summary.compliance))} ${complianceColor(`${report.summary.compliance}%`)}`);\n lines.push('');\n\n // Summary stats\n lines.push(chalk.bold('Summary'));\n lines.push(` Decisions: ${report.summary.activeDecisions} active / ${report.summary.totalDecisions} total`);\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(`- **Active Decisions:** ${report.summary.activeDecisions} / ${report.summary.totalDecisions}`);\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 = 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';\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\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 */\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\n const reports: StoredReport[] = [];\n for (const file of recentFiles) {\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 reports.push({ timestamp, report });\n } catch (error) {\n // Skip corrupted files\n console.warn(`Warning: Failed to load report ${file}:`, error);\n }\n }\n\n return reports;\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 console.warn(`Warning: Failed to delete old report ${file}:`, error);\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(\n d => d.decisionId === currDecision.decisionId\n );\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 +\n fixedViolations.high +\n fixedViolations.medium +\n 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.sort((a, b) => b.complianceChange - a.complianceChange).slice(0, 5);\n const mostDegraded = degrading.sort((a, b) => a.complianceChange - b.complianceChange).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 decisionMap.get(decision.decisionId)!.push(decision);\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} 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() } = 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 = constraint.type === 'invariant' ? '🔒' :\n 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: any[];\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: any) => 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.map(d => ({\n ...d,\n constraints: d.constraints.filter((c: any) => {\n const level = severityOrder[c.severity as keyof typeof severityOrder] || 0;\n return level >= minLevel;\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: any[] }): 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: {\n decisions: any[];\n filePath: string;\n }): any[] {\n const { decisions, filePath } = options;\n\n return decisions.filter(d =>\n d.constraints.some((c: any) => 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","/**\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: { filePath: string; includeRationale?: boolean; format?: 'markdown' | 'json' | 'mcp' }) => {\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: { format?: 'summary' | 'detailed' | 'json' | 'markdown'; includeAll?: boolean }) => {\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"],"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,CAAC,UAAU,MAAM,SAAS,QAAQ,CAAC;AAG9E,IAAM,yBAAyB,EAAE,OAAO;AAAA,EAC7C,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,gBAAgB,gDAAgD;AAAA,EAC5F,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAAA,EAChC,QAAQ;AAAA,EACR,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,IAAI,CAAC;AAAA,EACxC,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC1C,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC1C,cAAc,EAAE,OAAO,EAAE,SAAS;AAAA,EAClC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AACrC,CAAC;AAGM,IAAM,wBAAwB,EAAE,OAAO;AAAA,EAC5C,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAAA,EAClC,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC3B,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,cAAc,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAC7C,CAA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AK,OAAO;AAAA,MACV;AAAA,MACA;AAAA,QACE,OAAO;AAAA,QACP,aAAa;AAAA,QACb,aAAa;AAAA,UACX,QAAQA,GAAE,KAAK,CAAC,WAAW,YAAY,QAAQ,UAAU,CAAC,EAAE,SAAS,EAAE,QAAQ,SAAS;AAAA,UACxF,YAAYA,GAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,KAAK;AAAA,QAClD;AAAA,MACF;AAAA,MACA,OAAO,SAA0F;AAC/F,cAAM,SAAS,MAAM,eAAe,QAAQ,EAAE,KAAK,KAAK,KAAK,YAAY,KAAK,WAAW,CAAC;AAE1F,YAAI,KAAK,WAAW,QAAQ;AAC1B,iBAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE,CAAC,EAAE;AAAA,QAC9E;AAEA,YAAI,KAAK,WAAW,YAAY;AAC9B,iBAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qBAAqB,MAAM,EAAE,CAAC,EAAE;AAAA,QAC3E;AAEA,YAAI,KAAK,WAAW,YAAY;AAC9B,iBAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,oBAAoB,MAAM,EAAE,CAAC,EAAE;AAAA,QAC1E;AAGA,cAAM,UAAU;AAAA,UACd,WAAW,OAAO;AAAA,UAClB,SAAS,OAAO;AAAA,UAChB,YAAY,OAAO,QAAQ;AAAA,UAC3B,YAAY,OAAO,QAAQ;AAAA,UAC3B,WAAW,OAAO,QAAQ;AAAA,QAC5B;AACA,eAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE,CAAC,EAAE;AAAA,MAC/E;AAAA,IACF;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","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","stat","Project","resolve","stdout","readFile","writeFile","buildDependencyGraph","buildDependencyGraph","path","join","join","z","z"]}