@ipation/specbridge 1.0.4 → 1.0.6
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 +117 -113
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
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/index.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"],"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';\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);\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 ) {\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 );\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 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 { 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}\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('--fix', 'Attempt to auto-fix violations (not yet implemented)')\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 const 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 spinner.text = `Running ${level}-level verification...`;\n\n // Run verification\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n\n spinner.stop();\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n printResult(result, level);\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 Constraint,\n} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { selectVerifierForConstraint, type VerificationContext } from './verifiers/index.js';\nimport { glob, matchesPattern } from '../utils/glob.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\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 }\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 // Get or add source file\n let sourceFile = this.project.getSourceFile(filePath);\n if (!sourceFile) {\n try {\n sourceFile = this.project.addSourceFileAtPath(filePath);\n } catch {\n // Can't parse file, skip\n return violations;\n }\n }\n\n // Check each decision's constraints\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n // Check if file matches constraint scope\n if (!matchesPattern(filePath, constraint.scope, { cwd })) {\n continue;\n }\n\n // Check severity filter\n if (severityFilter && !severityFilter.includes(constraint.severity)) {\n continue;\n }\n\n // Check for exceptions\n if (this.isExcepted(filePath, constraint, cwd)) {\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 for (const file of files) {\n const violations = await this.verifyFile(file, decisions, severityFilter, cwd);\n onFileVerified(violations);\n }\n }\n\n /**\n * Check if file is excepted from constraint\n */\n private isExcepted(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\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 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 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 * Verifier exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './errors.js';\nexport * from './regex.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';\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};\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('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 * 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\n# Get list of staged TypeScript files\nSTAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\\\\.(ts|tsx)$')\n\nif [ -z \"$STAGED_FILES\" ]; then\n exit 0\nfi\n\necho \"Running SpecBridge verification...\"\n\n# Run specbridge verify on staged files\nnpx specbridge hook run --level commit --files \"$STAGED_FILES\"\n\nexit $?\n`;\n\nexport const hookCommand = new Command('hook')\n .description('Manage Git hooks for verification');\n\nhookCommand\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\nhookCommand\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 const files = options.files\n ? options.files.split(/[\\s,]+/).filter(f => f.length > 0)\n : undefined;\n\n if (!files || files.length === 0) {\n // No files to verify\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\nhookCommand\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 * 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 noRationale?: 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.noRationale !== true,\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"],"mappings":";;;AAIA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,aAAW;AAClB,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACDvB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MACA,SAChB;AACA,UAAM,OAAO;AAHG;AACA;AAGhB,SAAK,OAAO;AACZ,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAChD;AACF;AAKO,I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ChB,CAAC;","names":["Command","chalk","dirname","join","join","join","Command","chalk","ora","join","dirname","dirname","Node","Node","Command","ora","join","chalk","Command","chalk","ora","Project","join","z","SeveritySchema","VerificationConfigSchema","join","Node","Node","Project","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","Command","ora","join","chalk","Command","chalk","ora","join","chalk","table","getStatusColor","truncate","Command","ora","join","chalk","Command","chalk","Command","chalk","dirname","join","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/index.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"],"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';\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);\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 ) {\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 );\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 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 { 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}\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('--fix', 'Attempt to auto-fix violations (not yet implemented)')\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 const 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 spinner.text = `Running ${level}-level verification...`;\n\n // Run verification\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n\n spinner.stop();\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n printResult(result, level);\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 Constraint,\n} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { selectVerifierForConstraint, type VerificationContext } from './verifiers/index.js';\nimport { glob, matchesPattern } from '../utils/glob.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\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 }\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 // Get or add source file\n let sourceFile = this.project.getSourceFile(filePath);\n if (!sourceFile) {\n try {\n sourceFile = this.project.addSourceFileAtPath(filePath);\n } catch {\n // Can't parse file, skip\n return violations;\n }\n }\n\n // Check each decision's constraints\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n // Check if file matches constraint scope\n if (!matchesPattern(filePath, constraint.scope, { cwd })) {\n continue;\n }\n\n // Check severity filter\n if (severityFilter && !severityFilter.includes(constraint.severity)) {\n continue;\n }\n\n // Check for exceptions\n if (this.isExcepted(filePath, constraint, cwd)) {\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 for (const file of files) {\n const violations = await this.verifyFile(file, decisions, severityFilter, cwd);\n onFileVerified(violations);\n }\n }\n\n /**\n * Check if file is excepted from constraint\n */\n private isExcepted(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\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 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 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 * Verifier exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './errors.js';\nexport * from './regex.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';\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};\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('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 * 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\n# Get list of staged TypeScript files\nSTAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\\\\.(ts|tsx)$')\n\nif [ -z \"$STAGED_FILES\" ]; then\n exit 0\nfi\n\necho \"Running SpecBridge verification...\"\n\n# Run specbridge verify on staged files\nnpx specbridge hook run --level commit --files \"$STAGED_FILES\"\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 const files = options.files\n ? options.files.split(/[\\s,]+/).filter(f => f.length > 0)\n : undefined;\n\n if (!files || files.length === 0) {\n // No files to verify\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"],"mappings":";;;AAIA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,aAAW;AAClB,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,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,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","dirname","join","join","join","Command","chalk","ora","join","dirname","dirname","Node","Node","Command","ora","join","chalk","Command","chalk","ora","Project","join","z","SeveritySchema","VerificationConfigSchema","join","Node","Node","Project","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","Command","chalk","ora","join","chalk","table","getStatusColor","truncate","Command","ora","join","chalk","Command","chalk","Command","chalk","dirname","join","Command","chalk"]}
|