@ipation/specbridge 1.1.2 → 1.2.1

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/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli/index.ts","../src/core/errors/index.ts","../src/cli/commands/init.ts","../src/utils/fs.ts","../src/utils/yaml.ts","../src/core/schemas/config.schema.ts","../src/cli/commands/infer.ts","../src/inference/scanner.ts","../src/utils/glob.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/config/loader.ts","../src/cli/commands/verify.ts","../src/verification/engine.ts","../src/registry/loader.ts","../src/core/schemas/decision.schema.ts","../src/registry/registry.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/autofix/engine.ts","../src/verification/incremental.ts","../src/cli/commands/decision/index.ts","../src/cli/commands/decision/list.ts","../src/cli/commands/decision/show.ts","../src/cli/commands/decision/validate.ts","../src/cli/commands/decision/create.ts","../src/cli/commands/hook.ts","../src/cli/commands/report.ts","../src/reporting/reporter.ts","../src/reporting/formats/console.ts","../src/reporting/formats/markdown.ts","../src/cli/commands/context.ts","../src/agent/context.generator.ts","../src/cli/commands/lsp.ts","../src/lsp/server.ts","../src/lsp/index.ts","../src/cli/commands/watch.ts","../src/cli/commands/mcp-server.ts","../src/mcp/server.ts","../src/cli/commands/prompt.ts","../src/agent/templates.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * SpecBridge CLI Entry Point\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { formatError } from '../core/errors/index.js';\n\n// Import commands\nimport { initCommand } from './commands/init.js';\nimport { inferCommand } from './commands/infer.js';\nimport { verifyCommand } from './commands/verify.js';\nimport { decisionCommand } from './commands/decision/index.js';\nimport { hookCommand } from './commands/hook.js';\nimport { reportCommand } from './commands/report.js';\nimport { contextCommand } from './commands/context.js';\nimport { lspCommand } from './commands/lsp.js';\nimport { watchCommand } from './commands/watch.js';\nimport { mcpServerCommand } from './commands/mcp-server.js';\nimport { promptCommand } from './commands/prompt.js';\n\n// Read version from package.json\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n// In development: src/cli/index.ts -> ../../package.json\n// In production: dist/cli.js -> ../package.json\nconst packageJsonPath = join(__dirname, '../package.json');\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n\nconst program = new Command();\n\nprogram\n .name('specbridge')\n .description('Architecture Decision Runtime - Transform architectural decisions into executable, verifiable constraints')\n .version(packageJson.version);\n\n// Register commands\nprogram.addCommand(initCommand);\nprogram.addCommand(inferCommand);\nprogram.addCommand(verifyCommand);\nprogram.addCommand(decisionCommand);\nprogram.addCommand(hookCommand);\nprogram.addCommand(reportCommand);\nprogram.addCommand(contextCommand);\nprogram.addCommand(lspCommand);\nprogram.addCommand(watchCommand);\nprogram.addCommand(mcpServerCommand);\nprogram.addCommand(promptCommand);\n\n// Global error handler\nprogram.exitOverride((err) => {\n if (err.code === 'commander.help' || err.code === 'commander.helpDisplayed') {\n process.exit(0);\n }\n if (err.code === 'commander.version') {\n process.exit(0);\n }\n console.error(chalk.red(formatError(err)));\n process.exit(1);\n});\n\n// Parse and execute\nprogram.parseAsync(process.argv).catch((error: Error) => {\n console.error(chalk.red(formatError(error)));\n process.exit(1);\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 * Init command - Initialize SpecBridge in a project\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport {\n pathExists,\n ensureDir,\n writeTextFile,\n getSpecBridgeDir,\n getDecisionsDir,\n getVerifiersDir,\n getInferredDir,\n getReportsDir,\n getConfigPath,\n} from '../../utils/fs.js';\nimport { stringifyYaml } from '../../utils/yaml.js';\nimport { defaultConfig } from '../../core/schemas/config.schema.js';\nimport { AlreadyInitializedError } from '../../core/errors/index.js';\n\ninterface InitOptions {\n force?: boolean;\n name?: string;\n}\n\nexport const initCommand = new Command('init')\n .description('Initialize SpecBridge in the current project')\n .option('-f, --force', 'Overwrite existing configuration')\n .option('-n, --name <name>', 'Project name')\n .action(async (options: InitOptions) => {\n const cwd = process.cwd();\n const specbridgeDir = getSpecBridgeDir(cwd);\n\n // Check if already initialized\n if (!options.force && await pathExists(specbridgeDir)) {\n throw new AlreadyInitializedError(specbridgeDir);\n }\n\n const spinner = ora('Initializing SpecBridge...').start();\n\n try {\n // Create directory structure\n await ensureDir(specbridgeDir);\n await ensureDir(getDecisionsDir(cwd));\n await ensureDir(getVerifiersDir(cwd));\n await ensureDir(getInferredDir(cwd));\n await ensureDir(getReportsDir(cwd));\n\n // Determine project name\n const projectName = options.name || getProjectNameFromPath(cwd);\n\n // Create config file\n const config = {\n ...defaultConfig,\n project: {\n ...defaultConfig.project,\n name: projectName,\n },\n };\n\n const configContent = stringifyYaml(config);\n await writeTextFile(getConfigPath(cwd), configContent);\n\n // Create example decision\n const exampleDecision = createExampleDecision(projectName);\n await writeTextFile(\n join(getDecisionsDir(cwd), 'example.decision.yaml'),\n stringifyYaml(exampleDecision)\n );\n\n // Create .gitkeep files\n await writeTextFile(join(getVerifiersDir(cwd), '.gitkeep'), '');\n await writeTextFile(join(getInferredDir(cwd), '.gitkeep'), '');\n await writeTextFile(join(getReportsDir(cwd), '.gitkeep'), '');\n\n spinner.succeed('SpecBridge initialized successfully!');\n\n console.log('');\n console.log(chalk.green('Created:'));\n console.log(` ${chalk.dim('.specbridge/')}`);\n console.log(` ${chalk.dim('├──')} config.yaml`);\n console.log(` ${chalk.dim('├──')} decisions/`);\n console.log(` ${chalk.dim('│ └──')} example.decision.yaml`);\n console.log(` ${chalk.dim('├──')} verifiers/`);\n console.log(` ${chalk.dim('├──')} inferred/`);\n console.log(` ${chalk.dim('└──')} reports/`);\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(` 1. Edit ${chalk.bold('.specbridge/config.yaml')} to configure source paths`);\n console.log(` 2. Run ${chalk.bold('specbridge infer')} to detect patterns in your codebase`);\n console.log(` 3. Create decisions in ${chalk.bold('.specbridge/decisions/')}`);\n console.log(` 4. Run ${chalk.bold('specbridge verify')} to check compliance`);\n } catch (error) {\n spinner.fail('Failed to initialize SpecBridge');\n throw error;\n }\n });\n\n/**\n * Extract project name from directory path\n */\nfunction getProjectNameFromPath(dirPath: string): string {\n const parts = dirPath.split(/[/\\\\]/);\n return parts[parts.length - 1] || 'my-project';\n}\n\n/**\n * Create an example decision for new projects\n */\nfunction createExampleDecision(projectName: string) {\n return {\n kind: 'Decision',\n metadata: {\n id: 'example-001',\n title: 'Example Decision - Error Handling Convention',\n status: 'draft',\n owners: ['team'],\n tags: ['example', 'error-handling'],\n },\n decision: {\n summary: 'All errors should be handled using a consistent error class hierarchy.',\n rationale: `Consistent error handling improves debugging and makes the codebase more maintainable.\nThis is an example decision to demonstrate SpecBridge functionality.`,\n context: `This decision was auto-generated when initializing SpecBridge for ${projectName}.\nReplace or delete this file and create your own architectural decisions.`,\n },\n constraints: [\n {\n id: 'custom-errors',\n type: 'convention',\n rule: 'Custom error classes should extend a base AppError class',\n severity: 'medium',\n scope: 'src/**/*.ts',\n },\n {\n id: 'error-logging',\n type: 'guideline',\n rule: 'Errors should be logged with appropriate context before being thrown or handled',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n ],\n };\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 * 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 * Infer command - Detect patterns in the codebase\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { createInferenceEngine, getAnalyzerIds } from '../../inference/index.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { writeTextFile, getInferredDir, pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { Pattern } from '../../core/types/index.js';\n\ninterface InferOptions {\n output?: string;\n minConfidence?: string;\n analyzers?: string;\n json?: boolean;\n save?: boolean;\n}\n\nexport const inferCommand = new Command('infer')\n .description('Analyze codebase and detect patterns')\n .option('-o, --output <file>', 'Output file path')\n .option('-c, --min-confidence <number>', 'Minimum confidence threshold (0-100)', '50')\n .option('-a, --analyzers <list>', 'Comma-separated list of analyzers to run')\n .option('--json', 'Output as JSON')\n .option('--save', 'Save results to .specbridge/inferred/')\n .action(async (options: InferOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Loading configuration...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Parse options\n const minConfidence = parseInt(options.minConfidence || '50', 10);\n const analyzerList = options.analyzers\n ? options.analyzers.split(',').map(a => a.trim())\n : config.inference?.analyzers || getAnalyzerIds();\n\n spinner.text = `Scanning codebase (analyzers: ${analyzerList.join(', ')})...`;\n\n // Run inference\n const engine = createInferenceEngine();\n const result = await engine.infer({\n analyzers: analyzerList,\n minConfidence,\n sourceRoots: config.project.sourceRoots,\n exclude: config.project.exclude,\n cwd,\n });\n\n spinner.succeed(`Scanned ${result.filesScanned} files in ${result.duration}ms`);\n\n // Save results first (even if empty) if requested\n if (options.save || options.output) {\n const outputPath = options.output || join(getInferredDir(cwd), 'patterns.json');\n await writeTextFile(outputPath, JSON.stringify(result, null, 2));\n console.log(chalk.green(`\\nResults saved to: ${outputPath}`));\n }\n\n if (result.patterns.length === 0) {\n console.log(chalk.yellow('\\nNo patterns detected above confidence threshold.'));\n console.log(chalk.dim(`Try lowering --min-confidence (current: ${minConfidence})`));\n return;\n }\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n printPatterns(result.patterns);\n }\n\n // Show next steps\n if (!options.json) {\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(' Review detected patterns and create decisions for important ones.');\n console.log(` Use ${chalk.bold('specbridge decision create <id>')} to create a new decision.`);\n }\n } catch (error) {\n spinner.fail('Inference failed');\n throw error;\n }\n });\n\nfunction printPatterns(patterns: Pattern[]): void {\n console.log(chalk.bold(`\\nDetected ${patterns.length} pattern(s):\\n`));\n\n for (const pattern of patterns) {\n const confidenceColor = pattern.confidence >= 80\n ? chalk.green\n : pattern.confidence >= 60\n ? chalk.yellow\n : chalk.dim;\n\n console.log(chalk.bold(`${pattern.name}`));\n console.log(chalk.dim(` ID: ${pattern.id}`));\n console.log(` ${pattern.description}`);\n console.log(` Confidence: ${confidenceColor(`${pattern.confidence}%`)} (${pattern.occurrences} occurrences)`);\n console.log(chalk.dim(` Analyzer: ${pattern.analyzer}`));\n\n if (pattern.examples.length > 0) {\n console.log(chalk.dim(' Examples:'));\n for (const example of pattern.examples.slice(0, 2)) {\n console.log(chalk.dim(` - ${example.file}:${example.line}`));\n console.log(chalk.dim(` ${example.snippet}`));\n }\n }\n\n if (pattern.suggestedConstraint) {\n const typeColor =\n pattern.suggestedConstraint.type === 'invariant' ? chalk.red :\n pattern.suggestedConstraint.type === 'convention' ? chalk.yellow :\n chalk.green;\n\n console.log(chalk.cyan(' Suggested constraint:'));\n console.log(` Type: ${typeColor(pattern.suggestedConstraint.type || 'convention')}`);\n console.log(` Rule: ${pattern.suggestedConstraint.rule}`);\n }\n\n console.log('');\n }\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 * 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 * 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 * 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 * Verify command - Check code compliance\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { AutofixEngine, type AutofixResult } from '../../verification/autofix/engine.js';\nimport { getChangedFiles } from '../../verification/incremental.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { Violation, VerificationLevel, Severity } from '../../core/types/index.js';\n\ninterface VerifyOptions {\n level?: string;\n files?: string;\n decisions?: string;\n severity?: string;\n json?: boolean;\n fix?: boolean;\n dryRun?: boolean;\n interactive?: boolean;\n incremental?: boolean;\n}\n\nexport const verifyCommand = new Command('verify')\n .description('Verify code compliance against decisions')\n .option('-l, --level <level>', 'Verification level (commit, pr, full)', 'full')\n .option('-f, --files <patterns>', 'Comma-separated file patterns to check')\n .option('-d, --decisions <ids>', 'Comma-separated decision IDs to check')\n .option('-s, --severity <levels>', 'Comma-separated severity levels (critical, high, medium, low)')\n .option('--json', 'Output as JSON')\n .option('--incremental', 'Only verify changed files (git diff --name-only --diff-filter=AM HEAD)')\n .option('--fix', 'Apply auto-fixes for supported violations')\n .option('--dry-run', 'Show what would be fixed without applying (requires --fix)')\n .option('--interactive', 'Confirm each fix interactively (requires --fix)')\n .action(async (options: VerifyOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Loading configuration...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Parse options\n const level = (options.level || 'full') as VerificationLevel;\n let files = options.files?.split(',').map(f => f.trim());\n const decisions = options.decisions?.split(',').map(d => d.trim());\n const severity = options.severity?.split(',').map(s => s.trim() as Severity);\n\n if (options.incremental) {\n const changed = await getChangedFiles(cwd);\n files = changed.length > 0 ? changed : [];\n }\n\n spinner.text = `Running ${level}-level verification...`;\n\n // Run verification\n const engine = createVerificationEngine();\n let result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n\n // Apply auto-fixes (optional)\n let fixResult: AutofixResult | undefined;\n if (options.fix && result.violations.length > 0) {\n const fixableCount = result.violations.filter(v => v.autofix).length;\n\n if (fixableCount === 0) {\n spinner.stop();\n if (!options.json) {\n console.log(chalk.yellow('No auto-fixable violations found'));\n }\n } else {\n spinner.text = `Applying ${fixableCount} auto-fix(es)...`;\n const fixer = new AutofixEngine();\n fixResult = await fixer.applyFixes(result.violations, {\n dryRun: options.dryRun,\n interactive: options.interactive,\n });\n\n if (!options.dryRun && fixResult.applied.length > 0) {\n result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n }\n }\n }\n\n spinner.stop();\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify({ ...result, autofix: fixResult }, null, 2));\n } else {\n printResult(result, level);\n\n if (options.fix && fixResult) {\n console.log(chalk.green(`✓ Applied ${fixResult.applied.length} fix(es)`));\n if (fixResult.skipped > 0) {\n console.log(chalk.yellow(`⊘ Skipped ${fixResult.skipped} fix(es)`));\n }\n console.log('');\n }\n }\n\n // Exit with error code if verification failed\n if (!result.success) {\n process.exit(1);\n }\n } catch (error) {\n spinner.fail('Verification failed');\n throw error;\n }\n });\n\nfunction printResult(\n result: { success: boolean; violations: Violation[]; checked: number; passed: number; failed: number; skipped: number; duration: number },\n level: VerificationLevel\n): void {\n console.log('');\n\n if (result.violations.length === 0) {\n console.log(chalk.green('✓ All checks passed!'));\n console.log(chalk.dim(` ${result.checked} files checked in ${result.duration}ms`));\n return;\n }\n\n // Group violations by file\n const byFile = new Map<string, Violation[]>();\n for (const violation of result.violations) {\n const existing = byFile.get(violation.file) || [];\n existing.push(violation);\n byFile.set(violation.file, existing);\n }\n\n // Print violations by file\n for (const [file, violations] of byFile) {\n console.log(chalk.underline(file));\n\n for (const v of violations) {\n const typeIcon = getTypeIcon(v.type);\n const severityColor = getSeverityColor(v.severity);\n const location = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n\n console.log(\n ` ${typeIcon} ${severityColor(`[${v.severity}]`)} ${v.message}`\n );\n console.log(chalk.dim(` ${v.decisionId}/${v.constraintId}${location}`));\n\n if (v.suggestion) {\n console.log(chalk.cyan(` Suggestion: ${v.suggestion}`));\n }\n }\n\n console.log('');\n }\n\n // Summary\n const criticalCount = result.violations.filter(v => v.severity === 'critical').length;\n const highCount = result.violations.filter(v => v.severity === 'high').length;\n const mediumCount = result.violations.filter(v => v.severity === 'medium').length;\n const lowCount = result.violations.filter(v => v.severity === 'low').length;\n\n console.log(chalk.bold('Summary:'));\n console.log(` Files: ${result.checked} checked, ${result.passed} passed, ${result.failed} failed`);\n\n const violationParts: string[] = [];\n if (criticalCount > 0) violationParts.push(chalk.red(`${criticalCount} critical`));\n if (highCount > 0) violationParts.push(chalk.yellow(`${highCount} high`));\n if (mediumCount > 0) violationParts.push(chalk.cyan(`${mediumCount} medium`));\n if (lowCount > 0) violationParts.push(chalk.dim(`${lowCount} low`));\n\n console.log(` Violations: ${violationParts.join(', ')}`);\n console.log(` Duration: ${result.duration}ms`);\n\n if (!result.success) {\n console.log('');\n const blockingTypes = level === 'commit'\n ? 'invariant or critical'\n : level === 'pr'\n ? 'invariant, critical, or high'\n : 'invariant';\n console.log(chalk.red(`✗ Verification failed. ${blockingTypes} violations must be resolved.`));\n }\n}\n\nfunction getTypeIcon(type: string): string {\n switch (type) {\n case 'invariant':\n return chalk.red('●');\n case 'convention':\n return chalk.yellow('●');\n case 'guideline':\n return chalk.green('●');\n default:\n return '○';\n }\n}\n\nfunction getSeverityColor(severity: Severity): (text: string) => string {\n switch (severity) {\n case 'critical':\n return chalk.red;\n case 'high':\n return chalk.yellow;\n case 'medium':\n return chalk.cyan;\n case 'low':\n return chalk.dim;\n default:\n return chalk.white;\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 * 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 * 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 * 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 * 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 * 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 * 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 * Decision command group\n */\nimport { Command } from 'commander';\nimport { listDecisions } from './list.js';\nimport { showDecision } from './show.js';\nimport { validateDecisions } from './validate.js';\nimport { createDecision } from './create.js';\n\nexport const decisionCommand = new Command('decision')\n .description('Manage architectural decisions')\n .addCommand(listDecisions)\n .addCommand(showDecision)\n .addCommand(validateDecisions)\n .addCommand(createDecision);\n","/**\n * List decisions command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { table } from 'table';\nimport { createRegistry } from '../../../registry/registry.js';\nimport type { DecisionStatus, ConstraintType } from '../../../core/types/index.js';\n\ninterface ListOptions {\n status?: string;\n tag?: string;\n json?: boolean;\n}\n\nexport const listDecisions = new Command('list')\n .description('List all architectural decisions')\n .option('-s, --status <status>', 'Filter by status (draft, active, deprecated, superseded)')\n .option('-t, --tag <tag>', 'Filter by tag')\n .option('--json', 'Output as JSON')\n .action(async (options: ListOptions) => {\n const registry = createRegistry();\n const result = await registry.load();\n\n // Show loading errors as warnings\n if (result.errors.length > 0) {\n console.warn(chalk.yellow('\\nWarnings:'));\n for (const err of result.errors) {\n console.warn(chalk.yellow(` - ${err.filePath}: ${err.error}`));\n }\n console.log('');\n }\n\n // Apply filters\n const filter: { status?: DecisionStatus[]; tags?: string[] } = {};\n if (options.status) {\n filter.status = [options.status as DecisionStatus];\n }\n if (options.tag) {\n filter.tags = [options.tag];\n }\n\n const decisions = registry.getAll(filter);\n\n if (decisions.length === 0) {\n console.log(chalk.yellow('No decisions found.'));\n return;\n }\n\n if (options.json) {\n console.log(JSON.stringify(decisions, null, 2));\n return;\n }\n\n // Create table\n const data: string[][] = [\n [\n chalk.bold('ID'),\n chalk.bold('Title'),\n chalk.bold('Status'),\n chalk.bold('Constraints'),\n chalk.bold('Tags'),\n ],\n ];\n\n for (const decision of decisions) {\n const statusColor = getStatusColor(decision.metadata.status);\n const constraintTypes = getConstraintTypeSummary(decision.constraints.map(c => c.type));\n\n data.push([\n decision.metadata.id,\n truncate(decision.metadata.title, 40),\n statusColor(decision.metadata.status),\n constraintTypes,\n (decision.metadata.tags || []).join(', ') || '-',\n ]);\n }\n\n console.log(table(data, {\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 console.log(chalk.dim(`Total: ${decisions.length} decision(s)`));\n });\n\nfunction getStatusColor(status: DecisionStatus): (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 getConstraintTypeSummary(types: ConstraintType[]): string {\n const counts = {\n invariant: 0,\n convention: 0,\n guideline: 0,\n };\n\n for (const type of types) {\n counts[type]++;\n }\n\n const parts: string[] = [];\n if (counts.invariant > 0) parts.push(chalk.red(`${counts.invariant}I`));\n if (counts.convention > 0) parts.push(chalk.yellow(`${counts.convention}C`));\n if (counts.guideline > 0) parts.push(chalk.green(`${counts.guideline}G`));\n\n return parts.join(' ') || '-';\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 * Show decision command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createRegistry } from '../../../registry/registry.js';\nimport type { Decision, ConstraintType, Severity } from '../../../core/types/index.js';\n\ninterface ShowOptions {\n json?: boolean;\n}\n\nexport const showDecision = new Command('show')\n .description('Show details of a specific decision')\n .argument('<id>', 'Decision ID')\n .option('--json', 'Output as JSON')\n .action(async (id: string, options: ShowOptions) => {\n const registry = createRegistry();\n await registry.load();\n\n const decision = registry.get(id);\n\n if (options.json) {\n console.log(JSON.stringify(decision, null, 2));\n return;\n }\n\n printDecision(decision);\n });\n\nfunction printDecision(decision: Decision): void {\n const { metadata, decision: content, constraints } = decision;\n\n // Header\n console.log(chalk.bold.blue(`\\n${metadata.title}`));\n console.log(chalk.dim(`ID: ${metadata.id}`));\n console.log('');\n\n // Metadata\n console.log(chalk.bold('Status:'), getStatusBadge(metadata.status));\n console.log(chalk.bold('Owners:'), metadata.owners.join(', '));\n if (metadata.tags && metadata.tags.length > 0) {\n console.log(chalk.bold('Tags:'), metadata.tags.map(t => chalk.cyan(t)).join(', '));\n }\n if (metadata.createdAt) {\n console.log(chalk.bold('Created:'), metadata.createdAt);\n }\n if (metadata.supersededBy) {\n console.log(chalk.bold('Superseded by:'), chalk.yellow(metadata.supersededBy));\n }\n console.log('');\n\n // Decision content\n console.log(chalk.bold.underline('Summary'));\n console.log(content.summary);\n console.log('');\n\n console.log(chalk.bold.underline('Rationale'));\n console.log(content.rationale);\n console.log('');\n\n if (content.context) {\n console.log(chalk.bold.underline('Context'));\n console.log(content.context);\n console.log('');\n }\n\n if (content.consequences && content.consequences.length > 0) {\n console.log(chalk.bold.underline('Consequences'));\n for (const consequence of content.consequences) {\n console.log(` • ${consequence}`);\n }\n console.log('');\n }\n\n // Constraints\n console.log(chalk.bold.underline(`Constraints (${constraints.length})`));\n for (const constraint of constraints) {\n const typeIcon = getTypeIcon(constraint.type);\n const severityBadge = getSeverityBadge(constraint.severity);\n\n console.log(`\\n ${typeIcon} ${chalk.bold(constraint.id)} ${severityBadge}`);\n console.log(` ${constraint.rule}`);\n console.log(chalk.dim(` Scope: ${constraint.scope}`));\n\n if (constraint.verifier) {\n console.log(chalk.dim(` Verifier: ${constraint.verifier}`));\n }\n\n if (constraint.exceptions && constraint.exceptions.length > 0) {\n console.log(chalk.dim(` Exceptions: ${constraint.exceptions.length}`));\n }\n }\n console.log('');\n\n // Verification\n if (decision.verification?.automated && decision.verification.automated.length > 0) {\n console.log(chalk.bold.underline('Automated Verification'));\n for (const check of decision.verification.automated) {\n console.log(` • ${check.check} (${check.frequency})`);\n console.log(chalk.dim(` Target: ${check.target}`));\n }\n console.log('');\n }\n\n // Links\n if (decision.links) {\n const { related, supersedes, references } = decision.links;\n\n if (related && related.length > 0) {\n console.log(chalk.bold('Related:'), related.join(', '));\n }\n if (supersedes && supersedes.length > 0) {\n console.log(chalk.bold('Supersedes:'), supersedes.join(', '));\n }\n if (references && references.length > 0) {\n console.log(chalk.bold('References:'));\n for (const ref of references) {\n console.log(` • ${ref}`);\n }\n }\n }\n}\n\nfunction getStatusBadge(status: string): string {\n switch (status) {\n case 'active':\n return chalk.bgGreen.black(' ACTIVE ');\n case 'draft':\n return chalk.bgYellow.black(' DRAFT ');\n case 'deprecated':\n return chalk.bgGray.white(' DEPRECATED ');\n case 'superseded':\n return chalk.bgBlue.white(' SUPERSEDED ');\n default:\n return status;\n }\n}\n\nfunction getTypeIcon(type: ConstraintType): string {\n switch (type) {\n case 'invariant':\n return chalk.red('●');\n case 'convention':\n return chalk.yellow('●');\n case 'guideline':\n return chalk.green('●');\n default:\n return '○';\n }\n}\n\nfunction getSeverityBadge(severity: Severity): string {\n switch (severity) {\n case 'critical':\n return chalk.bgRed.white(' CRITICAL ');\n case 'high':\n return chalk.bgYellow.black(' HIGH ');\n case 'medium':\n return chalk.bgCyan.black(' MEDIUM ');\n case 'low':\n return chalk.bgGray.white(' LOW ');\n default:\n return severity;\n }\n}\n","/**\n * Validate decisions command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { validateDecisionFile } from '../../../registry/loader.js';\nimport { getDecisionsDir, readFilesInDir, pathExists, getSpecBridgeDir } from '../../../utils/fs.js';\nimport { NotInitializedError } from '../../../core/errors/index.js';\n\ninterface ValidateOptions {\n file?: string;\n}\n\nexport const validateDecisions = new Command('validate')\n .description('Validate decision files')\n .option('-f, --file <path>', 'Validate a specific file')\n .action(async (options: ValidateOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Validating decisions...').start();\n\n try {\n let files: string[] = [];\n\n if (options.file) {\n files = [options.file];\n } else {\n const decisionsDir = getDecisionsDir(cwd);\n const decisionFiles = await readFilesInDir(\n decisionsDir,\n (f) => f.endsWith('.decision.yaml')\n );\n files = decisionFiles.map((f) => join(decisionsDir, f));\n }\n\n if (files.length === 0) {\n spinner.info('No decision files found.');\n return;\n }\n\n let valid = 0;\n let invalid = 0;\n const errors: { file: string; errors: string[] }[] = [];\n\n for (const file of files) {\n const result = await validateDecisionFile(file);\n if (result.valid) {\n valid++;\n } else {\n invalid++;\n errors.push({ file, errors: result.errors });\n }\n }\n\n spinner.stop();\n\n // Print results\n if (invalid === 0) {\n console.log(chalk.green(`✓ All ${valid} decision file(s) are valid.`));\n } else {\n console.log(chalk.red(`✗ ${invalid} of ${files.length} decision file(s) have errors.\\n`));\n\n for (const { file, errors: fileErrors } of errors) {\n console.log(chalk.red(`File: ${file}`));\n for (const err of fileErrors) {\n console.log(chalk.dim(` - ${err}`));\n }\n console.log('');\n }\n\n process.exit(1);\n }\n } catch (error) {\n spinner.fail('Validation failed');\n throw error;\n }\n });\n","/**\n * Create decision command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { join } from 'node:path';\nimport { writeTextFile, getDecisionsDir, pathExists, getSpecBridgeDir } from '../../../utils/fs.js';\nimport { stringifyYaml } from '../../../utils/yaml.js';\nimport { NotInitializedError } from '../../../core/errors/index.js';\n\ninterface CreateOptions {\n title: string;\n summary: string;\n type?: 'invariant' | 'convention' | 'guideline';\n severity?: 'critical' | 'high' | 'medium' | 'low';\n scope?: string;\n owner?: string;\n}\n\nexport const createDecision = new Command('create')\n .description('Create a new decision file')\n .argument('<id>', 'Decision ID (e.g., auth-001)')\n .requiredOption('-t, --title <title>', 'Decision title')\n .requiredOption('-s, --summary <summary>', 'One-sentence summary')\n .option('--type <type>', 'Default constraint type (invariant, convention, guideline)', 'convention')\n .option('--severity <severity>', 'Default constraint severity (critical, high, medium, low)', 'medium')\n .option('--scope <scope>', 'Default constraint scope (glob pattern)', 'src/**/*.ts')\n .option('-o, --owner <owner>', 'Owner name', 'team')\n .action(async (id: string, options: CreateOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n // Validate ID format\n if (!/^[a-z0-9-]+$/.test(id)) {\n console.error(chalk.red('Error: Decision ID must be lowercase alphanumeric with hyphens only.'));\n process.exit(1);\n }\n\n const decisionsDir = getDecisionsDir(cwd);\n const filePath = join(decisionsDir, `${id}.decision.yaml`);\n\n // Check if file already exists\n if (await pathExists(filePath)) {\n console.error(chalk.red(`Error: Decision file already exists: ${filePath}`));\n process.exit(1);\n }\n\n // Create decision structure\n const decision = {\n kind: 'Decision',\n metadata: {\n id,\n title: options.title,\n status: 'draft',\n owners: [options.owner || 'team'],\n createdAt: new Date().toISOString(),\n tags: [],\n },\n decision: {\n summary: options.summary,\n rationale: 'TODO: Explain why this decision was made.',\n context: 'TODO: Describe the context and background.',\n consequences: [\n 'TODO: List positive consequences',\n 'TODO: List negative consequences or trade-offs',\n ],\n },\n constraints: [\n {\n id: `${id}-c1`,\n type: options.type || 'convention',\n rule: 'TODO: Describe the constraint rule',\n severity: options.severity || 'medium',\n scope: options.scope || 'src/**/*.ts',\n },\n ],\n verification: {\n automated: [],\n },\n };\n\n // Write file\n await writeTextFile(filePath, stringifyYaml(decision));\n\n console.log(chalk.green(`✓ Created decision: ${filePath}`));\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(` 1. Edit the file to add rationale, context, and consequences`);\n console.log(` 2. Define constraints with appropriate scopes`);\n console.log(` 3. Run ${chalk.bold('specbridge decision validate')} to check syntax`);\n console.log(` 4. Change status from ${chalk.yellow('draft')} to ${chalk.green('active')} when ready`);\n });\n","/**\n * Hook command - Git hook integration\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, readTextFile, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { VerificationLevel } from '../../core/types/index.js';\n\nconst HOOK_SCRIPT = `#!/bin/sh\n# SpecBridge pre-commit hook\n# Runs verification on staged files\n\necho \"Running SpecBridge verification...\"\n\n# Run specbridge hook (it will detect staged files automatically)\nnpx specbridge hook run --level commit\n\nexit $?\n`;\n\nexport function createHookCommand(): Command {\n const hookCommand = new Command('hook')\n .description('Manage Git hooks for verification');\n\n hookCommand\n .command('install')\n .description('Install Git pre-commit hook')\n .option('-f, --force', 'Overwrite existing hook')\n .option('--husky', 'Install for husky')\n .option('--lefthook', 'Install for lefthook')\n .action(async (options: { force?: boolean; husky?: boolean; lefthook?: boolean }) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Detecting hook system...').start();\n\n try {\n // Detect hook system\n let hookPath: string;\n let hookContent: string;\n\n if (options.husky) {\n // Install for husky\n hookPath = join(cwd, '.husky', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing husky pre-commit hook...';\n } else if (options.lefthook) {\n // Show lefthook config\n spinner.succeed('Lefthook detected');\n console.log('');\n console.log(chalk.cyan('Add this to your lefthook.yml:'));\n console.log('');\n console.log(chalk.dim(`pre-commit:\n commands:\n specbridge:\n glob: \"*.{ts,tsx}\"\n run: npx specbridge hook run --level commit --files {staged_files}\n`));\n return;\n } else {\n // Check for .husky directory\n if (await pathExists(join(cwd, '.husky'))) {\n hookPath = join(cwd, '.husky', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing husky pre-commit hook...';\n } else if (await pathExists(join(cwd, 'lefthook.yml'))) {\n spinner.succeed('Lefthook detected');\n console.log('');\n console.log(chalk.cyan('Add this to your lefthook.yml:'));\n console.log('');\n console.log(chalk.dim(`pre-commit:\n commands:\n specbridge:\n glob: \"*.{ts,tsx}\"\n run: npx specbridge hook run --level commit --files {staged_files}\n`));\n return;\n } else {\n // Default to .git/hooks\n hookPath = join(cwd, '.git', 'hooks', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing Git pre-commit hook...';\n }\n }\n\n // Check if hook already exists\n if (await pathExists(hookPath) && !options.force) {\n spinner.fail('Hook already exists');\n console.log(chalk.yellow(`Use --force to overwrite: ${hookPath}`));\n return;\n }\n\n // Write hook\n await writeTextFile(hookPath, hookContent);\n\n // Make executable (Unix)\n const { execSync } = await import('node:child_process');\n try {\n execSync(`chmod +x \"${hookPath}\"`, { stdio: 'ignore' });\n } catch {\n // Ignore on Windows\n }\n\n spinner.succeed('Pre-commit hook installed');\n console.log(chalk.dim(` Path: ${hookPath}`));\n console.log('');\n console.log(chalk.cyan('The hook will run on each commit and verify staged files.'));\n } catch (error) {\n spinner.fail('Failed to install hook');\n throw error;\n }\n });\n\n hookCommand\n .command('run')\n .description('Run verification (called by hook)')\n .option('-l, --level <level>', 'Verification level', 'commit')\n .option('-f, --files <files>', 'Space or comma-separated file list')\n .action(async (options: { level?: string; files?: string }) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n try {\n const config = await loadConfig(cwd);\n const level = (options.level || 'commit') as VerificationLevel;\n\n // Parse files\n let files = options.files\n ? options.files.split(/[\\s,]+/).filter(f => f.length > 0)\n : undefined;\n\n if (!files || files.length === 0) {\n // Auto-detect staged files\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileAsync = promisify(execFile);\n\n try {\n const { stdout } = await execFileAsync('git', ['diff', '--cached', '--name-only', '--diff-filter=AM'], { cwd });\n files = stdout\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((f) => /\\.(ts|tsx|js|jsx)$/.test(f));\n } catch {\n files = [];\n }\n }\n\n if (!files || files.length === 0) {\n process.exit(0);\n }\n\n // Run verification\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level,\n files,\n cwd,\n });\n\n // Output result\n if (result.violations.length === 0) {\n console.log(chalk.green('✓ SpecBridge: All checks passed'));\n process.exit(0);\n }\n\n // Print violations concisely\n console.log(chalk.red(`✗ SpecBridge: ${result.violations.length} violation(s) found`));\n console.log('');\n\n for (const v of result.violations) {\n const location = v.line ? `:${v.line}` : '';\n console.log(` ${v.file}${location}: ${v.message}`);\n console.log(chalk.dim(` [${v.severity}] ${v.decisionId}/${v.constraintId}`));\n }\n\n console.log('');\n console.log(chalk.yellow('Run `specbridge verify` for full details.'));\n\n process.exit(result.success ? 0 : 1);\n } catch (error) {\n console.error(chalk.red('SpecBridge verification failed'));\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n hookCommand\n .command('uninstall')\n .description('Remove Git pre-commit hook')\n .action(async () => {\n const cwd = process.cwd();\n const spinner = ora('Removing hook...').start();\n\n try {\n const hookPaths = [\n join(cwd, '.husky', 'pre-commit'),\n join(cwd, '.git', 'hooks', 'pre-commit'),\n ];\n\n let removed = false;\n for (const hookPath of hookPaths) {\n if (await pathExists(hookPath)) {\n const content = await readTextFile(hookPath);\n if (content.includes('SpecBridge')) {\n const { unlink } = await import('node:fs/promises');\n await unlink(hookPath);\n spinner.succeed(`Removed hook: ${hookPath}`);\n removed = true;\n }\n }\n }\n\n if (!removed) {\n spinner.info('No SpecBridge hooks found');\n }\n } catch (error) {\n spinner.fail('Failed to remove hook');\n throw error;\n }\n });\n\n return hookCommand;\n}\n\nexport const hookCommand = createHookCommand();\n","/**\n * Report command - Generate compliance reports\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { generateReport } from '../../reporting/reporter.js';\nimport { formatConsoleReport } from '../../reporting/formats/console.js';\nimport { formatMarkdownReport } from '../../reporting/formats/markdown.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, getReportsDir, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface ReportOptions {\n format?: string;\n output?: string;\n save?: boolean;\n all?: boolean;\n}\n\nexport const reportCommand = new Command('report')\n .description('Generate compliance report')\n .option('-f, --format <format>', 'Output format (console, json, markdown)', 'console')\n .option('-o, --output <file>', 'Output file path')\n .option('--save', 'Save to .specbridge/reports/')\n .option('-a, --all', 'Include all decisions (not just active)')\n .action(async (options: ReportOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Generating compliance report...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Generate report\n const report = await generateReport(config, {\n includeAll: options.all,\n cwd,\n });\n\n spinner.succeed('Report generated');\n\n // Format output\n let output: string;\n let extension: string;\n\n switch (options.format) {\n case 'json':\n output = JSON.stringify(report, null, 2);\n extension = 'json';\n break;\n case 'markdown':\n case 'md':\n output = formatMarkdownReport(report);\n extension = 'md';\n break;\n case 'console':\n default:\n output = formatConsoleReport(report);\n extension = 'txt';\n break;\n }\n\n // Output to console\n if (options.format !== 'json' || !options.output) {\n console.log(output);\n }\n\n // Save to file\n if (options.output || options.save) {\n const outputPath = options.output || join(\n getReportsDir(cwd),\n `health-${new Date().toISOString().split('T')[0]}.${extension}`\n );\n\n await writeTextFile(outputPath, output);\n console.log(chalk.green(`\\nReport saved to: ${outputPath}`));\n\n // Also save latest\n if (options.save && !options.output) {\n const latestPath = join(getReportsDir(cwd), `health-latest.${extension}`);\n await writeTextFile(latestPath, output);\n }\n }\n } catch (error) {\n spinner.fail('Failed to generate report');\n throw error;\n }\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 * Context command - Generate agent context\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { generateFormattedContext } from '../../agent/context.generator.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface ContextOptions {\n format?: string;\n output?: string;\n rationale?: boolean;\n}\n\nexport const contextCommand = new Command('context')\n .description('Generate architectural context for a file (for AI agents)')\n .argument('<file>', 'File path to generate context for')\n .option('-f, --format <format>', 'Output format (markdown, json, mcp)', 'markdown')\n .option('-o, --output <file>', 'Output file path')\n .option('--no-rationale', 'Exclude rationale/summary from output')\n .action(async (file: string, options: ContextOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Generate context\n const output = await generateFormattedContext(file, config, {\n format: options.format as 'markdown' | 'json' | 'mcp',\n includeRationale: options.rationale !== false,\n cwd,\n });\n\n // Output\n if (options.output) {\n await writeTextFile(options.output, output);\n console.log(chalk.green(`Context saved to: ${options.output}`));\n } else {\n console.log(output);\n }\n } catch (error) {\n console.error(chalk.red('Failed to generate context'));\n throw error;\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 * LSP command - Start SpecBridge language server\n */\nimport { Command } from 'commander';\nimport { startLspServer } from '../../lsp/index.js';\n\nexport const lspCommand = new Command('lsp')\n .description('Start SpecBridge language server (stdio)')\n .option('--verbose', 'Enable verbose server logging', false)\n .action(async (options: { verbose?: boolean }) => {\n await startLspServer({ cwd: process.cwd(), verbose: Boolean(options.verbose) });\n });\n\n","/**\n * SpecBridge Language Server (LSP)\n */\nimport { createConnection, ProposedFeatures, TextDocuments, TextDocumentSyncKind, DiagnosticSeverity, CodeActionKind } from 'vscode-languageserver/node.js';\nimport { TextDocument } from 'vscode-languageserver-textdocument';\nimport { fileURLToPath } from 'node:url';\nimport path from 'node:path';\nimport { Project } from 'ts-morph';\nimport chalk from 'chalk';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { getSpecBridgeDir, pathExists } from '../utils/fs.js';\nimport { selectVerifierForConstraint, type VerificationContext } from '../verification/verifiers/index.js';\nimport { shouldApplyConstraintToFile } from '../verification/applicability.js';\nimport type { Decision, Violation, Severity } from '../core/types/index.js';\nimport { NotInitializedError } from '../core/errors/index.js';\n\nexport interface LspServerOptions {\n cwd: string;\n verbose?: boolean;\n}\n\nfunction severityToDiagnostic(severity: Severity): DiagnosticSeverity {\n switch (severity) {\n case 'critical':\n return DiagnosticSeverity.Error;\n case 'high':\n return DiagnosticSeverity.Warning;\n case 'medium':\n return DiagnosticSeverity.Information;\n case 'low':\n return DiagnosticSeverity.Hint;\n default:\n return DiagnosticSeverity.Information;\n }\n}\n\nfunction uriToFilePath(uri: string): string {\n if (uri.startsWith('file://')) return fileURLToPath(uri);\n // Fallback: treat as plain path\n return uri;\n}\n\nfunction violationToRange(doc: TextDocument, v: Violation) {\n // Prefer autofix ranges when available, otherwise line/column best-effort.\n const edit = v.autofix?.edits?.[0];\n if (edit) {\n return {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n };\n }\n\n const line = Math.max(0, (v.line ?? 1) - 1);\n const char = Math.max(0, (v.column ?? 1) - 1);\n return {\n start: { line, character: char },\n end: { line, character: char + 1 },\n };\n}\n\nexport class SpecBridgeLspServer {\n private connection = createConnection(ProposedFeatures.all);\n private documents = new TextDocuments(TextDocument);\n\n private options: LspServerOptions;\n private registry: Registry | null = null;\n private decisions: Decision[] = [];\n private cwd: string;\n private project: Project;\n private cache = new Map<string, Violation[]>();\n private initError: string | null = null;\n\n constructor(options: LspServerOptions) {\n this.options = options;\n this.cwd = options.cwd;\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n async initialize(): Promise<void> {\n this.connection.onInitialize(async () => {\n await this.initializeWorkspace();\n\n return {\n capabilities: {\n textDocumentSync: TextDocumentSyncKind.Incremental,\n codeActionProvider: true,\n },\n };\n });\n\n this.documents.onDidOpen((e) => {\n void this.validateDocument(e.document);\n });\n\n this.documents.onDidChangeContent((change) => {\n void this.validateDocument(change.document);\n });\n\n this.documents.onDidClose((e) => {\n this.cache.delete(e.document.uri);\n this.connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });\n });\n\n this.connection.onCodeAction((params) => {\n const violations = this.cache.get(params.textDocument.uri) || [];\n const doc = this.documents.get(params.textDocument.uri);\n if (!doc) return [];\n\n return violations\n .filter((v) => v.autofix && v.autofix.edits.length > 0)\n .map((v) => {\n const edits = v.autofix!.edits.map((edit) => ({\n range: {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n },\n newText: edit.text,\n }));\n\n return {\n title: v.autofix!.description,\n kind: CodeActionKind.QuickFix,\n edit: {\n changes: {\n [params.textDocument.uri]: edits,\n },\n },\n };\n });\n });\n\n this.documents.listen(this.connection);\n this.connection.listen();\n }\n\n private async initializeWorkspace(): Promise<void> {\n // Ensure initialized (but keep server alive if not).\n if (!await pathExists(getSpecBridgeDir(this.cwd))) {\n const err = new NotInitializedError();\n this.initError = err.message;\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n return;\n }\n\n try {\n const config = await loadConfig(this.cwd);\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n this.decisions = this.registry.getActive();\n\n // Prime project with source roots (best-effort). This enables verifiers that depend on import graph.\n for (const root of config.project.sourceRoots) {\n // ts-morph doesn't support globs directly; add root folders when possible.\n const rootPath = path.isAbsolute(root) ? root : path.join(this.cwd, root);\n // If root is a glob, fall back to adding the directory portion.\n const dir = rootPath.includes('*') ? rootPath.split('*')[0] : rootPath;\n if (dir && await pathExists(dir)) {\n this.project.addSourceFilesAtPaths(path.join(dir, '**/*.{ts,tsx,js,jsx}'));\n }\n }\n\n if (this.options.verbose) {\n this.connection.console.log(chalk.dim(`Loaded ${this.decisions.length} active decision(s)`));\n }\n } catch (error) {\n this.initError = error instanceof Error ? error.message : String(error);\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n }\n }\n\n private async verifyTextDocument(doc: TextDocument): Promise<Violation[]> {\n if (this.initError) {\n throw new Error(this.initError);\n }\n if (!this.registry) return [];\n\n const filePath = uriToFilePath(doc.uri);\n const sourceFile = this.project.createSourceFile(filePath, doc.getText(), { overwrite: true });\n\n const violations: Violation[] = [];\n\n for (const decision of this.decisions) {\n for (const constraint of decision.constraints) {\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd: this.cwd })) continue;\n\n const verifier = selectVerifierForConstraint(constraint.rule, constraint.verifier);\n if (!verifier) continue;\n\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n };\n\n try {\n const constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n } catch {\n // Ignore verifier errors (LSP should stay responsive)\n }\n }\n }\n\n return violations;\n }\n\n private async validateDocument(doc: TextDocument): Promise<void> {\n try {\n const violations = await this.verifyTextDocument(doc);\n this.cache.set(doc.uri, violations);\n\n const diagnostics = violations.map((v) => ({\n range: violationToRange(doc, v),\n severity: severityToDiagnostic(v.severity),\n message: v.message,\n source: 'specbridge',\n }));\n\n this.connection.sendDiagnostics({ uri: doc.uri, diagnostics });\n } catch (error) {\n // If workspace isn't initialized, surface a single diagnostic.\n const msg = error instanceof Error ? error.message : String(error);\n this.connection.sendDiagnostics({\n uri: doc.uri,\n diagnostics: [\n {\n range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },\n severity: DiagnosticSeverity.Error,\n message: msg,\n source: 'specbridge',\n },\n ],\n });\n }\n }\n}\n","import { SpecBridgeLspServer, type LspServerOptions } from './server.js';\n\nexport async function startLspServer(options: LspServerOptions): Promise<void> {\n const server = new SpecBridgeLspServer(options);\n await server.initialize();\n}\n\n","/**\n * Watch command - Verify changed files continuously\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport chokidar from 'chokidar';\nimport path from 'node:path';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { getSpecBridgeDir, pathExists } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { VerificationLevel } from '../../core/types/index.js';\n\nexport const watchCommand = new Command('watch')\n .description('Watch for changes and verify files continuously')\n .option('-l, --level <level>', 'Verification level (commit, pr, full)', 'full')\n .option('--debounce <ms>', 'Debounce verify on rapid changes', '150')\n .action(async (options: { level?: string; debounce?: string }) => {\n const cwd = process.cwd();\n\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const config = await loadConfig(cwd);\n const engine = createVerificationEngine();\n const level = (options.level || 'full') as VerificationLevel;\n const debounceMs = Number.parseInt(options.debounce || '150', 10);\n\n let timer: NodeJS.Timeout | null = null;\n let pendingPath: string | null = null;\n\n const run = async (changedPath: string) => {\n const absolutePath = path.isAbsolute(changedPath) ? changedPath : path.join(cwd, changedPath);\n const result = await engine.verify(config, {\n level,\n files: [absolutePath],\n cwd,\n });\n\n const prefix = result.success ? chalk.green('✓') : chalk.red('✗');\n const summary = `${prefix} ${path.relative(cwd, absolutePath)}: ${result.violations.length} violation(s)`;\n console.log(summary);\n\n for (const v of result.violations.slice(0, 20)) {\n const loc = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n console.log(chalk.dim(` - ${v.file}${loc}: ${v.message} [${v.severity}]`));\n }\n if (result.violations.length > 20) {\n console.log(chalk.dim(` … ${result.violations.length - 20} more`));\n }\n };\n\n const watcher = chokidar.watch(config.project.sourceRoots, {\n cwd,\n ignored: config.project.exclude,\n ignoreInitial: true,\n persistent: true,\n });\n\n console.log(chalk.blue('Watching for changes...'));\n\n watcher.on('change', (changedPath) => {\n pendingPath = changedPath;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n if (!pendingPath) return;\n void run(pendingPath);\n pendingPath = null;\n }, debounceMs);\n });\n });\n\n","/**\n * MCP Server command - Start SpecBridge MCP server\n */\nimport { Command } from 'commander';\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { SpecBridgeMcpServer } from '../../mcp/server.js';\n\nfunction getCliVersion(): string {\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n // In production (bundled): import.meta.url points to dist/cli.js, so ../package.json is correct.\n const packageJsonPath = join(__dirname, '../package.json');\n const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n return String(pkg.version || '0.0.0');\n } catch {\n return '0.0.0';\n }\n}\n\nexport const mcpServerCommand = new Command('mcp-server')\n .description('Start SpecBridge MCP server (stdio)')\n .action(async () => {\n const server = new SpecBridgeMcpServer({\n cwd: process.cwd(),\n version: getCliVersion(),\n });\n\n await server.initialize();\n // MCP servers should write logs to stderr; keep stdout for protocol.\n console.error('SpecBridge MCP server starting (stdio)...');\n await server.startStdio();\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","/**\n * Prompt command - Generate AI agent prompt templates\n */\nimport { Command } from 'commander';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { generateContext } from '../../agent/context.generator.js';\nimport { templates } from '../../agent/templates.js';\n\nexport const promptCommand = new Command('prompt')\n .description('Generate AI agent prompt templates')\n .argument('<template>', 'Template name (code-review|refactoring|migration)')\n .argument('<file>', 'File path (used to select applicable decisions)')\n .option('--decision <id>', 'Decision id (required for migration)')\n .action(async (templateName: string, file: string, options: { decision?: string }) => {\n const cwd = process.cwd();\n\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const tpl = templates[templateName];\n if (!tpl) {\n throw new Error(`Unknown template: ${templateName}`);\n }\n\n if (templateName === 'migration' && !options.decision) {\n throw new Error('Missing --decision <id> for migration template');\n }\n\n const config = await loadConfig(cwd);\n const context = await generateContext(file, config, { cwd, includeRationale: true });\n const prompt = tpl.generate(context, { decisionId: options.decision });\n console.log(prompt);\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"],"mappings":";;;AAIA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,aAAW;AAClB,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,QAAAC,cAAY;;;ACDvB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MACA,SACA,YAChB;AACA,UAAM,OAAO;AAJG;AACA;AACA;AAGhB,SAAK,OAAO;AACZ,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAChD;AACF;AAKO,IAAM,cAAN,cAA0B,gBAAgB;AAAA,EAC/C,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,gBAAgB,OAAO;AACtC,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,0BAAN,cAAsC,gBAAgB;AAAA,EAC3D,YACE,SACgB,YACA,kBAChB;AACA,UAAM,SAAS,6BAA6B,EAAE,YAAY,iBAAiB,CAAC;AAH5D;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,wBAAN,cAAoC,gBAAgB;AAAA,EACzD,YAAY,YAAoB;AAC9B,UAAM,uBAAuB,UAAU,IAAI,sBAAsB,EAAE,WAAW,CAAC;AAC/E,SAAK,OAAO;AAAA,EACd;AACF;AAmCO,IAAM,kBAAN,cAA8B,gBAAgB;AAAA,EACnD,YAAY,SAAiCC,OAAc;AACzD,UAAM,SAAS,qBAAqB,EAAE,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hC,QAAQ,aAAa,CAAC,QAAQ;AAC5B,MAAI,IAAI,SAAS,oBAAoB,IAAI,SAAS,2BAA2B;AAC3E,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,MAAI,IAAI,SAAS,qBAAqB;AACpC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,UAAQ,MAAMC,QAAM,IAAI,YAAY,GAAG,CAAC,CAAC;AACzC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAGD,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAiB;AACvD,UAAQ,MAAMA,QAAM,IAAI,YAAY,KAAK,CAAC,CAAC;AAC3C,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Command","chalk","readFileSync","fileURLToPath","dirname","join","path","join","path","path","join","Command","chalk","ora","join","path","dirname","dirname","Node","path","Node","Command","ora","join","chalk","Command","chalk","ora","Project","join","z","SeveritySchema","VerificationConfigSchema","path","join","Node","Node","path","relative","path","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","stat","Project","resolve","readFile","writeFile","stdout","Command","ora","chalk","Command","Command","chalk","Command","chalk","Command","chalk","Command","chalk","getTypeIcon","Command","chalk","ora","join","Command","ora","join","chalk","Command","chalk","join","Command","chalk","join","Command","Command","chalk","ora","join","hookCommand","Command","ora","join","chalk","execFile","promisify","execFileAsync","stdout","Command","chalk","ora","join","chalk","table","getStatusColor","truncate","Command","ora","join","chalk","Command","chalk","Command","chalk","Command","path","Project","chalk","Project","chalk","path","Command","Command","chalk","path","Command","path","chalk","Command","fileURLToPath","dirname","join","z","z","__dirname","dirname","fileURLToPath","packageJsonPath","join","Command","Command","Command","dirname","fileURLToPath","join","readFileSync","Command","chalk"]}
1
+ {"version":3,"sources":["../src/cli/index.ts","../src/core/errors/index.ts","../src/cli/commands/init.ts","../src/utils/fs.ts","../src/utils/yaml.ts","../src/core/schemas/config.schema.ts","../src/cli/commands/infer.ts","../src/inference/scanner.ts","../src/utils/glob.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/config/loader.ts","../src/cli/commands/verify.ts","../src/verification/engine.ts","../src/registry/loader.ts","../src/core/schemas/decision.schema.ts","../src/registry/registry.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/autofix/engine.ts","../src/verification/incremental.ts","../src/cli/commands/decision/index.ts","../src/cli/commands/decision/list.ts","../src/cli/commands/decision/show.ts","../src/cli/commands/decision/validate.ts","../src/cli/commands/decision/create.ts","../src/cli/commands/hook.ts","../src/cli/commands/report.ts","../src/reporting/reporter.ts","../src/reporting/formats/console.ts","../src/reporting/formats/markdown.ts","../src/reporting/storage.ts","../src/reporting/drift.ts","../src/cli/commands/context.ts","../src/agent/context.generator.ts","../src/cli/commands/lsp.ts","../src/lsp/server.ts","../src/lsp/index.ts","../src/cli/commands/watch.ts","../src/cli/commands/mcp-server.ts","../src/mcp/server.ts","../src/cli/commands/prompt.ts","../src/agent/templates.ts","../src/cli/commands/analytics.ts","../src/analytics/engine.ts","../src/cli/commands/dashboard.ts","../src/dashboard/server.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * SpecBridge CLI Entry Point\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { formatError } from '../core/errors/index.js';\n\n// Import commands\nimport { initCommand } from './commands/init.js';\nimport { inferCommand } from './commands/infer.js';\nimport { verifyCommand } from './commands/verify.js';\nimport { decisionCommand } from './commands/decision/index.js';\nimport { hookCommand } from './commands/hook.js';\nimport { reportCommand } from './commands/report.js';\nimport { contextCommand } from './commands/context.js';\nimport { lspCommand } from './commands/lsp.js';\nimport { watchCommand } from './commands/watch.js';\nimport { mcpServerCommand } from './commands/mcp-server.js';\nimport { promptCommand } from './commands/prompt.js';\nimport { analyticsCommand } from './commands/analytics.js';\nimport { dashboardCommand } from './commands/dashboard.js';\n\n// Read version from package.json\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n// In development: src/cli/index.ts -> ../../package.json\n// In production: dist/cli.js -> ../package.json\nconst packageJsonPath = join(__dirname, '../package.json');\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n\nconst program = new Command();\n\nprogram\n .name('specbridge')\n .description('Architecture Decision Runtime - Transform architectural decisions into executable, verifiable constraints')\n .version(packageJson.version);\n\n// Register commands\nprogram.addCommand(initCommand);\nprogram.addCommand(inferCommand);\nprogram.addCommand(verifyCommand);\nprogram.addCommand(decisionCommand);\nprogram.addCommand(hookCommand);\nprogram.addCommand(reportCommand);\nprogram.addCommand(contextCommand);\nprogram.addCommand(lspCommand);\nprogram.addCommand(watchCommand);\nprogram.addCommand(mcpServerCommand);\nprogram.addCommand(promptCommand);\nprogram.addCommand(analyticsCommand);\nprogram.addCommand(dashboardCommand);\n\n// Global error handler\nprogram.exitOverride((err) => {\n if (err.code === 'commander.help' || err.code === 'commander.helpDisplayed') {\n process.exit(0);\n }\n if (err.code === 'commander.version') {\n process.exit(0);\n }\n console.error(chalk.red(formatError(err)));\n process.exit(1);\n});\n\n// Parse and execute\nprogram.parseAsync(process.argv).catch((error: Error) => {\n console.error(chalk.red(formatError(error)));\n process.exit(1);\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 * Init command - Initialize SpecBridge in a project\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport {\n pathExists,\n ensureDir,\n writeTextFile,\n getSpecBridgeDir,\n getDecisionsDir,\n getVerifiersDir,\n getInferredDir,\n getReportsDir,\n getConfigPath,\n} from '../../utils/fs.js';\nimport { stringifyYaml } from '../../utils/yaml.js';\nimport { defaultConfig } from '../../core/schemas/config.schema.js';\nimport { AlreadyInitializedError } from '../../core/errors/index.js';\n\ninterface InitOptions {\n force?: boolean;\n name?: string;\n}\n\nexport const initCommand = new Command('init')\n .description('Initialize SpecBridge in the current project')\n .option('-f, --force', 'Overwrite existing configuration')\n .option('-n, --name <name>', 'Project name')\n .action(async (options: InitOptions) => {\n const cwd = process.cwd();\n const specbridgeDir = getSpecBridgeDir(cwd);\n\n // Check if already initialized\n if (!options.force && await pathExists(specbridgeDir)) {\n throw new AlreadyInitializedError(specbridgeDir);\n }\n\n const spinner = ora('Initializing SpecBridge...').start();\n\n try {\n // Create directory structure\n await ensureDir(specbridgeDir);\n await ensureDir(getDecisionsDir(cwd));\n await ensureDir(getVerifiersDir(cwd));\n await ensureDir(getInferredDir(cwd));\n await ensureDir(getReportsDir(cwd));\n\n // Determine project name\n const projectName = options.name || getProjectNameFromPath(cwd);\n\n // Create config file\n const config = {\n ...defaultConfig,\n project: {\n ...defaultConfig.project,\n name: projectName,\n },\n };\n\n const configContent = stringifyYaml(config);\n await writeTextFile(getConfigPath(cwd), configContent);\n\n // Create example decision\n const exampleDecision = createExampleDecision(projectName);\n await writeTextFile(\n join(getDecisionsDir(cwd), 'example.decision.yaml'),\n stringifyYaml(exampleDecision)\n );\n\n // Create .gitkeep files\n await writeTextFile(join(getVerifiersDir(cwd), '.gitkeep'), '');\n await writeTextFile(join(getInferredDir(cwd), '.gitkeep'), '');\n await writeTextFile(join(getReportsDir(cwd), '.gitkeep'), '');\n\n spinner.succeed('SpecBridge initialized successfully!');\n\n console.log('');\n console.log(chalk.green('Created:'));\n console.log(` ${chalk.dim('.specbridge/')}`);\n console.log(` ${chalk.dim('├──')} config.yaml`);\n console.log(` ${chalk.dim('├──')} decisions/`);\n console.log(` ${chalk.dim('│ └──')} example.decision.yaml`);\n console.log(` ${chalk.dim('├──')} verifiers/`);\n console.log(` ${chalk.dim('├──')} inferred/`);\n console.log(` ${chalk.dim('└──')} reports/`);\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(` 1. Edit ${chalk.bold('.specbridge/config.yaml')} to configure source paths`);\n console.log(` 2. Run ${chalk.bold('specbridge infer')} to detect patterns in your codebase`);\n console.log(` 3. Create decisions in ${chalk.bold('.specbridge/decisions/')}`);\n console.log(` 4. Run ${chalk.bold('specbridge verify')} to check compliance`);\n } catch (error) {\n spinner.fail('Failed to initialize SpecBridge');\n throw error;\n }\n });\n\n/**\n * Extract project name from directory path\n */\nfunction getProjectNameFromPath(dirPath: string): string {\n const parts = dirPath.split(/[/\\\\]/);\n return parts[parts.length - 1] || 'my-project';\n}\n\n/**\n * Create an example decision for new projects\n */\nfunction createExampleDecision(projectName: string) {\n return {\n kind: 'Decision',\n metadata: {\n id: 'example-001',\n title: 'Example Decision - Error Handling Convention',\n status: 'draft',\n owners: ['team'],\n tags: ['example', 'error-handling'],\n },\n decision: {\n summary: 'All errors should be handled using a consistent error class hierarchy.',\n rationale: `Consistent error handling improves debugging and makes the codebase more maintainable.\nThis is an example decision to demonstrate SpecBridge functionality.`,\n context: `This decision was auto-generated when initializing SpecBridge for ${projectName}.\nReplace or delete this file and create your own architectural decisions.`,\n },\n constraints: [\n {\n id: 'custom-errors',\n type: 'convention',\n rule: 'Custom error classes should extend a base AppError class',\n severity: 'medium',\n scope: 'src/**/*.ts',\n },\n {\n id: 'error-logging',\n type: 'guideline',\n rule: 'Errors should be logged with appropriate context before being thrown or handled',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n ],\n };\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 * 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 * Infer command - Detect patterns in the codebase\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { createInferenceEngine, getAnalyzerIds } from '../../inference/index.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { writeTextFile, getInferredDir, pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { Pattern } from '../../core/types/index.js';\n\ninterface InferOptions {\n output?: string;\n minConfidence?: string;\n analyzers?: string;\n json?: boolean;\n save?: boolean;\n}\n\nexport const inferCommand = new Command('infer')\n .description('Analyze codebase and detect patterns')\n .option('-o, --output <file>', 'Output file path')\n .option('-c, --min-confidence <number>', 'Minimum confidence threshold (0-100)', '50')\n .option('-a, --analyzers <list>', 'Comma-separated list of analyzers to run')\n .option('--json', 'Output as JSON')\n .option('--save', 'Save results to .specbridge/inferred/')\n .action(async (options: InferOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Loading configuration...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Parse options\n const minConfidence = parseInt(options.minConfidence || '50', 10);\n const analyzerList = options.analyzers\n ? options.analyzers.split(',').map(a => a.trim())\n : config.inference?.analyzers || getAnalyzerIds();\n\n spinner.text = `Scanning codebase (analyzers: ${analyzerList.join(', ')})...`;\n\n // Run inference\n const engine = createInferenceEngine();\n const result = await engine.infer({\n analyzers: analyzerList,\n minConfidence,\n sourceRoots: config.project.sourceRoots,\n exclude: config.project.exclude,\n cwd,\n });\n\n spinner.succeed(`Scanned ${result.filesScanned} files in ${result.duration}ms`);\n\n // Save results first (even if empty) if requested\n if (options.save || options.output) {\n const outputPath = options.output || join(getInferredDir(cwd), 'patterns.json');\n await writeTextFile(outputPath, JSON.stringify(result, null, 2));\n console.log(chalk.green(`\\nResults saved to: ${outputPath}`));\n }\n\n if (result.patterns.length === 0) {\n console.log(chalk.yellow('\\nNo patterns detected above confidence threshold.'));\n console.log(chalk.dim(`Try lowering --min-confidence (current: ${minConfidence})`));\n return;\n }\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n printPatterns(result.patterns);\n }\n\n // Show next steps\n if (!options.json) {\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(' Review detected patterns and create decisions for important ones.');\n console.log(` Use ${chalk.bold('specbridge decision create <id>')} to create a new decision.`);\n }\n } catch (error) {\n spinner.fail('Inference failed');\n throw error;\n }\n });\n\nfunction printPatterns(patterns: Pattern[]): void {\n console.log(chalk.bold(`\\nDetected ${patterns.length} pattern(s):\\n`));\n\n for (const pattern of patterns) {\n const confidenceColor = pattern.confidence >= 80\n ? chalk.green\n : pattern.confidence >= 60\n ? chalk.yellow\n : chalk.dim;\n\n console.log(chalk.bold(`${pattern.name}`));\n console.log(chalk.dim(` ID: ${pattern.id}`));\n console.log(` ${pattern.description}`);\n console.log(` Confidence: ${confidenceColor(`${pattern.confidence}%`)} (${pattern.occurrences} occurrences)`);\n console.log(chalk.dim(` Analyzer: ${pattern.analyzer}`));\n\n if (pattern.examples.length > 0) {\n console.log(chalk.dim(' Examples:'));\n for (const example of pattern.examples.slice(0, 2)) {\n console.log(chalk.dim(` - ${example.file}:${example.line}`));\n console.log(chalk.dim(` ${example.snippet}`));\n }\n }\n\n if (pattern.suggestedConstraint) {\n const typeColor =\n pattern.suggestedConstraint.type === 'invariant' ? chalk.red :\n pattern.suggestedConstraint.type === 'convention' ? chalk.yellow :\n chalk.green;\n\n console.log(chalk.cyan(' Suggested constraint:'));\n console.log(` Type: ${typeColor(pattern.suggestedConstraint.type || 'convention')}`);\n console.log(` Rule: ${pattern.suggestedConstraint.rule}`);\n }\n\n console.log('');\n }\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 * 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 * 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 * 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 * Verify command - Check code compliance\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { AutofixEngine, type AutofixResult } from '../../verification/autofix/engine.js';\nimport { getChangedFiles } from '../../verification/incremental.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { Violation, VerificationLevel, Severity } from '../../core/types/index.js';\n\ninterface VerifyOptions {\n level?: string;\n files?: string;\n decisions?: string;\n severity?: string;\n json?: boolean;\n fix?: boolean;\n dryRun?: boolean;\n interactive?: boolean;\n incremental?: boolean;\n}\n\nexport const verifyCommand = new Command('verify')\n .description('Verify code compliance against decisions')\n .option('-l, --level <level>', 'Verification level (commit, pr, full)', 'full')\n .option('-f, --files <patterns>', 'Comma-separated file patterns to check')\n .option('-d, --decisions <ids>', 'Comma-separated decision IDs to check')\n .option('-s, --severity <levels>', 'Comma-separated severity levels (critical, high, medium, low)')\n .option('--json', 'Output as JSON')\n .option('--incremental', 'Only verify changed files (git diff --name-only --diff-filter=AM HEAD)')\n .option('--fix', 'Apply auto-fixes for supported violations')\n .option('--dry-run', 'Show what would be fixed without applying (requires --fix)')\n .option('--interactive', 'Confirm each fix interactively (requires --fix)')\n .action(async (options: VerifyOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Loading configuration...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Parse options\n const level = (options.level || 'full') as VerificationLevel;\n let files = options.files?.split(',').map(f => f.trim());\n const decisions = options.decisions?.split(',').map(d => d.trim());\n const severity = options.severity?.split(',').map(s => s.trim() as Severity);\n\n if (options.incremental) {\n const changed = await getChangedFiles(cwd);\n files = changed.length > 0 ? changed : [];\n }\n\n spinner.text = `Running ${level}-level verification...`;\n\n // Run verification\n const engine = createVerificationEngine();\n let result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n\n // Apply auto-fixes (optional)\n let fixResult: AutofixResult | undefined;\n if (options.fix && result.violations.length > 0) {\n const fixableCount = result.violations.filter(v => v.autofix).length;\n\n if (fixableCount === 0) {\n spinner.stop();\n if (!options.json) {\n console.log(chalk.yellow('No auto-fixable violations found'));\n }\n } else {\n spinner.text = `Applying ${fixableCount} auto-fix(es)...`;\n const fixer = new AutofixEngine();\n fixResult = await fixer.applyFixes(result.violations, {\n dryRun: options.dryRun,\n interactive: options.interactive,\n });\n\n if (!options.dryRun && fixResult.applied.length > 0) {\n result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n }\n }\n }\n\n spinner.stop();\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify({ ...result, autofix: fixResult }, null, 2));\n } else {\n printResult(result, level);\n\n if (options.fix && fixResult) {\n console.log(chalk.green(`✓ Applied ${fixResult.applied.length} fix(es)`));\n if (fixResult.skipped > 0) {\n console.log(chalk.yellow(`⊘ Skipped ${fixResult.skipped} fix(es)`));\n }\n console.log('');\n }\n }\n\n // Exit with error code if verification failed\n if (!result.success) {\n process.exit(1);\n }\n } catch (error) {\n spinner.fail('Verification failed');\n throw error;\n }\n });\n\nfunction printResult(\n result: { success: boolean; violations: Violation[]; checked: number; passed: number; failed: number; skipped: number; duration: number },\n level: VerificationLevel\n): void {\n console.log('');\n\n if (result.violations.length === 0) {\n console.log(chalk.green('✓ All checks passed!'));\n console.log(chalk.dim(` ${result.checked} files checked in ${result.duration}ms`));\n return;\n }\n\n // Group violations by file\n const byFile = new Map<string, Violation[]>();\n for (const violation of result.violations) {\n const existing = byFile.get(violation.file) || [];\n existing.push(violation);\n byFile.set(violation.file, existing);\n }\n\n // Print violations by file\n for (const [file, violations] of byFile) {\n console.log(chalk.underline(file));\n\n for (const v of violations) {\n const typeIcon = getTypeIcon(v.type);\n const severityColor = getSeverityColor(v.severity);\n const location = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n\n console.log(\n ` ${typeIcon} ${severityColor(`[${v.severity}]`)} ${v.message}`\n );\n console.log(chalk.dim(` ${v.decisionId}/${v.constraintId}${location}`));\n\n if (v.suggestion) {\n console.log(chalk.cyan(` Suggestion: ${v.suggestion}`));\n }\n }\n\n console.log('');\n }\n\n // Summary\n const criticalCount = result.violations.filter(v => v.severity === 'critical').length;\n const highCount = result.violations.filter(v => v.severity === 'high').length;\n const mediumCount = result.violations.filter(v => v.severity === 'medium').length;\n const lowCount = result.violations.filter(v => v.severity === 'low').length;\n\n console.log(chalk.bold('Summary:'));\n console.log(` Files: ${result.checked} checked, ${result.passed} passed, ${result.failed} failed`);\n\n const violationParts: string[] = [];\n if (criticalCount > 0) violationParts.push(chalk.red(`${criticalCount} critical`));\n if (highCount > 0) violationParts.push(chalk.yellow(`${highCount} high`));\n if (mediumCount > 0) violationParts.push(chalk.cyan(`${mediumCount} medium`));\n if (lowCount > 0) violationParts.push(chalk.dim(`${lowCount} low`));\n\n console.log(` Violations: ${violationParts.join(', ')}`);\n console.log(` Duration: ${result.duration}ms`);\n\n if (!result.success) {\n console.log('');\n const blockingTypes = level === 'commit'\n ? 'invariant or critical'\n : level === 'pr'\n ? 'invariant, critical, or high'\n : 'invariant';\n console.log(chalk.red(`✗ Verification failed. ${blockingTypes} violations must be resolved.`));\n }\n}\n\nfunction getTypeIcon(type: string): string {\n switch (type) {\n case 'invariant':\n return chalk.red('●');\n case 'convention':\n return chalk.yellow('●');\n case 'guideline':\n return chalk.green('●');\n default:\n return '○';\n }\n}\n\nfunction getSeverityColor(severity: Severity): (text: string) => string {\n switch (severity) {\n case 'critical':\n return chalk.red;\n case 'high':\n return chalk.yellow;\n case 'medium':\n return chalk.cyan;\n case 'low':\n return chalk.dim;\n default:\n return chalk.white;\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 * 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 * 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 * 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 * 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 * 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 * 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 * Decision command group\n */\nimport { Command } from 'commander';\nimport { listDecisions } from './list.js';\nimport { showDecision } from './show.js';\nimport { validateDecisions } from './validate.js';\nimport { createDecision } from './create.js';\n\nexport const decisionCommand = new Command('decision')\n .description('Manage architectural decisions')\n .addCommand(listDecisions)\n .addCommand(showDecision)\n .addCommand(validateDecisions)\n .addCommand(createDecision);\n","/**\n * List decisions command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { table } from 'table';\nimport { createRegistry } from '../../../registry/registry.js';\nimport type { DecisionStatus, ConstraintType } from '../../../core/types/index.js';\n\ninterface ListOptions {\n status?: string;\n tag?: string;\n json?: boolean;\n}\n\nexport const listDecisions = new Command('list')\n .description('List all architectural decisions')\n .option('-s, --status <status>', 'Filter by status (draft, active, deprecated, superseded)')\n .option('-t, --tag <tag>', 'Filter by tag')\n .option('--json', 'Output as JSON')\n .action(async (options: ListOptions) => {\n const registry = createRegistry();\n const result = await registry.load();\n\n // Show loading errors as warnings\n if (result.errors.length > 0) {\n console.warn(chalk.yellow('\\nWarnings:'));\n for (const err of result.errors) {\n console.warn(chalk.yellow(` - ${err.filePath}: ${err.error}`));\n }\n console.log('');\n }\n\n // Apply filters\n const filter: { status?: DecisionStatus[]; tags?: string[] } = {};\n if (options.status) {\n filter.status = [options.status as DecisionStatus];\n }\n if (options.tag) {\n filter.tags = [options.tag];\n }\n\n const decisions = registry.getAll(filter);\n\n if (decisions.length === 0) {\n console.log(chalk.yellow('No decisions found.'));\n return;\n }\n\n if (options.json) {\n console.log(JSON.stringify(decisions, null, 2));\n return;\n }\n\n // Create table\n const data: string[][] = [\n [\n chalk.bold('ID'),\n chalk.bold('Title'),\n chalk.bold('Status'),\n chalk.bold('Constraints'),\n chalk.bold('Tags'),\n ],\n ];\n\n for (const decision of decisions) {\n const statusColor = getStatusColor(decision.metadata.status);\n const constraintTypes = getConstraintTypeSummary(decision.constraints.map(c => c.type));\n\n data.push([\n decision.metadata.id,\n truncate(decision.metadata.title, 40),\n statusColor(decision.metadata.status),\n constraintTypes,\n (decision.metadata.tags || []).join(', ') || '-',\n ]);\n }\n\n console.log(table(data, {\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 console.log(chalk.dim(`Total: ${decisions.length} decision(s)`));\n });\n\nfunction getStatusColor(status: DecisionStatus): (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 getConstraintTypeSummary(types: ConstraintType[]): string {\n const counts = {\n invariant: 0,\n convention: 0,\n guideline: 0,\n };\n\n for (const type of types) {\n counts[type]++;\n }\n\n const parts: string[] = [];\n if (counts.invariant > 0) parts.push(chalk.red(`${counts.invariant}I`));\n if (counts.convention > 0) parts.push(chalk.yellow(`${counts.convention}C`));\n if (counts.guideline > 0) parts.push(chalk.green(`${counts.guideline}G`));\n\n return parts.join(' ') || '-';\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 * Show decision command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createRegistry } from '../../../registry/registry.js';\nimport type { Decision, ConstraintType, Severity } from '../../../core/types/index.js';\n\ninterface ShowOptions {\n json?: boolean;\n}\n\nexport const showDecision = new Command('show')\n .description('Show details of a specific decision')\n .argument('<id>', 'Decision ID')\n .option('--json', 'Output as JSON')\n .action(async (id: string, options: ShowOptions) => {\n const registry = createRegistry();\n await registry.load();\n\n const decision = registry.get(id);\n\n if (options.json) {\n console.log(JSON.stringify(decision, null, 2));\n return;\n }\n\n printDecision(decision);\n });\n\nfunction printDecision(decision: Decision): void {\n const { metadata, decision: content, constraints } = decision;\n\n // Header\n console.log(chalk.bold.blue(`\\n${metadata.title}`));\n console.log(chalk.dim(`ID: ${metadata.id}`));\n console.log('');\n\n // Metadata\n console.log(chalk.bold('Status:'), getStatusBadge(metadata.status));\n console.log(chalk.bold('Owners:'), metadata.owners.join(', '));\n if (metadata.tags && metadata.tags.length > 0) {\n console.log(chalk.bold('Tags:'), metadata.tags.map(t => chalk.cyan(t)).join(', '));\n }\n if (metadata.createdAt) {\n console.log(chalk.bold('Created:'), metadata.createdAt);\n }\n if (metadata.supersededBy) {\n console.log(chalk.bold('Superseded by:'), chalk.yellow(metadata.supersededBy));\n }\n console.log('');\n\n // Decision content\n console.log(chalk.bold.underline('Summary'));\n console.log(content.summary);\n console.log('');\n\n console.log(chalk.bold.underline('Rationale'));\n console.log(content.rationale);\n console.log('');\n\n if (content.context) {\n console.log(chalk.bold.underline('Context'));\n console.log(content.context);\n console.log('');\n }\n\n if (content.consequences && content.consequences.length > 0) {\n console.log(chalk.bold.underline('Consequences'));\n for (const consequence of content.consequences) {\n console.log(` • ${consequence}`);\n }\n console.log('');\n }\n\n // Constraints\n console.log(chalk.bold.underline(`Constraints (${constraints.length})`));\n for (const constraint of constraints) {\n const typeIcon = getTypeIcon(constraint.type);\n const severityBadge = getSeverityBadge(constraint.severity);\n\n console.log(`\\n ${typeIcon} ${chalk.bold(constraint.id)} ${severityBadge}`);\n console.log(` ${constraint.rule}`);\n console.log(chalk.dim(` Scope: ${constraint.scope}`));\n\n if (constraint.verifier) {\n console.log(chalk.dim(` Verifier: ${constraint.verifier}`));\n }\n\n if (constraint.exceptions && constraint.exceptions.length > 0) {\n console.log(chalk.dim(` Exceptions: ${constraint.exceptions.length}`));\n }\n }\n console.log('');\n\n // Verification\n if (decision.verification?.automated && decision.verification.automated.length > 0) {\n console.log(chalk.bold.underline('Automated Verification'));\n for (const check of decision.verification.automated) {\n console.log(` • ${check.check} (${check.frequency})`);\n console.log(chalk.dim(` Target: ${check.target}`));\n }\n console.log('');\n }\n\n // Links\n if (decision.links) {\n const { related, supersedes, references } = decision.links;\n\n if (related && related.length > 0) {\n console.log(chalk.bold('Related:'), related.join(', '));\n }\n if (supersedes && supersedes.length > 0) {\n console.log(chalk.bold('Supersedes:'), supersedes.join(', '));\n }\n if (references && references.length > 0) {\n console.log(chalk.bold('References:'));\n for (const ref of references) {\n console.log(` • ${ref}`);\n }\n }\n }\n}\n\nfunction getStatusBadge(status: string): string {\n switch (status) {\n case 'active':\n return chalk.bgGreen.black(' ACTIVE ');\n case 'draft':\n return chalk.bgYellow.black(' DRAFT ');\n case 'deprecated':\n return chalk.bgGray.white(' DEPRECATED ');\n case 'superseded':\n return chalk.bgBlue.white(' SUPERSEDED ');\n default:\n return status;\n }\n}\n\nfunction getTypeIcon(type: ConstraintType): string {\n switch (type) {\n case 'invariant':\n return chalk.red('●');\n case 'convention':\n return chalk.yellow('●');\n case 'guideline':\n return chalk.green('●');\n default:\n return '○';\n }\n}\n\nfunction getSeverityBadge(severity: Severity): string {\n switch (severity) {\n case 'critical':\n return chalk.bgRed.white(' CRITICAL ');\n case 'high':\n return chalk.bgYellow.black(' HIGH ');\n case 'medium':\n return chalk.bgCyan.black(' MEDIUM ');\n case 'low':\n return chalk.bgGray.white(' LOW ');\n default:\n return severity;\n }\n}\n","/**\n * Validate decisions command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { validateDecisionFile } from '../../../registry/loader.js';\nimport { getDecisionsDir, readFilesInDir, pathExists, getSpecBridgeDir } from '../../../utils/fs.js';\nimport { NotInitializedError } from '../../../core/errors/index.js';\n\ninterface ValidateOptions {\n file?: string;\n}\n\nexport const validateDecisions = new Command('validate')\n .description('Validate decision files')\n .option('-f, --file <path>', 'Validate a specific file')\n .action(async (options: ValidateOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Validating decisions...').start();\n\n try {\n let files: string[] = [];\n\n if (options.file) {\n files = [options.file];\n } else {\n const decisionsDir = getDecisionsDir(cwd);\n const decisionFiles = await readFilesInDir(\n decisionsDir,\n (f) => f.endsWith('.decision.yaml')\n );\n files = decisionFiles.map((f) => join(decisionsDir, f));\n }\n\n if (files.length === 0) {\n spinner.info('No decision files found.');\n return;\n }\n\n let valid = 0;\n let invalid = 0;\n const errors: { file: string; errors: string[] }[] = [];\n\n for (const file of files) {\n const result = await validateDecisionFile(file);\n if (result.valid) {\n valid++;\n } else {\n invalid++;\n errors.push({ file, errors: result.errors });\n }\n }\n\n spinner.stop();\n\n // Print results\n if (invalid === 0) {\n console.log(chalk.green(`✓ All ${valid} decision file(s) are valid.`));\n } else {\n console.log(chalk.red(`✗ ${invalid} of ${files.length} decision file(s) have errors.\\n`));\n\n for (const { file, errors: fileErrors } of errors) {\n console.log(chalk.red(`File: ${file}`));\n for (const err of fileErrors) {\n console.log(chalk.dim(` - ${err}`));\n }\n console.log('');\n }\n\n process.exit(1);\n }\n } catch (error) {\n spinner.fail('Validation failed');\n throw error;\n }\n });\n","/**\n * Create decision command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { join } from 'node:path';\nimport { writeTextFile, getDecisionsDir, pathExists, getSpecBridgeDir } from '../../../utils/fs.js';\nimport { stringifyYaml } from '../../../utils/yaml.js';\nimport { NotInitializedError } from '../../../core/errors/index.js';\n\ninterface CreateOptions {\n title: string;\n summary: string;\n type?: 'invariant' | 'convention' | 'guideline';\n severity?: 'critical' | 'high' | 'medium' | 'low';\n scope?: string;\n owner?: string;\n}\n\nexport const createDecision = new Command('create')\n .description('Create a new decision file')\n .argument('<id>', 'Decision ID (e.g., auth-001)')\n .requiredOption('-t, --title <title>', 'Decision title')\n .requiredOption('-s, --summary <summary>', 'One-sentence summary')\n .option('--type <type>', 'Default constraint type (invariant, convention, guideline)', 'convention')\n .option('--severity <severity>', 'Default constraint severity (critical, high, medium, low)', 'medium')\n .option('--scope <scope>', 'Default constraint scope (glob pattern)', 'src/**/*.ts')\n .option('-o, --owner <owner>', 'Owner name', 'team')\n .action(async (id: string, options: CreateOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n // Validate ID format\n if (!/^[a-z0-9-]+$/.test(id)) {\n console.error(chalk.red('Error: Decision ID must be lowercase alphanumeric with hyphens only.'));\n process.exit(1);\n }\n\n const decisionsDir = getDecisionsDir(cwd);\n const filePath = join(decisionsDir, `${id}.decision.yaml`);\n\n // Check if file already exists\n if (await pathExists(filePath)) {\n console.error(chalk.red(`Error: Decision file already exists: ${filePath}`));\n process.exit(1);\n }\n\n // Create decision structure\n const decision = {\n kind: 'Decision',\n metadata: {\n id,\n title: options.title,\n status: 'draft',\n owners: [options.owner || 'team'],\n createdAt: new Date().toISOString(),\n tags: [],\n },\n decision: {\n summary: options.summary,\n rationale: 'TODO: Explain why this decision was made.',\n context: 'TODO: Describe the context and background.',\n consequences: [\n 'TODO: List positive consequences',\n 'TODO: List negative consequences or trade-offs',\n ],\n },\n constraints: [\n {\n id: `${id}-c1`,\n type: options.type || 'convention',\n rule: 'TODO: Describe the constraint rule',\n severity: options.severity || 'medium',\n scope: options.scope || 'src/**/*.ts',\n },\n ],\n verification: {\n automated: [],\n },\n };\n\n // Write file\n await writeTextFile(filePath, stringifyYaml(decision));\n\n console.log(chalk.green(`✓ Created decision: ${filePath}`));\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(` 1. Edit the file to add rationale, context, and consequences`);\n console.log(` 2. Define constraints with appropriate scopes`);\n console.log(` 3. Run ${chalk.bold('specbridge decision validate')} to check syntax`);\n console.log(` 4. Change status from ${chalk.yellow('draft')} to ${chalk.green('active')} when ready`);\n });\n","/**\n * Hook command - Git hook integration\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, readTextFile, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { VerificationLevel } from '../../core/types/index.js';\n\nconst HOOK_SCRIPT = `#!/bin/sh\n# SpecBridge pre-commit hook\n# Runs verification on staged files\n\necho \"Running SpecBridge verification...\"\n\n# Run specbridge hook (it will detect staged files automatically)\nnpx specbridge hook run --level commit\n\nexit $?\n`;\n\nexport function createHookCommand(): Command {\n const hookCommand = new Command('hook')\n .description('Manage Git hooks for verification');\n\n hookCommand\n .command('install')\n .description('Install Git pre-commit hook')\n .option('-f, --force', 'Overwrite existing hook')\n .option('--husky', 'Install for husky')\n .option('--lefthook', 'Install for lefthook')\n .action(async (options: { force?: boolean; husky?: boolean; lefthook?: boolean }) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Detecting hook system...').start();\n\n try {\n // Detect hook system\n let hookPath: string;\n let hookContent: string;\n\n if (options.husky) {\n // Install for husky\n hookPath = join(cwd, '.husky', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing husky pre-commit hook...';\n } else if (options.lefthook) {\n // Show lefthook config\n spinner.succeed('Lefthook detected');\n console.log('');\n console.log(chalk.cyan('Add this to your lefthook.yml:'));\n console.log('');\n console.log(chalk.dim(`pre-commit:\n commands:\n specbridge:\n glob: \"*.{ts,tsx}\"\n run: npx specbridge hook run --level commit --files {staged_files}\n`));\n return;\n } else {\n // Check for .husky directory\n if (await pathExists(join(cwd, '.husky'))) {\n hookPath = join(cwd, '.husky', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing husky pre-commit hook...';\n } else if (await pathExists(join(cwd, 'lefthook.yml'))) {\n spinner.succeed('Lefthook detected');\n console.log('');\n console.log(chalk.cyan('Add this to your lefthook.yml:'));\n console.log('');\n console.log(chalk.dim(`pre-commit:\n commands:\n specbridge:\n glob: \"*.{ts,tsx}\"\n run: npx specbridge hook run --level commit --files {staged_files}\n`));\n return;\n } else {\n // Default to .git/hooks\n hookPath = join(cwd, '.git', 'hooks', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing Git pre-commit hook...';\n }\n }\n\n // Check if hook already exists\n if (await pathExists(hookPath) && !options.force) {\n spinner.fail('Hook already exists');\n console.log(chalk.yellow(`Use --force to overwrite: ${hookPath}`));\n return;\n }\n\n // Write hook\n await writeTextFile(hookPath, hookContent);\n\n // Make executable (Unix)\n const { execSync } = await import('node:child_process');\n try {\n execSync(`chmod +x \"${hookPath}\"`, { stdio: 'ignore' });\n } catch {\n // Ignore on Windows\n }\n\n spinner.succeed('Pre-commit hook installed');\n console.log(chalk.dim(` Path: ${hookPath}`));\n console.log('');\n console.log(chalk.cyan('The hook will run on each commit and verify staged files.'));\n } catch (error) {\n spinner.fail('Failed to install hook');\n throw error;\n }\n });\n\n hookCommand\n .command('run')\n .description('Run verification (called by hook)')\n .option('-l, --level <level>', 'Verification level', 'commit')\n .option('-f, --files <files>', 'Space or comma-separated file list')\n .action(async (options: { level?: string; files?: string }) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n try {\n const config = await loadConfig(cwd);\n const level = (options.level || 'commit') as VerificationLevel;\n\n // Parse files\n let files = options.files\n ? options.files.split(/[\\s,]+/).filter(f => f.length > 0)\n : undefined;\n\n if (!files || files.length === 0) {\n // Auto-detect staged files\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileAsync = promisify(execFile);\n\n try {\n const { stdout } = await execFileAsync('git', ['diff', '--cached', '--name-only', '--diff-filter=AM'], { cwd });\n files = stdout\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((f) => /\\.(ts|tsx|js|jsx)$/.test(f));\n } catch {\n files = [];\n }\n }\n\n if (!files || files.length === 0) {\n process.exit(0);\n }\n\n // Run verification\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level,\n files,\n cwd,\n });\n\n // Output result\n if (result.violations.length === 0) {\n console.log(chalk.green('✓ SpecBridge: All checks passed'));\n process.exit(0);\n }\n\n // Print violations concisely\n console.log(chalk.red(`✗ SpecBridge: ${result.violations.length} violation(s) found`));\n console.log('');\n\n for (const v of result.violations) {\n const location = v.line ? `:${v.line}` : '';\n console.log(` ${v.file}${location}: ${v.message}`);\n console.log(chalk.dim(` [${v.severity}] ${v.decisionId}/${v.constraintId}`));\n }\n\n console.log('');\n console.log(chalk.yellow('Run `specbridge verify` for full details.'));\n\n process.exit(result.success ? 0 : 1);\n } catch (error) {\n console.error(chalk.red('SpecBridge verification failed'));\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n hookCommand\n .command('uninstall')\n .description('Remove Git pre-commit hook')\n .action(async () => {\n const cwd = process.cwd();\n const spinner = ora('Removing hook...').start();\n\n try {\n const hookPaths = [\n join(cwd, '.husky', 'pre-commit'),\n join(cwd, '.git', 'hooks', 'pre-commit'),\n ];\n\n let removed = false;\n for (const hookPath of hookPaths) {\n if (await pathExists(hookPath)) {\n const content = await readTextFile(hookPath);\n if (content.includes('SpecBridge')) {\n const { unlink } = await import('node:fs/promises');\n await unlink(hookPath);\n spinner.succeed(`Removed hook: ${hookPath}`);\n removed = true;\n }\n }\n }\n\n if (!removed) {\n spinner.info('No SpecBridge hooks found');\n }\n } catch (error) {\n spinner.fail('Failed to remove hook');\n throw error;\n }\n });\n\n return hookCommand;\n}\n\nexport const hookCommand = createHookCommand();\n","/**\n * Report command - Generate compliance reports\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { generateReport } from '../../reporting/reporter.js';\nimport { formatConsoleReport } from '../../reporting/formats/console.js';\nimport { formatMarkdownReport } from '../../reporting/formats/markdown.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, getReportsDir, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { ReportStorage } from '../../reporting/storage.js';\nimport { detectDrift, analyzeTrend } from '../../reporting/drift.js';\n\ninterface ReportOptions {\n format?: string;\n output?: string;\n save?: boolean;\n all?: boolean;\n trend?: boolean;\n drift?: boolean;\n days?: string;\n}\n\nexport const reportCommand = new Command('report')\n .description('Generate compliance report')\n .option('-f, --format <format>', 'Output format (console, json, markdown)', 'console')\n .option('-o, --output <file>', 'Output file path')\n .option('--save', 'Save to .specbridge/reports/')\n .option('-a, --all', 'Include all decisions (not just active)')\n .option('--trend', 'Show compliance trend over time')\n .option('--drift', 'Analyze drift since last report')\n .option('--days <n>', 'Number of days for trend analysis', '30')\n .action(async (options: ReportOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Generating compliance report...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Generate report\n const report = await generateReport(config, {\n includeAll: options.all,\n cwd,\n });\n\n spinner.succeed('Report generated');\n\n // Initialize report storage\n const storage = new ReportStorage(cwd);\n\n // Auto-save all reports to history\n await storage.save(report);\n\n // Handle trend analysis\n if (options.trend) {\n console.log('\\n' + chalk.blue.bold('=== Compliance Trend Analysis ===\\n'));\n\n const days = parseInt(options.days || '30', 10);\n const history = await storage.loadHistory(days);\n\n if (history.length < 2) {\n console.log(chalk.yellow(`Not enough data for trend analysis. Found ${history.length} report(s), need at least 2.`));\n } else {\n const trend = await analyzeTrend(history);\n\n console.log(chalk.bold(`Period: ${trend.period.start} to ${trend.period.end} (${trend.period.days} days)`));\n console.log(`\\nOverall Compliance: ${trend.overall.startCompliance}% → ${trend.overall.endCompliance}% (${trend.overall.change > 0 ? '+' : ''}${trend.overall.change.toFixed(1)}%)`);\n\n const trendEmoji = trend.overall.trend === 'improving' ? '📈' : trend.overall.trend === 'degrading' ? '📉' : '➡️';\n const trendColor = trend.overall.trend === 'improving' ? chalk.green : trend.overall.trend === 'degrading' ? chalk.red : chalk.yellow;\n console.log(trendColor(`${trendEmoji} Trend: ${trend.overall.trend.toUpperCase()}`));\n\n // Show top degraded decisions\n const degrading = trend.decisions.filter(d => d.trend === 'degrading').slice(0, 3);\n if (degrading.length > 0) {\n console.log(chalk.red('\\n⚠️ Most Degraded Decisions:'));\n degrading.forEach(d => {\n console.log(` • ${d.title}: ${d.startCompliance}% → ${d.endCompliance}% (${d.change.toFixed(1)}%)`);\n });\n }\n\n // Show top improved decisions\n const improving = trend.decisions.filter(d => d.trend === 'improving').slice(0, 3);\n if (improving.length > 0) {\n console.log(chalk.green('\\n✅ Most Improved Decisions:'));\n improving.forEach(d => {\n console.log(` • ${d.title}: ${d.startCompliance}% → ${d.endCompliance}% (+${d.change.toFixed(1)}%)`);\n });\n }\n }\n\n console.log(''); // Empty line\n }\n\n // Handle drift analysis\n if (options.drift) {\n console.log('\\n' + chalk.blue.bold('=== Drift Analysis ===\\n'));\n\n const history = await storage.loadHistory(2);\n\n if (history.length < 2) {\n console.log(chalk.yellow('Not enough data for drift analysis. Need at least 2 reports.'));\n } else {\n const currentEntry = history[0];\n const previousEntry = history[1];\n\n if (!currentEntry || !previousEntry) {\n console.log(chalk.yellow('Invalid history data.'));\n return;\n }\n\n const drift = await detectDrift(currentEntry.report, previousEntry.report);\n\n console.log(chalk.bold(`Comparing: ${previousEntry.timestamp} vs ${currentEntry.timestamp}`));\n console.log(`\\nCompliance Change: ${drift.complianceChange > 0 ? '+' : ''}${drift.complianceChange.toFixed(1)}%`);\n\n const driftEmoji = drift.trend === 'improving' ? '📈' : drift.trend === 'degrading' ? '📉' : '➡️';\n const driftColor = drift.trend === 'improving' ? chalk.green : drift.trend === 'degrading' ? chalk.red : chalk.yellow;\n console.log(driftColor(`${driftEmoji} Overall Trend: ${drift.trend.toUpperCase()}`));\n\n // Show violation changes\n if (drift.summary.newViolations.total > 0) {\n console.log(chalk.red(`\\n⚠️ New Violations: ${drift.summary.newViolations.total}`));\n if (drift.summary.newViolations.critical > 0) {\n console.log(` • Critical: ${drift.summary.newViolations.critical}`);\n }\n if (drift.summary.newViolations.high > 0) {\n console.log(` • High: ${drift.summary.newViolations.high}`);\n }\n if (drift.summary.newViolations.medium > 0) {\n console.log(` • Medium: ${drift.summary.newViolations.medium}`);\n }\n if (drift.summary.newViolations.low > 0) {\n console.log(` • Low: ${drift.summary.newViolations.low}`);\n }\n }\n\n if (drift.summary.fixedViolations.total > 0) {\n console.log(chalk.green(`\\n✅ Fixed Violations: ${drift.summary.fixedViolations.total}`));\n if (drift.summary.fixedViolations.critical > 0) {\n console.log(` • Critical: ${drift.summary.fixedViolations.critical}`);\n }\n if (drift.summary.fixedViolations.high > 0) {\n console.log(` • High: ${drift.summary.fixedViolations.high}`);\n }\n if (drift.summary.fixedViolations.medium > 0) {\n console.log(` • Medium: ${drift.summary.fixedViolations.medium}`);\n }\n if (drift.summary.fixedViolations.low > 0) {\n console.log(` • Low: ${drift.summary.fixedViolations.low}`);\n }\n }\n\n // Show most degraded decisions\n if (drift.mostDegraded.length > 0) {\n console.log(chalk.red('\\n📉 Most Degraded:'));\n drift.mostDegraded.forEach(d => {\n console.log(` • ${d.title}: ${d.previousCompliance}% → ${d.currentCompliance}% (${d.complianceChange.toFixed(1)}%)`);\n if (d.newViolations > 0) {\n console.log(` +${d.newViolations} new violation(s)`);\n }\n });\n }\n\n // Show most improved decisions\n if (drift.mostImproved.length > 0) {\n console.log(chalk.green('\\n📈 Most Improved:'));\n drift.mostImproved.forEach(d => {\n console.log(` • ${d.title}: ${d.previousCompliance}% → ${d.currentCompliance}% (+${d.complianceChange.toFixed(1)}%)`);\n if (d.fixedViolations > 0) {\n console.log(` -${d.fixedViolations} fixed violation(s)`);\n }\n });\n }\n }\n\n console.log(''); // Empty line\n }\n\n // Format output\n let output: string;\n let extension: string;\n\n switch (options.format) {\n case 'json':\n output = JSON.stringify(report, null, 2);\n extension = 'json';\n break;\n case 'markdown':\n case 'md':\n output = formatMarkdownReport(report);\n extension = 'md';\n break;\n case 'console':\n default:\n output = formatConsoleReport(report);\n extension = 'txt';\n break;\n }\n\n // Output to console (skip if drift/trend already shown)\n if (!options.trend && !options.drift) {\n if (options.format !== 'json' || !options.output) {\n console.log(output);\n }\n }\n\n // Save to file\n if (options.output || options.save) {\n const outputPath = options.output || join(\n getReportsDir(cwd),\n `health-${new Date().toISOString().split('T')[0]}.${extension}`\n );\n\n await writeTextFile(outputPath, output);\n console.log(chalk.green(`\\nReport saved to: ${outputPath}`));\n\n // Also save latest\n if (options.save && !options.output) {\n const latestPath = join(getReportsDir(cwd), `health-latest.${extension}`);\n await writeTextFile(latestPath, output);\n }\n }\n } catch (error) {\n spinner.fail('Failed to generate report');\n throw error;\n }\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 * Context command - Generate agent context\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { generateFormattedContext } from '../../agent/context.generator.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface ContextOptions {\n format?: string;\n output?: string;\n rationale?: boolean;\n}\n\nexport const contextCommand = new Command('context')\n .description('Generate architectural context for a file (for AI agents)')\n .argument('<file>', 'File path to generate context for')\n .option('-f, --format <format>', 'Output format (markdown, json, mcp)', 'markdown')\n .option('-o, --output <file>', 'Output file path')\n .option('--no-rationale', 'Exclude rationale/summary from output')\n .action(async (file: string, options: ContextOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Generate context\n const output = await generateFormattedContext(file, config, {\n format: options.format as 'markdown' | 'json' | 'mcp',\n includeRationale: options.rationale !== false,\n cwd,\n });\n\n // Output\n if (options.output) {\n await writeTextFile(options.output, output);\n console.log(chalk.green(`Context saved to: ${options.output}`));\n } else {\n console.log(output);\n }\n } catch (error) {\n console.error(chalk.red('Failed to generate context'));\n throw error;\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 * LSP command - Start SpecBridge language server\n */\nimport { Command } from 'commander';\nimport { startLspServer } from '../../lsp/index.js';\n\nexport const lspCommand = new Command('lsp')\n .description('Start SpecBridge language server (stdio)')\n .option('--verbose', 'Enable verbose server logging', false)\n .action(async (options: { verbose?: boolean }) => {\n await startLspServer({ cwd: process.cwd(), verbose: Boolean(options.verbose) });\n });\n\n","/**\n * SpecBridge Language Server (LSP)\n */\nimport { createConnection, ProposedFeatures, TextDocuments, TextDocumentSyncKind, DiagnosticSeverity, CodeActionKind } from 'vscode-languageserver/node.js';\nimport { TextDocument } from 'vscode-languageserver-textdocument';\nimport { fileURLToPath } from 'node:url';\nimport path from 'node:path';\nimport { Project } from 'ts-morph';\nimport chalk from 'chalk';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { getSpecBridgeDir, pathExists } from '../utils/fs.js';\nimport { selectVerifierForConstraint, type VerificationContext } from '../verification/verifiers/index.js';\nimport { shouldApplyConstraintToFile } from '../verification/applicability.js';\nimport type { Decision, Violation, Severity } from '../core/types/index.js';\nimport { NotInitializedError } from '../core/errors/index.js';\n\nexport interface LspServerOptions {\n cwd: string;\n verbose?: boolean;\n}\n\nfunction severityToDiagnostic(severity: Severity): DiagnosticSeverity {\n switch (severity) {\n case 'critical':\n return DiagnosticSeverity.Error;\n case 'high':\n return DiagnosticSeverity.Warning;\n case 'medium':\n return DiagnosticSeverity.Information;\n case 'low':\n return DiagnosticSeverity.Hint;\n default:\n return DiagnosticSeverity.Information;\n }\n}\n\nfunction uriToFilePath(uri: string): string {\n if (uri.startsWith('file://')) return fileURLToPath(uri);\n // Fallback: treat as plain path\n return uri;\n}\n\nfunction violationToRange(doc: TextDocument, v: Violation) {\n // Prefer autofix ranges when available, otherwise line/column best-effort.\n const edit = v.autofix?.edits?.[0];\n if (edit) {\n return {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n };\n }\n\n const line = Math.max(0, (v.line ?? 1) - 1);\n const char = Math.max(0, (v.column ?? 1) - 1);\n return {\n start: { line, character: char },\n end: { line, character: char + 1 },\n };\n}\n\nexport class SpecBridgeLspServer {\n private connection = createConnection(ProposedFeatures.all);\n private documents = new TextDocuments(TextDocument);\n\n private options: LspServerOptions;\n private registry: Registry | null = null;\n private decisions: Decision[] = [];\n private cwd: string;\n private project: Project;\n private cache = new Map<string, Violation[]>();\n private initError: string | null = null;\n\n constructor(options: LspServerOptions) {\n this.options = options;\n this.cwd = options.cwd;\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n async initialize(): Promise<void> {\n this.connection.onInitialize(async () => {\n await this.initializeWorkspace();\n\n return {\n capabilities: {\n textDocumentSync: TextDocumentSyncKind.Incremental,\n codeActionProvider: true,\n },\n };\n });\n\n this.documents.onDidOpen((e) => {\n void this.validateDocument(e.document);\n });\n\n this.documents.onDidChangeContent((change) => {\n void this.validateDocument(change.document);\n });\n\n this.documents.onDidClose((e) => {\n this.cache.delete(e.document.uri);\n this.connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });\n });\n\n this.connection.onCodeAction((params) => {\n const violations = this.cache.get(params.textDocument.uri) || [];\n const doc = this.documents.get(params.textDocument.uri);\n if (!doc) return [];\n\n return violations\n .filter((v) => v.autofix && v.autofix.edits.length > 0)\n .map((v) => {\n const edits = v.autofix!.edits.map((edit) => ({\n range: {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n },\n newText: edit.text,\n }));\n\n return {\n title: v.autofix!.description,\n kind: CodeActionKind.QuickFix,\n edit: {\n changes: {\n [params.textDocument.uri]: edits,\n },\n },\n };\n });\n });\n\n this.documents.listen(this.connection);\n this.connection.listen();\n }\n\n private async initializeWorkspace(): Promise<void> {\n // Ensure initialized (but keep server alive if not).\n if (!await pathExists(getSpecBridgeDir(this.cwd))) {\n const err = new NotInitializedError();\n this.initError = err.message;\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n return;\n }\n\n try {\n const config = await loadConfig(this.cwd);\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n this.decisions = this.registry.getActive();\n\n // Prime project with source roots (best-effort). This enables verifiers that depend on import graph.\n for (const root of config.project.sourceRoots) {\n // ts-morph doesn't support globs directly; add root folders when possible.\n const rootPath = path.isAbsolute(root) ? root : path.join(this.cwd, root);\n // If root is a glob, fall back to adding the directory portion.\n const dir = rootPath.includes('*') ? rootPath.split('*')[0] : rootPath;\n if (dir && await pathExists(dir)) {\n this.project.addSourceFilesAtPaths(path.join(dir, '**/*.{ts,tsx,js,jsx}'));\n }\n }\n\n if (this.options.verbose) {\n this.connection.console.log(chalk.dim(`Loaded ${this.decisions.length} active decision(s)`));\n }\n } catch (error) {\n this.initError = error instanceof Error ? error.message : String(error);\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n }\n }\n\n private async verifyTextDocument(doc: TextDocument): Promise<Violation[]> {\n if (this.initError) {\n throw new Error(this.initError);\n }\n if (!this.registry) return [];\n\n const filePath = uriToFilePath(doc.uri);\n const sourceFile = this.project.createSourceFile(filePath, doc.getText(), { overwrite: true });\n\n const violations: Violation[] = [];\n\n for (const decision of this.decisions) {\n for (const constraint of decision.constraints) {\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd: this.cwd })) continue;\n\n const verifier = selectVerifierForConstraint(constraint.rule, constraint.verifier);\n if (!verifier) continue;\n\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n };\n\n try {\n const constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n } catch {\n // Ignore verifier errors (LSP should stay responsive)\n }\n }\n }\n\n return violations;\n }\n\n private async validateDocument(doc: TextDocument): Promise<void> {\n try {\n const violations = await this.verifyTextDocument(doc);\n this.cache.set(doc.uri, violations);\n\n const diagnostics = violations.map((v) => ({\n range: violationToRange(doc, v),\n severity: severityToDiagnostic(v.severity),\n message: v.message,\n source: 'specbridge',\n }));\n\n this.connection.sendDiagnostics({ uri: doc.uri, diagnostics });\n } catch (error) {\n // If workspace isn't initialized, surface a single diagnostic.\n const msg = error instanceof Error ? error.message : String(error);\n this.connection.sendDiagnostics({\n uri: doc.uri,\n diagnostics: [\n {\n range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },\n severity: DiagnosticSeverity.Error,\n message: msg,\n source: 'specbridge',\n },\n ],\n });\n }\n }\n}\n","import { SpecBridgeLspServer, type LspServerOptions } from './server.js';\n\nexport async function startLspServer(options: LspServerOptions): Promise<void> {\n const server = new SpecBridgeLspServer(options);\n await server.initialize();\n}\n\n","/**\n * Watch command - Verify changed files continuously\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport chokidar from 'chokidar';\nimport path from 'node:path';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { getSpecBridgeDir, pathExists } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { VerificationLevel } from '../../core/types/index.js';\n\nexport const watchCommand = new Command('watch')\n .description('Watch for changes and verify files continuously')\n .option('-l, --level <level>', 'Verification level (commit, pr, full)', 'full')\n .option('--debounce <ms>', 'Debounce verify on rapid changes', '150')\n .action(async (options: { level?: string; debounce?: string }) => {\n const cwd = process.cwd();\n\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const config = await loadConfig(cwd);\n const engine = createVerificationEngine();\n const level = (options.level || 'full') as VerificationLevel;\n const debounceMs = Number.parseInt(options.debounce || '150', 10);\n\n let timer: NodeJS.Timeout | null = null;\n let pendingPath: string | null = null;\n\n const run = async (changedPath: string) => {\n const absolutePath = path.isAbsolute(changedPath) ? changedPath : path.join(cwd, changedPath);\n const result = await engine.verify(config, {\n level,\n files: [absolutePath],\n cwd,\n });\n\n const prefix = result.success ? chalk.green('✓') : chalk.red('✗');\n const summary = `${prefix} ${path.relative(cwd, absolutePath)}: ${result.violations.length} violation(s)`;\n console.log(summary);\n\n for (const v of result.violations.slice(0, 20)) {\n const loc = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n console.log(chalk.dim(` - ${v.file}${loc}: ${v.message} [${v.severity}]`));\n }\n if (result.violations.length > 20) {\n console.log(chalk.dim(` … ${result.violations.length - 20} more`));\n }\n };\n\n const watcher = chokidar.watch(config.project.sourceRoots, {\n cwd,\n ignored: config.project.exclude,\n ignoreInitial: true,\n persistent: true,\n });\n\n console.log(chalk.blue('Watching for changes...'));\n\n watcher.on('change', (changedPath) => {\n pendingPath = changedPath;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n if (!pendingPath) return;\n void run(pendingPath);\n pendingPath = null;\n }, debounceMs);\n });\n });\n\n","/**\n * MCP Server command - Start SpecBridge MCP server\n */\nimport { Command } from 'commander';\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { SpecBridgeMcpServer } from '../../mcp/server.js';\n\nfunction getCliVersion(): string {\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n // In production (bundled): import.meta.url points to dist/cli.js, so ../package.json is correct.\n const packageJsonPath = join(__dirname, '../package.json');\n const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n return String(pkg.version || '0.0.0');\n } catch {\n return '0.0.0';\n }\n}\n\nexport const mcpServerCommand = new Command('mcp-server')\n .description('Start SpecBridge MCP server (stdio)')\n .action(async () => {\n const server = new SpecBridgeMcpServer({\n cwd: process.cwd(),\n version: getCliVersion(),\n });\n\n await server.initialize();\n // MCP servers should write logs to stderr; keep stdout for protocol.\n console.error('SpecBridge MCP server starting (stdio)...');\n await server.startStdio();\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","/**\n * Prompt command - Generate AI agent prompt templates\n */\nimport { Command } from 'commander';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { generateContext } from '../../agent/context.generator.js';\nimport { templates } from '../../agent/templates.js';\n\nexport const promptCommand = new Command('prompt')\n .description('Generate AI agent prompt templates')\n .argument('<template>', 'Template name (code-review|refactoring|migration)')\n .argument('<file>', 'File path (used to select applicable decisions)')\n .option('--decision <id>', 'Decision id (required for migration)')\n .action(async (templateName: string, file: string, options: { decision?: string }) => {\n const cwd = process.cwd();\n\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const tpl = templates[templateName];\n if (!tpl) {\n throw new Error(`Unknown template: ${templateName}`);\n }\n\n if (templateName === 'migration' && !options.decision) {\n throw new Error('Missing --decision <id> for migration template');\n }\n\n const config = await loadConfig(cwd);\n const context = await generateContext(file, config, { cwd, includeRationale: true });\n const prompt = tpl.generate(context, { decisionId: options.decision });\n console.log(prompt);\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 * Analytics command - Analyze compliance trends and decision impact\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { ReportStorage } from '../../reporting/storage.js';\nimport { AnalyticsEngine } from '../../analytics/engine.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface AnalyticsOptions {\n insights?: boolean;\n days?: string;\n format?: string;\n}\n\nexport const analyticsCommand = new Command('analytics')\n .description('Analyze compliance trends and decision impact')\n .argument('[decision-id]', 'Specific decision to analyze')\n .option('--insights', 'Show AI-generated insights')\n .option('--days <n>', 'Number of days of history to analyze', '90')\n .option('-f, --format <format>', 'Output format (console, json)', 'console')\n .action(async (decisionId: string | undefined, options: AnalyticsOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Analyzing compliance data...').start();\n\n try {\n const storage = new ReportStorage(cwd);\n const days = parseInt(options.days || '90', 10);\n const history = await storage.loadHistory(days);\n\n if (history.length === 0) {\n spinner.fail('No historical reports found');\n console.log(chalk.yellow('\\nGenerate reports with: specbridge report'));\n return;\n }\n\n spinner.succeed(`Loaded ${history.length} historical report(s)`);\n\n const engine = new AnalyticsEngine();\n\n // Format output\n if (options.format === 'json') {\n if (decisionId) {\n const metrics = await engine.analyzeDecision(decisionId, history);\n console.log(JSON.stringify(metrics, null, 2));\n } else {\n const summary = await engine.generateSummary(history);\n console.log(JSON.stringify(summary, null, 2));\n }\n return;\n }\n\n // Console format\n if (decisionId) {\n // Analyze specific decision\n const metrics = await engine.analyzeDecision(decisionId, history);\n\n console.log('\\n' + chalk.blue.bold(`=== Decision Analytics: ${metrics.title} ===\\n`));\n\n console.log(chalk.bold('Overview:'));\n console.log(` ID: ${metrics.decisionId}`);\n console.log(` Current Violations: ${metrics.totalViolations}`);\n console.log(` Average Compliance: ${metrics.averageComplianceScore.toFixed(1)}%`);\n\n const trendEmoji = metrics.trendDirection === 'up' ? '📈' : metrics.trendDirection === 'down' ? '📉' : '➡️';\n const trendColor = metrics.trendDirection === 'up' ? chalk.green : metrics.trendDirection === 'down' ? chalk.red : chalk.yellow;\n console.log(` ${trendColor(`${trendEmoji} Trend: ${metrics.trendDirection.toUpperCase()}`)}`);\n\n // Show history\n if (metrics.history.length > 0) {\n console.log(chalk.bold('\\nCompliance History:'));\n const recentHistory = metrics.history.slice(-10); // Show last 10 entries\n recentHistory.forEach(h => {\n const icon = h.violations === 0 ? '✅' : '⚠️';\n console.log(` ${icon} ${h.date}: ${h.compliance}% (${h.violations} violations)`);\n });\n }\n } else {\n // Overall analytics\n const summary = await engine.generateSummary(history);\n\n console.log('\\n' + chalk.blue.bold('=== Overall Analytics ===\\n'));\n\n console.log(chalk.bold('Summary:'));\n console.log(` Total Decisions: ${summary.totalDecisions}`);\n console.log(` Average Compliance: ${summary.averageCompliance}%`);\n console.log(` Critical Issues: ${summary.criticalIssues}`);\n\n const trendEmoji = summary.overallTrend === 'up' ? '📈' : summary.overallTrend === 'down' ? '📉' : '➡️';\n const trendColor = summary.overallTrend === 'up' ? chalk.green : summary.overallTrend === 'down' ? chalk.red : chalk.yellow;\n console.log(` ${trendColor(`${trendEmoji} Overall Trend: ${summary.overallTrend.toUpperCase()}`)}`);\n\n // Top performers\n if (summary.topDecisions.length > 0) {\n console.log(chalk.green('\\n✅ Top Performing Decisions:'));\n summary.topDecisions.forEach((d, i) => {\n console.log(` ${i + 1}. ${d.title}: ${d.compliance}%`);\n });\n }\n\n // Bottom performers\n if (summary.bottomDecisions.length > 0) {\n console.log(chalk.red('\\n⚠️ Decisions Needing Attention:'));\n summary.bottomDecisions.forEach((d, i) => {\n console.log(` ${i + 1}. ${d.title}: ${d.compliance}%`);\n });\n }\n\n // Show insights if requested or if there are issues\n if (options.insights || summary.criticalIssues > 0) {\n console.log(chalk.blue.bold('\\n=== Insights ===\\n'));\n\n const insights = summary.insights;\n\n // Group by type\n const warnings = insights.filter(i => i.type === 'warning');\n const successes = insights.filter(i => i.type === 'success');\n const infos = insights.filter(i => i.type === 'info');\n\n if (warnings.length > 0) {\n console.log(chalk.red('⚠️ Warnings:'));\n warnings.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n\n if (successes.length > 0) {\n console.log(chalk.green('✅ Positive Trends:'));\n successes.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n\n if (infos.length > 0) {\n console.log(chalk.blue('💡 Suggestions:'));\n infos.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n }\n }\n\n // Show data range\n const latestEntry = history[history.length - 1];\n const oldestEntry = history[0];\n if (latestEntry && oldestEntry) {\n console.log(chalk.gray(`\\nData range: ${latestEntry.timestamp} to ${oldestEntry.timestamp}`));\n }\n console.log(chalk.gray(`Analyzing ${history.length} report(s) over ${days} days\\n`));\n } catch (error) {\n spinner.fail('Analytics failed');\n throw error;\n }\n });\n","/**\n * Analytics engine - Provide insights into compliance trends and decision impact\n */\nimport type { DecisionCompliance, Severity } from '../core/types/index.js';\nimport type { StoredReport } from '../reporting/storage.js';\n\nexport interface DecisionMetrics {\n decisionId: string;\n title: string;\n totalViolations: number;\n violationsByFile: Map<string, number>;\n violationsBySeverity: Record<Severity, number>;\n mostViolatedConstraint: { id: string; count: number } | null;\n averageComplianceScore: number;\n trendDirection: 'up' | 'down' | 'stable';\n history: Array<{\n date: string;\n compliance: number;\n violations: number;\n }>;\n}\n\nexport interface Insight {\n type: 'warning' | 'info' | 'success';\n category: 'compliance' | 'trend' | 'hotspot' | 'suggestion';\n message: string;\n details?: string;\n decisionId?: string;\n}\n\nexport interface AnalyticsSummary {\n totalDecisions: number;\n averageCompliance: number;\n overallTrend: 'up' | 'down' | 'stable';\n criticalIssues: number;\n topDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n bottomDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n insights: Insight[];\n}\n\n/**\n * Analytics engine for compliance data\n */\nexport class AnalyticsEngine {\n /**\n * Analyze a specific decision across historical reports\n */\n async analyzeDecision(\n decisionId: string,\n history: StoredReport[]\n ): Promise<DecisionMetrics> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n // Extract decision data from each report\n const decisionHistory: Array<{\n date: string;\n data: DecisionCompliance;\n }> = [];\n\n for (const { timestamp, report } of history) {\n const decision = report.byDecision.find(d => d.decisionId === decisionId);\n if (decision) {\n decisionHistory.push({ date: timestamp, data: decision });\n }\n }\n\n if (decisionHistory.length === 0) {\n throw new Error(`Decision ${decisionId} not found in any report`);\n }\n\n // Get latest data\n const latestEntry = decisionHistory[decisionHistory.length - 1];\n if (!latestEntry) {\n throw new Error(`No data found for decision ${decisionId}`);\n }\n const latest = latestEntry.data;\n\n // Calculate averages\n const averageCompliance =\n decisionHistory.reduce((sum, h) => sum + h.data.compliance, 0) / decisionHistory.length;\n\n // Determine trend\n let trendDirection: 'up' | 'down' | 'stable' = 'stable';\n if (decisionHistory.length >= 2) {\n const firstEntry = decisionHistory[0];\n if (!firstEntry) {\n throw new Error('Invalid decision history');\n }\n const first = firstEntry.data.compliance;\n const last = latest.compliance;\n const change = last - first;\n\n if (change > 5) {\n trendDirection = 'up';\n } else if (change < -5) {\n trendDirection = 'down';\n }\n }\n\n // Build history summary\n const historyData = decisionHistory.map(h => ({\n date: h.date,\n compliance: h.data.compliance,\n violations: h.data.violations,\n }));\n\n return {\n decisionId,\n title: latest.title,\n totalViolations: latest.violations,\n violationsByFile: new Map(), // Would need violation details to populate\n violationsBySeverity: {\n critical: 0,\n high: 0,\n medium: 0,\n low: 0,\n }, // Would need violation details to populate\n mostViolatedConstraint: null, // Would need constraint details to populate\n averageComplianceScore: averageCompliance,\n trendDirection,\n history: historyData,\n };\n }\n\n /**\n * Generate insights from historical data\n */\n async generateInsights(history: StoredReport[]): Promise<Insight[]> {\n if (history.length === 0) {\n return [];\n }\n\n const insights: Insight[] = [];\n\n // Sort by date (oldest first)\n const sorted = history.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n const latestEntry = sorted[sorted.length - 1];\n if (!latestEntry) {\n throw new Error('No reports in history');\n }\n const latest = latestEntry.report;\n\n // Insight: Overall compliance trend\n if (sorted.length >= 2) {\n const firstEntry = sorted[0];\n if (!firstEntry) {\n return insights;\n }\n const first = firstEntry.report;\n const complianceChange = latest.summary.compliance - first.summary.compliance;\n\n if (complianceChange > 10) {\n insights.push({\n type: 'success',\n category: 'trend',\n message: `Compliance has improved by ${complianceChange.toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n } else if (complianceChange < -10) {\n insights.push({\n type: 'warning',\n category: 'trend',\n message: `Compliance has dropped by ${Math.abs(complianceChange).toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n }\n }\n\n // Insight: Critical violations\n if (latest.summary.violations.critical > 0) {\n insights.push({\n type: 'warning',\n category: 'compliance',\n message: `${latest.summary.violations.critical} critical violation(s) require immediate attention`,\n details: 'Critical violations block deployments and should be resolved as soon as possible',\n });\n }\n\n // Insight: Decision-specific issues\n const problematicDecisions = latest.byDecision.filter(d => d.compliance < 50);\n if (problematicDecisions.length > 0) {\n insights.push({\n type: 'warning',\n category: 'hotspot',\n message: `${problematicDecisions.length} decision(s) have less than 50% compliance`,\n details: problematicDecisions.map(d => `${d.title} (${d.compliance}%)`).join(', '),\n });\n }\n\n // Insight: High compliance decisions\n const excellentDecisions = latest.byDecision.filter(d => d.compliance === 100);\n if (excellentDecisions.length > 0) {\n insights.push({\n type: 'success',\n category: 'compliance',\n message: `${excellentDecisions.length} decision(s) have 100% compliance`,\n details: excellentDecisions.map(d => d.title).join(', '),\n });\n }\n\n // Insight: Compare to average\n const avgCompliance = latest.summary.compliance;\n const decisionsAboveAvg = latest.byDecision.filter(d => d.compliance > avgCompliance);\n const decisionsBelowAvg = latest.byDecision.filter(d => d.compliance < avgCompliance);\n\n if (decisionsBelowAvg.length > decisionsAboveAvg.length) {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: `${decisionsBelowAvg.length} decisions are below average compliance`,\n details: 'Consider focusing improvement efforts on these lower-performing decisions',\n });\n }\n\n // Insight: Violation distribution\n const totalViolations =\n latest.summary.violations.critical +\n latest.summary.violations.high +\n latest.summary.violations.medium +\n latest.summary.violations.low;\n\n if (totalViolations > 0) {\n const criticalPercent = (latest.summary.violations.critical / totalViolations) * 100;\n const highPercent = (latest.summary.violations.high / totalViolations) * 100;\n\n if (criticalPercent + highPercent > 60) {\n insights.push({\n type: 'warning',\n category: 'suggestion',\n message: 'Most violations are high severity',\n details: `${criticalPercent.toFixed(0)}% critical, ${highPercent.toFixed(0)}% high. Prioritize these for the biggest impact.`,\n });\n } else {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: 'Most violations are lower severity',\n details: 'Consider addressing high-severity issues first for maximum impact',\n });\n }\n }\n\n return insights;\n }\n\n /**\n * Generate analytics summary\n */\n async generateSummary(history: StoredReport[]): Promise<AnalyticsSummary> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n const latestEntry = history[history.length - 1];\n if (!latestEntry) {\n throw new Error('Invalid history data');\n }\n const latest = latestEntry.report;\n\n // Calculate overall trend\n let overallTrend: 'up' | 'down' | 'stable' = 'stable';\n if (history.length >= 2) {\n const firstEntry = history[0];\n if (!firstEntry) {\n throw new Error('Invalid history data');\n }\n const first = firstEntry.report;\n const change = latest.summary.compliance - first.summary.compliance;\n\n if (change > 5) {\n overallTrend = 'up';\n } else if (change < -5) {\n overallTrend = 'down';\n }\n }\n\n // Find top and bottom performers\n const sortedByCompliance = [...latest.byDecision].sort(\n (a, b) => b.compliance - a.compliance\n );\n\n const topDecisions = sortedByCompliance.slice(0, 5).map(d => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n const bottomDecisions = sortedByCompliance.slice(-5).reverse().map(d => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n // Generate insights\n const insights = await this.generateInsights(history);\n\n return {\n totalDecisions: latest.byDecision.length,\n averageCompliance: latest.summary.compliance,\n overallTrend,\n criticalIssues: latest.summary.violations.critical,\n topDecisions,\n bottomDecisions,\n insights,\n };\n }\n}\n","/**\n * Dashboard command - Start compliance dashboard web server\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { createDashboardServer } from '../../dashboard/server.js';\n\ninterface DashboardOptions {\n port?: string;\n host?: string;\n}\n\nexport const dashboardCommand = new Command('dashboard')\n .description('Start compliance dashboard web server')\n .option('-p, --port <port>', 'Port to listen on', '3000')\n .option('-h, --host <host>', 'Host to bind to', 'localhost')\n .action(async (options: DashboardOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n console.log(chalk.blue('Starting SpecBridge dashboard...'));\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Create server\n const app = createDashboardServer({ cwd, config });\n\n // Start listening\n const port = parseInt(options.port || '3000', 10);\n const host = options.host || 'localhost';\n\n app.listen(port, host, () => {\n console.log(chalk.green(`\\n✓ Dashboard running at http://${host}:${port}`));\n console.log(chalk.gray(' Press Ctrl+C to stop\\n'));\n\n // Show helpful endpoints\n console.log(chalk.bold('API Endpoints:'));\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/health`)} - Health check`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/report/latest`)} - Latest report`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/decisions`)} - All decisions`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/analytics/summary`)} - Analytics`);\n console.log('');\n });\n\n // Handle shutdown gracefully\n process.on('SIGINT', () => {\n console.log(chalk.yellow('\\n\\nShutting down dashboard...'));\n process.exit(0);\n });\n\n process.on('SIGTERM', () => {\n console.log(chalk.yellow('\\n\\nShutting down dashboard...'));\n process.exit(0);\n });\n } catch (error) {\n console.error(chalk.red('Failed to start dashboard:'), error);\n throw error;\n }\n });\n","/**\n * Dashboard server - Compliance dashboard backend with REST API\n */\nimport express, { type Request, type Response, type Application } from 'express';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { ReportStorage } from '../reporting/storage.js';\nimport { AnalyticsEngine } from '../analytics/engine.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { detectDrift, analyzeTrend } from '../reporting/drift.js';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\ninterface DashboardOptions {\n cwd: string;\n config: SpecBridgeConfig;\n}\n\n/**\n * Create and configure the dashboard server\n */\nexport function createDashboardServer(options: DashboardOptions): Application {\n const { cwd, config } = options;\n const app = express();\n\n // Middleware\n app.use(express.json());\n\n // CORS for development\n app.use((_req, res, next) => {\n res.header('Access-Control-Allow-Origin', '*');\n res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.header('Access-Control-Allow-Headers', 'Content-Type');\n next();\n });\n\n /**\n * GET /api/report/latest\n * Get the most recent compliance report\n */\n app.get('/api/report/latest', async (_req: Request, res: Response) => {\n try {\n const report = await generateReport(config, { cwd });\n res.json(report);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to generate report',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/report/history?days=30\n * Get historical reports\n */\n app.get('/api/report/history', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n res.json(history);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load history',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/report/dates\n * Get all available report dates\n */\n app.get('/api/report/dates', async (_req: Request, res: Response) => {\n try {\n const storage = new ReportStorage(cwd);\n const dates = await storage.getAvailableDates();\n res.json(dates);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load dates',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/report/:date\n * Get a specific report by date\n */\n app.get('/api/report/:date', async (req: Request, res: Response) => {\n try {\n const date = req.params.date;\n if (!date) {\n res.status(400).json({ error: 'Date parameter required' });\n return;\n }\n\n const storage = new ReportStorage(cwd);\n const report = await storage.loadByDate(date);\n\n if (!report) {\n res.status(404).json({ error: 'Report not found' });\n return;\n }\n\n res.json(report);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load report',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/decisions\n * Get all architectural decisions\n */\n app.get('/api/decisions', async (_req: Request, res: Response) => {\n try {\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n const decisions = registry.getAll();\n res.json(decisions);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load decisions',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/decisions/:id\n * Get a specific decision by ID\n */\n app.get('/api/decisions/:id', async (req: Request, res: Response) => {\n try {\n const id = req.params.id;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n const decision = registry.get(id);\n\n if (!decision) {\n res.status(404).json({ error: 'Decision not found' });\n return;\n }\n\n res.json(decision);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/analytics/summary?days=90\n * Get analytics summary\n */\n app.get('/api/analytics/summary', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 90;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const summary = await engine.generateSummary(history);\n res.json(summary);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to generate analytics',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/analytics/decision/:id?days=90\n * Get analytics for a specific decision\n */\n app.get('/api/analytics/decision/:id', async (req: Request, res: Response) => {\n try {\n const id = req.params.id;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const days = parseInt(req.query.days as string) || 90;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const metrics = await engine.analyzeDecision(id, history);\n res.json(metrics);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/drift?days=2\n * Get drift analysis between most recent reports\n */\n app.get('/api/drift', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 2;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for drift analysis' });\n return;\n }\n\n const currentEntry = history[0];\n const previousEntry = history[1];\n\n if (!currentEntry || !previousEntry) {\n res.status(400).json({ error: 'Invalid history data' });\n return;\n }\n\n const drift = await detectDrift(currentEntry.report, previousEntry.report);\n res.json(drift);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze drift',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/trend?days=30\n * Get compliance trend over time\n */\n app.get('/api/trend', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for trend analysis' });\n return;\n }\n\n const trend = await analyzeTrend(history);\n res.json(trend);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze trend',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/health\n * Health check endpoint\n */\n app.get('/api/health', (_req: Request, res: Response) => {\n res.json({\n status: 'ok',\n timestamp: new Date().toISOString(),\n project: config.project.name,\n });\n });\n\n // Serve static frontend files\n const publicDir = join(__dirname, 'public');\n app.use(express.static(publicDir));\n\n // Fallback to index.html for SPA routing\n app.get('*', (_req: Request, res: Response) => {\n res.sendFile(join(publicDir, 'index.html'));\n });\n\n return app;\n}\n"],"mappings":";;;AAIA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,aAAW;AAClB,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,QAAAC,cAAY;;;ACDvB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MACA,SACA,YAChB;AACA,UAAM,OAAO;AAJG;AACA;AACA;AAGhB,SAAK,OAAO;AACZ,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAChD;AACF;AAKO,IAAM,cAAN,cAA0B,gBAAgB;AAAA,EAC/C,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,gBAAgB,OAAO;AACtC,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,0BAAN,cAAsC,gBAAgB;AAAA,EAC3D,YACE,SACgB,YACA,kBAChB;AACA,UAAM,SAAS,6BAA6B,EAAE,YAAY,iBAAiB,CAAC;AAH5D;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,wBAAN,cAAoC,gBAAgB;AAAA,EACzD,YAAY,YAAoB;AAC9B,UAAM,uBAAuB,UAAU,IAAI,sBAAsB,EAAE,WAAW,CAAC;AAC/E,SAAK,OAAO;AAAA,EACd;AACF;AAmCO,IAAM,kBAAN,cAA8B,gBAAgB;AAAA,EACnD,YAAY,SAAiCC,OAAc;AACzD,UAAM,SAAS,qBAAqB,EAAE,MAA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,CAAC;","names":["Command","chalk","readFileSync","fileURLToPath","dirname","join","path","join","path","path","join","Command","chalk","ora","join","path","dirname","dirname","Node","path","Node","Command","ora","join","chalk","Command","chalk","ora","Project","join","z","SeveritySchema","VerificationConfigSchema","path","join","Node","Node","path","relative","path","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","stat","Project","resolve","readFile","writeFile","stdout","Command","ora","chalk","Command","Command","chalk","Command","chalk","Command","chalk","Command","chalk","getTypeIcon","Command","chalk","ora","join","Command","ora","join","chalk","Command","chalk","join","Command","chalk","join","Command","Command","chalk","ora","join","hookCommand","Command","ora","join","chalk","execFile","promisify","execFileAsync","stdout","Command","chalk","ora","join","chalk","table","getStatusColor","truncate","join","join","Command","ora","chalk","join","Command","chalk","Command","chalk","Command","path","Project","chalk","Project","chalk","path","Command","Command","chalk","path","Command","path","chalk","Command","fileURLToPath","dirname","join","z","z","__dirname","dirname","fileURLToPath","packageJsonPath","join","Command","Command","Command","Command","chalk","ora","Command","ora","chalk","Command","chalk","join","dirname","fileURLToPath","dirname","fileURLToPath","join","Command","chalk","__dirname","dirname","fileURLToPath","join","readFileSync","Command","chalk"]}