@ipation/specbridge 1.2.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli/index.ts","../src/core/errors/index.ts","../src/cli/commands/init.ts","../src/utils/fs.ts","../src/utils/yaml.ts","../src/core/schemas/config.schema.ts","../src/cli/commands/infer.ts","../src/inference/scanner.ts","../src/utils/glob.ts","../src/inference/analyzers/base.ts","../src/inference/analyzers/naming.ts","../src/inference/analyzers/imports.ts","../src/inference/analyzers/structure.ts","../src/inference/analyzers/errors.ts","../src/inference/analyzers/index.ts","../src/inference/engine.ts","../src/config/loader.ts","../src/cli/commands/verify.ts","../src/verification/engine.ts","../src/registry/loader.ts","../src/core/schemas/decision.schema.ts","../src/registry/registry.ts","../src/verification/verifiers/base.ts","../src/verification/verifiers/naming.ts","../src/verification/verifiers/imports.ts","../src/verification/verifiers/errors.ts","../src/verification/verifiers/regex.ts","../src/verification/verifiers/dependencies.ts","../src/verification/verifiers/complexity.ts","../src/verification/verifiers/security.ts","../src/verification/verifiers/api.ts","../src/verification/verifiers/index.ts","../src/verification/cache.ts","../src/verification/applicability.ts","../src/verification/autofix/engine.ts","../src/verification/incremental.ts","../src/cli/commands/decision/index.ts","../src/cli/commands/decision/list.ts","../src/cli/commands/decision/show.ts","../src/cli/commands/decision/validate.ts","../src/cli/commands/decision/create.ts","../src/cli/commands/hook.ts","../src/cli/commands/report.ts","../src/reporting/reporter.ts","../src/reporting/formats/console.ts","../src/reporting/formats/markdown.ts","../src/reporting/storage.ts","../src/reporting/drift.ts","../src/cli/commands/context.ts","../src/agent/context.generator.ts","../src/cli/commands/lsp.ts","../src/lsp/server.ts","../src/lsp/index.ts","../src/cli/commands/watch.ts","../src/cli/commands/mcp-server.ts","../src/mcp/server.ts","../src/cli/commands/prompt.ts","../src/agent/templates.ts","../src/cli/commands/analytics.ts","../src/analytics/engine.ts","../src/cli/commands/dashboard.ts","../src/dashboard/server.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * SpecBridge CLI Entry Point\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { formatError } from '../core/errors/index.js';\n\n// Import commands\nimport { initCommand } from './commands/init.js';\nimport { inferCommand } from './commands/infer.js';\nimport { verifyCommand } from './commands/verify.js';\nimport { decisionCommand } from './commands/decision/index.js';\nimport { hookCommand } from './commands/hook.js';\nimport { reportCommand } from './commands/report.js';\nimport { contextCommand } from './commands/context.js';\nimport { lspCommand } from './commands/lsp.js';\nimport { watchCommand } from './commands/watch.js';\nimport { mcpServerCommand } from './commands/mcp-server.js';\nimport { promptCommand } from './commands/prompt.js';\nimport { analyticsCommand } from './commands/analytics.js';\nimport { dashboardCommand } from './commands/dashboard.js';\n\n// Read version from package.json\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n// In development: src/cli/index.ts -> ../../package.json\n// In production: dist/cli.js -> ../package.json\nconst packageJsonPath = join(__dirname, '../package.json');\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n\nconst program = new Command();\n\nprogram\n .name('specbridge')\n .description('Architecture Decision Runtime - Transform architectural decisions into executable, verifiable constraints')\n .version(packageJson.version);\n\n// Register commands\nprogram.addCommand(initCommand);\nprogram.addCommand(inferCommand);\nprogram.addCommand(verifyCommand);\nprogram.addCommand(decisionCommand);\nprogram.addCommand(hookCommand);\nprogram.addCommand(reportCommand);\nprogram.addCommand(contextCommand);\nprogram.addCommand(lspCommand);\nprogram.addCommand(watchCommand);\nprogram.addCommand(mcpServerCommand);\nprogram.addCommand(promptCommand);\nprogram.addCommand(analyticsCommand);\nprogram.addCommand(dashboardCommand);\n\n// Global error handler\nprogram.exitOverride((err) => {\n if (err.code === 'commander.help' || err.code === 'commander.helpDisplayed') {\n process.exit(0);\n }\n if (err.code === 'commander.version') {\n process.exit(0);\n }\n console.error(chalk.red(formatError(err)));\n process.exit(1);\n});\n\n// Parse and execute\nprogram.parseAsync(process.argv).catch((error: Error) => {\n console.error(chalk.red(formatError(error)));\n process.exit(1);\n});\n","/**\n * Custom error types for SpecBridge\n */\n\n/**\n * Base error for SpecBridge\n */\nexport class SpecBridgeError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n public readonly suggestion?: string\n ) {\n super(message);\n this.name = 'SpecBridgeError';\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Configuration errors\n */\nexport class ConfigError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'CONFIG_ERROR', details);\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Decision validation errors\n */\nexport class DecisionValidationError extends SpecBridgeError {\n constructor(\n message: string,\n public readonly decisionId: string,\n public readonly validationErrors: string[]\n ) {\n super(message, 'DECISION_VALIDATION_ERROR', { decisionId, validationErrors });\n this.name = 'DecisionValidationError';\n }\n}\n\n/**\n * Decision not found\n */\nexport class DecisionNotFoundError extends SpecBridgeError {\n constructor(decisionId: string) {\n super(`Decision not found: ${decisionId}`, 'DECISION_NOT_FOUND', { decisionId });\n this.name = 'DecisionNotFoundError';\n }\n}\n\n/**\n * Registry errors\n */\nexport class RegistryError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'REGISTRY_ERROR', details);\n this.name = 'RegistryError';\n }\n}\n\n/**\n * Verification errors\n */\nexport class VerificationError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'VERIFICATION_ERROR', details);\n this.name = 'VerificationError';\n }\n}\n\n/**\n * Inference errors\n */\nexport class InferenceError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'INFERENCE_ERROR', details);\n this.name = 'InferenceError';\n }\n}\n\n/**\n * File system errors\n */\nexport class FileSystemError extends SpecBridgeError {\n constructor(message: string, public readonly path: string) {\n super(message, 'FILE_SYSTEM_ERROR', { path });\n this.name = 'FileSystemError';\n }\n}\n\n/**\n * Already initialized error\n */\nexport class AlreadyInitializedError extends SpecBridgeError {\n constructor(path: string) {\n super(`SpecBridge is already initialized at ${path}`, 'ALREADY_INITIALIZED', { path });\n this.name = 'AlreadyInitializedError';\n }\n}\n\n/**\n * Not initialized error\n */\nexport class NotInitializedError extends SpecBridgeError {\n constructor() {\n super(\n 'SpecBridge is not initialized. Run \"specbridge init\" first.',\n 'NOT_INITIALIZED',\n undefined,\n 'Run `specbridge init` in this directory to create .specbridge/'\n );\n this.name = 'NotInitializedError';\n }\n}\n\n/**\n * Verifier not found\n */\nexport class VerifierNotFoundError extends SpecBridgeError {\n constructor(verifierId: string) {\n super(`Verifier not found: ${verifierId}`, 'VERIFIER_NOT_FOUND', { verifierId });\n this.name = 'VerifierNotFoundError';\n }\n}\n\n/**\n * Analyzer not found\n */\nexport class AnalyzerNotFoundError extends SpecBridgeError {\n constructor(analyzerId: string) {\n super(`Analyzer not found: ${analyzerId}`, 'ANALYZER_NOT_FOUND', { analyzerId });\n this.name = 'AnalyzerNotFoundError';\n }\n}\n\n/**\n * Hook installation error\n */\nexport class HookError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'HOOK_ERROR', details);\n this.name = 'HookError';\n }\n}\n\n/**\n * Format error message for CLI output\n */\nexport function formatError(error: Error): string {\n if (error instanceof SpecBridgeError) {\n let message = `Error [${error.code}]: ${error.message}`;\n if (error.details) {\n const detailsStr = Object.entries(error.details)\n .filter(([key]) => key !== 'validationErrors')\n .map(([key, value]) => ` ${key}: ${value}`)\n .join('\\n');\n if (detailsStr) {\n message += `\\n${detailsStr}`;\n }\n }\n if (error instanceof DecisionValidationError && error.validationErrors.length > 0) {\n message += '\\nValidation errors:\\n' + error.validationErrors.map(e => ` - ${e}`).join('\\n');\n }\n if (error.suggestion) {\n message += `\\nSuggestion: ${error.suggestion}`;\n }\n return message;\n }\n return `Error: ${error.message}`;\n}\n","/**\n * Init command - Initialize SpecBridge in a project\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport {\n pathExists,\n ensureDir,\n writeTextFile,\n getSpecBridgeDir,\n getDecisionsDir,\n getVerifiersDir,\n getInferredDir,\n getReportsDir,\n getConfigPath,\n} from '../../utils/fs.js';\nimport { stringifyYaml } from '../../utils/yaml.js';\nimport { defaultConfig } from '../../core/schemas/config.schema.js';\nimport { AlreadyInitializedError } from '../../core/errors/index.js';\n\ninterface InitOptions {\n force?: boolean;\n name?: string;\n}\n\nexport const initCommand = new Command('init')\n .description('Initialize SpecBridge in the current project')\n .option('-f, --force', 'Overwrite existing configuration')\n .option('-n, --name <name>', 'Project name')\n .action(async (options: InitOptions) => {\n const cwd = process.cwd();\n const specbridgeDir = getSpecBridgeDir(cwd);\n\n // Check if already initialized\n if (!options.force && await pathExists(specbridgeDir)) {\n throw new AlreadyInitializedError(specbridgeDir);\n }\n\n const spinner = ora('Initializing SpecBridge...').start();\n\n try {\n // Create directory structure\n await ensureDir(specbridgeDir);\n await ensureDir(getDecisionsDir(cwd));\n await ensureDir(getVerifiersDir(cwd));\n await ensureDir(getInferredDir(cwd));\n await ensureDir(getReportsDir(cwd));\n\n // Determine project name\n const projectName = options.name || getProjectNameFromPath(cwd);\n\n // Create config file\n const config = {\n ...defaultConfig,\n project: {\n ...defaultConfig.project,\n name: projectName,\n },\n };\n\n const configContent = stringifyYaml(config);\n await writeTextFile(getConfigPath(cwd), configContent);\n\n // Create example decision\n const exampleDecision = createExampleDecision(projectName);\n await writeTextFile(\n join(getDecisionsDir(cwd), 'example.decision.yaml'),\n stringifyYaml(exampleDecision)\n );\n\n // Create .gitkeep files\n await writeTextFile(join(getVerifiersDir(cwd), '.gitkeep'), '');\n await writeTextFile(join(getInferredDir(cwd), '.gitkeep'), '');\n await writeTextFile(join(getReportsDir(cwd), '.gitkeep'), '');\n\n spinner.succeed('SpecBridge initialized successfully!');\n\n console.log('');\n console.log(chalk.green('Created:'));\n console.log(` ${chalk.dim('.specbridge/')}`);\n console.log(` ${chalk.dim('├──')} config.yaml`);\n console.log(` ${chalk.dim('├──')} decisions/`);\n console.log(` ${chalk.dim('│ └──')} example.decision.yaml`);\n console.log(` ${chalk.dim('├──')} verifiers/`);\n console.log(` ${chalk.dim('├──')} inferred/`);\n console.log(` ${chalk.dim('└──')} reports/`);\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(` 1. Edit ${chalk.bold('.specbridge/config.yaml')} to configure source paths`);\n console.log(` 2. Run ${chalk.bold('specbridge infer')} to detect patterns in your codebase`);\n console.log(` 3. Create decisions in ${chalk.bold('.specbridge/decisions/')}`);\n console.log(` 4. Run ${chalk.bold('specbridge verify')} to check compliance`);\n } catch (error) {\n spinner.fail('Failed to initialize SpecBridge');\n throw error;\n }\n });\n\n/**\n * Extract project name from directory path\n */\nfunction getProjectNameFromPath(dirPath: string): string {\n const parts = dirPath.split(/[/\\\\]/);\n return parts[parts.length - 1] || 'my-project';\n}\n\n/**\n * Create an example decision for new projects\n */\nfunction createExampleDecision(projectName: string) {\n return {\n kind: 'Decision',\n metadata: {\n id: 'example-001',\n title: 'Example Decision - Error Handling Convention',\n status: 'draft',\n owners: ['team'],\n tags: ['example', 'error-handling'],\n },\n decision: {\n summary: 'All errors should be handled using a consistent error class hierarchy.',\n rationale: `Consistent error handling improves debugging and makes the codebase more maintainable.\nThis is an example decision to demonstrate SpecBridge functionality.`,\n context: `This decision was auto-generated when initializing SpecBridge for ${projectName}.\nReplace or delete this file and create your own architectural decisions.`,\n },\n constraints: [\n {\n id: 'custom-errors',\n type: 'convention',\n rule: 'Custom error classes should extend a base AppError class',\n severity: 'medium',\n scope: 'src/**/*.ts',\n },\n {\n id: 'error-logging',\n type: 'guideline',\n rule: 'Errors should be logged with appropriate context before being thrown or handled',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n ],\n };\n}\n","/**\n * File system utilities\n */\nimport { readFile, writeFile, mkdir, access, readdir, stat } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { constants } from 'node:fs';\n\n/**\n * Check if a path exists\n */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a path is a directory\n */\nexport async function isDirectory(path: string): Promise<boolean> {\n try {\n const stats = await stat(path);\n return stats.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a directory exists\n */\nexport async function ensureDir(path: string): Promise<void> {\n await mkdir(path, { recursive: true });\n}\n\n/**\n * Read a text file\n */\nexport async function readTextFile(path: string): Promise<string> {\n return readFile(path, 'utf-8');\n}\n\n/**\n * Write a text file, creating directories as needed\n */\nexport async function writeTextFile(path: string, content: string): Promise<void> {\n await ensureDir(dirname(path));\n await writeFile(path, content, 'utf-8');\n}\n\n/**\n * Read all files in a directory matching a pattern\n */\nexport async function readFilesInDir(\n dirPath: string,\n filter?: (filename: string) => boolean\n): Promise<string[]> {\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n const files = entries\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name);\n\n if (filter) {\n return files.filter(filter);\n }\n return files;\n } catch {\n return [];\n }\n}\n\n/**\n * Get the .specbridge directory path\n */\nexport function getSpecBridgeDir(basePath: string = process.cwd()): string {\n return join(basePath, '.specbridge');\n}\n\n/**\n * Get the decisions directory path\n */\nexport function getDecisionsDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'decisions');\n}\n\n/**\n * Get the verifiers directory path\n */\nexport function getVerifiersDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'verifiers');\n}\n\n/**\n * Get the inferred patterns directory path\n */\nexport function getInferredDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'inferred');\n}\n\n/**\n * Get the reports directory path\n */\nexport function getReportsDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'reports');\n}\n\n/**\n * Get the config file path\n */\nexport function getConfigPath(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'config.yaml');\n}\n","/**\n * YAML utilities with comment preservation\n */\nimport { parse, stringify, Document, parseDocument } from 'yaml';\n\n/**\n * Parse YAML string to object\n */\nexport function parseYaml<T = unknown>(content: string): T {\n return parse(content) as T;\n}\n\n/**\n * Stringify object to YAML with nice formatting\n */\nexport function stringifyYaml(data: unknown, options?: { indent?: number }): string {\n return stringify(data, {\n indent: options?.indent ?? 2,\n lineWidth: 100,\n minContentWidth: 20,\n });\n}\n\n/**\n * Parse YAML preserving document structure (for editing)\n */\nexport function parseYamlDocument(content: string): Document {\n return parseDocument(content);\n}\n\n/**\n * Update YAML document preserving comments\n */\nexport function updateYamlDocument(doc: Document, path: string[], value: unknown): void {\n let current: unknown = doc.contents;\n\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n if (key && current && typeof current === 'object' && 'get' in current) {\n current = (current as { get: (key: string) => unknown }).get(key);\n }\n }\n\n const lastKey = path[path.length - 1];\n if (lastKey && current && typeof current === 'object' && 'set' in current) {\n (current as { set: (key: string, value: unknown) => void }).set(lastKey, value);\n }\n}\n","/**\n * Zod schemas for SpecBridge configuration\n */\nimport { z } from 'zod';\n\n// Severity for level config\nconst SeveritySchema = z.enum(['critical', 'high', 'medium', 'low']);\n\n// Level configuration\nconst LevelConfigSchema = z.object({\n timeout: z.number().positive().optional(),\n severity: z.array(SeveritySchema).optional(),\n});\n\n// Project configuration\nconst ProjectConfigSchema = z.object({\n name: z.string().min(1),\n sourceRoots: z.array(z.string().min(1)).min(1),\n exclude: z.array(z.string()).optional(),\n});\n\n// Inference configuration\nconst InferenceConfigSchema = z.object({\n minConfidence: z.number().min(0).max(100).optional(),\n analyzers: z.array(z.string()).optional(),\n});\n\n// Verification configuration\nconst VerificationConfigSchema = z.object({\n levels: z.object({\n commit: LevelConfigSchema.optional(),\n pr: LevelConfigSchema.optional(),\n full: LevelConfigSchema.optional(),\n }).optional(),\n});\n\n// Agent configuration\nconst AgentConfigSchema = z.object({\n format: z.enum(['markdown', 'json', 'mcp']).optional(),\n includeRationale: z.boolean().optional(),\n});\n\n// Complete SpecBridge configuration\nexport const SpecBridgeConfigSchema = z.object({\n version: z.string().regex(/^\\d+\\.\\d+$/, 'Version must be in format X.Y'),\n project: ProjectConfigSchema,\n inference: InferenceConfigSchema.optional(),\n verification: VerificationConfigSchema.optional(),\n agent: AgentConfigSchema.optional(),\n});\n\nexport type SpecBridgeConfigType = z.infer<typeof SpecBridgeConfigSchema>;\n\n/**\n * Validate configuration\n */\nexport function validateConfig(data: unknown): { success: true; data: SpecBridgeConfigType } | { success: false; errors: z.ZodError } {\n const result = SpecBridgeConfigSchema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, errors: result.error };\n}\n\n/**\n * Default configuration\n */\nexport const defaultConfig: SpecBridgeConfigType = {\n version: '1.0',\n project: {\n name: 'my-project',\n sourceRoots: ['src/**/*.ts', 'src/**/*.tsx'],\n exclude: ['**/*.test.ts', '**/*.spec.ts', '**/node_modules/**', '**/dist/**'],\n },\n inference: {\n minConfidence: 70,\n analyzers: ['naming', 'structure', 'imports', 'errors'],\n },\n verification: {\n levels: {\n commit: {\n timeout: 5000,\n severity: ['critical'],\n },\n pr: {\n timeout: 60000,\n severity: ['critical', 'high'],\n },\n full: {\n timeout: 300000,\n severity: ['critical', 'high', 'medium', 'low'],\n },\n },\n },\n agent: {\n format: 'markdown',\n includeRationale: true,\n },\n};\n","/**\n * Infer command - Detect patterns in the codebase\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { createInferenceEngine, getAnalyzerIds } from '../../inference/index.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { writeTextFile, getInferredDir, pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { Pattern } from '../../core/types/index.js';\n\ninterface InferOptions {\n output?: string;\n minConfidence?: string;\n analyzers?: string;\n json?: boolean;\n save?: boolean;\n}\n\nexport const inferCommand = new Command('infer')\n .description('Analyze codebase and detect patterns')\n .option('-o, --output <file>', 'Output file path')\n .option('-c, --min-confidence <number>', 'Minimum confidence threshold (0-100)', '50')\n .option('-a, --analyzers <list>', 'Comma-separated list of analyzers to run')\n .option('--json', 'Output as JSON')\n .option('--save', 'Save results to .specbridge/inferred/')\n .action(async (options: InferOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Loading configuration...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Parse options\n const minConfidence = parseInt(options.minConfidence || '50', 10);\n const analyzerList = options.analyzers\n ? options.analyzers.split(',').map(a => a.trim())\n : config.inference?.analyzers || getAnalyzerIds();\n\n spinner.text = `Scanning codebase (analyzers: ${analyzerList.join(', ')})...`;\n\n // Run inference\n const engine = createInferenceEngine();\n const result = await engine.infer({\n analyzers: analyzerList,\n minConfidence,\n sourceRoots: config.project.sourceRoots,\n exclude: config.project.exclude,\n cwd,\n });\n\n spinner.succeed(`Scanned ${result.filesScanned} files in ${result.duration}ms`);\n\n // Save results first (even if empty) if requested\n if (options.save || options.output) {\n const outputPath = options.output || join(getInferredDir(cwd), 'patterns.json');\n await writeTextFile(outputPath, JSON.stringify(result, null, 2));\n console.log(chalk.green(`\\nResults saved to: ${outputPath}`));\n }\n\n if (result.patterns.length === 0) {\n console.log(chalk.yellow('\\nNo patterns detected above confidence threshold.'));\n console.log(chalk.dim(`Try lowering --min-confidence (current: ${minConfidence})`));\n return;\n }\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n printPatterns(result.patterns);\n }\n\n // Show next steps\n if (!options.json) {\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(' Review detected patterns and create decisions for important ones.');\n console.log(` Use ${chalk.bold('specbridge decision create <id>')} to create a new decision.`);\n }\n } catch (error) {\n spinner.fail('Inference failed');\n throw error;\n }\n });\n\nfunction printPatterns(patterns: Pattern[]): void {\n console.log(chalk.bold(`\\nDetected ${patterns.length} pattern(s):\\n`));\n\n for (const pattern of patterns) {\n const confidenceColor = pattern.confidence >= 80\n ? chalk.green\n : pattern.confidence >= 60\n ? chalk.yellow\n : chalk.dim;\n\n console.log(chalk.bold(`${pattern.name}`));\n console.log(chalk.dim(` ID: ${pattern.id}`));\n console.log(` ${pattern.description}`);\n console.log(` Confidence: ${confidenceColor(`${pattern.confidence}%`)} (${pattern.occurrences} occurrences)`);\n console.log(chalk.dim(` Analyzer: ${pattern.analyzer}`));\n\n if (pattern.examples.length > 0) {\n console.log(chalk.dim(' Examples:'));\n for (const example of pattern.examples.slice(0, 2)) {\n console.log(chalk.dim(` - ${example.file}:${example.line}`));\n console.log(chalk.dim(` ${example.snippet}`));\n }\n }\n\n if (pattern.suggestedConstraint) {\n const typeColor =\n pattern.suggestedConstraint.type === 'invariant' ? chalk.red :\n pattern.suggestedConstraint.type === 'convention' ? chalk.yellow :\n chalk.green;\n\n console.log(chalk.cyan(' Suggested constraint:'));\n console.log(` Type: ${typeColor(pattern.suggestedConstraint.type || 'convention')}`);\n console.log(` Rule: ${pattern.suggestedConstraint.rule}`);\n }\n\n console.log('');\n }\n}\n","/**\n * Codebase scanner using ts-morph\n */\nimport { Project, SourceFile, Node, SyntaxKind } from 'ts-morph';\nimport { glob } from '../utils/glob.js';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\n\nexport interface ScanResult {\n files: ScannedFile[];\n totalFiles: number;\n totalLines: number;\n}\n\nexport interface ScannedFile {\n path: string;\n sourceFile: SourceFile;\n lines: number;\n}\n\nexport interface ScanOptions {\n sourceRoots: string[];\n exclude?: string[];\n cwd?: string;\n}\n\n/**\n * Scanner class for analyzing TypeScript/JavaScript codebases\n */\nexport class CodeScanner {\n private project: Project;\n private scannedFiles: Map<string, ScannedFile> = new Map();\n\n constructor() {\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n /**\n * Scan files matching the given patterns\n */\n async scan(options: ScanOptions): Promise<ScanResult> {\n const { sourceRoots, exclude = [], cwd = process.cwd() } = options;\n\n // Find files matching patterns\n const files = await glob(sourceRoots, {\n cwd,\n ignore: exclude,\n absolute: true,\n });\n\n // Add files to project\n for (const filePath of files) {\n try {\n const sourceFile = this.project.addSourceFileAtPath(filePath);\n const lines = sourceFile.getEndLineNumber();\n\n this.scannedFiles.set(filePath, {\n path: filePath,\n sourceFile,\n lines,\n });\n } catch {\n // Skip files that can't be parsed\n }\n }\n\n const scannedArray = Array.from(this.scannedFiles.values());\n const totalLines = scannedArray.reduce((sum, f) => sum + f.lines, 0);\n\n return {\n files: scannedArray,\n totalFiles: scannedArray.length,\n totalLines,\n };\n }\n\n /**\n * Get all scanned files\n */\n getFiles(): ScannedFile[] {\n return Array.from(this.scannedFiles.values());\n }\n\n /**\n * Get a specific file\n */\n getFile(path: string): ScannedFile | undefined {\n return this.scannedFiles.get(path);\n }\n\n /**\n * Get project instance for advanced analysis\n */\n getProject(): Project {\n return this.project;\n }\n\n /**\n * Find all classes in scanned files\n */\n findClasses(): { file: string; name: string; line: number }[] {\n const classes: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const classDecl of sourceFile.getClasses()) {\n const name = classDecl.getName();\n if (name) {\n classes.push({\n file: path,\n name,\n line: classDecl.getStartLineNumber(),\n });\n }\n }\n }\n\n return classes;\n }\n\n /**\n * Find all functions in scanned files\n */\n findFunctions(): { file: string; name: string; line: number; isExported: boolean }[] {\n const functions: { file: string; name: string; line: number; isExported: boolean }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n // Top-level functions\n for (const funcDecl of sourceFile.getFunctions()) {\n const name = funcDecl.getName();\n if (name) {\n functions.push({\n file: path,\n name,\n line: funcDecl.getStartLineNumber(),\n isExported: funcDecl.isExported(),\n });\n }\n }\n\n // Arrow functions assigned to variables\n for (const varDecl of sourceFile.getVariableDeclarations()) {\n const init = varDecl.getInitializer();\n if (init && Node.isArrowFunction(init)) {\n functions.push({\n file: path,\n name: varDecl.getName(),\n line: varDecl.getStartLineNumber(),\n isExported: varDecl.isExported(),\n });\n }\n }\n }\n\n return functions;\n }\n\n /**\n * Find all imports in scanned files\n */\n findImports(): { file: string; module: string; named: string[]; line: number }[] {\n const imports: { file: string; module: string; named: string[]; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const module = importDecl.getModuleSpecifierValue();\n const namedImports = importDecl\n .getNamedImports()\n .map((n) => n.getName());\n\n imports.push({\n file: path,\n module,\n named: namedImports,\n line: importDecl.getStartLineNumber(),\n });\n }\n }\n\n return imports;\n }\n\n /**\n * Find all interfaces in scanned files\n */\n findInterfaces(): { file: string; name: string; line: number }[] {\n const interfaces: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n interfaces.push({\n file: path,\n name: interfaceDecl.getName(),\n line: interfaceDecl.getStartLineNumber(),\n });\n }\n }\n\n return interfaces;\n }\n\n /**\n * Find all type aliases in scanned files\n */\n findTypeAliases(): { file: string; name: string; line: number }[] {\n const types: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n types.push({\n file: path,\n name: typeAlias.getName(),\n line: typeAlias.getStartLineNumber(),\n });\n }\n }\n\n return types;\n }\n\n /**\n * Find try-catch blocks in scanned files\n */\n findTryCatchBlocks(): { file: string; line: number; hasThrow: boolean }[] {\n const blocks: { file: string; line: number; hasThrow: boolean }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isTryStatement(node)) {\n const catchClause = node.getCatchClause();\n const hasThrow = catchClause\n ? catchClause.getDescendantsOfKind(SyntaxKind.ThrowStatement).length > 0\n : false;\n\n blocks.push({\n file: path,\n line: node.getStartLineNumber(),\n hasThrow,\n });\n }\n });\n }\n\n return blocks;\n }\n}\n\n/**\n * Create a scanner from config\n */\nexport function createScannerFromConfig(_config: SpecBridgeConfig): CodeScanner {\n return new CodeScanner();\n}\n","/**\n * Glob utilities for file matching\n */\nimport fg from 'fast-glob';\nimport { minimatch } from 'minimatch';\nimport { relative, isAbsolute } from 'node:path';\n\nexport interface GlobOptions {\n cwd?: string;\n ignore?: string[];\n absolute?: boolean;\n onlyFiles?: boolean;\n}\n\n/**\n * Find files matching glob patterns\n */\nexport async function glob(\n patterns: string | string[],\n options: GlobOptions = {}\n): Promise<string[]> {\n const {\n cwd = process.cwd(),\n ignore = [],\n absolute = false,\n onlyFiles = true,\n } = options;\n\n return fg(patterns, {\n cwd,\n ignore,\n absolute,\n onlyFiles,\n dot: false,\n });\n}\n\n/**\n * Normalize a file path to be relative to a base directory\n * Handles both absolute and relative paths, cross-platform\n */\nexport function normalizePath(filePath: string, basePath: string = process.cwd()): string {\n let resultPath: string;\n\n if (!isAbsolute(filePath)) {\n // Already relative, use as-is\n resultPath = filePath;\n } else {\n // Convert absolute to relative from basePath\n resultPath = relative(basePath, filePath);\n }\n\n // Ensure forward slashes (handle both Unix and Windows separators)\n return resultPath.replace(/\\\\/g, '/');\n}\n\n/**\n * Check if a file path matches a glob pattern\n */\nexport function matchesPattern(\n filePath: string,\n pattern: string,\n options: { cwd?: string } = {}\n): boolean {\n const cwd = options.cwd || process.cwd();\n const normalizedPath = normalizePath(filePath, cwd);\n\n return minimatch(normalizedPath, pattern, { matchBase: true });\n}\n\n/**\n * Check if a file path matches any of the given patterns\n */\nexport function matchesAnyPattern(\n filePath: string,\n patterns: string[],\n options: { cwd?: string } = {}\n): boolean {\n return patterns.some((pattern) => matchesPattern(filePath, pattern, options));\n}\n\n// Re-export minimatch for advanced usage\nexport { minimatch };\n","/**\n * Base analyzer interface\n */\nimport type { Pattern, PatternExample } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\n\n/**\n * Analyzer interface - all analyzers must implement this\n */\nexport interface Analyzer {\n /**\n * Unique identifier for this analyzer\n */\n readonly id: string;\n\n /**\n * Human-readable name\n */\n readonly name: string;\n\n /**\n * Description of what this analyzer detects\n */\n readonly description: string;\n\n /**\n * Analyze the codebase and return detected patterns\n */\n analyze(scanner: CodeScanner): Promise<Pattern[]>;\n}\n\n/**\n * Helper to create a pattern with consistent structure\n */\nexport function createPattern(\n analyzer: string,\n params: {\n id: string;\n name: string;\n description: string;\n confidence: number;\n occurrences: number;\n examples: PatternExample[];\n suggestedConstraint?: Pattern['suggestedConstraint'];\n }\n): Pattern {\n return {\n analyzer,\n ...params,\n };\n}\n\n/**\n * Calculate confidence based on occurrence ratio\n */\nexport function calculateConfidence(\n occurrences: number,\n total: number,\n minOccurrences: number = 3\n): number {\n if (occurrences < minOccurrences) {\n return 0;\n }\n\n const ratio = occurrences / total;\n // Scale from 50 (at minOccurrences) to 100 (at 100%)\n return Math.min(100, Math.round(50 + ratio * 50));\n}\n\n/**\n * Extract a code snippet around a line\n */\nexport function extractSnippet(\n content: string,\n line: number,\n contextLines: number = 1\n): string {\n const lines = content.split('\\n');\n const start = Math.max(0, line - 1 - contextLines);\n const end = Math.min(lines.length, line + contextLines);\n\n return lines.slice(start, end).join('\\n');\n}\n","/**\n * Naming convention analyzer\n */\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\ninterface NamingPattern {\n convention: string;\n regex: RegExp;\n description: string;\n}\n\nconst CLASS_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Classes use PascalCase' },\n];\n\nconst FUNCTION_PATTERNS: NamingPattern[] = [\n { convention: 'camelCase', regex: /^[a-z][a-zA-Z0-9]*$/, description: 'Functions use camelCase' },\n { convention: 'snake_case', regex: /^[a-z][a-z0-9_]*$/, description: 'Functions use snake_case' },\n];\n\nconst INTERFACE_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Interfaces use PascalCase' },\n { convention: 'IPrefixed', regex: /^I[A-Z][a-zA-Z0-9]*$/, description: 'Interfaces are prefixed with I' },\n];\n\nconst TYPE_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Types use PascalCase' },\n { convention: 'TSuffixed', regex: /^[A-Z][a-zA-Z0-9]*Type$/, description: 'Types are suffixed with Type' },\n];\n\nexport class NamingAnalyzer implements Analyzer {\n readonly id = 'naming';\n readonly name = 'Naming Convention Analyzer';\n readonly description = 'Detects naming conventions for classes, functions, interfaces, and types';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze class naming\n const classPattern = this.analyzeClassNaming(scanner);\n if (classPattern) patterns.push(classPattern);\n\n // Analyze function naming\n const functionPattern = this.analyzeFunctionNaming(scanner);\n if (functionPattern) patterns.push(functionPattern);\n\n // Analyze interface naming\n const interfacePattern = this.analyzeInterfaceNaming(scanner);\n if (interfacePattern) patterns.push(interfacePattern);\n\n // Analyze type naming\n const typePattern = this.analyzeTypeNaming(scanner);\n if (typePattern) patterns.push(typePattern);\n\n return patterns;\n }\n\n private analyzeClassNaming(scanner: CodeScanner): Pattern | null {\n const classes = scanner.findClasses();\n if (classes.length < 3) return null;\n\n const matches = this.findBestMatch(classes.map(c => c.name), CLASS_PATTERNS);\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-classes',\n name: 'Class Naming Convention',\n description: `Classes follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: classes.slice(0, 3).map(c => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Classes should use ${matches.convention} naming convention`,\n severity: 'medium',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeFunctionNaming(scanner: CodeScanner): Pattern | null {\n const functions = scanner.findFunctions();\n if (functions.length < 3) return null;\n\n const matches = this.findBestMatch(functions.map(f => f.name), FUNCTION_PATTERNS);\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-functions',\n name: 'Function Naming Convention',\n description: `Functions follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: functions.slice(0, 3).map(f => ({\n file: f.file,\n line: f.line,\n snippet: `function ${f.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Functions should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeInterfaceNaming(scanner: CodeScanner): Pattern | null {\n const interfaces = scanner.findInterfaces();\n if (interfaces.length < 3) return null;\n\n const matches = this.findBestMatch(interfaces.map(i => i.name), INTERFACE_PATTERNS);\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-interfaces',\n name: 'Interface Naming Convention',\n description: `Interfaces follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: interfaces.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `interface ${i.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Interfaces should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeTypeNaming(scanner: CodeScanner): Pattern | null {\n const types = scanner.findTypeAliases();\n if (types.length < 3) return null;\n\n const matches = this.findBestMatch(types.map(t => t.name), TYPE_PATTERNS);\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-types',\n name: 'Type Alias Naming Convention',\n description: `Type aliases follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: types.slice(0, 3).map(t => ({\n file: t.file,\n line: t.line,\n snippet: `type ${t.name}`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: `Type aliases should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private findBestMatch(\n names: string[],\n patterns: NamingPattern[]\n ): { convention: string; confidence: number; matchCount: number } | null {\n let bestMatch: { convention: string; matchCount: number } | null = null;\n\n for (const pattern of patterns) {\n const matchCount = names.filter(name => pattern.regex.test(name)).length;\n if (!bestMatch || matchCount > bestMatch.matchCount) {\n bestMatch = { convention: pattern.convention, matchCount };\n }\n }\n\n if (!bestMatch || bestMatch.matchCount < 3) return null;\n\n const confidence = calculateConfidence(bestMatch.matchCount, names.length);\n if (confidence < 50) return null;\n\n return {\n convention: bestMatch.convention,\n confidence,\n matchCount: bestMatch.matchCount,\n };\n }\n}\n","/**\n * Import pattern analyzer\n */\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class ImportsAnalyzer implements Analyzer {\n readonly id = 'imports';\n readonly name = 'Import Pattern Analyzer';\n readonly description = 'Detects import organization patterns and module usage conventions';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze barrel imports\n const barrelPattern = this.analyzeBarrelImports(scanner);\n if (barrelPattern) patterns.push(barrelPattern);\n\n // Analyze relative vs absolute imports\n const relativePattern = this.analyzeRelativeImports(scanner);\n if (relativePattern) patterns.push(relativePattern);\n\n // Analyze commonly used modules\n const modulePatterns = this.analyzeCommonModules(scanner);\n patterns.push(...modulePatterns);\n\n return patterns;\n }\n\n private analyzeBarrelImports(scanner: CodeScanner): Pattern | null {\n const imports = scanner.findImports();\n const barrelImports = imports.filter(i => {\n const modulePath = i.module;\n return modulePath.startsWith('.') && !modulePath.includes('.js') && !modulePath.includes('.ts');\n });\n\n // Check for index imports\n const indexImports = barrelImports.filter(i => {\n return i.module.endsWith('/index') || !i.module.includes('/');\n });\n\n if (indexImports.length < 3) return null;\n\n const confidence = calculateConfidence(indexImports.length, barrelImports.length);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-barrel',\n name: 'Barrel Import Pattern',\n description: 'Modules are imported through barrel (index) files',\n confidence,\n occurrences: indexImports.length,\n examples: indexImports.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 3).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: 'Import from barrel (index) files rather than individual modules',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeRelativeImports(scanner: CodeScanner): Pattern | null {\n const imports = scanner.findImports();\n const relativeImports = imports.filter(i => i.module.startsWith('.'));\n const absoluteImports = imports.filter(i => !i.module.startsWith('.') && !i.module.startsWith('@'));\n const aliasImports = imports.filter(i => i.module.startsWith('@/') || i.module.startsWith('~'));\n\n // Determine dominant pattern\n const total = relativeImports.length + absoluteImports.length + aliasImports.length;\n if (total < 10) return null;\n\n if (aliasImports.length > relativeImports.length && aliasImports.length >= 5) {\n const confidence = calculateConfidence(aliasImports.length, total);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-alias',\n name: 'Path Alias Import Pattern',\n description: 'Imports use path aliases (@ or ~) instead of relative paths',\n confidence,\n occurrences: aliasImports.length,\n examples: aliasImports.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: 'Use path aliases instead of relative imports',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n if (relativeImports.length > aliasImports.length * 2 && relativeImports.length >= 5) {\n const confidence = calculateConfidence(relativeImports.length, total);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-relative',\n name: 'Relative Import Pattern',\n description: 'Imports use relative paths',\n confidence,\n occurrences: relativeImports.length,\n examples: relativeImports.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Use relative imports for local modules',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeCommonModules(scanner: CodeScanner): Pattern[] {\n const patterns: Pattern[] = [];\n const imports = scanner.findImports();\n\n // Count external module usage\n const moduleCounts = new Map<string, { count: number; examples: typeof imports }>();\n\n for (const imp of imports) {\n // Skip relative imports\n if (imp.module.startsWith('.')) continue;\n\n // Get the package name (handle scoped packages)\n const parts = imp.module.split('/');\n const packageName = imp.module.startsWith('@') && parts.length > 1\n ? `${parts[0]}/${parts[1]}`\n : parts[0];\n\n if (packageName) {\n const existing = moduleCounts.get(packageName) || { count: 0, examples: [] };\n existing.count++;\n existing.examples.push(imp);\n moduleCounts.set(packageName, existing);\n }\n }\n\n // Create patterns for commonly used modules\n for (const [packageName, data] of moduleCounts) {\n if (data.count >= 5) {\n const confidence = Math.min(100, 50 + data.count * 2);\n\n patterns.push(createPattern(this.id, {\n id: `imports-module-${packageName.replace(/[/@]/g, '-')}`,\n name: `${packageName} Usage`,\n description: `${packageName} is used across ${data.count} files`,\n confidence,\n occurrences: data.count,\n examples: data.examples.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ') || '...'} } from '${i.module}'`,\n })),\n }));\n }\n }\n\n return patterns;\n }\n}\n","/**\n * Code structure pattern analyzer\n */\nimport { basename, dirname } from 'node:path';\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner, ScannedFile } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class StructureAnalyzer implements Analyzer {\n readonly id = 'structure';\n readonly name = 'Code Structure Analyzer';\n readonly description = 'Detects file organization and directory structure patterns';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n const files = scanner.getFiles();\n\n // Analyze directory conventions\n const dirPatterns = this.analyzeDirectoryConventions(files);\n patterns.push(...dirPatterns);\n\n // Analyze file naming conventions\n const filePatterns = this.analyzeFileNaming(files);\n patterns.push(...filePatterns);\n\n // Analyze colocation patterns\n const colocationPattern = this.analyzeColocation(files);\n if (colocationPattern) patterns.push(colocationPattern);\n\n return patterns;\n }\n\n private analyzeDirectoryConventions(files: ScannedFile[]): Pattern[] {\n const patterns: Pattern[] = [];\n const dirCounts = new Map<string, number>();\n\n // Count files per directory name\n for (const file of files) {\n const dir = basename(dirname(file.path));\n dirCounts.set(dir, (dirCounts.get(dir) || 0) + 1);\n }\n\n // Check for common directory structures\n const commonDirs = [\n { name: 'components', description: 'UI components are organized in a components directory' },\n { name: 'hooks', description: 'Custom hooks are organized in a hooks directory' },\n { name: 'utils', description: 'Utility functions are organized in a utils directory' },\n { name: 'services', description: 'Service modules are organized in a services directory' },\n { name: 'types', description: 'Type definitions are organized in a types directory' },\n { name: 'api', description: 'API modules are organized in an api directory' },\n { name: 'lib', description: 'Library code is organized in a lib directory' },\n { name: 'core', description: 'Core modules are organized in a core directory' },\n ];\n\n for (const { name, description } of commonDirs) {\n const count = dirCounts.get(name);\n if (count && count >= 3) {\n const exampleFiles = files\n .filter(f => basename(dirname(f.path)) === name)\n .slice(0, 3);\n\n patterns.push(createPattern(this.id, {\n id: `structure-dir-${name}`,\n name: `${name}/ Directory Convention`,\n description,\n confidence: Math.min(100, 60 + count * 5),\n occurrences: count,\n examples: exampleFiles.map(f => ({\n file: f.path,\n line: 1,\n snippet: basename(f.path),\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `${name.charAt(0).toUpperCase() + name.slice(1)} should be placed in the ${name}/ directory`,\n severity: 'low',\n scope: `src/**/${name}/**/*.ts`,\n },\n }));\n }\n }\n\n return patterns;\n }\n\n private analyzeFileNaming(files: ScannedFile[]): Pattern[] {\n const patterns: Pattern[] = [];\n\n // Check for suffix patterns\n const suffixPatterns: { suffix: string; pattern: RegExp; description: string }[] = [\n { suffix: '.test.ts', pattern: /\\.test\\.ts$/, description: 'Test files use .test.ts suffix' },\n { suffix: '.spec.ts', pattern: /\\.spec\\.ts$/, description: 'Test files use .spec.ts suffix' },\n { suffix: '.types.ts', pattern: /\\.types\\.ts$/, description: 'Type definition files use .types.ts suffix' },\n { suffix: '.utils.ts', pattern: /\\.utils\\.ts$/, description: 'Utility files use .utils.ts suffix' },\n { suffix: '.service.ts', pattern: /\\.service\\.ts$/, description: 'Service files use .service.ts suffix' },\n { suffix: '.controller.ts', pattern: /\\.controller\\.ts$/, description: 'Controller files use .controller.ts suffix' },\n { suffix: '.model.ts', pattern: /\\.model\\.ts$/, description: 'Model files use .model.ts suffix' },\n { suffix: '.schema.ts', pattern: /\\.schema\\.ts$/, description: 'Schema files use .schema.ts suffix' },\n ];\n\n for (const { suffix, pattern, description } of suffixPatterns) {\n const matchingFiles = files.filter(f => pattern.test(f.path));\n\n if (matchingFiles.length >= 3) {\n const confidence = Math.min(100, 60 + matchingFiles.length * 3);\n\n patterns.push(createPattern(this.id, {\n id: `structure-suffix-${suffix.replace(/\\./g, '-')}`,\n name: `${suffix} File Naming`,\n description,\n confidence,\n occurrences: matchingFiles.length,\n examples: matchingFiles.slice(0, 3).map(f => ({\n file: f.path,\n line: 1,\n snippet: basename(f.path),\n })),\n }));\n }\n }\n\n return patterns;\n }\n\n private analyzeColocation(files: ScannedFile[]): Pattern | null {\n // Check if test files are colocated with source files\n const testFiles = files.filter(f => /\\.(test|spec)\\.tsx?$/.test(f.path));\n const sourceFiles = files.filter(f => !/\\.(test|spec)\\.tsx?$/.test(f.path));\n\n if (testFiles.length < 3) return null;\n\n let colocatedCount = 0;\n const colocatedExamples: { file: string; line: number; snippet: string }[] = [];\n\n for (const testFile of testFiles) {\n const testDir = dirname(testFile.path);\n const testName = basename(testFile.path).replace(/\\.(test|spec)\\.tsx?$/, '');\n\n // Check if corresponding source file is in same directory\n const hasColocatedSource = sourceFiles.some(\n s => dirname(s.path) === testDir && basename(s.path).startsWith(testName)\n );\n\n if (hasColocatedSource) {\n colocatedCount++;\n if (colocatedExamples.length < 3) {\n colocatedExamples.push({\n file: testFile.path,\n line: 1,\n snippet: basename(testFile.path),\n });\n }\n }\n }\n\n const confidence = calculateConfidence(colocatedCount, testFiles.length);\n if (confidence < 60) return null;\n\n return createPattern(this.id, {\n id: 'structure-colocation',\n name: 'Test Colocation Pattern',\n description: 'Test files are colocated with their source files',\n confidence,\n occurrences: colocatedCount,\n examples: colocatedExamples,\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Test files should be colocated with their source files',\n severity: 'low',\n scope: 'src/**/*.test.ts',\n },\n });\n }\n}\n","/**\n * Error handling pattern analyzer\n */\nimport { Node } from 'ts-morph';\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class ErrorsAnalyzer implements Analyzer {\n readonly id = 'errors';\n readonly name = 'Error Handling Analyzer';\n readonly description = 'Detects error handling patterns and custom error class usage';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze custom error classes\n const errorClassPattern = this.analyzeCustomErrorClasses(scanner);\n if (errorClassPattern) patterns.push(errorClassPattern);\n\n // Analyze try-catch patterns\n const tryCatchPattern = this.analyzeTryCatchPatterns(scanner);\n if (tryCatchPattern) patterns.push(tryCatchPattern);\n\n // Analyze error throwing patterns\n const throwPattern = this.analyzeThrowPatterns(scanner);\n if (throwPattern) patterns.push(throwPattern);\n\n return patterns;\n }\n\n private analyzeCustomErrorClasses(scanner: CodeScanner): Pattern | null {\n const classes = scanner.findClasses();\n const errorClasses = classes.filter(c =>\n c.name.endsWith('Error') || c.name.endsWith('Exception')\n );\n\n if (errorClasses.length < 2) return null;\n\n // Check if they extend a common base\n const files = scanner.getFiles();\n const baseCount: Map<string, number> = new Map();\n\n for (const errorClass of errorClasses) {\n const file = files.find(f => f.path === errorClass.file);\n if (!file) continue;\n\n const classDecl = file.sourceFile.getClass(errorClass.name);\n if (!classDecl) continue;\n\n const extendClause = classDecl.getExtends();\n if (extendClause) {\n const baseName = extendClause.getText();\n if (baseName !== 'Error' && baseName.endsWith('Error')) {\n baseCount.set(baseName, (baseCount.get(baseName) || 0) + 1);\n }\n }\n }\n\n // Find the custom base with the most extending classes\n let customBaseName: string | null = null;\n let maxCount = 0;\n for (const [baseName, count] of baseCount.entries()) {\n if (count > maxCount) {\n maxCount = count;\n customBaseName = baseName;\n }\n }\n\n // Check for custom base pattern (requires >= 3 extending the same custom base)\n if (maxCount >= 3 && customBaseName) {\n const confidence = calculateConfidence(maxCount, errorClasses.length);\n\n return createPattern(this.id, {\n id: 'errors-custom-base',\n name: 'Custom Error Base Class',\n description: `Custom errors extend a common base class (${customBaseName})`,\n confidence,\n occurrences: maxCount,\n examples: errorClasses.slice(0, 3).map(c => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name} extends ${customBaseName}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Custom error classes should extend ${customBaseName}`,\n severity: 'medium',\n scope: 'src/**/*.ts',\n verifier: 'errors',\n },\n });\n }\n\n // Fall back to generic custom error classes pattern (requires >= 3 error classes)\n if (errorClasses.length >= 3) {\n const confidence = Math.min(100, 50 + errorClasses.length * 5);\n\n return createPattern(this.id, {\n id: 'errors-custom-classes',\n name: 'Custom Error Classes',\n description: 'Custom error classes are used for domain-specific errors',\n confidence,\n occurrences: errorClasses.length,\n examples: errorClasses.slice(0, 3).map(c => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name}`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Use custom error classes for domain-specific errors',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeTryCatchPatterns(scanner: CodeScanner): Pattern | null {\n const tryCatchBlocks = scanner.findTryCatchBlocks();\n\n if (tryCatchBlocks.length < 3) return null;\n\n // Check how many rethrow vs swallow\n const rethrowCount = tryCatchBlocks.filter(b => b.hasThrow).length;\n const swallowCount = tryCatchBlocks.length - rethrowCount;\n\n if (rethrowCount >= 3 && rethrowCount > swallowCount) {\n const confidence = calculateConfidence(rethrowCount, tryCatchBlocks.length);\n\n return createPattern(this.id, {\n id: 'errors-rethrow',\n name: 'Error Rethrow Pattern',\n description: 'Caught errors are typically rethrown after handling',\n confidence,\n occurrences: rethrowCount,\n examples: tryCatchBlocks\n .filter(b => b.hasThrow)\n .slice(0, 3)\n .map(b => ({\n file: b.file,\n line: b.line,\n snippet: 'try { ... } catch (e) { ... throw ... }',\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Caught errors should be rethrown or wrapped after handling',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeThrowPatterns(scanner: CodeScanner): Pattern | null {\n const files = scanner.getFiles();\n let throwNewError = 0;\n let throwCustom = 0;\n const examples: { file: string; line: number; snippet: string }[] = [];\n\n for (const { path, sourceFile } of files) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isThrowStatement(node)) {\n const expression = node.getExpression();\n if (expression) {\n const text = expression.getText();\n if (text.startsWith('new Error(')) {\n throwNewError++;\n } else if (text.startsWith('new ') && text.includes('Error')) {\n throwCustom++;\n if (examples.length < 3) {\n const snippet = text.length > 50 ? text.slice(0, 50) + '...' : text;\n examples.push({\n file: path,\n line: node.getStartLineNumber(),\n snippet: `throw ${snippet}`,\n });\n }\n }\n }\n }\n });\n }\n\n if (throwCustom >= 3 && throwCustom > throwNewError) {\n const confidence = calculateConfidence(throwCustom, throwCustom + throwNewError);\n\n return createPattern(this.id, {\n id: 'errors-throw-custom',\n name: 'Custom Error Throwing',\n description: 'Custom error classes are thrown instead of generic Error',\n confidence,\n occurrences: throwCustom,\n examples,\n suggestedConstraint: {\n type: 'convention',\n rule: 'Throw custom error classes instead of generic Error',\n severity: 'medium',\n scope: 'src/**/*.ts',\n verifier: 'errors',\n },\n });\n }\n\n return null;\n }\n}\n","/**\n * Analyzer exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './structure.js';\nexport * from './errors.js';\n\nimport type { Analyzer } from './base.js';\nimport { NamingAnalyzer } from './naming.js';\nimport { ImportsAnalyzer } from './imports.js';\nimport { StructureAnalyzer } from './structure.js';\nimport { ErrorsAnalyzer } from './errors.js';\n\n/**\n * Built-in analyzers registry\n */\nexport const builtinAnalyzers: Record<string, () => Analyzer> = {\n naming: () => new NamingAnalyzer(),\n imports: () => new ImportsAnalyzer(),\n structure: () => new StructureAnalyzer(),\n errors: () => new ErrorsAnalyzer(),\n};\n\n/**\n * Get analyzer by ID\n */\nexport function getAnalyzer(id: string): Analyzer | null {\n const factory = builtinAnalyzers[id];\n return factory ? factory() : null;\n}\n\n/**\n * Get all analyzer IDs\n */\nexport function getAnalyzerIds(): string[] {\n return Object.keys(builtinAnalyzers);\n}\n","/**\n * Inference Engine - Orchestrates pattern detection\n */\nimport type { Pattern, InferenceResult, SpecBridgeConfig } from '../core/types/index.js';\nimport { AnalyzerNotFoundError } from '../core/errors/index.js';\nimport { CodeScanner } from './scanner.js';\nimport { getAnalyzer, getAnalyzerIds, type Analyzer } from './analyzers/index.js';\n\nexport interface InferenceOptions {\n analyzers?: string[];\n minConfidence?: number;\n sourceRoots?: string[];\n exclude?: string[];\n cwd?: string;\n}\n\n/**\n * Inference Engine class\n */\nexport class InferenceEngine {\n private scanner: CodeScanner;\n private analyzers: Analyzer[] = [];\n\n constructor() {\n this.scanner = new CodeScanner();\n }\n\n /**\n * Configure analyzers to use\n */\n configureAnalyzers(analyzerIds: string[]): void {\n this.analyzers = [];\n\n for (const id of analyzerIds) {\n const analyzer = getAnalyzer(id);\n if (!analyzer) {\n throw new AnalyzerNotFoundError(id);\n }\n this.analyzers.push(analyzer);\n }\n }\n\n /**\n * Run inference on the codebase\n */\n async infer(options: InferenceOptions): Promise<InferenceResult> {\n const startTime = Date.now();\n\n const {\n analyzers: analyzerIds = getAnalyzerIds(),\n minConfidence = 50,\n sourceRoots = ['src/**/*.ts', 'src/**/*.tsx'],\n exclude = ['**/*.test.ts', '**/*.spec.ts', '**/node_modules/**', '**/dist/**'],\n cwd = process.cwd(),\n } = options;\n\n // Configure analyzers\n this.configureAnalyzers(analyzerIds);\n\n // Scan codebase\n const scanResult = await this.scanner.scan({\n sourceRoots,\n exclude,\n cwd,\n });\n\n if (scanResult.totalFiles === 0) {\n return {\n patterns: [],\n analyzersRun: analyzerIds,\n filesScanned: 0,\n duration: Date.now() - startTime,\n };\n }\n\n // Run all analyzers\n const allPatterns: Pattern[] = [];\n\n for (const analyzer of this.analyzers) {\n try {\n const patterns = await analyzer.analyze(this.scanner);\n allPatterns.push(...patterns);\n } catch (error) {\n // Log but don't fail on individual analyzer errors\n console.warn(`Analyzer ${analyzer.id} failed:`, error);\n }\n }\n\n // Filter by minimum confidence\n const filteredPatterns = allPatterns.filter(p => p.confidence >= minConfidence);\n\n // Sort by confidence (highest first)\n filteredPatterns.sort((a, b) => b.confidence - a.confidence);\n\n return {\n patterns: filteredPatterns,\n analyzersRun: analyzerIds,\n filesScanned: scanResult.totalFiles,\n duration: Date.now() - startTime,\n };\n }\n\n /**\n * Get scanner for direct access\n */\n getScanner(): CodeScanner {\n return this.scanner;\n }\n}\n\n/**\n * Create an inference engine from config\n */\nexport function createInferenceEngine(): InferenceEngine {\n return new InferenceEngine();\n}\n\n/**\n * Run inference with config\n */\nexport async function runInference(\n config: SpecBridgeConfig,\n options?: Partial<InferenceOptions>\n): Promise<InferenceResult> {\n const engine = createInferenceEngine();\n\n return engine.infer({\n analyzers: config.inference?.analyzers,\n minConfidence: config.inference?.minConfidence,\n sourceRoots: config.project.sourceRoots,\n exclude: config.project.exclude,\n ...options,\n });\n}\n","/**\n * Configuration loader\n */\nimport type { SpecBridgeConfig } from '../core/types/index.js';\nimport { validateConfig, defaultConfig } from '../core/schemas/config.schema.js';\nimport { ConfigError, NotInitializedError } from '../core/errors/index.js';\nimport { readTextFile, pathExists, getConfigPath, getSpecBridgeDir } from '../utils/fs.js';\nimport { parseYaml } from '../utils/yaml.js';\n\n/**\n * Load configuration from .specbridge/config.yaml\n */\nexport async function loadConfig(basePath: string = process.cwd()): Promise<SpecBridgeConfig> {\n const specbridgeDir = getSpecBridgeDir(basePath);\n const configPath = getConfigPath(basePath);\n\n // Check if specbridge is initialized\n if (!await pathExists(specbridgeDir)) {\n throw new NotInitializedError();\n }\n\n // Check if config file exists\n if (!await pathExists(configPath)) {\n // Return default config if no config file\n return defaultConfig;\n }\n\n // Load and parse config\n const content = await readTextFile(configPath);\n const parsed = parseYaml(content);\n\n // Validate config\n const result = validateConfig(parsed);\n if (!result.success) {\n const errors = result.errors.errors.map(e => `${e.path.join('.')}: ${e.message}`);\n throw new ConfigError(`Invalid configuration in ${configPath}`, { errors });\n }\n\n return result.data as SpecBridgeConfig;\n}\n\n/**\n * Merge partial config with defaults\n */\nexport function mergeWithDefaults(partial: Partial<SpecBridgeConfig>): SpecBridgeConfig {\n return {\n ...defaultConfig,\n ...partial,\n project: {\n ...defaultConfig.project,\n ...partial.project,\n },\n inference: {\n ...defaultConfig.inference,\n ...partial.inference,\n },\n verification: {\n ...defaultConfig.verification,\n ...partial.verification,\n levels: {\n ...defaultConfig.verification?.levels,\n ...partial.verification?.levels,\n },\n },\n agent: {\n ...defaultConfig.agent,\n ...partial.agent,\n },\n };\n}\n","/**\n * Verify command - Check code compliance\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { AutofixEngine, type AutofixResult } from '../../verification/autofix/engine.js';\nimport { getChangedFiles } from '../../verification/incremental.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { Violation, VerificationLevel, Severity } from '../../core/types/index.js';\n\ninterface VerifyOptions {\n level?: string;\n files?: string;\n decisions?: string;\n severity?: string;\n json?: boolean;\n fix?: boolean;\n dryRun?: boolean;\n interactive?: boolean;\n incremental?: boolean;\n}\n\nexport const verifyCommand = new Command('verify')\n .description('Verify code compliance against decisions')\n .option('-l, --level <level>', 'Verification level (commit, pr, full)', 'full')\n .option('-f, --files <patterns>', 'Comma-separated file patterns to check')\n .option('-d, --decisions <ids>', 'Comma-separated decision IDs to check')\n .option('-s, --severity <levels>', 'Comma-separated severity levels (critical, high, medium, low)')\n .option('--json', 'Output as JSON')\n .option('--incremental', 'Only verify changed files (git diff --name-only --diff-filter=AM HEAD)')\n .option('--fix', 'Apply auto-fixes for supported violations')\n .option('--dry-run', 'Show what would be fixed without applying (requires --fix)')\n .option('--interactive', 'Confirm each fix interactively (requires --fix)')\n .action(async (options: VerifyOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Loading configuration...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Parse options\n const level = (options.level || 'full') as VerificationLevel;\n let files = options.files?.split(',').map(f => f.trim());\n const decisions = options.decisions?.split(',').map(d => d.trim());\n const severity = options.severity?.split(',').map(s => s.trim() as Severity);\n\n if (options.incremental) {\n const changed = await getChangedFiles(cwd);\n files = changed.length > 0 ? changed : [];\n }\n\n spinner.text = `Running ${level}-level verification...`;\n\n // Run verification\n const engine = createVerificationEngine();\n let result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n\n // Apply auto-fixes (optional)\n let fixResult: AutofixResult | undefined;\n if (options.fix && result.violations.length > 0) {\n const fixableCount = result.violations.filter(v => v.autofix).length;\n\n if (fixableCount === 0) {\n spinner.stop();\n if (!options.json) {\n console.log(chalk.yellow('No auto-fixable violations found'));\n }\n } else {\n spinner.text = `Applying ${fixableCount} auto-fix(es)...`;\n const fixer = new AutofixEngine();\n fixResult = await fixer.applyFixes(result.violations, {\n dryRun: options.dryRun,\n interactive: options.interactive,\n });\n\n if (!options.dryRun && fixResult.applied.length > 0) {\n result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n }\n }\n }\n\n spinner.stop();\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify({ ...result, autofix: fixResult }, null, 2));\n } else {\n printResult(result, level);\n\n if (options.fix && fixResult) {\n console.log(chalk.green(`✓ Applied ${fixResult.applied.length} fix(es)`));\n if (fixResult.skipped > 0) {\n console.log(chalk.yellow(`⊘ Skipped ${fixResult.skipped} fix(es)`));\n }\n console.log('');\n }\n }\n\n // Exit with error code if verification failed\n if (!result.success) {\n process.exit(1);\n }\n } catch (error) {\n spinner.fail('Verification failed');\n throw error;\n }\n });\n\nfunction printResult(\n result: { success: boolean; violations: Violation[]; checked: number; passed: number; failed: number; skipped: number; duration: number },\n level: VerificationLevel\n): void {\n console.log('');\n\n if (result.violations.length === 0) {\n console.log(chalk.green('✓ All checks passed!'));\n console.log(chalk.dim(` ${result.checked} files checked in ${result.duration}ms`));\n return;\n }\n\n // Group violations by file\n const byFile = new Map<string, Violation[]>();\n for (const violation of result.violations) {\n const existing = byFile.get(violation.file) || [];\n existing.push(violation);\n byFile.set(violation.file, existing);\n }\n\n // Print violations by file\n for (const [file, violations] of byFile) {\n console.log(chalk.underline(file));\n\n for (const v of violations) {\n const typeIcon = getTypeIcon(v.type);\n const severityColor = getSeverityColor(v.severity);\n const location = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n\n console.log(\n ` ${typeIcon} ${severityColor(`[${v.severity}]`)} ${v.message}`\n );\n console.log(chalk.dim(` ${v.decisionId}/${v.constraintId}${location}`));\n\n if (v.suggestion) {\n console.log(chalk.cyan(` Suggestion: ${v.suggestion}`));\n }\n }\n\n console.log('');\n }\n\n // Summary\n const criticalCount = result.violations.filter(v => v.severity === 'critical').length;\n const highCount = result.violations.filter(v => v.severity === 'high').length;\n const mediumCount = result.violations.filter(v => v.severity === 'medium').length;\n const lowCount = result.violations.filter(v => v.severity === 'low').length;\n\n console.log(chalk.bold('Summary:'));\n console.log(` Files: ${result.checked} checked, ${result.passed} passed, ${result.failed} failed`);\n\n const violationParts: string[] = [];\n if (criticalCount > 0) violationParts.push(chalk.red(`${criticalCount} critical`));\n if (highCount > 0) violationParts.push(chalk.yellow(`${highCount} high`));\n if (mediumCount > 0) violationParts.push(chalk.cyan(`${mediumCount} medium`));\n if (lowCount > 0) violationParts.push(chalk.dim(`${lowCount} low`));\n\n console.log(` Violations: ${violationParts.join(', ')}`);\n console.log(` Duration: ${result.duration}ms`);\n\n if (!result.success) {\n console.log('');\n const blockingTypes = level === 'commit'\n ? 'invariant or critical'\n : level === 'pr'\n ? 'invariant, critical, or high'\n : 'invariant';\n console.log(chalk.red(`✗ Verification failed. ${blockingTypes} violations must be resolved.`));\n }\n}\n\nfunction getTypeIcon(type: string): string {\n switch (type) {\n case 'invariant':\n return chalk.red('●');\n case 'convention':\n return chalk.yellow('●');\n case 'guideline':\n return chalk.green('●');\n default:\n return '○';\n }\n}\n\nfunction getSeverityColor(severity: Severity): (text: string) => string {\n switch (severity) {\n case 'critical':\n return chalk.red;\n case 'high':\n return chalk.yellow;\n case 'medium':\n return chalk.cyan;\n case 'low':\n return chalk.dim;\n default:\n return chalk.white;\n }\n}\n","/**\n * Verification Engine - Orchestrates constraint checking\n */\nimport { Project } from 'ts-morph';\nimport type {\n Violation,\n VerificationResult,\n VerificationLevel,\n Severity,\n SpecBridgeConfig,\n Decision,\n} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { selectVerifierForConstraint, type VerificationContext } from './verifiers/index.js';\nimport { glob } from '../utils/glob.js';\nimport { AstCache } from './cache.js';\nimport { shouldApplyConstraintToFile } from './applicability.js';\n\nexport interface VerificationOptions {\n level?: VerificationLevel;\n files?: string[];\n decisions?: string[];\n severity?: Severity[];\n timeout?: number;\n cwd?: string;\n}\n\n/**\n * Verification Engine class\n */\nexport class VerificationEngine {\n private registry: Registry;\n private project: Project;\n private astCache: AstCache;\n\n constructor(registry?: Registry) {\n this.registry = registry || createRegistry();\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n this.astCache = new AstCache();\n }\n\n /**\n * Run verification\n */\n async verify(\n config: SpecBridgeConfig,\n options: VerificationOptions = {}\n ): Promise<VerificationResult> {\n const startTime = Date.now();\n\n const {\n level = 'full',\n files: specificFiles,\n decisions: decisionIds,\n cwd = process.cwd(),\n } = options;\n\n // Get level-specific settings\n const levelConfig = config.verification?.levels?.[level];\n const severityFilter = options.severity || levelConfig?.severity;\n const timeout = options.timeout || levelConfig?.timeout || 60000;\n\n // Load registry if not already loaded\n await this.registry.load();\n\n // Get decisions to verify\n let decisions = this.registry.getActive();\n if (decisionIds && decisionIds.length > 0) {\n decisions = decisions.filter(d => decisionIds.includes(d.metadata.id));\n }\n\n // Get files to verify\n const filesToVerify = specificFiles\n ? specificFiles\n : await glob(config.project.sourceRoots, {\n cwd,\n ignore: config.project.exclude,\n absolute: true,\n });\n\n if (filesToVerify.length === 0) {\n return {\n success: true,\n violations: [],\n checked: 0,\n passed: 0,\n failed: 0,\n skipped: 0,\n duration: Date.now() - startTime,\n };\n }\n\n // Collect all violations\n const allViolations: Violation[] = [];\n let checked = 0;\n let passed = 0;\n let failed = 0;\n const skipped = 0;\n\n // Process files with timeout\n let timeoutHandle: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<'timeout'>((resolve) => {\n timeoutHandle = setTimeout(() => resolve('timeout'), timeout);\n // Use unref() so timeout doesn't prevent process exit if it's the only thing left\n timeoutHandle.unref();\n });\n\n const verificationPromise = this.verifyFiles(\n filesToVerify,\n decisions,\n severityFilter,\n cwd,\n (violations) => {\n allViolations.push(...violations);\n checked++;\n if (violations.length > 0) {\n failed++;\n } else {\n passed++;\n }\n }\n );\n\n let result: void | 'timeout';\n try {\n result = await Promise.race([verificationPromise, timeoutPromise]);\n\n if (result === 'timeout') {\n return {\n success: false,\n violations: allViolations,\n checked,\n passed,\n failed,\n skipped: filesToVerify.length - checked,\n duration: timeout,\n };\n }\n } finally {\n // Always clear the timeout to prevent event loop leak\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n timeoutHandle = null;\n }\n }\n\n // Determine success based on level\n const hasBlockingViolations = allViolations.some(v => {\n if (level === 'commit') {\n return v.type === 'invariant' || v.severity === 'critical';\n }\n if (level === 'pr') {\n return v.type === 'invariant' || v.severity === 'critical' || v.severity === 'high';\n }\n return v.type === 'invariant';\n });\n\n return {\n success: !hasBlockingViolations,\n violations: allViolations,\n checked,\n passed,\n failed,\n skipped,\n duration: Date.now() - startTime,\n };\n }\n\n /**\n * Verify a single file\n */\n async verifyFile(\n filePath: string,\n decisions: Decision[],\n severityFilter?: Severity[],\n cwd: string = process.cwd()\n ): Promise<Violation[]> {\n const violations: Violation[] = [];\n\n const sourceFile = await this.astCache.get(filePath, this.project);\n if (!sourceFile) return violations;\n\n // Check each decision's constraints\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n // Check if file matches constraint scope\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd, severityFilter })) {\n continue;\n }\n\n // Get appropriate verifier\n const verifier = selectVerifierForConstraint(constraint.rule, constraint.verifier);\n if (!verifier) {\n continue;\n }\n\n // Run verification\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n };\n\n try {\n const constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n } catch {\n // Verifier failed, skip\n }\n }\n }\n\n return violations;\n }\n\n /**\n * Verify multiple files\n */\n private async verifyFiles(\n files: string[],\n decisions: Decision[],\n severityFilter: Severity[] | undefined,\n cwd: string,\n onFileVerified: (violations: Violation[]) => void\n ): Promise<void> {\n const BATCH_SIZE = 10;\n for (let i = 0; i < files.length; i += BATCH_SIZE) {\n const batch = files.slice(i, i + BATCH_SIZE);\n const results = await Promise.all(\n batch.map(file => this.verifyFile(file, decisions, severityFilter, cwd))\n );\n\n for (const violations of results) {\n onFileVerified(violations);\n }\n }\n }\n\n /**\n * Get registry\n */\n getRegistry(): Registry {\n return this.registry;\n }\n}\n\n/**\n * Create verification engine\n */\nexport function createVerificationEngine(registry?: Registry): VerificationEngine {\n return new VerificationEngine(registry);\n}\n","/**\n * Decision file loader\n */\nimport { join } from 'node:path';\nimport type { Decision } from '../core/types/index.js';\nimport { validateDecision, formatValidationErrors } from '../core/schemas/decision.schema.js';\nimport { DecisionValidationError, FileSystemError } from '../core/errors/index.js';\nimport { readTextFile, readFilesInDir, pathExists } from '../utils/fs.js';\nimport { parseYaml } from '../utils/yaml.js';\n\nexport interface LoadedDecision {\n decision: Decision;\n filePath: string;\n}\n\nexport interface LoadResult {\n decisions: LoadedDecision[];\n errors: LoadError[];\n}\n\nexport interface LoadError {\n filePath: string;\n error: string;\n}\n\n/**\n * Load a single decision file\n */\nexport async function loadDecisionFile(filePath: string): Promise<Decision> {\n if (!await pathExists(filePath)) {\n throw new FileSystemError(`Decision file not found: ${filePath}`, filePath);\n }\n\n const content = await readTextFile(filePath);\n const parsed = parseYaml(content);\n\n const result = validateDecision(parsed);\n if (!result.success) {\n const errors = formatValidationErrors(result.errors);\n throw new DecisionValidationError(\n `Invalid decision file: ${filePath}`,\n typeof parsed === 'object' && parsed !== null && 'metadata' in parsed\n ? (parsed as { metadata?: { id?: string } }).metadata?.id || 'unknown'\n : 'unknown',\n errors\n );\n }\n\n return result.data as Decision;\n}\n\n/**\n * Load all decisions from a directory\n */\nexport async function loadDecisionsFromDir(dirPath: string): Promise<LoadResult> {\n const decisions: LoadedDecision[] = [];\n const errors: LoadError[] = [];\n\n if (!await pathExists(dirPath)) {\n return { decisions, errors };\n }\n\n const files = await readFilesInDir(dirPath, (f) => f.endsWith('.decision.yaml'));\n\n for (const file of files) {\n const filePath = join(dirPath, file);\n try {\n const decision = await loadDecisionFile(filePath);\n decisions.push({ decision, filePath });\n } catch (error) {\n errors.push({\n filePath,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return { decisions, errors };\n}\n\n/**\n * Validate a decision file without loading it into registry\n */\nexport async function validateDecisionFile(filePath: string): Promise<{\n valid: boolean;\n errors: string[];\n}> {\n try {\n if (!await pathExists(filePath)) {\n return { valid: false, errors: [`File not found: ${filePath}`] };\n }\n\n const content = await readTextFile(filePath);\n const parsed = parseYaml(content);\n\n const result = validateDecision(parsed);\n if (!result.success) {\n return { valid: false, errors: formatValidationErrors(result.errors) };\n }\n\n return { valid: true, errors: [] };\n } catch (error) {\n return {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)],\n };\n }\n}\n","/**\n * Zod schemas for decision YAML validation\n */\nimport { z } from 'zod';\n\n// Status lifecycle\nexport const DecisionStatusSchema = z.enum(['draft', 'active', 'deprecated', 'superseded']);\n\n// Constraint types\nexport const ConstraintTypeSchema = z.enum(['invariant', 'convention', 'guideline']);\n\n// Severity levels\nexport const SeveritySchema = z.enum(['critical', 'high', 'medium', 'low']);\n\n// Verification frequency\nexport const VerificationFrequencySchema = z.enum(['commit', 'pr', 'daily', 'weekly']);\n\n// Decision metadata\nexport const DecisionMetadataSchema = z.object({\n id: z.string().min(1).regex(/^[a-z0-9-]+$/, 'ID must be lowercase alphanumeric with hyphens'),\n title: z.string().min(1).max(200),\n status: DecisionStatusSchema,\n owners: z.array(z.string().min(1)).min(1),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n supersededBy: z.string().optional(),\n tags: z.array(z.string()).optional(),\n});\n\n// Decision content\nexport const DecisionContentSchema = z.object({\n summary: z.string().min(1).max(500),\n rationale: z.string().min(1),\n context: z.string().optional(),\n consequences: z.array(z.string()).optional(),\n});\n\n// Constraint exception\nexport const ConstraintExceptionSchema = z.object({\n pattern: z.string().min(1),\n reason: z.string().min(1),\n approvedBy: z.string().optional(),\n expiresAt: z.string().datetime().optional(),\n});\n\n// Single constraint\nexport const ConstraintSchema = z.object({\n id: z.string().min(1).regex(/^[a-z0-9-]+$/, 'Constraint ID must be lowercase alphanumeric with hyphens'),\n type: ConstraintTypeSchema,\n rule: z.string().min(1),\n severity: SeveritySchema,\n scope: z.string().min(1),\n verifier: z.string().optional(),\n autofix: z.boolean().optional(),\n exceptions: z.array(ConstraintExceptionSchema).optional(),\n});\n\n// Verification config\nexport const VerificationConfigSchema = z.object({\n check: z.string().min(1),\n target: z.string().min(1),\n frequency: VerificationFrequencySchema,\n timeout: z.number().positive().optional(),\n});\n\n// Links\nexport const LinksSchema = z.object({\n related: z.array(z.string()).optional(),\n supersedes: z.array(z.string()).optional(),\n references: z.array(z.string().url()).optional(),\n});\n\n// Complete decision document\nexport const DecisionSchema = z.object({\n kind: z.literal('Decision'),\n metadata: DecisionMetadataSchema,\n decision: DecisionContentSchema,\n constraints: z.array(ConstraintSchema).min(1),\n verification: z.object({\n automated: z.array(VerificationConfigSchema).optional(),\n }).optional(),\n links: LinksSchema.optional(),\n});\n\n// Type exports (suffixed with Schema to avoid conflicts with core types)\nexport type DecisionStatusSchema_ = z.infer<typeof DecisionStatusSchema>;\nexport type ConstraintTypeSchema_ = z.infer<typeof ConstraintTypeSchema>;\nexport type SeveritySchema_ = z.infer<typeof SeveritySchema>;\nexport type VerificationFrequencySchema_ = z.infer<typeof VerificationFrequencySchema>;\nexport type DecisionMetadataSchema_ = z.infer<typeof DecisionMetadataSchema>;\nexport type DecisionContentSchema_ = z.infer<typeof DecisionContentSchema>;\nexport type ConstraintExceptionSchema_ = z.infer<typeof ConstraintExceptionSchema>;\nexport type ConstraintSchema_ = z.infer<typeof ConstraintSchema>;\nexport type VerificationConfigSchema_ = z.infer<typeof VerificationConfigSchema>;\nexport type DecisionTypeSchema = z.infer<typeof DecisionSchema>;\n\n/**\n * Validate a decision document\n */\nexport function validateDecision(data: unknown): { success: true; data: DecisionTypeSchema } | { success: false; errors: z.ZodError } {\n const result = DecisionSchema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, errors: result.error };\n}\n\n/**\n * Format Zod errors into human-readable messages\n */\nexport function formatValidationErrors(errors: z.ZodError): string[] {\n return errors.errors.map((err) => {\n const path = err.path.join('.');\n return `${path}: ${err.message}`;\n });\n}\n","/**\n * Decision Registry - Central store for architectural decisions\n */\nimport type { Decision, DecisionStatus, ConstraintType, Severity } from '../core/types/index.js';\nimport { DecisionNotFoundError, NotInitializedError } from '../core/errors/index.js';\nimport { loadDecisionsFromDir, type LoadedDecision, type LoadResult } from './loader.js';\nimport { getDecisionsDir, pathExists, getSpecBridgeDir } from '../utils/fs.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface RegistryOptions {\n basePath?: string;\n}\n\nexport interface DecisionFilter {\n status?: DecisionStatus[];\n tags?: string[];\n constraintType?: ConstraintType[];\n severity?: Severity[];\n}\n\nexport interface RegistryConstraintMatch {\n decisionId: string;\n decisionTitle: string;\n constraintId: string;\n type: ConstraintType;\n rule: string;\n severity: Severity;\n scope: string;\n}\n\n/**\n * Decision Registry class\n */\nexport class Registry {\n private decisions: Map<string, LoadedDecision> = new Map();\n private basePath: string;\n private loaded = false;\n\n constructor(options: RegistryOptions = {}) {\n this.basePath = options.basePath || process.cwd();\n }\n\n /**\n * Load all decisions from the decisions directory\n */\n async load(): Promise<LoadResult> {\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(this.basePath))) {\n throw new NotInitializedError();\n }\n\n const decisionsDir = getDecisionsDir(this.basePath);\n const result = await loadDecisionsFromDir(decisionsDir);\n\n this.decisions.clear();\n for (const loaded of result.decisions) {\n this.decisions.set(loaded.decision.metadata.id, loaded);\n }\n\n this.loaded = true;\n return result;\n }\n\n /**\n * Ensure registry is loaded\n */\n private ensureLoaded(): void {\n if (!this.loaded) {\n throw new Error('Registry not loaded. Call load() first.');\n }\n }\n\n /**\n * Get all decisions\n */\n getAll(filter?: DecisionFilter): Decision[] {\n this.ensureLoaded();\n\n let decisions = Array.from(this.decisions.values()).map((d) => d.decision);\n\n if (filter) {\n decisions = this.applyFilter(decisions, filter);\n }\n\n return decisions;\n }\n\n /**\n * Get active decisions only\n */\n getActive(): Decision[] {\n return this.getAll({ status: ['active'] });\n }\n\n /**\n * Get a decision by ID\n */\n get(id: string): Decision {\n this.ensureLoaded();\n\n const loaded = this.decisions.get(id);\n if (!loaded) {\n throw new DecisionNotFoundError(id);\n }\n\n return loaded.decision;\n }\n\n /**\n * Get a decision with its file path\n */\n getWithPath(id: string): LoadedDecision {\n this.ensureLoaded();\n\n const loaded = this.decisions.get(id);\n if (!loaded) {\n throw new DecisionNotFoundError(id);\n }\n\n return loaded;\n }\n\n /**\n * Check if a decision exists\n */\n has(id: string): boolean {\n this.ensureLoaded();\n return this.decisions.has(id);\n }\n\n /**\n * Get all decision IDs\n */\n getIds(): string[] {\n this.ensureLoaded();\n return Array.from(this.decisions.keys());\n }\n\n /**\n * Get constraints applicable to a specific file\n */\n getConstraintsForFile(filePath: string, filter?: DecisionFilter): RegistryConstraintMatch[] {\n this.ensureLoaded();\n\n const applicable: RegistryConstraintMatch[] = [];\n let decisions = this.getActive();\n\n if (filter) {\n decisions = this.applyFilter(decisions, filter);\n }\n\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n if (matchesPattern(filePath, constraint.scope)) {\n applicable.push({\n decisionId: decision.metadata.id,\n decisionTitle: decision.metadata.title,\n constraintId: constraint.id,\n type: constraint.type,\n rule: constraint.rule,\n severity: constraint.severity,\n scope: constraint.scope,\n });\n }\n }\n }\n\n return applicable;\n }\n\n /**\n * Get decisions by tag\n */\n getByTag(tag: string): Decision[] {\n return this.getAll().filter(\n (d) => d.metadata.tags?.includes(tag)\n );\n }\n\n /**\n * Get decisions by owner\n */\n getByOwner(owner: string): Decision[] {\n return this.getAll().filter(\n (d) => d.metadata.owners.includes(owner)\n );\n }\n\n /**\n * Apply filter to decisions\n */\n private applyFilter(decisions: Decision[], filter: DecisionFilter): Decision[] {\n return decisions.filter((decision) => {\n // Filter by status\n if (filter.status && !filter.status.includes(decision.metadata.status)) {\n return false;\n }\n\n // Filter by tags\n if (filter.tags) {\n const hasTags = filter.tags.some((tag) =>\n decision.metadata.tags?.includes(tag)\n );\n if (!hasTags) return false;\n }\n\n // Filter by constraint type\n if (filter.constraintType) {\n const hasType = decision.constraints.some((c) =>\n filter.constraintType?.includes(c.type)\n );\n if (!hasType) return false;\n }\n\n // Filter by severity\n if (filter.severity) {\n const hasSeverity = decision.constraints.some((c) =>\n filter.severity?.includes(c.severity)\n );\n if (!hasSeverity) return false;\n }\n\n return true;\n });\n }\n\n /**\n * Get count of decisions by status\n */\n getStatusCounts(): Record<DecisionStatus, number> {\n this.ensureLoaded();\n\n const counts: Record<DecisionStatus, number> = {\n draft: 0,\n active: 0,\n deprecated: 0,\n superseded: 0,\n };\n\n for (const loaded of this.decisions.values()) {\n counts[loaded.decision.metadata.status]++;\n }\n\n return counts;\n }\n\n /**\n * Get total constraint count\n */\n getConstraintCount(): number {\n this.ensureLoaded();\n\n let count = 0;\n for (const loaded of this.decisions.values()) {\n count += loaded.decision.constraints.length;\n }\n\n return count;\n }\n}\n\n/**\n * Create a new registry instance\n */\nexport function createRegistry(options?: RegistryOptions): Registry {\n return new Registry(options);\n}\n","/**\n * Base verifier interface\n */\nimport type { Violation, Constraint, Severity } from '../../core/types/index.js';\nimport type { SourceFile } from 'ts-morph';\n\n/**\n * Context passed to verifiers\n */\nexport interface VerificationContext {\n filePath: string;\n sourceFile: SourceFile;\n constraint: Constraint;\n decisionId: string;\n}\n\n/**\n * Verifier interface - all verifiers must implement this\n */\nexport interface Verifier {\n /**\n * Unique identifier for this verifier\n */\n readonly id: string;\n\n /**\n * Human-readable name\n */\n readonly name: string;\n\n /**\n * Description of what this verifier checks\n */\n readonly description: string;\n\n /**\n * Verify a file against a constraint\n */\n verify(ctx: VerificationContext): Promise<Violation[]>;\n}\n\n/**\n * Helper to create a violation\n */\nexport function createViolation(params: {\n decisionId: string;\n constraintId: string;\n type: Constraint['type'];\n severity: Severity;\n message: string;\n file: string;\n line?: number;\n column?: number;\n endLine?: number;\n endColumn?: number;\n suggestion?: string;\n autofix?: Violation['autofix'];\n}): Violation {\n return params;\n}\n","/**\n * Naming convention verifier\n */\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst NAMING_PATTERNS: Record<string, { regex: RegExp; description: string }> = {\n PascalCase: {\n regex: /^[A-Z][a-zA-Z0-9]*$/,\n description: 'PascalCase (e.g., MyClass)',\n },\n camelCase: {\n regex: /^[a-z][a-zA-Z0-9]*$/,\n description: 'camelCase (e.g., myFunction)',\n },\n UPPER_SNAKE_CASE: {\n regex: /^[A-Z][A-Z0-9_]*$/,\n description: 'UPPER_SNAKE_CASE (e.g., MAX_VALUE)',\n },\n snake_case: {\n regex: /^[a-z][a-z0-9_]*$/,\n description: 'snake_case (e.g., my_variable)',\n },\n 'kebab-case': {\n regex: /^[a-z][a-z0-9-]*$/,\n description: 'kebab-case (e.g., my-component)',\n },\n};\n\nexport class NamingVerifier implements Verifier {\n readonly id = 'naming';\n readonly name = 'Naming Convention Verifier';\n readonly description = 'Verifies naming conventions for classes, functions, and variables';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n\n // Parse constraint rule to extract target and convention\n // Expected format: \"Classes should use PascalCase\" or \"Functions should use camelCase\"\n const rule = constraint.rule.toLowerCase();\n let convention: string | null = null;\n let targetType: 'class' | 'function' | 'interface' | 'type' | null = null;\n\n // Detect convention\n for (const [name] of Object.entries(NAMING_PATTERNS)) {\n if (rule.includes(name.toLowerCase())) {\n convention = name;\n break;\n }\n }\n\n // Detect target type\n if (rule.includes('class')) targetType = 'class';\n else if (rule.includes('function')) targetType = 'function';\n else if (rule.includes('interface')) targetType = 'interface';\n else if (rule.includes('type')) targetType = 'type';\n\n if (!convention || !targetType) {\n // Can't parse rule, skip verification\n return violations;\n }\n\n const pattern = NAMING_PATTERNS[convention];\n if (!pattern) return violations;\n\n // Check based on target type\n if (targetType === 'class') {\n for (const classDecl of sourceFile.getClasses()) {\n const name = classDecl.getName();\n if (name && !pattern.regex.test(name)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Class \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: classDecl.getStartLineNumber(),\n column: classDecl.getStart() - classDecl.getStartLinePos(),\n suggestion: `Rename to follow ${pattern.description}`,\n }));\n }\n }\n }\n\n if (targetType === 'function') {\n for (const funcDecl of sourceFile.getFunctions()) {\n const name = funcDecl.getName();\n if (name && !pattern.regex.test(name)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: funcDecl.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n }));\n }\n }\n }\n\n if (targetType === 'interface') {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n const name = interfaceDecl.getName();\n if (!pattern.regex.test(name)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Interface \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: interfaceDecl.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n }));\n }\n }\n }\n\n if (targetType === 'type') {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const name = typeAlias.getName();\n if (!pattern.regex.test(name)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Type \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: typeAlias.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n }));\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Import pattern verifier\n */\nimport path from 'node:path';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nexport class ImportsVerifier implements Verifier {\n readonly id = 'imports';\n readonly name = 'Import Pattern Verifier';\n readonly description = 'Verifies import patterns like barrel imports, path aliases, etc.';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n // Check for required .js extensions in relative imports (ESM-friendly)\n if ((rule.includes('.js') && rule.includes('extension')) || rule.includes('esm') || rule.includes('add .js')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (!moduleSpec.startsWith('.')) continue;\n\n const ext = path.posix.extname(moduleSpec);\n let suggested: string | null = null;\n\n if (!ext) {\n suggested = `${moduleSpec}.js`;\n } else if (ext === '.ts' || ext === '.tsx' || ext === '.jsx') {\n suggested = moduleSpec.slice(0, -ext.length) + '.js';\n } else if (ext !== '.js') {\n continue;\n }\n\n if (!suggested || suggested === moduleSpec) continue;\n\n const ms = importDecl.getModuleSpecifier();\n const start = ms.getStart() + 1; // inside quotes\n const end = ms.getEnd() - 1;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Relative import \"${moduleSpec}\" should include a .js extension`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Update to \"${suggested}\"`,\n autofix: {\n description: 'Add/normalize .js extension in import specifier',\n edits: [{ start, end, text: suggested }],\n },\n }));\n }\n }\n\n // Check for barrel import requirement\n if (rule.includes('barrel') || rule.includes('index')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n\n // Skip external packages\n if (!moduleSpec.startsWith('.')) continue;\n\n // Check if importing specific file instead of barrel\n if (moduleSpec.match(/\\.(ts|js|tsx|jsx)$/) || moduleSpec.match(/\\/[^/]+$/)) {\n // Could be a direct file import - flag if not index\n if (!moduleSpec.endsWith('/index') && !moduleSpec.endsWith('index')) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Import from \"${moduleSpec}\" should use barrel (index) import`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Import from the parent directory index file instead',\n }));\n }\n }\n }\n }\n\n // Check for path alias requirement\n if (rule.includes('alias') || rule.includes('@/') || rule.includes('path alias')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n\n // Check for deeply nested relative imports\n if (moduleSpec.match(/^\\.\\.\\/\\.\\.\\/\\.\\.\\//)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Deep relative import \"${moduleSpec}\" should use path alias`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use path alias (e.g., @/module) for deep imports',\n }));\n }\n }\n }\n\n // Check for no circular imports (basic check)\n if (rule.includes('circular') || rule.includes('cycle')) {\n // This is a simplified check - a full cycle detection would need graph analysis\n // Check if any import matches the current file's exports\n // This is a very basic heuristic\n const currentFilename = filePath.replace(/\\.[jt]sx?$/, '');\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (moduleSpec.includes(currentFilename.split('/').pop() || '')) {\n // Potential self-reference, might indicate circular dependency\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible circular import detected: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Review import structure for circular dependencies',\n }));\n }\n }\n }\n\n // Check for no wildcard imports\n if (rule.includes('wildcard') || rule.includes('* as') || rule.includes('no namespace')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const namespaceImport = importDecl.getNamespaceImport();\n if (namespaceImport) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Namespace import \"* as ${namespaceImport.getText()}\" should use named imports`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use specific named imports instead of namespace import',\n }));\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Error handling verifier\n */\nimport { Node } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nexport class ErrorsVerifier implements Verifier {\n readonly id = 'errors';\n readonly name = 'Error Handling Verifier';\n readonly description = 'Verifies error handling patterns';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n // Check for custom error class extension\n if (rule.includes('extend') || rule.includes('base') || rule.includes('hierarchy')) {\n // Extract base class name from rule if mentioned\n const baseClassMatch = rule.match(/extend\\s+(\\w+)/i) || rule.match(/(\\w+Error)\\s+class/i);\n const requiredBase = baseClassMatch ? baseClassMatch[1] : null;\n\n for (const classDecl of sourceFile.getClasses()) {\n const className = classDecl.getName();\n if (!className?.endsWith('Error') && !className?.endsWith('Exception')) continue;\n\n const extendsClause = classDecl.getExtends();\n if (!extendsClause) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Error class \"${className}\" does not extend any base class`,\n file: filePath,\n line: classDecl.getStartLineNumber(),\n suggestion: requiredBase\n ? `Extend ${requiredBase}`\n : 'Extend a base error class for consistent error handling',\n }));\n } else if (requiredBase) {\n const baseName = extendsClause.getText();\n if (baseName !== requiredBase && baseName !== 'Error') {\n // Allow extending Error or the required base\n }\n }\n }\n }\n\n // Check for throwing custom errors vs generic Error\n if (rule.includes('custom error') || rule.includes('throw custom')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isThrowStatement(node)) {\n const expression = node.getExpression();\n if (expression) {\n const text = expression.getText();\n if (text.startsWith('new Error(')) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Throwing generic Error instead of custom error class',\n file: filePath,\n line: node.getStartLineNumber(),\n suggestion: 'Use a custom error class for better error handling',\n }));\n }\n }\n }\n });\n }\n\n // Check for empty catch blocks\n if (rule.includes('empty catch') || rule.includes('swallow') || rule.includes('handle')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isTryStatement(node)) {\n const catchClause = node.getCatchClause();\n if (catchClause) {\n const block = catchClause.getBlock();\n const statements = block.getStatements();\n\n // Check if catch block is empty or only has comments\n if (statements.length === 0) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Empty catch block swallows error without handling',\n file: filePath,\n line: catchClause.getStartLineNumber(),\n suggestion: 'Add error handling, logging, or rethrow the error',\n }));\n }\n }\n }\n });\n }\n\n // Check for console.error vs proper logging\n if (rule.includes('logging') || rule.includes('logger') || rule.includes('no console')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isCallExpression(node)) {\n const expression = node.getExpression();\n const text = expression.getText();\n if (text === 'console.error' || text === 'console.log') {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Using ${text} instead of proper logging`,\n file: filePath,\n line: node.getStartLineNumber(),\n suggestion: 'Use a proper logging library',\n }));\n }\n }\n });\n }\n\n return violations;\n }\n}\n","/**\n * Regex-based verifier for simple pattern matching\n */\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\n/**\n * A generic verifier that uses regex patterns from constraint rules\n * This handles constraints that specify patterns to match or avoid\n */\nexport class RegexVerifier implements Verifier {\n readonly id = 'regex';\n readonly name = 'Regex Pattern Verifier';\n readonly description = 'Verifies code against regex patterns specified in constraints';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n\n // Try to extract regex pattern from rule\n // Patterns like: \"must not contain /pattern/\" or \"should match /pattern/\"\n const mustNotMatch = rule.match(/must\\s+not\\s+(?:contain|match|use)\\s+\\/(.+?)\\//i);\n const shouldMatch = rule.match(/(?:should|must)\\s+(?:contain|match|use)\\s+\\/(.+?)\\//i);\n const forbiddenPattern = rule.match(/forbidden:\\s*\\/(.+?)\\//i);\n const requiredPattern = rule.match(/required:\\s*\\/(.+?)\\//i);\n\n const fileText = sourceFile.getFullText();\n\n // Handle \"must not contain\" patterns\n const patternToForbid = mustNotMatch?.[1] || forbiddenPattern?.[1];\n if (patternToForbid) {\n try {\n const regex = new RegExp(patternToForbid, 'g');\n let match: RegExpExecArray | null;\n\n while ((match = regex.exec(fileText)) !== null) {\n const beforeMatch = fileText.substring(0, match.index);\n const lineNumber = beforeMatch.split('\\n').length;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Found forbidden pattern: \"${match[0]}\"`,\n file: filePath,\n line: lineNumber,\n suggestion: `Remove or replace the pattern matching /${patternToForbid}/`,\n }));\n }\n } catch {\n // Invalid regex, skip\n }\n }\n\n // Handle \"should contain\" patterns (file-level check)\n const patternToRequire = shouldMatch?.[1] || requiredPattern?.[1];\n if (patternToRequire && !mustNotMatch) {\n try {\n const regex = new RegExp(patternToRequire);\n if (!regex.test(fileText)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `File does not contain required pattern: /${patternToRequire}/`,\n file: filePath,\n suggestion: `Add code matching /${patternToRequire}/`,\n }));\n }\n } catch {\n // Invalid regex, skip\n }\n }\n\n return violations;\n }\n}\n","/**\n * Dependency constraint verifier\n *\n * Supports rules like:\n * - \"No circular dependencies between modules\"\n * - \"Domain layer cannot depend on infrastructure layer\"\n * - \"No dependencies on package lodash\"\n * - \"Maximum import depth: 2\"\n */\nimport path from 'node:path';\nimport type { Project } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\ntype DependencyGraph = Map<string, Set<string>>;\n\nconst graphCache = new WeakMap<Project, { fileCount: number; graph: DependencyGraph }>();\n\nfunction normalizeFsPath(p: string): string {\n return p.replaceAll('\\\\', '/');\n}\n\nfunction joinLike(fromFilePath: string, relative: string): string {\n const fromNorm = normalizeFsPath(fromFilePath);\n const relNorm = normalizeFsPath(relative);\n\n if (path.isAbsolute(fromNorm)) {\n return normalizeFsPath(path.resolve(path.dirname(fromNorm), relNorm));\n }\n\n // In-memory ts-morph projects often use relative paths; keep them relative.\n const dir = path.posix.dirname(fromNorm);\n return path.posix.normalize(path.posix.join(dir, relNorm));\n}\n\nfunction resolveToSourceFilePath(project: Project, fromFilePath: string, moduleSpec: string): string | null {\n if (!moduleSpec.startsWith('.')) return null;\n\n const candidates: string[] = [];\n const raw = joinLike(fromFilePath, moduleSpec);\n\n const addCandidate = (p: string) => candidates.push(normalizeFsPath(p));\n\n // If an extension exists, try it and common TS/JS mappings.\n const ext = path.posix.extname(raw);\n if (ext) {\n addCandidate(raw);\n\n if (ext === '.js') addCandidate(raw.slice(0, -3) + '.ts');\n if (ext === '.jsx') addCandidate(raw.slice(0, -4) + '.tsx');\n if (ext === '.ts') addCandidate(raw.slice(0, -3) + '.js');\n if (ext === '.tsx') addCandidate(raw.slice(0, -4) + '.jsx');\n\n // Directory index variants.\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.ts'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.tsx'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.js'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.jsx'));\n } else {\n // No extension: try source extensions and index files.\n addCandidate(raw + '.ts');\n addCandidate(raw + '.tsx');\n addCandidate(raw + '.js');\n addCandidate(raw + '.jsx');\n\n addCandidate(path.posix.join(raw, 'index.ts'));\n addCandidate(path.posix.join(raw, 'index.tsx'));\n addCandidate(path.posix.join(raw, 'index.js'));\n addCandidate(path.posix.join(raw, 'index.jsx'));\n }\n\n for (const candidate of candidates) {\n const sf = project.getSourceFile(candidate);\n if (sf) return sf.getFilePath();\n }\n\n return null;\n}\n\nfunction buildDependencyGraph(project: Project): DependencyGraph {\n const cached = graphCache.get(project);\n const sourceFiles = project.getSourceFiles();\n if (cached && cached.fileCount === sourceFiles.length) {\n return cached.graph;\n }\n\n const graph: DependencyGraph = new Map();\n\n for (const sf of sourceFiles) {\n const from = normalizeFsPath(sf.getFilePath());\n if (!graph.has(from)) graph.set(from, new Set());\n\n for (const importDecl of sf.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n const resolved = resolveToSourceFilePath(project, from, moduleSpec);\n if (resolved) {\n graph.get(from)!.add(normalizeFsPath(resolved));\n }\n }\n }\n\n graphCache.set(project, { fileCount: sourceFiles.length, graph });\n return graph;\n}\n\nfunction tarjanScc(graph: DependencyGraph): string[][] {\n let index = 0;\n const stack: string[] = [];\n const onStack = new Set<string>();\n const indices = new Map<string, number>();\n const lowlink = new Map<string, number>();\n const result: string[][] = [];\n\n const strongConnect = (v: string) => {\n indices.set(v, index);\n lowlink.set(v, index);\n index++;\n stack.push(v);\n onStack.add(v);\n\n const edges = graph.get(v) || new Set<string>();\n for (const w of edges) {\n if (!indices.has(w)) {\n strongConnect(w);\n lowlink.set(v, Math.min(lowlink.get(v)!, lowlink.get(w)!));\n } else if (onStack.has(w)) {\n lowlink.set(v, Math.min(lowlink.get(v)!, indices.get(w)!));\n }\n }\n\n if (lowlink.get(v) === indices.get(v)) {\n const scc: string[] = [];\n while (stack.length > 0) {\n const w = stack.pop();\n if (!w) break;\n onStack.delete(w);\n scc.push(w);\n if (w === v) break;\n }\n result.push(scc);\n }\n };\n\n for (const v of graph.keys()) {\n if (!indices.has(v)) strongConnect(v);\n }\n\n return result;\n}\n\nfunction parseMaxImportDepth(rule: string): number | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/maximum\\s{1,5}import\\s{1,5}depth\\s{0,5}[:=]?\\s{0,5}(\\d+)/i);\n return m ? Number.parseInt(m[1]!, 10) : null;\n}\n\nfunction parseBannedDependency(rule: string): string | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/no\\s{1,5}dependencies?\\s{1,5}on\\s{1,5}(?:package\\s{1,5})?(.+?)(?:\\.|$)/i);\n if (!m) return null;\n const value = m[1]!.trim();\n return value.length > 0 ? value : null;\n}\n\nfunction parseLayerRule(rule: string): { fromLayer: string; toLayer: string } | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/(\\w+)\\s{1,5}layer\\s{1,5}cannot\\s{1,5}depend\\s{1,5}on\\s{1,5}(\\w+)\\s{1,5}layer/i);\n if (!m) return null;\n return { fromLayer: m[1]!.toLowerCase(), toLayer: m[2]!.toLowerCase() };\n}\n\nfunction fileInLayer(filePath: string, layer: string): boolean {\n const fp = normalizeFsPath(filePath).toLowerCase();\n return fp.includes(`/${layer}/`) || fp.endsWith(`/${layer}.ts`) || fp.endsWith(`/${layer}.tsx`);\n}\n\nexport class DependencyVerifier implements Verifier {\n readonly id = 'dependencies';\n readonly name = 'Dependency Verifier';\n readonly description = 'Checks dependency constraints, import depth, and circular dependencies';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n const lowerRule = rule.toLowerCase();\n const project = sourceFile.getProject();\n const projectFilePath = normalizeFsPath(sourceFile.getFilePath());\n\n // 1) Circular dependencies (across files)\n if (lowerRule.includes('circular') || lowerRule.includes('cycle')) {\n const graph = buildDependencyGraph(project);\n const sccs = tarjanScc(graph);\n const current = projectFilePath;\n\n for (const scc of sccs) {\n const hasSelfLoop = scc.length === 1 && (graph.get(scc[0]!)?.has(scc[0]!) ?? false);\n const isCycle = scc.length > 1 || hasSelfLoop;\n if (!isCycle) continue;\n\n if (!scc.includes(current)) continue;\n\n // Avoid duplicate reporting: only report from lexicographically-smallest file in the SCC.\n const sorted = [...scc].sort();\n if (sorted[0] !== current) continue;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Circular dependency detected across: ${sorted.join(' -> ')}`,\n file: filePath,\n line: 1,\n suggestion: 'Break the cycle by extracting shared abstractions or reversing the dependency',\n }));\n }\n }\n\n // 2) Layer constraints (heuristic by folder name)\n const layerRule = parseLayerRule(rule);\n if (layerRule && fileInLayer(projectFilePath, layerRule.fromLayer)) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n const resolved = resolveToSourceFilePath(project, projectFilePath, moduleSpec);\n if (!resolved) continue;\n\n if (fileInLayer(resolved, layerRule.toLayer)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Layer violation: ${layerRule.fromLayer} depends on ${layerRule.toLayer} via import \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Refactor to remove dependency from ${layerRule.fromLayer} to ${layerRule.toLayer}`,\n }));\n }\n }\n }\n\n // 3) Banned dependency (package or internal)\n const banned = parseBannedDependency(rule);\n if (banned) {\n const bannedLower = banned.toLowerCase();\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (moduleSpec.toLowerCase().includes(bannedLower)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Banned dependency import detected: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Remove or replace dependency \"${banned}\"`,\n }));\n }\n }\n }\n\n // 4) Import depth limits (../ count)\n const maxDepth = parseMaxImportDepth(rule);\n if (maxDepth !== null) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (!moduleSpec.startsWith('.')) continue;\n const depth = (moduleSpec.match(/\\.\\.\\//g) || []).length;\n if (depth > maxDepth) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Import depth ${depth} exceeds maximum ${maxDepth}: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use a shallower module boundary (or introduce a public entrypoint for this dependency)',\n }));\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Complexity constraint verifier\n *\n * Supports rules like:\n * - \"Cyclomatic complexity must not exceed 10\"\n * - \"File size must not exceed 300 lines\"\n * - \"Functions must have at most 4 parameters\"\n * - \"Nesting depth must not exceed 4\"\n */\nimport type { Node } from 'ts-morph';\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nfunction parseLimit(rule: string, pattern: RegExp): number | null {\n const m = rule.match(pattern);\n return m ? Number.parseInt(m[1]!, 10) : null;\n}\n\nfunction getFileLineCount(text: string): number {\n if (text.length === 0) return 0;\n return text.split('\\n').length;\n}\n\nfunction getDecisionPoints(fn: Node): number {\n let points = 0;\n for (const d of fn.getDescendants()) {\n switch (d.getKind()) {\n case SyntaxKind.IfStatement:\n case SyntaxKind.ForStatement:\n case SyntaxKind.ForInStatement:\n case SyntaxKind.ForOfStatement:\n case SyntaxKind.WhileStatement:\n case SyntaxKind.DoStatement:\n case SyntaxKind.CatchClause:\n case SyntaxKind.ConditionalExpression:\n case SyntaxKind.CaseClause:\n points++;\n break;\n case SyntaxKind.BinaryExpression: {\n // Count short-circuit operators (&&, ||)\n const text = d.getText();\n if (text.includes('&&') || text.includes('||')) points++;\n break;\n }\n default:\n break;\n }\n }\n return points;\n}\n\nfunction calculateCyclomaticComplexity(fn: Node): number {\n // Base complexity of 1 + number of decision points.\n return 1 + getDecisionPoints(fn);\n}\n\nfunction getFunctionDisplayName(fn: Node): string {\n // Best-effort name resolution.\n if ('getName' in (fn as any) && typeof (fn as any).getName === 'function') {\n const name = (fn as any).getName();\n if (typeof name === 'string' && name.length > 0) return name;\n }\n\n // Variable = () => ...\n const parent = fn.getParent();\n if (parent?.getKind() === SyntaxKind.VariableDeclaration) {\n const vd: any = parent;\n if (typeof vd.getName === 'function') return vd.getName();\n }\n\n return '<anonymous>';\n}\n\nfunction maxNestingDepth(node: Node): number {\n let maxDepth = 0;\n\n const walk = (n: Node, depth: number) => {\n maxDepth = Math.max(maxDepth, depth);\n\n const kind = n.getKind();\n const isNestingNode =\n kind === SyntaxKind.IfStatement ||\n kind === SyntaxKind.ForStatement ||\n kind === SyntaxKind.ForInStatement ||\n kind === SyntaxKind.ForOfStatement ||\n kind === SyntaxKind.WhileStatement ||\n kind === SyntaxKind.DoStatement ||\n kind === SyntaxKind.SwitchStatement ||\n kind === SyntaxKind.TryStatement;\n\n for (const child of n.getChildren()) {\n // Skip nested function scopes for nesting depth.\n if (\n child.getKind() === SyntaxKind.FunctionDeclaration ||\n child.getKind() === SyntaxKind.FunctionExpression ||\n child.getKind() === SyntaxKind.ArrowFunction ||\n child.getKind() === SyntaxKind.MethodDeclaration\n ) {\n continue;\n }\n walk(child, isNestingNode ? depth + 1 : depth);\n }\n };\n\n walk(node, 0);\n return maxDepth;\n}\n\nexport class ComplexityVerifier implements Verifier {\n readonly id = 'complexity';\n readonly name = 'Complexity Verifier';\n readonly description = 'Checks cyclomatic complexity, file size, parameters, and nesting depth';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n\n const maxComplexity = parseLimit(rule, /complexity\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n const maxLines = parseLimit(rule, /file\\s+size\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)\\s+lines?/i);\n const maxParams = parseLimit(rule, /at\\s+most\\s+(\\d+)\\s+parameters?/i) ?? parseLimit(rule, /parameters?\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n const maxNesting = parseLimit(rule, /nesting\\s+depth\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n\n if (maxLines !== null) {\n const lineCount = getFileLineCount(sourceFile.getFullText());\n if (lineCount > maxLines) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `File has ${lineCount} lines which exceeds maximum ${maxLines}`,\n file: filePath,\n line: 1,\n suggestion: 'Split the file into smaller modules',\n }));\n }\n }\n\n const functionLikes = [\n ...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionExpression),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.ArrowFunction),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.MethodDeclaration),\n ];\n\n for (const fn of functionLikes) {\n const fnName = getFunctionDisplayName(fn);\n\n if (maxComplexity !== null) {\n const complexity = calculateCyclomaticComplexity(fn);\n if (complexity > maxComplexity) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has cyclomatic complexity ${complexity} which exceeds maximum ${maxComplexity}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Refactor to reduce branching or extract smaller functions',\n }));\n }\n }\n\n if (maxParams !== null && 'getParameters' in (fn as any)) {\n const params = (fn as any).getParameters();\n const paramCount = Array.isArray(params) ? params.length : 0;\n if (paramCount > maxParams) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has ${paramCount} parameters which exceeds maximum ${maxParams}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Consider grouping parameters into an options object',\n }));\n }\n }\n\n if (maxNesting !== null) {\n const depth = maxNestingDepth(fn);\n if (depth > maxNesting) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has nesting depth ${depth} which exceeds maximum ${maxNesting}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Reduce nesting by using early returns or extracting functions',\n }));\n }\n }\n }\n\n return violations;\n }\n}\n\n","/**\n * Security verifier (heuristic/static checks)\n *\n * Supports rules like:\n * - \"No hardcoded secrets\"\n * - \"Avoid eval / Function constructor\"\n * - \"Prevent SQL injection\"\n * - \"Avoid innerHTML / dangerouslySetInnerHTML\"\n */\nimport type { Node } from 'ts-morph';\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst SECRET_NAME_RE = /(api[_-]?key|password|secret|token)/i;\n\nfunction isStringLiteralLike(node: Node): boolean {\n const k = node.getKind();\n return k === SyntaxKind.StringLiteral || k === SyntaxKind.NoSubstitutionTemplateLiteral;\n}\n\nexport class SecurityVerifier implements Verifier {\n readonly id = 'security';\n readonly name = 'Security Verifier';\n readonly description = 'Detects common security footguns (secrets, eval, XSS/SQL injection heuristics)';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n const checkSecrets = rule.includes('secret') || rule.includes('password') || rule.includes('token') || rule.includes('api key') || rule.includes('hardcoded');\n const checkEval = rule.includes('eval') || rule.includes('function constructor');\n const checkXss = rule.includes('xss') || rule.includes('innerhtml') || rule.includes('dangerouslysetinnerhtml');\n const checkSql = rule.includes('sql') || rule.includes('injection');\n const checkProto = rule.includes('prototype pollution') || rule.includes('__proto__');\n\n if (checkSecrets) {\n for (const vd of sourceFile.getVariableDeclarations()) {\n const name = vd.getName();\n if (!SECRET_NAME_RE.test(name)) continue;\n\n const init = vd.getInitializer();\n if (!init || !isStringLiteralLike(init)) continue;\n\n const value = init.getText().slice(1, -1); // best-effort strip quotes\n if (value.length === 0) continue;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible hardcoded secret in variable \"${name}\"`,\n file: filePath,\n line: vd.getStartLineNumber(),\n suggestion: 'Move secrets to environment variables or a secret manager',\n }));\n }\n\n for (const pa of sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {\n const nameNode: any = pa.getNameNode?.();\n const propName = nameNode?.getText?.() ?? '';\n if (!SECRET_NAME_RE.test(propName)) continue;\n\n const init = pa.getInitializer();\n if (!init || !isStringLiteralLike(init)) continue;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible hardcoded secret in object property ${propName}`,\n file: filePath,\n line: pa.getStartLineNumber(),\n suggestion: 'Move secrets to environment variables or a secret manager',\n }));\n }\n }\n\n if (checkEval) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const exprText = call.getExpression().getText();\n if (exprText === 'eval' || exprText === 'Function') {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Unsafe dynamic code execution via ${exprText}()`,\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Avoid eval/Function; use safer alternatives',\n }));\n }\n }\n }\n\n if (checkXss) {\n // innerHTML assignments\n for (const bin of sourceFile.getDescendantsOfKind(SyntaxKind.BinaryExpression)) {\n const left = bin.getLeft();\n if (left.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n const pa: any = left;\n if (pa.getName?.() === 'innerHTML') {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential XSS: assignment to innerHTML',\n file: filePath,\n line: bin.getStartLineNumber(),\n suggestion: 'Prefer textContent or a safe templating/escaping strategy',\n }));\n }\n }\n\n // React dangerouslySetInnerHTML usage\n if (sourceFile.getFullText().includes('dangerouslySetInnerHTML')) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential XSS: usage of dangerouslySetInnerHTML',\n file: filePath,\n line: 1,\n suggestion: 'Avoid dangerouslySetInnerHTML or ensure content is sanitized',\n }));\n }\n }\n\n if (checkSql) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n const name = (expr as any).getName?.();\n if (name !== 'query' && name !== 'execute') continue;\n\n const arg = call.getArguments()[0];\n if (!arg) continue;\n\n const isTemplate = arg.getKind() === SyntaxKind.TemplateExpression;\n const isConcat = arg.getKind() === SyntaxKind.BinaryExpression && arg.getText().includes('+');\n if (!isTemplate && !isConcat) continue;\n\n const text = arg.getText().toLowerCase();\n if (!text.includes('select') && !text.includes('insert') && !text.includes('update') && !text.includes('delete')) {\n continue;\n }\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential SQL injection: dynamically constructed SQL query',\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Use parameterized queries / prepared statements',\n }));\n }\n }\n\n if (checkProto) {\n const text = sourceFile.getFullText();\n if (text.includes('__proto__') || text.includes('constructor.prototype')) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential prototype pollution pattern detected',\n file: filePath,\n line: 1,\n suggestion: 'Avoid writing to __proto__/prototype; validate object keys',\n }));\n }\n }\n\n return violations;\n }\n}\n\n","/**\n * API consistency verifier (heuristic)\n *\n * Supports rules like:\n * - \"REST endpoints must use kebab-case\"\n */\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'all']);\n\nfunction isKebabPath(pathValue: string): boolean {\n const parts = pathValue.split('/').filter(Boolean);\n for (const part of parts) {\n if (part.startsWith(':')) continue; // path params\n if (!/^[a-z0-9-]+$/.test(part)) return false;\n }\n return true;\n}\n\nexport class ApiVerifier implements Verifier {\n readonly id = 'api';\n readonly name = 'API Consistency Verifier';\n readonly description = 'Checks basic REST endpoint naming conventions in common frameworks';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n const enforceKebab = rule.includes('kebab') || rule.includes('kebab-case');\n if (!enforceKebab) return violations;\n\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const method = (expr as any).getName?.();\n if (!method || !HTTP_METHODS.has(String(method))) continue;\n\n const firstArg = call.getArguments()[0];\n if (!firstArg || firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const pathValue = (firstArg as any).getLiteralValue?.() ?? firstArg.getText().slice(1, -1);\n if (typeof pathValue !== 'string') continue;\n\n if (!isKebabPath(pathValue)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Endpoint path \"${pathValue}\" is not kebab-case`,\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Use lowercase and hyphens in static path segments (e.g., /user-settings)',\n }));\n }\n }\n\n return violations;\n }\n}\n\n","/**\n * Verifier exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './errors.js';\nexport * from './regex.js';\nexport * from './dependencies.js';\nexport * from './complexity.js';\nexport * from './security.js';\nexport * from './api.js';\n\nimport type { Verifier } from './base.js';\nimport { NamingVerifier } from './naming.js';\nimport { ImportsVerifier } from './imports.js';\nimport { ErrorsVerifier } from './errors.js';\nimport { RegexVerifier } from './regex.js';\nimport { DependencyVerifier } from './dependencies.js';\nimport { ComplexityVerifier } from './complexity.js';\nimport { SecurityVerifier } from './security.js';\nimport { ApiVerifier } from './api.js';\n\n/**\n * Built-in verifiers registry\n */\nexport const builtinVerifiers: Record<string, () => Verifier> = {\n naming: () => new NamingVerifier(),\n imports: () => new ImportsVerifier(),\n errors: () => new ErrorsVerifier(),\n regex: () => new RegexVerifier(),\n dependencies: () => new DependencyVerifier(),\n complexity: () => new ComplexityVerifier(),\n security: () => new SecurityVerifier(),\n api: () => new ApiVerifier(),\n};\n\n/**\n * Get verifier by ID\n */\nexport function getVerifier(id: string): Verifier | null {\n const factory = builtinVerifiers[id];\n return factory ? factory() : null;\n}\n\n/**\n * Get all verifier IDs\n */\nexport function getVerifierIds(): string[] {\n return Object.keys(builtinVerifiers);\n}\n\n/**\n * Select appropriate verifier based on constraint rule\n */\nexport function selectVerifierForConstraint(rule: string, specifiedVerifier?: string): Verifier | null {\n // If verifier is explicitly specified, use it\n if (specifiedVerifier) {\n return getVerifier(specifiedVerifier);\n }\n\n // Auto-select based on rule content\n const lowerRule = rule.toLowerCase();\n\n if (lowerRule.includes('dependency') || lowerRule.includes('circular dependenc') || lowerRule.includes('import depth') || (lowerRule.includes('layer') && lowerRule.includes('depend on'))) {\n return getVerifier('dependencies');\n }\n\n if (lowerRule.includes('cyclomatic') || lowerRule.includes('complexity') || lowerRule.includes('nesting') || lowerRule.includes('parameters') || lowerRule.includes('file size')) {\n return getVerifier('complexity');\n }\n\n if (lowerRule.includes('security') || lowerRule.includes('secret') || lowerRule.includes('password') || lowerRule.includes('token') || lowerRule.includes('xss') || lowerRule.includes('sql') || lowerRule.includes('eval')) {\n return getVerifier('security');\n }\n\n if (lowerRule.includes('endpoint') || lowerRule.includes('rest') || (lowerRule.includes('api') && lowerRule.includes('path'))) {\n return getVerifier('api');\n }\n\n if (lowerRule.includes('naming') || lowerRule.includes('case')) {\n return getVerifier('naming');\n }\n\n if (lowerRule.includes('import') || lowerRule.includes('barrel') || lowerRule.includes('alias')) {\n return getVerifier('imports');\n }\n\n if (lowerRule.includes('error') || lowerRule.includes('throw') || lowerRule.includes('catch')) {\n return getVerifier('errors');\n }\n\n if (lowerRule.includes('/') || lowerRule.includes('pattern') || lowerRule.includes('regex')) {\n return getVerifier('regex');\n }\n\n // Default to regex verifier for pattern-based rules\n return getVerifier('regex');\n}\n","/**\n * AST parsing cache (per VerificationEngine instance)\n */\nimport { stat } from 'node:fs/promises';\nimport type { Project, SourceFile } from 'ts-morph';\n\nexport class AstCache {\n private cache = new Map<string, { sourceFile: SourceFile; mtimeMs: number }>();\n\n async get(filePath: string, project: Project): Promise<SourceFile | null> {\n try {\n const info = await stat(filePath);\n const cached = this.cache.get(filePath);\n\n if (cached && cached.mtimeMs >= info.mtimeMs) {\n return cached.sourceFile;\n }\n\n let sourceFile = project.getSourceFile(filePath);\n if (!sourceFile) {\n sourceFile = project.addSourceFileAtPath(filePath);\n } else {\n // Refresh from disk if the file changed.\n sourceFile.refreshFromFileSystemSync();\n }\n\n this.cache.set(filePath, { sourceFile, mtimeMs: info.mtimeMs });\n return sourceFile;\n } catch {\n return null;\n }\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\n","/**\n * Shared constraint applicability helpers\n */\nimport type { Constraint, Severity } from '../core/types/index.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport function isConstraintExcepted(filePath: string, constraint: Constraint, cwd: string): boolean {\n if (!constraint.exceptions) return false;\n\n return constraint.exceptions.some((exception) => {\n // Check if exception has expired\n if (exception.expiresAt) {\n const expiryDate = new Date(exception.expiresAt);\n if (expiryDate < new Date()) {\n return false;\n }\n }\n\n return matchesPattern(filePath, exception.pattern, { cwd });\n });\n}\n\nexport function shouldApplyConstraintToFile(params: {\n filePath: string;\n constraint: Constraint;\n cwd: string;\n severityFilter?: Severity[];\n}): boolean {\n const { filePath, constraint, cwd, severityFilter } = params;\n\n if (!matchesPattern(filePath, constraint.scope, { cwd })) return false;\n if (severityFilter && !severityFilter.includes(constraint.severity)) return false;\n if (isConstraintExcepted(filePath, constraint, cwd)) return false;\n\n return true;\n}\n\n","/**\n * Auto-fix engine\n */\nimport { readFile, writeFile } from 'node:fs/promises';\nimport readline from 'node:readline/promises';\nimport { stdin, stdout } from 'node:process';\nimport type { Violation, TextEdit } from '../../core/types/index.js';\n\nexport interface AutofixPatch {\n filePath: string;\n description: string;\n start: number;\n end: number;\n originalText: string;\n fixedText: string;\n}\n\nexport interface AutofixResult {\n applied: AutofixPatch[];\n skipped: number;\n}\n\ntype DescribedEdit = TextEdit & { description: string };\n\nfunction applyEdits(\n content: string,\n edits: DescribedEdit[]\n): { next: string; patches: AutofixPatch[]; skippedEdits: number } {\n const sorted = [...edits].sort((a, b) => b.start - a.start);\n\n let next = content;\n const patches: AutofixPatch[] = [];\n let skippedEdits = 0;\n let lastStart = Number.POSITIVE_INFINITY;\n\n for (const edit of sorted) {\n if (edit.start < 0 || edit.end < edit.start || edit.end > next.length) {\n skippedEdits++;\n continue;\n }\n\n // Overlap check (since edits are sorted by start descending)\n if (edit.end > lastStart) {\n skippedEdits++;\n continue;\n }\n lastStart = edit.start;\n\n const originalText = next.slice(edit.start, edit.end);\n next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);\n\n patches.push({\n filePath: '',\n description: edit.description,\n start: edit.start,\n end: edit.end,\n originalText,\n fixedText: edit.text,\n });\n }\n\n return { next, patches, skippedEdits };\n}\n\nasync function confirmFix(prompt: string): Promise<boolean> {\n const rl = readline.createInterface({ input: stdin, output: stdout });\n try {\n const answer = await rl.question(`${prompt} (y/N) `);\n return answer.trim().toLowerCase() === 'y';\n } finally {\n rl.close();\n }\n}\n\nexport class AutofixEngine {\n async applyFixes(\n violations: Violation[],\n options: { dryRun?: boolean; interactive?: boolean } = {}\n ): Promise<AutofixResult> {\n const fixable = violations.filter(v => v.autofix && v.autofix.edits.length > 0);\n const byFile = new Map<string, Violation[]>();\n for (const v of fixable) {\n const list = byFile.get(v.file) ?? [];\n list.push(v);\n byFile.set(v.file, list);\n }\n\n const applied: AutofixPatch[] = [];\n let skippedViolations = 0;\n\n for (const [filePath, fileViolations] of byFile) {\n const original = await readFile(filePath, 'utf-8');\n\n const edits: DescribedEdit[] = [];\n for (const violation of fileViolations) {\n const fix = violation.autofix!;\n if (options.interactive) {\n const ok = await confirmFix(`Apply fix: ${fix.description} (${filePath}:${violation.line ?? 1})?`);\n if (!ok) {\n skippedViolations++;\n continue;\n }\n }\n for (const edit of fix.edits) {\n edits.push({ ...edit, description: fix.description });\n }\n }\n\n if (edits.length === 0) continue;\n\n const { next, patches, skippedEdits } = applyEdits(original, edits);\n skippedViolations += skippedEdits;\n\n if (!options.dryRun) {\n await writeFile(filePath, next, 'utf-8');\n }\n\n for (const patch of patches) {\n applied.push({ ...patch, filePath });\n }\n }\n\n return { applied, skipped: skippedViolations };\n }\n}\n","/**\n * Incremental verification helpers\n */\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { resolve } from 'node:path';\nimport { pathExists } from '../utils/fs.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport async function getChangedFiles(cwd: string): Promise<string[]> {\n try {\n const { stdout } = await execFileAsync('git', ['diff', '--name-only', '--diff-filter=AM', 'HEAD'], { cwd });\n const rel = stdout\n .trim()\n .split('\\n')\n .map(s => s.trim())\n .filter(Boolean);\n\n const abs: string[] = [];\n for (const file of rel) {\n const full = resolve(cwd, file);\n if (await pathExists(full)) abs.push(full);\n }\n return abs;\n } catch {\n return [];\n }\n}\n\n","/**\n * Decision command group\n */\nimport { Command } from 'commander';\nimport { listDecisions } from './list.js';\nimport { showDecision } from './show.js';\nimport { validateDecisions } from './validate.js';\nimport { createDecision } from './create.js';\n\nexport const decisionCommand = new Command('decision')\n .description('Manage architectural decisions')\n .addCommand(listDecisions)\n .addCommand(showDecision)\n .addCommand(validateDecisions)\n .addCommand(createDecision);\n","/**\n * List decisions command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { table } from 'table';\nimport { createRegistry } from '../../../registry/registry.js';\nimport type { DecisionStatus, ConstraintType } from '../../../core/types/index.js';\n\ninterface ListOptions {\n status?: string;\n tag?: string;\n json?: boolean;\n}\n\nexport const listDecisions = new Command('list')\n .description('List all architectural decisions')\n .option('-s, --status <status>', 'Filter by status (draft, active, deprecated, superseded)')\n .option('-t, --tag <tag>', 'Filter by tag')\n .option('--json', 'Output as JSON')\n .action(async (options: ListOptions) => {\n const registry = createRegistry();\n const result = await registry.load();\n\n // Show loading errors as warnings\n if (result.errors.length > 0) {\n console.warn(chalk.yellow('\\nWarnings:'));\n for (const err of result.errors) {\n console.warn(chalk.yellow(` - ${err.filePath}: ${err.error}`));\n }\n console.log('');\n }\n\n // Apply filters\n const filter: { status?: DecisionStatus[]; tags?: string[] } = {};\n if (options.status) {\n filter.status = [options.status as DecisionStatus];\n }\n if (options.tag) {\n filter.tags = [options.tag];\n }\n\n const decisions = registry.getAll(filter);\n\n if (decisions.length === 0) {\n console.log(chalk.yellow('No decisions found.'));\n return;\n }\n\n if (options.json) {\n console.log(JSON.stringify(decisions, null, 2));\n return;\n }\n\n // Create table\n const data: string[][] = [\n [\n chalk.bold('ID'),\n chalk.bold('Title'),\n chalk.bold('Status'),\n chalk.bold('Constraints'),\n chalk.bold('Tags'),\n ],\n ];\n\n for (const decision of decisions) {\n const statusColor = getStatusColor(decision.metadata.status);\n const constraintTypes = getConstraintTypeSummary(decision.constraints.map(c => c.type));\n\n data.push([\n decision.metadata.id,\n truncate(decision.metadata.title, 40),\n statusColor(decision.metadata.status),\n constraintTypes,\n (decision.metadata.tags || []).join(', ') || '-',\n ]);\n }\n\n console.log(table(data, {\n border: {\n topBody: '',\n topJoin: '',\n topLeft: '',\n topRight: '',\n bottomBody: '',\n bottomJoin: '',\n bottomLeft: '',\n bottomRight: '',\n bodyLeft: '',\n bodyRight: '',\n bodyJoin: ' ',\n joinBody: '',\n joinLeft: '',\n joinRight: '',\n joinJoin: '',\n },\n drawHorizontalLine: (index) => index === 1,\n }));\n\n console.log(chalk.dim(`Total: ${decisions.length} decision(s)`));\n });\n\nfunction getStatusColor(status: DecisionStatus): (text: string) => string {\n switch (status) {\n case 'active':\n return chalk.green;\n case 'draft':\n return chalk.yellow;\n case 'deprecated':\n return chalk.gray;\n case 'superseded':\n return chalk.blue;\n default:\n return chalk.white;\n }\n}\n\nfunction getConstraintTypeSummary(types: ConstraintType[]): string {\n const counts = {\n invariant: 0,\n convention: 0,\n guideline: 0,\n };\n\n for (const type of types) {\n counts[type]++;\n }\n\n const parts: string[] = [];\n if (counts.invariant > 0) parts.push(chalk.red(`${counts.invariant}I`));\n if (counts.convention > 0) parts.push(chalk.yellow(`${counts.convention}C`));\n if (counts.guideline > 0) parts.push(chalk.green(`${counts.guideline}G`));\n\n return parts.join(' ') || '-';\n}\n\nfunction truncate(str: string, length: number): string {\n if (str.length <= length) return str;\n return str.slice(0, length - 3) + '...';\n}\n","/**\n * Show decision command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createRegistry } from '../../../registry/registry.js';\nimport type { Decision, ConstraintType, Severity } from '../../../core/types/index.js';\n\ninterface ShowOptions {\n json?: boolean;\n}\n\nexport const showDecision = new Command('show')\n .description('Show details of a specific decision')\n .argument('<id>', 'Decision ID')\n .option('--json', 'Output as JSON')\n .action(async (id: string, options: ShowOptions) => {\n const registry = createRegistry();\n await registry.load();\n\n const decision = registry.get(id);\n\n if (options.json) {\n console.log(JSON.stringify(decision, null, 2));\n return;\n }\n\n printDecision(decision);\n });\n\nfunction printDecision(decision: Decision): void {\n const { metadata, decision: content, constraints } = decision;\n\n // Header\n console.log(chalk.bold.blue(`\\n${metadata.title}`));\n console.log(chalk.dim(`ID: ${metadata.id}`));\n console.log('');\n\n // Metadata\n console.log(chalk.bold('Status:'), getStatusBadge(metadata.status));\n console.log(chalk.bold('Owners:'), metadata.owners.join(', '));\n if (metadata.tags && metadata.tags.length > 0) {\n console.log(chalk.bold('Tags:'), metadata.tags.map(t => chalk.cyan(t)).join(', '));\n }\n if (metadata.createdAt) {\n console.log(chalk.bold('Created:'), metadata.createdAt);\n }\n if (metadata.supersededBy) {\n console.log(chalk.bold('Superseded by:'), chalk.yellow(metadata.supersededBy));\n }\n console.log('');\n\n // Decision content\n console.log(chalk.bold.underline('Summary'));\n console.log(content.summary);\n console.log('');\n\n console.log(chalk.bold.underline('Rationale'));\n console.log(content.rationale);\n console.log('');\n\n if (content.context) {\n console.log(chalk.bold.underline('Context'));\n console.log(content.context);\n console.log('');\n }\n\n if (content.consequences && content.consequences.length > 0) {\n console.log(chalk.bold.underline('Consequences'));\n for (const consequence of content.consequences) {\n console.log(` • ${consequence}`);\n }\n console.log('');\n }\n\n // Constraints\n console.log(chalk.bold.underline(`Constraints (${constraints.length})`));\n for (const constraint of constraints) {\n const typeIcon = getTypeIcon(constraint.type);\n const severityBadge = getSeverityBadge(constraint.severity);\n\n console.log(`\\n ${typeIcon} ${chalk.bold(constraint.id)} ${severityBadge}`);\n console.log(` ${constraint.rule}`);\n console.log(chalk.dim(` Scope: ${constraint.scope}`));\n\n if (constraint.verifier) {\n console.log(chalk.dim(` Verifier: ${constraint.verifier}`));\n }\n\n if (constraint.exceptions && constraint.exceptions.length > 0) {\n console.log(chalk.dim(` Exceptions: ${constraint.exceptions.length}`));\n }\n }\n console.log('');\n\n // Verification\n if (decision.verification?.automated && decision.verification.automated.length > 0) {\n console.log(chalk.bold.underline('Automated Verification'));\n for (const check of decision.verification.automated) {\n console.log(` • ${check.check} (${check.frequency})`);\n console.log(chalk.dim(` Target: ${check.target}`));\n }\n console.log('');\n }\n\n // Links\n if (decision.links) {\n const { related, supersedes, references } = decision.links;\n\n if (related && related.length > 0) {\n console.log(chalk.bold('Related:'), related.join(', '));\n }\n if (supersedes && supersedes.length > 0) {\n console.log(chalk.bold('Supersedes:'), supersedes.join(', '));\n }\n if (references && references.length > 0) {\n console.log(chalk.bold('References:'));\n for (const ref of references) {\n console.log(` • ${ref}`);\n }\n }\n }\n}\n\nfunction getStatusBadge(status: string): string {\n switch (status) {\n case 'active':\n return chalk.bgGreen.black(' ACTIVE ');\n case 'draft':\n return chalk.bgYellow.black(' DRAFT ');\n case 'deprecated':\n return chalk.bgGray.white(' DEPRECATED ');\n case 'superseded':\n return chalk.bgBlue.white(' SUPERSEDED ');\n default:\n return status;\n }\n}\n\nfunction getTypeIcon(type: ConstraintType): string {\n switch (type) {\n case 'invariant':\n return chalk.red('●');\n case 'convention':\n return chalk.yellow('●');\n case 'guideline':\n return chalk.green('●');\n default:\n return '○';\n }\n}\n\nfunction getSeverityBadge(severity: Severity): string {\n switch (severity) {\n case 'critical':\n return chalk.bgRed.white(' CRITICAL ');\n case 'high':\n return chalk.bgYellow.black(' HIGH ');\n case 'medium':\n return chalk.bgCyan.black(' MEDIUM ');\n case 'low':\n return chalk.bgGray.white(' LOW ');\n default:\n return severity;\n }\n}\n","/**\n * Validate decisions command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { validateDecisionFile } from '../../../registry/loader.js';\nimport { getDecisionsDir, readFilesInDir, pathExists, getSpecBridgeDir } from '../../../utils/fs.js';\nimport { NotInitializedError } from '../../../core/errors/index.js';\n\ninterface ValidateOptions {\n file?: string;\n}\n\nexport const validateDecisions = new Command('validate')\n .description('Validate decision files')\n .option('-f, --file <path>', 'Validate a specific file')\n .action(async (options: ValidateOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Validating decisions...').start();\n\n try {\n let files: string[] = [];\n\n if (options.file) {\n files = [options.file];\n } else {\n const decisionsDir = getDecisionsDir(cwd);\n const decisionFiles = await readFilesInDir(\n decisionsDir,\n (f) => f.endsWith('.decision.yaml')\n );\n files = decisionFiles.map((f) => join(decisionsDir, f));\n }\n\n if (files.length === 0) {\n spinner.info('No decision files found.');\n return;\n }\n\n let valid = 0;\n let invalid = 0;\n const errors: { file: string; errors: string[] }[] = [];\n\n for (const file of files) {\n const result = await validateDecisionFile(file);\n if (result.valid) {\n valid++;\n } else {\n invalid++;\n errors.push({ file, errors: result.errors });\n }\n }\n\n spinner.stop();\n\n // Print results\n if (invalid === 0) {\n console.log(chalk.green(`✓ All ${valid} decision file(s) are valid.`));\n } else {\n console.log(chalk.red(`✗ ${invalid} of ${files.length} decision file(s) have errors.\\n`));\n\n for (const { file, errors: fileErrors } of errors) {\n console.log(chalk.red(`File: ${file}`));\n for (const err of fileErrors) {\n console.log(chalk.dim(` - ${err}`));\n }\n console.log('');\n }\n\n process.exit(1);\n }\n } catch (error) {\n spinner.fail('Validation failed');\n throw error;\n }\n });\n","/**\n * Create decision command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { join } from 'node:path';\nimport { writeTextFile, getDecisionsDir, pathExists, getSpecBridgeDir } from '../../../utils/fs.js';\nimport { stringifyYaml } from '../../../utils/yaml.js';\nimport { NotInitializedError } from '../../../core/errors/index.js';\n\ninterface CreateOptions {\n title: string;\n summary: string;\n type?: 'invariant' | 'convention' | 'guideline';\n severity?: 'critical' | 'high' | 'medium' | 'low';\n scope?: string;\n owner?: string;\n}\n\nexport const createDecision = new Command('create')\n .description('Create a new decision file')\n .argument('<id>', 'Decision ID (e.g., auth-001)')\n .requiredOption('-t, --title <title>', 'Decision title')\n .requiredOption('-s, --summary <summary>', 'One-sentence summary')\n .option('--type <type>', 'Default constraint type (invariant, convention, guideline)', 'convention')\n .option('--severity <severity>', 'Default constraint severity (critical, high, medium, low)', 'medium')\n .option('--scope <scope>', 'Default constraint scope (glob pattern)', 'src/**/*.ts')\n .option('-o, --owner <owner>', 'Owner name', 'team')\n .action(async (id: string, options: CreateOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n // Validate ID format\n if (!/^[a-z0-9-]+$/.test(id)) {\n console.error(chalk.red('Error: Decision ID must be lowercase alphanumeric with hyphens only.'));\n process.exit(1);\n }\n\n const decisionsDir = getDecisionsDir(cwd);\n const filePath = join(decisionsDir, `${id}.decision.yaml`);\n\n // Check if file already exists\n if (await pathExists(filePath)) {\n console.error(chalk.red(`Error: Decision file already exists: ${filePath}`));\n process.exit(1);\n }\n\n // Create decision structure\n const decision = {\n kind: 'Decision',\n metadata: {\n id,\n title: options.title,\n status: 'draft',\n owners: [options.owner || 'team'],\n createdAt: new Date().toISOString(),\n tags: [],\n },\n decision: {\n summary: options.summary,\n rationale: 'TODO: Explain why this decision was made.',\n context: 'TODO: Describe the context and background.',\n consequences: [\n 'TODO: List positive consequences',\n 'TODO: List negative consequences or trade-offs',\n ],\n },\n constraints: [\n {\n id: `${id}-c1`,\n type: options.type || 'convention',\n rule: 'TODO: Describe the constraint rule',\n severity: options.severity || 'medium',\n scope: options.scope || 'src/**/*.ts',\n },\n ],\n verification: {\n automated: [],\n },\n };\n\n // Write file\n await writeTextFile(filePath, stringifyYaml(decision));\n\n console.log(chalk.green(`✓ Created decision: ${filePath}`));\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(` 1. Edit the file to add rationale, context, and consequences`);\n console.log(` 2. Define constraints with appropriate scopes`);\n console.log(` 3. Run ${chalk.bold('specbridge decision validate')} to check syntax`);\n console.log(` 4. Change status from ${chalk.yellow('draft')} to ${chalk.green('active')} when ready`);\n });\n","/**\n * Hook command - Git hook integration\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, readTextFile, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { VerificationLevel } from '../../core/types/index.js';\n\nconst HOOK_SCRIPT = `#!/bin/sh\n# SpecBridge pre-commit hook\n# Runs verification on staged files\n\necho \"Running SpecBridge verification...\"\n\n# Run specbridge hook (it will detect staged files automatically)\nnpx specbridge hook run --level commit\n\nexit $?\n`;\n\nexport function createHookCommand(): Command {\n const hookCommand = new Command('hook')\n .description('Manage Git hooks for verification');\n\n hookCommand\n .command('install')\n .description('Install Git pre-commit hook')\n .option('-f, --force', 'Overwrite existing hook')\n .option('--husky', 'Install for husky')\n .option('--lefthook', 'Install for lefthook')\n .action(async (options: { force?: boolean; husky?: boolean; lefthook?: boolean }) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Detecting hook system...').start();\n\n try {\n // Detect hook system\n let hookPath: string;\n let hookContent: string;\n\n if (options.husky) {\n // Install for husky\n hookPath = join(cwd, '.husky', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing husky pre-commit hook...';\n } else if (options.lefthook) {\n // Show lefthook config\n spinner.succeed('Lefthook detected');\n console.log('');\n console.log(chalk.cyan('Add this to your lefthook.yml:'));\n console.log('');\n console.log(chalk.dim(`pre-commit:\n commands:\n specbridge:\n glob: \"*.{ts,tsx}\"\n run: npx specbridge hook run --level commit --files {staged_files}\n`));\n return;\n } else {\n // Check for .husky directory\n if (await pathExists(join(cwd, '.husky'))) {\n hookPath = join(cwd, '.husky', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing husky pre-commit hook...';\n } else if (await pathExists(join(cwd, 'lefthook.yml'))) {\n spinner.succeed('Lefthook detected');\n console.log('');\n console.log(chalk.cyan('Add this to your lefthook.yml:'));\n console.log('');\n console.log(chalk.dim(`pre-commit:\n commands:\n specbridge:\n glob: \"*.{ts,tsx}\"\n run: npx specbridge hook run --level commit --files {staged_files}\n`));\n return;\n } else {\n // Default to .git/hooks\n hookPath = join(cwd, '.git', 'hooks', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing Git pre-commit hook...';\n }\n }\n\n // Check if hook already exists\n if (await pathExists(hookPath) && !options.force) {\n spinner.fail('Hook already exists');\n console.log(chalk.yellow(`Use --force to overwrite: ${hookPath}`));\n return;\n }\n\n // Write hook\n await writeTextFile(hookPath, hookContent);\n\n // Make executable (Unix)\n const { execSync } = await import('node:child_process');\n try {\n execSync(`chmod +x \"${hookPath}\"`, { stdio: 'ignore' });\n } catch {\n // Ignore on Windows\n }\n\n spinner.succeed('Pre-commit hook installed');\n console.log(chalk.dim(` Path: ${hookPath}`));\n console.log('');\n console.log(chalk.cyan('The hook will run on each commit and verify staged files.'));\n } catch (error) {\n spinner.fail('Failed to install hook');\n throw error;\n }\n });\n\n hookCommand\n .command('run')\n .description('Run verification (called by hook)')\n .option('-l, --level <level>', 'Verification level', 'commit')\n .option('-f, --files <files>', 'Space or comma-separated file list')\n .action(async (options: { level?: string; files?: string }) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n try {\n const config = await loadConfig(cwd);\n const level = (options.level || 'commit') as VerificationLevel;\n\n // Parse files\n let files = options.files\n ? options.files.split(/[\\s,]+/).filter(f => f.length > 0)\n : undefined;\n\n if (!files || files.length === 0) {\n // Auto-detect staged files\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileAsync = promisify(execFile);\n\n try {\n const { stdout } = await execFileAsync('git', ['diff', '--cached', '--name-only', '--diff-filter=AM'], { cwd });\n files = stdout\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((f) => /\\.(ts|tsx|js|jsx)$/.test(f));\n } catch {\n files = [];\n }\n }\n\n if (!files || files.length === 0) {\n process.exit(0);\n }\n\n // Run verification\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level,\n files,\n cwd,\n });\n\n // Output result\n if (result.violations.length === 0) {\n console.log(chalk.green('✓ SpecBridge: All checks passed'));\n process.exit(0);\n }\n\n // Print violations concisely\n console.log(chalk.red(`✗ SpecBridge: ${result.violations.length} violation(s) found`));\n console.log('');\n\n for (const v of result.violations) {\n const location = v.line ? `:${v.line}` : '';\n console.log(` ${v.file}${location}: ${v.message}`);\n console.log(chalk.dim(` [${v.severity}] ${v.decisionId}/${v.constraintId}`));\n }\n\n console.log('');\n console.log(chalk.yellow('Run `specbridge verify` for full details.'));\n\n process.exit(result.success ? 0 : 1);\n } catch (error) {\n console.error(chalk.red('SpecBridge verification failed'));\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n hookCommand\n .command('uninstall')\n .description('Remove Git pre-commit hook')\n .action(async () => {\n const cwd = process.cwd();\n const spinner = ora('Removing hook...').start();\n\n try {\n const hookPaths = [\n join(cwd, '.husky', 'pre-commit'),\n join(cwd, '.git', 'hooks', 'pre-commit'),\n ];\n\n let removed = false;\n for (const hookPath of hookPaths) {\n if (await pathExists(hookPath)) {\n const content = await readTextFile(hookPath);\n if (content.includes('SpecBridge')) {\n const { unlink } = await import('node:fs/promises');\n await unlink(hookPath);\n spinner.succeed(`Removed hook: ${hookPath}`);\n removed = true;\n }\n }\n }\n\n if (!removed) {\n spinner.info('No SpecBridge hooks found');\n }\n } catch (error) {\n spinner.fail('Failed to remove hook');\n throw error;\n }\n });\n\n return hookCommand;\n}\n\nexport const hookCommand = createHookCommand();\n","/**\n * Report command - Generate compliance reports\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { generateReport } from '../../reporting/reporter.js';\nimport { formatConsoleReport } from '../../reporting/formats/console.js';\nimport { formatMarkdownReport } from '../../reporting/formats/markdown.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, getReportsDir, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { ReportStorage } from '../../reporting/storage.js';\nimport { detectDrift, analyzeTrend } from '../../reporting/drift.js';\n\ninterface ReportOptions {\n format?: string;\n output?: string;\n save?: boolean;\n all?: boolean;\n trend?: boolean;\n drift?: boolean;\n days?: string;\n}\n\nexport const reportCommand = new Command('report')\n .description('Generate compliance report')\n .option('-f, --format <format>', 'Output format (console, json, markdown)', 'console')\n .option('-o, --output <file>', 'Output file path')\n .option('--save', 'Save to .specbridge/reports/')\n .option('-a, --all', 'Include all decisions (not just active)')\n .option('--trend', 'Show compliance trend over time')\n .option('--drift', 'Analyze drift since last report')\n .option('--days <n>', 'Number of days for trend analysis', '30')\n .action(async (options: ReportOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Generating compliance report...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Generate report\n const report = await generateReport(config, {\n includeAll: options.all,\n cwd,\n });\n\n spinner.succeed('Report generated');\n\n // Initialize report storage\n const storage = new ReportStorage(cwd);\n\n // Auto-save all reports to history\n await storage.save(report);\n\n // Handle trend analysis\n if (options.trend) {\n console.log('\\n' + chalk.blue.bold('=== Compliance Trend Analysis ===\\n'));\n\n const days = parseInt(options.days || '30', 10);\n const history = await storage.loadHistory(days);\n\n if (history.length < 2) {\n console.log(chalk.yellow(`Not enough data for trend analysis. Found ${history.length} report(s), need at least 2.`));\n } else {\n const trend = await analyzeTrend(history);\n\n console.log(chalk.bold(`Period: ${trend.period.start} to ${trend.period.end} (${trend.period.days} days)`));\n console.log(`\\nOverall Compliance: ${trend.overall.startCompliance}% → ${trend.overall.endCompliance}% (${trend.overall.change > 0 ? '+' : ''}${trend.overall.change.toFixed(1)}%)`);\n\n const trendEmoji = trend.overall.trend === 'improving' ? '📈' : trend.overall.trend === 'degrading' ? '📉' : '➡️';\n const trendColor = trend.overall.trend === 'improving' ? chalk.green : trend.overall.trend === 'degrading' ? chalk.red : chalk.yellow;\n console.log(trendColor(`${trendEmoji} Trend: ${trend.overall.trend.toUpperCase()}`));\n\n // Show top degraded decisions\n const degrading = trend.decisions.filter(d => d.trend === 'degrading').slice(0, 3);\n if (degrading.length > 0) {\n console.log(chalk.red('\\n⚠️ Most Degraded Decisions:'));\n degrading.forEach(d => {\n console.log(` • ${d.title}: ${d.startCompliance}% → ${d.endCompliance}% (${d.change.toFixed(1)}%)`);\n });\n }\n\n // Show top improved decisions\n const improving = trend.decisions.filter(d => d.trend === 'improving').slice(0, 3);\n if (improving.length > 0) {\n console.log(chalk.green('\\n✅ Most Improved Decisions:'));\n improving.forEach(d => {\n console.log(` • ${d.title}: ${d.startCompliance}% → ${d.endCompliance}% (+${d.change.toFixed(1)}%)`);\n });\n }\n }\n\n console.log(''); // Empty line\n }\n\n // Handle drift analysis\n if (options.drift) {\n console.log('\\n' + chalk.blue.bold('=== Drift Analysis ===\\n'));\n\n const history = await storage.loadHistory(2);\n\n if (history.length < 2) {\n console.log(chalk.yellow('Not enough data for drift analysis. Need at least 2 reports.'));\n } else {\n const currentEntry = history[0];\n const previousEntry = history[1];\n\n if (!currentEntry || !previousEntry) {\n console.log(chalk.yellow('Invalid history data.'));\n return;\n }\n\n const drift = await detectDrift(currentEntry.report, previousEntry.report);\n\n console.log(chalk.bold(`Comparing: ${previousEntry.timestamp} vs ${currentEntry.timestamp}`));\n console.log(`\\nCompliance Change: ${drift.complianceChange > 0 ? '+' : ''}${drift.complianceChange.toFixed(1)}%`);\n\n const driftEmoji = drift.trend === 'improving' ? '📈' : drift.trend === 'degrading' ? '📉' : '➡️';\n const driftColor = drift.trend === 'improving' ? chalk.green : drift.trend === 'degrading' ? chalk.red : chalk.yellow;\n console.log(driftColor(`${driftEmoji} Overall Trend: ${drift.trend.toUpperCase()}`));\n\n // Show violation changes\n if (drift.summary.newViolations.total > 0) {\n console.log(chalk.red(`\\n⚠️ New Violations: ${drift.summary.newViolations.total}`));\n if (drift.summary.newViolations.critical > 0) {\n console.log(` • Critical: ${drift.summary.newViolations.critical}`);\n }\n if (drift.summary.newViolations.high > 0) {\n console.log(` • High: ${drift.summary.newViolations.high}`);\n }\n if (drift.summary.newViolations.medium > 0) {\n console.log(` • Medium: ${drift.summary.newViolations.medium}`);\n }\n if (drift.summary.newViolations.low > 0) {\n console.log(` • Low: ${drift.summary.newViolations.low}`);\n }\n }\n\n if (drift.summary.fixedViolations.total > 0) {\n console.log(chalk.green(`\\n✅ Fixed Violations: ${drift.summary.fixedViolations.total}`));\n if (drift.summary.fixedViolations.critical > 0) {\n console.log(` • Critical: ${drift.summary.fixedViolations.critical}`);\n }\n if (drift.summary.fixedViolations.high > 0) {\n console.log(` • High: ${drift.summary.fixedViolations.high}`);\n }\n if (drift.summary.fixedViolations.medium > 0) {\n console.log(` • Medium: ${drift.summary.fixedViolations.medium}`);\n }\n if (drift.summary.fixedViolations.low > 0) {\n console.log(` • Low: ${drift.summary.fixedViolations.low}`);\n }\n }\n\n // Show most degraded decisions\n if (drift.mostDegraded.length > 0) {\n console.log(chalk.red('\\n📉 Most Degraded:'));\n drift.mostDegraded.forEach(d => {\n console.log(` • ${d.title}: ${d.previousCompliance}% → ${d.currentCompliance}% (${d.complianceChange.toFixed(1)}%)`);\n if (d.newViolations > 0) {\n console.log(` +${d.newViolations} new violation(s)`);\n }\n });\n }\n\n // Show most improved decisions\n if (drift.mostImproved.length > 0) {\n console.log(chalk.green('\\n📈 Most Improved:'));\n drift.mostImproved.forEach(d => {\n console.log(` • ${d.title}: ${d.previousCompliance}% → ${d.currentCompliance}% (+${d.complianceChange.toFixed(1)}%)`);\n if (d.fixedViolations > 0) {\n console.log(` -${d.fixedViolations} fixed violation(s)`);\n }\n });\n }\n }\n\n console.log(''); // Empty line\n }\n\n // Format output\n let output: string;\n let extension: string;\n\n switch (options.format) {\n case 'json':\n output = JSON.stringify(report, null, 2);\n extension = 'json';\n break;\n case 'markdown':\n case 'md':\n output = formatMarkdownReport(report);\n extension = 'md';\n break;\n case 'console':\n default:\n output = formatConsoleReport(report);\n extension = 'txt';\n break;\n }\n\n // Output to console (skip if drift/trend already shown)\n if (!options.trend && !options.drift) {\n if (options.format !== 'json' || !options.output) {\n console.log(output);\n }\n }\n\n // Save to file\n if (options.output || options.save) {\n const outputPath = options.output || join(\n getReportsDir(cwd),\n `health-${new Date().toISOString().split('T')[0]}.${extension}`\n );\n\n await writeTextFile(outputPath, output);\n console.log(chalk.green(`\\nReport saved to: ${outputPath}`));\n\n // Also save latest\n if (options.save && !options.output) {\n const latestPath = join(getReportsDir(cwd), `health-latest.${extension}`);\n await writeTextFile(latestPath, output);\n }\n }\n } catch (error) {\n spinner.fail('Failed to generate report');\n throw error;\n }\n });\n","/**\n * Compliance reporter\n */\nimport type {\n ComplianceReport,\n DecisionCompliance,\n SpecBridgeConfig,\n} from '../core/types/index.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { createVerificationEngine } from '../verification/engine.js';\n\nexport interface ReportOptions {\n includeAll?: boolean;\n cwd?: string;\n}\n\n/**\n * Generate a compliance report\n */\nexport async function generateReport(\n config: SpecBridgeConfig,\n options: ReportOptions = {}\n): Promise<ComplianceReport> {\n const { includeAll = false, cwd = process.cwd() } = options;\n\n // Load registry\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n\n // Run full verification\n const engine = createVerificationEngine(registry);\n const result = await engine.verify(config, { level: 'full', cwd });\n\n // Get all decisions\n const decisions = includeAll ? registry.getAll() : registry.getActive();\n\n // Calculate per-decision compliance\n const byDecision: DecisionCompliance[] = [];\n\n for (const decision of decisions) {\n const decisionViolations = result.violations.filter(\n v => v.decisionId === decision.metadata.id\n );\n\n const constraintCount = decision.constraints.length;\n const violationCount = decisionViolations.length;\n\n // Simple compliance calculation\n // In a real system, this would be based on files checked\n const compliance = violationCount === 0\n ? 100\n : Math.max(0, 100 - Math.min(violationCount * 10, 100));\n\n byDecision.push({\n decisionId: decision.metadata.id,\n title: decision.metadata.title,\n status: decision.metadata.status,\n constraints: constraintCount,\n violations: violationCount,\n compliance,\n });\n }\n\n // Sort by compliance (lowest first to highlight problems)\n byDecision.sort((a, b) => a.compliance - b.compliance);\n\n // Calculate summary\n const totalDecisions = decisions.length;\n const activeDecisions = decisions.filter(d => d.metadata.status === 'active').length;\n const totalConstraints = decisions.reduce((sum, d) => sum + d.constraints.length, 0);\n\n const violationsBySeverity = {\n critical: result.violations.filter(v => v.severity === 'critical').length,\n high: result.violations.filter(v => v.severity === 'high').length,\n medium: result.violations.filter(v => v.severity === 'medium').length,\n low: result.violations.filter(v => v.severity === 'low').length,\n };\n\n // Overall compliance score\n const overallCompliance = byDecision.length > 0\n ? Math.round(byDecision.reduce((sum, d) => sum + d.compliance, 0) / byDecision.length)\n : 100;\n\n return {\n timestamp: new Date().toISOString(),\n project: config.project.name,\n summary: {\n totalDecisions,\n activeDecisions,\n totalConstraints,\n violations: violationsBySeverity,\n compliance: overallCompliance,\n },\n byDecision,\n };\n}\n\n/**\n * Check if compliance has degraded from previous report\n */\nexport function checkDegradation(\n current: ComplianceReport,\n previous: ComplianceReport | null\n): { degraded: boolean; details: string[] } {\n if (!previous) {\n return { degraded: false, details: [] };\n }\n\n const details: string[] = [];\n let degraded = false;\n\n // Check overall compliance\n if (current.summary.compliance < previous.summary.compliance) {\n degraded = true;\n details.push(\n `Overall compliance dropped from ${previous.summary.compliance}% to ${current.summary.compliance}%`\n );\n }\n\n // Check for new critical/high violations\n const newCritical = current.summary.violations.critical - previous.summary.violations.critical;\n const newHigh = current.summary.violations.high - previous.summary.violations.high;\n\n if (newCritical > 0) {\n degraded = true;\n details.push(`${newCritical} new critical violation(s)`);\n }\n\n if (newHigh > 0) {\n degraded = true;\n details.push(`${newHigh} new high severity violation(s)`);\n }\n\n return { degraded, details };\n}\n\n/**\n * Reporter class for formatting verification results\n */\nexport class Reporter {\n /**\n * Generate formatted report from verification result\n */\n generate(\n result: any,\n options: {\n format?: 'table' | 'json' | 'markdown';\n includePassedChecks?: boolean;\n groupBy?: 'severity' | 'file';\n colorize?: boolean;\n } = {}\n ): string {\n const { format = 'table', groupBy } = options;\n\n switch (format) {\n case 'json':\n return JSON.stringify(result, null, 2);\n\n case 'markdown':\n return this.formatAsMarkdown(result);\n\n case 'table':\n default:\n return groupBy ? this.formatAsTableGrouped(result, groupBy) : this.formatAsTable(result);\n }\n }\n\n /**\n * Generate compliance overview from multiple results\n */\n generateComplianceReport(results: any[]): string {\n const lines: string[] = [];\n lines.push('# Compliance Report\\n');\n\n if (results.length === 0) {\n lines.push('No results to report.\\n');\n return lines.join('\\n');\n }\n\n // Calculate overall stats\n const totalViolations = results.reduce(\n (sum, r) => sum + (r.summary?.totalViolations || r.violations?.length || 0),\n 0\n );\n const avgViolations = totalViolations / results.length;\n\n lines.push(`## Overall Statistics\\n`);\n lines.push(`- Total Results: ${results.length}`);\n lines.push(`- Total Violations: ${totalViolations}`);\n lines.push(`- Average Violations per Result: ${avgViolations.toFixed(1)}`);\n\n // Calculate compliance percentage (simplified)\n const complianceRate = results.length > 0\n ? ((results.filter(r => (r.violations?.length || 0) === 0).length / results.length) * 100)\n : 100;\n lines.push(`- Compliance Rate: ${complianceRate.toFixed(1)}%\\n`);\n\n return lines.join('\\n');\n }\n\n private formatAsTable(result: any): string {\n const lines: string[] = [];\n\n lines.push('Verification Report');\n lines.push('='.repeat(50));\n lines.push('');\n\n // Summary\n if (result.summary) {\n lines.push('Summary:');\n lines.push(` Decisions Checked: ${result.summary.decisionsChecked || 0}`);\n lines.push(` Files Checked: ${result.summary.filesChecked || 0}`);\n lines.push(` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`);\n lines.push(` Critical: ${result.summary.critical || 0}`);\n lines.push(` High: ${result.summary.high || 0}`);\n lines.push(` Medium: ${result.summary.medium || 0}`);\n lines.push(` Low: ${result.summary.low || 0}`);\n lines.push(` Duration: ${result.summary.duration || 0}ms`);\n lines.push('');\n }\n\n // Violations\n const totalViolations = result.summary?.totalViolations ?? result.violations?.length ?? 0;\n if (totalViolations > 0 && result.violations && result.violations.length > 0) {\n lines.push('Violations:');\n lines.push('-'.repeat(50));\n\n result.violations.forEach((v: any) => {\n const severity = v.severity.toLowerCase();\n lines.push(` [${v.severity.toUpperCase()}] ${v.decisionId} - ${v.constraintId} (${severity})`);\n lines.push(` ${v.message}`);\n lines.push(` Location: ${v.location?.file || v.file}:${v.location?.line || 0}:${v.location?.column || 0}`);\n lines.push('');\n });\n } else {\n lines.push('No violations found.');\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private formatAsTableGrouped(result: any, groupBy: 'severity' | 'file'): string {\n const lines: string[] = [];\n\n lines.push('Verification Report');\n lines.push('='.repeat(50));\n lines.push('');\n\n // Summary\n if (result.summary) {\n lines.push('Summary:');\n lines.push(` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`);\n lines.push('');\n }\n\n // Group violations\n if (result.violations && result.violations.length > 0) {\n if (groupBy === 'severity') {\n const grouped = new Map<string, any[]>();\n result.violations.forEach((v: any) => {\n const key = v.severity;\n if (!grouped.has(key)) grouped.set(key, []);\n grouped.get(key)!.push(v);\n });\n\n for (const [severity, violations] of grouped.entries()) {\n lines.push(`Severity: ${severity}`);\n lines.push('-'.repeat(30));\n violations.forEach(v => {\n lines.push(` ${v.decisionId} - ${v.message}`);\n });\n lines.push('');\n }\n } else if (groupBy === 'file') {\n const grouped = new Map<string, any[]>();\n result.violations.forEach((v: any) => {\n const key = v.location?.file || v.file || 'unknown';\n if (!grouped.has(key)) grouped.set(key, []);\n grouped.get(key)!.push(v);\n });\n\n for (const [file, violations] of grouped.entries()) {\n lines.push(`File: ${file}`);\n lines.push('-'.repeat(30));\n violations.forEach(v => {\n lines.push(` [${v.severity}] ${v.message}`);\n });\n lines.push('');\n }\n }\n } else {\n lines.push('No violations found.');\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private formatAsMarkdown(result: any): string {\n const lines: string[] = [];\n\n lines.push('## Verification Report\\n');\n\n // Summary\n if (result.summary) {\n lines.push('### Summary\\n');\n lines.push(`- **Decisions Checked:** ${result.summary.decisionsChecked || 0}`);\n lines.push(`- **Files Checked:** ${result.summary.filesChecked || 0}`);\n lines.push(`- **Total Violations:** ${result.summary.totalViolations || result.violations?.length || 0}`);\n lines.push(`- **Critical:** ${result.summary.critical || 0}`);\n lines.push(`- **High:** ${result.summary.high || 0}`);\n lines.push(`- **Medium:** ${result.summary.medium || 0}`);\n lines.push(`- **Low:** ${result.summary.low || 0}\\n`);\n }\n\n // Violations\n if (result.violations && result.violations.length > 0) {\n lines.push('### Violations\\n');\n\n result.violations.forEach((v: any) => {\n lines.push(`#### [${v.severity.toUpperCase()}] ${v.decisionId}`);\n lines.push(`**Message:** ${v.message}`);\n lines.push(`**Location:** \\`${v.location?.file || v.file}:${v.location?.line || 0}\\`\\n`);\n });\n } else {\n lines.push('No violations found.\\n');\n }\n\n return lines.join('\\n');\n }\n}\n","/**\n * Console output format for reports\n */\nimport chalk from 'chalk';\nimport { table } from 'table';\nimport type { ComplianceReport } from '../../core/types/index.js';\n\n/**\n * Format report for console output\n */\nexport function formatConsoleReport(report: ComplianceReport): string {\n const lines: string[] = [];\n\n // Header\n lines.push('');\n lines.push(chalk.bold.blue('SpecBridge Compliance Report'));\n lines.push(chalk.dim(`Generated: ${new Date(report.timestamp).toLocaleString()}`));\n lines.push(chalk.dim(`Project: ${report.project}`));\n lines.push('');\n\n // Overall compliance\n const complianceColor = getComplianceColor(report.summary.compliance);\n lines.push(chalk.bold('Overall Compliance'));\n lines.push(` ${complianceColor(formatComplianceBar(report.summary.compliance))} ${complianceColor(`${report.summary.compliance}%`)}`);\n lines.push('');\n\n // Summary stats\n lines.push(chalk.bold('Summary'));\n lines.push(` Decisions: ${report.summary.activeDecisions} active / ${report.summary.totalDecisions} total`);\n lines.push(` Constraints: ${report.summary.totalConstraints}`);\n lines.push('');\n\n // Violations\n lines.push(chalk.bold('Violations'));\n const { violations } = report.summary;\n const violationParts: string[] = [];\n\n if (violations.critical > 0) {\n violationParts.push(chalk.red(`${violations.critical} critical`));\n }\n if (violations.high > 0) {\n violationParts.push(chalk.yellow(`${violations.high} high`));\n }\n if (violations.medium > 0) {\n violationParts.push(chalk.cyan(`${violations.medium} medium`));\n }\n if (violations.low > 0) {\n violationParts.push(chalk.dim(`${violations.low} low`));\n }\n\n if (violationParts.length > 0) {\n lines.push(` ${violationParts.join(' | ')}`);\n } else {\n lines.push(chalk.green(' No violations'));\n }\n lines.push('');\n\n // Per-decision breakdown\n if (report.byDecision.length > 0) {\n lines.push(chalk.bold('By Decision'));\n lines.push('');\n\n const tableData: string[][] = [\n [\n chalk.bold('Decision'),\n chalk.bold('Status'),\n chalk.bold('Constraints'),\n chalk.bold('Violations'),\n chalk.bold('Compliance'),\n ],\n ];\n\n for (const dec of report.byDecision) {\n const compColor = getComplianceColor(dec.compliance);\n const statusColor = getStatusColor(dec.status);\n\n tableData.push([\n truncate(dec.title, 40),\n statusColor(dec.status),\n String(dec.constraints),\n dec.violations > 0 ? chalk.red(String(dec.violations)) : chalk.green('0'),\n compColor(`${dec.compliance}%`),\n ]);\n }\n\n const tableOutput = table(tableData, {\n border: {\n topBody: '',\n topJoin: '',\n topLeft: '',\n topRight: '',\n bottomBody: '',\n bottomJoin: '',\n bottomLeft: '',\n bottomRight: '',\n bodyLeft: ' ',\n bodyRight: '',\n bodyJoin: ' ',\n joinBody: '',\n joinLeft: '',\n joinRight: '',\n joinJoin: '',\n },\n drawHorizontalLine: (index) => index === 1,\n });\n\n lines.push(tableOutput);\n }\n\n return lines.join('\\n');\n}\n\nfunction formatComplianceBar(compliance: number): string {\n const filled = Math.round(compliance / 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n}\n\nfunction getComplianceColor(compliance: number): (text: string) => string {\n if (compliance >= 90) return chalk.green;\n if (compliance >= 70) return chalk.yellow;\n if (compliance >= 50) return chalk.hex('#FFA500');\n return chalk.red;\n}\n\nfunction getStatusColor(status: string): (text: string) => string {\n switch (status) {\n case 'active':\n return chalk.green;\n case 'draft':\n return chalk.yellow;\n case 'deprecated':\n return chalk.gray;\n case 'superseded':\n return chalk.blue;\n default:\n return chalk.white;\n }\n}\n\nfunction truncate(str: string, length: number): string {\n if (str.length <= length) return str;\n return str.slice(0, length - 3) + '...';\n}\n","/**\n * Markdown format for reports\n */\nimport type { ComplianceReport } from '../../core/types/index.js';\n\n/**\n * Format report as Markdown\n */\nexport function formatMarkdownReport(report: ComplianceReport): string {\n const lines: string[] = [];\n\n // Header\n lines.push('# SpecBridge Compliance Report');\n lines.push('');\n lines.push(`**Project:** ${report.project}`);\n lines.push(`**Generated:** ${new Date(report.timestamp).toLocaleString()}`);\n lines.push('');\n\n // Overall compliance\n lines.push('## Overall Compliance');\n lines.push('');\n lines.push(`**Score:** ${report.summary.compliance}%`);\n lines.push('');\n lines.push(formatProgressBar(report.summary.compliance));\n lines.push('');\n\n // Summary\n lines.push('## Summary');\n lines.push('');\n lines.push(`- **Active Decisions:** ${report.summary.activeDecisions} / ${report.summary.totalDecisions}`);\n lines.push(`- **Total Constraints:** ${report.summary.totalConstraints}`);\n lines.push('');\n\n // Violations\n lines.push('### Violations');\n lines.push('');\n const { violations } = report.summary;\n const totalViolations = violations.critical + violations.high + violations.medium + violations.low;\n\n if (totalViolations === 0) {\n lines.push('No violations found.');\n } else {\n lines.push(`| Severity | Count |`);\n lines.push(`|----------|-------|`);\n lines.push(`| Critical | ${violations.critical} |`);\n lines.push(`| High | ${violations.high} |`);\n lines.push(`| Medium | ${violations.medium} |`);\n lines.push(`| Low | ${violations.low} |`);\n lines.push(`| **Total** | **${totalViolations}** |`);\n }\n lines.push('');\n\n // By Decision\n if (report.byDecision.length > 0) {\n lines.push('## By Decision');\n lines.push('');\n lines.push('| Decision | Status | Constraints | Violations | Compliance |');\n lines.push('|----------|--------|-------------|------------|------------|');\n\n for (const dec of report.byDecision) {\n const complianceEmoji = dec.compliance >= 90 ? '✅' : dec.compliance >= 70 ? '⚠️' : '❌';\n lines.push(\n `| ${dec.title} | ${dec.status} | ${dec.constraints} | ${dec.violations} | ${complianceEmoji} ${dec.compliance}% |`\n );\n }\n lines.push('');\n }\n\n // Footer\n lines.push('---');\n lines.push('');\n lines.push('*Generated by [SpecBridge](https://github.com/nouatzi/specbridge)*');\n\n return lines.join('\\n');\n}\n\nfunction formatProgressBar(percentage: number): string {\n const width = 20;\n const filled = Math.round((percentage / 100) * width);\n const empty = width - filled;\n const filledChar = '█';\n const emptyChar = '░';\n\n return `\\`${filledChar.repeat(filled)}${emptyChar.repeat(empty)}\\` ${percentage}%`;\n}\n","/**\n * Report storage - Save and load historical compliance reports\n */\nimport { join } from 'node:path';\nimport type { ComplianceReport } from '../core/types/index.js';\nimport {\n ensureDir,\n writeTextFile,\n readTextFile,\n readFilesInDir,\n pathExists,\n getSpecBridgeDir,\n} from '../utils/fs.js';\n\nexport interface StoredReport {\n timestamp: string;\n report: ComplianceReport;\n}\n\n/**\n * ReportStorage - Handles persistence and retrieval of historical reports\n */\nexport class ReportStorage {\n private storageDir: string;\n\n constructor(basePath: string) {\n this.storageDir = join(getSpecBridgeDir(basePath), 'reports', 'history');\n }\n\n /**\n * Save a compliance report to storage\n */\n async save(report: ComplianceReport): Promise<string> {\n await ensureDir(this.storageDir);\n\n // Use date as filename (one report per day, overwrites if exists)\n const date = new Date(report.timestamp).toISOString().split('T')[0];\n const filename = `report-${date}.json`;\n const filepath = join(this.storageDir, filename);\n\n await writeTextFile(filepath, JSON.stringify(report, null, 2));\n\n return filepath;\n }\n\n /**\n * Load the most recent report\n */\n async loadLatest(): Promise<StoredReport | null> {\n if (!await pathExists(this.storageDir)) {\n return null;\n }\n\n const files = await readFilesInDir(this.storageDir);\n if (files.length === 0) {\n return null;\n }\n\n // Sort files by date (descending)\n const sortedFiles = files\n .filter(f => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n if (sortedFiles.length === 0) {\n return null;\n }\n\n const latestFile = sortedFiles[0];\n if (!latestFile) {\n return null;\n }\n\n const content = await readTextFile(join(this.storageDir, latestFile));\n const report = JSON.parse(content) as ComplianceReport;\n\n return {\n timestamp: latestFile.replace('report-', '').replace('.json', ''),\n report,\n };\n }\n\n /**\n * Load historical reports for the specified number of days\n */\n async loadHistory(days: number = 30): Promise<StoredReport[]> {\n if (!await pathExists(this.storageDir)) {\n return [];\n }\n\n const files = await readFilesInDir(this.storageDir);\n\n // Filter report files and sort by date\n const reportFiles = files\n .filter(f => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse(); // Most recent first\n\n // Take only the requested number of days\n const recentFiles = reportFiles.slice(0, days);\n\n // Load all reports\n const reports: StoredReport[] = [];\n for (const file of recentFiles) {\n try {\n const content = await readTextFile(join(this.storageDir, file));\n const report = JSON.parse(content) as ComplianceReport;\n const timestamp = file.replace('report-', '').replace('.json', '');\n\n reports.push({ timestamp, report });\n } catch (error) {\n // Skip corrupted files\n console.warn(`Warning: Failed to load report ${file}:`, error);\n }\n }\n\n return reports;\n }\n\n /**\n * Load a specific report by date\n */\n async loadByDate(date: string): Promise<ComplianceReport | null> {\n const filepath = join(this.storageDir, `report-${date}.json`);\n\n if (!await pathExists(filepath)) {\n return null;\n }\n\n const content = await readTextFile(filepath);\n return JSON.parse(content) as ComplianceReport;\n }\n\n /**\n * Get all available report dates\n */\n async getAvailableDates(): Promise<string[]> {\n if (!await pathExists(this.storageDir)) {\n return [];\n }\n\n const files = await readFilesInDir(this.storageDir);\n\n return files\n .filter(f => f.startsWith('report-') && f.endsWith('.json'))\n .map(f => f.replace('report-', '').replace('.json', ''))\n .sort()\n .reverse();\n }\n\n /**\n * Clear old reports (keep only the most recent N days)\n */\n async cleanup(keepDays: number = 90): Promise<number> {\n if (!await pathExists(this.storageDir)) {\n return 0;\n }\n\n const files = await readFilesInDir(this.storageDir);\n const reportFiles = files\n .filter(f => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n // Delete files beyond the keep limit\n const filesToDelete = reportFiles.slice(keepDays);\n\n for (const file of filesToDelete) {\n try {\n const filepath = join(this.storageDir, file);\n const fs = await import('node:fs/promises');\n await fs.unlink(filepath);\n } catch (error) {\n console.warn(`Warning: Failed to delete old report ${file}:`, error);\n }\n }\n\n return filesToDelete.length;\n }\n}\n","/**\n * Drift detection - Analyze compliance trends between reports\n */\nimport type { ComplianceReport, DecisionCompliance } from '../core/types/index.js';\n\nexport type TrendDirection = 'improving' | 'stable' | 'degrading';\n\nexport interface DriftAnalysis {\n decisionId: string;\n title: string;\n trend: TrendDirection;\n complianceChange: number; // percentage points\n newViolations: number;\n fixedViolations: number;\n currentCompliance: number;\n previousCompliance: number;\n}\n\nexport interface OverallDrift {\n trend: TrendDirection;\n complianceChange: number;\n summary: {\n newViolations: {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n };\n fixedViolations: {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n };\n };\n byDecision: DriftAnalysis[];\n mostImproved: DriftAnalysis[];\n mostDegraded: DriftAnalysis[];\n}\n\n/**\n * Detect drift between current and previous compliance reports\n */\nexport async function detectDrift(\n current: ComplianceReport,\n previous: ComplianceReport\n): Promise<OverallDrift> {\n const byDecision: DriftAnalysis[] = [];\n\n // Analyze per-decision drift\n for (const currDecision of current.byDecision) {\n const prevDecision = previous.byDecision.find(\n d => d.decisionId === currDecision.decisionId\n );\n\n if (!prevDecision) {\n // New decision - treat as stable for now\n byDecision.push({\n decisionId: currDecision.decisionId,\n title: currDecision.title,\n trend: 'stable',\n complianceChange: 0,\n newViolations: currDecision.violations,\n fixedViolations: 0,\n currentCompliance: currDecision.compliance,\n previousCompliance: currDecision.compliance,\n });\n continue;\n }\n\n const complianceChange = currDecision.compliance - prevDecision.compliance;\n const violationDiff = currDecision.violations - prevDecision.violations;\n\n // Determine trend with threshold\n let trend: TrendDirection;\n if (complianceChange > 5) {\n trend = 'improving';\n } else if (complianceChange < -5) {\n trend = 'degrading';\n } else {\n trend = 'stable';\n }\n\n byDecision.push({\n decisionId: currDecision.decisionId,\n title: currDecision.title,\n trend,\n complianceChange,\n newViolations: Math.max(0, violationDiff),\n fixedViolations: Math.max(0, -violationDiff),\n currentCompliance: currDecision.compliance,\n previousCompliance: prevDecision.compliance,\n });\n }\n\n // Calculate overall drift\n const overallComplianceChange = current.summary.compliance - previous.summary.compliance;\n\n let overallTrend: TrendDirection;\n if (overallComplianceChange > 5) {\n overallTrend = 'improving';\n } else if (overallComplianceChange < -5) {\n overallTrend = 'degrading';\n } else {\n overallTrend = 'stable';\n }\n\n // Calculate violation changes by severity\n const newViolations = {\n critical: Math.max(\n 0,\n current.summary.violations.critical - previous.summary.violations.critical\n ),\n high: Math.max(0, current.summary.violations.high - previous.summary.violations.high),\n medium: Math.max(0, current.summary.violations.medium - previous.summary.violations.medium),\n low: Math.max(0, current.summary.violations.low - previous.summary.violations.low),\n total: 0,\n };\n newViolations.total =\n newViolations.critical + newViolations.high + newViolations.medium + newViolations.low;\n\n const fixedViolations = {\n critical: Math.max(\n 0,\n previous.summary.violations.critical - current.summary.violations.critical\n ),\n high: Math.max(0, previous.summary.violations.high - current.summary.violations.high),\n medium: Math.max(0, previous.summary.violations.medium - current.summary.violations.medium),\n low: Math.max(0, previous.summary.violations.low - current.summary.violations.low),\n total: 0,\n };\n fixedViolations.total =\n fixedViolations.critical +\n fixedViolations.high +\n fixedViolations.medium +\n fixedViolations.low;\n\n // Find most improved and most degraded\n const improving = byDecision.filter(d => d.trend === 'improving');\n const degrading = byDecision.filter(d => d.trend === 'degrading');\n\n const mostImproved = improving.sort((a, b) => b.complianceChange - a.complianceChange).slice(0, 5);\n const mostDegraded = degrading.sort((a, b) => a.complianceChange - b.complianceChange).slice(0, 5);\n\n return {\n trend: overallTrend,\n complianceChange: overallComplianceChange,\n summary: {\n newViolations,\n fixedViolations,\n },\n byDecision,\n mostImproved,\n mostDegraded,\n };\n}\n\n/**\n * Analyze compliance trend over multiple reports\n */\nexport interface TrendAnalysis {\n period: {\n start: string;\n end: string;\n days: number;\n };\n overall: {\n startCompliance: number;\n endCompliance: number;\n change: number;\n trend: TrendDirection;\n dataPoints: Array<{ date: string; compliance: number }>;\n };\n decisions: Array<{\n decisionId: string;\n title: string;\n startCompliance: number;\n endCompliance: number;\n change: number;\n trend: TrendDirection;\n dataPoints: Array<{ date: string; compliance: number }>;\n }>;\n}\n\nexport async function analyzeTrend(\n reports: Array<{ timestamp: string; report: ComplianceReport }>\n): Promise<TrendAnalysis> {\n if (reports.length === 0) {\n throw new Error('No reports provided for trend analysis');\n }\n\n // Sort by timestamp (oldest first)\n const sortedReports = reports.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n\n const firstReport = sortedReports[0]?.report;\n const lastReport = sortedReports[sortedReports.length - 1]?.report;\n\n if (!firstReport || !lastReport) {\n throw new Error('Invalid reports data');\n }\n\n // Overall trend\n const overallChange = lastReport.summary.compliance - firstReport.summary.compliance;\n let overallTrend: TrendDirection;\n if (overallChange > 5) {\n overallTrend = 'improving';\n } else if (overallChange < -5) {\n overallTrend = 'degrading';\n } else {\n overallTrend = 'stable';\n }\n\n const overallDataPoints = sortedReports.map(r => ({\n date: r.timestamp,\n compliance: r.report.summary.compliance,\n }));\n\n // Per-decision trends\n const decisionMap = new Map<string, DecisionCompliance[]>();\n\n for (const { report } of sortedReports) {\n for (const decision of report.byDecision) {\n if (!decisionMap.has(decision.decisionId)) {\n decisionMap.set(decision.decisionId, []);\n }\n decisionMap.get(decision.decisionId)!.push(decision);\n }\n }\n\n const decisions = Array.from(decisionMap.entries()).map(([decisionId, data]) => {\n const first = data[0];\n const last = data[data.length - 1];\n\n if (!first || !last) {\n throw new Error(`Invalid decision data for ${decisionId}`);\n }\n\n const change = last.compliance - first.compliance;\n\n let trend: TrendDirection;\n if (change > 5) {\n trend = 'improving';\n } else if (change < -5) {\n trend = 'degrading';\n } else {\n trend = 'stable';\n }\n\n const dataPoints = sortedReports.map(r => {\n const decision = r.report.byDecision.find(d => d.decisionId === decisionId);\n return {\n date: r.timestamp,\n compliance: decision?.compliance ?? 0,\n };\n });\n\n return {\n decisionId,\n title: last.title,\n startCompliance: first.compliance,\n endCompliance: last.compliance,\n change,\n trend,\n dataPoints,\n };\n });\n\n const firstTimestamp = sortedReports[0]?.timestamp;\n const lastTimestamp = sortedReports[sortedReports.length - 1]?.timestamp;\n\n if (!firstTimestamp || !lastTimestamp) {\n throw new Error('Invalid report timestamps');\n }\n\n return {\n period: {\n start: firstTimestamp,\n end: lastTimestamp,\n days: sortedReports.length,\n },\n overall: {\n startCompliance: firstReport.summary.compliance,\n endCompliance: lastReport.summary.compliance,\n change: overallChange,\n trend: overallTrend,\n dataPoints: overallDataPoints,\n },\n decisions,\n };\n}\n","/**\n * Context command - Generate agent context\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { generateFormattedContext } from '../../agent/context.generator.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface ContextOptions {\n format?: string;\n output?: string;\n rationale?: boolean;\n}\n\nexport const contextCommand = new Command('context')\n .description('Generate architectural context for a file (for AI agents)')\n .argument('<file>', 'File path to generate context for')\n .option('-f, --format <format>', 'Output format (markdown, json, mcp)', 'markdown')\n .option('-o, --output <file>', 'Output file path')\n .option('--no-rationale', 'Exclude rationale/summary from output')\n .action(async (file: string, options: ContextOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Generate context\n const output = await generateFormattedContext(file, config, {\n format: options.format as 'markdown' | 'json' | 'mcp',\n includeRationale: options.rationale !== false,\n cwd,\n });\n\n // Output\n if (options.output) {\n await writeTextFile(options.output, output);\n console.log(chalk.green(`Context saved to: ${options.output}`));\n } else {\n console.log(output);\n }\n } catch (error) {\n console.error(chalk.red('Failed to generate context'));\n throw error;\n }\n });\n","/**\n * Agent context generator\n */\nimport type {\n AgentContext,\n ApplicableDecision,\n ApplicableConstraint,\n SpecBridgeConfig,\n} from '../core/types/index.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface ContextOptions {\n includeRationale?: boolean;\n format?: 'markdown' | 'json' | 'mcp';\n cwd?: string;\n}\n\n/**\n * Generate agent context for a file\n */\nexport async function generateContext(\n filePath: string,\n config: SpecBridgeConfig,\n options: ContextOptions = {}\n): Promise<AgentContext> {\n const { includeRationale = config.agent?.includeRationale ?? true, cwd = process.cwd() } = options;\n\n // Load registry\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n\n // Get active decisions\n const decisions = registry.getActive();\n\n // Find applicable decisions and constraints\n const applicableDecisions: ApplicableDecision[] = [];\n\n for (const decision of decisions) {\n const applicableConstraints: ApplicableConstraint[] = [];\n\n for (const constraint of decision.constraints) {\n if (matchesPattern(filePath, constraint.scope)) {\n applicableConstraints.push({\n id: constraint.id,\n type: constraint.type,\n rule: constraint.rule,\n severity: constraint.severity,\n });\n }\n }\n\n if (applicableConstraints.length > 0) {\n applicableDecisions.push({\n id: decision.metadata.id,\n title: decision.metadata.title,\n summary: includeRationale ? decision.decision.summary : '',\n constraints: applicableConstraints,\n });\n }\n }\n\n return {\n file: filePath,\n applicableDecisions,\n generatedAt: new Date().toISOString(),\n };\n}\n\n/**\n * Format context as Markdown for agent prompts\n */\nexport function formatContextAsMarkdown(context: AgentContext): string {\n const lines: string[] = [];\n\n lines.push('# Architectural Constraints');\n lines.push('');\n lines.push(`File: \\`${context.file}\\``);\n lines.push('');\n\n if (context.applicableDecisions.length === 0) {\n lines.push('No specific architectural constraints apply to this file.');\n return lines.join('\\n');\n }\n\n lines.push('The following architectural decisions apply to this file:');\n lines.push('');\n\n for (const decision of context.applicableDecisions) {\n lines.push(`## ${decision.title}`);\n lines.push('');\n\n if (decision.summary) {\n lines.push(decision.summary);\n lines.push('');\n }\n\n lines.push('### Constraints');\n lines.push('');\n\n for (const constraint of decision.constraints) {\n const typeEmoji = constraint.type === 'invariant' ? '🔒' :\n constraint.type === 'convention' ? '📋' : '💡';\n const severityBadge = `[${constraint.severity.toUpperCase()}]`;\n\n lines.push(`- ${typeEmoji} **${severityBadge}** ${constraint.rule}`);\n }\n\n lines.push('');\n }\n\n lines.push('---');\n lines.push('');\n lines.push('Please ensure your code complies with these constraints.');\n\n return lines.join('\\n');\n}\n\n/**\n * Format context as JSON\n */\nexport function formatContextAsJson(context: AgentContext): string {\n return JSON.stringify(context, null, 2);\n}\n\n/**\n * Format context for MCP (Model Context Protocol)\n */\nexport function formatContextAsMcp(context: AgentContext): object {\n return {\n type: 'architectural_context',\n version: '1.0',\n file: context.file,\n timestamp: context.generatedAt,\n decisions: context.applicableDecisions.map(d => ({\n id: d.id,\n title: d.title,\n summary: d.summary,\n constraints: d.constraints.map(c => ({\n id: c.id,\n type: c.type,\n severity: c.severity,\n rule: c.rule,\n })),\n })),\n };\n}\n\n/**\n * Generate context in specified format\n */\nexport async function generateFormattedContext(\n filePath: string,\n config: SpecBridgeConfig,\n options: ContextOptions = {}\n): Promise<string> {\n const context = await generateContext(filePath, config, options);\n const format = options.format || config.agent?.format || 'markdown';\n\n switch (format) {\n case 'json':\n return formatContextAsJson(context);\n case 'mcp':\n return JSON.stringify(formatContextAsMcp(context), null, 2);\n case 'markdown':\n default:\n return formatContextAsMarkdown(context);\n }\n}\n\n/**\n * AgentContextGenerator class for test compatibility\n */\nexport class AgentContextGenerator {\n /**\n * Generate context from decisions\n */\n generateContext(options: {\n decisions: any[];\n filePattern?: string;\n format?: 'markdown' | 'plain' | 'json';\n concise?: boolean;\n minSeverity?: string;\n includeExamples?: boolean;\n }): string {\n const { decisions, filePattern, format = 'markdown', concise = false, minSeverity } = options;\n\n // Filter deprecated decisions\n const activeDecisions = decisions.filter(d => d.metadata.status !== 'deprecated');\n\n // Filter by file pattern if provided\n let filteredDecisions = activeDecisions;\n if (filePattern) {\n filteredDecisions = activeDecisions.filter(d =>\n d.constraints.some((c: any) => matchesPattern(filePattern, c.scope))\n );\n }\n\n // Filter by severity if provided\n if (minSeverity) {\n const severityOrder = { low: 0, medium: 1, high: 2, critical: 3 };\n const minLevel = severityOrder[minSeverity as keyof typeof severityOrder] || 0;\n\n filteredDecisions = filteredDecisions.map(d => ({\n ...d,\n constraints: d.constraints.filter((c: any) => {\n const level = severityOrder[c.severity as keyof typeof severityOrder] || 0;\n return level >= minLevel;\n }),\n })).filter(d => d.constraints.length > 0);\n }\n\n // Format output\n if (filteredDecisions.length === 0) {\n return 'No architectural decisions apply.';\n }\n\n if (format === 'json') {\n return JSON.stringify({ decisions: filteredDecisions }, null, 2);\n }\n\n const lines: string[] = [];\n\n if (format === 'markdown') {\n lines.push('# Architectural Decisions\\n');\n for (const decision of filteredDecisions) {\n lines.push(`## ${decision.metadata.title}`);\n if (!concise && decision.decision.summary) {\n lines.push(`\\n${decision.decision.summary}\\n`);\n }\n lines.push('### Constraints\\n');\n for (const constraint of decision.constraints) {\n lines.push(`- **[${constraint.severity.toUpperCase()}]** ${constraint.rule}`);\n }\n lines.push('');\n }\n } else {\n // Plain text format\n for (const decision of filteredDecisions) {\n lines.push(`${decision.metadata.title}`);\n if (!concise && decision.decision.summary) {\n lines.push(`${decision.decision.summary}`);\n }\n for (const constraint of decision.constraints) {\n lines.push(` - ${constraint.rule}`);\n }\n lines.push('');\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Generate prompt suffix for AI agents\n */\n generatePromptSuffix(options: { decisions: any[] }): string {\n const { decisions } = options;\n\n if (decisions.length === 0) {\n return 'No architectural decisions to follow.';\n }\n\n const lines: string[] = [];\n lines.push('Please follow these architectural decisions and constraints:');\n lines.push('');\n\n for (const decision of decisions) {\n lines.push(`- ${decision.metadata.title}`);\n for (const constraint of decision.constraints) {\n lines.push(` - ${constraint.rule}`);\n }\n }\n\n lines.push('');\n lines.push('Ensure your code complies with all constraints listed above.');\n\n return lines.join('\\n');\n }\n\n /**\n * Extract relevant decisions for a specific file\n */\n extractRelevantDecisions(options: {\n decisions: any[];\n filePath: string;\n }): any[] {\n const { decisions, filePath } = options;\n\n return decisions.filter(d =>\n d.constraints.some((c: any) => matchesPattern(filePath, c.scope))\n );\n }\n}\n","/**\n * LSP command - Start SpecBridge language server\n */\nimport { Command } from 'commander';\nimport { startLspServer } from '../../lsp/index.js';\n\nexport const lspCommand = new Command('lsp')\n .description('Start SpecBridge language server (stdio)')\n .option('--verbose', 'Enable verbose server logging', false)\n .action(async (options: { verbose?: boolean }) => {\n await startLspServer({ cwd: process.cwd(), verbose: Boolean(options.verbose) });\n });\n\n","/**\n * SpecBridge Language Server (LSP)\n */\nimport { createConnection, ProposedFeatures, TextDocuments, TextDocumentSyncKind, DiagnosticSeverity, CodeActionKind } from 'vscode-languageserver/node.js';\nimport { TextDocument } from 'vscode-languageserver-textdocument';\nimport { fileURLToPath } from 'node:url';\nimport path from 'node:path';\nimport { Project } from 'ts-morph';\nimport chalk from 'chalk';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { getSpecBridgeDir, pathExists } from '../utils/fs.js';\nimport { selectVerifierForConstraint, type VerificationContext } from '../verification/verifiers/index.js';\nimport { shouldApplyConstraintToFile } from '../verification/applicability.js';\nimport type { Decision, Violation, Severity } from '../core/types/index.js';\nimport { NotInitializedError } from '../core/errors/index.js';\n\nexport interface LspServerOptions {\n cwd: string;\n verbose?: boolean;\n}\n\nfunction severityToDiagnostic(severity: Severity): DiagnosticSeverity {\n switch (severity) {\n case 'critical':\n return DiagnosticSeverity.Error;\n case 'high':\n return DiagnosticSeverity.Warning;\n case 'medium':\n return DiagnosticSeverity.Information;\n case 'low':\n return DiagnosticSeverity.Hint;\n default:\n return DiagnosticSeverity.Information;\n }\n}\n\nfunction uriToFilePath(uri: string): string {\n if (uri.startsWith('file://')) return fileURLToPath(uri);\n // Fallback: treat as plain path\n return uri;\n}\n\nfunction violationToRange(doc: TextDocument, v: Violation) {\n // Prefer autofix ranges when available, otherwise line/column best-effort.\n const edit = v.autofix?.edits?.[0];\n if (edit) {\n return {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n };\n }\n\n const line = Math.max(0, (v.line ?? 1) - 1);\n const char = Math.max(0, (v.column ?? 1) - 1);\n return {\n start: { line, character: char },\n end: { line, character: char + 1 },\n };\n}\n\nexport class SpecBridgeLspServer {\n private connection = createConnection(ProposedFeatures.all);\n private documents = new TextDocuments(TextDocument);\n\n private options: LspServerOptions;\n private registry: Registry | null = null;\n private decisions: Decision[] = [];\n private cwd: string;\n private project: Project;\n private cache = new Map<string, Violation[]>();\n private initError: string | null = null;\n\n constructor(options: LspServerOptions) {\n this.options = options;\n this.cwd = options.cwd;\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n async initialize(): Promise<void> {\n this.connection.onInitialize(async () => {\n await this.initializeWorkspace();\n\n return {\n capabilities: {\n textDocumentSync: TextDocumentSyncKind.Incremental,\n codeActionProvider: true,\n },\n };\n });\n\n this.documents.onDidOpen((e) => {\n void this.validateDocument(e.document);\n });\n\n this.documents.onDidChangeContent((change) => {\n void this.validateDocument(change.document);\n });\n\n this.documents.onDidClose((e) => {\n this.cache.delete(e.document.uri);\n this.connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });\n });\n\n this.connection.onCodeAction((params) => {\n const violations = this.cache.get(params.textDocument.uri) || [];\n const doc = this.documents.get(params.textDocument.uri);\n if (!doc) return [];\n\n return violations\n .filter((v) => v.autofix && v.autofix.edits.length > 0)\n .map((v) => {\n const edits = v.autofix!.edits.map((edit) => ({\n range: {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n },\n newText: edit.text,\n }));\n\n return {\n title: v.autofix!.description,\n kind: CodeActionKind.QuickFix,\n edit: {\n changes: {\n [params.textDocument.uri]: edits,\n },\n },\n };\n });\n });\n\n this.documents.listen(this.connection);\n this.connection.listen();\n }\n\n private async initializeWorkspace(): Promise<void> {\n // Ensure initialized (but keep server alive if not).\n if (!await pathExists(getSpecBridgeDir(this.cwd))) {\n const err = new NotInitializedError();\n this.initError = err.message;\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n return;\n }\n\n try {\n const config = await loadConfig(this.cwd);\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n this.decisions = this.registry.getActive();\n\n // Prime project with source roots (best-effort). This enables verifiers that depend on import graph.\n for (const root of config.project.sourceRoots) {\n // ts-morph doesn't support globs directly; add root folders when possible.\n const rootPath = path.isAbsolute(root) ? root : path.join(this.cwd, root);\n // If root is a glob, fall back to adding the directory portion.\n const dir = rootPath.includes('*') ? rootPath.split('*')[0] : rootPath;\n if (dir && await pathExists(dir)) {\n this.project.addSourceFilesAtPaths(path.join(dir, '**/*.{ts,tsx,js,jsx}'));\n }\n }\n\n if (this.options.verbose) {\n this.connection.console.log(chalk.dim(`Loaded ${this.decisions.length} active decision(s)`));\n }\n } catch (error) {\n this.initError = error instanceof Error ? error.message : String(error);\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n }\n }\n\n private async verifyTextDocument(doc: TextDocument): Promise<Violation[]> {\n if (this.initError) {\n throw new Error(this.initError);\n }\n if (!this.registry) return [];\n\n const filePath = uriToFilePath(doc.uri);\n const sourceFile = this.project.createSourceFile(filePath, doc.getText(), { overwrite: true });\n\n const violations: Violation[] = [];\n\n for (const decision of this.decisions) {\n for (const constraint of decision.constraints) {\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd: this.cwd })) continue;\n\n const verifier = selectVerifierForConstraint(constraint.rule, constraint.verifier);\n if (!verifier) continue;\n\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n };\n\n try {\n const constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n } catch {\n // Ignore verifier errors (LSP should stay responsive)\n }\n }\n }\n\n return violations;\n }\n\n private async validateDocument(doc: TextDocument): Promise<void> {\n try {\n const violations = await this.verifyTextDocument(doc);\n this.cache.set(doc.uri, violations);\n\n const diagnostics = violations.map((v) => ({\n range: violationToRange(doc, v),\n severity: severityToDiagnostic(v.severity),\n message: v.message,\n source: 'specbridge',\n }));\n\n this.connection.sendDiagnostics({ uri: doc.uri, diagnostics });\n } catch (error) {\n // If workspace isn't initialized, surface a single diagnostic.\n const msg = error instanceof Error ? error.message : String(error);\n this.connection.sendDiagnostics({\n uri: doc.uri,\n diagnostics: [\n {\n range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },\n severity: DiagnosticSeverity.Error,\n message: msg,\n source: 'specbridge',\n },\n ],\n });\n }\n }\n}\n","import { SpecBridgeLspServer, type LspServerOptions } from './server.js';\n\nexport async function startLspServer(options: LspServerOptions): Promise<void> {\n const server = new SpecBridgeLspServer(options);\n await server.initialize();\n}\n\n","/**\n * Watch command - Verify changed files continuously\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport chokidar from 'chokidar';\nimport path from 'node:path';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { getSpecBridgeDir, pathExists } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { VerificationLevel } from '../../core/types/index.js';\n\nexport const watchCommand = new Command('watch')\n .description('Watch for changes and verify files continuously')\n .option('-l, --level <level>', 'Verification level (commit, pr, full)', 'full')\n .option('--debounce <ms>', 'Debounce verify on rapid changes', '150')\n .action(async (options: { level?: string; debounce?: string }) => {\n const cwd = process.cwd();\n\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const config = await loadConfig(cwd);\n const engine = createVerificationEngine();\n const level = (options.level || 'full') as VerificationLevel;\n const debounceMs = Number.parseInt(options.debounce || '150', 10);\n\n let timer: NodeJS.Timeout | null = null;\n let pendingPath: string | null = null;\n\n const run = async (changedPath: string) => {\n const absolutePath = path.isAbsolute(changedPath) ? changedPath : path.join(cwd, changedPath);\n const result = await engine.verify(config, {\n level,\n files: [absolutePath],\n cwd,\n });\n\n const prefix = result.success ? chalk.green('✓') : chalk.red('✗');\n const summary = `${prefix} ${path.relative(cwd, absolutePath)}: ${result.violations.length} violation(s)`;\n console.log(summary);\n\n for (const v of result.violations.slice(0, 20)) {\n const loc = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n console.log(chalk.dim(` - ${v.file}${loc}: ${v.message} [${v.severity}]`));\n }\n if (result.violations.length > 20) {\n console.log(chalk.dim(` … ${result.violations.length - 20} more`));\n }\n };\n\n const watcher = chokidar.watch(config.project.sourceRoots, {\n cwd,\n ignored: config.project.exclude,\n ignoreInitial: true,\n persistent: true,\n });\n\n console.log(chalk.blue('Watching for changes...'));\n\n watcher.on('change', (changedPath) => {\n pendingPath = changedPath;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n if (!pendingPath) return;\n void run(pendingPath);\n pendingPath = null;\n }, debounceMs);\n });\n });\n\n","/**\n * MCP Server command - Start SpecBridge MCP server\n */\nimport { Command } from 'commander';\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { SpecBridgeMcpServer } from '../../mcp/server.js';\n\nfunction getCliVersion(): string {\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n // In production (bundled): import.meta.url points to dist/cli.js, so ../package.json is correct.\n const packageJsonPath = join(__dirname, '../package.json');\n const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n return String(pkg.version || '0.0.0');\n } catch {\n return '0.0.0';\n }\n}\n\nexport const mcpServerCommand = new Command('mcp-server')\n .description('Start SpecBridge MCP server (stdio)')\n .action(async () => {\n const server = new SpecBridgeMcpServer({\n cwd: process.cwd(),\n version: getCliVersion(),\n });\n\n await server.initialize();\n // MCP servers should write logs to stderr; keep stdout for protocol.\n console.error('SpecBridge MCP server starting (stdio)...');\n await server.startStdio();\n });\n\n","/**\n * SpecBridge MCP Server (Model Context Protocol)\n */\nimport { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { generateFormattedContext } from '../agent/context.generator.js';\nimport { createVerificationEngine } from '../verification/engine.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { formatConsoleReport } from '../reporting/formats/console.js';\nimport { formatMarkdownReport } from '../reporting/formats/markdown.js';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\n\nexport interface McpServerOptions {\n cwd: string;\n version: string;\n}\n\nexport class SpecBridgeMcpServer {\n private server: McpServer;\n private cwd: string;\n private config: SpecBridgeConfig | null = null;\n private registry: Registry | null = null;\n\n constructor(options: McpServerOptions) {\n this.cwd = options.cwd;\n this.server = new McpServer({ name: 'specbridge', version: options.version });\n }\n\n async initialize(): Promise<void> {\n this.config = await loadConfig(this.cwd);\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n\n this.registerResources();\n this.registerTools();\n }\n\n async startStdio(): Promise<void> {\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n }\n\n private getReady(): { config: SpecBridgeConfig; registry: Registry } {\n if (!this.config || !this.registry) {\n throw new Error('SpecBridge MCP server not initialized. Call initialize() first.');\n }\n return { config: this.config, registry: this.registry };\n }\n\n private registerResources(): void {\n const { config, registry } = this.getReady();\n\n // List all decisions\n this.server.registerResource(\n 'decisions',\n 'decision:///',\n {\n title: 'Architectural Decisions',\n description: 'List of all architectural decisions',\n mimeType: 'application/json',\n },\n async (uri: URL) => {\n const decisions = registry.getAll();\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(decisions, null, 2),\n },\n ],\n };\n }\n );\n\n // Read a specific decision\n this.server.registerResource(\n 'decision',\n new ResourceTemplate('decision://{id}', { list: undefined }),\n {\n title: 'Architectural Decision',\n description: 'A specific architectural decision by id',\n mimeType: 'application/json',\n },\n async (uri: URL, variables: Record<string, string | string[]>) => {\n const raw = variables.id;\n const decisionId = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '');\n const decision = registry.get(String(decisionId));\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(decision, null, 2),\n },\n ],\n };\n }\n );\n\n // Latest compliance report\n this.server.registerResource(\n 'latest_report',\n 'report:///latest',\n {\n title: 'Latest Compliance Report',\n description: 'Most recent compliance report (generated on demand)',\n mimeType: 'application/json',\n },\n async (uri: URL) => {\n const report = await generateReport(config, { cwd: this.cwd });\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n }\n );\n }\n\n private registerTools(): void {\n const { config } = this.getReady();\n\n this.server.registerTool(\n 'generate_context',\n {\n title: 'Generate architectural context',\n description: 'Generate architectural context for a file from applicable decisions',\n inputSchema: {\n filePath: z.string().describe('Path to the file to analyze'),\n includeRationale: z.boolean().optional().default(true),\n format: z.enum(['markdown', 'json', 'mcp']).optional().default('markdown'),\n },\n },\n async (args: { filePath: string; includeRationale?: boolean; format?: 'markdown' | 'json' | 'mcp' }) => {\n const text = await generateFormattedContext(args.filePath, config, {\n includeRationale: args.includeRationale,\n format: args.format,\n cwd: this.cwd,\n });\n\n return { content: [{ type: 'text', text }] };\n }\n );\n\n this.server.registerTool(\n 'verify_compliance',\n {\n title: 'Verify compliance',\n description: 'Verify code compliance against constraints',\n inputSchema: {\n level: z.enum(['commit', 'pr', 'full']).optional().default('full'),\n files: z.array(z.string()).optional(),\n decisions: z.array(z.string()).optional(),\n severity: z.array(z.enum(['critical', 'high', 'medium', 'low'])).optional(),\n },\n },\n async (args: {\n level?: 'commit' | 'pr' | 'full';\n files?: string[];\n decisions?: string[];\n severity?: ('critical' | 'high' | 'medium' | 'low')[];\n }) => {\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level: args.level,\n files: args.files,\n decisions: args.decisions,\n severity: args.severity,\n cwd: this.cwd,\n });\n\n return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };\n }\n );\n\n this.server.registerTool(\n 'get_report',\n {\n title: 'Get compliance report',\n description: 'Generate a compliance report for the current workspace',\n inputSchema: {\n format: z.enum(['summary', 'detailed', 'json', 'markdown']).optional().default('summary'),\n includeAll: z.boolean().optional().default(false),\n },\n },\n async (args: { format?: 'summary' | 'detailed' | 'json' | 'markdown'; includeAll?: boolean }) => {\n const report = await generateReport(config, { cwd: this.cwd, includeAll: args.includeAll });\n\n if (args.format === 'json') {\n return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }] };\n }\n\n if (args.format === 'markdown') {\n return { content: [{ type: 'text', text: formatMarkdownReport(report) }] };\n }\n\n if (args.format === 'detailed') {\n return { content: [{ type: 'text', text: formatConsoleReport(report) }] };\n }\n\n // summary\n const summary = {\n timestamp: report.timestamp,\n project: report.project,\n compliance: report.summary.compliance,\n violations: report.summary.violations,\n decisions: report.summary.activeDecisions,\n };\n return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] };\n }\n );\n }\n}\n","/**\n * Prompt command - Generate AI agent prompt templates\n */\nimport { Command } from 'commander';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { generateContext } from '../../agent/context.generator.js';\nimport { templates } from '../../agent/templates.js';\n\nexport const promptCommand = new Command('prompt')\n .description('Generate AI agent prompt templates')\n .argument('<template>', 'Template name (code-review|refactoring|migration)')\n .argument('<file>', 'File path (used to select applicable decisions)')\n .option('--decision <id>', 'Decision id (required for migration)')\n .action(async (templateName: string, file: string, options: { decision?: string }) => {\n const cwd = process.cwd();\n\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const tpl = templates[templateName];\n if (!tpl) {\n throw new Error(`Unknown template: ${templateName}`);\n }\n\n if (templateName === 'migration' && !options.decision) {\n throw new Error('Missing --decision <id> for migration template');\n }\n\n const config = await loadConfig(cwd);\n const context = await generateContext(file, config, { cwd, includeRationale: true });\n const prompt = tpl.generate(context, { decisionId: options.decision });\n console.log(prompt);\n });\n\n","/**\n * Prompt templates for AI agents\n */\nimport type { AgentContext } from '../core/types/index.js';\nimport { formatContextAsMarkdown } from './context.generator.js';\n\nexport interface PromptTemplate {\n name: string;\n description: string;\n generate: (context: AgentContext, options?: Record<string, unknown>) => string;\n}\n\nexport const templates: Record<string, PromptTemplate> = {\n 'code-review': {\n name: 'Code Review',\n description: 'Review code for architectural compliance',\n generate: (context) => {\n return [\n 'You are reviewing code for architectural compliance.',\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Identify violations of the constraints above.',\n '- Suggest concrete changes to achieve compliance.',\n ].join('\\n');\n },\n },\n\n refactoring: {\n name: 'Refactoring Guidance',\n description: 'Guide refactoring to meet constraints',\n generate: (context) => {\n return [\n 'You are helping refactor code to meet architectural constraints.',\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Propose a step-by-step refactoring plan to satisfy all invariants first, then conventions/guidelines.',\n '- Highlight risky changes and suggest safe incremental steps.',\n ].join('\\n');\n },\n },\n\n migration: {\n name: 'Migration Plan',\n description: 'Generate a migration plan for a new/changed decision',\n generate: (context, options) => {\n const decisionId = String(options?.decisionId ?? '');\n return [\n `A new architectural decision has been introduced: ${decisionId || '<decision-id>'}`,\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Provide an impact analysis.',\n '- Produce a step-by-step migration plan.',\n '- Include a checklist for completion.',\n ].join('\\n');\n },\n },\n};\n\n","/**\n * Analytics command - Analyze compliance trends and decision impact\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { ReportStorage } from '../../reporting/storage.js';\nimport { AnalyticsEngine } from '../../analytics/engine.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface AnalyticsOptions {\n insights?: boolean;\n days?: string;\n format?: string;\n}\n\nexport const analyticsCommand = new Command('analytics')\n .description('Analyze compliance trends and decision impact')\n .argument('[decision-id]', 'Specific decision to analyze')\n .option('--insights', 'Show AI-generated insights')\n .option('--days <n>', 'Number of days of history to analyze', '90')\n .option('-f, --format <format>', 'Output format (console, json)', 'console')\n .action(async (decisionId: string | undefined, options: AnalyticsOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Analyzing compliance data...').start();\n\n try {\n const storage = new ReportStorage(cwd);\n const days = parseInt(options.days || '90', 10);\n const history = await storage.loadHistory(days);\n\n if (history.length === 0) {\n spinner.fail('No historical reports found');\n console.log(chalk.yellow('\\nGenerate reports with: specbridge report'));\n return;\n }\n\n spinner.succeed(`Loaded ${history.length} historical report(s)`);\n\n const engine = new AnalyticsEngine();\n\n // Format output\n if (options.format === 'json') {\n if (decisionId) {\n const metrics = await engine.analyzeDecision(decisionId, history);\n console.log(JSON.stringify(metrics, null, 2));\n } else {\n const summary = await engine.generateSummary(history);\n console.log(JSON.stringify(summary, null, 2));\n }\n return;\n }\n\n // Console format\n if (decisionId) {\n // Analyze specific decision\n const metrics = await engine.analyzeDecision(decisionId, history);\n\n console.log('\\n' + chalk.blue.bold(`=== Decision Analytics: ${metrics.title} ===\\n`));\n\n console.log(chalk.bold('Overview:'));\n console.log(` ID: ${metrics.decisionId}`);\n console.log(` Current Violations: ${metrics.totalViolations}`);\n console.log(` Average Compliance: ${metrics.averageComplianceScore.toFixed(1)}%`);\n\n const trendEmoji = metrics.trendDirection === 'up' ? '📈' : metrics.trendDirection === 'down' ? '📉' : '➡️';\n const trendColor = metrics.trendDirection === 'up' ? chalk.green : metrics.trendDirection === 'down' ? chalk.red : chalk.yellow;\n console.log(` ${trendColor(`${trendEmoji} Trend: ${metrics.trendDirection.toUpperCase()}`)}`);\n\n // Show history\n if (metrics.history.length > 0) {\n console.log(chalk.bold('\\nCompliance History:'));\n const recentHistory = metrics.history.slice(-10); // Show last 10 entries\n recentHistory.forEach(h => {\n const icon = h.violations === 0 ? '✅' : '⚠️';\n console.log(` ${icon} ${h.date}: ${h.compliance}% (${h.violations} violations)`);\n });\n }\n } else {\n // Overall analytics\n const summary = await engine.generateSummary(history);\n\n console.log('\\n' + chalk.blue.bold('=== Overall Analytics ===\\n'));\n\n console.log(chalk.bold('Summary:'));\n console.log(` Total Decisions: ${summary.totalDecisions}`);\n console.log(` Average Compliance: ${summary.averageCompliance}%`);\n console.log(` Critical Issues: ${summary.criticalIssues}`);\n\n const trendEmoji = summary.overallTrend === 'up' ? '📈' : summary.overallTrend === 'down' ? '📉' : '➡️';\n const trendColor = summary.overallTrend === 'up' ? chalk.green : summary.overallTrend === 'down' ? chalk.red : chalk.yellow;\n console.log(` ${trendColor(`${trendEmoji} Overall Trend: ${summary.overallTrend.toUpperCase()}`)}`);\n\n // Top performers\n if (summary.topDecisions.length > 0) {\n console.log(chalk.green('\\n✅ Top Performing Decisions:'));\n summary.topDecisions.forEach((d, i) => {\n console.log(` ${i + 1}. ${d.title}: ${d.compliance}%`);\n });\n }\n\n // Bottom performers\n if (summary.bottomDecisions.length > 0) {\n console.log(chalk.red('\\n⚠️ Decisions Needing Attention:'));\n summary.bottomDecisions.forEach((d, i) => {\n console.log(` ${i + 1}. ${d.title}: ${d.compliance}%`);\n });\n }\n\n // Show insights if requested or if there are issues\n if (options.insights || summary.criticalIssues > 0) {\n console.log(chalk.blue.bold('\\n=== Insights ===\\n'));\n\n const insights = summary.insights;\n\n // Group by type\n const warnings = insights.filter(i => i.type === 'warning');\n const successes = insights.filter(i => i.type === 'success');\n const infos = insights.filter(i => i.type === 'info');\n\n if (warnings.length > 0) {\n console.log(chalk.red('⚠️ Warnings:'));\n warnings.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n\n if (successes.length > 0) {\n console.log(chalk.green('✅ Positive Trends:'));\n successes.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n\n if (infos.length > 0) {\n console.log(chalk.blue('💡 Suggestions:'));\n infos.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n }\n }\n\n // Show data range\n const latestEntry = history[history.length - 1];\n const oldestEntry = history[0];\n if (latestEntry && oldestEntry) {\n console.log(chalk.gray(`\\nData range: ${latestEntry.timestamp} to ${oldestEntry.timestamp}`));\n }\n console.log(chalk.gray(`Analyzing ${history.length} report(s) over ${days} days\\n`));\n } catch (error) {\n spinner.fail('Analytics failed');\n throw error;\n }\n });\n","/**\n * Analytics engine - Provide insights into compliance trends and decision impact\n */\nimport type { DecisionCompliance, Severity } from '../core/types/index.js';\nimport type { StoredReport } from '../reporting/storage.js';\n\nexport interface DecisionMetrics {\n decisionId: string;\n title: string;\n totalViolations: number;\n violationsByFile: Map<string, number>;\n violationsBySeverity: Record<Severity, number>;\n mostViolatedConstraint: { id: string; count: number } | null;\n averageComplianceScore: number;\n trendDirection: 'up' | 'down' | 'stable';\n history: Array<{\n date: string;\n compliance: number;\n violations: number;\n }>;\n}\n\nexport interface Insight {\n type: 'warning' | 'info' | 'success';\n category: 'compliance' | 'trend' | 'hotspot' | 'suggestion';\n message: string;\n details?: string;\n decisionId?: string;\n}\n\nexport interface AnalyticsSummary {\n totalDecisions: number;\n averageCompliance: number;\n overallTrend: 'up' | 'down' | 'stable';\n criticalIssues: number;\n topDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n bottomDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n insights: Insight[];\n}\n\n/**\n * Analytics engine for compliance data\n */\nexport class AnalyticsEngine {\n /**\n * Analyze a specific decision across historical reports\n */\n async analyzeDecision(\n decisionId: string,\n history: StoredReport[]\n ): Promise<DecisionMetrics> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n // Extract decision data from each report\n const decisionHistory: Array<{\n date: string;\n data: DecisionCompliance;\n }> = [];\n\n for (const { timestamp, report } of history) {\n const decision = report.byDecision.find(d => d.decisionId === decisionId);\n if (decision) {\n decisionHistory.push({ date: timestamp, data: decision });\n }\n }\n\n if (decisionHistory.length === 0) {\n throw new Error(`Decision ${decisionId} not found in any report`);\n }\n\n // Get latest data\n const latestEntry = decisionHistory[decisionHistory.length - 1];\n if (!latestEntry) {\n throw new Error(`No data found for decision ${decisionId}`);\n }\n const latest = latestEntry.data;\n\n // Calculate averages\n const averageCompliance =\n decisionHistory.reduce((sum, h) => sum + h.data.compliance, 0) / decisionHistory.length;\n\n // Determine trend\n let trendDirection: 'up' | 'down' | 'stable' = 'stable';\n if (decisionHistory.length >= 2) {\n const firstEntry = decisionHistory[0];\n if (!firstEntry) {\n throw new Error('Invalid decision history');\n }\n const first = firstEntry.data.compliance;\n const last = latest.compliance;\n const change = last - first;\n\n if (change > 5) {\n trendDirection = 'up';\n } else if (change < -5) {\n trendDirection = 'down';\n }\n }\n\n // Build history summary\n const historyData = decisionHistory.map(h => ({\n date: h.date,\n compliance: h.data.compliance,\n violations: h.data.violations,\n }));\n\n return {\n decisionId,\n title: latest.title,\n totalViolations: latest.violations,\n violationsByFile: new Map(), // Would need violation details to populate\n violationsBySeverity: {\n critical: 0,\n high: 0,\n medium: 0,\n low: 0,\n }, // Would need violation details to populate\n mostViolatedConstraint: null, // Would need constraint details to populate\n averageComplianceScore: averageCompliance,\n trendDirection,\n history: historyData,\n };\n }\n\n /**\n * Generate insights from historical data\n */\n async generateInsights(history: StoredReport[]): Promise<Insight[]> {\n if (history.length === 0) {\n return [];\n }\n\n const insights: Insight[] = [];\n\n // Sort by date (oldest first)\n const sorted = history.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n const latestEntry = sorted[sorted.length - 1];\n if (!latestEntry) {\n throw new Error('No reports in history');\n }\n const latest = latestEntry.report;\n\n // Insight: Overall compliance trend\n if (sorted.length >= 2) {\n const firstEntry = sorted[0];\n if (!firstEntry) {\n return insights;\n }\n const first = firstEntry.report;\n const complianceChange = latest.summary.compliance - first.summary.compliance;\n\n if (complianceChange > 10) {\n insights.push({\n type: 'success',\n category: 'trend',\n message: `Compliance has improved by ${complianceChange.toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n } else if (complianceChange < -10) {\n insights.push({\n type: 'warning',\n category: 'trend',\n message: `Compliance has dropped by ${Math.abs(complianceChange).toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n }\n }\n\n // Insight: Critical violations\n if (latest.summary.violations.critical > 0) {\n insights.push({\n type: 'warning',\n category: 'compliance',\n message: `${latest.summary.violations.critical} critical violation(s) require immediate attention`,\n details: 'Critical violations block deployments and should be resolved as soon as possible',\n });\n }\n\n // Insight: Decision-specific issues\n const problematicDecisions = latest.byDecision.filter(d => d.compliance < 50);\n if (problematicDecisions.length > 0) {\n insights.push({\n type: 'warning',\n category: 'hotspot',\n message: `${problematicDecisions.length} decision(s) have less than 50% compliance`,\n details: problematicDecisions.map(d => `${d.title} (${d.compliance}%)`).join(', '),\n });\n }\n\n // Insight: High compliance decisions\n const excellentDecisions = latest.byDecision.filter(d => d.compliance === 100);\n if (excellentDecisions.length > 0) {\n insights.push({\n type: 'success',\n category: 'compliance',\n message: `${excellentDecisions.length} decision(s) have 100% compliance`,\n details: excellentDecisions.map(d => d.title).join(', '),\n });\n }\n\n // Insight: Compare to average\n const avgCompliance = latest.summary.compliance;\n const decisionsAboveAvg = latest.byDecision.filter(d => d.compliance > avgCompliance);\n const decisionsBelowAvg = latest.byDecision.filter(d => d.compliance < avgCompliance);\n\n if (decisionsBelowAvg.length > decisionsAboveAvg.length) {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: `${decisionsBelowAvg.length} decisions are below average compliance`,\n details: 'Consider focusing improvement efforts on these lower-performing decisions',\n });\n }\n\n // Insight: Violation distribution\n const totalViolations =\n latest.summary.violations.critical +\n latest.summary.violations.high +\n latest.summary.violations.medium +\n latest.summary.violations.low;\n\n if (totalViolations > 0) {\n const criticalPercent = (latest.summary.violations.critical / totalViolations) * 100;\n const highPercent = (latest.summary.violations.high / totalViolations) * 100;\n\n if (criticalPercent + highPercent > 60) {\n insights.push({\n type: 'warning',\n category: 'suggestion',\n message: 'Most violations are high severity',\n details: `${criticalPercent.toFixed(0)}% critical, ${highPercent.toFixed(0)}% high. Prioritize these for the biggest impact.`,\n });\n } else {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: 'Most violations are lower severity',\n details: 'Consider addressing high-severity issues first for maximum impact',\n });\n }\n }\n\n return insights;\n }\n\n /**\n * Generate analytics summary\n */\n async generateSummary(history: StoredReport[]): Promise<AnalyticsSummary> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n const latestEntry = history[history.length - 1];\n if (!latestEntry) {\n throw new Error('Invalid history data');\n }\n const latest = latestEntry.report;\n\n // Calculate overall trend\n let overallTrend: 'up' | 'down' | 'stable' = 'stable';\n if (history.length >= 2) {\n const firstEntry = history[0];\n if (!firstEntry) {\n throw new Error('Invalid history data');\n }\n const first = firstEntry.report;\n const change = latest.summary.compliance - first.summary.compliance;\n\n if (change > 5) {\n overallTrend = 'up';\n } else if (change < -5) {\n overallTrend = 'down';\n }\n }\n\n // Find top and bottom performers\n const sortedByCompliance = [...latest.byDecision].sort(\n (a, b) => b.compliance - a.compliance\n );\n\n const topDecisions = sortedByCompliance.slice(0, 5).map(d => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n const bottomDecisions = sortedByCompliance.slice(-5).reverse().map(d => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n // Generate insights\n const insights = await this.generateInsights(history);\n\n return {\n totalDecisions: latest.byDecision.length,\n averageCompliance: latest.summary.compliance,\n overallTrend,\n criticalIssues: latest.summary.violations.critical,\n topDecisions,\n bottomDecisions,\n insights,\n };\n }\n}\n","/**\n * Dashboard command - Start compliance dashboard web server\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { createDashboardServer } from '../../dashboard/server.js';\n\ninterface DashboardOptions {\n port?: string;\n host?: string;\n}\n\nexport const dashboardCommand = new Command('dashboard')\n .description('Start compliance dashboard web server')\n .option('-p, --port <port>', 'Port to listen on', '3000')\n .option('-h, --host <host>', 'Host to bind to', 'localhost')\n .action(async (options: DashboardOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n console.log(chalk.blue('Starting SpecBridge dashboard...'));\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Create server\n const app = createDashboardServer({ cwd, config });\n\n // Start listening\n const port = parseInt(options.port || '3000', 10);\n const host = options.host || 'localhost';\n\n app.listen(port, host, () => {\n console.log(chalk.green(`\\n✓ Dashboard running at http://${host}:${port}`));\n console.log(chalk.gray(' Press Ctrl+C to stop\\n'));\n\n // Show helpful endpoints\n console.log(chalk.bold('API Endpoints:'));\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/health`)} - Health check`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/report/latest`)} - Latest report`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/decisions`)} - All decisions`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/analytics/summary`)} - Analytics`);\n console.log('');\n });\n\n // Handle shutdown gracefully\n process.on('SIGINT', () => {\n console.log(chalk.yellow('\\n\\nShutting down dashboard...'));\n process.exit(0);\n });\n\n process.on('SIGTERM', () => {\n console.log(chalk.yellow('\\n\\nShutting down dashboard...'));\n process.exit(0);\n });\n } catch (error) {\n console.error(chalk.red('Failed to start dashboard:'), error);\n throw error;\n }\n });\n","/**\n * Dashboard server - Compliance dashboard backend with REST API\n */\nimport express, { type Request, type Response, type Application } from 'express';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { ReportStorage } from '../reporting/storage.js';\nimport { AnalyticsEngine } from '../analytics/engine.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { detectDrift, analyzeTrend } from '../reporting/drift.js';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\ninterface DashboardOptions {\n cwd: string;\n config: SpecBridgeConfig;\n}\n\n/**\n * Create and configure the dashboard server\n */\nexport function createDashboardServer(options: DashboardOptions): Application {\n const { cwd, config } = options;\n const app = express();\n\n // Middleware\n app.use(express.json());\n\n // CORS for development\n app.use((_req, res, next) => {\n res.header('Access-Control-Allow-Origin', '*');\n res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.header('Access-Control-Allow-Headers', 'Content-Type');\n next();\n });\n\n /**\n * GET /api/report/latest\n * Get the most recent compliance report\n */\n app.get('/api/report/latest', async (_req: Request, res: Response) => {\n try {\n const report = await generateReport(config, { cwd });\n res.json(report);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to generate report',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/report/history?days=30\n * Get historical reports\n */\n app.get('/api/report/history', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n res.json(history);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load history',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/report/dates\n * Get all available report dates\n */\n app.get('/api/report/dates', async (_req: Request, res: Response) => {\n try {\n const storage = new ReportStorage(cwd);\n const dates = await storage.getAvailableDates();\n res.json(dates);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load dates',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/report/:date\n * Get a specific report by date\n */\n app.get('/api/report/:date', async (req: Request, res: Response) => {\n try {\n const date = req.params.date;\n if (!date) {\n res.status(400).json({ error: 'Date parameter required' });\n return;\n }\n\n const storage = new ReportStorage(cwd);\n const report = await storage.loadByDate(date);\n\n if (!report) {\n res.status(404).json({ error: 'Report not found' });\n return;\n }\n\n res.json(report);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load report',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/decisions\n * Get all architectural decisions\n */\n app.get('/api/decisions', async (_req: Request, res: Response) => {\n try {\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n const decisions = registry.getAll();\n res.json(decisions);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load decisions',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/decisions/:id\n * Get a specific decision by ID\n */\n app.get('/api/decisions/:id', async (req: Request, res: Response) => {\n try {\n const id = req.params.id;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n const decision = registry.get(id);\n\n if (!decision) {\n res.status(404).json({ error: 'Decision not found' });\n return;\n }\n\n res.json(decision);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/analytics/summary?days=90\n * Get analytics summary\n */\n app.get('/api/analytics/summary', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 90;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const summary = await engine.generateSummary(history);\n res.json(summary);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to generate analytics',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/analytics/decision/:id?days=90\n * Get analytics for a specific decision\n */\n app.get('/api/analytics/decision/:id', async (req: Request, res: Response) => {\n try {\n const id = req.params.id;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const days = parseInt(req.query.days as string) || 90;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const metrics = await engine.analyzeDecision(id, history);\n res.json(metrics);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/drift?days=2\n * Get drift analysis between most recent reports\n */\n app.get('/api/drift', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 2;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for drift analysis' });\n return;\n }\n\n const currentEntry = history[0];\n const previousEntry = history[1];\n\n if (!currentEntry || !previousEntry) {\n res.status(400).json({ error: 'Invalid history data' });\n return;\n }\n\n const drift = await detectDrift(currentEntry.report, previousEntry.report);\n res.json(drift);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze drift',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/trend?days=30\n * Get compliance trend over time\n */\n app.get('/api/trend', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const storage = new ReportStorage(cwd);\n const history = await storage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for trend analysis' });\n return;\n }\n\n const trend = await analyzeTrend(history);\n res.json(trend);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze trend',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n /**\n * GET /api/health\n * Health check endpoint\n */\n app.get('/api/health', (_req: Request, res: Response) => {\n res.json({\n status: 'ok',\n timestamp: new Date().toISOString(),\n project: config.project.name,\n });\n });\n\n // Serve static frontend files\n const publicDir = join(__dirname, 'public');\n app.use(express.static(publicDir));\n\n // Fallback to index.html for SPA routing\n app.get('*', (_req: Request, res: Response) => {\n res.sendFile(join(publicDir, 'index.html'));\n });\n\n return app;\n}\n"],"mappings":";;;AAIA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,aAAW;AAClB,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,QAAAC,cAAY;;;ACDvB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MACA,SACA,YAChB;AACA,UAAM,OAAO;AAJG;AACA;AACA;AAGhB,SAAK,OAAO;AACZ,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAChD;AACF;AAKO,IAAM,cAAN,cAA0B,gBAAgB;AAAA,EAC/C,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,gBAAgB,OAAO;AACtC,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,0BAAN,cAAsC,gBAAgB;AAAA,EAC3D,YACE,SACgB,YACA,kBAChB;AACA,UAAM,SAAS,6BAA6B,EAAE,YAAY,iBAAiB,CAAC;AAH5D;A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I,IAAI,SAAS,qBAAqB;AACpC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,UAAQ,MAAMC,QAAM,IAAI,YAAY,GAAG,CAAC,CAAC;AACzC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAGD,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAiB;AACvD,UAAQ,MAAMA,QAAM,IAAI,YAAY,KAAK,CAAC,CAAC;AAC3C,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Command","chalk","readFileSync","fileURLToPath","dirname","join","path","join","path","path","join","Command","chalk","ora","join","path","dirname","dirname","Node","path","Node","Command","ora","join","chalk","Command","chalk","ora","Project","join","z","SeveritySchema","VerificationConfigSchema","path","join","Node","Node","path","relative","path","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","stat","Project","resolve","readFile","writeFile","stdout","Command","ora","chalk","Command","Command","chalk","Command","chalk","Command","chalk","Command","chalk","getTypeIcon","Command","chalk","ora","join","Command","ora","join","chalk","Command","chalk","join","Command","chalk","join","Command","Command","chalk","ora","join","hookCommand","Command","ora","join","chalk","execFile","promisify","execFileAsync","stdout","Command","chalk","ora","join","chalk","table","getStatusColor","truncate","join","join","Command","ora","chalk","join","Command","chalk","Command","chalk","Command","path","Project","chalk","Project","chalk","path","Command","Command","chalk","path","Command","path","chalk","Command","fileURLToPath","dirname","join","z","z","__dirname","dirname","fileURLToPath","packageJsonPath","join","Command","Command","Command","Command","chalk","ora","Command","ora","chalk","Command","chalk","join","dirname","fileURLToPath","dirname","fileURLToPath","join","Command","chalk","__dirname","dirname","fileURLToPath","join","readFileSync","Command","chalk"]}
1
+ {"version":3,"sources":["../src/cli/index.ts","../src/core/errors/index.ts","../src/cli/commands/init.ts","../src/utils/fs.ts","../src/utils/yaml.ts","../src/core/schemas/config.schema.ts","../src/cli/commands/infer.ts","../src/inference/scanner.ts","../src/utils/glob.ts","../src/inference/analyzers/base.ts","../src/inference/analyzers/naming.ts","../src/inference/analyzers/imports.ts","../src/inference/analyzers/structure.ts","../src/inference/analyzers/errors.ts","../src/inference/analyzers/index.ts","../src/inference/engine.ts","../src/config/loader.ts","../src/cli/commands/verify.ts","../src/verification/engine.ts","../src/registry/loader.ts","../src/core/schemas/decision.schema.ts","../src/registry/registry.ts","../src/verification/verifiers/base.ts","../src/verification/verifiers/naming.ts","../src/verification/verifiers/imports.ts","../src/verification/verifiers/errors.ts","../src/verification/verifiers/regex.ts","../src/verification/verifiers/dependencies.ts","../src/verification/verifiers/complexity.ts","../src/verification/verifiers/security.ts","../src/verification/verifiers/api.ts","../src/verification/plugins/loader.ts","../node_modules/glob/src/index.ts","../node_modules/glob/src/glob.ts","../node_modules/lru-cache/src/index.ts","../node_modules/path-scurry/src/index.ts","../node_modules/minipass/src/index.ts","../node_modules/glob/src/pattern.ts","../node_modules/glob/src/ignore.ts","../node_modules/glob/src/processor.ts","../node_modules/glob/src/walker.ts","../node_modules/glob/src/has-magic.ts","../src/verification/verifiers/index.ts","../src/verification/cache.ts","../src/verification/results-cache.ts","../src/verification/applicability.ts","../src/verification/autofix/engine.ts","../src/verification/incremental.ts","../src/verification/explain.ts","../src/cli/commands/decision/index.ts","../src/cli/commands/decision/list.ts","../src/cli/commands/decision/show.ts","../src/cli/commands/decision/validate.ts","../src/cli/commands/decision/create.ts","../src/cli/commands/hook.ts","../src/cli/commands/report.ts","../src/reporting/reporter.ts","../src/reporting/formats/console.ts","../src/reporting/formats/markdown.ts","../src/reporting/storage.ts","../src/reporting/drift.ts","../src/cli/commands/context.ts","../src/agent/context.generator.ts","../src/cli/commands/lsp.ts","../src/lsp/server.ts","../src/lsp/index.ts","../src/cli/commands/watch.ts","../src/cli/commands/mcp-server.ts","../src/mcp/server.ts","../src/cli/commands/prompt.ts","../src/agent/templates.ts","../src/cli/commands/analytics.ts","../src/analytics/engine.ts","../src/cli/commands/dashboard.ts","../src/dashboard/server.ts","../src/cli/commands/impact.ts","../src/propagation/graph.ts","../src/propagation/engine.ts","../src/cli/commands/migrate.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * SpecBridge CLI Entry Point\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { formatError } from '../core/errors/index.js';\n\n// Import commands\nimport { initCommand } from './commands/init.js';\nimport { inferCommand } from './commands/infer.js';\nimport { verifyCommand } from './commands/verify.js';\nimport { decisionCommand } from './commands/decision/index.js';\nimport { hookCommand } from './commands/hook.js';\nimport { reportCommand } from './commands/report.js';\nimport { contextCommand } from './commands/context.js';\nimport { lspCommand } from './commands/lsp.js';\nimport { watchCommand } from './commands/watch.js';\nimport { mcpServerCommand } from './commands/mcp-server.js';\nimport { promptCommand } from './commands/prompt.js';\nimport { analyticsCommand } from './commands/analytics.js';\nimport { dashboardCommand } from './commands/dashboard.js';\nimport { impactCommand } from './commands/impact.js';\nimport { migrateCommand } from './commands/migrate.js';\n\n// Read version from package.json\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n// In development: src/cli/index.ts -> ../../package.json\n// In production: dist/cli.js -> ../package.json\nconst packageJsonPath = join(__dirname, '../package.json');\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n\nconst program = new Command();\n\nprogram\n .name('specbridge')\n .description('Architecture Decision Runtime - Transform architectural decisions into executable, verifiable constraints')\n .version(packageJson.version);\n\n// Register commands\nprogram.addCommand(initCommand);\nprogram.addCommand(inferCommand);\nprogram.addCommand(verifyCommand);\nprogram.addCommand(decisionCommand);\nprogram.addCommand(hookCommand);\nprogram.addCommand(reportCommand);\nprogram.addCommand(contextCommand);\nprogram.addCommand(lspCommand);\nprogram.addCommand(watchCommand);\nprogram.addCommand(mcpServerCommand);\nprogram.addCommand(promptCommand);\nprogram.addCommand(analyticsCommand);\nprogram.addCommand(dashboardCommand);\nprogram.addCommand(impactCommand);\nprogram.addCommand(migrateCommand);\n\n// Global error handler\nprogram.exitOverride((err) => {\n if (err.code === 'commander.help' || err.code === 'commander.helpDisplayed') {\n process.exit(0);\n }\n if (err.code === 'commander.version') {\n process.exit(0);\n }\n console.error(chalk.red(formatError(err)));\n process.exit(1);\n});\n\n// Parse and execute\nprogram.parseAsync(process.argv).catch((error: Error) => {\n console.error(chalk.red(formatError(error)));\n process.exit(1);\n});\n","/**\n * Custom error types for SpecBridge\n */\n\n/**\n * Base error for SpecBridge\n */\nexport class SpecBridgeError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n public readonly suggestion?: string\n ) {\n super(message);\n this.name = 'SpecBridgeError';\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Configuration errors\n */\nexport class ConfigError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'CONFIG_ERROR', details);\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Decision validation errors\n */\nexport class DecisionValidationError extends SpecBridgeError {\n constructor(\n message: string,\n public readonly decisionId: string,\n public readonly validationErrors: string[]\n ) {\n super(message, 'DECISION_VALIDATION_ERROR', { decisionId, validationErrors });\n this.name = 'DecisionValidationError';\n }\n}\n\n/**\n * Decision not found\n */\nexport class DecisionNotFoundError extends SpecBridgeError {\n constructor(decisionId: string) {\n super(`Decision not found: ${decisionId}`, 'DECISION_NOT_FOUND', { decisionId });\n this.name = 'DecisionNotFoundError';\n }\n}\n\n/**\n * Registry errors\n */\nexport class RegistryError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'REGISTRY_ERROR', details);\n this.name = 'RegistryError';\n }\n}\n\n/**\n * Verification errors\n */\nexport class VerificationError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'VERIFICATION_ERROR', details);\n this.name = 'VerificationError';\n }\n}\n\n/**\n * Inference errors\n */\nexport class InferenceError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'INFERENCE_ERROR', details);\n this.name = 'InferenceError';\n }\n}\n\n/**\n * File system errors\n */\nexport class FileSystemError extends SpecBridgeError {\n constructor(message: string, public readonly path: string) {\n super(message, 'FILE_SYSTEM_ERROR', { path });\n this.name = 'FileSystemError';\n }\n}\n\n/**\n * Already initialized error\n */\nexport class AlreadyInitializedError extends SpecBridgeError {\n constructor(path: string) {\n super(`SpecBridge is already initialized at ${path}`, 'ALREADY_INITIALIZED', { path });\n this.name = 'AlreadyInitializedError';\n }\n}\n\n/**\n * Not initialized error\n */\nexport class NotInitializedError extends SpecBridgeError {\n constructor() {\n super(\n 'SpecBridge is not initialized. Run \"specbridge init\" first.',\n 'NOT_INITIALIZED',\n undefined,\n 'Run `specbridge init` in this directory to create .specbridge/'\n );\n this.name = 'NotInitializedError';\n }\n}\n\n/**\n * Verifier not found\n */\nexport class VerifierNotFoundError extends SpecBridgeError {\n constructor(verifierId: string) {\n super(`Verifier not found: ${verifierId}`, 'VERIFIER_NOT_FOUND', { verifierId });\n this.name = 'VerifierNotFoundError';\n }\n}\n\n/**\n * Analyzer not found\n */\nexport class AnalyzerNotFoundError extends SpecBridgeError {\n constructor(analyzerId: string) {\n super(`Analyzer not found: ${analyzerId}`, 'ANALYZER_NOT_FOUND', { analyzerId });\n this.name = 'AnalyzerNotFoundError';\n }\n}\n\n/**\n * Hook installation error\n */\nexport class HookError extends SpecBridgeError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'HOOK_ERROR', details);\n this.name = 'HookError';\n }\n}\n\n/**\n * Format error message for CLI output\n */\nexport function formatError(error: Error): string {\n if (error instanceof SpecBridgeError) {\n let message = `Error [${error.code}]: ${error.message}`;\n if (error.details) {\n const detailsStr = Object.entries(error.details)\n .filter(([key]) => key !== 'validationErrors')\n .map(([key, value]) => ` ${key}: ${value}`)\n .join('\\n');\n if (detailsStr) {\n message += `\\n${detailsStr}`;\n }\n }\n if (error instanceof DecisionValidationError && error.validationErrors.length > 0) {\n message += '\\nValidation errors:\\n' + error.validationErrors.map(e => ` - ${e}`).join('\\n');\n }\n if (error.suggestion) {\n message += `\\nSuggestion: ${error.suggestion}`;\n }\n return message;\n }\n return `Error: ${error.message}`;\n}\n","/**\n * Init command - Initialize SpecBridge in a project\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport {\n pathExists,\n ensureDir,\n writeTextFile,\n getSpecBridgeDir,\n getDecisionsDir,\n getVerifiersDir,\n getInferredDir,\n getReportsDir,\n getConfigPath,\n} from '../../utils/fs.js';\nimport { stringifyYaml } from '../../utils/yaml.js';\nimport { defaultConfig } from '../../core/schemas/config.schema.js';\nimport { AlreadyInitializedError } from '../../core/errors/index.js';\n\ninterface InitOptions {\n force?: boolean;\n name?: string;\n}\n\nexport const initCommand = new Command('init')\n .description('Initialize SpecBridge in the current project')\n .option('-f, --force', 'Overwrite existing configuration')\n .option('-n, --name <name>', 'Project name')\n .action(async (options: InitOptions) => {\n const cwd = process.cwd();\n const specbridgeDir = getSpecBridgeDir(cwd);\n\n // Check if already initialized\n if (!options.force && await pathExists(specbridgeDir)) {\n throw new AlreadyInitializedError(specbridgeDir);\n }\n\n const spinner = ora('Initializing SpecBridge...').start();\n\n try {\n // Create directory structure\n await ensureDir(specbridgeDir);\n await ensureDir(getDecisionsDir(cwd));\n await ensureDir(getVerifiersDir(cwd));\n await ensureDir(getInferredDir(cwd));\n await ensureDir(getReportsDir(cwd));\n\n // Determine project name\n const projectName = options.name || getProjectNameFromPath(cwd);\n\n // Create config file\n const config = {\n ...defaultConfig,\n project: {\n ...defaultConfig.project,\n name: projectName,\n },\n };\n\n const configContent = stringifyYaml(config);\n await writeTextFile(getConfigPath(cwd), configContent);\n\n // Create example decision\n const exampleDecision = createExampleDecision(projectName);\n await writeTextFile(\n join(getDecisionsDir(cwd), 'example.decision.yaml'),\n stringifyYaml(exampleDecision)\n );\n\n // Create .gitkeep files\n await writeTextFile(join(getVerifiersDir(cwd), '.gitkeep'), '');\n await writeTextFile(join(getInferredDir(cwd), '.gitkeep'), '');\n await writeTextFile(join(getReportsDir(cwd), '.gitkeep'), '');\n\n spinner.succeed('SpecBridge initialized successfully!');\n\n console.log('');\n console.log(chalk.green('Created:'));\n console.log(` ${chalk.dim('.specbridge/')}`);\n console.log(` ${chalk.dim('├──')} config.yaml`);\n console.log(` ${chalk.dim('├──')} decisions/`);\n console.log(` ${chalk.dim('│ └──')} example.decision.yaml`);\n console.log(` ${chalk.dim('├──')} verifiers/`);\n console.log(` ${chalk.dim('├──')} inferred/`);\n console.log(` ${chalk.dim('└──')} reports/`);\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(` 1. Edit ${chalk.bold('.specbridge/config.yaml')} to configure source paths`);\n console.log(` 2. Run ${chalk.bold('specbridge infer')} to detect patterns in your codebase`);\n console.log(` 3. Create decisions in ${chalk.bold('.specbridge/decisions/')}`);\n console.log(` 4. Run ${chalk.bold('specbridge verify')} to check compliance`);\n } catch (error) {\n spinner.fail('Failed to initialize SpecBridge');\n throw error;\n }\n });\n\n/**\n * Extract project name from directory path\n */\nfunction getProjectNameFromPath(dirPath: string): string {\n const parts = dirPath.split(/[/\\\\]/);\n return parts[parts.length - 1] || 'my-project';\n}\n\n/**\n * Create an example decision for new projects\n */\nfunction createExampleDecision(projectName: string) {\n return {\n kind: 'Decision',\n metadata: {\n id: 'example-001',\n title: 'Example Decision - Error Handling Convention',\n status: 'draft',\n owners: ['team'],\n tags: ['example', 'error-handling'],\n },\n decision: {\n summary: 'All errors should be handled using a consistent error class hierarchy.',\n rationale: `Consistent error handling improves debugging and makes the codebase more maintainable.\nThis is an example decision to demonstrate SpecBridge functionality.`,\n context: `This decision was auto-generated when initializing SpecBridge for ${projectName}.\nReplace or delete this file and create your own architectural decisions.`,\n },\n constraints: [\n {\n id: 'custom-errors',\n type: 'convention',\n rule: 'Custom error classes should extend a base AppError class',\n severity: 'medium',\n scope: 'src/**/*.ts',\n },\n {\n id: 'error-logging',\n type: 'guideline',\n rule: 'Errors should be logged with appropriate context before being thrown or handled',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n ],\n };\n}\n","/**\n * File system utilities\n */\nimport { readFile, writeFile, mkdir, access, readdir, stat } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { constants } from 'node:fs';\n\n/**\n * Check if a path exists\n */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a path is a directory\n */\nexport async function isDirectory(path: string): Promise<boolean> {\n try {\n const stats = await stat(path);\n return stats.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a directory exists\n */\nexport async function ensureDir(path: string): Promise<void> {\n await mkdir(path, { recursive: true });\n}\n\n/**\n * Read a text file\n */\nexport async function readTextFile(path: string): Promise<string> {\n return readFile(path, 'utf-8');\n}\n\n/**\n * Write a text file, creating directories as needed\n */\nexport async function writeTextFile(path: string, content: string): Promise<void> {\n await ensureDir(dirname(path));\n await writeFile(path, content, 'utf-8');\n}\n\n/**\n * Read all files in a directory matching a pattern\n */\nexport async function readFilesInDir(\n dirPath: string,\n filter?: (filename: string) => boolean\n): Promise<string[]> {\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n const files = entries\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name);\n\n if (filter) {\n return files.filter(filter);\n }\n return files;\n } catch {\n return [];\n }\n}\n\n/**\n * Get the .specbridge directory path\n */\nexport function getSpecBridgeDir(basePath: string = process.cwd()): string {\n return join(basePath, '.specbridge');\n}\n\n/**\n * Get the decisions directory path\n */\nexport function getDecisionsDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'decisions');\n}\n\n/**\n * Get the verifiers directory path\n */\nexport function getVerifiersDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'verifiers');\n}\n\n/**\n * Get the inferred patterns directory path\n */\nexport function getInferredDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'inferred');\n}\n\n/**\n * Get the reports directory path\n */\nexport function getReportsDir(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'reports');\n}\n\n/**\n * Get the config file path\n */\nexport function getConfigPath(basePath: string = process.cwd()): string {\n return join(getSpecBridgeDir(basePath), 'config.yaml');\n}\n","/**\n * YAML utilities with comment preservation\n */\nimport { parse, stringify, Document, parseDocument } from 'yaml';\n\n/**\n * Parse YAML string to object\n */\nexport function parseYaml<T = unknown>(content: string): T {\n return parse(content) as T;\n}\n\n/**\n * Stringify object to YAML with nice formatting\n */\nexport function stringifyYaml(data: unknown, options?: { indent?: number }): string {\n return stringify(data, {\n indent: options?.indent ?? 2,\n lineWidth: 100,\n minContentWidth: 20,\n });\n}\n\n/**\n * Parse YAML preserving document structure (for editing)\n */\nexport function parseYamlDocument(content: string): Document {\n return parseDocument(content);\n}\n\n/**\n * Update YAML document preserving comments\n */\nexport function updateYamlDocument(doc: Document, path: string[], value: unknown): void {\n let current: unknown = doc.contents;\n\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n if (key && current && typeof current === 'object' && 'get' in current) {\n current = (current as { get: (key: string) => unknown }).get(key);\n }\n }\n\n const lastKey = path[path.length - 1];\n if (lastKey && current && typeof current === 'object' && 'set' in current) {\n (current as { set: (key: string, value: unknown) => void }).set(lastKey, value);\n }\n}\n","/**\n * Zod schemas for SpecBridge configuration\n */\nimport { z } from 'zod';\n\n// Severity for level config\nconst SeveritySchema = z.enum(['critical', 'high', 'medium', 'low']);\n\n// Level configuration\nconst LevelConfigSchema = z.object({\n timeout: z.number().positive().optional(),\n severity: z.array(SeveritySchema).optional(),\n});\n\n// Project configuration\nconst ProjectConfigSchema = z.object({\n name: z.string().min(1),\n sourceRoots: z.array(z.string().min(1)).min(1),\n exclude: z.array(z.string()).optional(),\n});\n\n// Inference configuration\nconst InferenceConfigSchema = z.object({\n minConfidence: z.number().min(0).max(100).optional(),\n analyzers: z.array(z.string()).optional(),\n});\n\n// Verification configuration\nconst VerificationConfigSchema = z.object({\n levels: z.object({\n commit: LevelConfigSchema.optional(),\n pr: LevelConfigSchema.optional(),\n full: LevelConfigSchema.optional(),\n }).optional(),\n});\n\n// Agent configuration\nconst AgentConfigSchema = z.object({\n format: z.enum(['markdown', 'json', 'mcp']).optional(),\n includeRationale: z.boolean().optional(),\n});\n\n// Complete SpecBridge configuration\nexport const SpecBridgeConfigSchema = z.object({\n version: z.string().regex(/^\\d+\\.\\d+$/, 'Version must be in format X.Y'),\n project: ProjectConfigSchema,\n inference: InferenceConfigSchema.optional(),\n verification: VerificationConfigSchema.optional(),\n agent: AgentConfigSchema.optional(),\n});\n\nexport type SpecBridgeConfigType = z.infer<typeof SpecBridgeConfigSchema>;\n\n/**\n * Validate configuration\n */\nexport function validateConfig(data: unknown): { success: true; data: SpecBridgeConfigType } | { success: false; errors: z.ZodError } {\n const result = SpecBridgeConfigSchema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, errors: result.error };\n}\n\n/**\n * Default configuration\n */\nexport const defaultConfig: SpecBridgeConfigType = {\n version: '1.0',\n project: {\n name: 'my-project',\n sourceRoots: ['src/**/*.ts', 'src/**/*.tsx'],\n exclude: ['**/*.test.ts', '**/*.spec.ts', '**/node_modules/**', '**/dist/**'],\n },\n inference: {\n minConfidence: 70,\n analyzers: ['naming', 'structure', 'imports', 'errors'],\n },\n verification: {\n levels: {\n commit: {\n timeout: 5000,\n severity: ['critical'],\n },\n pr: {\n timeout: 60000,\n severity: ['critical', 'high'],\n },\n full: {\n timeout: 300000,\n severity: ['critical', 'high', 'medium', 'low'],\n },\n },\n },\n agent: {\n format: 'markdown',\n includeRationale: true,\n },\n};\n","/**\n * Infer command - Detect patterns in the codebase\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { createInferenceEngine, getAnalyzerIds } from '../../inference/index.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { writeTextFile, getInferredDir, pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { Pattern } from '../../core/types/index.js';\n\ninterface InferOptions {\n output?: string;\n minConfidence?: string;\n analyzers?: string;\n json?: boolean;\n save?: boolean;\n}\n\nexport const inferCommand = new Command('infer')\n .description('Analyze codebase and detect patterns')\n .option('-o, --output <file>', 'Output file path')\n .option('-c, --min-confidence <number>', 'Minimum confidence threshold (0-100)', '50')\n .option('-a, --analyzers <list>', 'Comma-separated list of analyzers to run')\n .option('--json', 'Output as JSON')\n .option('--save', 'Save results to .specbridge/inferred/')\n .action(async (options: InferOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Loading configuration...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Parse options\n const minConfidence = parseInt(options.minConfidence || '50', 10);\n const analyzerList = options.analyzers\n ? options.analyzers.split(',').map(a => a.trim())\n : config.inference?.analyzers || getAnalyzerIds();\n\n spinner.text = `Scanning codebase (analyzers: ${analyzerList.join(', ')})...`;\n\n // Run inference\n const engine = createInferenceEngine();\n const result = await engine.infer({\n analyzers: analyzerList,\n minConfidence,\n sourceRoots: config.project.sourceRoots,\n exclude: config.project.exclude,\n cwd,\n });\n\n spinner.succeed(`Scanned ${result.filesScanned} files in ${result.duration}ms`);\n\n // Save results first (even if empty) if requested\n if (options.save || options.output) {\n const outputPath = options.output || join(getInferredDir(cwd), 'patterns.json');\n await writeTextFile(outputPath, JSON.stringify(result, null, 2));\n console.log(chalk.green(`\\nResults saved to: ${outputPath}`));\n }\n\n if (result.patterns.length === 0) {\n console.log(chalk.yellow('\\nNo patterns detected above confidence threshold.'));\n console.log(chalk.dim(`Try lowering --min-confidence (current: ${minConfidence})`));\n return;\n }\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n printPatterns(result.patterns);\n }\n\n // Show next steps\n if (!options.json) {\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(' Review detected patterns and create decisions for important ones.');\n console.log(` Use ${chalk.bold('specbridge decision create <id>')} to create a new decision.`);\n }\n } catch (error) {\n spinner.fail('Inference failed');\n throw error;\n }\n });\n\nfunction printPatterns(patterns: Pattern[]): void {\n console.log(chalk.bold(`\\nDetected ${patterns.length} pattern(s):\\n`));\n\n for (const pattern of patterns) {\n const confidenceColor = pattern.confidence >= 80\n ? chalk.green\n : pattern.confidence >= 60\n ? chalk.yellow\n : chalk.dim;\n\n console.log(chalk.bold(`${pattern.name}`));\n console.log(chalk.dim(` ID: ${pattern.id}`));\n console.log(` ${pattern.description}`);\n console.log(` Confidence: ${confidenceColor(`${pattern.confidence}%`)} (${pattern.occurrences} occurrences)`);\n console.log(chalk.dim(` Analyzer: ${pattern.analyzer}`));\n\n if (pattern.examples.length > 0) {\n console.log(chalk.dim(' Examples:'));\n for (const example of pattern.examples.slice(0, 2)) {\n console.log(chalk.dim(` - ${example.file}:${example.line}`));\n console.log(chalk.dim(` ${example.snippet}`));\n }\n }\n\n if (pattern.suggestedConstraint) {\n const typeColor =\n pattern.suggestedConstraint.type === 'invariant' ? chalk.red :\n pattern.suggestedConstraint.type === 'convention' ? chalk.yellow :\n chalk.green;\n\n console.log(chalk.cyan(' Suggested constraint:'));\n console.log(` Type: ${typeColor(pattern.suggestedConstraint.type || 'convention')}`);\n console.log(` Rule: ${pattern.suggestedConstraint.rule}`);\n }\n\n console.log('');\n }\n}\n","/**\n * Codebase scanner using ts-morph\n */\nimport { Project, SourceFile, Node, SyntaxKind } from 'ts-morph';\nimport { glob } from '../utils/glob.js';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\n\nexport interface ScanResult {\n files: ScannedFile[];\n totalFiles: number;\n totalLines: number;\n}\n\nexport interface ScannedFile {\n path: string;\n sourceFile: SourceFile;\n lines: number;\n}\n\nexport interface ScanOptions {\n sourceRoots: string[];\n exclude?: string[];\n cwd?: string;\n}\n\n/**\n * Scanner class for analyzing TypeScript/JavaScript codebases\n */\nexport class CodeScanner {\n private project: Project;\n private scannedFiles: Map<string, ScannedFile> = new Map();\n\n constructor() {\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n /**\n * Scan files matching the given patterns\n */\n async scan(options: ScanOptions): Promise<ScanResult> {\n const { sourceRoots, exclude = [], cwd = process.cwd() } = options;\n\n // Find files matching patterns\n const files = await glob(sourceRoots, {\n cwd,\n ignore: exclude,\n absolute: true,\n });\n\n // Add files to project\n for (const filePath of files) {\n try {\n const sourceFile = this.project.addSourceFileAtPath(filePath);\n const lines = sourceFile.getEndLineNumber();\n\n this.scannedFiles.set(filePath, {\n path: filePath,\n sourceFile,\n lines,\n });\n } catch {\n // Skip files that can't be parsed\n }\n }\n\n const scannedArray = Array.from(this.scannedFiles.values());\n const totalLines = scannedArray.reduce((sum, f) => sum + f.lines, 0);\n\n return {\n files: scannedArray,\n totalFiles: scannedArray.length,\n totalLines,\n };\n }\n\n /**\n * Get all scanned files\n */\n getFiles(): ScannedFile[] {\n return Array.from(this.scannedFiles.values());\n }\n\n /**\n * Get a specific file\n */\n getFile(path: string): ScannedFile | undefined {\n return this.scannedFiles.get(path);\n }\n\n /**\n * Get project instance for advanced analysis\n */\n getProject(): Project {\n return this.project;\n }\n\n /**\n * Find all classes in scanned files\n */\n findClasses(): { file: string; name: string; line: number }[] {\n const classes: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const classDecl of sourceFile.getClasses()) {\n const name = classDecl.getName();\n if (name) {\n classes.push({\n file: path,\n name,\n line: classDecl.getStartLineNumber(),\n });\n }\n }\n }\n\n return classes;\n }\n\n /**\n * Find all functions in scanned files\n */\n findFunctions(): { file: string; name: string; line: number; isExported: boolean }[] {\n const functions: { file: string; name: string; line: number; isExported: boolean }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n // Top-level functions\n for (const funcDecl of sourceFile.getFunctions()) {\n const name = funcDecl.getName();\n if (name) {\n functions.push({\n file: path,\n name,\n line: funcDecl.getStartLineNumber(),\n isExported: funcDecl.isExported(),\n });\n }\n }\n\n // Arrow functions assigned to variables\n for (const varDecl of sourceFile.getVariableDeclarations()) {\n const init = varDecl.getInitializer();\n if (init && Node.isArrowFunction(init)) {\n functions.push({\n file: path,\n name: varDecl.getName(),\n line: varDecl.getStartLineNumber(),\n isExported: varDecl.isExported(),\n });\n }\n }\n }\n\n return functions;\n }\n\n /**\n * Find all imports in scanned files\n */\n findImports(): { file: string; module: string; named: string[]; line: number }[] {\n const imports: { file: string; module: string; named: string[]; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const module = importDecl.getModuleSpecifierValue();\n const namedImports = importDecl\n .getNamedImports()\n .map((n) => n.getName());\n\n imports.push({\n file: path,\n module,\n named: namedImports,\n line: importDecl.getStartLineNumber(),\n });\n }\n }\n\n return imports;\n }\n\n /**\n * Find all interfaces in scanned files\n */\n findInterfaces(): { file: string; name: string; line: number }[] {\n const interfaces: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n interfaces.push({\n file: path,\n name: interfaceDecl.getName(),\n line: interfaceDecl.getStartLineNumber(),\n });\n }\n }\n\n return interfaces;\n }\n\n /**\n * Find all type aliases in scanned files\n */\n findTypeAliases(): { file: string; name: string; line: number }[] {\n const types: { file: string; name: string; line: number }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n types.push({\n file: path,\n name: typeAlias.getName(),\n line: typeAlias.getStartLineNumber(),\n });\n }\n }\n\n return types;\n }\n\n /**\n * Find try-catch blocks in scanned files\n */\n findTryCatchBlocks(): { file: string; line: number; hasThrow: boolean }[] {\n const blocks: { file: string; line: number; hasThrow: boolean }[] = [];\n\n for (const { path, sourceFile } of this.scannedFiles.values()) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isTryStatement(node)) {\n const catchClause = node.getCatchClause();\n const hasThrow = catchClause\n ? catchClause.getDescendantsOfKind(SyntaxKind.ThrowStatement).length > 0\n : false;\n\n blocks.push({\n file: path,\n line: node.getStartLineNumber(),\n hasThrow,\n });\n }\n });\n }\n\n return blocks;\n }\n}\n\n/**\n * Create a scanner from config\n */\nexport function createScannerFromConfig(_config: SpecBridgeConfig): CodeScanner {\n return new CodeScanner();\n}\n","/**\n * Glob utilities for file matching\n */\nimport fg from 'fast-glob';\nimport { minimatch } from 'minimatch';\nimport { relative, isAbsolute } from 'node:path';\n\nexport interface GlobOptions {\n cwd?: string;\n ignore?: string[];\n absolute?: boolean;\n onlyFiles?: boolean;\n}\n\n/**\n * Find files matching glob patterns\n */\nexport async function glob(\n patterns: string | string[],\n options: GlobOptions = {}\n): Promise<string[]> {\n const {\n cwd = process.cwd(),\n ignore = [],\n absolute = false,\n onlyFiles = true,\n } = options;\n\n return fg(patterns, {\n cwd,\n ignore,\n absolute,\n onlyFiles,\n dot: false,\n });\n}\n\n/**\n * Normalize a file path to be relative to a base directory\n * Handles both absolute and relative paths, cross-platform\n */\nexport function normalizePath(filePath: string, basePath: string = process.cwd()): string {\n let resultPath: string;\n\n if (!isAbsolute(filePath)) {\n // Already relative, use as-is\n resultPath = filePath;\n } else {\n // Convert absolute to relative from basePath\n resultPath = relative(basePath, filePath);\n }\n\n // Ensure forward slashes (handle both Unix and Windows separators)\n return resultPath.replace(/\\\\/g, '/');\n}\n\n/**\n * Check if a file path matches a glob pattern\n */\nexport function matchesPattern(\n filePath: string,\n pattern: string,\n options: { cwd?: string } = {}\n): boolean {\n const cwd = options.cwd || process.cwd();\n const normalizedPath = normalizePath(filePath, cwd);\n\n return minimatch(normalizedPath, pattern, { matchBase: true });\n}\n\n/**\n * Check if a file path matches any of the given patterns\n */\nexport function matchesAnyPattern(\n filePath: string,\n patterns: string[],\n options: { cwd?: string } = {}\n): boolean {\n return patterns.some((pattern) => matchesPattern(filePath, pattern, options));\n}\n\n// Re-export minimatch for advanced usage\nexport { minimatch };\n","/**\n * Base analyzer interface\n */\nimport type { Pattern, PatternExample } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\n\n/**\n * Analyzer interface - all analyzers must implement this\n */\nexport interface Analyzer {\n /**\n * Unique identifier for this analyzer\n */\n readonly id: string;\n\n /**\n * Human-readable name\n */\n readonly name: string;\n\n /**\n * Description of what this analyzer detects\n */\n readonly description: string;\n\n /**\n * Analyze the codebase and return detected patterns\n */\n analyze(scanner: CodeScanner): Promise<Pattern[]>;\n}\n\n/**\n * Helper to create a pattern with consistent structure\n */\nexport function createPattern(\n analyzer: string,\n params: {\n id: string;\n name: string;\n description: string;\n confidence: number;\n occurrences: number;\n examples: PatternExample[];\n suggestedConstraint?: Pattern['suggestedConstraint'];\n }\n): Pattern {\n return {\n analyzer,\n ...params,\n };\n}\n\n/**\n * Calculate confidence based on occurrence ratio\n */\nexport function calculateConfidence(\n occurrences: number,\n total: number,\n minOccurrences: number = 3\n): number {\n if (occurrences < minOccurrences) {\n return 0;\n }\n\n const ratio = occurrences / total;\n // Scale from 50 (at minOccurrences) to 100 (at 100%)\n return Math.min(100, Math.round(50 + ratio * 50));\n}\n\n/**\n * Extract a code snippet around a line\n */\nexport function extractSnippet(\n content: string,\n line: number,\n contextLines: number = 1\n): string {\n const lines = content.split('\\n');\n const start = Math.max(0, line - 1 - contextLines);\n const end = Math.min(lines.length, line + contextLines);\n\n return lines.slice(start, end).join('\\n');\n}\n","/**\n * Naming convention analyzer\n */\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\ninterface NamingPattern {\n convention: string;\n regex: RegExp;\n description: string;\n}\n\nconst CLASS_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Classes use PascalCase' },\n];\n\nconst FUNCTION_PATTERNS: NamingPattern[] = [\n { convention: 'camelCase', regex: /^[a-z][a-zA-Z0-9]*$/, description: 'Functions use camelCase' },\n { convention: 'snake_case', regex: /^[a-z][a-z0-9_]*$/, description: 'Functions use snake_case' },\n];\n\nconst INTERFACE_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Interfaces use PascalCase' },\n { convention: 'IPrefixed', regex: /^I[A-Z][a-zA-Z0-9]*$/, description: 'Interfaces are prefixed with I' },\n];\n\nconst TYPE_PATTERNS: NamingPattern[] = [\n { convention: 'PascalCase', regex: /^[A-Z][a-zA-Z0-9]*$/, description: 'Types use PascalCase' },\n { convention: 'TSuffixed', regex: /^[A-Z][a-zA-Z0-9]*Type$/, description: 'Types are suffixed with Type' },\n];\n\nexport class NamingAnalyzer implements Analyzer {\n readonly id = 'naming';\n readonly name = 'Naming Convention Analyzer';\n readonly description = 'Detects naming conventions for classes, functions, interfaces, and types';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze class naming\n const classPattern = this.analyzeClassNaming(scanner);\n if (classPattern) patterns.push(classPattern);\n\n // Analyze function naming\n const functionPattern = this.analyzeFunctionNaming(scanner);\n if (functionPattern) patterns.push(functionPattern);\n\n // Analyze interface naming\n const interfacePattern = this.analyzeInterfaceNaming(scanner);\n if (interfacePattern) patterns.push(interfacePattern);\n\n // Analyze type naming\n const typePattern = this.analyzeTypeNaming(scanner);\n if (typePattern) patterns.push(typePattern);\n\n return patterns;\n }\n\n private analyzeClassNaming(scanner: CodeScanner): Pattern | null {\n const classes = scanner.findClasses();\n if (classes.length < 3) return null;\n\n const matches = this.findBestMatch(classes.map(c => c.name), CLASS_PATTERNS);\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-classes',\n name: 'Class Naming Convention',\n description: `Classes follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: classes.slice(0, 3).map(c => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Classes should use ${matches.convention} naming convention`,\n severity: 'medium',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeFunctionNaming(scanner: CodeScanner): Pattern | null {\n const functions = scanner.findFunctions();\n if (functions.length < 3) return null;\n\n const matches = this.findBestMatch(functions.map(f => f.name), FUNCTION_PATTERNS);\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-functions',\n name: 'Function Naming Convention',\n description: `Functions follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: functions.slice(0, 3).map(f => ({\n file: f.file,\n line: f.line,\n snippet: `function ${f.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Functions should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeInterfaceNaming(scanner: CodeScanner): Pattern | null {\n const interfaces = scanner.findInterfaces();\n if (interfaces.length < 3) return null;\n\n const matches = this.findBestMatch(interfaces.map(i => i.name), INTERFACE_PATTERNS);\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-interfaces',\n name: 'Interface Naming Convention',\n description: `Interfaces follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: interfaces.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `interface ${i.name}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Interfaces should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeTypeNaming(scanner: CodeScanner): Pattern | null {\n const types = scanner.findTypeAliases();\n if (types.length < 3) return null;\n\n const matches = this.findBestMatch(types.map(t => t.name), TYPE_PATTERNS);\n if (!matches) return null;\n\n return createPattern(this.id, {\n id: 'naming-types',\n name: 'Type Alias Naming Convention',\n description: `Type aliases follow ${matches.convention} naming convention`,\n confidence: matches.confidence,\n occurrences: matches.matchCount,\n examples: types.slice(0, 3).map(t => ({\n file: t.file,\n line: t.line,\n snippet: `type ${t.name}`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: `Type aliases should use ${matches.convention} naming convention`,\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private findBestMatch(\n names: string[],\n patterns: NamingPattern[]\n ): { convention: string; confidence: number; matchCount: number } | null {\n let bestMatch: { convention: string; matchCount: number } | null = null;\n\n for (const pattern of patterns) {\n const matchCount = names.filter(name => pattern.regex.test(name)).length;\n if (!bestMatch || matchCount > bestMatch.matchCount) {\n bestMatch = { convention: pattern.convention, matchCount };\n }\n }\n\n if (!bestMatch || bestMatch.matchCount < 3) return null;\n\n const confidence = calculateConfidence(bestMatch.matchCount, names.length);\n if (confidence < 50) return null;\n\n return {\n convention: bestMatch.convention,\n confidence,\n matchCount: bestMatch.matchCount,\n };\n }\n}\n","/**\n * Import pattern analyzer\n */\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class ImportsAnalyzer implements Analyzer {\n readonly id = 'imports';\n readonly name = 'Import Pattern Analyzer';\n readonly description = 'Detects import organization patterns and module usage conventions';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze barrel imports\n const barrelPattern = this.analyzeBarrelImports(scanner);\n if (barrelPattern) patterns.push(barrelPattern);\n\n // Analyze relative vs absolute imports\n const relativePattern = this.analyzeRelativeImports(scanner);\n if (relativePattern) patterns.push(relativePattern);\n\n // Analyze commonly used modules\n const modulePatterns = this.analyzeCommonModules(scanner);\n patterns.push(...modulePatterns);\n\n return patterns;\n }\n\n private analyzeBarrelImports(scanner: CodeScanner): Pattern | null {\n const imports = scanner.findImports();\n const barrelImports = imports.filter(i => {\n const modulePath = i.module;\n return modulePath.startsWith('.') && !modulePath.includes('.js') && !modulePath.includes('.ts');\n });\n\n // Check for index imports\n const indexImports = barrelImports.filter(i => {\n return i.module.endsWith('/index') || !i.module.includes('/');\n });\n\n if (indexImports.length < 3) return null;\n\n const confidence = calculateConfidence(indexImports.length, barrelImports.length);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-barrel',\n name: 'Barrel Import Pattern',\n description: 'Modules are imported through barrel (index) files',\n confidence,\n occurrences: indexImports.length,\n examples: indexImports.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 3).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: 'Import from barrel (index) files rather than individual modules',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n private analyzeRelativeImports(scanner: CodeScanner): Pattern | null {\n const imports = scanner.findImports();\n const relativeImports = imports.filter(i => i.module.startsWith('.'));\n const absoluteImports = imports.filter(i => !i.module.startsWith('.') && !i.module.startsWith('@'));\n const aliasImports = imports.filter(i => i.module.startsWith('@/') || i.module.startsWith('~'));\n\n // Determine dominant pattern\n const total = relativeImports.length + absoluteImports.length + aliasImports.length;\n if (total < 10) return null;\n\n if (aliasImports.length > relativeImports.length && aliasImports.length >= 5) {\n const confidence = calculateConfidence(aliasImports.length, total);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-alias',\n name: 'Path Alias Import Pattern',\n description: 'Imports use path aliases (@ or ~) instead of relative paths',\n confidence,\n occurrences: aliasImports.length,\n examples: aliasImports.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: 'Use path aliases instead of relative imports',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n if (relativeImports.length > aliasImports.length * 2 && relativeImports.length >= 5) {\n const confidence = calculateConfidence(relativeImports.length, total);\n if (confidence < 50) return null;\n\n return createPattern(this.id, {\n id: 'imports-relative',\n name: 'Relative Import Pattern',\n description: 'Imports use relative paths',\n confidence,\n occurrences: relativeImports.length,\n examples: relativeImports.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ')} } from '${i.module}'`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Use relative imports for local modules',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeCommonModules(scanner: CodeScanner): Pattern[] {\n const patterns: Pattern[] = [];\n const imports = scanner.findImports();\n\n // Count external module usage\n const moduleCounts = new Map<string, { count: number; examples: typeof imports }>();\n\n for (const imp of imports) {\n // Skip relative imports\n if (imp.module.startsWith('.')) continue;\n\n // Get the package name (handle scoped packages)\n const parts = imp.module.split('/');\n const packageName = imp.module.startsWith('@') && parts.length > 1\n ? `${parts[0]}/${parts[1]}`\n : parts[0];\n\n if (packageName) {\n const existing = moduleCounts.get(packageName) || { count: 0, examples: [] };\n existing.count++;\n existing.examples.push(imp);\n moduleCounts.set(packageName, existing);\n }\n }\n\n // Create patterns for commonly used modules\n for (const [packageName, data] of moduleCounts) {\n if (data.count >= 5) {\n const confidence = Math.min(100, 50 + data.count * 2);\n\n patterns.push(createPattern(this.id, {\n id: `imports-module-${packageName.replace(/[/@]/g, '-')}`,\n name: `${packageName} Usage`,\n description: `${packageName} is used across ${data.count} files`,\n confidence,\n occurrences: data.count,\n examples: data.examples.slice(0, 3).map(i => ({\n file: i.file,\n line: i.line,\n snippet: `import { ${i.named.slice(0, 2).join(', ') || '...'} } from '${i.module}'`,\n })),\n }));\n }\n }\n\n return patterns;\n }\n}\n","/**\n * Code structure pattern analyzer\n */\nimport { basename, dirname } from 'node:path';\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner, ScannedFile } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class StructureAnalyzer implements Analyzer {\n readonly id = 'structure';\n readonly name = 'Code Structure Analyzer';\n readonly description = 'Detects file organization and directory structure patterns';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n const files = scanner.getFiles();\n\n // Analyze directory conventions\n const dirPatterns = this.analyzeDirectoryConventions(files);\n patterns.push(...dirPatterns);\n\n // Analyze file naming conventions\n const filePatterns = this.analyzeFileNaming(files);\n patterns.push(...filePatterns);\n\n // Analyze colocation patterns\n const colocationPattern = this.analyzeColocation(files);\n if (colocationPattern) patterns.push(colocationPattern);\n\n return patterns;\n }\n\n private analyzeDirectoryConventions(files: ScannedFile[]): Pattern[] {\n const patterns: Pattern[] = [];\n const dirCounts = new Map<string, number>();\n\n // Count files per directory name\n for (const file of files) {\n const dir = basename(dirname(file.path));\n dirCounts.set(dir, (dirCounts.get(dir) || 0) + 1);\n }\n\n // Check for common directory structures\n const commonDirs = [\n { name: 'components', description: 'UI components are organized in a components directory' },\n { name: 'hooks', description: 'Custom hooks are organized in a hooks directory' },\n { name: 'utils', description: 'Utility functions are organized in a utils directory' },\n { name: 'services', description: 'Service modules are organized in a services directory' },\n { name: 'types', description: 'Type definitions are organized in a types directory' },\n { name: 'api', description: 'API modules are organized in an api directory' },\n { name: 'lib', description: 'Library code is organized in a lib directory' },\n { name: 'core', description: 'Core modules are organized in a core directory' },\n ];\n\n for (const { name, description } of commonDirs) {\n const count = dirCounts.get(name);\n if (count && count >= 3) {\n const exampleFiles = files\n .filter(f => basename(dirname(f.path)) === name)\n .slice(0, 3);\n\n patterns.push(createPattern(this.id, {\n id: `structure-dir-${name}`,\n name: `${name}/ Directory Convention`,\n description,\n confidence: Math.min(100, 60 + count * 5),\n occurrences: count,\n examples: exampleFiles.map(f => ({\n file: f.path,\n line: 1,\n snippet: basename(f.path),\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `${name.charAt(0).toUpperCase() + name.slice(1)} should be placed in the ${name}/ directory`,\n severity: 'low',\n scope: `src/**/${name}/**/*.ts`,\n },\n }));\n }\n }\n\n return patterns;\n }\n\n private analyzeFileNaming(files: ScannedFile[]): Pattern[] {\n const patterns: Pattern[] = [];\n\n // Check for suffix patterns\n const suffixPatterns: { suffix: string; pattern: RegExp; description: string }[] = [\n { suffix: '.test.ts', pattern: /\\.test\\.ts$/, description: 'Test files use .test.ts suffix' },\n { suffix: '.spec.ts', pattern: /\\.spec\\.ts$/, description: 'Test files use .spec.ts suffix' },\n { suffix: '.types.ts', pattern: /\\.types\\.ts$/, description: 'Type definition files use .types.ts suffix' },\n { suffix: '.utils.ts', pattern: /\\.utils\\.ts$/, description: 'Utility files use .utils.ts suffix' },\n { suffix: '.service.ts', pattern: /\\.service\\.ts$/, description: 'Service files use .service.ts suffix' },\n { suffix: '.controller.ts', pattern: /\\.controller\\.ts$/, description: 'Controller files use .controller.ts suffix' },\n { suffix: '.model.ts', pattern: /\\.model\\.ts$/, description: 'Model files use .model.ts suffix' },\n { suffix: '.schema.ts', pattern: /\\.schema\\.ts$/, description: 'Schema files use .schema.ts suffix' },\n ];\n\n for (const { suffix, pattern, description } of suffixPatterns) {\n const matchingFiles = files.filter(f => pattern.test(f.path));\n\n if (matchingFiles.length >= 3) {\n const confidence = Math.min(100, 60 + matchingFiles.length * 3);\n\n patterns.push(createPattern(this.id, {\n id: `structure-suffix-${suffix.replace(/\\./g, '-')}`,\n name: `${suffix} File Naming`,\n description,\n confidence,\n occurrences: matchingFiles.length,\n examples: matchingFiles.slice(0, 3).map(f => ({\n file: f.path,\n line: 1,\n snippet: basename(f.path),\n })),\n }));\n }\n }\n\n return patterns;\n }\n\n private analyzeColocation(files: ScannedFile[]): Pattern | null {\n // Check if test files are colocated with source files\n const testFiles = files.filter(f => /\\.(test|spec)\\.tsx?$/.test(f.path));\n const sourceFiles = files.filter(f => !/\\.(test|spec)\\.tsx?$/.test(f.path));\n\n if (testFiles.length < 3) return null;\n\n let colocatedCount = 0;\n const colocatedExamples: { file: string; line: number; snippet: string }[] = [];\n\n for (const testFile of testFiles) {\n const testDir = dirname(testFile.path);\n const testName = basename(testFile.path).replace(/\\.(test|spec)\\.tsx?$/, '');\n\n // Check if corresponding source file is in same directory\n const hasColocatedSource = sourceFiles.some(\n s => dirname(s.path) === testDir && basename(s.path).startsWith(testName)\n );\n\n if (hasColocatedSource) {\n colocatedCount++;\n if (colocatedExamples.length < 3) {\n colocatedExamples.push({\n file: testFile.path,\n line: 1,\n snippet: basename(testFile.path),\n });\n }\n }\n }\n\n const confidence = calculateConfidence(colocatedCount, testFiles.length);\n if (confidence < 60) return null;\n\n return createPattern(this.id, {\n id: 'structure-colocation',\n name: 'Test Colocation Pattern',\n description: 'Test files are colocated with their source files',\n confidence,\n occurrences: colocatedCount,\n examples: colocatedExamples,\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Test files should be colocated with their source files',\n severity: 'low',\n scope: 'src/**/*.test.ts',\n },\n });\n }\n}\n","/**\n * Error handling pattern analyzer\n */\nimport { Node } from 'ts-morph';\nimport type { Pattern } from '../../core/types/index.js';\nimport type { CodeScanner } from '../scanner.js';\nimport { type Analyzer, createPattern, calculateConfidence } from './base.js';\n\nexport class ErrorsAnalyzer implements Analyzer {\n readonly id = 'errors';\n readonly name = 'Error Handling Analyzer';\n readonly description = 'Detects error handling patterns and custom error class usage';\n\n async analyze(scanner: CodeScanner): Promise<Pattern[]> {\n const patterns: Pattern[] = [];\n\n // Analyze custom error classes\n const errorClassPattern = this.analyzeCustomErrorClasses(scanner);\n if (errorClassPattern) patterns.push(errorClassPattern);\n\n // Analyze try-catch patterns\n const tryCatchPattern = this.analyzeTryCatchPatterns(scanner);\n if (tryCatchPattern) patterns.push(tryCatchPattern);\n\n // Analyze error throwing patterns\n const throwPattern = this.analyzeThrowPatterns(scanner);\n if (throwPattern) patterns.push(throwPattern);\n\n return patterns;\n }\n\n private analyzeCustomErrorClasses(scanner: CodeScanner): Pattern | null {\n const classes = scanner.findClasses();\n const errorClasses = classes.filter(c =>\n c.name.endsWith('Error') || c.name.endsWith('Exception')\n );\n\n if (errorClasses.length < 2) return null;\n\n // Check if they extend a common base\n const files = scanner.getFiles();\n const baseCount: Map<string, number> = new Map();\n\n for (const errorClass of errorClasses) {\n const file = files.find(f => f.path === errorClass.file);\n if (!file) continue;\n\n const classDecl = file.sourceFile.getClass(errorClass.name);\n if (!classDecl) continue;\n\n const extendClause = classDecl.getExtends();\n if (extendClause) {\n const baseName = extendClause.getText();\n if (baseName !== 'Error' && baseName.endsWith('Error')) {\n baseCount.set(baseName, (baseCount.get(baseName) || 0) + 1);\n }\n }\n }\n\n // Find the custom base with the most extending classes\n let customBaseName: string | null = null;\n let maxCount = 0;\n for (const [baseName, count] of baseCount.entries()) {\n if (count > maxCount) {\n maxCount = count;\n customBaseName = baseName;\n }\n }\n\n // Check for custom base pattern (requires >= 3 extending the same custom base)\n if (maxCount >= 3 && customBaseName) {\n const confidence = calculateConfidence(maxCount, errorClasses.length);\n\n return createPattern(this.id, {\n id: 'errors-custom-base',\n name: 'Custom Error Base Class',\n description: `Custom errors extend a common base class (${customBaseName})`,\n confidence,\n occurrences: maxCount,\n examples: errorClasses.slice(0, 3).map(c => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name} extends ${customBaseName}`,\n })),\n suggestedConstraint: {\n type: 'convention',\n rule: `Custom error classes should extend ${customBaseName}`,\n severity: 'medium',\n scope: 'src/**/*.ts',\n verifier: 'errors',\n },\n });\n }\n\n // Fall back to generic custom error classes pattern (requires >= 3 error classes)\n if (errorClasses.length >= 3) {\n const confidence = Math.min(100, 50 + errorClasses.length * 5);\n\n return createPattern(this.id, {\n id: 'errors-custom-classes',\n name: 'Custom Error Classes',\n description: 'Custom error classes are used for domain-specific errors',\n confidence,\n occurrences: errorClasses.length,\n examples: errorClasses.slice(0, 3).map(c => ({\n file: c.file,\n line: c.line,\n snippet: `class ${c.name}`,\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Use custom error classes for domain-specific errors',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeTryCatchPatterns(scanner: CodeScanner): Pattern | null {\n const tryCatchBlocks = scanner.findTryCatchBlocks();\n\n if (tryCatchBlocks.length < 3) return null;\n\n // Check how many rethrow vs swallow\n const rethrowCount = tryCatchBlocks.filter(b => b.hasThrow).length;\n const swallowCount = tryCatchBlocks.length - rethrowCount;\n\n if (rethrowCount >= 3 && rethrowCount > swallowCount) {\n const confidence = calculateConfidence(rethrowCount, tryCatchBlocks.length);\n\n return createPattern(this.id, {\n id: 'errors-rethrow',\n name: 'Error Rethrow Pattern',\n description: 'Caught errors are typically rethrown after handling',\n confidence,\n occurrences: rethrowCount,\n examples: tryCatchBlocks\n .filter(b => b.hasThrow)\n .slice(0, 3)\n .map(b => ({\n file: b.file,\n line: b.line,\n snippet: 'try { ... } catch (e) { ... throw ... }',\n })),\n suggestedConstraint: {\n type: 'guideline',\n rule: 'Caught errors should be rethrown or wrapped after handling',\n severity: 'low',\n scope: 'src/**/*.ts',\n },\n });\n }\n\n return null;\n }\n\n private analyzeThrowPatterns(scanner: CodeScanner): Pattern | null {\n const files = scanner.getFiles();\n let throwNewError = 0;\n let throwCustom = 0;\n const examples: { file: string; line: number; snippet: string }[] = [];\n\n for (const { path, sourceFile } of files) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isThrowStatement(node)) {\n const expression = node.getExpression();\n if (expression) {\n const text = expression.getText();\n if (text.startsWith('new Error(')) {\n throwNewError++;\n } else if (text.startsWith('new ') && text.includes('Error')) {\n throwCustom++;\n if (examples.length < 3) {\n const snippet = text.length > 50 ? text.slice(0, 50) + '...' : text;\n examples.push({\n file: path,\n line: node.getStartLineNumber(),\n snippet: `throw ${snippet}`,\n });\n }\n }\n }\n }\n });\n }\n\n if (throwCustom >= 3 && throwCustom > throwNewError) {\n const confidence = calculateConfidence(throwCustom, throwCustom + throwNewError);\n\n return createPattern(this.id, {\n id: 'errors-throw-custom',\n name: 'Custom Error Throwing',\n description: 'Custom error classes are thrown instead of generic Error',\n confidence,\n occurrences: throwCustom,\n examples,\n suggestedConstraint: {\n type: 'convention',\n rule: 'Throw custom error classes instead of generic Error',\n severity: 'medium',\n scope: 'src/**/*.ts',\n verifier: 'errors',\n },\n });\n }\n\n return null;\n }\n}\n","/**\n * Analyzer exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './structure.js';\nexport * from './errors.js';\n\nimport type { Analyzer } from './base.js';\nimport { NamingAnalyzer } from './naming.js';\nimport { ImportsAnalyzer } from './imports.js';\nimport { StructureAnalyzer } from './structure.js';\nimport { ErrorsAnalyzer } from './errors.js';\n\n/**\n * Built-in analyzers registry\n */\nexport const builtinAnalyzers: Record<string, () => Analyzer> = {\n naming: () => new NamingAnalyzer(),\n imports: () => new ImportsAnalyzer(),\n structure: () => new StructureAnalyzer(),\n errors: () => new ErrorsAnalyzer(),\n};\n\n/**\n * Get analyzer by ID\n */\nexport function getAnalyzer(id: string): Analyzer | null {\n const factory = builtinAnalyzers[id];\n return factory ? factory() : null;\n}\n\n/**\n * Get all analyzer IDs\n */\nexport function getAnalyzerIds(): string[] {\n return Object.keys(builtinAnalyzers);\n}\n","/**\n * Inference Engine - Orchestrates pattern detection\n */\nimport type { Pattern, InferenceResult, SpecBridgeConfig } from '../core/types/index.js';\nimport { AnalyzerNotFoundError } from '../core/errors/index.js';\nimport { CodeScanner } from './scanner.js';\nimport { getAnalyzer, getAnalyzerIds, type Analyzer } from './analyzers/index.js';\n\nexport interface InferenceOptions {\n analyzers?: string[];\n minConfidence?: number;\n sourceRoots?: string[];\n exclude?: string[];\n cwd?: string;\n}\n\n/**\n * Inference Engine class\n */\nexport class InferenceEngine {\n private scanner: CodeScanner;\n private analyzers: Analyzer[] = [];\n\n constructor() {\n this.scanner = new CodeScanner();\n }\n\n /**\n * Configure analyzers to use\n */\n configureAnalyzers(analyzerIds: string[]): void {\n this.analyzers = [];\n\n for (const id of analyzerIds) {\n const analyzer = getAnalyzer(id);\n if (!analyzer) {\n throw new AnalyzerNotFoundError(id);\n }\n this.analyzers.push(analyzer);\n }\n }\n\n /**\n * Run inference on the codebase\n */\n async infer(options: InferenceOptions): Promise<InferenceResult> {\n const startTime = Date.now();\n\n const {\n analyzers: analyzerIds = getAnalyzerIds(),\n minConfidence = 50,\n sourceRoots = ['src/**/*.ts', 'src/**/*.tsx'],\n exclude = ['**/*.test.ts', '**/*.spec.ts', '**/node_modules/**', '**/dist/**'],\n cwd = process.cwd(),\n } = options;\n\n // Configure analyzers\n this.configureAnalyzers(analyzerIds);\n\n // Scan codebase\n const scanResult = await this.scanner.scan({\n sourceRoots,\n exclude,\n cwd,\n });\n\n if (scanResult.totalFiles === 0) {\n return {\n patterns: [],\n analyzersRun: analyzerIds,\n filesScanned: 0,\n duration: Date.now() - startTime,\n };\n }\n\n // Run all analyzers\n const allPatterns: Pattern[] = [];\n\n for (const analyzer of this.analyzers) {\n try {\n const patterns = await analyzer.analyze(this.scanner);\n allPatterns.push(...patterns);\n } catch (error) {\n // Log but don't fail on individual analyzer errors\n console.warn(`Analyzer ${analyzer.id} failed:`, error);\n }\n }\n\n // Filter by minimum confidence\n const filteredPatterns = allPatterns.filter(p => p.confidence >= minConfidence);\n\n // Sort by confidence (highest first)\n filteredPatterns.sort((a, b) => b.confidence - a.confidence);\n\n return {\n patterns: filteredPatterns,\n analyzersRun: analyzerIds,\n filesScanned: scanResult.totalFiles,\n duration: Date.now() - startTime,\n };\n }\n\n /**\n * Get scanner for direct access\n */\n getScanner(): CodeScanner {\n return this.scanner;\n }\n}\n\n/**\n * Create an inference engine from config\n */\nexport function createInferenceEngine(): InferenceEngine {\n return new InferenceEngine();\n}\n\n/**\n * Run inference with config\n */\nexport async function runInference(\n config: SpecBridgeConfig,\n options?: Partial<InferenceOptions>\n): Promise<InferenceResult> {\n const engine = createInferenceEngine();\n\n return engine.infer({\n analyzers: config.inference?.analyzers,\n minConfidence: config.inference?.minConfidence,\n sourceRoots: config.project.sourceRoots,\n exclude: config.project.exclude,\n ...options,\n });\n}\n","/**\n * Configuration loader\n */\nimport type { SpecBridgeConfig } from '../core/types/index.js';\nimport { validateConfig, defaultConfig } from '../core/schemas/config.schema.js';\nimport { ConfigError, NotInitializedError } from '../core/errors/index.js';\nimport { readTextFile, pathExists, getConfigPath, getSpecBridgeDir } from '../utils/fs.js';\nimport { parseYaml } from '../utils/yaml.js';\n\n/**\n * Load configuration from .specbridge/config.yaml\n */\nexport async function loadConfig(basePath: string = process.cwd()): Promise<SpecBridgeConfig> {\n const specbridgeDir = getSpecBridgeDir(basePath);\n const configPath = getConfigPath(basePath);\n\n // Check if specbridge is initialized\n if (!await pathExists(specbridgeDir)) {\n throw new NotInitializedError();\n }\n\n // Check if config file exists\n if (!await pathExists(configPath)) {\n // Return default config if no config file\n return defaultConfig;\n }\n\n // Load and parse config\n const content = await readTextFile(configPath);\n const parsed = parseYaml(content);\n\n // Validate config\n const result = validateConfig(parsed);\n if (!result.success) {\n const errors = result.errors.errors.map(e => `${e.path.join('.')}: ${e.message}`);\n throw new ConfigError(`Invalid configuration in ${configPath}`, { errors });\n }\n\n return result.data as SpecBridgeConfig;\n}\n\n/**\n * Merge partial config with defaults\n */\nexport function mergeWithDefaults(partial: Partial<SpecBridgeConfig>): SpecBridgeConfig {\n return {\n ...defaultConfig,\n ...partial,\n project: {\n ...defaultConfig.project,\n ...partial.project,\n },\n inference: {\n ...defaultConfig.inference,\n ...partial.inference,\n },\n verification: {\n ...defaultConfig.verification,\n ...partial.verification,\n levels: {\n ...defaultConfig.verification?.levels,\n ...partial.verification?.levels,\n },\n },\n agent: {\n ...defaultConfig.agent,\n ...partial.agent,\n },\n };\n}\n","/**\n * Verify command - Check code compliance\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { AutofixEngine, type AutofixResult } from '../../verification/autofix/engine.js';\nimport { getChangedFiles } from '../../verification/incremental.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { ExplainReporter } from '../../verification/explain.js';\nimport type { Violation, VerificationLevel, Severity } from '../../core/types/index.js';\n\ninterface VerifyOptions {\n level?: string;\n files?: string;\n decisions?: string;\n severity?: string;\n json?: boolean;\n fix?: boolean;\n dryRun?: boolean;\n interactive?: boolean;\n incremental?: boolean;\n explain?: boolean;\n}\n\nexport const verifyCommand = new Command('verify')\n .description('Verify code compliance against decisions')\n .option('-l, --level <level>', 'Verification level (commit, pr, full)', 'full')\n .option('-f, --files <patterns>', 'Comma-separated file patterns to check')\n .option('-d, --decisions <ids>', 'Comma-separated decision IDs to check')\n .option('-s, --severity <levels>', 'Comma-separated severity levels (critical, high, medium, low)')\n .option('--json', 'Output as JSON')\n .option('--incremental', 'Only verify changed files (git diff --name-only --diff-filter=AM HEAD)')\n .option('--explain', 'Show detailed explanation of verification process')\n .option('--fix', 'Apply auto-fixes for supported violations')\n .option('--dry-run', 'Show what would be fixed without applying (requires --fix)')\n .option('--interactive', 'Confirm each fix interactively (requires --fix)')\n .action(async (options: VerifyOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Loading configuration...').start();\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Parse options\n const level = (options.level || 'full') as VerificationLevel;\n let files = options.files?.split(',').map(f => f.trim());\n const decisions = options.decisions?.split(',').map(d => d.trim());\n const severity = options.severity?.split(',').map(s => s.trim() as Severity);\n\n if (options.incremental) {\n const changed = await getChangedFiles(cwd);\n files = changed.length > 0 ? changed : [];\n }\n\n spinner.text = `Running ${level}-level verification...`;\n\n // Create explain reporter if requested\n const reporter = options.explain ? new ExplainReporter() : undefined;\n\n // Run verification\n const engine = createVerificationEngine();\n let result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n reporter,\n });\n\n // Apply auto-fixes (optional)\n let fixResult: AutofixResult | undefined;\n if (options.fix && result.violations.length > 0) {\n const fixableCount = result.violations.filter(v => v.autofix).length;\n\n if (fixableCount === 0) {\n spinner.stop();\n if (!options.json) {\n console.log(chalk.yellow('No auto-fixable violations found'));\n }\n } else {\n spinner.text = `Applying ${fixableCount} auto-fix(es)...`;\n const fixer = new AutofixEngine();\n fixResult = await fixer.applyFixes(result.violations, {\n dryRun: options.dryRun,\n interactive: options.interactive,\n });\n\n if (!options.dryRun && fixResult.applied.length > 0) {\n result = await engine.verify(config, {\n level,\n files,\n decisions,\n severity,\n cwd,\n });\n }\n }\n }\n\n spinner.stop();\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify({ ...result, autofix: fixResult }, null, 2));\n } else {\n // Display warnings and errors first\n if (result.warnings && result.warnings.length > 0) {\n console.log(chalk.yellow.bold('\\nWarnings:'));\n for (const warning of result.warnings) {\n console.log(chalk.yellow(` ⚠ ${warning.message}`));\n console.log(chalk.dim(` ${warning.decisionId}/${warning.constraintId}`));\n if (warning.file) {\n console.log(chalk.dim(` File: ${warning.file}`));\n }\n }\n console.log('');\n }\n\n if (result.errors && result.errors.length > 0) {\n console.log(chalk.red.bold('\\nErrors:'));\n for (const error of result.errors) {\n console.log(chalk.red(` ✗ ${error.message}`));\n if (error.decisionId && error.constraintId) {\n console.log(chalk.dim(` ${error.decisionId}/${error.constraintId}`));\n }\n if (error.file) {\n console.log(chalk.dim(` File: ${error.file}`));\n }\n }\n console.log('');\n }\n\n printResult(result, level);\n\n if (options.fix && fixResult) {\n console.log(chalk.green(`✓ Applied ${fixResult.applied.length} fix(es)`));\n if (fixResult.skipped > 0) {\n console.log(chalk.yellow(`⊘ Skipped ${fixResult.skipped} fix(es)`));\n }\n console.log('');\n }\n\n // Print explanation if requested\n if (options.explain && reporter) {\n reporter.print();\n }\n }\n\n // Exit with error code if verification failed\n if (!result.success) {\n process.exit(1);\n }\n } catch (error) {\n spinner.fail('Verification failed');\n throw error;\n }\n });\n\nfunction printResult(\n result: { success: boolean; violations: Violation[]; checked: number; passed: number; failed: number; skipped: number; duration: number },\n level: VerificationLevel\n): void {\n console.log('');\n\n if (result.violations.length === 0) {\n console.log(chalk.green('✓ All checks passed!'));\n console.log(chalk.dim(` ${result.checked} files checked in ${result.duration}ms`));\n return;\n }\n\n // Group violations by file\n const byFile = new Map<string, Violation[]>();\n for (const violation of result.violations) {\n const existing = byFile.get(violation.file) || [];\n existing.push(violation);\n byFile.set(violation.file, existing);\n }\n\n // Print violations by file\n for (const [file, violations] of byFile) {\n console.log(chalk.underline(file));\n\n for (const v of violations) {\n const typeIcon = getTypeIcon(v.type);\n const severityColor = getSeverityColor(v.severity);\n const location = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n\n console.log(\n ` ${typeIcon} ${severityColor(`[${v.severity}]`)} ${v.message}`\n );\n console.log(chalk.dim(` ${v.decisionId}/${v.constraintId}${location}`));\n\n if (v.suggestion) {\n console.log(chalk.cyan(` Suggestion: ${v.suggestion}`));\n }\n }\n\n console.log('');\n }\n\n // Summary\n const criticalCount = result.violations.filter(v => v.severity === 'critical').length;\n const highCount = result.violations.filter(v => v.severity === 'high').length;\n const mediumCount = result.violations.filter(v => v.severity === 'medium').length;\n const lowCount = result.violations.filter(v => v.severity === 'low').length;\n\n console.log(chalk.bold('Summary:'));\n console.log(` Files: ${result.checked} checked, ${result.passed} passed, ${result.failed} failed`);\n\n const violationParts: string[] = [];\n if (criticalCount > 0) violationParts.push(chalk.red(`${criticalCount} critical`));\n if (highCount > 0) violationParts.push(chalk.yellow(`${highCount} high`));\n if (mediumCount > 0) violationParts.push(chalk.cyan(`${mediumCount} medium`));\n if (lowCount > 0) violationParts.push(chalk.dim(`${lowCount} low`));\n\n console.log(` Violations: ${violationParts.join(', ')}`);\n console.log(` Duration: ${result.duration}ms`);\n\n if (!result.success) {\n console.log('');\n const blockingTypes = level === 'commit'\n ? 'invariant or critical'\n : level === 'pr'\n ? 'invariant, critical, or high'\n : 'invariant';\n console.log(chalk.red(`✗ Verification failed. ${blockingTypes} violations must be resolved.`));\n }\n}\n\nfunction getTypeIcon(type: string): string {\n switch (type) {\n case 'invariant':\n return chalk.red('●');\n case 'convention':\n return chalk.yellow('●');\n case 'guideline':\n return chalk.green('●');\n default:\n return '○';\n }\n}\n\nfunction getSeverityColor(severity: Severity): (text: string) => string {\n switch (severity) {\n case 'critical':\n return chalk.red;\n case 'high':\n return chalk.yellow;\n case 'medium':\n return chalk.cyan;\n case 'low':\n return chalk.dim;\n default:\n return chalk.white;\n }\n}\n","/**\n * Verification Engine - Orchestrates constraint checking\n */\nimport { Project } from 'ts-morph';\nimport chalk from 'chalk';\nimport type {\n Violation,\n VerificationResult,\n VerificationLevel,\n Severity,\n SpecBridgeConfig,\n Decision,\n VerificationWarning,\n VerificationIssue,\n} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { selectVerifierForConstraint, getVerifierIds, type VerificationContext } from './verifiers/index.js';\nimport { glob } from '../utils/glob.js';\nimport { AstCache } from './cache.js';\nimport { ResultsCache } from './results-cache.js';\nimport { shouldApplyConstraintToFile } from './applicability.js';\nimport { ExplainReporter } from './explain.js';\nimport { getPluginLoader } from './plugins/loader.js';\nimport { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\n\nexport interface VerificationOptions {\n level?: VerificationLevel;\n files?: string[];\n decisions?: string[];\n severity?: Severity[];\n timeout?: number;\n cwd?: string;\n reporter?: ExplainReporter;\n}\n\n/**\n * Verification Engine class\n */\nexport class VerificationEngine {\n private registry: Registry;\n private project: Project;\n private astCache: AstCache;\n private resultsCache: ResultsCache;\n private pluginsLoaded = false;\n\n constructor(registry?: Registry) {\n this.registry = registry || createRegistry();\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n this.astCache = new AstCache();\n this.resultsCache = new ResultsCache();\n }\n\n /**\n * Run verification\n */\n async verify(\n config: SpecBridgeConfig,\n options: VerificationOptions = {}\n ): Promise<VerificationResult> {\n const startTime = Date.now();\n\n const {\n level = 'full',\n files: specificFiles,\n decisions: decisionIds,\n cwd = process.cwd(),\n } = options;\n\n // Get level-specific settings\n const levelConfig = config.verification?.levels?.[level];\n const severityFilter = options.severity || levelConfig?.severity;\n const timeout = options.timeout || levelConfig?.timeout || 60000;\n\n // Load plugins once per engine instance\n if (!this.pluginsLoaded) {\n await getPluginLoader().loadPlugins(cwd);\n this.pluginsLoaded = true;\n }\n\n // Load registry if not already loaded\n await this.registry.load();\n\n // Get decisions to verify\n let decisions = this.registry.getActive();\n if (decisionIds && decisionIds.length > 0) {\n decisions = decisions.filter(d => decisionIds.includes(d.metadata.id));\n }\n\n // Get files to verify\n const filesToVerify = specificFiles\n ? specificFiles\n : await glob(config.project.sourceRoots, {\n cwd,\n ignore: config.project.exclude,\n absolute: true,\n });\n\n if (filesToVerify.length === 0) {\n return {\n success: true,\n violations: [],\n checked: 0,\n passed: 0,\n failed: 0,\n skipped: 0,\n duration: Date.now() - startTime,\n warnings: [],\n errors: [],\n };\n }\n\n // Collect all violations, warnings, and errors\n const allViolations: Violation[] = [];\n const allWarnings: VerificationWarning[] = [];\n const allErrors: VerificationIssue[] = [];\n let checked = 0;\n let passed = 0;\n let failed = 0;\n const skipped = 0;\n\n // 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 options.reporter,\n (violations, warnings, errors) => {\n allViolations.push(...violations);\n allWarnings.push(...warnings);\n allErrors.push(...errors);\n checked++;\n if (violations.length > 0) {\n failed++;\n } else {\n passed++;\n }\n }\n );\n\n let result: void | 'timeout';\n try {\n result = await Promise.race([verificationPromise, timeoutPromise]);\n\n if (result === 'timeout') {\n return {\n success: false,\n violations: allViolations,\n checked,\n passed,\n failed,\n skipped: filesToVerify.length - checked,\n duration: timeout,\n warnings: allWarnings,\n errors: allErrors,\n };\n }\n } finally {\n // Always clear the timeout to prevent event loop leak\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n timeoutHandle = null;\n }\n }\n\n // Determine success based on level\n const hasBlockingViolations = allViolations.some(v => {\n if (level === 'commit') {\n return v.type === 'invariant' || v.severity === 'critical';\n }\n if (level === 'pr') {\n return v.type === 'invariant' || v.severity === 'critical' || v.severity === 'high';\n }\n return v.type === 'invariant';\n });\n\n return {\n success: !hasBlockingViolations,\n violations: allViolations,\n checked,\n passed,\n failed,\n skipped,\n duration: Date.now() - startTime,\n warnings: allWarnings,\n errors: allErrors,\n };\n }\n\n /**\n * Verify a single file\n */\n async verifyFile(\n filePath: string,\n decisions: Decision[],\n severityFilter?: Severity[],\n cwd: string = process.cwd(),\n reporter?: ExplainReporter\n ): Promise<{ violations: Violation[]; warnings: VerificationWarning[]; errors: VerificationIssue[] }> {\n const violations: Violation[] = [];\n const warnings: VerificationWarning[] = [];\n const errors: VerificationIssue[] = [];\n\n const sourceFile = await this.astCache.get(filePath, this.project);\n if (!sourceFile) return { violations, warnings, errors };\n\n // Compute file hash once for caching\n let fileHash: string | null = null;\n try {\n const content = await readFile(filePath, 'utf-8');\n fileHash = createHash('sha256').update(content).digest('hex');\n } catch {\n // If we can't read the file, skip caching\n fileHash = null;\n }\n\n // Check each decision's constraints\n for (const decision of decisions) {\n for (const constraint of decision.constraints) {\n // Check if file matches constraint scope\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd, severityFilter })) {\n // Track skipped constraint in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: false,\n reason: 'File does not match scope pattern or severity filter',\n });\n }\n continue;\n }\n\n // Get appropriate verifier\n const verifier = selectVerifierForConstraint(\n constraint.rule,\n constraint.verifier,\n constraint.check\n );\n\n if (!verifier) {\n // Determine what was requested\n const requestedVerifier = constraint.check?.verifier || constraint.verifier || 'auto-detected';\n\n console.warn(\n chalk.yellow(\n `Warning: No verifier found for ${decision.metadata.id}/${constraint.id}\\n` +\n ` Requested: ${requestedVerifier}\\n` +\n ` Available: ${getVerifierIds().join(', ')}`\n )\n );\n\n warnings.push({\n type: 'missing_verifier',\n message: `No verifier found for constraint (requested: ${requestedVerifier})`,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n file: filePath,\n });\n\n // Track in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: false,\n reason: `No verifier found (requested: ${requestedVerifier})`,\n });\n }\n\n continue;\n }\n\n // Check results cache first\n let constraintViolations: Violation[];\n\n if (fileHash) {\n const cacheKey = {\n filePath,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n fileHash,\n };\n\n const cached = this.resultsCache.get(cacheKey);\n if (cached) {\n // Cache hit!\n constraintViolations = cached;\n violations.push(...constraintViolations);\n\n // Track in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope (cached)',\n selectedVerifier: verifier.id,\n });\n }\n\n continue;\n }\n }\n\n // Run verification\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n };\n\n const verificationStart = Date.now();\n try {\n constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n\n // Cache results\n if (fileHash) {\n this.resultsCache.set(\n {\n filePath,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n fileHash,\n },\n constraintViolations\n );\n }\n\n // Track successful verification in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope',\n selectedVerifier: verifier.id,\n verifierOutput: {\n violations: constraintViolations.length,\n duration: Date.now() - verificationStart,\n },\n });\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack = error instanceof Error ? error.stack : undefined;\n\n console.error(\n chalk.red(\n `Error: Verifier '${verifier.id}' failed\\n` +\n ` File: ${filePath}\\n` +\n ` Decision: ${decision.metadata.id}/${constraint.id}\\n` +\n ` Error: ${errorMessage}`\n )\n );\n\n if (errorStack) {\n console.error(chalk.dim(errorStack));\n }\n\n errors.push({\n type: 'verifier_exception',\n message: `Verifier '${verifier.id}' failed: ${errorMessage}`,\n decisionId: decision.metadata.id,\n constraintId: constraint.id,\n file: filePath,\n stack: errorStack,\n });\n\n // Track failed verification in reporter\n if (reporter) {\n reporter.add({\n file: filePath,\n decision,\n constraint,\n applied: true,\n reason: 'Constraint matches file scope',\n selectedVerifier: verifier.id,\n verifierOutput: {\n violations: 0,\n duration: Date.now() - verificationStart,\n error: errorMessage,\n },\n });\n }\n }\n }\n }\n\n return { violations, warnings, errors };\n }\n\n /**\n * Verify multiple files\n */\n private async verifyFiles(\n files: string[],\n decisions: Decision[],\n severityFilter: Severity[] | undefined,\n cwd: string,\n reporter: ExplainReporter | undefined,\n onFileVerified: (violations: Violation[], warnings: VerificationWarning[], errors: VerificationIssue[]) => void\n ): Promise<void> {\n const BATCH_SIZE = 50; // Increased from 10 for better parallelism\n for (let i = 0; i < files.length; i += BATCH_SIZE) {\n const batch = files.slice(i, i + BATCH_SIZE);\n const results = await Promise.all(\n batch.map(file => this.verifyFile(file, decisions, severityFilter, cwd, reporter))\n );\n\n for (const result of results) {\n onFileVerified(result.violations, result.warnings, result.errors);\n }\n }\n }\n\n /**\n * Get registry\n */\n getRegistry(): Registry {\n return this.registry;\n }\n}\n\n/**\n * Create verification engine\n */\nexport function createVerificationEngine(registry?: Registry): VerificationEngine {\n return new VerificationEngine(registry);\n}\n","/**\n * 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// Constraint check (structured verifier specification)\nexport const ConstraintCheckSchema = z.object({\n verifier: z.string().min(1),\n params: z.record(z.unknown()).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 check: ConstraintCheckSchema.optional(),\n autofix: z.boolean().optional(),\n exceptions: z.array(ConstraintExceptionSchema).optional(),\n});\n\n// Verification config\nexport const VerificationConfigSchema = z.object({\n check: z.string().min(1),\n target: z.string().min(1),\n frequency: VerificationFrequencySchema,\n timeout: z.number().positive().optional(),\n});\n\n// Links\nexport const LinksSchema = z.object({\n related: z.array(z.string()).optional(),\n supersedes: z.array(z.string()).optional(),\n references: z.array(z.string().url()).optional(),\n});\n\n// Complete decision document\nexport const DecisionSchema = z.object({\n kind: z.literal('Decision'),\n metadata: DecisionMetadataSchema,\n decision: DecisionContentSchema,\n constraints: z.array(ConstraintSchema).min(1),\n verification: z.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 ConstraintCheckSchema_ = z.infer<typeof ConstraintCheckSchema>;\nexport type ConstraintSchema_ = z.infer<typeof ConstraintSchema>;\nexport type VerificationConfigSchema_ = z.infer<typeof VerificationConfigSchema>;\nexport type DecisionTypeSchema = z.infer<typeof DecisionSchema>;\n\n/**\n * Validate a decision document\n */\nexport function validateDecision(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 * Plugin metadata\n */\nexport interface VerifierPluginMetadata {\n /** Unique identifier matching /^[a-z][a-z0-9-]*$/ */\n id: string;\n /** Semver version string */\n version: string;\n /** Plugin author */\n author?: string;\n /** Brief description of what this verifier checks */\n description?: string;\n}\n\n/**\n * Verifier plugin interface\n * Custom verifiers must export a default object implementing this interface\n */\nexport interface VerifierPlugin {\n /** Plugin metadata */\n metadata: VerifierPluginMetadata;\n\n /** Factory function that creates a new verifier instance */\n createVerifier: () => Verifier;\n\n /** Optional Zod schema for validating constraint.check.params */\n paramsSchema?: unknown; // Will be validated as ZodSchema at runtime\n}\n\n/**\n * Helper to define a verifier plugin with type safety\n *\n * @example\n * ```typescript\n * import { defineVerifierPlugin, type Verifier } from '@ipation/specbridge';\n *\n * class MyVerifier implements Verifier {\n * readonly id = 'my-custom';\n * readonly name = 'My Custom Verifier';\n * readonly description = 'Checks custom patterns';\n *\n * async verify(ctx) {\n * // Implementation\n * return [];\n * }\n * }\n *\n * export default defineVerifierPlugin({\n * metadata: {\n * id: 'my-custom',\n * version: '1.0.0',\n * author: 'Your Name'\n * },\n * createVerifier: () => new MyVerifier()\n * });\n * ```\n */\nexport function defineVerifierPlugin(plugin: VerifierPlugin): VerifierPlugin {\n return plugin;\n}\n\n/**\n * Helper to create a violation\n */\nexport function createViolation(params: {\n decisionId: string;\n constraintId: string;\n type: Constraint['type'];\n severity: Severity;\n message: string;\n file: string;\n line?: number;\n column?: number;\n endLine?: number;\n endColumn?: number;\n suggestion?: string;\n autofix?: Violation['autofix'];\n}): Violation {\n return params;\n}\n","/**\n * Naming convention verifier\n */\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst NAMING_PATTERNS: Record<string, { regex: RegExp; description: string }> = {\n PascalCase: {\n regex: /^[A-Z][a-zA-Z0-9]*$/,\n description: 'PascalCase (e.g., MyClass)',\n },\n camelCase: {\n regex: /^[a-z][a-zA-Z0-9]*$/,\n description: 'camelCase (e.g., myFunction)',\n },\n UPPER_SNAKE_CASE: {\n regex: /^[A-Z][A-Z0-9_]*$/,\n description: 'UPPER_SNAKE_CASE (e.g., MAX_VALUE)',\n },\n snake_case: {\n regex: /^[a-z][a-z0-9_]*$/,\n description: 'snake_case (e.g., my_variable)',\n },\n 'kebab-case': {\n regex: /^[a-z][a-z0-9-]*$/,\n description: 'kebab-case (e.g., my-component)',\n },\n};\n\nexport class NamingVerifier implements Verifier {\n readonly id = 'naming';\n readonly name = 'Naming Convention Verifier';\n readonly description = 'Verifies naming conventions for classes, functions, and variables';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n\n // Parse constraint rule to extract target and convention\n // Expected format: \"Classes should use PascalCase\" or \"Functions should use camelCase\"\n const rule = constraint.rule.toLowerCase();\n let convention: string | null = null;\n let targetType: 'class' | 'function' | 'interface' | 'type' | null = null;\n\n // Detect convention\n for (const [name] of Object.entries(NAMING_PATTERNS)) {\n if (rule.includes(name.toLowerCase())) {\n convention = name;\n break;\n }\n }\n\n // Detect target type\n if (rule.includes('class')) targetType = 'class';\n else if (rule.includes('function')) targetType = 'function';\n else if (rule.includes('interface')) targetType = 'interface';\n else if (rule.includes('type')) targetType = 'type';\n\n if (!convention || !targetType) {\n // Can't parse rule, skip verification\n return violations;\n }\n\n const pattern = NAMING_PATTERNS[convention];\n if (!pattern) return violations;\n\n // Check based on target type\n if (targetType === 'class') {\n for (const classDecl of sourceFile.getClasses()) {\n const name = classDecl.getName();\n if (name && !pattern.regex.test(name)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Class \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: classDecl.getStartLineNumber(),\n column: classDecl.getStart() - classDecl.getStartLinePos(),\n suggestion: `Rename to follow ${pattern.description}`,\n }));\n }\n }\n }\n\n if (targetType === 'function') {\n for (const funcDecl of sourceFile.getFunctions()) {\n const name = funcDecl.getName();\n if (name && !pattern.regex.test(name)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: funcDecl.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n }));\n }\n }\n }\n\n if (targetType === 'interface') {\n for (const interfaceDecl of sourceFile.getInterfaces()) {\n const name = interfaceDecl.getName();\n if (!pattern.regex.test(name)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Interface \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: interfaceDecl.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n }));\n }\n }\n }\n\n if (targetType === 'type') {\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const name = typeAlias.getName();\n if (!pattern.regex.test(name)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Type \"${name}\" does not follow ${pattern.description} naming convention`,\n file: filePath,\n line: typeAlias.getStartLineNumber(),\n suggestion: `Rename to follow ${pattern.description}`,\n }));\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Import pattern verifier\n */\nimport path from 'node:path';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nexport class ImportsVerifier implements Verifier {\n readonly id = 'imports';\n readonly name = 'Import Pattern Verifier';\n readonly description = 'Verifies import patterns like barrel imports, path aliases, etc.';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n // Check for required .js extensions in relative imports (ESM-friendly)\n if ((rule.includes('.js') && rule.includes('extension')) || rule.includes('esm') || rule.includes('add .js')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (!moduleSpec.startsWith('.')) continue;\n\n const ext = path.posix.extname(moduleSpec);\n let suggested: string | null = null;\n\n if (!ext) {\n suggested = `${moduleSpec}.js`;\n } else if (ext === '.ts' || ext === '.tsx' || ext === '.jsx') {\n suggested = moduleSpec.slice(0, -ext.length) + '.js';\n } else if (ext !== '.js') {\n continue;\n }\n\n if (!suggested || suggested === moduleSpec) continue;\n\n const ms = importDecl.getModuleSpecifier();\n const start = ms.getStart() + 1; // inside quotes\n const end = ms.getEnd() - 1;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Relative import \"${moduleSpec}\" should include a .js extension`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Update to \"${suggested}\"`,\n autofix: {\n description: 'Add/normalize .js extension in import specifier',\n edits: [{ start, end, text: suggested }],\n },\n }));\n }\n }\n\n // Check for barrel import requirement\n if (rule.includes('barrel') || rule.includes('index')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n\n // Skip external packages\n if (!moduleSpec.startsWith('.')) continue;\n\n // Check if importing specific file instead of barrel\n if (moduleSpec.match(/\\.(ts|js|tsx|jsx)$/) || moduleSpec.match(/\\/[^/]+$/)) {\n // Could be a direct file import - flag if not index\n if (!moduleSpec.endsWith('/index') && !moduleSpec.endsWith('index')) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Import from \"${moduleSpec}\" should use barrel (index) import`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Import from the parent directory index file instead',\n }));\n }\n }\n }\n }\n\n // Check for path alias requirement\n if (rule.includes('alias') || rule.includes('@/') || rule.includes('path alias')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n\n // Check for deeply nested relative imports\n if (moduleSpec.match(/^\\.\\.\\/\\.\\.\\/\\.\\.\\//)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Deep relative import \"${moduleSpec}\" should use path alias`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use path alias (e.g., @/module) for deep imports',\n }));\n }\n }\n }\n\n // Check for no circular imports (basic check)\n if (rule.includes('circular') || rule.includes('cycle')) {\n // This is a simplified check - a full cycle detection would need graph analysis\n // Check if any import matches the current file's exports\n // This is a very basic heuristic\n const currentFilename = filePath.replace(/\\.[jt]sx?$/, '');\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (moduleSpec.includes(currentFilename.split('/').pop() || '')) {\n // Potential self-reference, might indicate circular dependency\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible circular import detected: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Review import structure for circular dependencies',\n }));\n }\n }\n }\n\n // Check for no wildcard imports\n if (rule.includes('wildcard') || rule.includes('* as') || rule.includes('no namespace')) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const namespaceImport = importDecl.getNamespaceImport();\n if (namespaceImport) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Namespace import \"* as ${namespaceImport.getText()}\" should use named imports`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use specific named imports instead of namespace import',\n }));\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Error handling verifier\n */\nimport { Node } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nexport class ErrorsVerifier implements Verifier {\n readonly id = 'errors';\n readonly name = 'Error Handling Verifier';\n readonly description = 'Verifies error handling patterns';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n // Check for custom error class extension\n if (rule.includes('extend') || rule.includes('base') || rule.includes('hierarchy')) {\n // Extract base class name from rule if mentioned\n const baseClassMatch = rule.match(/extend\\s+(\\w+)/i) || rule.match(/(\\w+Error)\\s+class/i);\n const requiredBase = baseClassMatch ? baseClassMatch[1] : null;\n\n for (const classDecl of sourceFile.getClasses()) {\n const className = classDecl.getName();\n if (!className?.endsWith('Error') && !className?.endsWith('Exception')) continue;\n\n const extendsClause = classDecl.getExtends();\n if (!extendsClause) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Error class \"${className}\" does not extend any base class`,\n file: filePath,\n line: classDecl.getStartLineNumber(),\n suggestion: requiredBase\n ? `Extend ${requiredBase}`\n : 'Extend a base error class for consistent error handling',\n }));\n } else if (requiredBase) {\n const baseName = extendsClause.getText();\n if (baseName !== requiredBase && baseName !== 'Error') {\n // Allow extending Error or the required base\n }\n }\n }\n }\n\n // Check for throwing custom errors vs generic Error\n if (rule.includes('custom error') || rule.includes('throw custom')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isThrowStatement(node)) {\n const expression = node.getExpression();\n if (expression) {\n const text = expression.getText();\n if (text.startsWith('new Error(')) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Throwing generic Error instead of custom error class',\n file: filePath,\n line: node.getStartLineNumber(),\n suggestion: 'Use a custom error class for better error handling',\n }));\n }\n }\n }\n });\n }\n\n // Check for empty catch blocks\n if (rule.includes('empty catch') || rule.includes('swallow') || rule.includes('handle')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isTryStatement(node)) {\n const catchClause = node.getCatchClause();\n if (catchClause) {\n const block = catchClause.getBlock();\n const statements = block.getStatements();\n\n // Check if catch block is empty or only has comments\n if (statements.length === 0) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Empty catch block swallows error without handling',\n file: filePath,\n line: catchClause.getStartLineNumber(),\n suggestion: 'Add error handling, logging, or rethrow the error',\n }));\n }\n }\n }\n });\n }\n\n // Check for console.error vs proper logging\n if (rule.includes('logging') || rule.includes('logger') || rule.includes('no console')) {\n sourceFile.forEachDescendant((node) => {\n if (Node.isCallExpression(node)) {\n const expression = node.getExpression();\n const text = expression.getText();\n if (text === 'console.error' || text === 'console.log') {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Using ${text} instead of proper logging`,\n file: filePath,\n line: node.getStartLineNumber(),\n suggestion: 'Use a proper logging library',\n }));\n }\n }\n });\n }\n\n return violations;\n }\n}\n","/**\n * Regex-based verifier for simple pattern matching\n */\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\n/**\n * A generic verifier that uses regex patterns from constraint rules\n * This handles constraints that specify patterns to match or avoid\n */\nexport class RegexVerifier implements Verifier {\n readonly id = 'regex';\n readonly name = 'Regex Pattern Verifier';\n readonly description = 'Verifies code against regex patterns specified in constraints';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n\n // Try to extract regex pattern from rule\n // Patterns like: \"must not contain /pattern/\" or \"should match /pattern/\"\n const mustNotMatch = rule.match(/must\\s+not\\s+(?:contain|match|use)\\s+\\/(.+?)\\//i);\n const shouldMatch = rule.match(/(?:should|must)\\s+(?:contain|match|use)\\s+\\/(.+?)\\//i);\n const forbiddenPattern = rule.match(/forbidden:\\s*\\/(.+?)\\//i);\n const requiredPattern = rule.match(/required:\\s*\\/(.+?)\\//i);\n\n const fileText = sourceFile.getFullText();\n\n // Handle \"must not contain\" patterns\n const patternToForbid = mustNotMatch?.[1] || forbiddenPattern?.[1];\n if (patternToForbid) {\n try {\n const regex = new RegExp(patternToForbid, 'g');\n let match: RegExpExecArray | null;\n\n while ((match = regex.exec(fileText)) !== null) {\n const beforeMatch = fileText.substring(0, match.index);\n const lineNumber = beforeMatch.split('\\n').length;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Found forbidden pattern: \"${match[0]}\"`,\n file: filePath,\n line: lineNumber,\n suggestion: `Remove or replace the pattern matching /${patternToForbid}/`,\n }));\n }\n } catch {\n // Invalid regex, skip\n }\n }\n\n // Handle \"should contain\" patterns (file-level check)\n const patternToRequire = shouldMatch?.[1] || requiredPattern?.[1];\n if (patternToRequire && !mustNotMatch) {\n try {\n const regex = new RegExp(patternToRequire);\n if (!regex.test(fileText)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `File does not contain required pattern: /${patternToRequire}/`,\n file: filePath,\n suggestion: `Add code matching /${patternToRequire}/`,\n }));\n }\n } catch {\n // Invalid regex, skip\n }\n }\n\n return violations;\n }\n}\n","/**\n * Dependency constraint verifier\n *\n * Supports rules like:\n * - \"No circular dependencies between modules\"\n * - \"Domain layer cannot depend on infrastructure layer\"\n * - \"No dependencies on package lodash\"\n * - \"Maximum import depth: 2\"\n */\nimport path from 'node:path';\nimport type { Project } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\ntype DependencyGraph = Map<string, Set<string>>;\n\nconst graphCache = new WeakMap<Project, { fileCount: number; graph: DependencyGraph }>();\n\nfunction normalizeFsPath(p: string): string {\n return p.replaceAll('\\\\', '/');\n}\n\nfunction joinLike(fromFilePath: string, relative: string): string {\n const fromNorm = normalizeFsPath(fromFilePath);\n const relNorm = normalizeFsPath(relative);\n\n if (path.isAbsolute(fromNorm)) {\n return normalizeFsPath(path.resolve(path.dirname(fromNorm), relNorm));\n }\n\n // In-memory ts-morph projects often use relative paths; keep them relative.\n const dir = path.posix.dirname(fromNorm);\n return path.posix.normalize(path.posix.join(dir, relNorm));\n}\n\nfunction resolveToSourceFilePath(project: Project, fromFilePath: string, moduleSpec: string): string | null {\n if (!moduleSpec.startsWith('.')) return null;\n\n const candidates: string[] = [];\n const raw = joinLike(fromFilePath, moduleSpec);\n\n const addCandidate = (p: string) => candidates.push(normalizeFsPath(p));\n\n // If an extension exists, try it and common TS/JS mappings.\n const ext = path.posix.extname(raw);\n if (ext) {\n addCandidate(raw);\n\n if (ext === '.js') addCandidate(raw.slice(0, -3) + '.ts');\n if (ext === '.jsx') addCandidate(raw.slice(0, -4) + '.tsx');\n if (ext === '.ts') addCandidate(raw.slice(0, -3) + '.js');\n if (ext === '.tsx') addCandidate(raw.slice(0, -4) + '.jsx');\n\n // Directory index variants.\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.ts'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.tsx'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.js'));\n addCandidate(path.posix.join(raw.replace(/\\/$/, ''), 'index.jsx'));\n } else {\n // No extension: try source extensions and index files.\n addCandidate(raw + '.ts');\n addCandidate(raw + '.tsx');\n addCandidate(raw + '.js');\n addCandidate(raw + '.jsx');\n\n addCandidate(path.posix.join(raw, 'index.ts'));\n addCandidate(path.posix.join(raw, 'index.tsx'));\n addCandidate(path.posix.join(raw, 'index.js'));\n addCandidate(path.posix.join(raw, 'index.jsx'));\n }\n\n for (const candidate of candidates) {\n const sf = project.getSourceFile(candidate);\n if (sf) return sf.getFilePath();\n }\n\n return null;\n}\n\nfunction buildDependencyGraph(project: Project): DependencyGraph {\n const cached = graphCache.get(project);\n const sourceFiles = project.getSourceFiles();\n if (cached && cached.fileCount === sourceFiles.length) {\n return cached.graph;\n }\n\n const graph: DependencyGraph = new Map();\n\n for (const sf of sourceFiles) {\n const from = normalizeFsPath(sf.getFilePath());\n if (!graph.has(from)) graph.set(from, new Set());\n\n for (const importDecl of sf.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n const resolved = resolveToSourceFilePath(project, from, moduleSpec);\n if (resolved) {\n graph.get(from)!.add(normalizeFsPath(resolved));\n }\n }\n }\n\n graphCache.set(project, { fileCount: sourceFiles.length, graph });\n return graph;\n}\n\nfunction tarjanScc(graph: DependencyGraph): string[][] {\n let index = 0;\n const stack: string[] = [];\n const onStack = new Set<string>();\n const indices = new Map<string, number>();\n const lowlink = new Map<string, number>();\n const result: string[][] = [];\n\n const strongConnect = (v: string) => {\n indices.set(v, index);\n lowlink.set(v, index);\n index++;\n stack.push(v);\n onStack.add(v);\n\n const edges = graph.get(v) || new Set<string>();\n for (const w of edges) {\n if (!indices.has(w)) {\n strongConnect(w);\n lowlink.set(v, Math.min(lowlink.get(v)!, lowlink.get(w)!));\n } else if (onStack.has(w)) {\n lowlink.set(v, Math.min(lowlink.get(v)!, indices.get(w)!));\n }\n }\n\n if (lowlink.get(v) === indices.get(v)) {\n const scc: string[] = [];\n while (stack.length > 0) {\n const w = stack.pop();\n if (!w) break;\n onStack.delete(w);\n scc.push(w);\n if (w === v) break;\n }\n result.push(scc);\n }\n };\n\n for (const v of graph.keys()) {\n if (!indices.has(v)) strongConnect(v);\n }\n\n return result;\n}\n\nfunction parseMaxImportDepth(rule: string): number | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/maximum\\s{1,5}import\\s{1,5}depth\\s{0,5}[:=]?\\s{0,5}(\\d+)/i);\n return m ? Number.parseInt(m[1]!, 10) : null;\n}\n\nfunction parseBannedDependency(rule: string): string | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/no\\s{1,5}dependencies?\\s{1,5}on\\s{1,5}(?:package\\s{1,5})?(.+?)(?:\\.|$)/i);\n if (!m) return null;\n const value = m[1]!.trim();\n return value.length > 0 ? value : null;\n}\n\nfunction parseLayerRule(rule: string): { fromLayer: string; toLayer: string } | null {\n // Use bounded quantifiers to prevent ReDoS\n const m = rule.match(/(\\w+)\\s{1,5}layer\\s{1,5}cannot\\s{1,5}depend\\s{1,5}on\\s{1,5}(\\w+)\\s{1,5}layer/i);\n if (!m) return null;\n return { fromLayer: m[1]!.toLowerCase(), toLayer: m[2]!.toLowerCase() };\n}\n\nfunction fileInLayer(filePath: string, layer: string): boolean {\n const fp = normalizeFsPath(filePath).toLowerCase();\n return fp.includes(`/${layer}/`) || fp.endsWith(`/${layer}.ts`) || fp.endsWith(`/${layer}.tsx`);\n}\n\nexport class DependencyVerifier implements Verifier {\n readonly id = 'dependencies';\n readonly name = 'Dependency Verifier';\n readonly description = 'Checks dependency constraints, import depth, and circular dependencies';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n const lowerRule = rule.toLowerCase();\n const project = sourceFile.getProject();\n const projectFilePath = normalizeFsPath(sourceFile.getFilePath());\n\n // 1) Circular dependencies (across files)\n if (lowerRule.includes('circular') || lowerRule.includes('cycle')) {\n const graph = buildDependencyGraph(project);\n const sccs = tarjanScc(graph);\n const current = projectFilePath;\n\n for (const scc of sccs) {\n const hasSelfLoop = scc.length === 1 && (graph.get(scc[0]!)?.has(scc[0]!) ?? false);\n const isCycle = scc.length > 1 || hasSelfLoop;\n if (!isCycle) continue;\n\n if (!scc.includes(current)) continue;\n\n // Avoid duplicate reporting: only report from lexicographically-smallest file in the SCC.\n const sorted = [...scc].sort();\n if (sorted[0] !== current) continue;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Circular dependency detected across: ${sorted.join(' -> ')}`,\n file: filePath,\n line: 1,\n suggestion: 'Break the cycle by extracting shared abstractions or reversing the dependency',\n }));\n }\n }\n\n // 2) Layer constraints (heuristic by folder name)\n const layerRule = parseLayerRule(rule);\n if (layerRule && fileInLayer(projectFilePath, layerRule.fromLayer)) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n const resolved = resolveToSourceFilePath(project, projectFilePath, moduleSpec);\n if (!resolved) continue;\n\n if (fileInLayer(resolved, layerRule.toLayer)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Layer violation: ${layerRule.fromLayer} depends on ${layerRule.toLayer} via import \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Refactor to remove dependency from ${layerRule.fromLayer} to ${layerRule.toLayer}`,\n }));\n }\n }\n }\n\n // 3) Banned dependency (package or internal)\n const banned = parseBannedDependency(rule);\n if (banned) {\n const bannedLower = banned.toLowerCase();\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (moduleSpec.toLowerCase().includes(bannedLower)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Banned dependency import detected: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: `Remove or replace dependency \"${banned}\"`,\n }));\n }\n }\n }\n\n // 4) Import depth limits (../ count)\n const maxDepth = parseMaxImportDepth(rule);\n if (maxDepth !== null) {\n for (const importDecl of sourceFile.getImportDeclarations()) {\n const moduleSpec = importDecl.getModuleSpecifierValue();\n if (!moduleSpec.startsWith('.')) continue;\n const depth = (moduleSpec.match(/\\.\\.\\//g) || []).length;\n if (depth > maxDepth) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Import depth ${depth} exceeds maximum ${maxDepth}: \"${moduleSpec}\"`,\n file: filePath,\n line: importDecl.getStartLineNumber(),\n suggestion: 'Use a shallower module boundary (or introduce a public entrypoint for this dependency)',\n }));\n }\n }\n }\n\n return violations;\n }\n}\n","/**\n * Complexity constraint verifier\n *\n * Supports rules like:\n * - \"Cyclomatic complexity must not exceed 10\"\n * - \"File size must not exceed 300 lines\"\n * - \"Functions must have at most 4 parameters\"\n * - \"Nesting depth must not exceed 4\"\n */\nimport type { Node } from 'ts-morph';\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nfunction parseLimit(rule: string, pattern: RegExp): number | null {\n const m = rule.match(pattern);\n return m ? Number.parseInt(m[1]!, 10) : null;\n}\n\nfunction getFileLineCount(text: string): number {\n if (text.length === 0) return 0;\n return text.split('\\n').length;\n}\n\nfunction getDecisionPoints(fn: Node): number {\n let points = 0;\n for (const d of fn.getDescendants()) {\n switch (d.getKind()) {\n case SyntaxKind.IfStatement:\n case SyntaxKind.ForStatement:\n case SyntaxKind.ForInStatement:\n case SyntaxKind.ForOfStatement:\n case SyntaxKind.WhileStatement:\n case SyntaxKind.DoStatement:\n case SyntaxKind.CatchClause:\n case SyntaxKind.ConditionalExpression:\n case SyntaxKind.CaseClause:\n points++;\n break;\n case SyntaxKind.BinaryExpression: {\n // Count short-circuit operators (&&, ||)\n const text = d.getText();\n if (text.includes('&&') || text.includes('||')) points++;\n break;\n }\n default:\n break;\n }\n }\n return points;\n}\n\nfunction calculateCyclomaticComplexity(fn: Node): number {\n // Base complexity of 1 + number of decision points.\n return 1 + getDecisionPoints(fn);\n}\n\nfunction getFunctionDisplayName(fn: Node): string {\n // Best-effort name resolution.\n if ('getName' in (fn as any) && typeof (fn as any).getName === 'function') {\n const name = (fn as any).getName();\n if (typeof name === 'string' && name.length > 0) return name;\n }\n\n // Variable = () => ...\n const parent = fn.getParent();\n if (parent?.getKind() === SyntaxKind.VariableDeclaration) {\n const vd: any = parent;\n if (typeof vd.getName === 'function') return vd.getName();\n }\n\n return '<anonymous>';\n}\n\nfunction maxNestingDepth(node: Node): number {\n let maxDepth = 0;\n\n const walk = (n: Node, depth: number) => {\n maxDepth = Math.max(maxDepth, depth);\n\n const kind = n.getKind();\n const isNestingNode =\n kind === SyntaxKind.IfStatement ||\n kind === SyntaxKind.ForStatement ||\n kind === SyntaxKind.ForInStatement ||\n kind === SyntaxKind.ForOfStatement ||\n kind === SyntaxKind.WhileStatement ||\n kind === SyntaxKind.DoStatement ||\n kind === SyntaxKind.SwitchStatement ||\n kind === SyntaxKind.TryStatement;\n\n for (const child of n.getChildren()) {\n // Skip nested function scopes for nesting depth.\n if (\n child.getKind() === SyntaxKind.FunctionDeclaration ||\n child.getKind() === SyntaxKind.FunctionExpression ||\n child.getKind() === SyntaxKind.ArrowFunction ||\n child.getKind() === SyntaxKind.MethodDeclaration\n ) {\n continue;\n }\n walk(child, isNestingNode ? depth + 1 : depth);\n }\n };\n\n walk(node, 0);\n return maxDepth;\n}\n\nexport class ComplexityVerifier implements Verifier {\n readonly id = 'complexity';\n readonly name = 'Complexity Verifier';\n readonly description = 'Checks cyclomatic complexity, file size, parameters, and nesting depth';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule;\n\n const maxComplexity = parseLimit(rule, /complexity\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n const maxLines = parseLimit(rule, /file\\s+size\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)\\s+lines?/i);\n const maxParams = parseLimit(rule, /at\\s+most\\s+(\\d+)\\s+parameters?/i) ?? parseLimit(rule, /parameters?\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n const maxNesting = parseLimit(rule, /nesting\\s+depth\\s+(?:must\\s+)?not\\s+exceed\\s+(\\d+)/i);\n\n if (maxLines !== null) {\n const lineCount = getFileLineCount(sourceFile.getFullText());\n if (lineCount > maxLines) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `File has ${lineCount} lines which exceeds maximum ${maxLines}`,\n file: filePath,\n line: 1,\n suggestion: 'Split the file into smaller modules',\n }));\n }\n }\n\n const functionLikes = [\n ...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionExpression),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.ArrowFunction),\n ...sourceFile.getDescendantsOfKind(SyntaxKind.MethodDeclaration),\n ];\n\n for (const fn of functionLikes) {\n const fnName = getFunctionDisplayName(fn);\n\n if (maxComplexity !== null) {\n const complexity = calculateCyclomaticComplexity(fn);\n if (complexity > maxComplexity) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has cyclomatic complexity ${complexity} which exceeds maximum ${maxComplexity}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Refactor to reduce branching or extract smaller functions',\n }));\n }\n }\n\n if (maxParams !== null && 'getParameters' in (fn as any)) {\n const params = (fn as any).getParameters();\n const paramCount = Array.isArray(params) ? params.length : 0;\n if (paramCount > maxParams) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has ${paramCount} parameters which exceeds maximum ${maxParams}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Consider grouping parameters into an options object',\n }));\n }\n }\n\n if (maxNesting !== null) {\n const depth = maxNestingDepth(fn);\n if (depth > maxNesting) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Function ${fnName} has nesting depth ${depth} which exceeds maximum ${maxNesting}`,\n file: filePath,\n line: fn.getStartLineNumber(),\n suggestion: 'Reduce nesting by using early returns or extracting functions',\n }));\n }\n }\n }\n\n return violations;\n }\n}\n\n","/**\n * Security verifier (heuristic/static checks)\n *\n * Supports rules like:\n * - \"No hardcoded secrets\"\n * - \"Avoid eval / Function constructor\"\n * - \"Prevent SQL injection\"\n * - \"Avoid innerHTML / dangerouslySetInnerHTML\"\n */\nimport type { Node } from 'ts-morph';\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst SECRET_NAME_RE = /(api[_-]?key|password|secret|token)/i;\n\nfunction isStringLiteralLike(node: Node): boolean {\n const k = node.getKind();\n return k === SyntaxKind.StringLiteral || k === SyntaxKind.NoSubstitutionTemplateLiteral;\n}\n\nexport class SecurityVerifier implements Verifier {\n readonly id = 'security';\n readonly name = 'Security Verifier';\n readonly description = 'Detects common security footguns (secrets, eval, XSS/SQL injection heuristics)';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n const checkSecrets = rule.includes('secret') || rule.includes('password') || rule.includes('token') || rule.includes('api key') || rule.includes('hardcoded');\n const checkEval = rule.includes('eval') || rule.includes('function constructor');\n const checkXss = rule.includes('xss') || rule.includes('innerhtml') || rule.includes('dangerouslysetinnerhtml');\n const checkSql = rule.includes('sql') || rule.includes('injection');\n const checkProto = rule.includes('prototype pollution') || rule.includes('__proto__');\n\n if (checkSecrets) {\n for (const vd of sourceFile.getVariableDeclarations()) {\n const name = vd.getName();\n if (!SECRET_NAME_RE.test(name)) continue;\n\n const init = vd.getInitializer();\n if (!init || !isStringLiteralLike(init)) continue;\n\n const value = init.getText().slice(1, -1); // best-effort strip quotes\n if (value.length === 0) continue;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible hardcoded secret in variable \"${name}\"`,\n file: filePath,\n line: vd.getStartLineNumber(),\n suggestion: 'Move secrets to environment variables or a secret manager',\n }));\n }\n\n for (const pa of sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {\n const nameNode: any = pa.getNameNode?.();\n const propName = nameNode?.getText?.() ?? '';\n if (!SECRET_NAME_RE.test(propName)) continue;\n\n const init = pa.getInitializer();\n if (!init || !isStringLiteralLike(init)) continue;\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Possible hardcoded secret in object property ${propName}`,\n file: filePath,\n line: pa.getStartLineNumber(),\n suggestion: 'Move secrets to environment variables or a secret manager',\n }));\n }\n }\n\n if (checkEval) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const exprText = call.getExpression().getText();\n if (exprText === 'eval' || exprText === 'Function') {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Unsafe dynamic code execution via ${exprText}()`,\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Avoid eval/Function; use safer alternatives',\n }));\n }\n }\n }\n\n if (checkXss) {\n // innerHTML assignments\n for (const bin of sourceFile.getDescendantsOfKind(SyntaxKind.BinaryExpression)) {\n const left = bin.getLeft();\n if (left.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n const pa: any = left;\n if (pa.getName?.() === 'innerHTML') {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential XSS: assignment to innerHTML',\n file: filePath,\n line: bin.getStartLineNumber(),\n suggestion: 'Prefer textContent or a safe templating/escaping strategy',\n }));\n }\n }\n\n // React dangerouslySetInnerHTML usage\n if (sourceFile.getFullText().includes('dangerouslySetInnerHTML')) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential XSS: usage of dangerouslySetInnerHTML',\n file: filePath,\n line: 1,\n suggestion: 'Avoid dangerouslySetInnerHTML or ensure content is sanitized',\n }));\n }\n }\n\n if (checkSql) {\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n const name = (expr as any).getName?.();\n if (name !== 'query' && name !== 'execute') continue;\n\n const arg = call.getArguments()[0];\n if (!arg) continue;\n\n const isTemplate = arg.getKind() === SyntaxKind.TemplateExpression;\n const isConcat = arg.getKind() === SyntaxKind.BinaryExpression && arg.getText().includes('+');\n if (!isTemplate && !isConcat) continue;\n\n const text = arg.getText().toLowerCase();\n if (!text.includes('select') && !text.includes('insert') && !text.includes('update') && !text.includes('delete')) {\n continue;\n }\n\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential SQL injection: dynamically constructed SQL query',\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Use parameterized queries / prepared statements',\n }));\n }\n }\n\n if (checkProto) {\n const text = sourceFile.getFullText();\n if (text.includes('__proto__') || text.includes('constructor.prototype')) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: 'Potential prototype pollution pattern detected',\n file: filePath,\n line: 1,\n suggestion: 'Avoid writing to __proto__/prototype; validate object keys',\n }));\n }\n }\n\n return violations;\n }\n}\n\n","/**\n * API consistency verifier (heuristic)\n *\n * Supports rules like:\n * - \"REST endpoints must use kebab-case\"\n */\nimport { SyntaxKind } from 'ts-morph';\nimport type { Violation } from '../../core/types/index.js';\nimport { type Verifier, type VerificationContext, createViolation } from './base.js';\n\nconst HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'all']);\n\nfunction isKebabPath(pathValue: string): boolean {\n const parts = pathValue.split('/').filter(Boolean);\n for (const part of parts) {\n if (part.startsWith(':')) continue; // path params\n if (!/^[a-z0-9-]+$/.test(part)) return false;\n }\n return true;\n}\n\nexport class ApiVerifier implements Verifier {\n readonly id = 'api';\n readonly name = 'API Consistency Verifier';\n readonly description = 'Checks basic REST endpoint naming conventions in common frameworks';\n\n async verify(ctx: VerificationContext): Promise<Violation[]> {\n const violations: Violation[] = [];\n const { sourceFile, constraint, decisionId, filePath } = ctx;\n const rule = constraint.rule.toLowerCase();\n\n const enforceKebab = rule.includes('kebab') || rule.includes('kebab-case');\n if (!enforceKebab) return violations;\n\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const method = (expr as any).getName?.();\n if (!method || !HTTP_METHODS.has(String(method))) continue;\n\n const firstArg = call.getArguments()[0];\n if (!firstArg || firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const pathValue = (firstArg as any).getLiteralValue?.() ?? firstArg.getText().slice(1, -1);\n if (typeof pathValue !== 'string') continue;\n\n if (!isKebabPath(pathValue)) {\n violations.push(createViolation({\n decisionId,\n constraintId: constraint.id,\n type: constraint.type,\n severity: constraint.severity,\n message: `Endpoint path \"${pathValue}\" is not kebab-case`,\n file: filePath,\n line: call.getStartLineNumber(),\n suggestion: 'Use lowercase and hyphens in static path segments (e.g., /user-settings)',\n }));\n }\n }\n\n return violations;\n }\n}\n\n","/**\n * Plugin loader for custom verifiers\n *\n * Dynamically loads verifier plugins from .specbridge/verifiers/\n */\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { pathToFileURL } from 'url';\nimport { glob } from 'glob';\nimport type { Verifier, VerifierPlugin } from '../verifiers/base.js';\n\n/**\n * Manages loading and registry of custom verifier plugins\n */\nexport class PluginLoader {\n private plugins = new Map<string, () => Verifier>();\n private loaded = false;\n private loadErrors: Array<{ file: string; error: string }> = [];\n\n /**\n * Load all plugins from the specified base path\n *\n * @param basePath - Project root directory (usually cwd)\n */\n async loadPlugins(basePath: string): Promise<void> {\n const verifiersDir = join(basePath, '.specbridge', 'verifiers');\n\n // Check if directory exists\n if (!existsSync(verifiersDir)) {\n this.loaded = true;\n return;\n }\n\n // Find all .ts and .js files (excluding tests and .d.ts)\n const files = await glob('**/*.{ts,js}', {\n cwd: verifiersDir,\n absolute: true,\n ignore: ['**/*.test.{ts,js}', '**/*.d.ts'],\n });\n\n // Load each plugin\n for (const file of files) {\n try {\n await this.loadPlugin(file);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.loadErrors.push({ file, error: message });\n console.warn(`Failed to load plugin from ${file}: ${message}`);\n }\n }\n\n this.loaded = true;\n\n // Log summary\n if (this.plugins.size > 0) {\n console.log(`Loaded ${this.plugins.size} custom verifier(s)`);\n }\n if (this.loadErrors.length > 0) {\n console.warn(`Failed to load ${this.loadErrors.length} plugin(s)`);\n }\n }\n\n /**\n * Load a single plugin file\n */\n private async loadPlugin(filePath: string): Promise<void> {\n // Convert to file URL for ESM import\n const fileUrl = pathToFileURL(filePath).href;\n\n // Dynamic import\n const module = await import(fileUrl);\n\n // Extract plugin (default export or named 'plugin' export)\n const plugin: VerifierPlugin = module.default || module.plugin;\n\n if (!plugin) {\n throw new Error('Plugin must export a default or named \"plugin\" export');\n }\n\n // Validate plugin structure\n this.validatePlugin(plugin, filePath);\n\n // Check for ID conflicts\n if (this.plugins.has(plugin.metadata.id)) {\n throw new Error(\n `Plugin ID \"${plugin.metadata.id}\" is already registered. ` +\n `Each plugin must have a unique ID.`\n );\n }\n\n // Register plugin factory\n this.plugins.set(plugin.metadata.id, plugin.createVerifier);\n }\n\n /**\n * Validate plugin structure and metadata\n */\n private validatePlugin(plugin: VerifierPlugin, _filePath: string): void {\n // Check required fields\n if (!plugin.metadata) {\n throw new Error('Plugin must have a \"metadata\" property');\n }\n\n if (!plugin.metadata.id || typeof plugin.metadata.id !== 'string') {\n throw new Error('Plugin metadata must have a string \"id\" property');\n }\n\n if (!plugin.metadata.version || typeof plugin.metadata.version !== 'string') {\n throw new Error('Plugin metadata must have a string \"version\" property');\n }\n\n // Validate ID format: lowercase alphanumeric with hyphens, must start with letter\n const idPattern = /^[a-z][a-z0-9-]*$/;\n if (!idPattern.test(plugin.metadata.id)) {\n throw new Error(\n `Plugin ID \"${plugin.metadata.id}\" is invalid. ` +\n `ID must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens.`\n );\n }\n\n // Check createVerifier is a function\n if (typeof plugin.createVerifier !== 'function') {\n throw new Error('Plugin must have a \"createVerifier\" function');\n }\n\n // Test that createVerifier returns a valid Verifier\n let verifier: Verifier;\n try {\n verifier = plugin.createVerifier();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`createVerifier() threw an error: ${message}`);\n }\n\n // Validate verifier interface\n if (!verifier || typeof verifier !== 'object') {\n throw new Error('createVerifier() must return an object');\n }\n\n if (!verifier.id || typeof verifier.id !== 'string') {\n throw new Error('Verifier must have a string \"id\" property');\n }\n\n if (!verifier.name || typeof verifier.name !== 'string') {\n throw new Error('Verifier must have a string \"name\" property');\n }\n\n if (!verifier.description || typeof verifier.description !== 'string') {\n throw new Error('Verifier must have a string \"description\" property');\n }\n\n if (typeof verifier.verify !== 'function') {\n throw new Error('Verifier must have a \"verify\" method');\n }\n\n // Verify that verifier.id matches plugin.metadata.id\n if (verifier.id !== plugin.metadata.id) {\n throw new Error(\n `Verifier ID \"${verifier.id}\" does not match plugin metadata ID \"${plugin.metadata.id}\". ` +\n `These must be identical.`\n );\n }\n }\n\n /**\n * Get a verifier instance by ID\n *\n * @param id - Verifier ID\n * @returns Verifier instance or null if not found\n */\n getVerifier(id: string): Verifier | null {\n const factory = this.plugins.get(id);\n return factory ? factory() : null;\n }\n\n /**\n * Get all registered plugin IDs\n */\n getPluginIds(): string[] {\n return Array.from(this.plugins.keys());\n }\n\n /**\n * Check if plugins have been loaded\n */\n isLoaded(): boolean {\n return this.loaded;\n }\n\n /**\n * Get load errors (for diagnostics)\n */\n getLoadErrors(): Array<{ file: string; error: string }> {\n return [...this.loadErrors];\n }\n\n /**\n * Reset the loader (useful for testing)\n */\n reset(): void {\n this.plugins.clear();\n this.loaded = false;\n this.loadErrors = [];\n }\n}\n\n/**\n * Singleton plugin loader instance\n */\nlet pluginLoader: PluginLoader | null = null;\n\n/**\n * Get the global plugin loader instance\n */\nexport function getPluginLoader(): PluginLoader {\n if (!pluginLoader) {\n pluginLoader = new PluginLoader();\n }\n return pluginLoader;\n}\n\n/**\n * Reset the global plugin loader (for testing)\n */\nexport function resetPluginLoader(): void {\n if (pluginLoader) {\n pluginLoader.reset();\n }\n pluginLoader = null;\n}\n","import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass<Path, Path>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesUnset,\n): Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass<Path, Path> | Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass<Path, Path>\nexport function globStream(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass<Path, Path> | Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise<string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Promise<Path[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Promise<string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions,\n): Promise<Path[] | string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Generator<Path, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions,\n): Generator<Path, void, void> | Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator<Path, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions,\n): AsyncGenerator<Path, void, void> | AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n stream: globStreamSync,\n iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n glob: glob_,\n globSync,\n sync,\n globStream,\n stream,\n globStreamSync,\n streamSync,\n globIterate,\n iterate,\n globIterateSync,\n iterateSync,\n Glob,\n hasMagic,\n escape,\n unescape,\n})\nglob.glob = glob\n","import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude<Minimatch['globParts'], undefined>\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n /**\n * Set to `true` to always receive absolute paths for\n * matched files. Set to `false` to always return relative paths.\n *\n * When this option is not set, absolute paths are returned for patterns\n * that are absolute, and otherwise paths are returned that are relative\n * to the `cwd` setting.\n *\n * This does _not_ make an extra system call to get\n * the realpath, it only does string path resolution.\n *\n * Conflicts with {@link withFileTypes}\n */\n absolute?: boolean\n\n /**\n * Set to false to enable {@link windowsPathsNoEscape}\n *\n * @deprecated\n */\n allowWindowsEscape?: boolean\n\n /**\n * The current working directory in which to search. Defaults to\n * `process.cwd()`.\n *\n * May be eiher a string path or a `file://` URL object or string.\n */\n cwd?: string | URL\n\n /**\n * Include `.dot` files in normal matches and `globstar`\n * matches. Note that an explicit dot in a portion of the pattern\n * will always match dot files.\n */\n dot?: boolean\n\n /**\n * Prepend all relative path strings with `./` (or `.\\` on Windows).\n *\n * Without this option, returned relative paths are \"bare\", so instead of\n * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n *\n * Relative patterns starting with `'../'` are not prepended with `./`, even\n * if this option is set.\n */\n dotRelative?: boolean\n\n /**\n * Follow symlinked directories when expanding `**`\n * patterns. This can result in a lot of duplicate references in\n * the presence of cyclic links, and make performance quite bad.\n *\n * By default, a `**` in a pattern will follow 1 symbolic link if\n * it is not the first item in the pattern, or none if it is the\n * first item in the pattern, following the same behavior as Bash.\n */\n follow?: boolean\n\n /**\n * string or string[], or an object with `ignore` and `ignoreChildren`\n * methods.\n *\n * If a string or string[] is provided, then this is treated as a glob\n * pattern or array of glob patterns to exclude from matches. To ignore all\n * children within a directory, as well as the entry itself, append `'/**'`\n * to the ignore pattern.\n *\n * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n * any other settings.\n *\n * If an object is provided that has `ignored(path)` and/or\n * `childrenIgnored(path)` methods, then these methods will be called to\n * determine whether any Path is a match or if its children should be\n * traversed, respectively.\n */\n ignore?: string | string[] | IgnoreLike\n\n /**\n * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n * effect if {@link nobrace} is set.\n *\n * Only has effect on the {@link hasMagic} function.\n */\n magicalBraces?: boolean\n\n /**\n * Add a `/` character to directory matches. Note that this requires\n * additional stat calls in some cases.\n */\n mark?: boolean\n\n /**\n * Perform a basename-only match if the pattern does not contain any slash\n * characters. That is, `*.js` would be treated as equivalent to\n * `**\\/*.js`, matching all js files in all directories.\n */\n matchBase?: boolean\n\n /**\n * Limit the directory traversal to a given depth below the cwd.\n * Note that this does NOT prevent traversal to sibling folders,\n * root patterns, and so on. It only limits the maximum folder depth\n * that the walk will descend, relative to the cwd.\n */\n maxDepth?: number\n\n /**\n * Do not expand `{a,b}` and `{1..3}` brace sets.\n */\n nobrace?: boolean\n\n /**\n * Perform a case-insensitive match. This defaults to `true` on macOS and\n * Windows systems, and `false` on all others.\n *\n * **Note** `nocase` should only be explicitly set when it is\n * known that the filesystem's case sensitivity differs from the\n * platform default. If set `true` on case-sensitive file\n * systems, or `false` on case-insensitive file systems, then the\n * walk may return more or less results than expected.\n */\n nocase?: boolean\n\n /**\n * Do not match directories, only files. (Note: to match\n * _only_ directories, put a `/` at the end of the pattern.)\n */\n nodir?: boolean\n\n /**\n * Do not match \"extglob\" patterns such as `+(a|b)`.\n */\n noext?: boolean\n\n /**\n * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n * `*` instead.)\n *\n * Conflicts with {@link matchBase}\n */\n noglobstar?: boolean\n\n /**\n * Defaults to value of `process.platform` if available, or `'linux'` if\n * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n * behavior.\n */\n platform?: NodeJS.Platform\n\n /**\n * Set to true to call `fs.realpath` on all of the\n * results. In the case of an entry that cannot be resolved, the\n * entry is omitted. This incurs a slight performance penalty, of\n * course, because of the added system calls.\n */\n realpath?: boolean\n\n /**\n *\n * A string path resolved against the `cwd` option, which\n * is used as the starting point for absolute patterns that start\n * with `/`, (but not drive letters or UNC paths on Windows).\n *\n * Note that this _doesn't_ necessarily limit the walk to the\n * `root` directory, and doesn't affect the cwd starting point for\n * non-absolute patterns. A pattern containing `..` will still be\n * able to traverse out of the root directory, if it is not an\n * actual root directory on the filesystem, and any non-absolute\n * patterns will be matched in the `cwd`. For example, the\n * pattern `/../*` with `{root:'/some/path'}` will return all\n * files in `/some`, not all files in `/some/path`. The pattern\n * `*` with `{root:'/some/path'}` will return all the entries in\n * the cwd, not the entries in `/some/path`.\n *\n * To start absolute and non-absolute patterns in the same\n * path, you can use `{root:''}`. However, be aware that on\n * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n * _always_ start in the `x:/` or `//host/share` directory,\n * regardless of the `root` setting.\n */\n root?: string\n\n /**\n * A [PathScurry](http://npm.im/path-scurry) object used\n * to traverse the file system. If the `nocase` option is set\n * explicitly, then any provided `scurry` object must match this\n * setting.\n */\n scurry?: PathScurry\n\n /**\n * Call `lstat()` on all entries, whether required or not to determine\n * if it's a valid match. When used with {@link withFileTypes}, this means\n * that matches will include data such as modified time, permissions, and\n * so on. Note that this will incur a performance cost due to the added\n * system calls.\n */\n stat?: boolean\n\n /**\n * An AbortSignal which will cancel the Glob walk when\n * triggered.\n */\n signal?: AbortSignal\n\n /**\n * Use `\\\\` as a path separator _only_, and\n * _never_ as an escape character. If set, all `\\\\` characters are\n * replaced with `/` in the pattern.\n *\n * Note that this makes it **impossible** to match against paths\n * containing literal glob pattern characters, but allows matching\n * with patterns constructed using `path.join()` and\n * `path.resolve()` on Windows platforms, mimicking the (buggy!)\n * behavior of Glob v7 and before on Windows. Please use with\n * caution, and be mindful of [the caveat below about Windows\n * paths](#windows). (For legacy reasons, this is also set if\n * `allowWindowsEscape` is set to the exact value `false`.)\n */\n windowsPathsNoEscape?: boolean\n\n /**\n * Return [PathScurry](http://npm.im/path-scurry)\n * `Path` objects instead of strings. These are similar to a\n * NodeJS `Dirent` object, but with additional methods and\n * properties.\n *\n * Conflicts with {@link absolute}\n */\n withFileTypes?: boolean\n\n /**\n * An fs implementation to override some or all of the defaults. See\n * http://npm.im/path-scurry for details about what can be overridden.\n */\n fs?: FSOption\n\n /**\n * Just passed along to Minimatch. Note that this makes all pattern\n * matching operations slower and *extremely* noisy.\n */\n debug?: boolean\n\n /**\n * Return `/` delimited paths, even on Windows.\n *\n * On posix systems, this has no effect. But, on Windows, it means that\n * paths will be `/` delimited, and absolute paths will be their full\n * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n * `'//?/C:/foo/bar'`\n */\n posix?: boolean\n\n /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n withFileTypes: true\n // string options not relevant if returning Path objects.\n absolute?: undefined\n mark?: undefined\n posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n withFileTypes?: undefined\n}\n\nexport type Result<Opts> =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results<Opts> = Result<Opts>[]\n\nexport type FileTypes<Opts> =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? false\n : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob<Opts extends GlobOptions> implements GlobOptions {\n absolute?: boolean\n cwd: string\n root?: string\n dot: boolean\n dotRelative: boolean\n follow: boolean\n ignore?: string | string[] | IgnoreLike\n magicalBraces: boolean\n mark?: boolean\n matchBase: boolean\n maxDepth: number\n nobrace: boolean\n nocase: boolean\n nodir: boolean\n noext: boolean\n noglobstar: boolean\n pattern: string[]\n platform: NodeJS.Platform\n realpath: boolean\n scurry: PathScurry\n stat: boolean\n signal?: AbortSignal\n windowsPathsNoEscape: boolean\n withFileTypes: FileTypes<Opts>\n includeChildMatches: boolean\n\n /**\n * The options provided to the constructor.\n */\n opts: Opts\n\n /**\n * An array of parsed immutable {@link Pattern} objects.\n */\n patterns: Pattern[]\n\n /**\n * All options are stored as properties on the `Glob` object.\n *\n * See {@link GlobOptions} for full options descriptions.\n *\n * Note that a previous `Glob` object can be passed as the\n * `GlobOptions` to another `Glob` instantiation to re-use settings\n * and caches with a new pattern.\n *\n * Traversal functions can be called multiple times to run the walk\n * again.\n */\n constructor(pattern: string | string[], opts: Opts) {\n /* c8 ignore start */\n if (!opts) throw new TypeError('glob options required')\n /* c8 ignore stop */\n this.withFileTypes = !!opts.withFileTypes as FileTypes<Opts>\n this.signal = opts.signal\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.dotRelative = !!opts.dotRelative\n this.nodir = !!opts.nodir\n this.mark = !!opts.mark\n if (!opts.cwd) {\n this.cwd = ''\n } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n opts.cwd = fileURLToPath(opts.cwd)\n }\n this.cwd = opts.cwd || ''\n this.root = opts.root\n this.magicalBraces = !!opts.magicalBraces\n this.nobrace = !!opts.nobrace\n this.noext = !!opts.noext\n this.realpath = !!opts.realpath\n this.absolute = opts.absolute\n this.includeChildMatches = opts.includeChildMatches !== false\n\n this.noglobstar = !!opts.noglobstar\n this.matchBase = !!opts.matchBase\n this.maxDepth =\n typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n this.stat = !!opts.stat\n this.ignore = opts.ignore\n\n if (this.withFileTypes && this.absolute !== undefined) {\n throw new Error('cannot set absolute and withFileTypes:true')\n }\n\n if (typeof pattern === 'string') {\n pattern = [pattern]\n }\n\n this.windowsPathsNoEscape =\n !!opts.windowsPathsNoEscape ||\n (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n false\n\n if (this.windowsPathsNoEscape) {\n pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n }\n\n if (this.matchBase) {\n if (opts.noglobstar) {\n throw new TypeError('base matching requires globstar')\n }\n pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n }\n\n this.pattern = pattern\n\n this.platform = opts.platform || defaultPlatform\n this.opts = { ...opts, platform: this.platform }\n if (opts.scurry) {\n this.scurry = opts.scurry\n if (\n opts.nocase !== undefined &&\n opts.nocase !== opts.scurry.nocase\n ) {\n throw new Error('nocase option contradicts provided scurry option')\n }\n } else {\n const Scurry =\n opts.platform === 'win32' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? PathScurryPosix\n : PathScurry\n this.scurry = new Scurry(this.cwd, {\n nocase: opts.nocase,\n fs: opts.fs,\n })\n }\n this.nocase = this.scurry.nocase\n\n // If you do nocase:true on a case-sensitive file system, then\n // we need to use regexps instead of strings for non-magic\n // path portions, because statting `aBc` won't return results\n // for the file `AbC` for example.\n const nocaseMagicOnly =\n this.platform === 'darwin' || this.platform === 'win32'\n\n const mmo: MinimatchOptions = {\n // default nocase based on platform\n ...opts,\n dot: this.dot,\n matchBase: this.matchBase,\n nobrace: this.nobrace,\n nocase: this.nocase,\n nocaseMagicOnly,\n nocomment: true,\n noext: this.noext,\n nonegate: true,\n optimizationLevel: 2,\n platform: this.platform,\n windowsPathsNoEscape: this.windowsPathsNoEscape,\n debug: !!this.opts.debug,\n }\n\n const mms = this.pattern.map(p => new Minimatch(p, mmo))\n const [matchSet, globParts] = mms.reduce(\n (set: [MatchSet, GlobParts], m) => {\n set[0].push(...m.set)\n set[1].push(...m.globParts)\n return set\n },\n [[], []],\n )\n this.patterns = matchSet.map((set, i) => {\n const g = globParts[i]\n /* c8 ignore start */\n if (!g) throw new Error('invalid pattern object')\n /* c8 ignore stop */\n return new Pattern(set, g, 0, this.platform)\n })\n }\n\n /**\n * Returns a Promise that resolves to the results array.\n */\n async walk(): Promise<Results<Opts>>\n async walk(): Promise<(string | Path)[]> {\n // Walkers always return array of Path objects, so we just have to\n // coerce them into the right shape. It will have already called\n // realpath() if the option was set to do so, so we know that's cached.\n // start out knowing the cwd, at least\n return [\n ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walk()),\n ]\n }\n\n /**\n * synchronous {@link Glob.walk}\n */\n walkSync(): Results<Opts>\n walkSync(): (string | Path)[] {\n return [\n ...new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walkSync(),\n ]\n }\n\n /**\n * Stream results asynchronously.\n */\n stream(): Minipass<Result<Opts>, Result<Opts>>\n stream(): Minipass<string | Path, string | Path> {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).stream()\n }\n\n /**\n * Stream results synchronously.\n */\n streamSync(): Minipass<Result<Opts>, Result<Opts>>\n streamSync(): Minipass<string | Path, string | Path> {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).streamSync()\n }\n\n /**\n * Default sync iteration function. Returns a Generator that\n * iterates over the results.\n */\n iterateSync(): Generator<Result<Opts>, void, void> {\n return this.streamSync()[Symbol.iterator]()\n }\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n /**\n * Default async iteration function. Returns an AsyncGenerator that\n * iterates over the results.\n */\n iterate(): AsyncGenerator<Result<Opts>, void, void> {\n return this.stream()[Symbol.asyncIterator]()\n }\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n}\n","/**\n * @module LRUCache\n */\n\n// module-private names and types\ntype Perf = { now: () => number }\nconst perf: Perf =\n typeof performance === 'object' &&\n performance &&\n typeof performance.now === 'function'\n ? performance\n : Date\n\nconst warned = new Set<string>()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n typeof process === 'object' && !!process ? process : {}\n) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n msg: string,\n type: string,\n code: string,\n fn: ForC\n) => {\n typeof PROCESS.emitWarning === 'function'\n ? PROCESS.emitWarning(msg, type, code, fn)\n : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n //@ts-ignore\n AS = class AbortSignal {\n onabort?: (...a: any[]) => any\n _onabort: ((...a: any[]) => any)[] = []\n reason?: any\n aborted: boolean = false\n addEventListener(_: string, fn: (...a: any[]) => any) {\n this._onabort.push(fn)\n }\n }\n //@ts-ignore\n AC = class AbortController {\n constructor() {\n warnACPolyfill()\n }\n signal = new AS()\n abort(reason: any) {\n if (this.signal.aborted) return\n //@ts-ignore\n this.signal.reason = reason\n //@ts-ignore\n this.signal.aborted = true\n //@ts-ignore\n for (const fn of this.signal._onabort) {\n fn(reason)\n }\n this.signal.onabort?.(reason)\n }\n }\n let printACPolyfillWarning =\n PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n const warnACPolyfill = () => {\n if (!printACPolyfillWarning) return\n printACPolyfillWarning = false\n emitWarning(\n 'AbortController is not defined. If using lru-cache in ' +\n 'node 14, load an AbortController polyfill from the ' +\n '`node-abort-controller` package. A minimal polyfill is ' +\n 'provided for use by LRUCache.fetch(), but it should not be ' +\n 'relied upon in other contexts (eg, passing it to other APIs that ' +\n 'use AbortController/AbortSignal might have undesirable effects). ' +\n 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n 'NO_ABORT_CONTROLLER',\n 'ENOTSUP',\n warnACPolyfill\n )\n }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values. Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n !isPosInt(max)\n ? null\n : max <= Math.pow(2, 8)\n ? Uint8Array\n : max <= Math.pow(2, 16)\n ? Uint16Array\n : max <= Math.pow(2, 32)\n ? Uint32Array\n : max <= Number.MAX_SAFE_INTEGER\n ? ZeroArray\n : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array<number> {\n constructor(size: number) {\n super(size)\n this.fill(0)\n }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n heap: NumberArray\n length: number\n // private constructor\n static #constructing: boolean = false\n static create(max: number): StackLike {\n const HeapCls = getUintArray(max)\n if (!HeapCls) return []\n Stack.#constructing = true\n const s = new Stack(max, HeapCls)\n Stack.#constructing = false\n return s\n }\n constructor(\n max: number,\n HeapCls: { new (n: number): NumberArray }\n ) {\n /* c8 ignore start */\n if (!Stack.#constructing) {\n throw new TypeError('instantiate Stack using Stack.create(n)')\n }\n /* c8 ignore stop */\n this.heap = new HeapCls(max)\n this.length = 0\n }\n push(n: Index) {\n this.heap[this.length++] = n\n }\n pop(): Index {\n return this.heap[--this.length] as Index\n }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch<V> = Promise<V | undefined> & {\n __returned: BackgroundFetch<V> | undefined\n __abortController: AbortController\n __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask<K, V> = [\n value: V,\n key: K,\n reason: LRUCache.DisposeReason\n]\n\nexport namespace LRUCache {\n /**\n * An integer greater than 0, reflecting the calculated size of items\n */\n export type Size = number\n\n /**\n * Integer greater than 0, representing some number of milliseconds, or the\n * time at which a TTL started counting from.\n */\n export type Milliseconds = number\n\n /**\n * An integer greater than 0, reflecting a number of items\n */\n export type Count = number\n\n /**\n * The reason why an item was removed from the cache, passed\n * to the {@link Disposer} methods.\n *\n * - `evict`: The item was evicted because it is the least recently used,\n * and the cache is full.\n * - `set`: A new value was set, overwriting the old value being disposed.\n * - `delete`: The item was explicitly deleted, either by calling\n * {@link LRUCache#delete}, {@link LRUCache#clear}, or\n * {@link LRUCache#set} with an undefined value.\n * - `expire`: The item was removed due to exceeding its TTL.\n * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n * `undefined` or was aborted, causing the item to be deleted.\n */\n export type DisposeReason =\n | 'evict'\n | 'set'\n | 'delete'\n | 'expire'\n | 'fetch'\n /**\n * A method called upon item removal, passed as the\n * {@link OptionsBase.dispose} and/or\n * {@link OptionsBase.disposeAfter} options.\n */\n export type Disposer<K, V> = (\n value: V,\n key: K,\n reason: DisposeReason\n ) => void\n\n /**\n * A function that returns the effective calculated size\n * of an entry in the cache.\n */\n export type SizeCalculator<K, V> = (value: V, key: K) => Size\n\n /**\n * Options provided to the\n * {@link OptionsBase.fetchMethod} function.\n */\n export interface FetcherOptions<K, V, FC = unknown> {\n signal: AbortSignal\n options: FetcherFetchOptions<K, V, FC>\n /**\n * Object provided in the {@link FetchOptions.context} option to\n * {@link LRUCache#fetch}\n */\n context: FC\n }\n\n /**\n * Occasionally, it may be useful to track the internal behavior of the\n * cache, particularly for logging, debugging, or for behavior within the\n * `fetchMethod`. To do this, you can pass a `status` object to the\n * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n *\n * The `status` option should be a plain JavaScript object. The following\n * fields will be set on it appropriately, depending on the situation.\n */\n export interface Status<V> {\n /**\n * The status of a set() operation.\n *\n * - add: the item was not found in the cache, and was added\n * - update: the item was in the cache, with the same value provided\n * - replace: the item was in the cache, and replaced\n * - miss: the item was not added to the cache for some reason\n */\n set?: 'add' | 'update' | 'replace' | 'miss'\n\n /**\n * the ttl stored for the item, or undefined if ttls are not used.\n */\n ttl?: Milliseconds\n\n /**\n * the start time for the item, or undefined if ttls are not used.\n */\n start?: Milliseconds\n\n /**\n * The timestamp used for TTL calculation\n */\n now?: Milliseconds\n\n /**\n * the remaining ttl for the item, or undefined if ttls are not used.\n */\n remainingTTL?: Milliseconds\n\n /**\n * The calculated size for the item, if sizes are used.\n */\n entrySize?: Size\n\n /**\n * The total calculated size of the cache, if sizes are used.\n */\n totalCalculatedSize?: Size\n\n /**\n * A flag indicating that the item was not stored, due to exceeding the\n * {@link OptionsBase.maxEntrySize}\n */\n maxEntrySizeExceeded?: true\n\n /**\n * The old value, specified in the case of `set:'update'` or\n * `set:'replace'`\n */\n oldValue?: V\n\n /**\n * The results of a {@link LRUCache#has} operation\n *\n * - hit: the item was found in the cache\n * - stale: the item was found in the cache, but is stale\n * - miss: the item was not found in the cache\n */\n has?: 'hit' | 'stale' | 'miss'\n\n /**\n * The status of a {@link LRUCache#fetch} operation.\n * Note that this can change as the underlying fetch() moves through\n * various states.\n *\n * - inflight: there is another fetch() for this key which is in process\n * - get: there is no {@link OptionsBase.fetchMethod}, so\n * {@link LRUCache#get} was called.\n * - miss: the item is not in cache, and will be fetched.\n * - hit: the item is in the cache, and was resolved immediately.\n * - stale: the item is in the cache, but stale.\n * - refresh: the item is in the cache, and not stale, but\n * {@link FetchOptions.forceRefresh} was specified.\n */\n fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n /**\n * The {@link OptionsBase.fetchMethod} was called\n */\n fetchDispatched?: true\n\n /**\n * The cached value was updated after a successful call to\n * {@link OptionsBase.fetchMethod}\n */\n fetchUpdated?: true\n\n /**\n * The reason for a fetch() rejection. Either the error raised by the\n * {@link OptionsBase.fetchMethod}, or the reason for an\n * AbortSignal.\n */\n fetchError?: Error\n\n /**\n * The fetch received an abort signal\n */\n fetchAborted?: true\n\n /**\n * The abort signal received was ignored, and the fetch was allowed to\n * continue.\n */\n fetchAbortIgnored?: true\n\n /**\n * The fetchMethod promise resolved successfully\n */\n fetchResolved?: true\n\n /**\n * The fetchMethod promise was rejected\n */\n fetchRejected?: true\n\n /**\n * The status of a {@link LRUCache#get} operation.\n *\n * - fetching: The item is currently being fetched. If a previous value\n * is present and allowed, that will be returned.\n * - stale: The item is in the cache, and is stale.\n * - hit: the item is in the cache\n * - miss: the item is not in the cache\n */\n get?: 'stale' | 'hit' | 'miss'\n\n /**\n * A fetch or get operation returned a stale value.\n */\n returnedStale?: true\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#fetch}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link OptionsBase.noDeleteOnFetchRejection},\n * {@link OptionsBase.allowStaleOnFetchRejection},\n * {@link FetchOptions.forceRefresh}, and\n * {@link FetcherOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n * function, but the {@link GetOptions} fields will of course have no\n * effect, as the {@link LRUCache#get} call already happened by the time\n * the fetchMethod is called.\n */\n export interface FetcherFetchOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n | 'noDeleteOnFetchRejection'\n | 'allowStaleOnFetchRejection'\n | 'ignoreFetchAbort'\n | 'allowStaleOnFetchAbort'\n > {\n status?: Status<V>\n size?: Size\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#fetch} method.\n */\n export interface FetchOptions<K, V, FC>\n extends FetcherFetchOptions<K, V, FC> {\n /**\n * Set to true to force a re-load of the existing data, even if it\n * is not yet stale.\n */\n forceRefresh?: boolean\n /**\n * Context provided to the {@link OptionsBase.fetchMethod} as\n * the {@link FetcherOptions.context} param.\n *\n * If the FC type is specified as unknown (the default),\n * undefined or void, then this is optional. Otherwise, it will\n * be required.\n */\n context?: FC\n signal?: AbortSignal\n status?: Status<V>\n }\n /**\n * Options provided to {@link LRUCache#fetch} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface FetchOptionsWithContext<K, V, FC>\n extends FetchOptions<K, V, FC> {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#fetch} when the FC type is\n * `undefined` or `void`\n */\n export interface FetchOptionsNoContext<K, V>\n extends FetchOptions<K, V, undefined> {\n context?: undefined\n }\n\n export interface MemoOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n | 'noDeleteOnFetchRejection'\n | 'allowStaleOnFetchRejection'\n | 'ignoreFetchAbort'\n | 'allowStaleOnFetchAbort'\n > {\n /**\n * Set to true to force a re-load of the existing data, even if it\n * is not yet stale.\n */\n forceRefresh?: boolean\n /**\n * Context provided to the {@link OptionsBase.memoMethod} as\n * the {@link MemoizerOptions.context} param.\n *\n * If the FC type is specified as unknown (the default),\n * undefined or void, then this is optional. Otherwise, it will\n * be required.\n */\n context?: FC\n status?: Status<V>\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface MemoOptionsWithContext<K, V, FC>\n extends MemoOptions<K, V, FC> {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is\n * `undefined` or `void`\n */\n export interface MemoOptionsNoContext<K, V>\n extends MemoOptions<K, V, undefined> {\n context?: undefined\n }\n\n /**\n * Options provided to the\n * {@link OptionsBase.memoMethod} function.\n */\n export interface MemoizerOptions<K, V, FC = unknown> {\n options: MemoizerMemoOptions<K, V, FC>\n /**\n * Object provided in the {@link MemoOptions.context} option to\n * {@link LRUCache#memo}\n */\n context: FC\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#memo}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link MemoOptions.forceRefresh}, and\n * {@link MemoerOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.memoMethod}\n * function, but the {@link GetOptions} fields will of course have no\n * effect, as the {@link LRUCache#get} call already happened by the time\n * the memoMethod is called.\n */\n export interface MemoizerMemoOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n > {\n status?: Status<V>\n size?: Size\n start?: Milliseconds\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#has} method.\n */\n export interface HasOptions<K, V, FC>\n extends Pick<OptionsBase<K, V, FC>, 'updateAgeOnHas'> {\n status?: Status<V>\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#get} method.\n */\n export interface GetOptions<K, V, FC>\n extends Pick<\n OptionsBase<K, V, FC>,\n 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n > {\n status?: Status<V>\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#peek} method.\n */\n export interface PeekOptions<K, V, FC>\n extends Pick<OptionsBase<K, V, FC>, 'allowStale'> {}\n\n /**\n * Options that may be passed to the {@link LRUCache#set} method.\n */\n export interface SetOptions<K, V, FC>\n extends Pick<\n OptionsBase<K, V, FC>,\n 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n > {\n /**\n * If size tracking is enabled, then setting an explicit size\n * in the {@link LRUCache#set} call will prevent calling the\n * {@link OptionsBase.sizeCalculation} function.\n */\n size?: Size\n /**\n * If TTL tracking is enabled, then setting an explicit start\n * time in the {@link LRUCache#set} call will override the\n * default time from `performance.now()` or `Date.now()`.\n *\n * Note that it must be a valid value for whichever time-tracking\n * method is in use.\n */\n start?: Milliseconds\n status?: Status<V>\n }\n\n /**\n * The type signature for the {@link OptionsBase.fetchMethod} option.\n */\n export type Fetcher<K, V, FC = unknown> = (\n key: K,\n staleValue: V | undefined,\n options: FetcherOptions<K, V, FC>\n ) => Promise<V | undefined | void> | V | undefined | void\n\n /**\n * the type signature for the {@link OptionsBase.memoMethod} option.\n */\n export type Memoizer<K, V, FC = unknown> = (\n key: K,\n staleValue: V | undefined,\n options: MemoizerOptions<K, V, FC>\n ) => V\n\n /**\n * Options which may be passed to the {@link LRUCache} constructor.\n *\n * Most of these may be overridden in the various options that use\n * them.\n *\n * Despite all being technically optional, the constructor requires that\n * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n *\n * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n * (and in fact required by the type definitions here) that the cache\n * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n * unbounded storage.\n *\n * All options are also available on the {@link LRUCache} instance, making\n * it safe to pass an LRUCache instance as the options argumemnt to\n * make another empty cache of the same type.\n *\n * Some options are marked as read-only, because changing them after\n * instantiation is not safe. Changing any of the other options will of\n * course only have an effect on subsequent method calls.\n */\n export interface OptionsBase<K, V, FC> {\n /**\n * The maximum number of items to store in the cache before evicting\n * old entries. This is read-only on the {@link LRUCache} instance,\n * and may not be overridden.\n *\n * If set, then storage space will be pre-allocated at construction\n * time, and the cache will perform significantly faster.\n *\n * Note that significantly fewer items may be stored, if\n * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n * set.\n *\n * **It is strongly recommended to set a `max` to prevent unbounded growth\n * of the cache.**\n */\n max?: Count\n\n /**\n * Max time in milliseconds for items to live in cache before they are\n * considered stale. Note that stale items are NOT preemptively removed by\n * default, and MAY live in the cache, contributing to its LRU max, long\n * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n * set.\n *\n * If set to `0` (the default value), then that means \"do not track\n * TTL\", not \"expire immediately\".\n *\n * Also, as this cache is optimized for LRU/MRU operations, some of\n * the staleness/TTL checks will reduce performance, as they will incur\n * overhead by deleting items.\n *\n * This is not primarily a TTL cache, and does not make strong TTL\n * guarantees. There is no pre-emptive pruning of expired items, but you\n * _may_ set a TTL on the cache, and it will treat expired items as missing\n * when they are fetched, and delete them.\n *\n * Optional, but must be a non-negative integer in ms if specified.\n *\n * This may be overridden by passing an options object to `cache.set()`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if ttl tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n * and `ttlAutopurge` is not set, then a warning will be emitted\n * cautioning about the potential for unbounded memory consumption.\n * (The TypeScript definitions will also discourage this.)\n */\n ttl?: Milliseconds\n\n /**\n * Minimum amount of time in ms in which to check for staleness.\n * Defaults to 1, which means that the current time is checked\n * at most once per millisecond.\n *\n * Set to 0 to check the current time every time staleness is tested.\n * (This reduces performance, and is theoretically unnecessary.)\n *\n * Setting this to a higher value will improve performance somewhat\n * while using ttl tracking, albeit at the expense of keeping stale\n * items around a bit longer than their TTLs would indicate.\n *\n * @default 1\n */\n ttlResolution?: Milliseconds\n\n /**\n * Preemptively remove stale items from the cache.\n *\n * Note that this may *significantly* degrade performance, especially if\n * the cache is storing a large number of items. It is almost always best\n * to just leave the stale items in the cache, and let them fall out as new\n * items are added.\n *\n * Note that this means that {@link OptionsBase.allowStale} is a bit\n * pointless, as stale items will be deleted almost as soon as they\n * expire.\n *\n * Use with caution!\n */\n ttlAutopurge?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever it is retrieved from cache with\n * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n * of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n */\n updateAgeOnGet?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever its presence in the cache is\n * checked with {@link LRUCache#has}, causing it to not expire. (It can\n * still fall out of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n */\n updateAgeOnHas?: boolean\n\n /**\n * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n * stale data, if available.\n *\n * By default, if you set `ttl`, stale items will only be deleted from the\n * cache when you `get(key)`. That is, it's not preemptively pruning items,\n * unless {@link OptionsBase.ttlAutopurge} is set.\n *\n * If you set `allowStale:true`, it'll return the stale value *as well as*\n * deleting it. If you don't set this, then it'll return `undefined` when\n * you try to get a stale entry.\n *\n * Note that when a stale entry is fetched, _even if it is returned due to\n * `allowStale` being set_, it is removed from the cache immediately. You\n * can suppress this behavior by setting\n * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n * the options provided to {@link LRUCache#get}.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n * The `cache.has()` method will always return `false` for stale items.\n *\n * Only relevant if a ttl is set.\n */\n allowStale?: boolean\n\n /**\n * Function that is called on items when they are dropped from the\n * cache, as `dispose(value, key, reason)`.\n *\n * This can be handy if you want to close file descriptors or do\n * other cleanup tasks when items are no longer stored in the cache.\n *\n * **NOTE**: It is called _before_ the item has been fully removed\n * from the cache, so if you want to put it right back in, you need\n * to wait until the next tick. If you try to add it back in during\n * the `dispose()` function call, it will break things in subtle and\n * weird ways.\n *\n * Unlike several other options, this may _not_ be overridden by\n * passing an option to `set()`, for performance reasons.\n *\n * The `reason` will be one of the following strings, corresponding\n * to the reason for the item's deletion:\n *\n * - `evict` Item was evicted to make space for a new addition\n * - `set` Item was overwritten by a new value\n * - `expire` Item expired its TTL\n * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n * fetchMethod returning `undefined.\n * - `delete` Item was removed by explicit `cache.delete(key)`,\n * `cache.clear()`, or `cache.set(key, undefined)`.\n */\n dispose?: Disposer<K, V>\n\n /**\n * The same as {@link OptionsBase.dispose}, but called *after* the entry\n * is completely removed and the cache is once again in a clean state.\n *\n * It is safe to add an item right back into the cache at this point.\n * However, note that it is *very* easy to inadvertently create infinite\n * recursion this way.\n */\n disposeAfter?: Disposer<K, V>\n\n /**\n * Set to true to suppress calling the\n * {@link OptionsBase.dispose} function if the entry key is\n * still accessible within the cache.\n *\n * This may be overridden by passing an options object to\n * {@link LRUCache#set}.\n *\n * Only relevant if `dispose` or `disposeAfter` are set.\n */\n noDisposeOnSet?: boolean\n\n /**\n * Boolean flag to tell the cache to not update the TTL when setting a new\n * value for an existing key (ie, when updating a value rather than\n * inserting a new value). Note that the TTL value is _always_ set (if\n * provided) when adding a new entry into the cache.\n *\n * Has no effect if a {@link OptionsBase.ttl} is not set.\n *\n * May be passed as an option to {@link LRUCache#set}.\n */\n noUpdateTTL?: boolean\n\n /**\n * Set to a positive integer to track the sizes of items added to the\n * cache, and automatically evict items in order to stay below this size.\n * Note that this may result in fewer than `max` items being stored.\n *\n * Attempting to add an item to the cache whose calculated size is greater\n * that this amount will be a no-op. The item will not be cached, and no\n * other items will be evicted.\n *\n * Optional, must be a positive integer if provided.\n *\n * Sets `maxEntrySize` to the same value, unless a different value is\n * provided for `maxEntrySize`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if size tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * Note also that size tracking can negatively impact performance,\n * though for most cases, only minimally.\n */\n maxSize?: Size\n\n /**\n * The maximum allowed size for any single item in the cache.\n *\n * If a larger item is passed to {@link LRUCache#set} or returned by a\n * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n * it will not be stored in the cache.\n *\n * Attempting to add an item whose calculated size is greater than\n * this amount will not cache the item or evict any old items, but\n * WILL delete an existing value if one is already present.\n *\n * Optional, must be a positive integer if provided. Defaults to\n * the value of `maxSize` if provided.\n */\n maxEntrySize?: Size\n\n /**\n * A function that returns a number indicating the item's size.\n *\n * Requires {@link OptionsBase.maxSize} to be set.\n *\n * If not provided, and {@link OptionsBase.maxSize} or\n * {@link OptionsBase.maxEntrySize} are set, then all\n * {@link LRUCache#set} calls **must** provide an explicit\n * {@link SetOptions.size} or sizeCalculation param.\n */\n sizeCalculation?: SizeCalculator<K, V>\n\n /**\n * Method that provides the implementation for {@link LRUCache#fetch}\n *\n * ```ts\n * fetchMethod(key, staleValue, { signal, options, context })\n * ```\n *\n * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n * to `Promise.resolve(cache.get(key))`.\n *\n * If at any time, `signal.aborted` is set to `true`, or if the\n * `signal.onabort` method is called, or if it emits an `'abort'` event\n * which you can listen to with `addEventListener`, then that means that\n * the fetch should be abandoned. This may be passed along to async\n * functions aware of AbortController/AbortSignal behavior.\n *\n * The `fetchMethod` should **only** return `undefined` or a Promise\n * resolving to `undefined` if the AbortController signaled an `abort`\n * event. In all other cases, it should return or resolve to a value\n * suitable for adding to the cache.\n *\n * The `options` object is a union of the options that may be provided to\n * `set()` and `get()`. If they are modified, then that will result in\n * modifying the settings to `cache.set()` when the value is resolved, and\n * in the case of\n * {@link OptionsBase.noDeleteOnFetchRejection} and\n * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n * `fetchMethod` failures.\n *\n * For example, a DNS cache may update the TTL based on the value returned\n * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n */\n fetchMethod?: Fetcher<K, V, FC>\n\n /**\n * Method that provides the implementation for {@link LRUCache#memo}\n */\n memoMethod?: Memoizer<K, V, FC>\n\n /**\n * Set to true to suppress the deletion of stale data when a\n * {@link OptionsBase.fetchMethod} returns a rejected promise.\n */\n noDeleteOnFetchRejection?: boolean\n\n /**\n * Do not delete stale items when they are retrieved with\n * {@link LRUCache#get}.\n *\n * Note that the `get` return value will still be `undefined`\n * unless {@link OptionsBase.allowStale} is true.\n *\n * When using time-expiring entries with `ttl`, by default stale\n * items will be removed from the cache when the key is accessed\n * with `cache.get()`.\n *\n * Setting this option will cause stale items to remain in the cache, until\n * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n * `noDeleteOnStaleGet` set to `false`.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n *\n * Only relevant if a ttl is used.\n */\n noDeleteOnStaleGet?: boolean\n\n /**\n * Set to true to allow returning stale data when a\n * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n * promise.\n *\n * This differs from using {@link OptionsBase.allowStale} in that stale\n * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n * fails, not any other times.\n *\n * If a `fetchMethod` fails, and there is no stale value available, the\n * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n * suppressed.\n *\n * Implies `noDeleteOnFetchRejection`.\n *\n * This may be set in calls to `fetch()`, or defaulted on the constructor,\n * or overridden by modifying the options object in the `fetchMethod`.\n */\n allowStaleOnFetchRejection?: boolean\n\n /**\n * Set to true to return a stale value from the cache when the\n * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n * an `'abort'` event, whether user-triggered, or due to internal cache\n * behavior.\n *\n * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n * any value it returns will be ignored and not cached.\n *\n * Caveat: since fetches are aborted when a new value is explicitly\n * set in the cache, this can lead to fetch returning a stale value,\n * since that was the fallback value _at the moment the `fetch()` was\n * initiated_, even though the new updated value is now present in\n * the cache.\n *\n * For example:\n *\n * ```ts\n * const cache = new LRUCache<string, any>({\n * ttl: 100,\n * fetchMethod: async (url, oldValue, { signal }) => {\n * const res = await fetch(url, { signal })\n * return await res.json()\n * }\n * })\n * cache.set('https://example.com/', { some: 'data' })\n * // 100ms go by...\n * const result = cache.fetch('https://example.com/')\n * cache.set('https://example.com/', { other: 'thing' })\n * console.log(await result) // { some: 'data' }\n * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n * ```\n */\n allowStaleOnFetchAbort?: boolean\n\n /**\n * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n * resulting resolution value, as long as it is not `undefined`.\n *\n * When used on its own, this means aborted {@link LRUCache#fetch} calls\n * are not immediately resolved or rejected when they are aborted, and\n * instead take the full time to await.\n *\n * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n * {@link LRUCache#fetch} calls will resolve immediately to their stale\n * cached value or `undefined`, and will continue to process and eventually\n * update the cache when they resolve, as long as the resulting value is\n * not `undefined`, thus supporting a \"return stale on timeout while\n * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n *\n * For example:\n *\n * ```ts\n * const c = new LRUCache({\n * ttl: 100,\n * ignoreFetchAbort: true,\n * allowStaleOnFetchAbort: true,\n * fetchMethod: async (key, oldValue, { signal }) => {\n * // note: do NOT pass the signal to fetch()!\n * // let's say this fetch can take a long time.\n * const res = await fetch(`https://slow-backend-server/${key}`)\n * return await res.json()\n * },\n * })\n *\n * // this will return the stale value after 100ms, while still\n * // updating in the background for next time.\n * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n * ```\n *\n * **Note**: regardless of this setting, an `abort` event _is still\n * emitted on the `AbortSignal` object_, so may result in invalid results\n * when passed to other underlying APIs that use AbortSignals.\n *\n * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n * call to {@link LRUCache#fetch}.\n */\n ignoreFetchAbort?: boolean\n }\n\n export interface OptionsMaxLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n max: Count\n }\n export interface OptionsTTLLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n ttl: Milliseconds\n ttlAutopurge: boolean\n }\n export interface OptionsSizeLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n maxSize: Size\n }\n\n /**\n * The valid safe options for the {@link LRUCache} constructor\n */\n export type Options<K, V, FC> =\n | OptionsMaxLimit<K, V, FC>\n | OptionsSizeLimit<K, V, FC>\n | OptionsTTLLimit<K, V, FC>\n\n /**\n * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n * and returned by {@link LRUCache#info}.\n */\n export interface Entry<V> {\n value: V\n ttl?: Milliseconds\n size?: Size\n start?: Milliseconds\n }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache<K extends {}, V extends {}, FC = unknown>\n implements Map<K, V>\n{\n // options that cannot be changed without disaster\n readonly #max: LRUCache.Count\n readonly #maxSize: LRUCache.Size\n readonly #dispose?: LRUCache.Disposer<K, V>\n readonly #disposeAfter?: LRUCache.Disposer<K, V>\n readonly #fetchMethod?: LRUCache.Fetcher<K, V, FC>\n readonly #memoMethod?: LRUCache.Memoizer<K, V, FC>\n\n /**\n * {@link LRUCache.OptionsBase.ttl}\n */\n ttl: LRUCache.Milliseconds\n\n /**\n * {@link LRUCache.OptionsBase.ttlResolution}\n */\n ttlResolution: LRUCache.Milliseconds\n /**\n * {@link LRUCache.OptionsBase.ttlAutopurge}\n */\n ttlAutopurge: boolean\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnGet}\n */\n updateAgeOnGet: boolean\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnHas}\n */\n updateAgeOnHas: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStale}\n */\n allowStale: boolean\n\n /**\n * {@link LRUCache.OptionsBase.noDisposeOnSet}\n */\n noDisposeOnSet: boolean\n /**\n * {@link LRUCache.OptionsBase.noUpdateTTL}\n */\n noUpdateTTL: boolean\n /**\n * {@link LRUCache.OptionsBase.maxEntrySize}\n */\n maxEntrySize: LRUCache.Size\n /**\n * {@link LRUCache.OptionsBase.sizeCalculation}\n */\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n */\n noDeleteOnFetchRejection: boolean\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n */\n noDeleteOnStaleGet: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n */\n allowStaleOnFetchAbort: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n */\n allowStaleOnFetchRejection: boolean\n /**\n * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n */\n ignoreFetchAbort: boolean\n\n // computed properties\n #size: LRUCache.Count\n #calculatedSize: LRUCache.Size\n #keyMap: Map<K, Index>\n #keyList: (K | undefined)[]\n #valList: (V | BackgroundFetch<V> | undefined)[]\n #next: NumberArray\n #prev: NumberArray\n #head: Index\n #tail: Index\n #free: StackLike\n #disposed?: DisposeTask<K, V>[]\n #sizes?: ZeroArray\n #starts?: ZeroArray\n #ttls?: ZeroArray\n\n #hasDispose: boolean\n #hasFetchMethod: boolean\n #hasDisposeAfter: boolean\n\n /**\n * Do not call this method unless you need to inspect the\n * inner workings of the cache. If anything returned by this\n * object is modified in any way, strange breakage may occur.\n *\n * These fields are private for a reason!\n *\n * @internal\n */\n static unsafeExposeInternals<\n K extends {},\n V extends {},\n FC extends unknown = unknown\n >(c: LRUCache<K, V, FC>) {\n return {\n // properties\n starts: c.#starts,\n ttls: c.#ttls,\n sizes: c.#sizes,\n keyMap: c.#keyMap as Map<K, number>,\n keyList: c.#keyList,\n valList: c.#valList,\n next: c.#next,\n prev: c.#prev,\n get head() {\n return c.#head\n },\n get tail() {\n return c.#tail\n },\n free: c.#free,\n // methods\n isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n backgroundFetch: (\n k: K,\n index: number | undefined,\n options: LRUCache.FetchOptions<K, V, FC>,\n context: any\n ): BackgroundFetch<V> =>\n c.#backgroundFetch(\n k,\n index as Index | undefined,\n options,\n context\n ),\n moveToTail: (index: number): void =>\n c.#moveToTail(index as Index),\n indexes: (options?: { allowStale: boolean }) =>\n c.#indexes(options),\n rindexes: (options?: { allowStale: boolean }) =>\n c.#rindexes(options),\n isStale: (index: number | undefined) =>\n c.#isStale(index as Index),\n }\n }\n\n // Protected read-only members\n\n /**\n * {@link LRUCache.OptionsBase.max} (read-only)\n */\n get max(): LRUCache.Count {\n return this.#max\n }\n /**\n * {@link LRUCache.OptionsBase.maxSize} (read-only)\n */\n get maxSize(): LRUCache.Count {\n return this.#maxSize\n }\n /**\n * The total computed size of items in the cache (read-only)\n */\n get calculatedSize(): LRUCache.Size {\n return this.#calculatedSize\n }\n /**\n * The number of items stored in the cache (read-only)\n */\n get size(): LRUCache.Count {\n return this.#size\n }\n /**\n * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n */\n get fetchMethod(): LRUCache.Fetcher<K, V, FC> | undefined {\n return this.#fetchMethod\n }\n get memoMethod(): LRUCache.Memoizer<K, V, FC> | undefined {\n return this.#memoMethod\n }\n /**\n * {@link LRUCache.OptionsBase.dispose} (read-only)\n */\n get dispose() {\n return this.#dispose\n }\n /**\n * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n */\n get disposeAfter() {\n return this.#disposeAfter\n }\n\n constructor(\n options: LRUCache.Options<K, V, FC> | LRUCache<K, V, FC>\n ) {\n const {\n max = 0,\n ttl,\n ttlResolution = 1,\n ttlAutopurge,\n updateAgeOnGet,\n updateAgeOnHas,\n allowStale,\n dispose,\n disposeAfter,\n noDisposeOnSet,\n noUpdateTTL,\n maxSize = 0,\n maxEntrySize = 0,\n sizeCalculation,\n fetchMethod,\n memoMethod,\n noDeleteOnFetchRejection,\n noDeleteOnStaleGet,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n } = options\n\n if (max !== 0 && !isPosInt(max)) {\n throw new TypeError('max option must be a nonnegative integer')\n }\n\n const UintArray = max ? getUintArray(max) : Array\n if (!UintArray) {\n throw new Error('invalid max value: ' + max)\n }\n\n this.#max = max\n this.#maxSize = maxSize\n this.maxEntrySize = maxEntrySize || this.#maxSize\n this.sizeCalculation = sizeCalculation\n if (this.sizeCalculation) {\n if (!this.#maxSize && !this.maxEntrySize) {\n throw new TypeError(\n 'cannot set sizeCalculation without setting maxSize or maxEntrySize'\n )\n }\n if (typeof this.sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation set to non-function')\n }\n }\n\n if (\n memoMethod !== undefined &&\n typeof memoMethod !== 'function'\n ) {\n throw new TypeError('memoMethod must be a function if defined')\n }\n this.#memoMethod = memoMethod\n\n if (\n fetchMethod !== undefined &&\n typeof fetchMethod !== 'function'\n ) {\n throw new TypeError(\n 'fetchMethod must be a function if specified'\n )\n }\n this.#fetchMethod = fetchMethod\n this.#hasFetchMethod = !!fetchMethod\n\n this.#keyMap = new Map()\n this.#keyList = new Array(max).fill(undefined)\n this.#valList = new Array(max).fill(undefined)\n this.#next = new UintArray(max)\n this.#prev = new UintArray(max)\n this.#head = 0 as Index\n this.#tail = 0 as Index\n this.#free = Stack.create(max)\n this.#size = 0\n this.#calculatedSize = 0\n\n if (typeof dispose === 'function') {\n this.#dispose = dispose\n }\n if (typeof disposeAfter === 'function') {\n this.#disposeAfter = disposeAfter\n this.#disposed = []\n } else {\n this.#disposeAfter = undefined\n this.#disposed = undefined\n }\n this.#hasDispose = !!this.#dispose\n this.#hasDisposeAfter = !!this.#disposeAfter\n\n this.noDisposeOnSet = !!noDisposeOnSet\n this.noUpdateTTL = !!noUpdateTTL\n this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n this.ignoreFetchAbort = !!ignoreFetchAbort\n\n // NB: maxEntrySize is set to maxSize if it's set\n if (this.maxEntrySize !== 0) {\n if (this.#maxSize !== 0) {\n if (!isPosInt(this.#maxSize)) {\n throw new TypeError(\n 'maxSize must be a positive integer if specified'\n )\n }\n }\n if (!isPosInt(this.maxEntrySize)) {\n throw new TypeError(\n 'maxEntrySize must be a positive integer if specified'\n )\n }\n this.#initializeSizeTracking()\n }\n\n this.allowStale = !!allowStale\n this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n this.updateAgeOnGet = !!updateAgeOnGet\n this.updateAgeOnHas = !!updateAgeOnHas\n this.ttlResolution =\n isPosInt(ttlResolution) || ttlResolution === 0\n ? ttlResolution\n : 1\n this.ttlAutopurge = !!ttlAutopurge\n this.ttl = ttl || 0\n if (this.ttl) {\n if (!isPosInt(this.ttl)) {\n throw new TypeError(\n 'ttl must be a positive integer if specified'\n )\n }\n this.#initializeTTLTracking()\n }\n\n // do not allow completely unbounded caches\n if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n throw new TypeError(\n 'At least one of max, maxSize, or ttl is required'\n )\n }\n if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n const code = 'LRU_CACHE_UNBOUNDED'\n if (shouldWarn(code)) {\n warned.add(code)\n const msg =\n 'TTL caching without ttlAutopurge, max, or maxSize can ' +\n 'result in unbounded memory consumption.'\n emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n }\n }\n }\n\n /**\n * Return the number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n */\n getRemainingTTL(key: K) {\n return this.#keyMap.has(key) ? Infinity : 0\n }\n\n #initializeTTLTracking() {\n const ttls = new ZeroArray(this.#max)\n const starts = new ZeroArray(this.#max)\n this.#ttls = ttls\n this.#starts = starts\n\n this.#setItemTTL = (index, ttl, start = perf.now()) => {\n starts[index] = ttl !== 0 ? start : 0\n ttls[index] = ttl\n if (ttl !== 0 && this.ttlAutopurge) {\n const t = setTimeout(() => {\n if (this.#isStale(index)) {\n this.#delete(this.#keyList[index] as K, 'expire')\n }\n }, ttl + 1)\n // unref() not supported on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref()\n }\n /* c8 ignore stop */\n }\n }\n\n this.#updateItemAge = index => {\n starts[index] = ttls[index] !== 0 ? perf.now() : 0\n }\n\n this.#statusTTL = (status, index) => {\n if (ttls[index]) {\n const ttl = ttls[index]\n const start = starts[index]\n /* c8 ignore next */\n if (!ttl || !start) return\n status.ttl = ttl\n status.start = start\n status.now = cachedNow || getNow()\n const age = status.now - start\n status.remainingTTL = ttl - age\n }\n }\n\n // debounce calls to perf.now() to 1s so we're not hitting\n // that costly call repeatedly.\n let cachedNow = 0\n const getNow = () => {\n const n = perf.now()\n if (this.ttlResolution > 0) {\n cachedNow = n\n const t = setTimeout(\n () => (cachedNow = 0),\n this.ttlResolution\n )\n // not available on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref()\n }\n /* c8 ignore stop */\n }\n return n\n }\n\n this.getRemainingTTL = key => {\n const index = this.#keyMap.get(key)\n if (index === undefined) {\n return 0\n }\n const ttl = ttls[index]\n const start = starts[index]\n if (!ttl || !start) {\n return Infinity\n }\n const age = (cachedNow || getNow()) - start\n return ttl - age\n }\n\n this.#isStale = index => {\n const s = starts[index]\n const t = ttls[index]\n return !!t && !!s && (cachedNow || getNow()) - s > t\n }\n }\n\n // conditionally set private methods related to TTL\n #updateItemAge: (index: Index) => void = () => {}\n #statusTTL: (status: LRUCache.Status<V>, index: Index) => void =\n () => {}\n #setItemTTL: (\n index: Index,\n ttl: LRUCache.Milliseconds,\n start?: LRUCache.Milliseconds\n // ignore because we never call this if we're not already in TTL mode\n /* c8 ignore start */\n ) => void = () => {}\n /* c8 ignore stop */\n\n #isStale: (index: Index) => boolean = () => false\n\n #initializeSizeTracking() {\n const sizes = new ZeroArray(this.#max)\n this.#calculatedSize = 0\n this.#sizes = sizes\n this.#removeItemSize = index => {\n this.#calculatedSize -= sizes[index] as number\n sizes[index] = 0\n }\n this.#requireSize = (k, v, size, sizeCalculation) => {\n // provisionally accept background fetches.\n // actual value size will be checked when they return.\n if (this.#isBackgroundFetch(v)) {\n return 0\n }\n if (!isPosInt(size)) {\n if (sizeCalculation) {\n if (typeof sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation must be a function')\n }\n size = sizeCalculation(v, k)\n if (!isPosInt(size)) {\n throw new TypeError(\n 'sizeCalculation return invalid (expect positive integer)'\n )\n }\n } else {\n throw new TypeError(\n 'invalid size value (must be positive integer). ' +\n 'When maxSize or maxEntrySize is used, sizeCalculation ' +\n 'or size must be set.'\n )\n }\n }\n return size\n }\n this.#addItemSize = (\n index: Index,\n size: LRUCache.Size,\n status?: LRUCache.Status<V>\n ) => {\n sizes[index] = size\n if (this.#maxSize) {\n const maxSize = this.#maxSize - (sizes[index] as number)\n while (this.#calculatedSize > maxSize) {\n this.#evict(true)\n }\n }\n this.#calculatedSize += sizes[index] as number\n if (status) {\n status.entrySize = size\n status.totalCalculatedSize = this.#calculatedSize\n }\n }\n }\n\n #removeItemSize: (index: Index) => void = _i => {}\n #addItemSize: (\n index: Index,\n size: LRUCache.Size,\n status?: LRUCache.Status<V>\n ) => void = (_i, _s, _st) => {}\n #requireSize: (\n k: K,\n v: V | BackgroundFetch<V>,\n size?: LRUCache.Size,\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n ) => LRUCache.Size = (\n _k: K,\n _v: V | BackgroundFetch<V>,\n size?: LRUCache.Size,\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n ) => {\n if (size || sizeCalculation) {\n throw new TypeError(\n 'cannot set size without setting maxSize or maxEntrySize on cache'\n )\n }\n return 0\n };\n\n *#indexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#tail; true; ) {\n if (!this.#isValidIndex(i)) {\n break\n }\n if (allowStale || !this.#isStale(i)) {\n yield i\n }\n if (i === this.#head) {\n break\n } else {\n i = this.#prev[i] as Index\n }\n }\n }\n }\n\n *#rindexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#head; true; ) {\n if (!this.#isValidIndex(i)) {\n break\n }\n if (allowStale || !this.#isStale(i)) {\n yield i\n }\n if (i === this.#tail) {\n break\n } else {\n i = this.#next[i] as Index\n }\n }\n }\n }\n\n #isValidIndex(index: Index) {\n return (\n index !== undefined &&\n this.#keyMap.get(this.#keyList[index] as K) === index\n )\n }\n\n /**\n * Return a generator yielding `[key, value]` pairs,\n * in order from most recently used to least recently used.\n */\n *entries() {\n for (const i of this.#indexes()) {\n if (\n this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield [this.#keyList[i], this.#valList[i]] as [K, V]\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.entries}\n *\n * Return a generator yielding `[key, value]` pairs,\n * in order from least recently used to most recently used.\n */\n *rentries() {\n for (const i of this.#rindexes()) {\n if (\n this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield [this.#keyList[i], this.#valList[i]]\n }\n }\n }\n\n /**\n * Return a generator yielding the keys in the cache,\n * in order from most recently used to least recently used.\n */\n *keys() {\n for (const i of this.#indexes()) {\n const k = this.#keyList[i]\n if (\n k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield k\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.keys}\n *\n * Return a generator yielding the keys in the cache,\n * in order from least recently used to most recently used.\n */\n *rkeys() {\n for (const i of this.#rindexes()) {\n const k = this.#keyList[i]\n if (\n k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield k\n }\n }\n }\n\n /**\n * Return a generator yielding the values in the cache,\n * in order from most recently used to least recently used.\n */\n *values() {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n if (\n v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield this.#valList[i] as V\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.values}\n *\n * Return a generator yielding the values in the cache,\n * in order from least recently used to most recently used.\n */\n *rvalues() {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i]\n if (\n v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield this.#valList[i]\n }\n }\n }\n\n /**\n * Iterating over the cache itself yields the same results as\n * {@link LRUCache.entries}\n */\n [Symbol.iterator]() {\n return this.entries()\n }\n\n /**\n * A String value that is used in the creation of the default string\n * description of an object. Called by the built-in method\n * `Object.prototype.toString`.\n */\n [Symbol.toStringTag] = 'LRUCache'\n\n /**\n * Find a value for which the supplied fn method returns a truthy value,\n * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n */\n find(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => boolean,\n getOptions: LRUCache.GetOptions<K, V, FC> = {}\n ) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n if (fn(value, this.#keyList[i] as K, this)) {\n return this.get(this.#keyList[i] as K, getOptions)\n }\n }\n }\n\n /**\n * Call the supplied function on each item in the cache, in order from most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or iterate over stale values.\n */\n forEach(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any,\n thisp: any = this\n ) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n fn.call(thisp, value, this.#keyList[i] as K, this)\n }\n }\n\n /**\n * The same as {@link LRUCache.forEach} but items are iterated over in\n * reverse order. (ie, less recently used items are iterated over first.)\n */\n rforEach(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any,\n thisp: any = this\n ) {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n fn.call(thisp, value, this.#keyList[i] as K, this)\n }\n }\n\n /**\n * Delete any stale entries. Returns true if anything was removed,\n * false otherwise.\n */\n purgeStale() {\n let deleted = false\n for (const i of this.#rindexes({ allowStale: true })) {\n if (this.#isStale(i)) {\n this.#delete(this.#keyList[i] as K, 'expire')\n deleted = true\n }\n }\n return deleted\n }\n\n /**\n * Get the extended info about a given entry, to get its value, size, and\n * TTL info simultaneously. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * if relevant.\n */\n info(key: K): LRUCache.Entry<V> | undefined {\n const i = this.#keyMap.get(key)\n if (i === undefined) return undefined\n const v = this.#valList[i]\n const value: V | undefined = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) return undefined\n const entry: LRUCache.Entry<V> = { value }\n if (this.#ttls && this.#starts) {\n const ttl = this.#ttls[i]\n const start = this.#starts[i]\n if (ttl && start) {\n const remain = ttl - (perf.now() - start)\n entry.ttl = remain\n entry.start = Date.now()\n }\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i]\n }\n return entry\n }\n\n /**\n * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n * passed to {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\n */\n dump() {\n const arr: [K, LRUCache.Entry<V>][] = []\n for (const i of this.#indexes({ allowStale: true })) {\n const key = this.#keyList[i]\n const v = this.#valList[i]\n const value: V | undefined = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined || key === undefined) continue\n const entry: LRUCache.Entry<V> = { value }\n if (this.#ttls && this.#starts) {\n entry.ttl = this.#ttls[i]\n // always dump the start relative to a portable timestamp\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = perf.now() - (this.#starts[i] as number)\n entry.start = Math.floor(Date.now() - age)\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i]\n }\n arr.unshift([key, entry])\n }\n return arr\n }\n\n /**\n * Reset the cache and load in the items in entries in the order listed.\n *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\n */\n load(arr: [K, LRUCache.Entry<V>][]) {\n this.clear()\n for (const [key, entry] of arr) {\n if (entry.start) {\n // entry.start is a portable timestamp, but we may be using\n // node's performance.now(), so calculate the offset, so that\n // we get the intended remaining TTL, no matter how long it's\n // been on ice.\n //\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = Date.now() - entry.start\n entry.start = perf.now() - age\n }\n this.set(key, entry.value, entry)\n }\n }\n\n /**\n * Add a value to the cache.\n *\n * Note: if `undefined` is specified as a value, this is an alias for\n * {@link LRUCache#delete}\n *\n * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\n */\n set(\n k: K,\n v: V | BackgroundFetch<V> | undefined,\n setOptions: LRUCache.SetOptions<K, V, FC> = {}\n ) {\n if (v === undefined) {\n this.delete(k)\n return this\n }\n const {\n ttl = this.ttl,\n start,\n noDisposeOnSet = this.noDisposeOnSet,\n sizeCalculation = this.sizeCalculation,\n status,\n } = setOptions\n let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n const size = this.#requireSize(\n k,\n v,\n setOptions.size || 0,\n sizeCalculation\n )\n // if the item doesn't fit, don't do anything\n // NB: maxEntrySize set to maxSize by default\n if (this.maxEntrySize && size > this.maxEntrySize) {\n if (status) {\n status.set = 'miss'\n status.maxEntrySizeExceeded = true\n }\n // have to delete, in case something is there already.\n this.#delete(k, 'set')\n return this\n }\n let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n if (index === undefined) {\n // addition\n index = (\n this.#size === 0\n ? this.#tail\n : this.#free.length !== 0\n ? this.#free.pop()\n : this.#size === this.#max\n ? this.#evict(false)\n : this.#size\n ) as Index\n this.#keyList[index] = k\n this.#valList[index] = v\n this.#keyMap.set(k, index)\n this.#next[this.#tail] = index\n this.#prev[index] = this.#tail\n this.#tail = index\n this.#size++\n this.#addItemSize(index, size, status)\n if (status) status.set = 'add'\n noUpdateTTL = false\n } else {\n // update\n this.#moveToTail(index)\n const oldVal = this.#valList[index] as V | BackgroundFetch<V>\n if (v !== oldVal) {\n if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n oldVal.__abortController.abort(new Error('replaced'))\n const { __staleWhileFetching: s } = oldVal\n if (s !== undefined && !noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(s as V, k, 'set')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([s as V, k, 'set'])\n }\n }\n } else if (!noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(oldVal as V, k, 'set')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([oldVal as V, k, 'set'])\n }\n }\n this.#removeItemSize(index)\n this.#addItemSize(index, size, status)\n this.#valList[index] = v\n if (status) {\n status.set = 'replace'\n const oldValue =\n oldVal && this.#isBackgroundFetch(oldVal)\n ? oldVal.__staleWhileFetching\n : oldVal\n if (oldValue !== undefined) status.oldValue = oldValue\n }\n } else if (status) {\n status.set = 'update'\n }\n }\n if (ttl !== 0 && !this.#ttls) {\n this.#initializeTTLTracking()\n }\n if (this.#ttls) {\n if (!noUpdateTTL) {\n this.#setItemTTL(index, ttl, start)\n }\n if (status) this.#statusTTL(status, index)\n }\n if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n return this\n }\n\n /**\n * Evict the least recently used item, returning its value or\n * `undefined` if cache is empty.\n */\n pop(): V | undefined {\n try {\n while (this.#size) {\n const val = this.#valList[this.#head]\n this.#evict(true)\n if (this.#isBackgroundFetch(val)) {\n if (val.__staleWhileFetching) {\n return val.__staleWhileFetching\n }\n } else if (val !== undefined) {\n return val\n }\n }\n } finally {\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n }\n }\n\n #evict(free: boolean) {\n const head = this.#head\n const k = this.#keyList[head] as K\n const v = this.#valList[head] as V\n if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('evicted'))\n } else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v, k, 'evict')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v, k, 'evict'])\n }\n }\n this.#removeItemSize(head)\n // if we aren't about to use the index, then null these out\n if (free) {\n this.#keyList[head] = undefined\n this.#valList[head] = undefined\n this.#free.push(head)\n }\n if (this.#size === 1) {\n this.#head = this.#tail = 0 as Index\n this.#free.length = 0\n } else {\n this.#head = this.#next[head] as Index\n }\n this.#keyMap.delete(k)\n this.#size--\n return head\n }\n\n /**\n * Check if a key is in the cache, without updating the recency of use.\n * Will return false if the item is stale, even though it is technically\n * in the cache.\n *\n * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\n *\n * Will not update item age unless\n * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n */\n has(k: K, hasOptions: LRUCache.HasOptions<K, V, FC> = {}) {\n const { updateAgeOnHas = this.updateAgeOnHas, status } =\n hasOptions\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n const v = this.#valList[index]\n if (\n this.#isBackgroundFetch(v) &&\n v.__staleWhileFetching === undefined\n ) {\n return false\n }\n if (!this.#isStale(index)) {\n if (updateAgeOnHas) {\n this.#updateItemAge(index)\n }\n if (status) {\n status.has = 'hit'\n this.#statusTTL(status, index)\n }\n return true\n } else if (status) {\n status.has = 'stale'\n this.#statusTTL(status, index)\n }\n } else if (status) {\n status.has = 'miss'\n }\n return false\n }\n\n /**\n * Like {@link LRUCache#get} but doesn't update recency or delete stale\n * items.\n *\n * Returns `undefined` if the item is stale, unless\n * {@link LRUCache.OptionsBase.allowStale} is set.\n */\n peek(k: K, peekOptions: LRUCache.PeekOptions<K, V, FC> = {}) {\n const { allowStale = this.allowStale } = peekOptions\n const index = this.#keyMap.get(k)\n if (\n index === undefined ||\n (!allowStale && this.#isStale(index))\n ) {\n return\n }\n const v = this.#valList[index]\n // either stale and allowed, or forcing a refresh of non-stale value\n return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n }\n\n #backgroundFetch(\n k: K,\n index: Index | undefined,\n options: LRUCache.FetchOptions<K, V, FC>,\n context: any\n ): BackgroundFetch<V> {\n const v = index === undefined ? undefined : this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n return v\n }\n\n const ac = new AC()\n const { signal } = options\n // when/if our AC signals, then stop listening to theirs.\n signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n signal: ac.signal,\n })\n\n const fetchOpts = {\n signal: ac.signal,\n options,\n context,\n }\n\n const cb = (\n v: V | undefined,\n updateCache = false\n ): V | undefined => {\n const { aborted } = ac.signal\n const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n if (options.status) {\n if (aborted && !updateCache) {\n options.status.fetchAborted = true\n options.status.fetchError = ac.signal.reason\n if (ignoreAbort) options.status.fetchAbortIgnored = true\n } else {\n options.status.fetchResolved = true\n }\n }\n if (aborted && !ignoreAbort && !updateCache) {\n return fetchFail(ac.signal.reason)\n }\n // either we didn't abort, and are still here, or we did, and ignored\n const bf = p as BackgroundFetch<V>\n if (this.#valList[index as Index] === p) {\n if (v === undefined) {\n if (bf.__staleWhileFetching) {\n this.#valList[index as Index] = bf.__staleWhileFetching\n } else {\n this.#delete(k, 'fetch')\n }\n } else {\n if (options.status) options.status.fetchUpdated = true\n this.set(k, v, fetchOpts.options)\n }\n }\n return v\n }\n\n const eb = (er: any) => {\n if (options.status) {\n options.status.fetchRejected = true\n options.status.fetchError = er\n }\n return fetchFail(er)\n }\n\n const fetchFail = (er: any): V | undefined => {\n const { aborted } = ac.signal\n const allowStaleAborted =\n aborted && options.allowStaleOnFetchAbort\n const allowStale =\n allowStaleAborted || options.allowStaleOnFetchRejection\n const noDelete = allowStale || options.noDeleteOnFetchRejection\n const bf = p as BackgroundFetch<V>\n if (this.#valList[index as Index] === p) {\n // if we allow stale on fetch rejections, then we need to ensure that\n // the stale value is not removed from the cache when the fetch fails.\n const del = !noDelete || bf.__staleWhileFetching === undefined\n if (del) {\n this.#delete(k, 'fetch')\n } else if (!allowStaleAborted) {\n // still replace the *promise* with the stale value,\n // since we are done with the promise at this point.\n // leave it untouched if we're still waiting for an\n // aborted background fetch that hasn't yet returned.\n this.#valList[index as Index] = bf.__staleWhileFetching\n }\n }\n if (allowStale) {\n if (options.status && bf.__staleWhileFetching !== undefined) {\n options.status.returnedStale = true\n }\n return bf.__staleWhileFetching\n } else if (bf.__returned === bf) {\n throw er\n }\n }\n\n const pcall = (\n res: (v: V | undefined) => void,\n rej: (e: any) => void\n ) => {\n const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n if (fmp && fmp instanceof Promise) {\n fmp.then(v => res(v === undefined ? undefined : v), rej)\n }\n // ignored, we go until we finish, regardless.\n // defer check until we are actually aborting,\n // so fetchMethod can override.\n ac.signal.addEventListener('abort', () => {\n if (\n !options.ignoreFetchAbort ||\n options.allowStaleOnFetchAbort\n ) {\n res(undefined)\n // when it eventually resolves, update the cache.\n if (options.allowStaleOnFetchAbort) {\n res = v => cb(v, true)\n }\n }\n })\n }\n\n if (options.status) options.status.fetchDispatched = true\n const p = new Promise(pcall).then(cb, eb)\n const bf: BackgroundFetch<V> = Object.assign(p, {\n __abortController: ac,\n __staleWhileFetching: v,\n __returned: undefined,\n })\n\n if (index === undefined) {\n // internal, don't expose status.\n this.set(k, bf, { ...fetchOpts.options, status: undefined })\n index = this.#keyMap.get(k)\n } else {\n this.#valList[index] = bf\n }\n return bf\n }\n\n #isBackgroundFetch(p: any): p is BackgroundFetch<V> {\n if (!this.#hasFetchMethod) return false\n const b = p as BackgroundFetch<V>\n return (\n !!b &&\n b instanceof Promise &&\n b.hasOwnProperty('__staleWhileFetching') &&\n b.__abortController instanceof AC\n )\n }\n\n /**\n * Make an asynchronous cached fetch using the\n * {@link LRUCache.OptionsBase.fetchMethod} function.\n *\n * If the value is in the cache and not stale, then the returned\n * Promise resolves to the value.\n *\n * If not in the cache, or beyond its TTL staleness, then\n * `fetchMethod(key, staleValue, { options, signal, context })` is\n * called, and the value returned will be added to the cache once\n * resolved.\n *\n * If called with `allowStale`, and an asynchronous fetch is\n * currently in progress to reload a stale value, then the former\n * stale value will be returned.\n *\n * If called with `forceRefresh`, then the cached item will be\n * re-fetched, even if it is not stale. However, if `allowStale` is also\n * set, then the old value will still be returned. This is useful\n * in cases where you want to force a reload of a cached value. If\n * a background fetch is already in progress, then `forceRefresh`\n * has no effect.\n *\n * If multiple fetches for the same key are issued, then they will all be\n * coalesced into a single call to fetchMethod.\n *\n * Note that this means that handling options such as\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n * {@link LRUCache.FetchOptions.signal},\n * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n * determined by the FIRST fetch() call for a given key.\n *\n * This is a known (fixable) shortcoming which will be addresed on when\n * someone complains about it, as the fix would involve added complexity and\n * may not be worth the costs for this edge case.\n *\n * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n * effectively an alias for `Promise.resolve(cache.get(key))`.\n *\n * When the fetch method resolves to a value, if the fetch has not\n * been aborted due to deletion, eviction, or being overwritten,\n * then it is added to the cache using the options provided.\n *\n * If the key is evicted or deleted before the `fetchMethod`\n * resolves, then the AbortSignal passed to the `fetchMethod` will\n * receive an `abort` event, and the promise returned by `fetch()`\n * will reject with the reason for the abort.\n *\n * If a `signal` is passed to the `fetch()` call, then aborting the\n * signal will abort the fetch and cause the `fetch()` promise to\n * reject with the reason provided.\n *\n * **Setting `context`**\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the {@link LRUCache} constructor, then all\n * calls to `cache.fetch()` _must_ provide a `context` option. If\n * set to `undefined` or `void`, then calls to fetch _must not_\n * provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that\n * might be relevant in the course of fetching the data. It is only\n * relevant for the course of a single `fetch()` operation, and\n * discarded afterwards.\n *\n * **Note: `fetch()` calls are inflight-unique**\n *\n * If you call `fetch()` multiple times with the same key value,\n * then every call after the first will resolve on the same\n * promise<sup>1</sup>,\n * _even if they have different settings that would otherwise change\n * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n * or `ignoreFetchAbort`.\n *\n * In most cases, this is not a problem (in fact, only fetching\n * something once is what you probably want, if you're caching in\n * the first place). If you are changing the fetch() options\n * dramatically between runs, there's a good chance that you might\n * be trying to fit divergent semantics into a single object, and\n * would be better off with multiple cache instances.\n *\n * **1**: Ie, they're not the \"same Promise\", but they resolve at\n * the same time, because they're both waiting on the same\n * underlying fetchMethod response.\n */\n\n fetch(\n k: K,\n fetchOptions: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n ): Promise<undefined | V>\n\n // this overload not allowed if context is required\n fetch(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n fetchOptions?: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : never\n ): Promise<undefined | V>\n\n async fetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions<K, V, FC> = {}\n ): Promise<undefined | V> {\n const {\n // get options\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n // set options\n ttl = this.ttl,\n noDisposeOnSet = this.noDisposeOnSet,\n size = 0,\n sizeCalculation = this.sizeCalculation,\n noUpdateTTL = this.noUpdateTTL,\n // fetch exclusive options\n noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n ignoreFetchAbort = this.ignoreFetchAbort,\n allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n context,\n forceRefresh = false,\n status,\n signal,\n } = fetchOptions\n\n if (!this.#hasFetchMethod) {\n if (status) status.fetch = 'get'\n return this.get(k, {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n status,\n })\n }\n\n const options = {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n ttl,\n noDisposeOnSet,\n size,\n sizeCalculation,\n noUpdateTTL,\n noDeleteOnFetchRejection,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n status,\n signal,\n }\n\n let index = this.#keyMap.get(k)\n if (index === undefined) {\n if (status) status.fetch = 'miss'\n const p = this.#backgroundFetch(k, index, options, context)\n return (p.__returned = p)\n } else {\n // in cache, maybe already fetching\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n const stale =\n allowStale && v.__staleWhileFetching !== undefined\n if (status) {\n status.fetch = 'inflight'\n if (stale) status.returnedStale = true\n }\n return stale ? v.__staleWhileFetching : (v.__returned = v)\n }\n\n // if we force a refresh, that means do NOT serve the cached value,\n // unless we are already in the process of refreshing the cache.\n const isStale = this.#isStale(index)\n if (!forceRefresh && !isStale) {\n if (status) status.fetch = 'hit'\n this.#moveToTail(index)\n if (updateAgeOnGet) {\n this.#updateItemAge(index)\n }\n if (status) this.#statusTTL(status, index)\n return v\n }\n\n // ok, it is stale or a forced refresh, and not already fetching.\n // refresh the cache.\n const p = this.#backgroundFetch(k, index, options, context)\n const hasStale = p.__staleWhileFetching !== undefined\n const staleVal = hasStale && allowStale\n if (status) {\n status.fetch = isStale ? 'stale' : 'refresh'\n if (staleVal && isStale) status.returnedStale = true\n }\n return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n }\n }\n\n /**\n * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n * because `ignoreFetchAbort` was specified (either to the constructor or\n * in the {@link LRUCache.FetchOptions}). Also, the\n * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n * the test even more complicated.\n *\n * Because inferring the cases where `undefined` might be returned are so\n * cumbersome, but testing for `undefined` can also be annoying, this method\n * can be used, which will reject if `this.fetch()` resolves to undefined.\n */\n forceFetch(\n k: K,\n fetchOptions: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n ): Promise<V>\n // this overload not allowed if context is required\n forceFetch(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n fetchOptions?: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : never\n ): Promise<V>\n async forceFetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions<K, V, FC> = {}\n ): Promise<V> {\n const v = await this.fetch(\n k,\n fetchOptions as unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n )\n if (v === undefined) throw new Error('fetch() returned undefined')\n return v\n }\n\n /**\n * If the key is found in the cache, then this is equivalent to\n * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n * _must_ provide a `context` option. If set to `undefined` or `void`, then\n * calls to memo _must not_ provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that might be\n * relevant in the course of fetching the data. It is only relevant for the\n * course of a single `memo()` operation, and discarded afterwards.\n */\n memo(\n k: K,\n memoOptions: unknown extends FC\n ? LRUCache.MemoOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext<K, V>\n : LRUCache.MemoOptionsWithContext<K, V, FC>\n ): V\n // this overload not allowed if context is required\n memo(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n memoOptions?: unknown extends FC\n ? LRUCache.MemoOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext<K, V>\n : never\n ): V\n memo(k: K, memoOptions: LRUCache.MemoOptions<K, V, FC> = {}) {\n const memoMethod = this.#memoMethod\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor')\n }\n const { context, forceRefresh, ...options } = memoOptions\n const v = this.get(k, options)\n if (!forceRefresh && v !== undefined) return v\n const vv = memoMethod(k, v, {\n options,\n context,\n } as LRUCache.MemoizerOptions<K, V, FC>)\n this.set(k, vv, options)\n return vv\n }\n\n /**\n * Return a value from the cache. Will update the recency of the cache\n * entry found.\n *\n * If the key is not found, get() will return `undefined`.\n */\n get(k: K, getOptions: LRUCache.GetOptions<K, V, FC> = {}) {\n const {\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n status,\n } = getOptions\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n const value = this.#valList[index]\n const fetching = this.#isBackgroundFetch(value)\n if (status) this.#statusTTL(status, index)\n if (this.#isStale(index)) {\n if (status) status.get = 'stale'\n // delete only if not an in-flight background fetch\n if (!fetching) {\n if (!noDeleteOnStaleGet) {\n this.#delete(k, 'expire')\n }\n if (status && allowStale) status.returnedStale = true\n return allowStale ? value : undefined\n } else {\n if (\n status &&\n allowStale &&\n value.__staleWhileFetching !== undefined\n ) {\n status.returnedStale = true\n }\n return allowStale ? value.__staleWhileFetching : undefined\n }\n } else {\n if (status) status.get = 'hit'\n // if we're currently fetching it, we don't actually have it yet\n // it's not stale, which means this isn't a staleWhileRefetching.\n // If it's not stale, and fetching, AND has a __staleWhileFetching\n // value, then that means the user fetched with {forceRefresh:true},\n // so it's safe to return that value.\n if (fetching) {\n return value.__staleWhileFetching\n }\n this.#moveToTail(index)\n if (updateAgeOnGet) {\n this.#updateItemAge(index)\n }\n return value\n }\n } else if (status) {\n status.get = 'miss'\n }\n }\n\n #connect(p: Index, n: Index) {\n this.#prev[n] = p\n this.#next[p] = n\n }\n\n #moveToTail(index: Index): void {\n // if tail already, nothing to do\n // if head, move head to next[index]\n // else\n // move next[prev[index]] to next[index] (head has no prev)\n // move prev[next[index]] to prev[index]\n // prev[index] = tail\n // next[tail] = index\n // tail = index\n if (index !== this.#tail) {\n if (index === this.#head) {\n this.#head = this.#next[index] as Index\n } else {\n this.#connect(\n this.#prev[index] as Index,\n this.#next[index] as Index\n )\n }\n this.#connect(this.#tail, index)\n this.#tail = index\n }\n }\n\n /**\n * Deletes a key out of the cache.\n *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k: K) {\n return this.#delete(k, 'delete')\n }\n\n #delete(k: K, reason: LRUCache.DisposeReason) {\n let deleted = false\n if (this.#size !== 0) {\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n deleted = true\n if (this.#size === 1) {\n this.#clear(reason)\n } else {\n this.#removeItemSize(index)\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'))\n } else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v as V, k, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k, reason])\n }\n }\n this.#keyMap.delete(k)\n this.#keyList[index] = undefined\n this.#valList[index] = undefined\n if (index === this.#tail) {\n this.#tail = this.#prev[index] as Index\n } else if (index === this.#head) {\n this.#head = this.#next[index] as Index\n } else {\n const pi = this.#prev[index] as number\n this.#next[pi] = this.#next[index] as number\n const ni = this.#next[index] as number\n this.#prev[ni] = this.#prev[index] as number\n }\n this.#size--\n this.#free.push(index)\n }\n }\n }\n if (this.#hasDisposeAfter && this.#disposed?.length) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n return deleted\n }\n\n /**\n * Clear the cache entirely, throwing away all values.\n */\n clear() {\n return this.#clear('delete')\n }\n #clear(reason: LRUCache.DisposeReason) {\n for (const index of this.#rindexes({ allowStale: true })) {\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'))\n } else {\n const k = this.#keyList[index]\n if (this.#hasDispose) {\n this.#dispose?.(v as V, k as K, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k as K, reason])\n }\n }\n }\n\n this.#keyMap.clear()\n this.#valList.fill(undefined)\n this.#keyList.fill(undefined)\n if (this.#ttls && this.#starts) {\n this.#ttls.fill(0)\n this.#starts.fill(0)\n }\n if (this.#sizes) {\n this.#sizes.fill(0)\n }\n this.#head = 0 as Index\n this.#tail = 0 as Index\n this.#free.length = 0\n this.#calculatedSize = 0\n this.#size = 0\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n }\n}\n","import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n lstatSync,\n readdir as readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods. Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n * readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n * - lstat\n * - readdir (Dirent variant only)\n * - readlink\n * - realpath\n */\nexport interface FSOption {\n lstatSync?: (path: string) => Stats\n readdir?: (\n path: string,\n options: { withFileTypes: true },\n cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n ) => void\n readdirSync?: (\n path: string,\n options: { withFileTypes: true },\n ) => Dirent[]\n readlinkSync?: (path: string) => string\n realpathSync?: (path: string) => string\n promises?: {\n lstat?: (path: string) => Promise<Stats>\n readdir?: (\n path: string,\n options: { withFileTypes: true },\n ) => Promise<Dirent[]>\n readlink?: (path: string) => Promise<string>\n realpath?: (path: string) => Promise<string>\n [k: string]: any\n }\n [k: string]: any\n}\n\ninterface FSValue {\n lstatSync: (path: string) => Stats\n readdir: (\n path: string,\n options: { withFileTypes: true },\n cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n ) => void\n readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n readlinkSync: (path: string) => string\n realpathSync: (path: string) => string\n promises: {\n lstat: (path: string) => Promise<Stats>\n readdir: (\n path: string,\n options: { withFileTypes: true },\n ) => Promise<Dirent[]>\n readlink: (path: string) => Promise<string>\n realpath: (path: string) => Promise<string>\n [k: string]: any\n }\n [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n lstatSync,\n readdir: readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync,\n promises: {\n lstat,\n readdir,\n readlink,\n realpath,\n },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n defaultFS\n : {\n ...defaultFS,\n ...fsOption,\n promises: {\n ...defaultFS.promises,\n ...(fsOption.promises || {}),\n },\n }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n | 'Unknown'\n | 'FIFO'\n | 'CharacterDevice'\n | 'Directory'\n | 'BlockDevice'\n | 'File'\n | 'SymbolicLink'\n | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n s.isFile() ? IFREG\n : s.isDirectory() ? IFDIR\n : s.isSymbolicLink() ? IFLNK\n : s.isCharacterDevice() ? IFCHR\n : s.isBlockDevice() ? IFBLK\n : s.isSocket() ? IFSOCK\n : s.isFIFO() ? IFIFO\n : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new Map<string, string>()\nconst normalize = (s: string) => {\n const c = normalizeCache.get(s)\n if (c) return c\n const n = s.normalize('NFKD')\n normalizeCache.set(s, n)\n return n\n}\n\nconst normalizeNocaseCache = new Map<string, string>()\nconst normalizeNocase = (s: string) => {\n const c = normalizeNocaseCache.get(s)\n if (c) return c\n const n = normalize(s.toLowerCase())\n normalizeNocaseCache.set(s, n)\n return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n fullpath?: string\n relative?: string\n relativePosix?: string\n parent?: PathBase\n /**\n * See {@link FSOption}\n */\n fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache<string, string> {\n constructor() {\n super({ max: 256 })\n }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent. At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache. This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache<PathBase, Children> {\n constructor(maxSize: number = 16 * 1024) {\n super({\n maxSize,\n // parent + children\n sizeCalculation: a => a.length + 1,\n })\n }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n /**\n * the basename of this path\n *\n * **Important**: *always* test the path name against any test string\n * usingthe {@link isNamed} method, and not by directly comparing this\n * string. Otherwise, unicode path strings that the system sees as identical\n * will not be properly treated as the same path, leading to incorrect\n * behavior and possible security issues.\n */\n name: string\n /**\n * the Path entry corresponding to the path root.\n *\n * @internal\n */\n root: PathBase\n /**\n * All roots found within the current PathScurry family\n *\n * @internal\n */\n roots: { [k: string]: PathBase }\n /**\n * a reference to the parent path, or undefined in the case of root entries\n *\n * @internal\n */\n parent?: PathBase\n /**\n * boolean indicating whether paths are compared case-insensitively\n * @internal\n */\n nocase: boolean\n\n /**\n * boolean indicating that this path is the current working directory\n * of the PathScurry collection that contains it.\n */\n isCWD: boolean = false\n\n /**\n * the string or regexp used to split paths. On posix, it is `'/'`, and on\n * windows it is a RegExp matching either `'/'` or `'\\\\'`\n */\n abstract splitSep: string | RegExp\n /**\n * The path separator string to use when joining paths\n */\n abstract sep: string\n\n // potential default fs override\n #fs: FSValue\n\n // Stats fields\n #dev?: number\n get dev() {\n return this.#dev\n }\n #mode?: number\n get mode() {\n return this.#mode\n }\n #nlink?: number\n get nlink() {\n return this.#nlink\n }\n #uid?: number\n get uid() {\n return this.#uid\n }\n #gid?: number\n get gid() {\n return this.#gid\n }\n #rdev?: number\n get rdev() {\n return this.#rdev\n }\n #blksize?: number\n get blksize() {\n return this.#blksize\n }\n #ino?: number\n get ino() {\n return this.#ino\n }\n #size?: number\n get size() {\n return this.#size\n }\n #blocks?: number\n get blocks() {\n return this.#blocks\n }\n #atimeMs?: number\n get atimeMs() {\n return this.#atimeMs\n }\n #mtimeMs?: number\n get mtimeMs() {\n return this.#mtimeMs\n }\n #ctimeMs?: number\n get ctimeMs() {\n return this.#ctimeMs\n }\n #birthtimeMs?: number\n get birthtimeMs() {\n return this.#birthtimeMs\n }\n #atime?: Date\n get atime() {\n return this.#atime\n }\n #mtime?: Date\n get mtime() {\n return this.#mtime\n }\n #ctime?: Date\n get ctime() {\n return this.#ctime\n }\n #birthtime?: Date\n get birthtime() {\n return this.#birthtime\n }\n\n #matchName: string\n #depth?: number\n #fullpath?: string\n #fullpathPosix?: string\n #relative?: string\n #relativePosix?: string\n #type: number\n #children: ChildrenCache\n #linkTarget?: PathBase\n #realpath?: PathBase\n\n /**\n * This property is for compatibility with the Dirent class as of\n * Node v20, where Dirent['parentPath'] refers to the path of the\n * directory that was passed to readdir. For root entries, it's the path\n * to the entry itself.\n */\n get parentPath(): string {\n return (this.parent || this).fullpath()\n }\n\n /**\n * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n * this property refers to the *parent* path, not the path object itself.\n */\n get path(): string {\n return this.parentPath\n }\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n this.name = name\n this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n this.#type = type & TYPEMASK\n this.nocase = nocase\n this.roots = roots\n this.root = root || this\n this.#children = children\n this.#fullpath = opts.fullpath\n this.#relative = opts.relative\n this.#relativePosix = opts.relativePosix\n this.parent = opts.parent\n if (this.parent) {\n this.#fs = this.parent.#fs\n } else {\n this.#fs = fsFromOption(opts.fs)\n }\n }\n\n /**\n * Returns the depth of the Path object from its root.\n *\n * For example, a path at `/foo/bar` would have a depth of 2.\n */\n depth(): number {\n if (this.#depth !== undefined) return this.#depth\n if (!this.parent) return (this.#depth = 0)\n return (this.#depth = this.parent.depth() + 1)\n }\n\n /**\n * @internal\n */\n abstract getRootString(path: string): string\n /**\n * @internal\n */\n abstract getRoot(rootPath: string): PathBase\n /**\n * @internal\n */\n abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n /**\n * @internal\n */\n childrenCache() {\n return this.#children\n }\n\n /**\n * Get the Path object referenced by the string path, resolved from this Path\n */\n resolve(path?: string): PathBase {\n if (!path) {\n return this\n }\n const rootPath = this.getRootString(path)\n const dir = path.substring(rootPath.length)\n const dirParts = dir.split(this.splitSep)\n const result: PathBase =\n rootPath ?\n this.getRoot(rootPath).#resolveParts(dirParts)\n : this.#resolveParts(dirParts)\n return result\n }\n\n #resolveParts(dirParts: string[]) {\n let p: PathBase = this\n for (const part of dirParts) {\n p = p.child(part)\n }\n return p\n }\n\n /**\n * Returns the cached children Path objects, if still available. If they\n * have fallen out of the cache, then returns an empty array, and resets the\n * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n * lookup.\n *\n * @internal\n */\n children(): Children {\n const cached = this.#children.get(this)\n if (cached) {\n return cached\n }\n const children: Children = Object.assign([], { provisional: 0 })\n this.#children.set(this, children)\n this.#type &= ~READDIR_CALLED\n return children\n }\n\n /**\n * Resolves a path portion and returns or creates the child Path.\n *\n * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n * `'..'`.\n *\n * This should not be called directly. If `pathPart` contains any path\n * separators, it will lead to unsafe undefined behavior.\n *\n * Use `Path.resolve()` instead.\n *\n * @internal\n */\n child(pathPart: string, opts?: PathOpts): PathBase {\n if (pathPart === '' || pathPart === '.') {\n return this\n }\n if (pathPart === '..') {\n return this.parent || this\n }\n\n // find the child\n const children = this.children()\n const name =\n this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n for (const p of children) {\n if (p.#matchName === name) {\n return p\n }\n }\n\n // didn't find it, create provisional child, since it might not\n // actually exist. If we know the parent isn't a dir, then\n // in fact it CAN'T exist.\n const s = this.parent ? this.sep : ''\n const fullpath =\n this.#fullpath ? this.#fullpath + s + pathPart : undefined\n const pchild = this.newChild(pathPart, UNKNOWN, {\n ...opts,\n parent: this,\n fullpath,\n })\n\n if (!this.canReaddir()) {\n pchild.#type |= ENOENT\n }\n\n // don't have to update provisional, because if we have real children,\n // then provisional is set to children.length, otherwise a lower number\n children.push(pchild)\n return pchild\n }\n\n /**\n * The relative path from the cwd. If it does not share an ancestor with\n * the cwd, then this ends up being equivalent to the fullpath()\n */\n relative(): string {\n if (this.isCWD) return ''\n if (this.#relative !== undefined) {\n return this.#relative\n }\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#relative = this.name)\n }\n const pv = p.relative()\n return pv + (!pv || !p.parent ? '' : this.sep) + name\n }\n\n /**\n * The relative path from the cwd, using / as the path separator.\n * If it does not share an ancestor with\n * the cwd, then this ends up being equivalent to the fullpathPosix()\n * On posix systems, this is identical to relative().\n */\n relativePosix(): string {\n if (this.sep === '/') return this.relative()\n if (this.isCWD) return ''\n if (this.#relativePosix !== undefined) return this.#relativePosix\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#relativePosix = this.fullpathPosix())\n }\n const pv = p.relativePosix()\n return pv + (!pv || !p.parent ? '' : '/') + name\n }\n\n /**\n * The fully resolved path string for this Path entry\n */\n fullpath(): string {\n if (this.#fullpath !== undefined) {\n return this.#fullpath\n }\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#fullpath = this.name)\n }\n const pv = p.fullpath()\n const fp = pv + (!p.parent ? '' : this.sep) + name\n return (this.#fullpath = fp)\n }\n\n /**\n * On platforms other than windows, this is identical to fullpath.\n *\n * On windows, this is overridden to return the forward-slash form of the\n * full UNC path.\n */\n fullpathPosix(): string {\n if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n if (!this.parent) {\n const p = this.fullpath().replace(/\\\\/g, '/')\n if (/^[a-z]:\\//i.test(p)) {\n return (this.#fullpathPosix = `//?/${p}`)\n } else {\n return (this.#fullpathPosix = p)\n }\n }\n const p = this.parent\n const pfpp = p.fullpathPosix()\n const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n return (this.#fullpathPosix = fpp)\n }\n\n /**\n * Is the Path of an unknown type?\n *\n * Note that we might know *something* about it if there has been a previous\n * filesystem operation, for example that it does not exist, or is not a\n * link, or whether it has child entries.\n */\n isUnknown(): boolean {\n return (this.#type & IFMT) === UNKNOWN\n }\n\n isType(type: Type): boolean {\n return this[`is${type}`]()\n }\n\n getType(): Type {\n return (\n this.isUnknown() ? 'Unknown'\n : this.isDirectory() ? 'Directory'\n : this.isFile() ? 'File'\n : this.isSymbolicLink() ? 'SymbolicLink'\n : this.isFIFO() ? 'FIFO'\n : this.isCharacterDevice() ? 'CharacterDevice'\n : this.isBlockDevice() ? 'BlockDevice'\n : /* c8 ignore start */ this.isSocket() ? 'Socket'\n : 'Unknown'\n )\n /* c8 ignore stop */\n }\n\n /**\n * Is the Path a regular file?\n */\n isFile(): boolean {\n return (this.#type & IFMT) === IFREG\n }\n\n /**\n * Is the Path a directory?\n */\n isDirectory(): boolean {\n return (this.#type & IFMT) === IFDIR\n }\n\n /**\n * Is the path a character device?\n */\n isCharacterDevice(): boolean {\n return (this.#type & IFMT) === IFCHR\n }\n\n /**\n * Is the path a block device?\n */\n isBlockDevice(): boolean {\n return (this.#type & IFMT) === IFBLK\n }\n\n /**\n * Is the path a FIFO pipe?\n */\n isFIFO(): boolean {\n return (this.#type & IFMT) === IFIFO\n }\n\n /**\n * Is the path a socket?\n */\n isSocket(): boolean {\n return (this.#type & IFMT) === IFSOCK\n }\n\n /**\n * Is the path a symbolic link?\n */\n isSymbolicLink(): boolean {\n return (this.#type & IFLNK) === IFLNK\n }\n\n /**\n * Return the entry if it has been subject of a successful lstat, or\n * undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* simply\n * mean that we haven't called lstat on it.\n */\n lstatCached(): PathBase | undefined {\n return this.#type & LSTAT_CALLED ? this : undefined\n }\n\n /**\n * Return the cached link target if the entry has been the subject of a\n * successful readlink, or undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * readlink() has been called at some point.\n */\n readlinkCached(): PathBase | undefined {\n return this.#linkTarget\n }\n\n /**\n * Returns the cached realpath target if the entry has been the subject\n * of a successful realpath, or undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * realpath() has been called at some point.\n */\n realpathCached(): PathBase | undefined {\n return this.#realpath\n }\n\n /**\n * Returns the cached child Path entries array if the entry has been the\n * subject of a successful readdir(), or [] otherwise.\n *\n * Does not read the filesystem, so an empty array *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * readdir() has been called recently enough to still be valid.\n */\n readdirCached(): PathBase[] {\n const children = this.children()\n return children.slice(0, children.provisional)\n }\n\n /**\n * Return true if it's worth trying to readlink. Ie, we don't (yet) have\n * any indication that readlink will definitely fail.\n *\n * Returns false if the path is known to not be a symlink, if a previous\n * readlink failed, or if the entry does not exist.\n */\n canReadlink(): boolean {\n if (this.#linkTarget) return true\n if (!this.parent) return false\n // cases where it cannot possibly succeed\n const ifmt = this.#type & IFMT\n return !(\n (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n this.#type & ENOREADLINK ||\n this.#type & ENOENT\n )\n }\n\n /**\n * Return true if readdir has previously been successfully called on this\n * path, indicating that cachedReaddir() is likely valid.\n */\n calledReaddir(): boolean {\n return !!(this.#type & READDIR_CALLED)\n }\n\n /**\n * Returns true if the path is known to not exist. That is, a previous lstat\n * or readdir failed to verify its existence when that would have been\n * expected, or a parent entry was marked either enoent or enotdir.\n */\n isENOENT(): boolean {\n return !!(this.#type & ENOENT)\n }\n\n /**\n * Return true if the path is a match for the given path name. This handles\n * case sensitivity and unicode normalization.\n *\n * Note: even on case-sensitive systems, it is **not** safe to test the\n * equality of the `.name` property to determine whether a given pathname\n * matches, due to unicode normalization mismatches.\n *\n * Always use this method instead of testing the `path.name` property\n * directly.\n */\n isNamed(n: string): boolean {\n return !this.nocase ?\n this.#matchName === normalize(n)\n : this.#matchName === normalizeNocase(n)\n }\n\n /**\n * Return the Path object corresponding to the target of a symbolic link.\n *\n * If the Path is not a symbolic link, or if the readlink call fails for any\n * reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n */\n async readlink(): Promise<PathBase | undefined> {\n const target = this.#linkTarget\n if (target) {\n return target\n }\n if (!this.canReadlink()) {\n return undefined\n }\n /* c8 ignore start */\n // already covered by the canReadlink test, here for ts grumples\n if (!this.parent) {\n return undefined\n }\n /* c8 ignore stop */\n try {\n const read = await this.#fs.promises.readlink(this.fullpath())\n const linkTarget = (await this.parent.realpath())?.resolve(read)\n if (linkTarget) {\n return (this.#linkTarget = linkTarget)\n }\n } catch (er) {\n this.#readlinkFail((er as NodeJS.ErrnoException).code)\n return undefined\n }\n }\n\n /**\n * Synchronous {@link PathBase.readlink}\n */\n readlinkSync(): PathBase | undefined {\n const target = this.#linkTarget\n if (target) {\n return target\n }\n if (!this.canReadlink()) {\n return undefined\n }\n /* c8 ignore start */\n // already covered by the canReadlink test, here for ts grumples\n if (!this.parent) {\n return undefined\n }\n /* c8 ignore stop */\n try {\n const read = this.#fs.readlinkSync(this.fullpath())\n const linkTarget = this.parent.realpathSync()?.resolve(read)\n if (linkTarget) {\n return (this.#linkTarget = linkTarget)\n }\n } catch (er) {\n this.#readlinkFail((er as NodeJS.ErrnoException).code)\n return undefined\n }\n }\n\n #readdirSuccess(children: Children) {\n // succeeded, mark readdir called bit\n this.#type |= READDIR_CALLED\n // mark all remaining provisional children as ENOENT\n for (let p = children.provisional; p < children.length; p++) {\n const c = children[p]\n if (c) c.#markENOENT()\n }\n }\n\n #markENOENT() {\n // mark as UNKNOWN and ENOENT\n if (this.#type & ENOENT) return\n this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n this.#markChildrenENOENT()\n }\n\n #markChildrenENOENT() {\n // all children are provisional and do not exist\n const children = this.children()\n children.provisional = 0\n for (const p of children) {\n p.#markENOENT()\n }\n }\n\n #markENOREALPATH() {\n this.#type |= ENOREALPATH\n this.#markENOTDIR()\n }\n\n // save the information when we know the entry is not a dir\n #markENOTDIR() {\n // entry is not a directory, so any children can't exist.\n // this *should* be impossible, since any children created\n // after it's been marked ENOTDIR should be marked ENOENT,\n // so it won't even get to this point.\n /* c8 ignore start */\n if (this.#type & ENOTDIR) return\n /* c8 ignore stop */\n let t = this.#type\n // this could happen if we stat a dir, then delete it,\n // then try to read it or one of its children.\n if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n this.#type = t | ENOTDIR\n this.#markChildrenENOENT()\n }\n\n #readdirFail(code: string = '') {\n // markENOTDIR and markENOENT also set provisional=0\n if (code === 'ENOTDIR' || code === 'EPERM') {\n this.#markENOTDIR()\n } else if (code === 'ENOENT') {\n this.#markENOENT()\n } else {\n this.children().provisional = 0\n }\n }\n\n #lstatFail(code: string = '') {\n // Windows just raises ENOENT in this case, disable for win CI\n /* c8 ignore start */\n if (code === 'ENOTDIR') {\n // already know it has a parent by this point\n const p = this.parent as PathBase\n p.#markENOTDIR()\n } else if (code === 'ENOENT') {\n /* c8 ignore stop */\n this.#markENOENT()\n }\n }\n\n #readlinkFail(code: string = '') {\n let ter = this.#type\n ter |= ENOREADLINK\n if (code === 'ENOENT') ter |= ENOENT\n // windows gets a weird error when you try to readlink a file\n if (code === 'EINVAL' || code === 'UNKNOWN') {\n // exists, but not a symlink, we don't know WHAT it is, so remove\n // all IFMT bits.\n ter &= IFMT_UNKNOWN\n }\n this.#type = ter\n // windows just gets ENOENT in this case. We do cover the case,\n // just disabled because it's impossible on Windows CI\n /* c8 ignore start */\n if (code === 'ENOTDIR' && this.parent) {\n this.parent.#markENOTDIR()\n }\n /* c8 ignore stop */\n }\n\n #readdirAddChild(e: Dirent, c: Children) {\n return (\n this.#readdirMaybePromoteChild(e, c) ||\n this.#readdirAddNewChild(e, c)\n )\n }\n\n #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n // alloc new entry at head, so it's never provisional\n const type = entToType(e)\n const child = this.newChild(e.name, type, { parent: this })\n const ifmt = child.#type & IFMT\n if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n child.#type |= ENOTDIR\n }\n c.unshift(child)\n c.provisional++\n return child\n }\n\n #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n for (let p = c.provisional; p < c.length; p++) {\n const pchild = c[p]\n const name =\n this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n if (name !== pchild!.#matchName) {\n continue\n }\n\n return this.#readdirPromoteChild(e, pchild!, p, c)\n }\n }\n\n #readdirPromoteChild(\n e: Dirent,\n p: PathBase,\n index: number,\n c: Children,\n ): PathBase {\n const v = p.name\n // retain any other flags, but set ifmt from dirent\n p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n // case sensitivity fixing when we learn the true name.\n if (v !== e.name) p.name = e.name\n\n // just advance provisional index (potentially off the list),\n // otherwise we have to splice/pop it out and re-insert at head\n if (index !== c.provisional) {\n if (index === c.length - 1) c.pop()\n else c.splice(index, 1)\n c.unshift(p)\n }\n c.provisional++\n return p\n }\n\n /**\n * Call lstat() on this Path, and update all known information that can be\n * determined.\n *\n * Note that unlike `fs.lstat()`, the returned value does not contain some\n * information, such as `mode`, `dev`, `nlink`, and `ino`. If that\n * information is required, you will need to call `fs.lstat` yourself.\n *\n * If the Path refers to a nonexistent file, or if the lstat call fails for\n * any reason, `undefined` is returned. Otherwise the updated Path object is\n * returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async lstat(): Promise<PathBase | undefined> {\n if ((this.#type & ENOENT) === 0) {\n try {\n this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n return this\n } catch (er) {\n this.#lstatFail((er as NodeJS.ErrnoException).code)\n }\n }\n }\n\n /**\n * synchronous {@link PathBase.lstat}\n */\n lstatSync(): PathBase | undefined {\n if ((this.#type & ENOENT) === 0) {\n try {\n this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n return this\n } catch (er) {\n this.#lstatFail((er as NodeJS.ErrnoException).code)\n }\n }\n }\n\n #applyStat(st: Stats) {\n const {\n atime,\n atimeMs,\n birthtime,\n birthtimeMs,\n blksize,\n blocks,\n ctime,\n ctimeMs,\n dev,\n gid,\n ino,\n mode,\n mtime,\n mtimeMs,\n nlink,\n rdev,\n size,\n uid,\n } = st\n this.#atime = atime\n this.#atimeMs = atimeMs\n this.#birthtime = birthtime\n this.#birthtimeMs = birthtimeMs\n this.#blksize = blksize\n this.#blocks = blocks\n this.#ctime = ctime\n this.#ctimeMs = ctimeMs\n this.#dev = dev\n this.#gid = gid\n this.#ino = ino\n this.#mode = mode\n this.#mtime = mtime\n this.#mtimeMs = mtimeMs\n this.#nlink = nlink\n this.#rdev = rdev\n this.#size = size\n this.#uid = uid\n const ifmt = entToType(st)\n // retain any other flags, but set the ifmt\n this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n this.#type |= ENOTDIR\n }\n }\n\n #onReaddirCB: ((\n er: NodeJS.ErrnoException | null,\n entries: Path[],\n ) => any)[] = []\n #readdirCBInFlight: boolean = false\n #callOnReaddirCB(children: Path[]) {\n this.#readdirCBInFlight = false\n const cbs = this.#onReaddirCB.slice()\n this.#onReaddirCB.length = 0\n cbs.forEach(cb => cb(null, children))\n }\n\n /**\n * Standard node-style callback interface to get list of directory entries.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n *\n * @param cb The callback called with (er, entries). Note that the `er`\n * param is somewhat extraneous, as all readdir() errors are handled and\n * simply result in an empty set of entries being returned.\n * @param allowZalgo Boolean indicating that immediately known results should\n * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n * zalgo at your peril, the dark pony lord is devious and unforgiving.\n */\n readdirCB(\n cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n allowZalgo: boolean = false,\n ): void {\n if (!this.canReaddir()) {\n if (allowZalgo) cb(null, [])\n else queueMicrotask(() => cb(null, []))\n return\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n const c = children.slice(0, children.provisional)\n if (allowZalgo) cb(null, c)\n else queueMicrotask(() => cb(null, c))\n return\n }\n\n // don't have to worry about zalgo at this point.\n this.#onReaddirCB.push(cb)\n if (this.#readdirCBInFlight) {\n return\n }\n this.#readdirCBInFlight = true\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n if (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n } else {\n // if we didn't get an error, we always get entries.\n //@ts-ignore\n for (const e of entries) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n }\n this.#callOnReaddirCB(children.slice(0, children.provisional))\n return\n })\n }\n\n #asyncReaddirInFlight?: Promise<void>\n\n /**\n * Return an array of known child entries.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async readdir(): Promise<PathBase[]> {\n if (!this.canReaddir()) {\n return []\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n return children.slice(0, children.provisional)\n }\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n if (this.#asyncReaddirInFlight) {\n await this.#asyncReaddirInFlight\n } else {\n /* c8 ignore start */\n let resolve: () => void = () => {}\n /* c8 ignore stop */\n this.#asyncReaddirInFlight = new Promise<void>(\n res => (resolve = res),\n )\n try {\n for (const e of await this.#fs.promises.readdir(fullpath, {\n withFileTypes: true,\n })) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n } catch (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n }\n this.#asyncReaddirInFlight = undefined\n resolve()\n }\n return children.slice(0, children.provisional)\n }\n\n /**\n * synchronous {@link PathBase.readdir}\n */\n readdirSync(): PathBase[] {\n if (!this.canReaddir()) {\n return []\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n return children.slice(0, children.provisional)\n }\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n try {\n for (const e of this.#fs.readdirSync(fullpath, {\n withFileTypes: true,\n })) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n } catch (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n }\n return children.slice(0, children.provisional)\n }\n\n canReaddir() {\n if (this.#type & ENOCHILD) return false\n const ifmt = IFMT & this.#type\n // we always set ENOTDIR when setting IFMT, so should be impossible\n /* c8 ignore start */\n if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n return false\n }\n /* c8 ignore stop */\n return true\n }\n\n shouldWalk(\n dirs: Set<PathBase | undefined>,\n walkFilter?: (e: PathBase) => boolean,\n ): boolean {\n return (\n (this.#type & IFDIR) === IFDIR &&\n !(this.#type & ENOCHILD) &&\n !dirs.has(this) &&\n (!walkFilter || walkFilter(this))\n )\n }\n\n /**\n * Return the Path object corresponding to path as resolved\n * by realpath(3).\n *\n * If the realpath call fails for any reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n * On success, returns a Path object.\n */\n async realpath(): Promise<PathBase | undefined> {\n if (this.#realpath) return this.#realpath\n if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n try {\n const rp = await this.#fs.promises.realpath(this.fullpath())\n return (this.#realpath = this.resolve(rp))\n } catch (_) {\n this.#markENOREALPATH()\n }\n }\n\n /**\n * Synchronous {@link realpath}\n */\n realpathSync(): PathBase | undefined {\n if (this.#realpath) return this.#realpath\n if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n try {\n const rp = this.#fs.realpathSync(this.fullpath())\n return (this.#realpath = this.resolve(rp))\n } catch (_) {\n this.#markENOREALPATH()\n }\n }\n\n /**\n * Internal method to mark this Path object as the scurry cwd,\n * called by {@link PathScurry#chdir}\n *\n * @internal\n */\n [setAsCwd](oldCwd: PathBase): void {\n if (oldCwd === this) return\n oldCwd.isCWD = false\n this.isCWD = true\n\n const changed = new Set<PathBase>([])\n let rp = []\n let p: PathBase = this\n while (p && p.parent) {\n changed.add(p)\n p.#relative = rp.join(this.sep)\n p.#relativePosix = rp.join('/')\n p = p.parent\n rp.push('..')\n }\n // now un-memoize parents of old cwd\n p = oldCwd\n while (p && p.parent && !changed.has(p)) {\n p.#relative = undefined\n p.#relativePosix = undefined\n p = p.parent\n }\n }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n /**\n * Separator for generating path strings.\n */\n sep: '\\\\' = '\\\\'\n /**\n * Separator for parsing path strings.\n */\n splitSep: RegExp = eitherSep\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n super(name, type, root, roots, nocase, children, opts)\n }\n\n /**\n * @internal\n */\n newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n return new PathWin32(\n name,\n type,\n this.root,\n this.roots,\n this.nocase,\n this.childrenCache(),\n opts,\n )\n }\n\n /**\n * @internal\n */\n getRootString(path: string): string {\n return win32.parse(path).root\n }\n\n /**\n * @internal\n */\n getRoot(rootPath: string): PathBase {\n rootPath = uncToDrive(rootPath.toUpperCase())\n if (rootPath === this.root.name) {\n return this.root\n }\n // ok, not that one, check if it matches another we know about\n for (const [compare, root] of Object.entries(this.roots)) {\n if (this.sameRoot(rootPath, compare)) {\n return (this.roots[rootPath] = root)\n }\n }\n // otherwise, have to create a new one.\n return (this.roots[rootPath] = new PathScurryWin32(\n rootPath,\n this,\n ).root)\n }\n\n /**\n * @internal\n */\n sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n // windows can (rarely) have case-sensitive filesystem, but\n // UNC and drive letters are always case-insensitive, and canonically\n // represented uppercase.\n rootPath = rootPath\n .toUpperCase()\n .replace(/\\//g, '\\\\')\n .replace(uncDriveRegexp, '$1\\\\')\n return rootPath === compare\n }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n /**\n * separator for parsing path strings\n */\n splitSep: '/' = '/'\n /**\n * separator for generating path strings\n */\n sep: '/' = '/'\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n super(name, type, root, roots, nocase, children, opts)\n }\n\n /**\n * @internal\n */\n getRootString(path: string): string {\n return path.startsWith('/') ? '/' : ''\n }\n\n /**\n * @internal\n */\n getRoot(_rootPath: string): PathBase {\n return this.root\n }\n\n /**\n * @internal\n */\n newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n return new PathPosix(\n name,\n type,\n this.root,\n this.roots,\n this.nocase,\n this.childrenCache(),\n opts,\n )\n }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n /**\n * perform case-insensitive path matching. Default based on platform\n * subclass.\n */\n nocase?: boolean\n /**\n * Number of Path entries to keep in the cache of Path child references.\n *\n * Setting this higher than 65536 will dramatically increase the data\n * consumption and construction time overhead of each PathScurry.\n *\n * Setting this value to 256 or lower will significantly reduce the data\n * consumption and construction time overhead, but may also reduce resolve()\n * and readdir() performance on large filesystems.\n *\n * Default `16384`.\n */\n childrenCacheSize?: number\n /**\n * An object that overrides the built-in functions from the fs and\n * fs/promises modules.\n *\n * See {@link FSOption}\n */\n fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n /**\n * The root Path entry for the current working directory of this Scurry\n */\n root: PathBase\n /**\n * The string path for the root of this Scurry's current working directory\n */\n rootPath: string\n /**\n * A collection of all roots encountered, referenced by rootPath\n */\n roots: { [k: string]: PathBase }\n /**\n * The Path entry corresponding to this PathScurry's current working directory.\n */\n cwd: PathBase\n #resolveCache: ResolveCache\n #resolvePosixCache: ResolveCache\n #children: ChildrenCache\n /**\n * Perform path comparisons case-insensitively.\n *\n * Defaults true on Darwin and Windows systems, false elsewhere.\n */\n nocase: boolean\n\n /**\n * The path separator used for parsing paths\n *\n * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n */\n abstract sep: string | RegExp\n\n #fs: FSValue\n\n /**\n * This class should not be instantiated directly.\n *\n * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n *\n * @internal\n */\n constructor(\n cwd: URL | string = process.cwd(),\n pathImpl: typeof win32 | typeof posix,\n sep: string | RegExp,\n {\n nocase,\n childrenCacheSize = 16 * 1024,\n fs = defaultFS,\n }: PathScurryOpts = {},\n ) {\n this.#fs = fsFromOption(fs)\n if (cwd instanceof URL || cwd.startsWith('file://')) {\n cwd = fileURLToPath(cwd)\n }\n // resolve and split root, and then add to the store.\n // this is the only time we call path.resolve()\n const cwdPath = pathImpl.resolve(cwd)\n this.roots = Object.create(null)\n this.rootPath = this.parseRootPath(cwdPath)\n this.#resolveCache = new ResolveCache()\n this.#resolvePosixCache = new ResolveCache()\n this.#children = new ChildrenCache(childrenCacheSize)\n\n const split = cwdPath.substring(this.rootPath.length).split(sep)\n // resolve('/') leaves '', splits to [''], we don't want that.\n if (split.length === 1 && !split[0]) {\n split.pop()\n }\n /* c8 ignore start */\n if (nocase === undefined) {\n throw new TypeError(\n 'must provide nocase setting to PathScurryBase ctor',\n )\n }\n /* c8 ignore stop */\n this.nocase = nocase\n this.root = this.newRoot(this.#fs)\n this.roots[this.rootPath] = this.root\n let prev: PathBase = this.root\n let len = split.length - 1\n const joinSep = pathImpl.sep\n let abs = this.rootPath\n let sawFirst = false\n for (const part of split) {\n const l = len--\n prev = prev.child(part, {\n relative: new Array(l).fill('..').join(joinSep),\n relativePosix: new Array(l).fill('..').join('/'),\n fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n })\n sawFirst = true\n }\n this.cwd = prev\n }\n\n /**\n * Get the depth of a provided path, string, or the cwd\n */\n depth(path: Path | string = this.cwd): number {\n if (typeof path === 'string') {\n path = this.cwd.resolve(path)\n }\n return path.depth()\n }\n\n /**\n * Parse the root portion of a path string\n *\n * @internal\n */\n abstract parseRootPath(dir: string): string\n /**\n * create a new Path to use as root during construction.\n *\n * @internal\n */\n abstract newRoot(fs: FSValue): PathBase\n /**\n * Determine whether a given path string is absolute\n */\n abstract isAbsolute(p: string): boolean\n\n /**\n * Return the cache of child entries. Exposed so subclasses can create\n * child Path objects in a platform-specific way.\n *\n * @internal\n */\n childrenCache() {\n return this.#children\n }\n\n /**\n * Resolve one or more path strings to a resolved string\n *\n * Same interface as require('path').resolve.\n *\n * Much faster than path.resolve() when called multiple times for the same\n * path, because the resolved Path objects are cached. Much slower\n * otherwise.\n */\n resolve(...paths: string[]): string {\n // first figure out the minimum number of paths we have to test\n // we always start at cwd, but any absolutes will bump the start\n let r = ''\n for (let i = paths.length - 1; i >= 0; i--) {\n const p = paths[i]\n if (!p || p === '.') continue\n r = r ? `${p}/${r}` : p\n if (this.isAbsolute(p)) {\n break\n }\n }\n const cached = this.#resolveCache.get(r)\n if (cached !== undefined) {\n return cached\n }\n const result = this.cwd.resolve(r).fullpath()\n this.#resolveCache.set(r, result)\n return result\n }\n\n /**\n * Resolve one or more path strings to a resolved string, returning\n * the posix path. Identical to .resolve() on posix systems, but on\n * windows will return a forward-slash separated UNC path.\n *\n * Same interface as require('path').resolve.\n *\n * Much faster than path.resolve() when called multiple times for the same\n * path, because the resolved Path objects are cached. Much slower\n * otherwise.\n */\n resolvePosix(...paths: string[]): string {\n // first figure out the minimum number of paths we have to test\n // we always start at cwd, but any absolutes will bump the start\n let r = ''\n for (let i = paths.length - 1; i >= 0; i--) {\n const p = paths[i]\n if (!p || p === '.') continue\n r = r ? `${p}/${r}` : p\n if (this.isAbsolute(p)) {\n break\n }\n }\n const cached = this.#resolvePosixCache.get(r)\n if (cached !== undefined) {\n return cached\n }\n const result = this.cwd.resolve(r).fullpathPosix()\n this.#resolvePosixCache.set(r, result)\n return result\n }\n\n /**\n * find the relative path from the cwd to the supplied path string or entry\n */\n relative(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.relative()\n }\n\n /**\n * find the relative path from the cwd to the supplied path string or\n * entry, using / as the path delimiter, even on Windows.\n */\n relativePosix(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.relativePosix()\n }\n\n /**\n * Return the basename for the provided string or Path object\n */\n basename(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.name\n }\n\n /**\n * Return the dirname for the provided string or Path object\n */\n dirname(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return (entry.parent || entry).fullpath()\n }\n\n /**\n * Return an array of known child entries.\n *\n * First argument may be either a string, or a Path object.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n *\n * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n * `{ withFileTypes: false }` to return strings.\n */\n\n readdir(): Promise<PathBase[]>\n readdir(opts: { withFileTypes: true }): Promise<PathBase[]>\n readdir(opts: { withFileTypes: false }): Promise<string[]>\n readdir(opts: { withFileTypes: boolean }): Promise<PathBase[] | string[]>\n readdir(entry: PathBase | string): Promise<PathBase[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: true },\n ): Promise<PathBase[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: false },\n ): Promise<string[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: boolean },\n ): Promise<PathBase[] | string[]>\n async readdir(\n entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n opts: { withFileTypes: boolean } = {\n withFileTypes: true,\n },\n ): Promise<PathBase[] | string[]> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const { withFileTypes } = opts\n if (!entry.canReaddir()) {\n return []\n } else {\n const p = await entry.readdir()\n return withFileTypes ? p : p.map(e => e.name)\n }\n }\n\n /**\n * synchronous {@link PathScurryBase.readdir}\n */\n readdirSync(): PathBase[]\n readdirSync(opts: { withFileTypes: true }): PathBase[]\n readdirSync(opts: { withFileTypes: false }): string[]\n readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n readdirSync(entry: PathBase | string): PathBase[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: true },\n ): PathBase[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: false },\n ): string[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: boolean },\n ): PathBase[] | string[]\n readdirSync(\n entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n opts: { withFileTypes: boolean } = {\n withFileTypes: true,\n },\n ): PathBase[] | string[] {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const { withFileTypes = true } = opts\n if (!entry.canReaddir()) {\n return []\n } else if (withFileTypes) {\n return entry.readdirSync()\n } else {\n return entry.readdirSync().map(e => e.name)\n }\n }\n\n /**\n * Call lstat() on the string or Path object, and update all known\n * information that can be determined.\n *\n * Note that unlike `fs.lstat()`, the returned value does not contain some\n * information, such as `mode`, `dev`, `nlink`, and `ino`. If that\n * information is required, you will need to call `fs.lstat` yourself.\n *\n * If the Path refers to a nonexistent file, or if the lstat call fails for\n * any reason, `undefined` is returned. Otherwise the updated Path object is\n * returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async lstat(\n entry: string | PathBase = this.cwd,\n ): Promise<PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.lstat()\n }\n\n /**\n * synchronous {@link PathScurryBase.lstat}\n */\n lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.lstatSync()\n }\n\n /**\n * Return the Path object or string path corresponding to the target of a\n * symbolic link.\n *\n * If the path is not a symbolic link, or if the readlink call fails for any\n * reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n *\n * `{withFileTypes}` option defaults to `false`.\n *\n * On success, returns a Path object if `withFileTypes` option is true,\n * otherwise a string.\n */\n readlink(): Promise<string | undefined>\n readlink(opt: { withFileTypes: false }): Promise<string | undefined>\n readlink(opt: { withFileTypes: true }): Promise<PathBase | undefined>\n readlink(opt: {\n withFileTypes: boolean\n }): Promise<PathBase | string | undefined>\n readlink(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): Promise<string | undefined>\n readlink(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): Promise<PathBase | undefined>\n readlink(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): Promise<string | PathBase | undefined>\n async readlink(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): Promise<string | PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = await entry.readlink()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * synchronous {@link PathScurryBase.readlink}\n */\n readlinkSync(): string | undefined\n readlinkSync(opt: { withFileTypes: false }): string | undefined\n readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n readlinkSync(opt: {\n withFileTypes: boolean\n }): PathBase | string | undefined\n readlinkSync(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): string | undefined\n readlinkSync(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): PathBase | undefined\n readlinkSync(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): string | PathBase | undefined\n readlinkSync(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): string | PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = entry.readlinkSync()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * Return the Path object or string path corresponding to path as resolved\n * by realpath(3).\n *\n * If the realpath call fails for any reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n *\n * `{withFileTypes}` option defaults to `false`.\n *\n * On success, returns a Path object if `withFileTypes` option is true,\n * otherwise a string.\n */\n realpath(): Promise<string | undefined>\n realpath(opt: { withFileTypes: false }): Promise<string | undefined>\n realpath(opt: { withFileTypes: true }): Promise<PathBase | undefined>\n realpath(opt: {\n withFileTypes: boolean\n }): Promise<PathBase | string | undefined>\n realpath(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): Promise<string | undefined>\n realpath(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): Promise<PathBase | undefined>\n realpath(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): Promise<string | PathBase | undefined>\n async realpath(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): Promise<string | PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = await entry.realpath()\n return withFileTypes ? e : e?.fullpath()\n }\n\n realpathSync(): string | undefined\n realpathSync(opt: { withFileTypes: false }): string | undefined\n realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n realpathSync(opt: {\n withFileTypes: boolean\n }): PathBase | string | undefined\n realpathSync(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): string | undefined\n realpathSync(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): PathBase | undefined\n realpathSync(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): string | PathBase | undefined\n realpathSync(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): string | PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = entry.realpathSync()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * Asynchronously walk the directory tree, returning an array of\n * all path strings or Path objects found.\n *\n * Note that this will be extremely memory-hungry on large filesystems.\n * In such cases, it may be better to use the stream or async iterator\n * walk implementation.\n */\n walk(): Promise<PathBase[]>\n walk(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Promise<PathBase[]>\n walk(opts: WalkOptionsWithFileTypesFalse): Promise<string[]>\n walk(opts: WalkOptions): Promise<string[] | PathBase[]>\n walk(entry: string | PathBase): Promise<PathBase[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Promise<PathBase[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Promise<string[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Promise<PathBase[] | string[]>\n async walk(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Promise<PathBase[] | string[]> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results: (string | PathBase)[] = []\n if (!filter || filter(entry)) {\n results.push(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>()\n const walk = (\n dir: PathBase,\n cb: (er?: NodeJS.ErrnoException) => void,\n ) => {\n dirs.add(dir)\n dir.readdirCB((er, entries) => {\n /* c8 ignore start */\n if (er) {\n return cb(er)\n }\n /* c8 ignore stop */\n let len = entries.length\n if (!len) return cb()\n const next = () => {\n if (--len === 0) {\n cb()\n }\n }\n for (const e of entries) {\n if (!filter || filter(e)) {\n results.push(withFileTypes ? e : e.fullpath())\n }\n if (follow && e.isSymbolicLink()) {\n e.realpath()\n .then(r => (r?.isUnknown() ? r.lstat() : r))\n .then(r =>\n r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n )\n } else {\n if (e.shouldWalk(dirs, walkFilter)) {\n walk(e, next)\n } else {\n next()\n }\n }\n }\n }, true) // zalgooooooo\n }\n\n const start = entry\n return new Promise<PathBase[] | string[]>((res, rej) => {\n walk(start, er => {\n /* c8 ignore start */\n if (er) return rej(er)\n /* c8 ignore stop */\n res(results as PathBase[] | string[])\n })\n })\n }\n\n /**\n * Synchronously walk the directory tree, returning an array of\n * all path strings or Path objects found.\n *\n * Note that this will be extremely memory-hungry on large filesystems.\n * In such cases, it may be better to use the stream or async iterator\n * walk implementation.\n */\n walkSync(): PathBase[]\n walkSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): PathBase[]\n walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n walkSync(opts: WalkOptions): string[] | PathBase[]\n walkSync(entry: string | PathBase): PathBase[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): PathBase[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): string[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): PathBase[] | string[]\n walkSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): PathBase[] | string[] {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results: (string | PathBase)[] = []\n if (!filter || filter(entry)) {\n results.push(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>([entry])\n for (const dir of dirs) {\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n results.push(withFileTypes ? e : e.fullpath())\n }\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n dirs.add(r)\n }\n }\n }\n return results as string[] | PathBase[]\n }\n\n /**\n * Support for `for await`\n *\n * Alias for {@link PathScurryBase.iterate}\n *\n * Note: As of Node 19, this is very slow, compared to other methods of\n * walking. Consider using {@link PathScurryBase.stream} if memory overhead\n * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n */\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n\n /**\n * Async generator form of {@link PathScurryBase.walk}\n *\n * Note: As of Node 19, this is very slow, compared to other methods of\n * walking, especially if most/all of the directory tree has been previously\n * walked. Consider using {@link PathScurryBase.stream} if memory overhead\n * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n */\n iterate(): AsyncGenerator<PathBase, void, void>\n iterate(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): AsyncGenerator<PathBase, void, void>\n iterate(\n opts: WalkOptionsWithFileTypesFalse,\n ): AsyncGenerator<string, void, void>\n iterate(opts: WalkOptions): AsyncGenerator<string | PathBase, void, void>\n iterate(entry: string | PathBase): AsyncGenerator<PathBase, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): AsyncGenerator<PathBase, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): AsyncGenerator<string, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptions,\n ): AsyncGenerator<PathBase | string, void, void>\n iterate(\n entry: string | PathBase | WalkOptions = this.cwd,\n options: WalkOptions = {},\n ): AsyncGenerator<PathBase | string, void, void> {\n // iterating async over the stream is significantly more performant,\n // especially in the warm-cache scenario, because it buffers up directory\n // entries in the background instead of waiting for a yield for each one.\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n options = entry\n entry = this.cwd\n }\n return this.stream(entry, options)[Symbol.asyncIterator]()\n }\n\n /**\n * Iterating over a PathScurry performs a synchronous walk.\n *\n * Alias for {@link PathScurryBase.iterateSync}\n */\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n iterateSync(): Generator<PathBase, void, void>\n iterateSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Generator<PathBase, void, void>\n iterateSync(\n opts: WalkOptionsWithFileTypesFalse,\n ): Generator<string, void, void>\n iterateSync(opts: WalkOptions): Generator<string | PathBase, void, void>\n iterateSync(entry: string | PathBase): Generator<PathBase, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Generator<PathBase, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Generator<string, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Generator<PathBase | string, void, void>\n *iterateSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Generator<PathBase | string, void, void> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n if (!filter || filter(entry)) {\n yield withFileTypes ? entry : entry.fullpath()\n }\n const dirs = new Set<PathBase>([entry])\n for (const dir of dirs) {\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n yield withFileTypes ? e : e.fullpath()\n }\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n dirs.add(r)\n }\n }\n }\n }\n\n /**\n * Stream form of {@link PathScurryBase.walk}\n *\n * Returns a Minipass stream that emits {@link PathBase} objects by default,\n * or strings if `{ withFileTypes: false }` is set in the options.\n */\n stream(): Minipass<PathBase>\n stream(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Minipass<PathBase>\n stream(opts: WalkOptionsWithFileTypesFalse): Minipass<string>\n stream(opts: WalkOptions): Minipass<string | PathBase>\n stream(entry: string | PathBase): Minipass<PathBase>\n stream(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): Minipass<PathBase>\n stream(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Minipass<string>\n stream(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Minipass<string> | Minipass<PathBase>\n stream(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Minipass<string> | Minipass<PathBase> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results = new Minipass<string | PathBase>({ objectMode: true })\n if (!filter || filter(entry)) {\n results.write(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>()\n const queue: PathBase[] = [entry]\n let processing = 0\n const process = () => {\n let paused = false\n while (!paused) {\n const dir = queue.shift()\n if (!dir) {\n if (processing === 0) results.end()\n return\n }\n\n processing++\n dirs.add(dir)\n\n const onReaddir = (\n er: null | NodeJS.ErrnoException,\n entries: PathBase[],\n didRealpaths: boolean = false,\n ) => {\n /* c8 ignore start */\n if (er) return results.emit('error', er)\n /* c8 ignore stop */\n if (follow && !didRealpaths) {\n const promises: Promise<PathBase | undefined>[] = []\n for (const e of entries) {\n if (e.isSymbolicLink()) {\n promises.push(\n e\n .realpath()\n .then((r: PathBase | undefined) =>\n r?.isUnknown() ? r.lstat() : r,\n ),\n )\n }\n }\n if (promises.length) {\n Promise.all(promises).then(() =>\n onReaddir(null, entries, true),\n )\n return\n }\n }\n\n for (const e of entries) {\n if (e && (!filter || filter(e))) {\n if (!results.write(withFileTypes ? e : e.fullpath())) {\n paused = true\n }\n }\n }\n\n processing--\n for (const e of entries) {\n const r = e.realpathCached() || e\n if (r.shouldWalk(dirs, walkFilter)) {\n queue.push(r)\n }\n }\n if (paused && !results.flowing) {\n results.once('drain', process)\n } else if (!sync) {\n process()\n }\n }\n\n // zalgo containment\n let sync = true\n dir.readdirCB(onReaddir, true)\n sync = false\n }\n }\n process()\n return results as Minipass<string> | Minipass<PathBase>\n }\n\n /**\n * Synchronous form of {@link PathScurryBase.stream}\n *\n * Returns a Minipass stream that emits {@link PathBase} objects by default,\n * or strings if `{ withFileTypes: false }` is set in the options.\n *\n * Will complete the walk in a single tick if the stream is consumed fully.\n * Otherwise, will pause as needed for stream backpressure.\n */\n streamSync(): Minipass<PathBase>\n streamSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Minipass<PathBase>\n streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass<string>\n streamSync(opts: WalkOptions): Minipass<string | PathBase>\n streamSync(entry: string | PathBase): Minipass<PathBase>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): Minipass<PathBase>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Minipass<string>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Minipass<string> | Minipass<PathBase>\n streamSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Minipass<string> | Minipass<PathBase> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results = new Minipass<string | PathBase>({ objectMode: true })\n const dirs = new Set<PathBase>()\n if (!filter || filter(entry)) {\n results.write(withFileTypes ? entry : entry.fullpath())\n }\n const queue: PathBase[] = [entry]\n let processing = 0\n const process = () => {\n let paused = false\n while (!paused) {\n const dir = queue.shift()\n if (!dir) {\n if (processing === 0) results.end()\n return\n }\n processing++\n dirs.add(dir)\n\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n if (!results.write(withFileTypes ? e : e.fullpath())) {\n paused = true\n }\n }\n }\n processing--\n for (const e of entries) {\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n queue.push(r)\n }\n }\n }\n if (paused && !results.flowing) results.once('drain', process)\n }\n process()\n return results as Minipass<string> | Minipass<PathBase>\n }\n\n chdir(path: string | Path = this.cwd) {\n const oldCwd = this.cwd\n this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n this.cwd[setAsCwd](oldCwd)\n }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n /**\n * Return results as {@link PathBase} objects rather than strings.\n * When set to false, results are fully resolved paths, as returned by\n * {@link PathBase.fullpath}.\n * @default true\n */\n withFileTypes?: boolean\n\n /**\n * Attempt to read directory entries from symbolic links. Otherwise, only\n * actual directories are traversed. Regardless of this setting, a given\n * target path will only ever be walked once, meaning that a symbolic link\n * to a previously traversed directory will never be followed.\n *\n * Setting this imposes a slight performance penalty, because `readlink`\n * must be called on all symbolic links encountered, in order to avoid\n * infinite cycles.\n * @default false\n */\n follow?: boolean\n\n /**\n * Only return entries where the provided function returns true.\n *\n * This will not prevent directories from being traversed, even if they do\n * not pass the filter, though it will prevent directories themselves from\n * being included in the result set. See {@link walkFilter}\n *\n * Asynchronous functions are not supported here.\n *\n * By default, if no filter is provided, all entries and traversed\n * directories are included.\n */\n filter?: (entry: PathBase) => boolean\n\n /**\n * Only traverse directories (and in the case of {@link follow} being set to\n * true, symbolic links to directories) if the provided function returns\n * true.\n *\n * This will not prevent directories from being included in the result set,\n * even if they do not pass the supplied filter function. See {@link filter}\n * to do that.\n *\n * Asynchronous functions are not supported here.\n */\n walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings. Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n /**\n * separator for generating path strings\n */\n sep: '\\\\' = '\\\\'\n\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = true } = opts\n super(cwd, win32, '\\\\', { ...opts, nocase })\n this.nocase = nocase\n for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n p.nocase = this.nocase\n }\n }\n\n /**\n * @internal\n */\n parseRootPath(dir: string): string {\n // if the path starts with a single separator, it's not a UNC, and we'll\n // just get separator as the root, and driveFromUNC will return \\\n // In that case, mount \\ on the root from the cwd.\n return win32.parse(dir).root.toUpperCase()\n }\n\n /**\n * @internal\n */\n newRoot(fs: FSValue) {\n return new PathWin32(\n this.rootPath,\n IFDIR,\n undefined,\n this.roots,\n this.nocase,\n this.childrenCache(),\n { fs },\n )\n }\n\n /**\n * Return true if the provided path string is an absolute path\n */\n isAbsolute(p: string): boolean {\n return (\n p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n )\n }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n /**\n * separator for generating path strings\n */\n sep: '/' = '/'\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = false } = opts\n super(cwd, posix, '/', { ...opts, nocase })\n this.nocase = nocase\n }\n\n /**\n * @internal\n */\n parseRootPath(_dir: string): string {\n return '/'\n }\n\n /**\n * @internal\n */\n newRoot(fs: FSValue) {\n return new PathPosix(\n this.rootPath,\n IFDIR,\n undefined,\n this.roots,\n this.nocase,\n this.childrenCache(),\n { fs },\n )\n }\n\n /**\n * Return true if the provided path string is an absolute path\n */\n isAbsolute(p: string): boolean {\n return p.startsWith('/')\n }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = true } = opts\n super(cwd, { ...opts, nocase })\n }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType<typeof Path>\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n | typeof PathScurryWin32\n | typeof PathScurryDarwin\n | typeof PathScurryPosix =\n process.platform === 'win32' ? PathScurryWin32\n : process.platform === 'darwin' ? PathScurryDarwin\n : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType<typeof PathScurry>\n","const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n","// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n p0: '',\n p1: '',\n p2: string,\n p3: string,\n ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n readonly #patternList: PatternList\n readonly #globList: GlobList\n readonly #index: number\n readonly length: number\n readonly #platform: NodeJS.Platform\n #rest?: Pattern | null\n #globString?: string\n #isDrive?: boolean\n #isUNC?: boolean\n #isAbsolute?: boolean\n #followGlobstar: boolean = true\n\n constructor(\n patternList: MMPattern[],\n globList: string[],\n index: number,\n platform: NodeJS.Platform,\n ) {\n if (!isPatternList(patternList)) {\n throw new TypeError('empty pattern list')\n }\n if (!isGlobList(globList)) {\n throw new TypeError('empty glob list')\n }\n if (globList.length !== patternList.length) {\n throw new TypeError('mismatched pattern list and glob list lengths')\n }\n this.length = patternList.length\n if (index < 0 || index >= this.length) {\n throw new TypeError('index out of range')\n }\n this.#patternList = patternList\n this.#globList = globList\n this.#index = index\n this.#platform = platform\n\n // normalize root entries of absolute patterns on initial creation.\n if (this.#index === 0) {\n // c: => ['c:/']\n // C:/ => ['C:/']\n // C:/x => ['C:/', 'x']\n // //host/share => ['//host/share/']\n // //host/share/ => ['//host/share/']\n // //host/share/x => ['//host/share/', 'x']\n // /etc => ['/', 'etc']\n // / => ['/']\n if (this.isUNC()) {\n // '' / '' / 'host' / 'share'\n const [p0, p1, p2, p3, ...prest] = this.#patternList\n const [g0, g1, g2, g3, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = [p0, p1, p2, p3, ''].join('/')\n const g = [g0, g1, g2, g3, ''].join('/')\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n } else if (this.isDrive() || this.isAbsolute()) {\n const [p1, ...prest] = this.#patternList\n const [g1, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = (p1 as string) + '/'\n const g = g1 + '/'\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n }\n }\n }\n\n /**\n * The first entry in the parsed list of patterns\n */\n pattern(): MMPattern {\n return this.#patternList[this.#index] as MMPattern\n }\n\n /**\n * true of if pattern() returns a string\n */\n isString(): boolean {\n return typeof this.#patternList[this.#index] === 'string'\n }\n /**\n * true of if pattern() returns GLOBSTAR\n */\n isGlobstar(): boolean {\n return this.#patternList[this.#index] === GLOBSTAR\n }\n /**\n * true if pattern() returns a regexp\n */\n isRegExp(): boolean {\n return this.#patternList[this.#index] instanceof RegExp\n }\n\n /**\n * The /-joined set of glob parts that make up this pattern\n */\n globString(): string {\n return (this.#globString =\n this.#globString ||\n (this.#index === 0 ?\n this.isAbsolute() ?\n this.#globList[0] + this.#globList.slice(1).join('/')\n : this.#globList.join('/')\n : this.#globList.slice(this.#index).join('/')))\n }\n\n /**\n * true if there are more pattern parts after this one\n */\n hasMore(): boolean {\n return this.length > this.#index + 1\n }\n\n /**\n * The rest of the pattern after this part, or null if this is the end\n */\n rest(): Pattern | null {\n if (this.#rest !== undefined) return this.#rest\n if (!this.hasMore()) return (this.#rest = null)\n this.#rest = new Pattern(\n this.#patternList,\n this.#globList,\n this.#index + 1,\n this.#platform,\n )\n this.#rest.#isAbsolute = this.#isAbsolute\n this.#rest.#isUNC = this.#isUNC\n this.#rest.#isDrive = this.#isDrive\n return this.#rest\n }\n\n /**\n * true if the pattern represents a //unc/path/ on windows\n */\n isUNC(): boolean {\n const pl = this.#patternList\n return this.#isUNC !== undefined ?\n this.#isUNC\n : (this.#isUNC =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n pl[0] === '' &&\n pl[1] === '' &&\n typeof pl[2] === 'string' &&\n !!pl[2] &&\n typeof pl[3] === 'string' &&\n !!pl[3])\n }\n\n // pattern like C:/...\n // split = ['C:', ...]\n // XXX: would be nice to handle patterns like `c:*` to test the cwd\n // in c: for *, but I don't know of a way to even figure out what that\n // cwd is without actually chdir'ing into it?\n /**\n * True if the pattern starts with a drive letter on Windows\n */\n isDrive(): boolean {\n const pl = this.#patternList\n return this.#isDrive !== undefined ?\n this.#isDrive\n : (this.#isDrive =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n this.length > 1 &&\n typeof pl[0] === 'string' &&\n /^[a-z]:$/i.test(pl[0]))\n }\n\n // pattern = '/' or '/...' or '/x/...'\n // split = ['', ''] or ['', ...] or ['', 'x', ...]\n // Drive and UNC both considered absolute on windows\n /**\n * True if the pattern is rooted on an absolute path\n */\n isAbsolute(): boolean {\n const pl = this.#patternList\n return this.#isAbsolute !== undefined ?\n this.#isAbsolute\n : (this.#isAbsolute =\n (pl[0] === '' && pl.length > 1) ||\n this.isDrive() ||\n this.isUNC())\n }\n\n /**\n * consume the root of the pattern, and return it\n */\n root(): string {\n const p = this.#patternList[0]\n return (\n typeof p === 'string' && this.isAbsolute() && this.#index === 0\n ) ?\n p\n : ''\n }\n\n /**\n * Check to see if the current globstar pattern is allowed to follow\n * a symbolic link.\n */\n checkFollowGlobstar(): boolean {\n return !(\n this.#index === 0 ||\n !this.isGlobstar() ||\n !this.#followGlobstar\n )\n }\n\n /**\n * Mark that the current globstar pattern is following a symbolic link\n */\n markFollowGlobstar(): boolean {\n if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n return false\n this.#followGlobstar = false\n return true\n }\n}\n","// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n ignored?: (p: Path) => boolean\n childrenIgnored?: (p: Path) => boolean\n add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n relative: Minimatch[]\n relativeChildren: Minimatch[]\n absolute: Minimatch[]\n absoluteChildren: Minimatch[]\n platform: NodeJS.Platform\n mmopts: MinimatchOptions\n\n constructor(\n ignored: string[],\n {\n nobrace,\n nocase,\n noext,\n noglobstar,\n platform = defaultPlatform,\n }: GlobWalkerOpts,\n ) {\n this.relative = []\n this.absolute = []\n this.relativeChildren = []\n this.absoluteChildren = []\n this.platform = platform\n this.mmopts = {\n dot: true,\n nobrace,\n nocase,\n noext,\n noglobstar,\n optimizationLevel: 2,\n platform,\n nocomment: true,\n nonegate: true,\n }\n for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\n // this is a little weird, but it gives us a clean set of optimized\n // minimatch matchers, without getting tripped up if one of them\n // ends in /** inside a brace section, and it's only inefficient at\n // the start of the walk, not along it.\n // It'd be nice if the Pattern class just had a .test() method, but\n // handling globstars is a bit of a pita, and that code already lives\n // in minimatch anyway.\n // Another way would be if maybe Minimatch could take its set/globParts\n // as an option, and then we could at least just use Pattern to test\n // for absolute-ness.\n // Yet another way, Minimatch could take an array of glob strings, and\n // a cwd option, and do the right thing.\n const mm = new Minimatch(ign, this.mmopts)\n for (let i = 0; i < mm.set.length; i++) {\n const parsed = mm.set[i]\n const globParts = mm.globParts[i]\n /* c8 ignore start */\n if (!parsed || !globParts) {\n throw new Error('invalid pattern object')\n }\n // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.mmopts)\n const children = globParts[globParts.length - 1] === '**'\n const absolute = p.isAbsolute()\n if (absolute) this.absolute.push(m)\n else this.relative.push(m)\n if (children) {\n if (absolute) this.absoluteChildren.push(m)\n else this.relativeChildren.push(m)\n }\n }\n }\n\n ignored(p: Path): boolean {\n const fullpath = p.fullpath()\n const fullpaths = `${fullpath}/`\n const relative = p.relative() || '.'\n const relatives = `${relative}/`\n for (const m of this.relative) {\n if (m.match(relative) || m.match(relatives)) return true\n }\n for (const m of this.absolute) {\n if (m.match(fullpath) || m.match(fullpaths)) return true\n }\n return false\n }\n\n childrenIgnored(p: Path): boolean {\n const fullpath = p.fullpath() + '/'\n const relative = (p.relative() || '.') + '/'\n for (const m of this.relativeChildren) {\n if (m.match(relative)) return true\n }\n for (const m of this.absoluteChildren) {\n if (m.match(fullpath)) return true\n }\n return false\n }\n}\n","// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n store: Map<string, Set<string>>\n constructor(store: Map<string, Set<string>> = new Map()) {\n this.store = store\n }\n copy() {\n return new HasWalkedCache(new Map(this.store))\n }\n hasWalked(target: Path, pattern: Pattern) {\n return this.store.get(target.fullpath())?.has(pattern.globString())\n }\n storeWalked(target: Path, pattern: Pattern) {\n const fullpath = target.fullpath()\n const cached = this.store.get(fullpath)\n if (cached) cached.add(pattern.globString())\n else this.store.set(fullpath, new Set([pattern.globString()]))\n }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n store: Map<Path, number> = new Map()\n add(target: Path, absolute: boolean, ifDir: boolean) {\n const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n const current = this.store.get(target)\n this.store.set(target, current === undefined ? n : n & current)\n }\n // match, absolute, ifdir\n entries(): [Path, boolean, boolean][] {\n return [...this.store.entries()].map(([path, n]) => [\n path,\n !!(n & 2),\n !!(n & 1),\n ])\n }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n store: Map<Path, Pattern[]> = new Map()\n add(target: Path, pattern: Pattern) {\n if (!target.canReaddir()) {\n return\n }\n const subs = this.store.get(target)\n if (subs) {\n if (!subs.find(p => p.globString() === pattern.globString())) {\n subs.push(pattern)\n }\n } else this.store.set(target, [pattern])\n }\n get(target: Path): Pattern[] {\n const subs = this.store.get(target)\n /* c8 ignore start */\n if (!subs) {\n throw new Error('attempting to walk unknown path')\n }\n /* c8 ignore stop */\n return subs\n }\n entries(): [Path, Pattern[]][] {\n return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n }\n keys(): Path[] {\n return [...this.store.keys()].filter(t => t.canReaddir())\n }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n hasWalkedCache: HasWalkedCache\n matches = new MatchRecord()\n subwalks = new SubWalks()\n patterns?: Pattern[]\n follow: boolean\n dot: boolean\n opts: GlobWalkerOpts\n\n constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n this.opts = opts\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.hasWalkedCache =\n hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n }\n\n processPatterns(target: Path, patterns: Pattern[]) {\n this.patterns = patterns\n const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n // map of paths to the magic-starting subwalks they need to walk\n // first item in patterns is the filter\n\n for (let [t, pattern] of processingSet) {\n this.hasWalkedCache.storeWalked(t, pattern)\n\n const root = pattern.root()\n const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n // start absolute patterns at root\n if (root) {\n t = t.resolve(\n root === '/' && this.opts.root !== undefined ?\n this.opts.root\n : root,\n )\n const rest = pattern.rest()\n if (!rest) {\n this.matches.add(t, true, false)\n continue\n } else {\n pattern = rest\n }\n }\n\n if (t.isENOENT()) continue\n\n let p: MMPattern\n let rest: Pattern | null\n let changed = false\n while (\n typeof (p = pattern.pattern()) === 'string' &&\n (rest = pattern.rest())\n ) {\n const c = t.resolve(p)\n t = c\n pattern = rest\n changed = true\n }\n p = pattern.pattern()\n rest = pattern.rest()\n if (changed) {\n if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n this.hasWalkedCache.storeWalked(t, pattern)\n }\n\n // now we have either a final string for a known entry,\n // more strings for an unknown entry,\n // or a pattern starting with magic, mounted on t.\n if (typeof p === 'string') {\n // must not be final entry, otherwise we would have\n // concatenated it earlier.\n const ifDir = p === '..' || p === '' || p === '.'\n this.matches.add(t.resolve(p), absolute, ifDir)\n continue\n } else if (p === GLOBSTAR) {\n // if no rest, match and subwalk pattern\n // if rest, process rest and subwalk pattern\n // if it's a symlink, but we didn't get here by way of a\n // globstar match (meaning it's the first time THIS globstar\n // has traversed a symlink), then we follow it. Otherwise, stop.\n if (\n !t.isSymbolicLink() ||\n this.follow ||\n pattern.checkFollowGlobstar()\n ) {\n this.subwalks.add(t, pattern)\n }\n const rp = rest?.pattern()\n const rrest = rest?.rest()\n if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n // only HAS to be a dir if it ends in **/ or **/.\n // but ending in ** will match files as well.\n this.matches.add(t, absolute, rp === '' || rp === '.')\n } else {\n if (rp === '..') {\n // this would mean you're matching **/.. at the fs root,\n // and no thanks, I'm not gonna test that specific case.\n /* c8 ignore start */\n const tp = t.parent || t\n /* c8 ignore stop */\n if (!rrest) this.matches.add(tp, absolute, true)\n else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n this.subwalks.add(tp, rrest)\n }\n }\n }\n } else if (p instanceof RegExp) {\n this.subwalks.add(t, pattern)\n }\n }\n\n return this\n }\n\n subwalkTargets(): Path[] {\n return this.subwalks.keys()\n }\n\n child() {\n return new Processor(this.opts, this.hasWalkedCache)\n }\n\n // return a new Processor containing the subwalks for each\n // child entry, and a set of matches, and\n // a hasWalkedCache that's a copy of this one\n // then we're going to call\n filterEntries(parent: Path, entries: Path[]): Processor {\n const patterns = this.subwalks.get(parent)\n // put matches and entry walks into the results processor\n const results = this.child()\n for (const e of entries) {\n for (const pattern of patterns) {\n const absolute = pattern.isAbsolute()\n const p = pattern.pattern()\n const rest = pattern.rest()\n if (p === GLOBSTAR) {\n results.testGlobstar(e, pattern, rest, absolute)\n } else if (p instanceof RegExp) {\n results.testRegExp(e, p, rest, absolute)\n } else {\n results.testString(e, p, rest, absolute)\n }\n }\n }\n return results\n }\n\n testGlobstar(\n e: Path,\n pattern: Pattern,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (this.dot || !e.name.startsWith('.')) {\n if (!pattern.hasMore()) {\n this.matches.add(e, absolute, false)\n }\n if (e.canReaddir()) {\n // if we're in follow mode or it's not a symlink, just keep\n // testing the same pattern. If there's more after the globstar,\n // then this symlink consumes the globstar. If not, then we can\n // follow at most ONE symlink along the way, so we mark it, which\n // also checks to ensure that it wasn't already marked.\n if (this.follow || !e.isSymbolicLink()) {\n this.subwalks.add(e, pattern)\n } else if (e.isSymbolicLink()) {\n if (rest && pattern.checkFollowGlobstar()) {\n this.subwalks.add(e, rest)\n } else if (pattern.markFollowGlobstar()) {\n this.subwalks.add(e, pattern)\n }\n }\n }\n }\n // if the NEXT thing matches this entry, then also add\n // the rest.\n if (rest) {\n const rp = rest.pattern()\n if (\n typeof rp === 'string' &&\n // dots and empty were handled already\n rp !== '..' &&\n rp !== '' &&\n rp !== '.'\n ) {\n this.testString(e, rp, rest.rest(), absolute)\n } else if (rp === '..') {\n /* c8 ignore start */\n const ep = e.parent || e\n /* c8 ignore stop */\n this.subwalks.add(ep, rest)\n } else if (rp instanceof RegExp) {\n this.testRegExp(e, rp, rest.rest(), absolute)\n }\n }\n }\n\n testRegExp(\n e: Path,\n p: MMRegExp,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (!p.test(e.name)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n\n testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n // should never happen?\n if (!e.isNamed(p)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n}\n","/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed? that'd speed\n// things up a lot. Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n absolute?: boolean\n allowWindowsEscape?: boolean\n cwd?: string | URL\n dot?: boolean\n dotRelative?: boolean\n follow?: boolean\n ignore?: string | string[] | IgnoreLike\n mark?: boolean\n matchBase?: boolean\n // Note: maxDepth here means \"maximum actual Path.depth()\",\n // not \"maximum depth beyond cwd\"\n maxDepth?: number\n nobrace?: boolean\n nocase?: boolean\n nodir?: boolean\n noext?: boolean\n noglobstar?: boolean\n platform?: NodeJS.Platform\n posix?: boolean\n realpath?: boolean\n root?: string\n stat?: boolean\n signal?: AbortSignal\n windowsPathsNoEscape?: boolean\n withFileTypes?: boolean\n includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n withFileTypes?: undefined\n}\n\nexport type Result<O extends GlobWalkerOpts> =\n O extends GWOFileTypesTrue ? Path\n : O extends GWOFileTypesFalse ? string\n : O extends GWOFileTypesUnset ? string\n : Path | string\n\nexport type Matches<O extends GlobWalkerOpts> =\n O extends GWOFileTypesTrue ? Set<Path>\n : O extends GWOFileTypesFalse ? Set<string>\n : O extends GWOFileTypesUnset ? Set<string>\n : Set<Path | string>\n\nexport type MatchStream<O extends GlobWalkerOpts> = Minipass<\n Result<O>,\n Result<O>\n>\n\nconst makeIgnore = (\n ignore: string | string[] | IgnoreLike,\n opts: GlobWalkerOpts,\n): IgnoreLike =>\n typeof ignore === 'string' ? new Ignore([ignore], opts)\n : Array.isArray(ignore) ? new Ignore(ignore, opts)\n : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil<O extends GlobWalkerOpts = GlobWalkerOpts> {\n path: Path\n patterns: Pattern[]\n opts: O\n seen: Set<Path> = new Set<Path>()\n paused: boolean = false\n aborted: boolean = false\n #onResume: (() => any)[] = []\n #ignore?: IgnoreLike\n #sep: '\\\\' | '/'\n signal?: AbortSignal\n maxDepth: number\n includeChildMatches: boolean\n\n constructor(patterns: Pattern[], path: Path, opts: O)\n constructor(patterns: Pattern[], path: Path, opts: O) {\n this.patterns = patterns\n this.path = path\n this.opts = opts\n this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n this.includeChildMatches = opts.includeChildMatches !== false\n if (opts.ignore || !this.includeChildMatches) {\n this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n if (\n !this.includeChildMatches &&\n typeof this.#ignore.add !== 'function'\n ) {\n const m = 'cannot ignore child matches, ignore lacks add() method.'\n throw new Error(m)\n }\n }\n // ignore, always set with maxDepth, but it's optional on the\n // GlobOptions type\n /* c8 ignore start */\n this.maxDepth = opts.maxDepth || Infinity\n /* c8 ignore stop */\n if (opts.signal) {\n this.signal = opts.signal\n this.signal.addEventListener('abort', () => {\n this.#onResume.length = 0\n })\n }\n }\n\n #ignored(path: Path): boolean {\n return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n }\n #childrenIgnored(path: Path): boolean {\n return !!this.#ignore?.childrenIgnored?.(path)\n }\n\n // backpressure mechanism\n pause() {\n this.paused = true\n }\n resume() {\n /* c8 ignore start */\n if (this.signal?.aborted) return\n /* c8 ignore stop */\n this.paused = false\n let fn: (() => any) | undefined = undefined\n while (!this.paused && (fn = this.#onResume.shift())) {\n fn()\n }\n }\n onResume(fn: () => any) {\n if (this.signal?.aborted) return\n /* c8 ignore start */\n if (!this.paused) {\n fn()\n } else {\n /* c8 ignore stop */\n this.#onResume.push(fn)\n }\n }\n\n // do the requisite realpath/stat checking, and return the path\n // to add or undefined to filter it out.\n async matchCheck(e: Path, ifDir: boolean): Promise<Path | undefined> {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || (await e.realpath())\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? await e.lstat() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = await s.realpath()\n /* c8 ignore start */\n if (target && (target.isUnknown() || this.opts.stat)) {\n await target.lstat()\n }\n /* c8 ignore stop */\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n return (\n e &&\n (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n (!ifDir || e.canReaddir()) &&\n (!this.opts.nodir || !e.isDirectory()) &&\n (!this.opts.nodir ||\n !this.opts.follow ||\n !e.isSymbolicLink() ||\n !e.realpathCached()?.isDirectory()) &&\n !this.#ignored(e)\n ) ?\n e\n : undefined\n }\n\n matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || e.realpathSync()\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? e.lstatSync() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = s.realpathSync()\n if (target && (target?.isUnknown() || this.opts.stat)) {\n target.lstatSync()\n }\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n abstract matchEmit(p: Result<O>): void\n abstract matchEmit(p: string | Path): void\n\n matchFinish(e: Path, absolute: boolean) {\n if (this.#ignored(e)) return\n // we know we have an ignore if this is false, but TS doesn't\n if (!this.includeChildMatches && this.#ignore?.add) {\n const ign = `${e.relativePosix()}/**`\n this.#ignore.add(ign)\n }\n const abs =\n this.opts.absolute === undefined ? absolute : this.opts.absolute\n this.seen.add(e)\n const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n // ok, we have what we need!\n if (this.opts.withFileTypes) {\n this.matchEmit(e)\n } else if (abs) {\n const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n this.matchEmit(abs + mark)\n } else {\n const rel = this.opts.posix ? e.relativePosix() : e.relative()\n const pre =\n this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n '.' + this.#sep\n : ''\n this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n }\n }\n\n async match(e: Path, absolute: boolean, ifDir: boolean): Promise<void> {\n const p = await this.matchCheck(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n const p = this.matchCheckSync(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const childrenCached = t.readdirCached()\n if (t.calledReaddir())\n this.walkCB3(t, childrenCached, processor, next)\n else {\n t.readdirCB(\n (_, entries) => this.walkCB3(t, entries, processor, next),\n true,\n )\n }\n }\n\n next()\n }\n\n walkCB3(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2(target, patterns, processor.child(), next)\n }\n\n next()\n }\n\n walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2Sync(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() =>\n this.walkCB2Sync(target, patterns, processor, cb),\n )\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const children = t.readdirSync()\n this.walkCB3Sync(t, children, processor, next)\n }\n\n next()\n }\n\n walkCB3Sync(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2Sync(target, patterns, processor.child(), next)\n }\n\n next()\n }\n}\n\nexport class GlobWalker<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil<O> {\n matches = new Set<Result<O>>()\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n }\n\n matchEmit(e: Result<O>): void {\n this.matches.add(e)\n }\n\n async walk(): Promise<Set<Result<O>>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n await this.path.lstat()\n }\n await new Promise((res, rej) => {\n this.walkCB(this.path, this.patterns, () => {\n if (this.signal?.aborted) {\n rej(this.signal.reason)\n } else {\n res(this.matches)\n }\n })\n })\n return this.matches\n }\n\n walkSync(): Set<Result<O>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n // nothing for the callback to do, because this never pauses\n this.walkCBSync(this.path, this.patterns, () => {\n if (this.signal?.aborted) throw this.signal.reason\n })\n return this.matches\n }\n}\n\nexport class GlobStream<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil<O> {\n results: Minipass<Result<O>, Result<O>>\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n this.results = new Minipass<Result<O>, Result<O>>({\n signal: this.signal,\n objectMode: true,\n })\n this.results.on('drain', () => this.resume())\n this.results.on('resume', () => this.resume())\n }\n\n matchEmit(e: Result<O>): void {\n this.results.write(e)\n if (!this.results.flowing) this.pause()\n }\n\n stream(): MatchStream<O> {\n const target = this.path\n if (target.isUnknown()) {\n target.lstat().then(() => {\n this.walkCB(target, this.patterns, () => this.results.end())\n })\n } else {\n this.walkCB(target, this.patterns, () => this.results.end())\n }\n return this.results\n }\n\n streamSync(): MatchStream<O> {\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n this.walkCBSync(this.path, this.patterns, () => this.results.end())\n return this.results\n }\n}\n","import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n pattern: string | string[],\n options: GlobOptions = {},\n): boolean => {\n if (!Array.isArray(pattern)) {\n pattern = [pattern]\n }\n for (const p of pattern) {\n if (new Minimatch(p, options).hasMagic()) return true\n }\n return false\n}\n","/**\n * Verifier exports\n */\nexport * from './base.js';\nexport * from './naming.js';\nexport * from './imports.js';\nexport * from './errors.js';\nexport * from './regex.js';\nexport * from './dependencies.js';\nexport * from './complexity.js';\nexport * from './security.js';\nexport * from './api.js';\n\nimport type { Verifier } from './base.js';\nimport { NamingVerifier } from './naming.js';\nimport { ImportsVerifier } from './imports.js';\nimport { ErrorsVerifier } from './errors.js';\nimport { RegexVerifier } from './regex.js';\nimport { DependencyVerifier } from './dependencies.js';\nimport { ComplexityVerifier } from './complexity.js';\nimport { SecurityVerifier } from './security.js';\nimport { ApiVerifier } from './api.js';\nimport { getPluginLoader } from '../plugins/loader.js';\n\n/**\n * Built-in verifiers registry\n */\nexport const builtinVerifiers: Record<string, () => Verifier> = {\n naming: () => new NamingVerifier(),\n imports: () => new ImportsVerifier(),\n errors: () => new ErrorsVerifier(),\n regex: () => new RegexVerifier(),\n dependencies: () => new DependencyVerifier(),\n complexity: () => new ComplexityVerifier(),\n security: () => new SecurityVerifier(),\n api: () => new ApiVerifier(),\n};\n\n/**\n * Verifier instance pool (reuse instances instead of creating new ones)\n */\nconst verifierInstances = new Map<string, Verifier>();\n\n/**\n * Get verifier by ID\n * Checks custom plugins first, then built-in verifiers\n * Instances are pooled for performance\n */\nexport function getVerifier(id: string): Verifier | null {\n // Check instance pool first\n if (verifierInstances.has(id)) {\n return verifierInstances.get(id)!;\n }\n\n // Priority 1: Custom plugins\n const pluginLoader = getPluginLoader();\n const customVerifier = pluginLoader.getVerifier(id);\n if (customVerifier) {\n verifierInstances.set(id, customVerifier);\n return customVerifier;\n }\n\n // Priority 2: Built-in verifiers\n const factory = builtinVerifiers[id];\n if (factory) {\n const verifier = factory();\n verifierInstances.set(id, verifier);\n return verifier;\n }\n\n return null;\n}\n\n/**\n * Get all verifier IDs (built-in + plugins)\n */\nexport function getVerifierIds(): string[] {\n const builtinIds = Object.keys(builtinVerifiers);\n const pluginIds = getPluginLoader().getPluginIds();\n return [...new Set([...builtinIds, ...pluginIds])];\n}\n\n/**\n * Clear the verifier instance pool (for testing)\n */\nexport function clearVerifierPool(): void {\n verifierInstances.clear();\n}\n\n/**\n * Select appropriate verifier based on constraint\n */\nexport function selectVerifierForConstraint(\n rule: string,\n specifiedVerifier?: string,\n check?: { verifier: string; params?: Record<string, unknown> }\n): Verifier | null {\n // Priority 1: Use check block verifier if present (new structured format)\n if (check?.verifier) {\n return getVerifier(check.verifier);\n }\n\n // Priority 2: Use legacy verifier field if specified\n if (specifiedVerifier) {\n return getVerifier(specifiedVerifier);\n }\n\n // Priority 3: Auto-select based on rule content\n const lowerRule = rule.toLowerCase();\n\n if (lowerRule.includes('dependency') || lowerRule.includes('circular dependenc') || lowerRule.includes('import depth') || (lowerRule.includes('layer') && lowerRule.includes('depend on'))) {\n return getVerifier('dependencies');\n }\n\n if (lowerRule.includes('cyclomatic') || lowerRule.includes('complexity') || lowerRule.includes('nesting') || lowerRule.includes('parameters') || lowerRule.includes('file size')) {\n return getVerifier('complexity');\n }\n\n if (lowerRule.includes('security') || lowerRule.includes('secret') || lowerRule.includes('password') || lowerRule.includes('token') || lowerRule.includes('xss') || lowerRule.includes('sql') || lowerRule.includes('eval')) {\n return getVerifier('security');\n }\n\n if (lowerRule.includes('endpoint') || lowerRule.includes('rest') || (lowerRule.includes('api') && lowerRule.includes('path'))) {\n return getVerifier('api');\n }\n\n if (lowerRule.includes('naming') || lowerRule.includes('case')) {\n return getVerifier('naming');\n }\n\n if (lowerRule.includes('import') || lowerRule.includes('barrel') || lowerRule.includes('alias')) {\n return getVerifier('imports');\n }\n\n if (lowerRule.includes('error') || lowerRule.includes('throw') || lowerRule.includes('catch')) {\n return getVerifier('errors');\n }\n\n if (lowerRule.includes('/') || lowerRule.includes('pattern') || lowerRule.includes('regex')) {\n return getVerifier('regex');\n }\n\n // Default to regex verifier for pattern-based rules\n return getVerifier('regex');\n}\n","/**\n * AST parsing cache (per VerificationEngine instance)\n * Uses content hashing for better invalidation\n */\nimport { stat, readFile } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport type { Project, SourceFile } from 'ts-morph';\n\ninterface CacheEntry {\n sourceFile: SourceFile;\n hash: string;\n mtimeMs: number;\n}\n\nexport class AstCache {\n private cache = new Map<string, CacheEntry>();\n\n async get(filePath: string, project: Project): Promise<SourceFile | null> {\n try {\n const stats = await stat(filePath);\n const cached = this.cache.get(filePath);\n\n // Quick check: mtime hasn't changed\n if (cached && cached.mtimeMs >= stats.mtimeMs) {\n return cached.sourceFile;\n }\n\n // Read and hash content\n const content = await readFile(filePath, 'utf-8');\n const hash = createHash('sha256').update(content).digest('hex');\n\n // If hash matches, update mtime but keep AST\n if (cached && cached.hash === hash) {\n cached.mtimeMs = stats.mtimeMs;\n return cached.sourceFile;\n }\n\n // Re-parse: content has changed\n let sourceFile = project.getSourceFile(filePath);\n if (!sourceFile) {\n sourceFile = project.addSourceFileAtPath(filePath);\n } else {\n // Refresh from disk if the file changed\n sourceFile.refreshFromFileSystemSync();\n }\n\n this.cache.set(filePath, {\n sourceFile,\n hash,\n mtimeMs: stats.mtimeMs,\n });\n\n return sourceFile;\n } catch {\n return null;\n }\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n getStats() {\n return {\n entries: this.cache.size,\n memoryEstimate: this.cache.size * 50000, // Rough estimate: 50KB per AST\n };\n }\n}\n\n","/**\n * Results cache - Caches verification results by file hash + constraint\n *\n * Avoids re-running verifiers on unchanged files\n */\nimport type { Violation } from '../core/types/index.js';\n\nexport interface CacheKey {\n filePath: string;\n decisionId: string;\n constraintId: string;\n fileHash: string;\n}\n\n/**\n * Cache for verification results\n * Results are keyed by file path + decision + constraint + file hash\n */\nexport class ResultsCache {\n private cache = new Map<string, Violation[]>();\n\n /**\n * Generate cache key from components\n */\n private getCacheKey(key: CacheKey): string {\n return `${key.filePath}:${key.decisionId}:${key.constraintId}:${key.fileHash}`;\n }\n\n /**\n * Get cached violations for a specific verification\n *\n * @returns Violations if cached, null if not found\n */\n get(key: CacheKey): Violation[] | null {\n const cacheKey = this.getCacheKey(key);\n return this.cache.get(cacheKey) || null;\n }\n\n /**\n * Store verification results in cache\n */\n set(key: CacheKey, violations: Violation[]): void {\n const cacheKey = this.getCacheKey(key);\n this.cache.set(cacheKey, violations);\n }\n\n /**\n * Check if result is cached\n */\n has(key: CacheKey): boolean {\n const cacheKey = this.getCacheKey(key);\n return this.cache.has(cacheKey);\n }\n\n /**\n * Clear entire cache\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Clear cache entries for a specific file\n */\n clearFile(filePath: string): void {\n for (const key of this.cache.keys()) {\n if (key.startsWith(`${filePath}:`)) {\n this.cache.delete(key);\n }\n }\n }\n\n /**\n * Clear cache entries for a specific decision\n */\n clearDecision(decisionId: string): void {\n for (const key of this.cache.keys()) {\n if (key.includes(`:${decisionId}:`)) {\n this.cache.delete(key);\n }\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats() {\n return {\n entries: this.cache.size,\n memoryEstimate: this.cache.size * 1000, // Rough estimate: 1KB per result\n };\n }\n}\n","/**\n * Shared constraint applicability helpers\n */\nimport type { Constraint, Severity } from '../core/types/index.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport function isConstraintExcepted(filePath: string, constraint: Constraint, cwd: string): boolean {\n if (!constraint.exceptions) return false;\n\n return constraint.exceptions.some((exception) => {\n // Check if exception has expired\n if (exception.expiresAt) {\n const expiryDate = new Date(exception.expiresAt);\n if (expiryDate < new Date()) {\n return false;\n }\n }\n\n return matchesPattern(filePath, exception.pattern, { cwd });\n });\n}\n\nexport function shouldApplyConstraintToFile(params: {\n filePath: string;\n constraint: Constraint;\n cwd: string;\n severityFilter?: Severity[];\n}): boolean {\n const { filePath, constraint, cwd, severityFilter } = params;\n\n if (!matchesPattern(filePath, constraint.scope, { cwd })) return false;\n if (severityFilter && !severityFilter.includes(constraint.severity)) return false;\n if (isConstraintExcepted(filePath, constraint, cwd)) return false;\n\n return true;\n}\n\n","/**\n * Auto-fix engine\n */\nimport { readFile, writeFile } from 'node:fs/promises';\nimport readline from 'node:readline/promises';\nimport { stdin, stdout } from 'node:process';\nimport type { Violation, TextEdit } from '../../core/types/index.js';\n\nexport interface AutofixPatch {\n filePath: string;\n description: string;\n start: number;\n end: number;\n originalText: string;\n fixedText: string;\n}\n\nexport interface AutofixResult {\n applied: AutofixPatch[];\n skipped: number;\n}\n\ntype DescribedEdit = TextEdit & { description: string };\n\nfunction applyEdits(\n content: string,\n edits: DescribedEdit[]\n): { next: string; patches: AutofixPatch[]; skippedEdits: number } {\n const sorted = [...edits].sort((a, b) => b.start - a.start);\n\n let next = content;\n const patches: AutofixPatch[] = [];\n let skippedEdits = 0;\n let lastStart = Number.POSITIVE_INFINITY;\n\n for (const edit of sorted) {\n if (edit.start < 0 || edit.end < edit.start || edit.end > next.length) {\n skippedEdits++;\n continue;\n }\n\n // Overlap check (since edits are sorted by start descending)\n if (edit.end > lastStart) {\n skippedEdits++;\n continue;\n }\n lastStart = edit.start;\n\n const originalText = next.slice(edit.start, edit.end);\n next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);\n\n patches.push({\n filePath: '',\n description: edit.description,\n start: edit.start,\n end: edit.end,\n originalText,\n fixedText: edit.text,\n });\n }\n\n return { next, patches, skippedEdits };\n}\n\nasync function confirmFix(prompt: string): Promise<boolean> {\n const rl = readline.createInterface({ input: stdin, output: stdout });\n try {\n const answer = await rl.question(`${prompt} (y/N) `);\n return answer.trim().toLowerCase() === 'y';\n } finally {\n rl.close();\n }\n}\n\nexport class AutofixEngine {\n async applyFixes(\n violations: Violation[],\n options: { dryRun?: boolean; interactive?: boolean } = {}\n ): Promise<AutofixResult> {\n const fixable = violations.filter(v => v.autofix && v.autofix.edits.length > 0);\n const byFile = new Map<string, Violation[]>();\n for (const v of fixable) {\n const list = byFile.get(v.file) ?? [];\n list.push(v);\n byFile.set(v.file, list);\n }\n\n const applied: AutofixPatch[] = [];\n let skippedViolations = 0;\n\n for (const [filePath, fileViolations] of byFile) {\n const original = await readFile(filePath, 'utf-8');\n\n const edits: DescribedEdit[] = [];\n for (const violation of fileViolations) {\n const fix = violation.autofix!;\n if (options.interactive) {\n const ok = await confirmFix(`Apply fix: ${fix.description} (${filePath}:${violation.line ?? 1})?`);\n if (!ok) {\n skippedViolations++;\n continue;\n }\n }\n for (const edit of fix.edits) {\n edits.push({ ...edit, description: fix.description });\n }\n }\n\n if (edits.length === 0) continue;\n\n const { next, patches, skippedEdits } = applyEdits(original, edits);\n skippedViolations += skippedEdits;\n\n if (!options.dryRun) {\n await writeFile(filePath, next, 'utf-8');\n }\n\n for (const patch of patches) {\n applied.push({ ...patch, filePath });\n }\n }\n\n return { applied, skipped: skippedViolations };\n }\n}\n","/**\n * Incremental verification helpers\n */\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { resolve } from 'node:path';\nimport { pathExists } from '../utils/fs.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport async function getChangedFiles(cwd: string): Promise<string[]> {\n try {\n const { stdout } = await execFileAsync('git', ['diff', '--name-only', '--diff-filter=AM', 'HEAD'], { cwd });\n const rel = stdout\n .trim()\n .split('\\n')\n .map(s => s.trim())\n .filter(Boolean);\n\n const abs: string[] = [];\n for (const file of rel) {\n const full = resolve(cwd, file);\n if (await pathExists(full)) abs.push(full);\n }\n return abs;\n } catch {\n return [];\n }\n}\n\n","/**\n * Explain Reporter - Provides detailed explanation of verification process\n */\nimport chalk from 'chalk';\nimport type { Decision, Constraint } from '../core/types/index.js';\n\n/**\n * Entry in the explanation trace\n */\nexport interface ExplanationEntry {\n file: string;\n decision: Decision;\n constraint: Constraint;\n applied: boolean;\n reason: string;\n selectedVerifier?: string;\n verifierOutput?: {\n violations: number;\n duration: number;\n error?: string;\n };\n}\n\n/**\n * Reporter for --explain mode\n */\nexport class ExplainReporter {\n private entries: ExplanationEntry[] = [];\n\n /**\n * Add an entry to the explanation trace\n */\n add(entry: ExplanationEntry): void {\n this.entries.push(entry);\n }\n\n /**\n * Print the explanation trace\n */\n print(): void {\n if (this.entries.length === 0) {\n console.log(chalk.dim('No constraints were evaluated.'));\n return;\n }\n\n console.log(chalk.bold('\\n=== Verification Explanation ===\\n'));\n\n // Group by file\n const byFile = new Map<string, ExplanationEntry[]>();\n for (const entry of this.entries) {\n const existing = byFile.get(entry.file) || [];\n existing.push(entry);\n byFile.set(entry.file, existing);\n }\n\n // Print grouped by file\n for (const [file, entries] of byFile) {\n console.log(chalk.underline(file));\n\n for (const entry of entries) {\n const icon = entry.applied ? chalk.green('✓') : chalk.dim('⊘');\n const constraintId = `${entry.decision.metadata.id}/${entry.constraint.id}`;\n\n console.log(` ${icon} ${constraintId}`);\n console.log(chalk.dim(` ${entry.reason}`));\n\n if (entry.applied && entry.selectedVerifier) {\n console.log(chalk.dim(` Verifier: ${entry.selectedVerifier}`));\n\n if (entry.verifierOutput) {\n if (entry.verifierOutput.error) {\n console.log(chalk.red(` Error: ${entry.verifierOutput.error}`));\n } else {\n const violationText = entry.verifierOutput.violations === 1\n ? '1 violation'\n : `${entry.verifierOutput.violations} violations`;\n const resultColor = entry.verifierOutput.violations > 0 ? chalk.red : chalk.green;\n console.log(\n chalk.dim(` Result: `) +\n resultColor(violationText) +\n chalk.dim(` in ${entry.verifierOutput.duration}ms`)\n );\n }\n }\n }\n\n console.log('');\n }\n }\n\n // Summary\n const applied = this.entries.filter(e => e.applied).length;\n const skipped = this.entries.filter(e => !e.applied).length;\n\n console.log(chalk.bold('Summary:'));\n console.log(` Constraints Applied: ${chalk.green(applied)}`);\n console.log(` Constraints Skipped: ${chalk.dim(skipped)}`);\n }\n\n /**\n * Get all entries\n */\n getEntries(): ExplanationEntry[] {\n return [...this.entries];\n }\n\n /**\n * Clear all entries\n */\n clear(): void {\n this.entries = [];\n }\n}\n","/**\n * Decision command group\n */\nimport { Command } from 'commander';\nimport { listDecisions } from './list.js';\nimport { showDecision } from './show.js';\nimport { validateDecisions } from './validate.js';\nimport { createDecision } from './create.js';\n\nexport const decisionCommand = new Command('decision')\n .description('Manage architectural decisions')\n .addCommand(listDecisions)\n .addCommand(showDecision)\n .addCommand(validateDecisions)\n .addCommand(createDecision);\n","/**\n * List decisions command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { table } from 'table';\nimport { createRegistry } from '../../../registry/registry.js';\nimport type { DecisionStatus, ConstraintType } from '../../../core/types/index.js';\n\ninterface ListOptions {\n status?: string;\n tag?: string;\n json?: boolean;\n}\n\nexport const listDecisions = new Command('list')\n .description('List all architectural decisions')\n .option('-s, --status <status>', 'Filter by status (draft, active, deprecated, superseded)')\n .option('-t, --tag <tag>', 'Filter by tag')\n .option('--json', 'Output as JSON')\n .action(async (options: ListOptions) => {\n const registry = createRegistry();\n const result = await registry.load();\n\n // Show loading errors as warnings\n if (result.errors.length > 0) {\n console.warn(chalk.yellow('\\nWarnings:'));\n for (const err of result.errors) {\n console.warn(chalk.yellow(` - ${err.filePath}: ${err.error}`));\n }\n console.log('');\n }\n\n // Apply filters\n const filter: { status?: DecisionStatus[]; tags?: string[] } = {};\n if (options.status) {\n filter.status = [options.status as DecisionStatus];\n }\n if (options.tag) {\n filter.tags = [options.tag];\n }\n\n const decisions = registry.getAll(filter);\n\n if (decisions.length === 0) {\n console.log(chalk.yellow('No decisions found.'));\n return;\n }\n\n if (options.json) {\n console.log(JSON.stringify(decisions, null, 2));\n return;\n }\n\n // Create table\n const data: string[][] = [\n [\n chalk.bold('ID'),\n chalk.bold('Title'),\n chalk.bold('Status'),\n chalk.bold('Constraints'),\n chalk.bold('Tags'),\n ],\n ];\n\n for (const decision of decisions) {\n const statusColor = getStatusColor(decision.metadata.status);\n const constraintTypes = getConstraintTypeSummary(decision.constraints.map(c => c.type));\n\n data.push([\n decision.metadata.id,\n truncate(decision.metadata.title, 40),\n statusColor(decision.metadata.status),\n constraintTypes,\n (decision.metadata.tags || []).join(', ') || '-',\n ]);\n }\n\n console.log(table(data, {\n border: {\n topBody: '',\n topJoin: '',\n topLeft: '',\n topRight: '',\n bottomBody: '',\n bottomJoin: '',\n bottomLeft: '',\n bottomRight: '',\n bodyLeft: '',\n bodyRight: '',\n bodyJoin: ' ',\n joinBody: '',\n joinLeft: '',\n joinRight: '',\n joinJoin: '',\n },\n drawHorizontalLine: (index) => index === 1,\n }));\n\n console.log(chalk.dim(`Total: ${decisions.length} decision(s)`));\n });\n\nfunction getStatusColor(status: DecisionStatus): (text: string) => string {\n switch (status) {\n case 'active':\n return chalk.green;\n case 'draft':\n return chalk.yellow;\n case 'deprecated':\n return chalk.gray;\n case 'superseded':\n return chalk.blue;\n default:\n return chalk.white;\n }\n}\n\nfunction getConstraintTypeSummary(types: ConstraintType[]): string {\n const counts = {\n invariant: 0,\n convention: 0,\n guideline: 0,\n };\n\n for (const type of types) {\n counts[type]++;\n }\n\n const parts: string[] = [];\n if (counts.invariant > 0) parts.push(chalk.red(`${counts.invariant}I`));\n if (counts.convention > 0) parts.push(chalk.yellow(`${counts.convention}C`));\n if (counts.guideline > 0) parts.push(chalk.green(`${counts.guideline}G`));\n\n return parts.join(' ') || '-';\n}\n\nfunction truncate(str: string, length: number): string {\n if (str.length <= length) return str;\n return str.slice(0, length - 3) + '...';\n}\n","/**\n * Show decision command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createRegistry } from '../../../registry/registry.js';\nimport type { Decision, ConstraintType, Severity } from '../../../core/types/index.js';\n\ninterface ShowOptions {\n json?: boolean;\n}\n\nexport const showDecision = new Command('show')\n .description('Show details of a specific decision')\n .argument('<id>', 'Decision ID')\n .option('--json', 'Output as JSON')\n .action(async (id: string, options: ShowOptions) => {\n const registry = createRegistry();\n await registry.load();\n\n const decision = registry.get(id);\n\n if (options.json) {\n console.log(JSON.stringify(decision, null, 2));\n return;\n }\n\n printDecision(decision);\n });\n\nfunction printDecision(decision: Decision): void {\n const { metadata, decision: content, constraints } = decision;\n\n // Header\n console.log(chalk.bold.blue(`\\n${metadata.title}`));\n console.log(chalk.dim(`ID: ${metadata.id}`));\n console.log('');\n\n // Metadata\n console.log(chalk.bold('Status:'), getStatusBadge(metadata.status));\n console.log(chalk.bold('Owners:'), metadata.owners.join(', '));\n if (metadata.tags && metadata.tags.length > 0) {\n console.log(chalk.bold('Tags:'), metadata.tags.map(t => chalk.cyan(t)).join(', '));\n }\n if (metadata.createdAt) {\n console.log(chalk.bold('Created:'), metadata.createdAt);\n }\n if (metadata.supersededBy) {\n console.log(chalk.bold('Superseded by:'), chalk.yellow(metadata.supersededBy));\n }\n console.log('');\n\n // Decision content\n console.log(chalk.bold.underline('Summary'));\n console.log(content.summary);\n console.log('');\n\n console.log(chalk.bold.underline('Rationale'));\n console.log(content.rationale);\n console.log('');\n\n if (content.context) {\n console.log(chalk.bold.underline('Context'));\n console.log(content.context);\n console.log('');\n }\n\n if (content.consequences && content.consequences.length > 0) {\n console.log(chalk.bold.underline('Consequences'));\n for (const consequence of content.consequences) {\n console.log(` • ${consequence}`);\n }\n console.log('');\n }\n\n // Constraints\n console.log(chalk.bold.underline(`Constraints (${constraints.length})`));\n for (const constraint of constraints) {\n const typeIcon = getTypeIcon(constraint.type);\n const severityBadge = getSeverityBadge(constraint.severity);\n\n console.log(`\\n ${typeIcon} ${chalk.bold(constraint.id)} ${severityBadge}`);\n console.log(` ${constraint.rule}`);\n console.log(chalk.dim(` Scope: ${constraint.scope}`));\n\n if (constraint.verifier) {\n console.log(chalk.dim(` Verifier: ${constraint.verifier}`));\n }\n\n if (constraint.exceptions && constraint.exceptions.length > 0) {\n console.log(chalk.dim(` Exceptions: ${constraint.exceptions.length}`));\n }\n }\n console.log('');\n\n // Verification\n if (decision.verification?.automated && decision.verification.automated.length > 0) {\n console.log(chalk.bold.underline('Automated Verification'));\n for (const check of decision.verification.automated) {\n console.log(` • ${check.check} (${check.frequency})`);\n console.log(chalk.dim(` Target: ${check.target}`));\n }\n console.log('');\n }\n\n // Links\n if (decision.links) {\n const { related, supersedes, references } = decision.links;\n\n if (related && related.length > 0) {\n console.log(chalk.bold('Related:'), related.join(', '));\n }\n if (supersedes && supersedes.length > 0) {\n console.log(chalk.bold('Supersedes:'), supersedes.join(', '));\n }\n if (references && references.length > 0) {\n console.log(chalk.bold('References:'));\n for (const ref of references) {\n console.log(` • ${ref}`);\n }\n }\n }\n}\n\nfunction getStatusBadge(status: string): string {\n switch (status) {\n case 'active':\n return chalk.bgGreen.black(' ACTIVE ');\n case 'draft':\n return chalk.bgYellow.black(' DRAFT ');\n case 'deprecated':\n return chalk.bgGray.white(' DEPRECATED ');\n case 'superseded':\n return chalk.bgBlue.white(' SUPERSEDED ');\n default:\n return status;\n }\n}\n\nfunction getTypeIcon(type: ConstraintType): string {\n switch (type) {\n case 'invariant':\n return chalk.red('●');\n case 'convention':\n return chalk.yellow('●');\n case 'guideline':\n return chalk.green('●');\n default:\n return '○';\n }\n}\n\nfunction getSeverityBadge(severity: Severity): string {\n switch (severity) {\n case 'critical':\n return chalk.bgRed.white(' CRITICAL ');\n case 'high':\n return chalk.bgYellow.black(' HIGH ');\n case 'medium':\n return chalk.bgCyan.black(' MEDIUM ');\n case 'low':\n return chalk.bgGray.white(' LOW ');\n default:\n return severity;\n }\n}\n","/**\n * Validate decisions command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { validateDecisionFile } from '../../../registry/loader.js';\nimport { getDecisionsDir, readFilesInDir, pathExists, getSpecBridgeDir } from '../../../utils/fs.js';\nimport { NotInitializedError } from '../../../core/errors/index.js';\n\ninterface ValidateOptions {\n file?: string;\n}\n\nexport const validateDecisions = new Command('validate')\n .description('Validate decision files')\n .option('-f, --file <path>', 'Validate a specific file')\n .action(async (options: ValidateOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Validating decisions...').start();\n\n try {\n let files: string[] = [];\n\n if (options.file) {\n files = [options.file];\n } else {\n const decisionsDir = getDecisionsDir(cwd);\n const decisionFiles = await readFilesInDir(\n decisionsDir,\n (f) => f.endsWith('.decision.yaml')\n );\n files = decisionFiles.map((f) => join(decisionsDir, f));\n }\n\n if (files.length === 0) {\n spinner.info('No decision files found.');\n return;\n }\n\n let valid = 0;\n let invalid = 0;\n const errors: { file: string; errors: string[] }[] = [];\n\n for (const file of files) {\n const result = await validateDecisionFile(file);\n if (result.valid) {\n valid++;\n } else {\n invalid++;\n errors.push({ file, errors: result.errors });\n }\n }\n\n spinner.stop();\n\n // Print results\n if (invalid === 0) {\n console.log(chalk.green(`✓ All ${valid} decision file(s) are valid.`));\n } else {\n console.log(chalk.red(`✗ ${invalid} of ${files.length} decision file(s) have errors.\\n`));\n\n for (const { file, errors: fileErrors } of errors) {\n console.log(chalk.red(`File: ${file}`));\n for (const err of fileErrors) {\n console.log(chalk.dim(` - ${err}`));\n }\n console.log('');\n }\n\n process.exit(1);\n }\n } catch (error) {\n spinner.fail('Validation failed');\n throw error;\n }\n });\n","/**\n * Create decision command\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { join } from 'node:path';\nimport { writeTextFile, getDecisionsDir, pathExists, getSpecBridgeDir } from '../../../utils/fs.js';\nimport { stringifyYaml } from '../../../utils/yaml.js';\nimport { NotInitializedError } from '../../../core/errors/index.js';\n\ninterface CreateOptions {\n title: string;\n summary: string;\n type?: 'invariant' | 'convention' | 'guideline';\n severity?: 'critical' | 'high' | 'medium' | 'low';\n scope?: string;\n owner?: string;\n}\n\nexport const createDecision = new Command('create')\n .description('Create a new decision file')\n .argument('<id>', 'Decision ID (e.g., auth-001)')\n .requiredOption('-t, --title <title>', 'Decision title')\n .requiredOption('-s, --summary <summary>', 'One-sentence summary')\n .option('--type <type>', 'Default constraint type (invariant, convention, guideline)', 'convention')\n .option('--severity <severity>', 'Default constraint severity (critical, high, medium, low)', 'medium')\n .option('--scope <scope>', 'Default constraint scope (glob pattern)', 'src/**/*.ts')\n .option('-o, --owner <owner>', 'Owner name', 'team')\n .action(async (id: string, options: CreateOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n // Validate ID format\n if (!/^[a-z0-9-]+$/.test(id)) {\n console.error(chalk.red('Error: Decision ID must be lowercase alphanumeric with hyphens only.'));\n process.exit(1);\n }\n\n const decisionsDir = getDecisionsDir(cwd);\n const filePath = join(decisionsDir, `${id}.decision.yaml`);\n\n // Check if file already exists\n if (await pathExists(filePath)) {\n console.error(chalk.red(`Error: Decision file already exists: ${filePath}`));\n process.exit(1);\n }\n\n // Create decision structure\n const decision = {\n kind: 'Decision',\n metadata: {\n id,\n title: options.title,\n status: 'draft',\n owners: [options.owner || 'team'],\n createdAt: new Date().toISOString(),\n tags: [],\n },\n decision: {\n summary: options.summary,\n rationale: 'TODO: Explain why this decision was made.',\n context: 'TODO: Describe the context and background.',\n consequences: [\n 'TODO: List positive consequences',\n 'TODO: List negative consequences or trade-offs',\n ],\n },\n constraints: [\n {\n id: `${id}-c1`,\n type: options.type || 'convention',\n rule: 'TODO: Describe the constraint rule',\n severity: options.severity || 'medium',\n scope: options.scope || 'src/**/*.ts',\n },\n ],\n verification: {\n automated: [],\n },\n };\n\n // Write file\n await writeTextFile(filePath, stringifyYaml(decision));\n\n console.log(chalk.green(`✓ Created decision: ${filePath}`));\n console.log('');\n console.log(chalk.cyan('Next steps:'));\n console.log(` 1. Edit the file to add rationale, context, and consequences`);\n console.log(` 2. Define constraints with appropriate scopes`);\n console.log(` 3. Run ${chalk.bold('specbridge decision validate')} to check syntax`);\n console.log(` 4. Change status from ${chalk.yellow('draft')} to ${chalk.green('active')} when ready`);\n });\n","/**\n * Hook command - Git hook integration\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, readTextFile, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { VerificationLevel } from '../../core/types/index.js';\n\nconst HOOK_SCRIPT = `#!/bin/sh\n# SpecBridge pre-commit hook\n# Runs verification on staged files\n\necho \"Running SpecBridge verification...\"\n\n# Run specbridge hook (it will detect staged files automatically)\nnpx specbridge hook run --level commit\n\nexit $?\n`;\n\nexport function createHookCommand(): Command {\n const hookCommand = new Command('hook')\n .description('Manage Git hooks for verification');\n\n hookCommand\n .command('install')\n .description('Install Git pre-commit hook')\n .option('-f, --force', 'Overwrite existing hook')\n .option('--husky', 'Install for husky')\n .option('--lefthook', 'Install for lefthook')\n .action(async (options: { force?: boolean; husky?: boolean; lefthook?: boolean }) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Detecting hook system...').start();\n\n try {\n // Detect hook system\n let hookPath: string;\n let hookContent: string;\n\n if (options.husky) {\n // Install for husky\n hookPath = join(cwd, '.husky', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing husky pre-commit hook...';\n } else if (options.lefthook) {\n // Show lefthook config\n spinner.succeed('Lefthook detected');\n console.log('');\n console.log(chalk.cyan('Add this to your lefthook.yml:'));\n console.log('');\n console.log(chalk.dim(`pre-commit:\n commands:\n specbridge:\n glob: \"*.{ts,tsx}\"\n run: npx specbridge hook run --level commit --files {staged_files}\n`));\n return;\n } else {\n // Check for .husky directory\n if (await pathExists(join(cwd, '.husky'))) {\n hookPath = join(cwd, '.husky', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing husky pre-commit hook...';\n } else if (await pathExists(join(cwd, 'lefthook.yml'))) {\n spinner.succeed('Lefthook detected');\n console.log('');\n console.log(chalk.cyan('Add this to your lefthook.yml:'));\n console.log('');\n console.log(chalk.dim(`pre-commit:\n commands:\n specbridge:\n glob: \"*.{ts,tsx}\"\n run: npx specbridge hook run --level commit --files {staged_files}\n`));\n return;\n } else {\n // Default to .git/hooks\n hookPath = join(cwd, '.git', 'hooks', 'pre-commit');\n hookContent = HOOK_SCRIPT;\n spinner.text = 'Installing Git pre-commit hook...';\n }\n }\n\n // Check if hook already exists\n if (await pathExists(hookPath) && !options.force) {\n spinner.fail('Hook already exists');\n console.log(chalk.yellow(`Use --force to overwrite: ${hookPath}`));\n return;\n }\n\n // Write hook\n await writeTextFile(hookPath, hookContent);\n\n // Make executable (Unix)\n const { execSync } = await import('node:child_process');\n try {\n execSync(`chmod +x \"${hookPath}\"`, { stdio: 'ignore' });\n } catch {\n // Ignore on Windows\n }\n\n spinner.succeed('Pre-commit hook installed');\n console.log(chalk.dim(` Path: ${hookPath}`));\n console.log('');\n console.log(chalk.cyan('The hook will run on each commit and verify staged files.'));\n } catch (error) {\n spinner.fail('Failed to install hook');\n throw error;\n }\n });\n\n hookCommand\n .command('run')\n .description('Run verification (called by hook)')\n .option('-l, --level <level>', 'Verification level', 'commit')\n .option('-f, --files <files>', 'Space or comma-separated file list')\n .action(async (options: { level?: string; files?: string }) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n try {\n const config = await loadConfig(cwd);\n const level = (options.level || 'commit') as VerificationLevel;\n\n // Parse files\n let files = options.files\n ? options.files.split(/[\\s,]+/).filter(f => f.length > 0)\n : undefined;\n\n if (!files || files.length === 0) {\n // Auto-detect staged files\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileAsync = promisify(execFile);\n\n try {\n const { stdout } = await execFileAsync('git', ['diff', '--cached', '--name-only', '--diff-filter=AM'], { cwd });\n files = stdout\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((f) => /\\.(ts|tsx|js|jsx)$/.test(f));\n } catch {\n files = [];\n }\n }\n\n if (!files || files.length === 0) {\n process.exit(0);\n }\n\n // Run verification\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level,\n files,\n cwd,\n });\n\n // Output result\n if (result.violations.length === 0) {\n console.log(chalk.green('✓ SpecBridge: All checks passed'));\n process.exit(0);\n }\n\n // Print violations concisely\n console.log(chalk.red(`✗ SpecBridge: ${result.violations.length} violation(s) found`));\n console.log('');\n\n for (const v of result.violations) {\n const location = v.line ? `:${v.line}` : '';\n console.log(` ${v.file}${location}: ${v.message}`);\n console.log(chalk.dim(` [${v.severity}] ${v.decisionId}/${v.constraintId}`));\n }\n\n console.log('');\n console.log(chalk.yellow('Run `specbridge verify` for full details.'));\n\n process.exit(result.success ? 0 : 1);\n } catch (error) {\n console.error(chalk.red('SpecBridge verification failed'));\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n hookCommand\n .command('uninstall')\n .description('Remove Git pre-commit hook')\n .action(async () => {\n const cwd = process.cwd();\n const spinner = ora('Removing hook...').start();\n\n try {\n const hookPaths = [\n join(cwd, '.husky', 'pre-commit'),\n join(cwd, '.git', 'hooks', 'pre-commit'),\n ];\n\n let removed = false;\n for (const hookPath of hookPaths) {\n if (await pathExists(hookPath)) {\n const content = await readTextFile(hookPath);\n if (content.includes('SpecBridge')) {\n const { unlink } = await import('node:fs/promises');\n await unlink(hookPath);\n spinner.succeed(`Removed hook: ${hookPath}`);\n removed = true;\n }\n }\n }\n\n if (!removed) {\n spinner.info('No SpecBridge hooks found');\n }\n } catch (error) {\n spinner.fail('Failed to remove hook');\n throw error;\n }\n });\n\n return hookCommand;\n}\n\nexport const hookCommand = createHookCommand();\n","/**\n * Report command - Generate compliance reports\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { generateReport } from '../../reporting/reporter.js';\nimport { formatConsoleReport } from '../../reporting/formats/console.js';\nimport { formatMarkdownReport } from '../../reporting/formats/markdown.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, getReportsDir, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { ReportStorage } from '../../reporting/storage.js';\nimport { detectDrift, analyzeTrend } from '../../reporting/drift.js';\n\ninterface ReportOptions {\n format?: string;\n output?: string;\n save?: boolean;\n all?: boolean;\n trend?: boolean;\n drift?: boolean;\n days?: string;\n legacyCompliance?: 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 .option('--trend', 'Show compliance trend over time')\n .option('--drift', 'Analyze drift since last report')\n .option('--days <n>', 'Number of days for trend analysis', '30')\n .option('--legacy-compliance', 'Use v1.3 compliance formula (for comparison)')\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 legacyCompliance: options.legacyCompliance,\n });\n\n spinner.succeed('Report generated');\n\n // Initialize report storage\n const storage = new ReportStorage(cwd);\n\n // Auto-save all reports to history\n await storage.save(report);\n\n // Handle trend analysis\n if (options.trend) {\n console.log('\\n' + chalk.blue.bold('=== Compliance Trend Analysis ===\\n'));\n\n const days = parseInt(options.days || '30', 10);\n const history = await storage.loadHistory(days);\n\n if (history.length < 2) {\n console.log(chalk.yellow(`Not enough data for trend analysis. Found ${history.length} report(s), need at least 2.`));\n } else {\n const trend = await analyzeTrend(history);\n\n console.log(chalk.bold(`Period: ${trend.period.start} to ${trend.period.end} (${trend.period.days} days)`));\n console.log(`\\nOverall Compliance: ${trend.overall.startCompliance}% → ${trend.overall.endCompliance}% (${trend.overall.change > 0 ? '+' : ''}${trend.overall.change.toFixed(1)}%)`);\n\n const trendEmoji = trend.overall.trend === 'improving' ? '📈' : trend.overall.trend === 'degrading' ? '📉' : '➡️';\n const trendColor = trend.overall.trend === 'improving' ? chalk.green : trend.overall.trend === 'degrading' ? chalk.red : chalk.yellow;\n console.log(trendColor(`${trendEmoji} Trend: ${trend.overall.trend.toUpperCase()}`));\n\n // Show top degraded decisions\n const degrading = trend.decisions.filter(d => d.trend === 'degrading').slice(0, 3);\n if (degrading.length > 0) {\n console.log(chalk.red('\\n⚠️ Most Degraded Decisions:'));\n degrading.forEach(d => {\n console.log(` • ${d.title}: ${d.startCompliance}% → ${d.endCompliance}% (${d.change.toFixed(1)}%)`);\n });\n }\n\n // Show top improved decisions\n const improving = trend.decisions.filter(d => d.trend === 'improving').slice(0, 3);\n if (improving.length > 0) {\n console.log(chalk.green('\\n✅ Most Improved Decisions:'));\n improving.forEach(d => {\n console.log(` • ${d.title}: ${d.startCompliance}% → ${d.endCompliance}% (+${d.change.toFixed(1)}%)`);\n });\n }\n }\n\n console.log(''); // Empty line\n }\n\n // Handle drift analysis\n if (options.drift) {\n console.log('\\n' + chalk.blue.bold('=== Drift Analysis ===\\n'));\n\n const history = await storage.loadHistory(2);\n\n if (history.length < 2) {\n console.log(chalk.yellow('Not enough data for drift analysis. Need at least 2 reports.'));\n } else {\n const currentEntry = history[0];\n const previousEntry = history[1];\n\n if (!currentEntry || !previousEntry) {\n console.log(chalk.yellow('Invalid history data.'));\n return;\n }\n\n const drift = await detectDrift(currentEntry.report, previousEntry.report);\n\n console.log(chalk.bold(`Comparing: ${previousEntry.timestamp} vs ${currentEntry.timestamp}`));\n console.log(`\\nCompliance Change: ${drift.complianceChange > 0 ? '+' : ''}${drift.complianceChange.toFixed(1)}%`);\n\n const driftEmoji = drift.trend === 'improving' ? '📈' : drift.trend === 'degrading' ? '📉' : '➡️';\n const driftColor = drift.trend === 'improving' ? chalk.green : drift.trend === 'degrading' ? chalk.red : chalk.yellow;\n console.log(driftColor(`${driftEmoji} Overall Trend: ${drift.trend.toUpperCase()}`));\n\n // Show violation changes\n if (drift.summary.newViolations.total > 0) {\n console.log(chalk.red(`\\n⚠️ New Violations: ${drift.summary.newViolations.total}`));\n if (drift.summary.newViolations.critical > 0) {\n console.log(` • Critical: ${drift.summary.newViolations.critical}`);\n }\n if (drift.summary.newViolations.high > 0) {\n console.log(` • High: ${drift.summary.newViolations.high}`);\n }\n if (drift.summary.newViolations.medium > 0) {\n console.log(` • Medium: ${drift.summary.newViolations.medium}`);\n }\n if (drift.summary.newViolations.low > 0) {\n console.log(` • Low: ${drift.summary.newViolations.low}`);\n }\n }\n\n if (drift.summary.fixedViolations.total > 0) {\n console.log(chalk.green(`\\n✅ Fixed Violations: ${drift.summary.fixedViolations.total}`));\n if (drift.summary.fixedViolations.critical > 0) {\n console.log(` • Critical: ${drift.summary.fixedViolations.critical}`);\n }\n if (drift.summary.fixedViolations.high > 0) {\n console.log(` • High: ${drift.summary.fixedViolations.high}`);\n }\n if (drift.summary.fixedViolations.medium > 0) {\n console.log(` • Medium: ${drift.summary.fixedViolations.medium}`);\n }\n if (drift.summary.fixedViolations.low > 0) {\n console.log(` • Low: ${drift.summary.fixedViolations.low}`);\n }\n }\n\n // Show most degraded decisions\n if (drift.mostDegraded.length > 0) {\n console.log(chalk.red('\\n📉 Most Degraded:'));\n drift.mostDegraded.forEach(d => {\n console.log(` • ${d.title}: ${d.previousCompliance}% → ${d.currentCompliance}% (${d.complianceChange.toFixed(1)}%)`);\n if (d.newViolations > 0) {\n console.log(` +${d.newViolations} new violation(s)`);\n }\n });\n }\n\n // Show most improved decisions\n if (drift.mostImproved.length > 0) {\n console.log(chalk.green('\\n📈 Most Improved:'));\n drift.mostImproved.forEach(d => {\n console.log(` • ${d.title}: ${d.previousCompliance}% → ${d.currentCompliance}% (+${d.complianceChange.toFixed(1)}%)`);\n if (d.fixedViolations > 0) {\n console.log(` -${d.fixedViolations} fixed violation(s)`);\n }\n });\n }\n }\n\n console.log(''); // Empty line\n }\n\n // Format output\n let output: string;\n let extension: string;\n\n switch (options.format) {\n case 'json':\n output = JSON.stringify(report, null, 2);\n extension = 'json';\n break;\n case 'markdown':\n case 'md':\n output = formatMarkdownReport(report);\n extension = 'md';\n break;\n case 'console':\n default:\n output = formatConsoleReport(report);\n extension = 'txt';\n break;\n }\n\n // Output to console (skip if drift/trend already shown)\n if (!options.trend && !options.drift) {\n if (options.format !== 'json' || !options.output) {\n console.log(output);\n }\n }\n\n // Save to file\n if (options.output || options.save) {\n const outputPath = options.output || join(\n getReportsDir(cwd),\n `health-${new Date().toISOString().split('T')[0]}.${extension}`\n );\n\n await writeTextFile(outputPath, output);\n console.log(chalk.green(`\\nReport saved to: ${outputPath}`));\n\n // Also save latest\n if (options.save && !options.output) {\n const latestPath = join(getReportsDir(cwd), `health-latest.${extension}`);\n await writeTextFile(latestPath, output);\n }\n }\n } catch (error) {\n spinner.fail('Failed to generate report');\n throw error;\n }\n });\n","/**\n * Compliance reporter\n */\nimport type {\n ComplianceReport,\n DecisionCompliance,\n SpecBridgeConfig,\n} from '../core/types/index.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { createVerificationEngine } from '../verification/engine.js';\n\nexport interface ReportOptions {\n includeAll?: boolean;\n cwd?: string;\n /** Use v1.3 compliance formula instead of v2.0 severity-weighted formula */\n legacyCompliance?: boolean;\n}\n\n/**\n * Generate a compliance report\n */\nexport async function generateReport(\n config: SpecBridgeConfig,\n options: ReportOptions = {}\n): Promise<ComplianceReport> {\n const { includeAll = false, cwd = process.cwd() } = options;\n\n // Load registry\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n\n // Run full verification\n const engine = createVerificationEngine(registry);\n const result = await engine.verify(config, { level: 'full', cwd });\n\n // Get all decisions\n const decisions = includeAll ? registry.getAll() : registry.getActive();\n\n // Calculate per-decision compliance\n const byDecision: DecisionCompliance[] = [];\n\n for (const decision of decisions) {\n const decisionViolations = result.violations.filter(\n v => v.decisionId === decision.metadata.id\n );\n\n const constraintCount = decision.constraints.length;\n const violationCount = decisionViolations.length;\n\n // Calculate compliance based on mode\n let compliance: number;\n let violationsBySeverity: DecisionCompliance['violationsBySeverity'];\n let weightedScore: number | undefined;\n let coverageRate: number | undefined;\n\n if (options.legacyCompliance) {\n // v1.3 formula: Simple count-based\n compliance = violationCount === 0\n ? 100\n : Math.max(0, 100 - Math.min(violationCount * 10, 100));\n } else {\n // v2.0 formula: Severity-weighted with coverage penalty\n const weights = { critical: 40, high: 25, medium: 10, low: 2 };\n\n // Count violations by severity\n const bySeverity = {\n critical: decisionViolations.filter(v => v.severity === 'critical').length,\n high: decisionViolations.filter(v => v.severity === 'high').length,\n medium: decisionViolations.filter(v => v.severity === 'medium').length,\n low: decisionViolations.filter(v => v.severity === 'low').length,\n };\n\n // Calculate weighted score\n weightedScore = decisionViolations.reduce(\n (score, v) => score + weights[v.severity],\n 0\n );\n\n // Base compliance\n compliance = Math.max(0, 100 - weightedScore);\n\n // Apply coverage penalty (up to 20% reduction)\n if (decisionViolations.length > 0 && constraintCount > 0) {\n const violationRate = decisionViolations.length / constraintCount;\n compliance = compliance * (1 - violationRate * 0.2);\n coverageRate = violationRate;\n }\n\n compliance = Math.round(compliance);\n violationsBySeverity = bySeverity;\n }\n\n byDecision.push({\n decisionId: decision.metadata.id,\n title: decision.metadata.title,\n status: decision.metadata.status,\n constraints: constraintCount,\n violations: violationCount,\n compliance,\n violationsBySeverity,\n weightedScore,\n coverageRate,\n });\n }\n\n // Sort by compliance (lowest first to highlight problems)\n byDecision.sort((a, b) => a.compliance - b.compliance);\n\n // Calculate summary\n const totalDecisions = decisions.length;\n const activeDecisions = decisions.filter(d => d.metadata.status === 'active').length;\n const totalConstraints = decisions.reduce((sum, d) => sum + d.constraints.length, 0);\n\n const violationsBySeverity = {\n critical: result.violations.filter(v => v.severity === 'critical').length,\n high: result.violations.filter(v => v.severity === 'high').length,\n medium: result.violations.filter(v => v.severity === 'medium').length,\n low: result.violations.filter(v => v.severity === 'low').length,\n };\n\n // Overall compliance score\n const overallCompliance = byDecision.length > 0\n ? Math.round(byDecision.reduce((sum, d) => sum + d.compliance, 0) / byDecision.length)\n : 100;\n\n return {\n timestamp: new Date().toISOString(),\n project: config.project.name,\n summary: {\n totalDecisions,\n activeDecisions,\n totalConstraints,\n violations: violationsBySeverity,\n compliance: overallCompliance,\n },\n byDecision,\n };\n}\n\n/**\n * Check if compliance has degraded from previous report\n */\nexport function checkDegradation(\n current: ComplianceReport,\n previous: ComplianceReport | null\n): { degraded: boolean; details: string[] } {\n if (!previous) {\n return { degraded: false, details: [] };\n }\n\n const details: string[] = [];\n let degraded = false;\n\n // Check overall compliance\n if (current.summary.compliance < previous.summary.compliance) {\n degraded = true;\n details.push(\n `Overall compliance dropped from ${previous.summary.compliance}% to ${current.summary.compliance}%`\n );\n }\n\n // Check for new critical/high violations\n const newCritical = current.summary.violations.critical - previous.summary.violations.critical;\n const newHigh = current.summary.violations.high - previous.summary.violations.high;\n\n if (newCritical > 0) {\n degraded = true;\n details.push(`${newCritical} new critical violation(s)`);\n }\n\n if (newHigh > 0) {\n degraded = true;\n details.push(`${newHigh} new high severity violation(s)`);\n }\n\n return { degraded, details };\n}\n\n/**\n * Reporter class for formatting verification results\n */\nexport class Reporter {\n /**\n * Generate formatted report from verification result\n */\n generate(\n result: any,\n options: {\n format?: 'table' | 'json' | 'markdown';\n includePassedChecks?: boolean;\n groupBy?: 'severity' | 'file';\n colorize?: boolean;\n } = {}\n ): string {\n const { format = 'table', groupBy } = options;\n\n switch (format) {\n case 'json':\n return JSON.stringify(result, null, 2);\n\n case 'markdown':\n return this.formatAsMarkdown(result);\n\n case 'table':\n default:\n return groupBy ? this.formatAsTableGrouped(result, groupBy) : this.formatAsTable(result);\n }\n }\n\n /**\n * Generate compliance overview from multiple results\n */\n generateComplianceReport(results: any[]): string {\n const lines: string[] = [];\n lines.push('# Compliance Report\\n');\n\n if (results.length === 0) {\n lines.push('No results to report.\\n');\n return lines.join('\\n');\n }\n\n // Calculate overall stats\n const totalViolations = results.reduce(\n (sum, r) => sum + (r.summary?.totalViolations || r.violations?.length || 0),\n 0\n );\n const avgViolations = totalViolations / results.length;\n\n lines.push(`## Overall Statistics\\n`);\n lines.push(`- Total Results: ${results.length}`);\n lines.push(`- Total Violations: ${totalViolations}`);\n lines.push(`- Average Violations per Result: ${avgViolations.toFixed(1)}`);\n\n // Calculate compliance percentage (simplified)\n const complianceRate = results.length > 0\n ? ((results.filter(r => (r.violations?.length || 0) === 0).length / results.length) * 100)\n : 100;\n lines.push(`- Compliance Rate: ${complianceRate.toFixed(1)}%\\n`);\n\n return lines.join('\\n');\n }\n\n private formatAsTable(result: any): string {\n const lines: string[] = [];\n\n lines.push('Verification Report');\n lines.push('='.repeat(50));\n lines.push('');\n\n // Summary\n if (result.summary) {\n lines.push('Summary:');\n lines.push(` Decisions Checked: ${result.summary.decisionsChecked || 0}`);\n lines.push(` Files Checked: ${result.summary.filesChecked || 0}`);\n lines.push(` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`);\n lines.push(` Critical: ${result.summary.critical || 0}`);\n lines.push(` High: ${result.summary.high || 0}`);\n lines.push(` Medium: ${result.summary.medium || 0}`);\n lines.push(` Low: ${result.summary.low || 0}`);\n lines.push(` Duration: ${result.summary.duration || 0}ms`);\n lines.push('');\n }\n\n // Violations\n const totalViolations = result.summary?.totalViolations ?? result.violations?.length ?? 0;\n if (totalViolations > 0 && result.violations && result.violations.length > 0) {\n lines.push('Violations:');\n lines.push('-'.repeat(50));\n\n result.violations.forEach((v: any) => {\n const severity = v.severity.toLowerCase();\n lines.push(` [${v.severity.toUpperCase()}] ${v.decisionId} - ${v.constraintId} (${severity})`);\n lines.push(` ${v.message}`);\n lines.push(` Location: ${v.location?.file || v.file}:${v.location?.line || 0}:${v.location?.column || 0}`);\n lines.push('');\n });\n } else {\n lines.push('No violations found.');\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private formatAsTableGrouped(result: any, groupBy: 'severity' | 'file'): string {\n const lines: string[] = [];\n\n lines.push('Verification Report');\n lines.push('='.repeat(50));\n lines.push('');\n\n // Summary\n if (result.summary) {\n lines.push('Summary:');\n lines.push(` Total Violations: ${result.summary.totalViolations || result.violations?.length || 0}`);\n lines.push('');\n }\n\n // Group violations\n if (result.violations && result.violations.length > 0) {\n if (groupBy === 'severity') {\n const grouped = new Map<string, any[]>();\n result.violations.forEach((v: any) => {\n const key = v.severity;\n if (!grouped.has(key)) grouped.set(key, []);\n grouped.get(key)!.push(v);\n });\n\n for (const [severity, violations] of grouped.entries()) {\n lines.push(`Severity: ${severity}`);\n lines.push('-'.repeat(30));\n violations.forEach(v => {\n lines.push(` ${v.decisionId} - ${v.message}`);\n });\n lines.push('');\n }\n } else if (groupBy === 'file') {\n const grouped = new Map<string, any[]>();\n result.violations.forEach((v: any) => {\n const key = v.location?.file || v.file || 'unknown';\n if (!grouped.has(key)) grouped.set(key, []);\n grouped.get(key)!.push(v);\n });\n\n for (const [file, violations] of grouped.entries()) {\n lines.push(`File: ${file}`);\n lines.push('-'.repeat(30));\n violations.forEach(v => {\n lines.push(` [${v.severity}] ${v.message}`);\n });\n lines.push('');\n }\n }\n } else {\n lines.push('No violations found.');\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private formatAsMarkdown(result: any): string {\n const lines: string[] = [];\n\n lines.push('## Verification Report\\n');\n\n // Summary\n if (result.summary) {\n lines.push('### Summary\\n');\n lines.push(`- **Decisions Checked:** ${result.summary.decisionsChecked || 0}`);\n lines.push(`- **Files Checked:** ${result.summary.filesChecked || 0}`);\n lines.push(`- **Total Violations:** ${result.summary.totalViolations || result.violations?.length || 0}`);\n lines.push(`- **Critical:** ${result.summary.critical || 0}`);\n lines.push(`- **High:** ${result.summary.high || 0}`);\n lines.push(`- **Medium:** ${result.summary.medium || 0}`);\n lines.push(`- **Low:** ${result.summary.low || 0}\\n`);\n }\n\n // Violations\n if (result.violations && result.violations.length > 0) {\n lines.push('### Violations\\n');\n\n result.violations.forEach((v: any) => {\n lines.push(`#### [${v.severity.toUpperCase()}] ${v.decisionId}`);\n lines.push(`**Message:** ${v.message}`);\n lines.push(`**Location:** \\`${v.location?.file || v.file}:${v.location?.line || 0}\\`\\n`);\n });\n } else {\n lines.push('No violations found.\\n');\n }\n\n return lines.join('\\n');\n }\n}\n","/**\n * Console output format for reports\n */\nimport chalk from 'chalk';\nimport { table } from 'table';\nimport type { ComplianceReport } from '../../core/types/index.js';\n\n/**\n * Format report for console output\n */\nexport function formatConsoleReport(report: ComplianceReport): string {\n const lines: string[] = [];\n\n // Header\n lines.push('');\n lines.push(chalk.bold.blue('SpecBridge Compliance Report'));\n lines.push(chalk.dim(`Generated: ${new Date(report.timestamp).toLocaleString()}`));\n lines.push(chalk.dim(`Project: ${report.project}`));\n lines.push('');\n\n // Overall compliance\n const complianceColor = getComplianceColor(report.summary.compliance);\n lines.push(chalk.bold('Overall Compliance'));\n lines.push(` ${complianceColor(formatComplianceBar(report.summary.compliance))} ${complianceColor(`${report.summary.compliance}%`)}`);\n lines.push('');\n\n // Summary stats\n lines.push(chalk.bold('Summary'));\n lines.push(` Decisions: ${report.summary.activeDecisions} active / ${report.summary.totalDecisions} total`);\n lines.push(` Constraints: ${report.summary.totalConstraints}`);\n lines.push('');\n\n // Violations\n lines.push(chalk.bold('Violations'));\n const { violations } = report.summary;\n const violationParts: string[] = [];\n\n if (violations.critical > 0) {\n violationParts.push(chalk.red(`${violations.critical} critical`));\n }\n if (violations.high > 0) {\n violationParts.push(chalk.yellow(`${violations.high} high`));\n }\n if (violations.medium > 0) {\n violationParts.push(chalk.cyan(`${violations.medium} medium`));\n }\n if (violations.low > 0) {\n violationParts.push(chalk.dim(`${violations.low} low`));\n }\n\n if (violationParts.length > 0) {\n lines.push(` ${violationParts.join(' | ')}`);\n } else {\n lines.push(chalk.green(' No violations'));\n }\n lines.push('');\n\n // Per-decision breakdown\n if (report.byDecision.length > 0) {\n lines.push(chalk.bold('By Decision'));\n lines.push('');\n\n const tableData: string[][] = [\n [\n chalk.bold('Decision'),\n chalk.bold('Status'),\n chalk.bold('Constraints'),\n chalk.bold('Violations'),\n chalk.bold('Compliance'),\n ],\n ];\n\n for (const dec of report.byDecision) {\n const compColor = getComplianceColor(dec.compliance);\n const statusColor = getStatusColor(dec.status);\n\n tableData.push([\n truncate(dec.title, 40),\n statusColor(dec.status),\n String(dec.constraints),\n dec.violations > 0 ? chalk.red(String(dec.violations)) : chalk.green('0'),\n compColor(`${dec.compliance}%`),\n ]);\n }\n\n const tableOutput = table(tableData, {\n border: {\n topBody: '',\n topJoin: '',\n topLeft: '',\n topRight: '',\n bottomBody: '',\n bottomJoin: '',\n bottomLeft: '',\n bottomRight: '',\n bodyLeft: ' ',\n bodyRight: '',\n bodyJoin: ' ',\n joinBody: '',\n joinLeft: '',\n joinRight: '',\n joinJoin: '',\n },\n drawHorizontalLine: (index) => index === 1,\n });\n\n lines.push(tableOutput);\n }\n\n return lines.join('\\n');\n}\n\nfunction formatComplianceBar(compliance: number): string {\n const filled = Math.round(compliance / 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n}\n\nfunction getComplianceColor(compliance: number): (text: string) => string {\n if (compliance >= 90) return chalk.green;\n if (compliance >= 70) return chalk.yellow;\n if (compliance >= 50) return chalk.hex('#FFA500');\n return chalk.red;\n}\n\nfunction getStatusColor(status: string): (text: string) => string {\n switch (status) {\n case 'active':\n return chalk.green;\n case 'draft':\n return chalk.yellow;\n case 'deprecated':\n return chalk.gray;\n case 'superseded':\n return chalk.blue;\n default:\n return chalk.white;\n }\n}\n\nfunction truncate(str: string, length: number): string {\n if (str.length <= length) return str;\n return str.slice(0, length - 3) + '...';\n}\n","/**\n * Markdown format for reports\n */\nimport type { ComplianceReport } from '../../core/types/index.js';\n\n/**\n * Format report as Markdown\n */\nexport function formatMarkdownReport(report: ComplianceReport): string {\n const lines: string[] = [];\n\n // Header\n lines.push('# SpecBridge Compliance Report');\n lines.push('');\n lines.push(`**Project:** ${report.project}`);\n lines.push(`**Generated:** ${new Date(report.timestamp).toLocaleString()}`);\n lines.push('');\n\n // Overall compliance\n lines.push('## Overall Compliance');\n lines.push('');\n lines.push(`**Score:** ${report.summary.compliance}%`);\n lines.push('');\n lines.push(formatProgressBar(report.summary.compliance));\n lines.push('');\n\n // Summary\n lines.push('## Summary');\n lines.push('');\n lines.push(`- **Active Decisions:** ${report.summary.activeDecisions} / ${report.summary.totalDecisions}`);\n lines.push(`- **Total Constraints:** ${report.summary.totalConstraints}`);\n lines.push('');\n\n // Violations\n lines.push('### Violations');\n lines.push('');\n const { violations } = report.summary;\n const totalViolations = violations.critical + violations.high + violations.medium + violations.low;\n\n if (totalViolations === 0) {\n lines.push('No violations found.');\n } else {\n lines.push(`| Severity | Count |`);\n lines.push(`|----------|-------|`);\n lines.push(`| Critical | ${violations.critical} |`);\n lines.push(`| High | ${violations.high} |`);\n lines.push(`| Medium | ${violations.medium} |`);\n lines.push(`| Low | ${violations.low} |`);\n lines.push(`| **Total** | **${totalViolations}** |`);\n }\n lines.push('');\n\n // By Decision\n if (report.byDecision.length > 0) {\n lines.push('## By Decision');\n lines.push('');\n lines.push('| Decision | Status | Constraints | Violations | Compliance |');\n lines.push('|----------|--------|-------------|------------|------------|');\n\n for (const dec of report.byDecision) {\n const complianceEmoji = dec.compliance >= 90 ? '✅' : dec.compliance >= 70 ? '⚠️' : '❌';\n lines.push(\n `| ${dec.title} | ${dec.status} | ${dec.constraints} | ${dec.violations} | ${complianceEmoji} ${dec.compliance}% |`\n );\n }\n lines.push('');\n }\n\n // Footer\n lines.push('---');\n lines.push('');\n lines.push('*Generated by [SpecBridge](https://github.com/nouatzi/specbridge)*');\n\n return lines.join('\\n');\n}\n\nfunction formatProgressBar(percentage: number): string {\n const width = 20;\n const filled = Math.round((percentage / 100) * width);\n const empty = width - filled;\n const filledChar = '█';\n const emptyChar = '░';\n\n return `\\`${filledChar.repeat(filled)}${emptyChar.repeat(empty)}\\` ${percentage}%`;\n}\n","/**\n * Report storage - Save and load historical compliance reports\n */\nimport { join } from 'node:path';\nimport type { ComplianceReport } from '../core/types/index.js';\nimport {\n ensureDir,\n writeTextFile,\n readTextFile,\n readFilesInDir,\n pathExists,\n getSpecBridgeDir,\n} from '../utils/fs.js';\n\nexport interface StoredReport {\n timestamp: string;\n report: ComplianceReport;\n}\n\n/**\n * ReportStorage - Handles persistence and retrieval of historical reports\n */\nexport class ReportStorage {\n private storageDir: string;\n\n constructor(basePath: string) {\n this.storageDir = join(getSpecBridgeDir(basePath), 'reports', 'history');\n }\n\n /**\n * Save a compliance report to storage\n */\n async save(report: ComplianceReport): Promise<string> {\n await ensureDir(this.storageDir);\n\n // Use date as filename (one report per day, overwrites if exists)\n const date = new Date(report.timestamp).toISOString().split('T')[0];\n const filename = `report-${date}.json`;\n const filepath = join(this.storageDir, filename);\n\n await writeTextFile(filepath, JSON.stringify(report, null, 2));\n\n return filepath;\n }\n\n /**\n * Load the most recent report\n */\n async loadLatest(): Promise<StoredReport | null> {\n if (!await pathExists(this.storageDir)) {\n return null;\n }\n\n const files = await readFilesInDir(this.storageDir);\n if (files.length === 0) {\n return null;\n }\n\n // Sort files by date (descending)\n const sortedFiles = files\n .filter(f => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n if (sortedFiles.length === 0) {\n return null;\n }\n\n const latestFile = sortedFiles[0];\n if (!latestFile) {\n return null;\n }\n\n const content = await readTextFile(join(this.storageDir, latestFile));\n const report = JSON.parse(content) as ComplianceReport;\n\n return {\n timestamp: latestFile.replace('report-', '').replace('.json', ''),\n report,\n };\n }\n\n /**\n * Load historical reports for the specified number of days\n * Uses parallel I/O for better performance\n */\n async loadHistory(days: number = 30): Promise<StoredReport[]> {\n if (!await pathExists(this.storageDir)) {\n return [];\n }\n\n const files = await readFilesInDir(this.storageDir);\n\n // Filter report files and sort by date\n const reportFiles = files\n .filter(f => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse(); // Most recent first\n\n // Take only the requested number of days\n const recentFiles = reportFiles.slice(0, days);\n\n // Load all reports in parallel\n const reportPromises = recentFiles.map(async (file) => {\n try {\n const content = await readTextFile(join(this.storageDir, file));\n const report = JSON.parse(content) as ComplianceReport;\n const timestamp = file.replace('report-', '').replace('.json', '');\n\n return { timestamp, report } as StoredReport;\n } catch (error) {\n // Skip corrupted files\n console.warn(`Warning: Failed to load report ${file}:`, error);\n return null;\n }\n });\n\n const results = await Promise.all(reportPromises);\n\n // Filter out null results from failed loads\n return results.filter((r): r is StoredReport => r !== null);\n }\n\n /**\n * Load a specific report by date\n */\n async loadByDate(date: string): Promise<ComplianceReport | null> {\n const filepath = join(this.storageDir, `report-${date}.json`);\n\n if (!await pathExists(filepath)) {\n return null;\n }\n\n const content = await readTextFile(filepath);\n return JSON.parse(content) as ComplianceReport;\n }\n\n /**\n * Get all available report dates\n */\n async getAvailableDates(): Promise<string[]> {\n if (!await pathExists(this.storageDir)) {\n return [];\n }\n\n const files = await readFilesInDir(this.storageDir);\n\n return files\n .filter(f => f.startsWith('report-') && f.endsWith('.json'))\n .map(f => f.replace('report-', '').replace('.json', ''))\n .sort()\n .reverse();\n }\n\n /**\n * Clear old reports (keep only the most recent N days)\n */\n async cleanup(keepDays: number = 90): Promise<number> {\n if (!await pathExists(this.storageDir)) {\n return 0;\n }\n\n const files = await readFilesInDir(this.storageDir);\n const reportFiles = files\n .filter(f => f.startsWith('report-') && f.endsWith('.json'))\n .sort()\n .reverse();\n\n // Delete files beyond the keep limit\n const filesToDelete = reportFiles.slice(keepDays);\n\n for (const file of filesToDelete) {\n try {\n const filepath = join(this.storageDir, file);\n const fs = await import('node:fs/promises');\n await fs.unlink(filepath);\n } catch (error) {\n console.warn(`Warning: Failed to delete old report ${file}:`, error);\n }\n }\n\n return filesToDelete.length;\n }\n}\n","/**\n * Drift detection - Analyze compliance trends between reports\n */\nimport type { ComplianceReport, DecisionCompliance } from '../core/types/index.js';\n\nexport type TrendDirection = 'improving' | 'stable' | 'degrading';\n\nexport interface DriftAnalysis {\n decisionId: string;\n title: string;\n trend: TrendDirection;\n complianceChange: number; // percentage points\n newViolations: number;\n fixedViolations: number;\n currentCompliance: number;\n previousCompliance: number;\n}\n\nexport interface OverallDrift {\n trend: TrendDirection;\n complianceChange: number;\n summary: {\n newViolations: {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n };\n fixedViolations: {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n };\n };\n byDecision: DriftAnalysis[];\n mostImproved: DriftAnalysis[];\n mostDegraded: DriftAnalysis[];\n}\n\n/**\n * Detect drift between current and previous compliance reports\n */\nexport async function detectDrift(\n current: ComplianceReport,\n previous: ComplianceReport\n): Promise<OverallDrift> {\n const byDecision: DriftAnalysis[] = [];\n\n // Analyze per-decision drift\n for (const currDecision of current.byDecision) {\n const prevDecision = previous.byDecision.find(\n d => d.decisionId === currDecision.decisionId\n );\n\n if (!prevDecision) {\n // New decision - treat as stable for now\n byDecision.push({\n decisionId: currDecision.decisionId,\n title: currDecision.title,\n trend: 'stable',\n complianceChange: 0,\n newViolations: currDecision.violations,\n fixedViolations: 0,\n currentCompliance: currDecision.compliance,\n previousCompliance: currDecision.compliance,\n });\n continue;\n }\n\n const complianceChange = currDecision.compliance - prevDecision.compliance;\n const violationDiff = currDecision.violations - prevDecision.violations;\n\n // Determine trend with threshold\n let trend: TrendDirection;\n if (complianceChange > 5) {\n trend = 'improving';\n } else if (complianceChange < -5) {\n trend = 'degrading';\n } else {\n trend = 'stable';\n }\n\n byDecision.push({\n decisionId: currDecision.decisionId,\n title: currDecision.title,\n trend,\n complianceChange,\n newViolations: Math.max(0, violationDiff),\n fixedViolations: Math.max(0, -violationDiff),\n currentCompliance: currDecision.compliance,\n previousCompliance: prevDecision.compliance,\n });\n }\n\n // Calculate overall drift\n const overallComplianceChange = current.summary.compliance - previous.summary.compliance;\n\n let overallTrend: TrendDirection;\n if (overallComplianceChange > 5) {\n overallTrend = 'improving';\n } else if (overallComplianceChange < -5) {\n overallTrend = 'degrading';\n } else {\n overallTrend = 'stable';\n }\n\n // Calculate violation changes by severity\n const newViolations = {\n critical: Math.max(\n 0,\n current.summary.violations.critical - previous.summary.violations.critical\n ),\n high: Math.max(0, current.summary.violations.high - previous.summary.violations.high),\n medium: Math.max(0, current.summary.violations.medium - previous.summary.violations.medium),\n low: Math.max(0, current.summary.violations.low - previous.summary.violations.low),\n total: 0,\n };\n newViolations.total =\n newViolations.critical + newViolations.high + newViolations.medium + newViolations.low;\n\n const fixedViolations = {\n critical: Math.max(\n 0,\n previous.summary.violations.critical - current.summary.violations.critical\n ),\n high: Math.max(0, previous.summary.violations.high - current.summary.violations.high),\n medium: Math.max(0, previous.summary.violations.medium - current.summary.violations.medium),\n low: Math.max(0, previous.summary.violations.low - current.summary.violations.low),\n total: 0,\n };\n fixedViolations.total =\n fixedViolations.critical +\n fixedViolations.high +\n fixedViolations.medium +\n fixedViolations.low;\n\n // Find most improved and most degraded\n const improving = byDecision.filter(d => d.trend === 'improving');\n const degrading = byDecision.filter(d => d.trend === 'degrading');\n\n const mostImproved = improving.sort((a, b) => b.complianceChange - a.complianceChange).slice(0, 5);\n const mostDegraded = degrading.sort((a, b) => a.complianceChange - b.complianceChange).slice(0, 5);\n\n return {\n trend: overallTrend,\n complianceChange: overallComplianceChange,\n summary: {\n newViolations,\n fixedViolations,\n },\n byDecision,\n mostImproved,\n mostDegraded,\n };\n}\n\n/**\n * Analyze compliance trend over multiple reports\n */\nexport interface TrendAnalysis {\n period: {\n start: string;\n end: string;\n days: number;\n };\n overall: {\n startCompliance: number;\n endCompliance: number;\n change: number;\n trend: TrendDirection;\n dataPoints: Array<{ date: string; compliance: number }>;\n };\n decisions: Array<{\n decisionId: string;\n title: string;\n startCompliance: number;\n endCompliance: number;\n change: number;\n trend: TrendDirection;\n dataPoints: Array<{ date: string; compliance: number }>;\n }>;\n}\n\nexport async function analyzeTrend(\n reports: Array<{ timestamp: string; report: ComplianceReport }>\n): Promise<TrendAnalysis> {\n if (reports.length === 0) {\n throw new Error('No reports provided for trend analysis');\n }\n\n // Sort by timestamp (oldest first)\n const sortedReports = reports.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n\n const firstReport = sortedReports[0]?.report;\n const lastReport = sortedReports[sortedReports.length - 1]?.report;\n\n if (!firstReport || !lastReport) {\n throw new Error('Invalid reports data');\n }\n\n // Overall trend\n const overallChange = lastReport.summary.compliance - firstReport.summary.compliance;\n let overallTrend: TrendDirection;\n if (overallChange > 5) {\n overallTrend = 'improving';\n } else if (overallChange < -5) {\n overallTrend = 'degrading';\n } else {\n overallTrend = 'stable';\n }\n\n const overallDataPoints = sortedReports.map(r => ({\n date: r.timestamp,\n compliance: r.report.summary.compliance,\n }));\n\n // Per-decision trends\n const decisionMap = new Map<string, DecisionCompliance[]>();\n\n for (const { report } of sortedReports) {\n for (const decision of report.byDecision) {\n if (!decisionMap.has(decision.decisionId)) {\n decisionMap.set(decision.decisionId, []);\n }\n decisionMap.get(decision.decisionId)!.push(decision);\n }\n }\n\n const decisions = Array.from(decisionMap.entries()).map(([decisionId, data]) => {\n const first = data[0];\n const last = data[data.length - 1];\n\n if (!first || !last) {\n throw new Error(`Invalid decision data for ${decisionId}`);\n }\n\n const change = last.compliance - first.compliance;\n\n let trend: TrendDirection;\n if (change > 5) {\n trend = 'improving';\n } else if (change < -5) {\n trend = 'degrading';\n } else {\n trend = 'stable';\n }\n\n const dataPoints = sortedReports.map(r => {\n const decision = r.report.byDecision.find(d => d.decisionId === decisionId);\n return {\n date: r.timestamp,\n compliance: decision?.compliance ?? 0,\n };\n });\n\n return {\n decisionId,\n title: last.title,\n startCompliance: first.compliance,\n endCompliance: last.compliance,\n change,\n trend,\n dataPoints,\n };\n });\n\n const firstTimestamp = sortedReports[0]?.timestamp;\n const lastTimestamp = sortedReports[sortedReports.length - 1]?.timestamp;\n\n if (!firstTimestamp || !lastTimestamp) {\n throw new Error('Invalid report timestamps');\n }\n\n return {\n period: {\n start: firstTimestamp,\n end: lastTimestamp,\n days: sortedReports.length,\n },\n overall: {\n startCompliance: firstReport.summary.compliance,\n endCompliance: lastReport.summary.compliance,\n change: overallChange,\n trend: overallTrend,\n dataPoints: overallDataPoints,\n },\n decisions,\n };\n}\n","/**\n * Context command - Generate agent context\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { generateFormattedContext } from '../../agent/context.generator.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, writeTextFile, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface ContextOptions {\n format?: string;\n output?: string;\n rationale?: boolean;\n}\n\nexport const contextCommand = new Command('context')\n .description('Generate architectural context for a file (for AI agents)')\n .argument('<file>', 'File path to generate context for')\n .option('-f, --format <format>', 'Output format (markdown, json, mcp)', 'markdown')\n .option('-o, --output <file>', 'Output file path')\n .option('--no-rationale', 'Exclude rationale/summary from output')\n .action(async (file: string, options: ContextOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Generate context\n const output = await generateFormattedContext(file, config, {\n format: options.format as 'markdown' | 'json' | 'mcp',\n includeRationale: options.rationale !== false,\n cwd,\n });\n\n // Output\n if (options.output) {\n await writeTextFile(options.output, output);\n console.log(chalk.green(`Context saved to: ${options.output}`));\n } else {\n console.log(output);\n }\n } catch (error) {\n console.error(chalk.red('Failed to generate context'));\n throw error;\n }\n });\n","/**\n * Agent context generator\n */\nimport type {\n AgentContext,\n ApplicableDecision,\n ApplicableConstraint,\n SpecBridgeConfig,\n} from '../core/types/index.js';\nimport { createRegistry } from '../registry/registry.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface ContextOptions {\n includeRationale?: boolean;\n format?: 'markdown' | 'json' | 'mcp';\n cwd?: string;\n}\n\n/**\n * Generate agent context for a file\n */\nexport async function generateContext(\n filePath: string,\n config: SpecBridgeConfig,\n options: ContextOptions = {}\n): Promise<AgentContext> {\n const { includeRationale = config.agent?.includeRationale ?? true, cwd = process.cwd() } = options;\n\n // Load registry\n const registry = createRegistry({ basePath: cwd });\n await registry.load();\n\n // Get active decisions\n const decisions = registry.getActive();\n\n // Find applicable decisions and constraints\n const applicableDecisions: ApplicableDecision[] = [];\n\n for (const decision of decisions) {\n const applicableConstraints: ApplicableConstraint[] = [];\n\n for (const constraint of decision.constraints) {\n if (matchesPattern(filePath, constraint.scope)) {\n applicableConstraints.push({\n id: constraint.id,\n type: constraint.type,\n rule: constraint.rule,\n severity: constraint.severity,\n });\n }\n }\n\n if (applicableConstraints.length > 0) {\n applicableDecisions.push({\n id: decision.metadata.id,\n title: decision.metadata.title,\n summary: includeRationale ? decision.decision.summary : '',\n constraints: applicableConstraints,\n });\n }\n }\n\n return {\n file: filePath,\n applicableDecisions,\n generatedAt: new Date().toISOString(),\n };\n}\n\n/**\n * Format context as Markdown for agent prompts\n */\nexport function formatContextAsMarkdown(context: AgentContext): string {\n const lines: string[] = [];\n\n lines.push('# Architectural Constraints');\n lines.push('');\n lines.push(`File: \\`${context.file}\\``);\n lines.push('');\n\n if (context.applicableDecisions.length === 0) {\n lines.push('No specific architectural constraints apply to this file.');\n return lines.join('\\n');\n }\n\n lines.push('The following architectural decisions apply to this file:');\n lines.push('');\n\n for (const decision of context.applicableDecisions) {\n lines.push(`## ${decision.title}`);\n lines.push('');\n\n if (decision.summary) {\n lines.push(decision.summary);\n lines.push('');\n }\n\n lines.push('### Constraints');\n lines.push('');\n\n for (const constraint of decision.constraints) {\n const typeEmoji = constraint.type === 'invariant' ? '🔒' :\n constraint.type === 'convention' ? '📋' : '💡';\n const severityBadge = `[${constraint.severity.toUpperCase()}]`;\n\n lines.push(`- ${typeEmoji} **${severityBadge}** ${constraint.rule}`);\n }\n\n lines.push('');\n }\n\n lines.push('---');\n lines.push('');\n lines.push('Please ensure your code complies with these constraints.');\n\n return lines.join('\\n');\n}\n\n/**\n * Format context as JSON\n */\nexport function formatContextAsJson(context: AgentContext): string {\n return JSON.stringify(context, null, 2);\n}\n\n/**\n * Format context for MCP (Model Context Protocol)\n */\nexport function formatContextAsMcp(context: AgentContext): object {\n return {\n type: 'architectural_context',\n version: '1.0',\n file: context.file,\n timestamp: context.generatedAt,\n decisions: context.applicableDecisions.map(d => ({\n id: d.id,\n title: d.title,\n summary: d.summary,\n constraints: d.constraints.map(c => ({\n id: c.id,\n type: c.type,\n severity: c.severity,\n rule: c.rule,\n })),\n })),\n };\n}\n\n/**\n * Generate context in specified format\n */\nexport async function generateFormattedContext(\n filePath: string,\n config: SpecBridgeConfig,\n options: ContextOptions = {}\n): Promise<string> {\n const context = await generateContext(filePath, config, options);\n const format = options.format || config.agent?.format || 'markdown';\n\n switch (format) {\n case 'json':\n return formatContextAsJson(context);\n case 'mcp':\n return JSON.stringify(formatContextAsMcp(context), null, 2);\n case 'markdown':\n default:\n return formatContextAsMarkdown(context);\n }\n}\n\n/**\n * AgentContextGenerator class for test compatibility\n */\nexport class AgentContextGenerator {\n /**\n * Generate context from decisions\n */\n generateContext(options: {\n decisions: any[];\n filePattern?: string;\n format?: 'markdown' | 'plain' | 'json';\n concise?: boolean;\n minSeverity?: string;\n includeExamples?: boolean;\n }): string {\n const { decisions, filePattern, format = 'markdown', concise = false, minSeverity } = options;\n\n // Filter deprecated decisions\n const activeDecisions = decisions.filter(d => d.metadata.status !== 'deprecated');\n\n // Filter by file pattern if provided\n let filteredDecisions = activeDecisions;\n if (filePattern) {\n filteredDecisions = activeDecisions.filter(d =>\n d.constraints.some((c: any) => matchesPattern(filePattern, c.scope))\n );\n }\n\n // Filter by severity if provided\n if (minSeverity) {\n const severityOrder = { low: 0, medium: 1, high: 2, critical: 3 };\n const minLevel = severityOrder[minSeverity as keyof typeof severityOrder] || 0;\n\n filteredDecisions = filteredDecisions.map(d => ({\n ...d,\n constraints: d.constraints.filter((c: any) => {\n const level = severityOrder[c.severity as keyof typeof severityOrder] || 0;\n return level >= minLevel;\n }),\n })).filter(d => d.constraints.length > 0);\n }\n\n // Format output\n if (filteredDecisions.length === 0) {\n return 'No architectural decisions apply.';\n }\n\n if (format === 'json') {\n return JSON.stringify({ decisions: filteredDecisions }, null, 2);\n }\n\n const lines: string[] = [];\n\n if (format === 'markdown') {\n lines.push('# Architectural Decisions\\n');\n for (const decision of filteredDecisions) {\n lines.push(`## ${decision.metadata.title}`);\n if (!concise && decision.decision.summary) {\n lines.push(`\\n${decision.decision.summary}\\n`);\n }\n lines.push('### Constraints\\n');\n for (const constraint of decision.constraints) {\n lines.push(`- **[${constraint.severity.toUpperCase()}]** ${constraint.rule}`);\n }\n lines.push('');\n }\n } else {\n // Plain text format\n for (const decision of filteredDecisions) {\n lines.push(`${decision.metadata.title}`);\n if (!concise && decision.decision.summary) {\n lines.push(`${decision.decision.summary}`);\n }\n for (const constraint of decision.constraints) {\n lines.push(` - ${constraint.rule}`);\n }\n lines.push('');\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Generate prompt suffix for AI agents\n */\n generatePromptSuffix(options: { decisions: any[] }): string {\n const { decisions } = options;\n\n if (decisions.length === 0) {\n return 'No architectural decisions to follow.';\n }\n\n const lines: string[] = [];\n lines.push('Please follow these architectural decisions and constraints:');\n lines.push('');\n\n for (const decision of decisions) {\n lines.push(`- ${decision.metadata.title}`);\n for (const constraint of decision.constraints) {\n lines.push(` - ${constraint.rule}`);\n }\n }\n\n lines.push('');\n lines.push('Ensure your code complies with all constraints listed above.');\n\n return lines.join('\\n');\n }\n\n /**\n * Extract relevant decisions for a specific file\n */\n extractRelevantDecisions(options: {\n decisions: any[];\n filePath: string;\n }): any[] {\n const { decisions, filePath } = options;\n\n return decisions.filter(d =>\n d.constraints.some((c: any) => matchesPattern(filePath, c.scope))\n );\n }\n}\n","/**\n * LSP command - Start SpecBridge language server\n */\nimport { Command } from 'commander';\nimport { startLspServer } from '../../lsp/index.js';\n\nexport const lspCommand = new Command('lsp')\n .description('Start SpecBridge language server (stdio)')\n .option('--verbose', 'Enable verbose server logging', false)\n .action(async (options: { verbose?: boolean }) => {\n await startLspServer({ cwd: process.cwd(), verbose: Boolean(options.verbose) });\n });\n\n","/**\n * SpecBridge Language Server (LSP)\n */\nimport { createConnection, ProposedFeatures, TextDocuments, TextDocumentSyncKind, DiagnosticSeverity, CodeActionKind } from 'vscode-languageserver/node.js';\nimport { TextDocument } from 'vscode-languageserver-textdocument';\nimport { fileURLToPath } from 'node:url';\nimport path from 'node:path';\nimport { Project } from 'ts-morph';\nimport chalk from 'chalk';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { getSpecBridgeDir, pathExists } from '../utils/fs.js';\nimport { selectVerifierForConstraint, type VerificationContext } from '../verification/verifiers/index.js';\nimport { shouldApplyConstraintToFile } from '../verification/applicability.js';\nimport type { Decision, Violation, Severity } from '../core/types/index.js';\nimport { NotInitializedError } from '../core/errors/index.js';\n\nexport interface LspServerOptions {\n cwd: string;\n verbose?: boolean;\n}\n\nfunction severityToDiagnostic(severity: Severity): DiagnosticSeverity {\n switch (severity) {\n case 'critical':\n return DiagnosticSeverity.Error;\n case 'high':\n return DiagnosticSeverity.Warning;\n case 'medium':\n return DiagnosticSeverity.Information;\n case 'low':\n return DiagnosticSeverity.Hint;\n default:\n return DiagnosticSeverity.Information;\n }\n}\n\nfunction uriToFilePath(uri: string): string {\n if (uri.startsWith('file://')) return fileURLToPath(uri);\n // Fallback: treat as plain path\n return uri;\n}\n\nfunction violationToRange(doc: TextDocument, v: Violation) {\n // Prefer autofix ranges when available, otherwise line/column best-effort.\n const edit = v.autofix?.edits?.[0];\n if (edit) {\n return {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n };\n }\n\n const line = Math.max(0, (v.line ?? 1) - 1);\n const char = Math.max(0, (v.column ?? 1) - 1);\n return {\n start: { line, character: char },\n end: { line, character: char + 1 },\n };\n}\n\nexport class SpecBridgeLspServer {\n private connection = createConnection(ProposedFeatures.all);\n private documents = new TextDocuments(TextDocument);\n\n private options: LspServerOptions;\n private registry: Registry | null = null;\n private decisions: Decision[] = [];\n private cwd: string;\n private project: Project;\n private cache = new Map<string, Violation[]>();\n private initError: string | null = null;\n\n constructor(options: LspServerOptions) {\n this.options = options;\n this.cwd = options.cwd;\n this.project = new Project({\n compilerOptions: {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n skipLibCheck: true,\n },\n skipAddingFilesFromTsConfig: true,\n });\n }\n\n async initialize(): Promise<void> {\n this.connection.onInitialize(async () => {\n await this.initializeWorkspace();\n\n return {\n capabilities: {\n textDocumentSync: TextDocumentSyncKind.Incremental,\n codeActionProvider: true,\n },\n };\n });\n\n this.documents.onDidOpen((e) => {\n void this.validateDocument(e.document);\n });\n\n this.documents.onDidChangeContent((change) => {\n void this.validateDocument(change.document);\n });\n\n this.documents.onDidClose((e) => {\n this.cache.delete(e.document.uri);\n this.connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });\n });\n\n this.connection.onCodeAction((params) => {\n const violations = this.cache.get(params.textDocument.uri) || [];\n const doc = this.documents.get(params.textDocument.uri);\n if (!doc) return [];\n\n return violations\n .filter((v) => v.autofix && v.autofix.edits.length > 0)\n .map((v) => {\n const edits = v.autofix!.edits.map((edit) => ({\n range: {\n start: doc.positionAt(edit.start),\n end: doc.positionAt(edit.end),\n },\n newText: edit.text,\n }));\n\n return {\n title: v.autofix!.description,\n kind: CodeActionKind.QuickFix,\n edit: {\n changes: {\n [params.textDocument.uri]: edits,\n },\n },\n };\n });\n });\n\n this.documents.listen(this.connection);\n this.connection.listen();\n }\n\n private async initializeWorkspace(): Promise<void> {\n // Ensure initialized (but keep server alive if not).\n if (!await pathExists(getSpecBridgeDir(this.cwd))) {\n const err = new NotInitializedError();\n this.initError = err.message;\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n return;\n }\n\n try {\n const config = await loadConfig(this.cwd);\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n this.decisions = this.registry.getActive();\n\n // Prime project with source roots (best-effort). This enables verifiers that depend on import graph.\n for (const root of config.project.sourceRoots) {\n // ts-morph doesn't support globs directly; add root folders when possible.\n const rootPath = path.isAbsolute(root) ? root : path.join(this.cwd, root);\n // If root is a glob, fall back to adding the directory portion.\n const dir = rootPath.includes('*') ? rootPath.split('*')[0] : rootPath;\n if (dir && await pathExists(dir)) {\n this.project.addSourceFilesAtPaths(path.join(dir, '**/*.{ts,tsx,js,jsx}'));\n }\n }\n\n if (this.options.verbose) {\n this.connection.console.log(chalk.dim(`Loaded ${this.decisions.length} active decision(s)`));\n }\n } catch (error) {\n this.initError = error instanceof Error ? error.message : String(error);\n if (this.options.verbose) this.connection.console.error(chalk.red(this.initError));\n }\n }\n\n private async verifyTextDocument(doc: TextDocument): Promise<Violation[]> {\n if (this.initError) {\n throw new Error(this.initError);\n }\n if (!this.registry) return [];\n\n const filePath = uriToFilePath(doc.uri);\n const sourceFile = this.project.createSourceFile(filePath, doc.getText(), { overwrite: true });\n\n const violations: Violation[] = [];\n\n for (const decision of this.decisions) {\n for (const constraint of decision.constraints) {\n if (!shouldApplyConstraintToFile({ filePath, constraint, cwd: this.cwd })) continue;\n\n const verifier = selectVerifierForConstraint(constraint.rule, constraint.verifier);\n if (!verifier) continue;\n\n const ctx: VerificationContext = {\n filePath,\n sourceFile,\n constraint,\n decisionId: decision.metadata.id,\n };\n\n try {\n const constraintViolations = await verifier.verify(ctx);\n violations.push(...constraintViolations);\n } catch {\n // Ignore verifier errors (LSP should stay responsive)\n }\n }\n }\n\n return violations;\n }\n\n private async validateDocument(doc: TextDocument): Promise<void> {\n try {\n const violations = await this.verifyTextDocument(doc);\n this.cache.set(doc.uri, violations);\n\n const diagnostics = violations.map((v) => ({\n range: violationToRange(doc, v),\n severity: severityToDiagnostic(v.severity),\n message: v.message,\n source: 'specbridge',\n }));\n\n this.connection.sendDiagnostics({ uri: doc.uri, diagnostics });\n } catch (error) {\n // If workspace isn't initialized, surface a single diagnostic.\n const msg = error instanceof Error ? error.message : String(error);\n this.connection.sendDiagnostics({\n uri: doc.uri,\n diagnostics: [\n {\n range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },\n severity: DiagnosticSeverity.Error,\n message: msg,\n source: 'specbridge',\n },\n ],\n });\n }\n }\n}\n","import { SpecBridgeLspServer, type LspServerOptions } from './server.js';\n\nexport async function startLspServer(options: LspServerOptions): Promise<void> {\n const server = new SpecBridgeLspServer(options);\n await server.initialize();\n}\n\n","/**\n * Watch command - Verify changed files continuously\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport chokidar from 'chokidar';\nimport path from 'node:path';\nimport { createVerificationEngine } from '../../verification/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { getSpecBridgeDir, pathExists } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { VerificationLevel } from '../../core/types/index.js';\n\nexport const watchCommand = new Command('watch')\n .description('Watch for changes and verify files continuously')\n .option('-l, --level <level>', 'Verification level (commit, pr, full)', 'full')\n .option('--debounce <ms>', 'Debounce verify on rapid changes', '150')\n .action(async (options: { level?: string; debounce?: string }) => {\n const cwd = process.cwd();\n\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const config = await loadConfig(cwd);\n const engine = createVerificationEngine();\n const level = (options.level || 'full') as VerificationLevel;\n const debounceMs = Number.parseInt(options.debounce || '150', 10);\n\n let timer: NodeJS.Timeout | null = null;\n let pendingPath: string | null = null;\n\n const run = async (changedPath: string) => {\n const absolutePath = path.isAbsolute(changedPath) ? changedPath : path.join(cwd, changedPath);\n const result = await engine.verify(config, {\n level,\n files: [absolutePath],\n cwd,\n });\n\n const prefix = result.success ? chalk.green('✓') : chalk.red('✗');\n const summary = `${prefix} ${path.relative(cwd, absolutePath)}: ${result.violations.length} violation(s)`;\n console.log(summary);\n\n for (const v of result.violations.slice(0, 20)) {\n const loc = v.line ? `:${v.line}${v.column ? `:${v.column}` : ''}` : '';\n console.log(chalk.dim(` - ${v.file}${loc}: ${v.message} [${v.severity}]`));\n }\n if (result.violations.length > 20) {\n console.log(chalk.dim(` … ${result.violations.length - 20} more`));\n }\n };\n\n const watcher = chokidar.watch(config.project.sourceRoots, {\n cwd,\n ignored: config.project.exclude,\n ignoreInitial: true,\n persistent: true,\n });\n\n console.log(chalk.blue('Watching for changes...'));\n\n watcher.on('change', (changedPath) => {\n pendingPath = changedPath;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n if (!pendingPath) return;\n void run(pendingPath);\n pendingPath = null;\n }, debounceMs);\n });\n });\n\n","/**\n * MCP Server command - Start SpecBridge MCP server\n */\nimport { Command } from 'commander';\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { SpecBridgeMcpServer } from '../../mcp/server.js';\n\nfunction getCliVersion(): string {\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n // In production (bundled): import.meta.url points to dist/cli.js, so ../package.json is correct.\n const packageJsonPath = join(__dirname, '../package.json');\n const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n return String(pkg.version || '0.0.0');\n } catch {\n return '0.0.0';\n }\n}\n\nexport const mcpServerCommand = new Command('mcp-server')\n .description('Start SpecBridge MCP server (stdio)')\n .action(async () => {\n const server = new SpecBridgeMcpServer({\n cwd: process.cwd(),\n version: getCliVersion(),\n });\n\n await server.initialize();\n // MCP servers should write logs to stderr; keep stdout for protocol.\n console.error('SpecBridge MCP server starting (stdio)...');\n await server.startStdio();\n });\n\n","/**\n * SpecBridge MCP Server (Model Context Protocol)\n */\nimport { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { loadConfig } from '../config/loader.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { generateFormattedContext } from '../agent/context.generator.js';\nimport { createVerificationEngine } from '../verification/engine.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { formatConsoleReport } from '../reporting/formats/console.js';\nimport { formatMarkdownReport } from '../reporting/formats/markdown.js';\nimport type { SpecBridgeConfig } from '../core/types/index.js';\n\nexport interface McpServerOptions {\n cwd: string;\n version: string;\n}\n\nexport class SpecBridgeMcpServer {\n private server: McpServer;\n private cwd: string;\n private config: SpecBridgeConfig | null = null;\n private registry: Registry | null = null;\n\n constructor(options: McpServerOptions) {\n this.cwd = options.cwd;\n this.server = new McpServer({ name: 'specbridge', version: options.version });\n }\n\n async initialize(): Promise<void> {\n this.config = await loadConfig(this.cwd);\n this.registry = createRegistry({ basePath: this.cwd });\n await this.registry.load();\n\n this.registerResources();\n this.registerTools();\n }\n\n async startStdio(): Promise<void> {\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n }\n\n private getReady(): { config: SpecBridgeConfig; registry: Registry } {\n if (!this.config || !this.registry) {\n throw new Error('SpecBridge MCP server not initialized. Call initialize() first.');\n }\n return { config: this.config, registry: this.registry };\n }\n\n private registerResources(): void {\n const { config, registry } = this.getReady();\n\n // List all decisions\n this.server.registerResource(\n 'decisions',\n 'decision:///',\n {\n title: 'Architectural Decisions',\n description: 'List of all architectural decisions',\n mimeType: 'application/json',\n },\n async (uri: URL) => {\n const decisions = registry.getAll();\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(decisions, null, 2),\n },\n ],\n };\n }\n );\n\n // Read a specific decision\n this.server.registerResource(\n 'decision',\n new ResourceTemplate('decision://{id}', { list: undefined }),\n {\n title: 'Architectural Decision',\n description: 'A specific architectural decision by id',\n mimeType: 'application/json',\n },\n async (uri: URL, variables: Record<string, string | string[]>) => {\n const raw = variables.id;\n const decisionId = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '');\n const decision = registry.get(String(decisionId));\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(decision, null, 2),\n },\n ],\n };\n }\n );\n\n // Latest compliance report\n this.server.registerResource(\n 'latest_report',\n 'report:///latest',\n {\n title: 'Latest Compliance Report',\n description: 'Most recent compliance report (generated on demand)',\n mimeType: 'application/json',\n },\n async (uri: URL) => {\n const report = await generateReport(config, { cwd: this.cwd });\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n }\n );\n }\n\n private registerTools(): void {\n const { config } = this.getReady();\n\n this.server.registerTool(\n 'generate_context',\n {\n title: 'Generate architectural context',\n description: 'Generate architectural context for a file from applicable decisions',\n inputSchema: {\n filePath: z.string().describe('Path to the file to analyze'),\n includeRationale: z.boolean().optional().default(true),\n format: z.enum(['markdown', 'json', 'mcp']).optional().default('markdown'),\n },\n },\n async (args: { filePath: string; includeRationale?: boolean; format?: 'markdown' | 'json' | 'mcp' }) => {\n const text = await generateFormattedContext(args.filePath, config, {\n includeRationale: args.includeRationale,\n format: args.format,\n cwd: this.cwd,\n });\n\n return { content: [{ type: 'text', text }] };\n }\n );\n\n this.server.registerTool(\n 'verify_compliance',\n {\n title: 'Verify compliance',\n description: 'Verify code compliance against constraints',\n inputSchema: {\n level: z.enum(['commit', 'pr', 'full']).optional().default('full'),\n files: z.array(z.string()).optional(),\n decisions: z.array(z.string()).optional(),\n severity: z.array(z.enum(['critical', 'high', 'medium', 'low'])).optional(),\n },\n },\n async (args: {\n level?: 'commit' | 'pr' | 'full';\n files?: string[];\n decisions?: string[];\n severity?: ('critical' | 'high' | 'medium' | 'low')[];\n }) => {\n const engine = createVerificationEngine();\n const result = await engine.verify(config, {\n level: args.level,\n files: args.files,\n decisions: args.decisions,\n severity: args.severity,\n cwd: this.cwd,\n });\n\n return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };\n }\n );\n\n this.server.registerTool(\n 'get_report',\n {\n title: 'Get compliance report',\n description: 'Generate a compliance report for the current workspace',\n inputSchema: {\n format: z.enum(['summary', 'detailed', 'json', 'markdown']).optional().default('summary'),\n includeAll: z.boolean().optional().default(false),\n },\n },\n async (args: { format?: 'summary' | 'detailed' | 'json' | 'markdown'; includeAll?: boolean }) => {\n const report = await generateReport(config, { cwd: this.cwd, includeAll: args.includeAll });\n\n if (args.format === 'json') {\n return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }] };\n }\n\n if (args.format === 'markdown') {\n return { content: [{ type: 'text', text: formatMarkdownReport(report) }] };\n }\n\n if (args.format === 'detailed') {\n return { content: [{ type: 'text', text: formatConsoleReport(report) }] };\n }\n\n // summary\n const summary = {\n timestamp: report.timestamp,\n project: report.project,\n compliance: report.summary.compliance,\n violations: report.summary.violations,\n decisions: report.summary.activeDecisions,\n };\n return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] };\n }\n );\n }\n}\n","/**\n * Prompt command - Generate AI agent prompt templates\n */\nimport { Command } from 'commander';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { generateContext } from '../../agent/context.generator.js';\nimport { templates } from '../../agent/templates.js';\n\nexport const promptCommand = new Command('prompt')\n .description('Generate AI agent prompt templates')\n .argument('<template>', 'Template name (code-review|refactoring|migration)')\n .argument('<file>', 'File path (used to select applicable decisions)')\n .option('--decision <id>', 'Decision id (required for migration)')\n .action(async (templateName: string, file: string, options: { decision?: string }) => {\n const cwd = process.cwd();\n\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const tpl = templates[templateName];\n if (!tpl) {\n throw new Error(`Unknown template: ${templateName}`);\n }\n\n if (templateName === 'migration' && !options.decision) {\n throw new Error('Missing --decision <id> for migration template');\n }\n\n const config = await loadConfig(cwd);\n const context = await generateContext(file, config, { cwd, includeRationale: true });\n const prompt = tpl.generate(context, { decisionId: options.decision });\n console.log(prompt);\n });\n\n","/**\n * Prompt templates for AI agents\n */\nimport type { AgentContext } from '../core/types/index.js';\nimport { formatContextAsMarkdown } from './context.generator.js';\n\nexport interface PromptTemplate {\n name: string;\n description: string;\n generate: (context: AgentContext, options?: Record<string, unknown>) => string;\n}\n\nexport const templates: Record<string, PromptTemplate> = {\n 'code-review': {\n name: 'Code Review',\n description: 'Review code for architectural compliance',\n generate: (context) => {\n return [\n 'You are reviewing code for architectural compliance.',\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Identify violations of the constraints above.',\n '- Suggest concrete changes to achieve compliance.',\n ].join('\\n');\n },\n },\n\n refactoring: {\n name: 'Refactoring Guidance',\n description: 'Guide refactoring to meet constraints',\n generate: (context) => {\n return [\n 'You are helping refactor code to meet architectural constraints.',\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Propose a step-by-step refactoring plan to satisfy all invariants first, then conventions/guidelines.',\n '- Highlight risky changes and suggest safe incremental steps.',\n ].join('\\n');\n },\n },\n\n migration: {\n name: 'Migration Plan',\n description: 'Generate a migration plan for a new/changed decision',\n generate: (context, options) => {\n const decisionId = String(options?.decisionId ?? '');\n return [\n `A new architectural decision has been introduced: ${decisionId || '<decision-id>'}`,\n '',\n formatContextAsMarkdown(context),\n '',\n 'Task:',\n '- Provide an impact analysis.',\n '- Produce a step-by-step migration plan.',\n '- Include a checklist for completion.',\n ].join('\\n');\n },\n },\n};\n\n","/**\n * Analytics command - Analyze compliance trends and decision impact\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { ReportStorage } from '../../reporting/storage.js';\nimport { AnalyticsEngine } from '../../analytics/engine.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface AnalyticsOptions {\n insights?: boolean;\n days?: string;\n format?: string;\n}\n\nexport const analyticsCommand = new Command('analytics')\n .description('Analyze compliance trends and decision impact')\n .argument('[decision-id]', 'Specific decision to analyze')\n .option('--insights', 'Show AI-generated insights')\n .option('--days <n>', 'Number of days of history to analyze', '90')\n .option('-f, --format <format>', 'Output format (console, json)', 'console')\n .action(async (decisionId: string | undefined, options: AnalyticsOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n const spinner = ora('Analyzing compliance data...').start();\n\n try {\n const storage = new ReportStorage(cwd);\n const days = parseInt(options.days || '90', 10);\n const history = await storage.loadHistory(days);\n\n if (history.length === 0) {\n spinner.fail('No historical reports found');\n console.log(chalk.yellow('\\nGenerate reports with: specbridge report'));\n return;\n }\n\n spinner.succeed(`Loaded ${history.length} historical report(s)`);\n\n const engine = new AnalyticsEngine();\n\n // Format output\n if (options.format === 'json') {\n if (decisionId) {\n const metrics = await engine.analyzeDecision(decisionId, history);\n console.log(JSON.stringify(metrics, null, 2));\n } else {\n const summary = await engine.generateSummary(history);\n console.log(JSON.stringify(summary, null, 2));\n }\n return;\n }\n\n // Console format\n if (decisionId) {\n // Analyze specific decision\n const metrics = await engine.analyzeDecision(decisionId, history);\n\n console.log('\\n' + chalk.blue.bold(`=== Decision Analytics: ${metrics.title} ===\\n`));\n\n console.log(chalk.bold('Overview:'));\n console.log(` ID: ${metrics.decisionId}`);\n console.log(` Current Violations: ${metrics.totalViolations}`);\n console.log(` Average Compliance: ${metrics.averageComplianceScore.toFixed(1)}%`);\n\n const trendEmoji = metrics.trendDirection === 'up' ? '📈' : metrics.trendDirection === 'down' ? '📉' : '➡️';\n const trendColor = metrics.trendDirection === 'up' ? chalk.green : metrics.trendDirection === 'down' ? chalk.red : chalk.yellow;\n console.log(` ${trendColor(`${trendEmoji} Trend: ${metrics.trendDirection.toUpperCase()}`)}`);\n\n // Show history\n if (metrics.history.length > 0) {\n console.log(chalk.bold('\\nCompliance History:'));\n const recentHistory = metrics.history.slice(-10); // Show last 10 entries\n recentHistory.forEach(h => {\n const icon = h.violations === 0 ? '✅' : '⚠️';\n console.log(` ${icon} ${h.date}: ${h.compliance}% (${h.violations} violations)`);\n });\n }\n } else {\n // Overall analytics\n const summary = await engine.generateSummary(history);\n\n console.log('\\n' + chalk.blue.bold('=== Overall Analytics ===\\n'));\n\n console.log(chalk.bold('Summary:'));\n console.log(` Total Decisions: ${summary.totalDecisions}`);\n console.log(` Average Compliance: ${summary.averageCompliance}%`);\n console.log(` Critical Issues: ${summary.criticalIssues}`);\n\n const trendEmoji = summary.overallTrend === 'up' ? '📈' : summary.overallTrend === 'down' ? '📉' : '➡️';\n const trendColor = summary.overallTrend === 'up' ? chalk.green : summary.overallTrend === 'down' ? chalk.red : chalk.yellow;\n console.log(` ${trendColor(`${trendEmoji} Overall Trend: ${summary.overallTrend.toUpperCase()}`)}`);\n\n // Top performers\n if (summary.topDecisions.length > 0) {\n console.log(chalk.green('\\n✅ Top Performing Decisions:'));\n summary.topDecisions.forEach((d, i) => {\n console.log(` ${i + 1}. ${d.title}: ${d.compliance}%`);\n });\n }\n\n // Bottom performers\n if (summary.bottomDecisions.length > 0) {\n console.log(chalk.red('\\n⚠️ Decisions Needing Attention:'));\n summary.bottomDecisions.forEach((d, i) => {\n console.log(` ${i + 1}. ${d.title}: ${d.compliance}%`);\n });\n }\n\n // Show insights if requested or if there are issues\n if (options.insights || summary.criticalIssues > 0) {\n console.log(chalk.blue.bold('\\n=== Insights ===\\n'));\n\n const insights = summary.insights;\n\n // Group by type\n const warnings = insights.filter(i => i.type === 'warning');\n const successes = insights.filter(i => i.type === 'success');\n const infos = insights.filter(i => i.type === 'info');\n\n if (warnings.length > 0) {\n console.log(chalk.red('⚠️ Warnings:'));\n warnings.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n\n if (successes.length > 0) {\n console.log(chalk.green('✅ Positive Trends:'));\n successes.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n\n if (infos.length > 0) {\n console.log(chalk.blue('💡 Suggestions:'));\n infos.forEach(i => {\n console.log(` • ${i.message}`);\n if (i.details) {\n console.log(chalk.gray(` ${i.details}`));\n }\n });\n console.log('');\n }\n }\n }\n\n // Show data range\n const latestEntry = history[history.length - 1];\n const oldestEntry = history[0];\n if (latestEntry && oldestEntry) {\n console.log(chalk.gray(`\\nData range: ${latestEntry.timestamp} to ${oldestEntry.timestamp}`));\n }\n console.log(chalk.gray(`Analyzing ${history.length} report(s) over ${days} days\\n`));\n } catch (error) {\n spinner.fail('Analytics failed');\n throw error;\n }\n });\n","/**\n * Analytics engine - Provide insights into compliance trends and decision impact\n */\nimport type { DecisionCompliance, Severity } from '../core/types/index.js';\nimport type { StoredReport } from '../reporting/storage.js';\n\nexport interface DecisionMetrics {\n decisionId: string;\n title: string;\n totalViolations: number;\n violationsByFile: Map<string, number>;\n violationsBySeverity: Record<Severity, number>;\n mostViolatedConstraint: { id: string; count: number } | null;\n averageComplianceScore: number;\n trendDirection: 'up' | 'down' | 'stable';\n history: Array<{\n date: string;\n compliance: number;\n violations: number;\n }>;\n}\n\nexport interface Insight {\n type: 'warning' | 'info' | 'success';\n category: 'compliance' | 'trend' | 'hotspot' | 'suggestion';\n message: string;\n details?: string;\n decisionId?: string;\n}\n\nexport interface AnalyticsSummary {\n totalDecisions: number;\n averageCompliance: number;\n overallTrend: 'up' | 'down' | 'stable';\n criticalIssues: number;\n topDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n bottomDecisions: Array<{\n decisionId: string;\n title: string;\n compliance: number;\n }>;\n insights: Insight[];\n}\n\n/**\n * Analytics engine for compliance data\n */\nexport class AnalyticsEngine {\n /**\n * Analyze a specific decision across historical reports\n */\n async analyzeDecision(\n decisionId: string,\n history: StoredReport[]\n ): Promise<DecisionMetrics> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n // Extract decision data from each report\n const decisionHistory: Array<{\n date: string;\n data: DecisionCompliance;\n }> = [];\n\n for (const { timestamp, report } of history) {\n const decision = report.byDecision.find(d => d.decisionId === decisionId);\n if (decision) {\n decisionHistory.push({ date: timestamp, data: decision });\n }\n }\n\n if (decisionHistory.length === 0) {\n throw new Error(`Decision ${decisionId} not found in any report`);\n }\n\n // Get latest data\n const latestEntry = decisionHistory[decisionHistory.length - 1];\n if (!latestEntry) {\n throw new Error(`No data found for decision ${decisionId}`);\n }\n const latest = latestEntry.data;\n\n // Calculate averages\n const averageCompliance =\n decisionHistory.reduce((sum, h) => sum + h.data.compliance, 0) / decisionHistory.length;\n\n // Determine trend\n let trendDirection: 'up' | 'down' | 'stable' = 'stable';\n if (decisionHistory.length >= 2) {\n const firstEntry = decisionHistory[0];\n if (!firstEntry) {\n throw new Error('Invalid decision history');\n }\n const first = firstEntry.data.compliance;\n const last = latest.compliance;\n const change = last - first;\n\n if (change > 5) {\n trendDirection = 'up';\n } else if (change < -5) {\n trendDirection = 'down';\n }\n }\n\n // Build history summary\n const historyData = decisionHistory.map(h => ({\n date: h.date,\n compliance: h.data.compliance,\n violations: h.data.violations,\n }));\n\n return {\n decisionId,\n title: latest.title,\n totalViolations: latest.violations,\n violationsByFile: new Map(), // Would need violation details to populate\n violationsBySeverity: {\n critical: 0,\n high: 0,\n medium: 0,\n low: 0,\n }, // Would need violation details to populate\n mostViolatedConstraint: null, // Would need constraint details to populate\n averageComplianceScore: averageCompliance,\n trendDirection,\n history: historyData,\n };\n }\n\n /**\n * Generate insights from historical data\n */\n async generateInsights(history: StoredReport[]): Promise<Insight[]> {\n if (history.length === 0) {\n return [];\n }\n\n const insights: Insight[] = [];\n\n // Sort by date (oldest first)\n const sorted = history.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n const latestEntry = sorted[sorted.length - 1];\n if (!latestEntry) {\n throw new Error('No reports in history');\n }\n const latest = latestEntry.report;\n\n // Insight: Overall compliance trend\n if (sorted.length >= 2) {\n const firstEntry = sorted[0];\n if (!firstEntry) {\n return insights;\n }\n const first = firstEntry.report;\n const complianceChange = latest.summary.compliance - first.summary.compliance;\n\n if (complianceChange > 10) {\n insights.push({\n type: 'success',\n category: 'trend',\n message: `Compliance has improved by ${complianceChange.toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n } else if (complianceChange < -10) {\n insights.push({\n type: 'warning',\n category: 'trend',\n message: `Compliance has dropped by ${Math.abs(complianceChange).toFixed(1)}% over the past ${sorted.length} days`,\n details: `From ${first.summary.compliance}% to ${latest.summary.compliance}%`,\n });\n }\n }\n\n // Insight: Critical violations\n if (latest.summary.violations.critical > 0) {\n insights.push({\n type: 'warning',\n category: 'compliance',\n message: `${latest.summary.violations.critical} critical violation(s) require immediate attention`,\n details: 'Critical violations block deployments and should be resolved as soon as possible',\n });\n }\n\n // Insight: Decision-specific issues\n const problematicDecisions = latest.byDecision.filter(d => d.compliance < 50);\n if (problematicDecisions.length > 0) {\n insights.push({\n type: 'warning',\n category: 'hotspot',\n message: `${problematicDecisions.length} decision(s) have less than 50% compliance`,\n details: problematicDecisions.map(d => `${d.title} (${d.compliance}%)`).join(', '),\n });\n }\n\n // Insight: High compliance decisions\n const excellentDecisions = latest.byDecision.filter(d => d.compliance === 100);\n if (excellentDecisions.length > 0) {\n insights.push({\n type: 'success',\n category: 'compliance',\n message: `${excellentDecisions.length} decision(s) have 100% compliance`,\n details: excellentDecisions.map(d => d.title).join(', '),\n });\n }\n\n // Insight: Compare to average\n const avgCompliance = latest.summary.compliance;\n const decisionsAboveAvg = latest.byDecision.filter(d => d.compliance > avgCompliance);\n const decisionsBelowAvg = latest.byDecision.filter(d => d.compliance < avgCompliance);\n\n if (decisionsBelowAvg.length > decisionsAboveAvg.length) {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: `${decisionsBelowAvg.length} decisions are below average compliance`,\n details: 'Consider focusing improvement efforts on these lower-performing decisions',\n });\n }\n\n // Insight: Violation distribution\n const totalViolations =\n latest.summary.violations.critical +\n latest.summary.violations.high +\n latest.summary.violations.medium +\n latest.summary.violations.low;\n\n if (totalViolations > 0) {\n const criticalPercent = (latest.summary.violations.critical / totalViolations) * 100;\n const highPercent = (latest.summary.violations.high / totalViolations) * 100;\n\n if (criticalPercent + highPercent > 60) {\n insights.push({\n type: 'warning',\n category: 'suggestion',\n message: 'Most violations are high severity',\n details: `${criticalPercent.toFixed(0)}% critical, ${highPercent.toFixed(0)}% high. Prioritize these for the biggest impact.`,\n });\n } else {\n insights.push({\n type: 'info',\n category: 'suggestion',\n message: 'Most violations are lower severity',\n details: 'Consider addressing high-severity issues first for maximum impact',\n });\n }\n }\n\n return insights;\n }\n\n /**\n * Generate analytics summary\n */\n async generateSummary(history: StoredReport[]): Promise<AnalyticsSummary> {\n if (history.length === 0) {\n throw new Error('No historical reports provided');\n }\n\n const latestEntry = history[history.length - 1];\n if (!latestEntry) {\n throw new Error('Invalid history data');\n }\n const latest = latestEntry.report;\n\n // Calculate overall trend\n let overallTrend: 'up' | 'down' | 'stable' = 'stable';\n if (history.length >= 2) {\n const firstEntry = history[0];\n if (!firstEntry) {\n throw new Error('Invalid history data');\n }\n const first = firstEntry.report;\n const change = latest.summary.compliance - first.summary.compliance;\n\n if (change > 5) {\n overallTrend = 'up';\n } else if (change < -5) {\n overallTrend = 'down';\n }\n }\n\n // Find top and bottom performers\n const sortedByCompliance = [...latest.byDecision].sort(\n (a, b) => b.compliance - a.compliance\n );\n\n const topDecisions = sortedByCompliance.slice(0, 5).map(d => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n const bottomDecisions = sortedByCompliance.slice(-5).reverse().map(d => ({\n decisionId: d.decisionId,\n title: d.title,\n compliance: d.compliance,\n }));\n\n // Generate insights\n const insights = await this.generateInsights(history);\n\n return {\n totalDecisions: latest.byDecision.length,\n averageCompliance: latest.summary.compliance,\n overallTrend,\n criticalIssues: latest.summary.violations.critical,\n topDecisions,\n bottomDecisions,\n insights,\n };\n }\n}\n","/**\n * Dashboard command - Start compliance dashboard web server\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport { createDashboardServer } from '../../dashboard/server.js';\n\ninterface DashboardOptions {\n port?: string;\n host?: string;\n}\n\nexport const dashboardCommand = new Command('dashboard')\n .description('Start compliance dashboard web server')\n .option('-p, --port <port>', 'Port to listen on', '3000')\n .option('-h, --host <host>', 'Host to bind to', 'localhost')\n .action(async (options: DashboardOptions) => {\n const cwd = process.cwd();\n\n // Check if specbridge is initialized\n if (!await pathExists(getSpecBridgeDir(cwd))) {\n throw new NotInitializedError();\n }\n\n console.log(chalk.blue('Starting SpecBridge dashboard...'));\n\n try {\n // Load config\n const config = await loadConfig(cwd);\n\n // Create server\n const server = createDashboardServer({ cwd, config });\n\n // Initialize (loads registry and starts caching)\n await server.start();\n\n // Start listening\n const port = parseInt(options.port || '3000', 10);\n const host = options.host || 'localhost';\n\n server.getApp().listen(port, host, () => {\n console.log(chalk.green(`\\n✓ Dashboard running at http://${host}:${port}`));\n console.log(chalk.gray(' Press Ctrl+C to stop\\n'));\n\n // Show helpful endpoints\n console.log(chalk.bold('API Endpoints:'));\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/health`)} - Health check`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/report/latest`)} - Latest report (cached)`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/decisions`)} - All decisions`);\n console.log(` ${chalk.cyan(`http://${host}:${port}/api/analytics/summary`)} - Analytics`);\n console.log('');\n });\n\n // Handle shutdown gracefully\n const shutdown = () => {\n console.log(chalk.yellow('\\n\\nShutting down dashboard...'));\n server.stop();\n process.exit(0);\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n console.error(chalk.red('Failed to start dashboard:'), error);\n throw error;\n }\n });\n","/**\n * Dashboard server - Compliance dashboard backend with REST API\n */\nimport express, { type Request, type Response, type Application } from 'express';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { SpecBridgeConfig, ComplianceReport } from '../core/types/index.js';\nimport { generateReport } from '../reporting/reporter.js';\nimport { ReportStorage } from '../reporting/storage.js';\nimport { AnalyticsEngine } from '../analytics/engine.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { detectDrift, analyzeTrend } from '../reporting/drift.js';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\ninterface DashboardOptions {\n cwd: string;\n config: SpecBridgeConfig;\n}\n\n/**\n * Dashboard Server with caching\n */\nclass DashboardServer {\n private app: Application;\n private cwd: string;\n private config: SpecBridgeConfig;\n private registry: Registry;\n private reportStorage: ReportStorage;\n\n // Caching infrastructure\n private cachedReport: ComplianceReport | null = null;\n private cacheTimestamp: number = 0;\n private readonly CACHE_TTL = 60000; // 1 minute\n private refreshInterval: NodeJS.Timeout | null = null;\n\n constructor(options: DashboardOptions) {\n this.cwd = options.cwd;\n this.config = options.config;\n this.app = express();\n this.registry = createRegistry({ basePath: this.cwd });\n this.reportStorage = new ReportStorage(this.cwd);\n\n this.setupMiddleware();\n this.setupRoutes();\n }\n\n /**\n * Start the server with background cache refresh\n */\n async start(): Promise<void> {\n // Load registry once\n await this.registry.load();\n\n // Initial cache population\n await this.refreshCache();\n\n // Background refresh\n this.refreshInterval = setInterval(\n () => this.refreshCache().catch(console.error),\n this.CACHE_TTL\n );\n }\n\n /**\n * Stop the server and clear intervals\n */\n stop(): void {\n if (this.refreshInterval) {\n clearInterval(this.refreshInterval);\n this.refreshInterval = null;\n }\n }\n\n /**\n * Refresh the cached report\n */\n private async refreshCache(): Promise<void> {\n try {\n const report = await generateReport(this.config, { cwd: this.cwd });\n\n this.cachedReport = report;\n this.cacheTimestamp = Date.now();\n\n // Persist to disk\n await this.reportStorage.save(report);\n } catch (error) {\n console.error('Cache refresh failed:', error);\n\n // Fallback: Load last saved report if cache is empty\n if (!this.cachedReport) {\n try {\n const stored = await this.reportStorage.loadLatest();\n if (stored) {\n this.cachedReport = stored.report;\n }\n } catch (fallbackError) {\n console.error('Failed to load fallback report:', fallbackError);\n }\n }\n }\n }\n\n /**\n * Get the Express app instance\n */\n getApp(): Application {\n return this.app;\n }\n\n /**\n * Setup middleware\n */\n private setupMiddleware(): void {\n this.app.use(express.json());\n\n // CORS for development\n this.app.use((_req, res, next) => {\n res.header('Access-Control-Allow-Origin', '*');\n res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.header('Access-Control-Allow-Headers', 'Content-Type');\n next();\n });\n }\n\n /**\n * Setup all routes\n */\n private setupRoutes(): void {\n this.setupReportRoutes();\n this.setupDecisionRoutes();\n this.setupAnalyticsRoutes();\n this.setupHealthRoute();\n this.setupStaticFiles();\n }\n\n /**\n * Setup report-related routes\n */\n private setupReportRoutes(): void {\n // GET /api/report/latest - Serve cached report\n this.app.get('/api/report/latest', (_req: Request, res: Response) => {\n if (!this.cachedReport) {\n res.status(503).json({ error: 'Report not ready' });\n return;\n }\n\n res.json({\n ...this.cachedReport,\n cached: true,\n cacheAge: Date.now() - this.cacheTimestamp,\n });\n });\n\n // GET /api/report/history?days=30\n this.app.get('/api/report/history', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const history = await this.reportStorage.loadHistory(days);\n res.json(history);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load history',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/report/dates\n this.app.get('/api/report/dates', async (_req: Request, res: Response) => {\n try {\n const dates = await this.reportStorage.getAvailableDates();\n res.json(dates);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load dates',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/report/:date\n this.app.get('/api/report/:date', async (req: Request, res: Response) => {\n try {\n const date = req.params.date;\n if (!date) {\n res.status(400).json({ error: 'Date parameter required' });\n return;\n }\n\n const report = await this.reportStorage.loadByDate(date);\n\n if (!report) {\n res.status(404).json({ error: 'Report not found' });\n return;\n }\n\n res.json(report);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load report',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup decision-related routes\n */\n private setupDecisionRoutes(): void {\n // GET /api/decisions\n this.app.get('/api/decisions', async (_req: Request, res: Response) => {\n try {\n const decisions = this.registry.getAll();\n res.json(decisions);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load decisions',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/decisions/:id\n this.app.get('/api/decisions/:id', async (req: Request, res: Response) => {\n try {\n const id = req.params.id;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const decision = this.registry.get(id);\n\n if (!decision) {\n res.status(404).json({ error: 'Decision not found' });\n return;\n }\n\n res.json(decision);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to load decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup analytics-related routes\n */\n private setupAnalyticsRoutes(): void {\n // GET /api/analytics/summary?days=90\n this.app.get('/api/analytics/summary', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 90;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const summary = await engine.generateSummary(history);\n res.json(summary);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to generate analytics',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/analytics/decision/:id?days=90\n this.app.get('/api/analytics/decision/:id', async (req: Request, res: Response) => {\n try {\n const id = req.params.id;\n if (!id) {\n res.status(400).json({ error: 'Decision ID required' });\n return;\n }\n\n const days = parseInt(req.query.days as string) || 90;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length === 0) {\n res.status(404).json({ error: 'No historical data available' });\n return;\n }\n\n const engine = new AnalyticsEngine();\n const metrics = await engine.analyzeDecision(id, history);\n res.json(metrics);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze decision',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/drift?days=2\n this.app.get('/api/drift', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 2;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for drift analysis' });\n return;\n }\n\n const currentEntry = history[0];\n const previousEntry = history[1];\n\n if (!currentEntry || !previousEntry) {\n res.status(400).json({ error: 'Invalid history data' });\n return;\n }\n\n const drift = await detectDrift(currentEntry.report, previousEntry.report);\n res.json(drift);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze drift',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n\n // GET /api/trend?days=30\n this.app.get('/api/trend', async (req: Request, res: Response) => {\n try {\n const days = parseInt(req.query.days as string) || 30;\n const history = await this.reportStorage.loadHistory(days);\n\n if (history.length < 2) {\n res.status(404).json({ error: 'Need at least 2 reports for trend analysis' });\n return;\n }\n\n const trend = await analyzeTrend(history);\n res.json(trend);\n } catch (error) {\n res.status(500).json({\n error: 'Failed to analyze trend',\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n });\n }\n\n /**\n * Setup health check route\n */\n private setupHealthRoute(): void {\n this.app.get('/api/health', (_req: Request, res: Response) => {\n res.json({\n status: 'ok',\n timestamp: new Date().toISOString(),\n project: this.config.project.name,\n cache: {\n loaded: this.cachedReport !== null,\n age: Date.now() - this.cacheTimestamp,\n nextRefresh: this.CACHE_TTL - (Date.now() - this.cacheTimestamp),\n },\n });\n });\n }\n\n /**\n * Setup static file serving\n */\n private setupStaticFiles(): void {\n // Serve static frontend files\n const publicDir = join(__dirname, 'public');\n this.app.use(express.static(publicDir, {\n maxAge: '1h', // Cache static assets\n etag: true,\n }));\n\n // Fallback to index.html for SPA routing\n this.app.get('*', (_req: Request, res: Response) => {\n res.sendFile(join(publicDir, 'index.html'));\n });\n }\n}\n\n/**\n * Create and configure the dashboard server (factory function)\n * @returns DashboardServer instance\n */\nexport function createDashboardServer(options: DashboardOptions): DashboardServer {\n return new DashboardServer(options);\n}\n\n// Export the class for advanced usage\nexport { DashboardServer };\n","/**\n * Impact command - Analyze impact of decision changes\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { createPropagationEngine } from '../../propagation/engine.js';\nimport { loadConfig } from '../../config/loader.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\nimport type { ImpactAnalysis } from '../../core/types/index.js';\n\ninterface ImpactOptions {\n change?: string;\n json?: boolean;\n showSteps?: boolean;\n}\n\nexport const impactCommand = new Command('impact')\n .description('Analyze impact of decision changes')\n .argument('<decision-id>', 'Decision ID to analyze')\n .option('-c, --change <type>', 'Type of change (created, modified, deprecated)', 'modified')\n .option('--json', 'Output as JSON')\n .option('--show-steps', 'Show detailed migration steps', true)\n .action(async (decisionId: string, options: ImpactOptions) => {\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 change type\n const changeType = (options.change || 'modified') as 'created' | 'modified' | 'deprecated';\n if (!['created', 'modified', 'deprecated'].includes(changeType)) {\n spinner.fail();\n console.error(chalk.red(`Invalid change type: ${changeType}`));\n console.error(chalk.dim('Valid types: created, modified, deprecated'));\n process.exit(1);\n }\n\n spinner.text = `Analyzing impact of ${changeType} decision ${decisionId}...`;\n\n // Create propagation engine and analyze impact\n const engine = createPropagationEngine();\n const analysis = await engine.analyzeImpact(decisionId, changeType, config, { cwd });\n\n spinner.stop();\n\n // Output results\n if (options.json) {\n console.log(JSON.stringify(analysis, null, 2));\n } else {\n printImpactAnalysis(analysis, options.showSteps !== false);\n }\n } catch (error) {\n spinner.fail('Impact analysis failed');\n throw error;\n }\n });\n\n/**\n * Print impact analysis in human-readable format\n */\nfunction printImpactAnalysis(analysis: ImpactAnalysis, showSteps: boolean): void {\n console.log(chalk.bold(`\\n=== Impact Analysis: ${analysis.decision} ===\\n`));\n\n // Change type\n const changeLabel = chalk.cyan(analysis.change);\n console.log(`Change Type: ${changeLabel}`);\n\n // Estimated effort\n const effortColor = analysis.estimatedEffort === 'high'\n ? chalk.red\n : analysis.estimatedEffort === 'medium'\n ? chalk.yellow\n : chalk.green;\n console.log(`Estimated Effort: ${effortColor(analysis.estimatedEffort.toUpperCase())}\\n`);\n\n // Affected files\n console.log(chalk.bold(`Affected Files: ${analysis.affectedFiles.length}`));\n\n if (analysis.affectedFiles.length > 0) {\n const displayCount = Math.min(analysis.affectedFiles.length, 10);\n\n for (let i = 0; i < displayCount; i++) {\n const file = analysis.affectedFiles[i];\n if (!file) continue;\n\n const violationText = file.violations === 1 ? '1 violation' : `${file.violations} violations`;\n const autoFixText = file.autoFixable > 0\n ? chalk.green(` (${file.autoFixable} auto-fixable)`)\n : '';\n\n console.log(` ${chalk.red('●')} ${file.path} - ${violationText}${autoFixText}`);\n }\n\n if (analysis.affectedFiles.length > displayCount) {\n const remaining = analysis.affectedFiles.length - displayCount;\n console.log(chalk.dim(` ... and ${remaining} more file(s)`));\n }\n } else {\n console.log(chalk.green(' No violations found'));\n }\n\n // Migration steps\n if (showSteps && analysis.migrationSteps && analysis.migrationSteps.length > 0) {\n console.log(chalk.bold('\\nMigration Plan:'));\n\n for (const step of analysis.migrationSteps) {\n const icon = step.automated ? '🤖' : '👤';\n const typeLabel = step.automated ? chalk.green('[Automated]') : chalk.yellow('[Manual]');\n\n console.log(` ${icon} Step ${step.order}: ${step.description} ${typeLabel}`);\n\n if (step.files.length > 0) {\n const displayFiles = Math.min(step.files.length, 3);\n for (let i = 0; i < displayFiles; i++) {\n console.log(chalk.dim(` - ${step.files[i]}`));\n }\n\n if (step.files.length > displayFiles) {\n console.log(chalk.dim(` ... and ${step.files.length - displayFiles} more file(s)`));\n }\n }\n\n console.log('');\n }\n }\n\n // Summary\n const totalViolations = analysis.affectedFiles.reduce((sum, f) => sum + f.violations, 0);\n const totalAutoFixable = analysis.affectedFiles.reduce((sum, f) => sum + f.autoFixable, 0);\n const manualFixes = totalViolations - totalAutoFixable;\n\n console.log(chalk.bold('Summary:'));\n console.log(` Total Violations: ${totalViolations}`);\n console.log(` Auto-fixable: ${chalk.green(totalAutoFixable)}`);\n console.log(` Manual Fixes Required: ${manualFixes > 0 ? chalk.yellow(manualFixes) : chalk.green(0)}`);\n}\n","/**\n * Dependency graph for impact analysis\n */\nimport type { Decision } from '../core/types/index.js';\nimport { matchesPattern } from '../utils/glob.js';\n\nexport interface GraphNode {\n type: 'decision' | 'constraint' | 'file';\n id: string;\n edges: string[];\n}\n\nexport interface DependencyGraph {\n nodes: Map<string, GraphNode>;\n decisionToFiles: Map<string, Set<string>>;\n fileToDecisions: Map<string, Set<string>>;\n}\n\n/**\n * Build dependency graph from decisions and file list\n */\nexport async function buildDependencyGraph(\n decisions: Decision[],\n files: string[]\n): Promise<DependencyGraph> {\n const nodes = new Map<string, GraphNode>();\n const decisionToFiles = new Map<string, Set<string>>();\n const fileToDecisions = new Map<string, Set<string>>();\n\n // Add decision nodes\n for (const decision of decisions) {\n const decisionId = `decision:${decision.metadata.id}`;\n nodes.set(decisionId, {\n type: 'decision',\n id: decision.metadata.id,\n edges: decision.constraints.map(c => `constraint:${decision.metadata.id}/${c.id}`),\n });\n\n // Add constraint nodes\n for (const constraint of decision.constraints) {\n const constraintId = `constraint:${decision.metadata.id}/${constraint.id}`;\n const matchingFiles: string[] = [];\n\n for (const file of files) {\n if (matchesPattern(file, constraint.scope)) {\n matchingFiles.push(`file:${file}`);\n\n // Update file -> decision mapping\n const fileDecisions = fileToDecisions.get(file) || new Set();\n fileDecisions.add(decision.metadata.id);\n fileToDecisions.set(file, fileDecisions);\n\n // Update decision -> files mapping\n const decFiles = decisionToFiles.get(decision.metadata.id) || new Set();\n decFiles.add(file);\n decisionToFiles.set(decision.metadata.id, decFiles);\n }\n }\n\n nodes.set(constraintId, {\n type: 'constraint',\n id: `${decision.metadata.id}/${constraint.id}`,\n edges: matchingFiles,\n });\n }\n }\n\n // Add file nodes\n for (const file of files) {\n const fileId = `file:${file}`;\n if (!nodes.has(fileId)) {\n nodes.set(fileId, {\n type: 'file',\n id: file,\n edges: [],\n });\n }\n }\n\n return {\n nodes,\n decisionToFiles,\n fileToDecisions,\n };\n}\n\n/**\n * Get files affected by a decision\n */\nexport function getAffectedFiles(\n graph: DependencyGraph,\n decisionId: string\n): string[] {\n const files = graph.decisionToFiles.get(decisionId);\n return files ? Array.from(files) : [];\n}\n\n/**\n * Get decisions affecting a file\n */\nexport function getAffectingDecisions(\n graph: DependencyGraph,\n filePath: string\n): string[] {\n const decisions = graph.fileToDecisions.get(filePath);\n return decisions ? Array.from(decisions) : [];\n}\n\n/**\n * Calculate transitive closure for a node\n */\nexport function getTransitiveDependencies(\n graph: DependencyGraph,\n nodeId: string,\n visited: Set<string> = new Set()\n): string[] {\n if (visited.has(nodeId)) {\n return [];\n }\n\n visited.add(nodeId);\n const node = graph.nodes.get(nodeId);\n\n if (!node) {\n return [];\n }\n\n const deps: string[] = [nodeId];\n\n for (const edge of node.edges) {\n deps.push(...getTransitiveDependencies(graph, edge, visited));\n }\n\n return deps;\n}\n","/**\n * Propagation Engine - Analyze impact of decision changes\n */\nimport type {\n ImpactAnalysis,\n AffectedFile,\n MigrationStep,\n SpecBridgeConfig,\n} from '../core/types/index.js';\nimport { createRegistry, type Registry } from '../registry/registry.js';\nimport { createVerificationEngine } from '../verification/engine.js';\nimport { buildDependencyGraph, getAffectedFiles, type DependencyGraph } from './graph.js';\nimport { glob } from '../utils/glob.js';\n\nexport interface PropagationOptions {\n cwd?: string;\n}\n\n/**\n * Propagation Engine class\n */\nexport class PropagationEngine {\n private registry: Registry;\n private graph: DependencyGraph | null = null;\n\n constructor(registry?: Registry) {\n this.registry = registry || createRegistry();\n }\n\n /**\n * Initialize the engine with current state\n */\n async initialize(config: SpecBridgeConfig, options: PropagationOptions = {}): Promise<void> {\n const { cwd = process.cwd() } = options;\n\n // Load registry\n await this.registry.load();\n\n // Get all files\n const files = await glob(config.project.sourceRoots, {\n cwd,\n ignore: config.project.exclude,\n absolute: true,\n });\n\n // Build dependency graph\n const decisions = this.registry.getActive();\n this.graph = await buildDependencyGraph(decisions, files);\n }\n\n /**\n * Analyze impact of changing a decision\n */\n async analyzeImpact(\n decisionId: string,\n change: 'created' | 'modified' | 'deprecated',\n config: SpecBridgeConfig,\n options: PropagationOptions = {}\n ): Promise<ImpactAnalysis> {\n const { cwd = process.cwd() } = options;\n\n // Ensure initialized\n if (!this.graph) {\n await this.initialize(config, options);\n }\n\n // Get affected files\n const affectedFilePaths = getAffectedFiles(this.graph!, decisionId);\n\n // Run verification on affected files\n const verificationEngine = createVerificationEngine(this.registry);\n const result = await verificationEngine.verify(config, {\n files: affectedFilePaths,\n decisions: [decisionId],\n cwd,\n });\n\n // Group violations by file\n const fileViolations = new Map<string, { total: number; autoFixable: number }>();\n for (const violation of result.violations) {\n const existing = fileViolations.get(violation.file) || { total: 0, autoFixable: 0 };\n existing.total++;\n if (violation.autofix) {\n existing.autoFixable++;\n }\n fileViolations.set(violation.file, existing);\n }\n\n // Build affected files list\n const affectedFiles: AffectedFile[] = affectedFilePaths.map(path => ({\n path,\n violations: fileViolations.get(path)?.total || 0,\n autoFixable: fileViolations.get(path)?.autoFixable || 0,\n }));\n\n // Sort by violations (most first)\n affectedFiles.sort((a, b) => b.violations - a.violations);\n\n // Estimate effort\n const totalViolations = result.violations.length;\n const totalAutoFixable = result.violations.filter(v => v.autofix).length;\n const manualFixes = totalViolations - totalAutoFixable;\n\n let estimatedEffort: 'low' | 'medium' | 'high';\n if (manualFixes === 0) {\n estimatedEffort = 'low';\n } else if (manualFixes <= 10) {\n estimatedEffort = 'medium';\n } else {\n estimatedEffort = 'high';\n }\n\n // Generate migration steps\n const migrationSteps = this.generateMigrationSteps(\n affectedFiles,\n totalAutoFixable > 0\n );\n\n return {\n decision: decisionId,\n change,\n affectedFiles,\n estimatedEffort,\n migrationSteps,\n };\n }\n\n /**\n * Generate migration steps\n */\n private generateMigrationSteps(\n affectedFiles: AffectedFile[],\n hasAutoFixes: boolean\n ): MigrationStep[] {\n const steps: MigrationStep[] = [];\n let order = 1;\n\n // Step 1: Run auto-fixes if available\n if (hasAutoFixes) {\n steps.push({\n order: order++,\n description: 'Run auto-fix for mechanical violations',\n files: affectedFiles.filter(f => f.autoFixable > 0).map(f => f.path),\n automated: true,\n });\n }\n\n // Step 2: Manual fixes for remaining violations\n const filesWithManualFixes = affectedFiles.filter(\n f => f.violations > f.autoFixable\n );\n\n if (filesWithManualFixes.length > 0) {\n // Group by severity/priority\n const highPriority = filesWithManualFixes.filter(f => f.violations > 5);\n const mediumPriority = filesWithManualFixes.filter(\n f => f.violations <= 5 && f.violations > 1\n );\n const lowPriority = filesWithManualFixes.filter(f => f.violations === 1);\n\n if (highPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix high-violation files first',\n files: highPriority.map(f => f.path),\n automated: false,\n });\n }\n\n if (mediumPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix medium-violation files',\n files: mediumPriority.map(f => f.path),\n automated: false,\n });\n }\n\n if (lowPriority.length > 0) {\n steps.push({\n order: order++,\n description: 'Fix remaining files',\n files: lowPriority.map(f => f.path),\n automated: false,\n });\n }\n }\n\n // Step 3: Verification\n steps.push({\n order: order++,\n description: 'Run verification to confirm all violations resolved',\n files: [],\n automated: true,\n });\n\n return steps;\n }\n\n /**\n * Get dependency graph\n */\n getGraph(): DependencyGraph | null {\n return this.graph;\n }\n}\n\n/**\n * Create propagation engine\n */\nexport function createPropagationEngine(registry?: Registry): PropagationEngine {\n return new PropagationEngine(registry);\n}\n","/**\n * Migrate command - Automated v1 → v2 migration\n */\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { join } from 'node:path';\nimport { readdir, copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { loadConfig } from '../../config/loader.js';\nimport { generateReport } from '../../reporting/reporter.js';\nimport { pathExists, getSpecBridgeDir } from '../../utils/fs.js';\nimport { NotInitializedError } from '../../core/errors/index.js';\n\ninterface MigrateOptions {\n from?: string;\n to?: string;\n dryRun?: boolean;\n}\n\ninterface MigrationReport {\n decisionsUpdated: number;\n backupPath: string;\n complianceComparison?: {\n v1: number;\n v2: number;\n difference: number;\n };\n changes: string[];\n}\n\nexport const migrateCommand = new Command('migrate')\n .description('Migrate SpecBridge configuration and decisions')\n .option('--from <version>', 'Source version (e.g., v1, v1.3)', 'v1')\n .option('--to <version>', 'Target version (e.g., v2, v2.0)', 'v2')\n .option('--dry-run', 'Preview changes without applying')\n .action(async (options: MigrateOptions) => {\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 from = options.from || 'v1';\n const to = options.to || 'v2';\n\n console.log(chalk.blue.bold(`\\n=== SpecBridge Migration: ${from} → ${to} ===\\n`));\n\n if (from !== 'v1' && from !== 'v1.3') {\n console.error(chalk.red(`Unsupported source version: ${from}`));\n console.log(chalk.gray('Supported: v1, v1.3'));\n process.exit(1);\n }\n\n if (to !== 'v2' && to !== 'v2.0') {\n console.error(chalk.red(`Unsupported target version: ${to}`));\n console.log(chalk.gray('Supported: v2, v2.0'));\n process.exit(1);\n }\n\n const spinner = ora('Analyzing current configuration...').start();\n\n try {\n const report: MigrationReport = {\n decisionsUpdated: 0,\n backupPath: '',\n changes: [],\n };\n\n // Step 1: Create backup\n spinner.text = 'Creating backup...';\n const backupPath = await createBackup(cwd, options.dryRun || false);\n report.backupPath = backupPath;\n report.changes.push(`Created backup at: ${backupPath}`);\n\n // Step 2: Generate v1 compliance report for comparison\n spinner.text = 'Generating v1 compliance baseline...';\n let v1Compliance: number | undefined;\n try {\n const config = await loadConfig(cwd);\n const v1Report = await generateReport(config, { cwd, legacyCompliance: true });\n v1Compliance = v1Report.summary.compliance;\n } catch (error) {\n spinner.warn('Could not generate v1 baseline report');\n }\n\n // Step 3: Migrate decision files\n spinner.text = 'Migrating decision files...';\n const decisionsUpdated = await migrateDecisions(cwd, options.dryRun || false);\n report.decisionsUpdated = decisionsUpdated;\n\n if (decisionsUpdated > 0) {\n report.changes.push(`Updated ${decisionsUpdated} decision file(s)`);\n } else {\n report.changes.push('No decision files needed migration');\n }\n\n // Step 4: Generate v2 compliance report for comparison\n if (!options.dryRun && v1Compliance !== undefined) {\n spinner.text = 'Generating v2 compliance comparison...';\n try {\n const config = await loadConfig(cwd);\n const v2Report = await generateReport(config, { cwd, legacyCompliance: false });\n const v2Compliance = v2Report.summary.compliance;\n\n report.complianceComparison = {\n v1: v1Compliance,\n v2: v2Compliance,\n difference: v2Compliance - v1Compliance,\n };\n } catch (error) {\n spinner.warn('Could not generate v2 comparison report');\n }\n }\n\n // Step 5: Validate all decisions\n if (!options.dryRun) {\n spinner.text = 'Validating migrated decisions...';\n // The loadConfig call above already validates, so if we got here, we're good\n report.changes.push('All decisions validated successfully');\n }\n\n spinner.succeed(options.dryRun ? 'Migration preview complete' : 'Migration complete');\n\n // Display report\n console.log(chalk.green.bold('\\n✓ Migration Summary:\\n'));\n console.log(chalk.bold('Backup:'));\n console.log(` ${report.backupPath}`);\n console.log('');\n\n console.log(chalk.bold('Changes:'));\n for (const change of report.changes) {\n console.log(` • ${change}`);\n }\n console.log('');\n\n if (report.complianceComparison) {\n console.log(chalk.bold('Compliance Comparison:'));\n console.log(` v1.3 formula: ${report.complianceComparison.v1}%`);\n console.log(` v2.0 formula: ${report.complianceComparison.v2}%`);\n\n const diff = report.complianceComparison.difference;\n const diffColor = diff > 0 ? chalk.green : diff < 0 ? chalk.red : chalk.yellow;\n console.log(` Difference: ${diffColor(`${diff > 0 ? '+' : ''}${diff.toFixed(1)}%`)}`);\n console.log('');\n\n if (Math.abs(diff) > 10) {\n console.log(chalk.yellow('⚠️ Note: Compliance score changed significantly due to severity weighting.'));\n console.log(chalk.gray(' Consider adjusting CI thresholds if needed.\\n'));\n }\n }\n\n if (options.dryRun) {\n console.log(chalk.yellow('This was a dry run. No changes were applied.'));\n console.log(chalk.gray('Run without --dry-run to apply changes.\\n'));\n } else {\n console.log(chalk.green('✓ Migration successful!'));\n console.log(chalk.gray(`\\nRollback: Copy files from ${report.backupPath} back to .specbridge/decisions/\\n`));\n }\n\n } catch (error) {\n spinner.fail('Migration failed');\n console.error(chalk.red('\\nError:'), error instanceof Error ? error.message : error);\n console.log(chalk.gray('\\nNo changes were applied.'));\n throw error;\n }\n });\n\n/**\n * Create backup of .specbridge/decisions/\n */\nasync function createBackup(cwd: string, dryRun: boolean): Promise<string> {\n const decisionsDir = join(getSpecBridgeDir(cwd), 'decisions');\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-').split('T').join('_');\n const backupDir = join(getSpecBridgeDir(cwd), 'decisions.backup', timestamp);\n\n if (dryRun) {\n return backupDir;\n }\n\n await mkdir(backupDir, { recursive: true });\n\n // Copy all decision files\n if (await pathExists(decisionsDir)) {\n const files = await readdir(decisionsDir);\n for (const file of files) {\n if (file.endsWith('.decision.yaml') || file.endsWith('.decision.yml')) {\n await copyFile(\n join(decisionsDir, file),\n join(backupDir, file)\n );\n }\n }\n }\n\n return backupDir;\n}\n\n/**\n * Migrate decision files from v1 to v2 format\n * Main change: verifier field → check.verifier\n */\nasync function migrateDecisions(cwd: string, dryRun: boolean): Promise<number> {\n const decisionsDir = join(getSpecBridgeDir(cwd), 'decisions');\n\n if (!await pathExists(decisionsDir)) {\n return 0;\n }\n\n const files = await readdir(decisionsDir);\n let updatedCount = 0;\n\n for (const file of files) {\n if (!file.endsWith('.decision.yaml') && !file.endsWith('.decision.yml')) {\n continue;\n }\n\n const filePath = join(decisionsDir, file);\n const content = await readFile(filePath, 'utf-8');\n\n // Check if file needs migration\n // Look for constraints with 'verifier:' field (v1 format)\n const needsMigration = /^\\s+verifier:\\s+\\S+/m.test(content);\n\n if (!needsMigration) {\n continue;\n }\n\n // Migrate: Convert verifier field to check block\n // This is a simple regex-based migration\n // Pattern: \" verifier: <name>\" → \" check:\\n verifier: <name>\"\n let migratedContent = content.replace(\n /^(\\s+)verifier:\\s+(\\S+)$/gm,\n '$1check:\\n$1 verifier: $2'\n );\n\n if (dryRun) {\n console.log(chalk.gray(` Would migrate: ${file}`));\n updatedCount++;\n } else {\n await writeFile(filePath, migratedContent, 'utf-8');\n updatedCount++;\n }\n }\n\n return updatedCount;\n}\n"],"mappings":";;;AAIA,SAAS,WAAAA,iBAAe;AACxB,OAAOC,aAAW;AAClB,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,QAAAC,cAAY;;;ACDvB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MACA,SACA,YAChB;AACA,UAAM,OAAO;AAJG;AACA;AACA;AAGhB,SAAK,OAAO;AACZ,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAChD;AACF;AAKO,IAAM,cAAN,cAA0B,gBAAgB;AAAA,EAC/C,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,gBAAgB,OAAO;AACtC,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,0BAAN,cAAsC,gBAAgB;AAAA,EAC3D,YACE,SACgB,YACA,kBAChB;AACA,UAAM,SAAS,6BAA6B,EAAE,YAAY,iBAAiB,CAAC;AAH5D;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,wBAAN,cAAoC,gBAAgB;AAAA,EACzD,YAAY,YAAoB;AAC9B,UAAM,uBAAuB,UAAU,IAAI,sBAAsB,EAAE,WAAW,CAAC;AAC/E,SAAK,OAAO;AAAA,EACd;AACF;AAmCO,IAAM,kBAAN,cAA8B,gBAAgB;AAAA,EACnD,YAAY,SAAiCC,OAAc;AACzD,UAAM,SAAS,qBAAqB,EAAE,MAAAA,MAAK,CAAC;AADD,gBAAAA;AAE3C,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,0BAAN,cAAsC,gBAAgB;AAAA,EAC3D,YAAYA,OAAc;AACxB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SAAO;AACT;;;A9EzNA,IAAMC,aAAYC,SAAQC,eAAc,YAAY,GAAG,CAAC;AAGxD,IAAM,kBAAkBC,OAAKH,YAAW,iBAAiB;AACzD,IAAM,cAAc,KAAK,MAAMI,cAAa,iBAAiB,OAAO,CAAC;AAErE,IAAM,UAAU,IAAIC,UAAQ;AAE5B,QACG,KAAK,YAAY,EACjB,YAAY,2GAA2G,EACvH,QAAQ,YAAY,OAAO;AAG9B,QAAQ,WAAW,WAAW;AAC9B,QAAQ,WAAW,YAAY;AAC/B,QAAQ,WAAW,aAAa;AAChC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,WAAW;AAC9B,QAAQ,WAAW,aAAa;AAChC,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,UAAU;AAC7B,QAAQ,WAAW,YAAY;AAC/B,QAAQ,WAAW,gBAAgB;AACnC,QAAQ,WAAW,aAAa;AAChC,QAAQ,WAAW,gBAAgB;AACnC,QAAQ,WAAW,gBAAgB;AACnC,QAAQ,WAAW,aAAa;AAChC,QAAQ,WAAW,cAAc;AAGjC,QAAQ,aAAa,CAAC,QAAQ;AAC5B,MAAI,IAAI,SAAS,oBAAoB,IAAI,SAAS,2BAA2B;AAC3E,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,MAAI,IAAI,SAAS,qBAAqB;AACpC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,UAAQ,MAAMC,QAAM,IAAI,YAAY,GAAG,CAAC,CAAC;AACzC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAGD,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAiB;AACvD,UAAQ,MAAMA,QAAM,IAAI,YAAY,KAAK,CAAC,CAAC;AAC3C,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Command","chalk","readFileSync","fileURLToPath","dirname","join","path","join","path","path","join","Command","chalk","ora","join","path","dirname","dirname","Node","path","Node","Command","ora","join","chalk","Command","chalk","ora","Project","chalk","join","z","SeveritySchema","VerificationConfigSchema","path","join","Node","Node","path","relative","path","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","SyntaxKind","join","Minimatch","fileURLToPath","v","bf","readdir","p","ret","resolve","res","readdir","path","p","resolve","process","sync","relative","GLOBSTAR","path","rest","path","abs","target","defaultPlatform","fileURLToPath","Minimatch","Minimatch","escape","unescape","glob","join","glob","pluginLoader","stat","readFile","createHash","readFile","Project","resolve","chalk","readFile","writeFile","stdout","chalk","Command","ora","chalk","Command","Command","chalk","Command","chalk","Command","chalk","Command","chalk","getTypeIcon","Command","chalk","ora","join","Command","ora","join","chalk","Command","chalk","join","Command","chalk","join","Command","Command","chalk","ora","join","hookCommand","Command","ora","join","chalk","execFile","promisify","execFileAsync","stdout","Command","chalk","ora","join","violationsBySeverity","chalk","table","getStatusColor","truncate","join","join","Command","ora","chalk","join","Command","chalk","Command","chalk","Command","fileURLToPath","path","Project","chalk","fileURLToPath","Project","chalk","path","Command","Command","chalk","path","Command","path","chalk","Command","fileURLToPath","dirname","join","z","z","__dirname","dirname","fileURLToPath","packageJsonPath","join","Command","Command","Command","Command","chalk","ora","Command","ora","chalk","Command","chalk","join","dirname","fileURLToPath","dirname","fileURLToPath","join","Command","chalk","Command","chalk","ora","buildDependencyGraph","buildDependencyGraph","path","Command","ora","chalk","Command","chalk","ora","join","readdir","mkdir","readFile","writeFile","Command","chalk","ora","join","mkdir","readdir","readFile","writeFile","__dirname","dirname","fileURLToPath","join","readFileSync","Command","chalk"]}