bilmem 0.1.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/README.md +439 -0
- package/dist/canonical-CglQQ0xc.d.ts +262 -0
- package/dist/cli/index.js +7601 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/core/index.d.ts +311 -0
- package/dist/core/index.js +1975 -0
- package/dist/core/index.js.map +1 -0
- package/dist/filesystem-B3qAej0l.d.ts +69 -0
- package/dist/index.d.ts +163 -0
- package/dist/index.js +7765 -0
- package/dist/index.js.map +1 -0
- package/dist/install/index.d.ts +373 -0
- package/dist/install/index.js +6632 -0
- package/dist/install/index.js.map +1 -0
- package/dist/jev/index.d.ts +32 -0
- package/dist/jev/index.js +269 -0
- package/dist/jev/index.js.map +1 -0
- package/dist/mcp/index.d.ts +13 -0
- package/dist/mcp/index.js +5479 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/rules/index.d.ts +59 -0
- package/dist/rules/index.js +388 -0
- package/dist/rules/index.js.map +1 -0
- package/dist/scanner/index.d.ts +169 -0
- package/dist/scanner/index.js +3829 -0
- package/dist/scanner/index.js.map +1 -0
- package/dist/search/index.d.ts +44 -0
- package/dist/search/index.js +301 -0
- package/dist/search/index.js.map +1 -0
- package/dist/stats/index.d.ts +60 -0
- package/dist/stats/index.js +1373 -0
- package/dist/stats/index.js.map +1 -0
- package/dist/storage/index.d.ts +82 -0
- package/dist/storage/index.js +1748 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/types-Nxq5Gzay.d.ts +390 -0
- package/package.json +71 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/scanner/filesystem.ts","../../src/core/knowledge.ts","../../src/core/quarantine.ts","../../src/scanner/markdown.ts","../../src/scanner/git.ts","../../src/scanner/source.ts","../../src/scanner/engine.ts","../../src/core/unknown.ts","../../src/core/relations.ts","../../src/storage/canonical.ts","../../src/rules/loader.ts","../../src/stats/events.ts","../../src/search/indexer.ts","../../src/rules/evaluator.ts"],"sourcesContent":["import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Observation } from '../core/types.js';\nimport { createObservation } from '../core/knowledge.js';\n\nexport interface ScannedFileInfo {\n path: string;\n relativePath: string;\n name: string;\n ext: string;\n size: number;\n mtimeMs?: number;\n isDirectory?: boolean;\n}\n\nexport interface WalkOptions {\n maxDepth?: number;\n maxFiles?: number;\n ignoredDirs?: Set<string> | string[];\n includeHidden?: boolean;\n readGitignore?: boolean;\n filter?: (entry: ScannedFileInfo) => boolean;\n}\n\nconst DEFAULT_IGNORED_DIRS = new Set([\n '.git',\n '.bilmem',\n 'node_modules',\n 'dist',\n 'build',\n 'target',\n 'vendor',\n '.cache',\n '.idea',\n '.vscode',\n 'coverage',\n '.next',\n '.nuxt',\n '.turbo',\n '.output',\n 'tmp',\n 'temp'\n]);\n\n/**\n * Normalizes relative path to use standard forward slashes.\n */\nfunction normalizeRelPath(rel: string): string {\n return rel.split(path.sep).join('/');\n}\n\n/**\n * Basic gitignore parser: extracts ignore patterns from .gitignore file.\n */\nasync function loadGitignorePatterns(rootDir: string): Promise<RegExp[]> {\n try {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const content = await fs.readFile(gitignorePath, 'utf-8');\n const regexes: RegExp[] = [];\n\n for (const rawLine of content.split('\\n')) {\n const line = rawLine.trim();\n if (!line || line.startsWith('#')) continue;\n\n // Clean glob pattern\n let pattern = line.replace(/^\\//, '').replace(/\\/$/, '');\n if (!pattern) continue;\n\n // Escape special regex chars except * and ?\n pattern = pattern.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n pattern = pattern.replace(/\\*\\*/g, '.*');\n pattern = pattern.replace(/\\*/g, '[^/]*');\n pattern = pattern.replace(/\\?/g, '[^/]');\n\n try {\n regexes.push(new RegExp(`(^|/)${pattern}($|/)`));\n } catch {\n // Skip invalid pattern\n }\n }\n return regexes;\n } catch {\n return [];\n }\n}\n\n/**\n * High-performance, depth-controlled recursive directory walker.\n * Respects default ignores, .gitignore patterns, symlink circularity, and file limits.\n */\nexport async function walkDirectory(\n dir: string,\n optionsOrRoot?: string | WalkOptions,\n legacyFileList?: ScannedFileInfo[]\n): Promise<ScannedFileInfo[]> {\n let root: string;\n let options: WalkOptions;\n\n if (typeof optionsOrRoot === 'string') {\n root = optionsOrRoot;\n options = {};\n } else {\n options = optionsOrRoot ?? {};\n root = dir;\n }\n\n const fileList: ScannedFileInfo[] = legacyFileList ?? [];\n const maxDepth = options.maxDepth ?? 15;\n const maxFiles = options.maxFiles ?? 25000;\n const includeHidden = options.includeHidden ?? false;\n\n const ignoredDirs = new Set(DEFAULT_IGNORED_DIRS);\n if (options.ignoredDirs) {\n for (const d of options.ignoredDirs) {\n ignoredDirs.add(d.toLowerCase());\n }\n }\n\n const gitignoreRules = options.readGitignore !== false\n ? await loadGitignorePatterns(root)\n : [];\n\n const visitedRealPaths = new Set<string>();\n\n async function walk(currentDir: string, currentDepth: number): Promise<void> {\n if (currentDepth > maxDepth || fileList.length >= maxFiles) {\n return;\n }\n\n try {\n const real = await fs.realpath(currentDir);\n if (visitedRealPaths.has(real)) {\n return; // Circular symlink prevention\n }\n visitedRealPaths.add(real);\n } catch {\n return;\n }\n\n let entries;\n try {\n entries = await fs.readdir(currentDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (fileList.length >= maxFiles) break;\n\n const fullPath = path.join(currentDir, entry.name);\n const rawRelPath = path.relative(root, fullPath);\n const relPath = normalizeRelPath(rawRelPath);\n const lowerName = entry.name.toLowerCase();\n\n // Check gitignore rules\n if (gitignoreRules.some((rule) => rule.test(relPath))) {\n continue;\n }\n\n if (entry.isDirectory()) {\n if (ignoredDirs.has(lowerName)) continue;\n // Don't skip .github even if hidden is disabled\n if (!includeHidden && entry.name.startsWith('.') && lowerName !== '.github') {\n continue;\n }\n await walk(fullPath, currentDepth + 1);\n } else if (entry.isFile()) {\n if (!includeHidden && entry.name.startsWith('.') && lowerName !== '.env.example') {\n // Skip dotfiles unless explicitly requested\n continue;\n }\n\n const ext = path.extname(entry.name).toLowerCase();\n try {\n const stat = await fs.stat(fullPath);\n const fileInfo: ScannedFileInfo = {\n path: fullPath,\n relativePath: relPath,\n name: entry.name,\n ext,\n size: stat.size,\n mtimeMs: stat.mtimeMs,\n isDirectory: false\n };\n\n if (!options.filter || options.filter(fileInfo)) {\n fileList.push(fileInfo);\n }\n } catch {\n // Ignore unreadable file\n }\n }\n }\n }\n\n await walk(dir, 0);\n return fileList;\n}\n\n// --- Extensible Project Context ---\n\n/**\n * Queryable project context providing cached text and JSON reads for detectors.\n */\nexport class ProjectContext {\n readonly rootDir: string;\n readonly files: ScannedFileInfo[];\n private relPathSet: Set<string>;\n private fileNameSet: Set<string>;\n private textCache = new Map<string, string | null>();\n private jsonCache = new Map<string, unknown | null>();\n\n constructor(files: ScannedFileInfo[], rootDir: string) {\n this.rootDir = rootDir;\n this.files = files;\n this.relPathSet = new Set(files.map((f) => f.relativePath.toLowerCase()));\n this.fileNameSet = new Set(files.map((f) => f.name.toLowerCase()));\n }\n\n hasFile(nameOrRelPath: string): boolean {\n const lower = normalizeRelPath(nameOrRelPath).toLowerCase();\n return this.fileNameSet.has(lower) || this.relPathSet.has(lower);\n }\n\n hasDirectory(dirNameOrRelPath: string): boolean {\n const prefix = normalizeRelPath(dirNameOrRelPath).toLowerCase().replace(/\\/$/, '') + '/';\n return Array.from(this.relPathSet).some((p) => p.startsWith(prefix));\n }\n\n findFiles(predicate: (file: ScannedFileInfo) => boolean): ScannedFileInfo[] {\n return this.files.filter(predicate);\n }\n\n async readText(relativePath: string, maxBytes: number = 64 * 1024): Promise<string | null> {\n const key = normalizeRelPath(relativePath).toLowerCase();\n if (this.textCache.has(key)) {\n return this.textCache.get(key)!;\n }\n\n const fullPath = path.resolve(this.rootDir, relativePath);\n try {\n const handle = await fs.open(fullPath, 'r');\n const buffer = Buffer.alloc(maxBytes);\n const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);\n await handle.close();\n const content = buffer.toString('utf-8', 0, bytesRead);\n this.textCache.set(key, content);\n return content;\n } catch {\n this.textCache.set(key, null);\n return null;\n }\n }\n\n async readJson<T = any>(relativePath: string): Promise<T | null> {\n const key = normalizeRelPath(relativePath).toLowerCase();\n if (this.jsonCache.has(key)) {\n return this.jsonCache.get(key) as T | null;\n }\n\n const text = await this.readText(relativePath);\n if (!text) {\n this.jsonCache.set(key, null);\n return null;\n }\n\n try {\n const parsed = JSON.parse(text) as T;\n this.jsonCache.set(key, parsed);\n return parsed;\n } catch {\n this.jsonCache.set(key, null);\n return null;\n }\n }\n}\n\n// --- Extensible Convention Detector Engine ---\n\nexport type DetectorCategory =\n | 'runtime'\n | 'language'\n | 'package-manager'\n | 'framework'\n | 'testing'\n | 'database'\n | 'tooling'\n | 'ci-cd'\n | 'monorepo'\n | 'documentation'\n | 'architecture';\n\nexport interface ConventionDetector {\n id: string;\n name: string;\n category: DetectorCategory;\n description?: string;\n detect(ctx: ProjectContext): Promise<Observation | Observation[] | null> | Observation | Observation[] | null;\n}\n\nexport class ConventionRegistry {\n private detectors = new Map<string, ConventionDetector>();\n\n register(detector: ConventionDetector): this {\n this.detectors.set(detector.id, detector);\n return this;\n }\n\n unregister(id: string): boolean {\n return this.detectors.delete(id);\n }\n\n get(id: string): ConventionDetector | undefined {\n return this.detectors.get(id);\n }\n\n list(): ConventionDetector[] {\n return Array.from(this.detectors.values());\n }\n\n async run(ctx: ProjectContext): Promise<Observation[]> {\n const observations: Observation[] = [];\n for (const detector of this.detectors.values()) {\n try {\n const result = await detector.detect(ctx);\n if (result) {\n if (Array.isArray(result)) {\n observations.push(...result);\n } else {\n observations.push(result);\n }\n }\n } catch {\n // Individual detector failures do not abort scanning\n }\n }\n return observations;\n }\n}\n\n// --- Built-in Pluggable Detectors ---\n\nexport const BUILTIN_DETECTORS: ConventionDetector[] = [\n // 1. Node.js & package.json\n {\n id: 'node-manifest',\n name: 'Node.js Manifest Detector',\n category: 'runtime',\n async detect(ctx) {\n if (!ctx.hasFile('package.json')) return null;\n\n const pkg = await ctx.readJson<{\n name?: string;\n version?: string;\n type?: string;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n }>('package.json');\n\n const now = new Date().toISOString();\n const scripts = pkg?.scripts ? Object.keys(pkg.scripts) : [];\n const isEsm = pkg?.type === 'module';\n\n const scriptSummary = scripts.length > 0 ? ` with scripts: ${scripts.slice(0, 5).join(', ')}` : '';\n const moduleType = isEsm ? ' (ESM module)' : ' (CommonJS)';\n\n return createObservation({\n source: 'filesystem:package.json',\n claim: `Project utilizes Node.js ecosystem with package.json manifest${moduleType}${scriptSummary}`,\n provenance: { type: 'file', path: 'package.json', timestamp: now },\n confidence: 0.99,\n positive: ['node', 'npm', 'javascript', isEsm ? 'esm' : 'cjs', ...(pkg?.name ? [pkg.name.toLowerCase()] : [])],\n details: {\n ecosystem: 'node',\n name: pkg?.name,\n version: pkg?.version,\n type: pkg?.type,\n scripts\n }\n });\n }\n },\n\n // 2. Package Manager\n {\n id: 'package-manager',\n name: 'Package Manager Detector',\n category: 'package-manager',\n detect(ctx) {\n const now = new Date().toISOString();\n if (ctx.hasFile('pnpm-lock.yaml')) {\n return createObservation({\n source: 'filesystem:pnpm-lock.yaml',\n claim: 'Project utilizes pnpm as the package manager',\n provenance: { type: 'file', path: 'pnpm-lock.yaml', timestamp: now },\n confidence: 0.99,\n positive: ['pnpm', 'package-manager', 'node']\n });\n }\n if (ctx.hasFile('bun.lockb') || ctx.hasFile('bun.lock')) {\n return createObservation({\n source: 'filesystem:bun.lock',\n claim: 'Project utilizes Bun runtime and package manager',\n provenance: { type: 'file', path: 'bun.lock', timestamp: now },\n confidence: 0.99,\n positive: ['bun', 'package-manager']\n });\n }\n if (ctx.hasFile('yarn.lock')) {\n return createObservation({\n source: 'filesystem:yarn.lock',\n claim: 'Project utilizes Yarn package manager',\n provenance: { type: 'file', path: 'yarn.lock', timestamp: now },\n confidence: 0.99,\n positive: ['yarn', 'package-manager', 'node']\n });\n }\n if (ctx.hasFile('package-lock.json')) {\n return createObservation({\n source: 'filesystem:package-lock.json',\n claim: 'Project utilizes npm as package manager with package-lock.json',\n provenance: { type: 'file', path: 'package-lock.json', timestamp: now },\n confidence: 0.95,\n positive: ['npm', 'package-manager', 'node']\n });\n }\n return null;\n }\n },\n\n // 3. TypeScript Configuration\n {\n id: 'typescript-config',\n name: 'TypeScript Compiler Detector',\n category: 'language',\n async detect(ctx) {\n if (!ctx.hasFile('tsconfig.json')) return null;\n\n const tsconfig = await ctx.readJson<{\n compilerOptions?: {\n target?: string;\n module?: string;\n strict?: boolean;\n jsx?: string;\n };\n }>('tsconfig.json');\n\n const now = new Date().toISOString();\n const opts = tsconfig?.compilerOptions;\n const targetStr = opts?.target ? ` target ${opts.target}` : '';\n const strictStr = opts?.strict ? ' with strict mode' : '';\n\n return createObservation({\n source: 'filesystem:tsconfig.json',\n claim: `Project is configured for TypeScript compilation${targetStr}${strictStr}`,\n provenance: { type: 'file', path: 'tsconfig.json', timestamp: now },\n confidence: 0.99,\n positive: ['typescript', 'ts', ...(opts?.target ? [opts.target.toLowerCase()] : [])],\n details: { language: 'typescript', target: opts?.target, strict: opts?.strict }\n });\n }\n },\n\n // 4. Rust & Cargo\n {\n id: 'rust-cargo',\n name: 'Rust & Cargo Detector',\n category: 'language',\n async detect(ctx) {\n if (!ctx.hasFile('cargo.toml')) return null;\n const now = new Date().toISOString();\n const cargoText = await ctx.readText('Cargo.toml');\n const isWorkspace = cargoText?.includes('[workspace]') ?? false;\n const claim = isWorkspace\n ? 'Project utilizes Rust with Cargo workspace configuration'\n : 'Project utilizes Rust and Cargo';\n\n return createObservation({\n source: 'filesystem:cargo.toml',\n claim,\n provenance: { type: 'file', path: 'Cargo.toml', timestamp: now },\n confidence: 0.99,\n positive: ['rust', 'cargo', ...(isWorkspace ? ['workspace'] : [])],\n details: { ecosystem: 'rust', isWorkspace }\n });\n }\n },\n\n // 5. Go Modules\n {\n id: 'go-module',\n name: 'Go Modules Detector',\n category: 'language',\n async detect(ctx) {\n if (!ctx.hasFile('go.mod')) return null;\n const now = new Date().toISOString();\n const goModText = await ctx.readText('go.mod');\n const modMatch = goModText?.match(/^module\\s+([^\\s]+)/m);\n const modName = modMatch ? ` (${modMatch[1]})` : '';\n\n return createObservation({\n source: 'filesystem:go.mod',\n claim: `Project utilizes Go modules${modName}`,\n provenance: { type: 'file', path: 'go.mod', timestamp: now },\n confidence: 0.99,\n positive: ['go', 'golang'],\n details: { ecosystem: 'go', module: modMatch ? modMatch[1] : undefined }\n });\n }\n },\n\n // 6. Python Environment\n {\n id: 'python-project',\n name: 'Python Environment Detector',\n category: 'language',\n detect(ctx) {\n const hasPyproject = ctx.hasFile('pyproject.toml');\n const hasReqs = ctx.hasFile('requirements.txt');\n const hasPipfile = ctx.hasFile('pipfile');\n const hasUvLock = ctx.hasFile('uv.lock');\n const hasPoetry = ctx.hasFile('poetry.lock');\n\n if (!hasPyproject && !hasReqs && !hasPipfile && !hasUvLock && !hasPoetry) {\n return null;\n }\n\n const now = new Date().toISOString();\n const tools: string[] = [];\n if (hasUvLock) tools.push('uv');\n if (hasPoetry) tools.push('poetry');\n if (hasPyproject) tools.push('pyproject.toml');\n if (hasReqs) tools.push('requirements.txt');\n\n return createObservation({\n source: 'filesystem:python',\n claim: `Project contains Python dependencies (${tools.join(', ')})`,\n provenance: {\n type: 'file',\n path: hasPyproject ? 'pyproject.toml' : hasReqs ? 'requirements.txt' : 'uv.lock',\n timestamp: now\n },\n confidence: 0.95,\n positive: ['python', 'py', ...tools],\n details: { ecosystem: 'python', tools }\n });\n }\n },\n\n // 7. Monorepo & Workspaces\n {\n id: 'monorepo',\n name: 'Monorepo Workspace Detector',\n category: 'monorepo',\n detect(ctx) {\n const hasTurbo = ctx.hasFile('turbo.json');\n const hasNx = ctx.hasFile('nx.json');\n const hasPnpmWs = ctx.hasFile('pnpm-workspace.yaml');\n const hasLerna = ctx.hasFile('lerna.json');\n\n if (!hasTurbo && !hasNx && !hasPnpmWs && !hasLerna) {\n return null;\n }\n\n const now = new Date().toISOString();\n const tools: string[] = [];\n if (hasTurbo) tools.push('turborepo');\n if (hasNx) tools.push('nx');\n if (hasPnpmWs) tools.push('pnpm-workspaces');\n if (hasLerna) tools.push('lerna');\n\n return createObservation({\n source: 'filesystem:monorepo',\n claim: `Project is structured as a monorepo workspace managed by ${tools.join(', ')}`,\n provenance: { type: 'file', path: hasTurbo ? 'turbo.json' : hasPnpmWs ? 'pnpm-workspace.yaml' : 'nx.json', timestamp: now },\n confidence: 0.95,\n positive: ['monorepo', 'workspace', ...tools]\n });\n }\n },\n\n // 8. Testing Suites\n {\n id: 'testing-suite',\n name: 'Testing Suite & Framework Detector',\n category: 'testing',\n detect(ctx) {\n const now = new Date().toISOString();\n const hasVitest = ctx.hasFile('vitest.config.ts') || ctx.hasFile('vitest.config.js') || ctx.hasFile('vitest.config.mts');\n const hasJest = ctx.hasFile('jest.config.js') || ctx.hasFile('jest.config.ts');\n const hasPlaywright = ctx.hasFile('playwright.config.ts') || ctx.hasFile('playwright.config.js');\n const hasPytest = ctx.hasFile('pytest.ini') || ctx.hasFile('conftest.py');\n\n const testFiles = ctx.findFiles(\n (f) =>\n f.relativePath.includes('test') ||\n f.relativePath.includes('spec') ||\n f.name.endsWith('.test.ts') ||\n f.name.endsWith('.spec.ts') ||\n f.name.endsWith('.test.js') ||\n f.name.endsWith('_test.go') ||\n f.name.startsWith('test_')\n );\n\n if (!hasVitest && !hasJest && !hasPlaywright && !hasPytest && testFiles.length === 0) {\n return null;\n }\n\n const frameworks: string[] = [];\n if (hasVitest) frameworks.push('Vitest');\n if (hasJest) frameworks.push('Jest');\n if (hasPlaywright) frameworks.push('Playwright');\n if (hasPytest) frameworks.push('Pytest');\n\n const fwStr = frameworks.length > 0 ? ` (${frameworks.join(', ')})` : '';\n\n return createObservation({\n source: 'filesystem:tests',\n claim: `Project includes automated test suite${fwStr} with ${testFiles.length} test files detected`,\n provenance: { type: 'file', path: 'test', timestamp: now },\n confidence: 0.95,\n positive: ['tests', 'testing', 'qa', ...frameworks.map((f) => f.toLowerCase())],\n details: { testFilesCount: testFiles.length, frameworks }\n });\n }\n },\n\n // 9. Database & ORM\n {\n id: 'database-orm',\n name: 'Database & Schema Detector',\n category: 'database',\n detect(ctx) {\n const now = new Date().toISOString();\n const hasPrisma = ctx.hasFile('schema.prisma') || ctx.hasDirectory('prisma');\n const hasDrizzle = ctx.hasFile('drizzle.config.ts') || ctx.hasFile('drizzle.config.js');\n const hasMigrations = ctx.hasDirectory('migrations') || ctx.hasDirectory('db/migrations');\n\n if (!hasPrisma && !hasDrizzle && !hasMigrations) {\n return null;\n }\n\n const tools: string[] = [];\n if (hasPrisma) tools.push('Prisma');\n if (hasDrizzle) tools.push('Drizzle');\n if (hasMigrations) tools.push('SQL Migrations');\n\n return createObservation({\n source: 'filesystem:database',\n claim: `Project includes database schema and migration tooling: ${tools.join(', ')}`,\n provenance: { type: 'file', path: hasPrisma ? 'prisma/schema.prisma' : 'migrations', timestamp: now },\n confidence: 0.92,\n positive: ['database', 'orm', 'migrations', ...tools.map((t) => t.toLowerCase())]\n });\n }\n },\n\n // 10. Container & DevOps\n {\n id: 'container-devops',\n name: 'Container & Docker Detector',\n category: 'tooling',\n detect(ctx) {\n const now = new Date().toISOString();\n const hasDockerfile = ctx.hasFile('dockerfile');\n const hasCompose = ctx.hasFile('docker-compose.yml') || ctx.hasFile('compose.yaml') || ctx.hasFile('docker-compose.yaml');\n\n if (!hasDockerfile && !hasCompose) return null;\n\n return createObservation({\n source: 'filesystem:docker',\n claim: 'Project includes Docker container configuration',\n provenance: { type: 'file', path: hasDockerfile ? 'Dockerfile' : 'docker-compose.yml', timestamp: now },\n confidence: 0.95,\n positive: ['docker', 'containers', 'devops']\n });\n }\n },\n\n // 11. CI/CD Workflows\n {\n id: 'ci-cd',\n name: 'CI/CD Workflow Detector',\n category: 'ci-cd',\n detect(ctx) {\n const now = new Date().toISOString();\n const ghWorkflows = ctx.findFiles((f) => f.relativePath.startsWith('.github/workflows/'));\n const hasGitlab = ctx.hasFile('.gitlab-ci.yml');\n\n if (ghWorkflows.length === 0 && !hasGitlab) return null;\n\n const claim = ghWorkflows.length > 0\n ? `Project configures GitHub Actions CI/CD workflows (${ghWorkflows.length} workflow files)`\n : 'Project configures GitLab CI pipeline';\n\n return createObservation({\n source: 'filesystem:ci',\n claim,\n provenance: { type: 'file', path: ghWorkflows.length > 0 ? '.github/workflows' : '.gitlab-ci.yml', timestamp: now },\n confidence: 0.95,\n positive: ['ci', 'github-actions', 'automation']\n });\n }\n },\n\n // 12. Documentation\n {\n id: 'documentation',\n name: 'Project Documentation Detector',\n category: 'documentation',\n detect(ctx) {\n const now = new Date().toISOString();\n const hasReadme = ctx.hasFile('readme.md');\n const hasDocs = ctx.hasDirectory('docs');\n const hasContributing = ctx.hasFile('contributing.md');\n\n if (!hasReadme && !hasDocs && !hasContributing) return null;\n\n return createObservation({\n source: 'filesystem:readme.md',\n claim: 'Root README.md is present for project documentation',\n provenance: { type: 'file', path: 'README.md', timestamp: now },\n confidence: 0.95,\n positive: ['documentation', 'readme']\n });\n }\n },\n\n // 13. Architecture & Code Layout\n {\n id: 'code-layout',\n name: 'Architecture & Layout Pattern Detector',\n category: 'architecture',\n detect(ctx) {\n const now = new Date().toISOString();\n const isCleanArch =\n (ctx.hasDirectory('src/domain') || ctx.hasDirectory('domain')) &&\n (ctx.hasDirectory('src/application') || ctx.hasDirectory('application'));\n\n if (isCleanArch) {\n return createObservation({\n source: 'filesystem:architecture',\n claim: 'Project follows Clean / Hexagonal Architecture layout (domain, application, infrastructure)',\n provenance: { type: 'file', path: 'src', timestamp: now },\n confidence: 0.88,\n positive: ['clean-architecture', 'domain-driven', 'hexagonal']\n });\n }\n\n const isFeatureSliced = ctx.hasDirectory('src/features') || ctx.hasDirectory('src/modules');\n if (isFeatureSliced) {\n return createObservation({\n source: 'filesystem:architecture',\n claim: 'Project follows Feature-sliced or modular directory architecture',\n provenance: { type: 'file', path: 'src', timestamp: now },\n confidence: 0.85,\n positive: ['feature-sliced', 'modular-architecture']\n });\n }\n\n return null;\n }\n }\n];\n\n// --- Default Global Registry ---\n\nexport const defaultRegistry = new ConventionRegistry();\nfor (const detector of BUILTIN_DETECTORS) {\n defaultRegistry.register(detector);\n}\n\n/**\n * Convenience helper to register a new convention detector globally.\n */\nexport function registerConventionDetector(detector: ConventionDetector): void {\n defaultRegistry.register(detector);\n}\n\n/**\n * Analyzes project structure using extensible convention detectors.\n */\nexport async function analyzeProjectStructure(\n files: ScannedFileInfo[],\n rootDir: string,\n registry: ConventionRegistry = defaultRegistry\n): Promise<Observation[]> {\n const ctx = new ProjectContext(files, rootDir);\n return registry.run(ctx);\n}\n","import { createHash } from 'node:crypto';\nimport type {\n Knowledge,\n KnowledgeType,\n KnowledgeStatus,\n KnowledgeStage,\n KnowledgeHistoryEntry,\n KnowledgeOutcomesSummary,\n Scope,\n Observation,\n Evidence,\n Provenance,\n ReconciliationResult,\n ReconciliationAction,\n ConfidenceTier\n} from './types.js';\nimport { determineInitialStage, calculateKnowledgeValue, evaluatePromotion } from './quarantine.js';\nimport type { MetricEvent } from '../stats/types.js';\n\n/**\n * Deterministic mapping between confidence tiers and normalized float scores.\n * Replaces arbitrary precision floats with explainable thresholds.\n */\nexport function tierToConfidence(tier: ConfidenceTier): number {\n switch (tier) {\n case 'low':\n return 0.50;\n case 'medium':\n return 0.75;\n case 'high':\n return 0.95;\n }\n}\n\nexport function confidenceToTier(score: number): ConfidenceTier {\n if (score >= 0.85) return 'high';\n if (score >= 0.65) return 'medium';\n return 'low';\n}\n\nexport function hashString(input: string): string {\n return createHash('sha256').update(input.trim().toLowerCase()).digest('hex').slice(0, 16);\n}\n\nexport function createObservation(params: {\n source: string;\n claim: string;\n provenance?: Provenance;\n confidence?: number;\n positive?: string[];\n negative?: string[];\n details?: Record<string, unknown>;\n}): Observation {\n const provenance: Provenance = params.provenance ?? {\n type: 'file',\n path: params.source,\n timestamp: new Date().toISOString()\n };\n const contentForHash = `${params.source}:${params.claim}:${provenance.commit || provenance.timestamp || Date.now()}`;\n const id = `obs_${hashString(contentForHash)}`;\n\n return {\n id,\n source: params.source,\n claim: params.claim.trim(),\n provenance,\n confidence: Math.min(1.0, Math.max(0.0, params.confidence ?? 0.8)),\n positive: Array.from(new Set(params.positive?.map((p) => p.trim().toLowerCase()) ?? [])),\n negative: Array.from(new Set(params.negative?.map((n) => n.trim().toLowerCase()) ?? [])),\n details: params.details,\n recordedAt: new Date().toISOString()\n };\n}\n\n/**\n * Creates or consolidates evidence based on underlying source.\n * Crucial constraint: Multiple agents reading the same source must NOT count as independent evidence.\n */\nexport function createEvidence(\n observation: Observation,\n type: 'supports' | 'contradicts' | 'observes' = 'supports'\n): Evidence {\n const sourceHash = hashString(observation.source);\n const id = `evi_${sourceHash}`;\n\n return {\n id,\n source: observation.source,\n sourceHash,\n observationIds: [observation.id],\n type,\n claim: observation.claim,\n provenance: observation.provenance,\n weight: 1.0,\n firstObservedAt: observation.recordedAt,\n lastObservedAt: observation.recordedAt\n };\n}\n\nexport function createKnowledge(params: {\n id: string;\n type?: KnowledgeType;\n status?: KnowledgeStatus;\n stage?: KnowledgeStage;\n statement: string;\n positive?: string[];\n negative?: string[];\n relations?: string[];\n depends_on?: string[];\n resolves?: string[];\n question?: string;\n confidence?: number;\n confidenceTier?: ConfidenceTier;\n evidence?: string[];\n scope?: Scope;\n tags?: string[];\n history?: KnowledgeHistoryEntry[];\n outcomesSummary?: KnowledgeOutcomesSummary;\n}): Knowledge {\n const now = new Date().toISOString();\n const confidenceTier =\n params.confidenceTier ??\n (params.confidence !== undefined ? confidenceToTier(params.confidence) : undefined);\n const confidence =\n params.confidence !== undefined\n ? params.confidence\n : (confidenceTier ? tierToConfidence(confidenceTier) : 0.85);\n\n const dependsOn = new Set<string>(params.depends_on ?? []);\n if (params.evidence) {\n for (const ev of params.evidence) {\n if (ev.startsWith('file:') || ev.startsWith('test:') || ev.startsWith('code:')) {\n dependsOn.add(ev);\n } else if (ev.includes('/') || ev.endsWith('.json') || ev.endsWith('.yaml') || ev.endsWith('.yml')) {\n dependsOn.add(`file:${ev}`);\n }\n }\n }\n\n const initialStage = params.stage ?? determineInitialStage({\n type: params.type ?? 'lesson',\n evidence: params.evidence ?? [],\n confidence\n });\n\n const status = params.status ?? (initialStage === 'candidate' ? 'candidate' : 'active');\n\n const history: KnowledgeHistoryEntry[] = params.history ?? [\n {\n timestamp: now,\n stage: initialStage,\n status,\n reason: `Initial knowledge recorded (${params.type ?? 'lesson'})`,\n source: params.evidence?.[0]\n }\n ];\n\n const knowledgeItem: Knowledge = {\n id: params.id.trim(),\n type: params.type ?? 'lesson',\n status,\n stage: initialStage,\n statement: params.statement.trim(),\n positive: Array.from(new Set(params.positive?.map((p) => p.trim().toLowerCase()) ?? [])),\n negative: Array.from(new Set(params.negative?.map((n) => n.trim().toLowerCase()) ?? [])),\n relations: Array.from(new Set(params.relations?.map((r) => r.trim()) ?? [])),\n depends_on: Array.from(dependsOn),\n resolves: params.resolves ? Array.from(new Set(params.resolves.map((r) => r.trim()))) : undefined,\n question: params.question?.trim(),\n confidence: Math.min(1.0, Math.max(0.0, confidence)),\n confidenceTier,\n evidence: Array.from(new Set(params.evidence ?? [])),\n scope: params.scope ?? 'project',\n tags: Array.from(new Set(params.tags?.map((t) => t.trim().toLowerCase()) ?? [])),\n temporal: {\n revision: 1\n },\n metrics: {\n reuse_count: 0,\n support_count: 1,\n contradiction_count: 0,\n successful_outcomes: 0,\n failed_outcomes: 0\n },\n outcomesSummary: params.outcomesSummary ?? {\n applied: 0,\n successful: 0,\n misleading: 0,\n neutral: 0\n },\n history,\n value: 0,\n createdAt: now,\n updatedAt: now\n };\n\n knowledgeItem.value = calculateKnowledgeValue(knowledgeItem);\n return knowledgeItem;\n}\n\n/**\n * Calculate effective confidence combining evidence ratio and outcome history.\n */\nexport function calculateEffectiveConfidence(knowledge: Knowledge): number {\n const m = knowledge.metrics;\n const base = knowledge.confidence;\n\n // Evidence ratio dampening: heavily penalizes contradictions\n const evRatio = (m.support_count + 1) / (m.support_count + 3 * m.contradiction_count + 1);\n\n const totalOutcomes = m.successful_outcomes + m.failed_outcomes;\n let outRatio = 1.0;\n let evWeight = 0.6;\n let outWeight = 0.4;\n\n if (totalOutcomes === 0) {\n evWeight = 0.85;\n outWeight = 0.15;\n } else {\n outRatio = (m.successful_outcomes + 1) / (totalOutcomes + 1);\n }\n\n const effective = base * (evWeight * evRatio + outWeight * outRatio);\n return Math.round(Math.min(1.0, Math.max(0.05, effective)) * 100) / 100;\n}\n\nconst knowledgeTokenCache = new WeakMap<Knowledge, Set<string>>();\n\n/**\n * Tokenize string into lowercase terms for lexical similarity comparison.\n */\nfunction tokenize(text: string): Set<string> {\n return new Set(\n text\n .toLowerCase()\n .replace(/[^a-z0-9_-]/g, ' ')\n .split(/\\s+/)\n .filter((t) => t.length > 2)\n );\n}\n\nfunction getCachedTokens(k: Knowledge): Set<string> {\n let tokens = knowledgeTokenCache.get(k);\n if (!tokens) {\n tokens = tokenize(k.statement);\n knowledgeTokenCache.set(k, tokens);\n }\n return tokens;\n}\n\nfunction jaccardSimilarity(setA: Set<string>, setB: Set<string>): number {\n if (setA.size === 0 && setB.size === 0) return 1.0;\n let intersection = 0;\n for (const item of setA) {\n if (setB.has(item)) intersection++;\n }\n const union = setA.size + setB.size - intersection;\n return union === 0 ? 0 : intersection / union;\n}\n\n/**\n * Known polar antonym word pairs.\n */\nconst POLAR_ANTONYMS: Array<[string, string]> = [\n ['enabled', 'disabled'],\n ['enable', 'disable'],\n ['active', 'inactive'],\n ['true', 'false'],\n ['on', 'off'],\n ['yes', 'no'],\n ['allowed', 'disallowed'],\n ['allowed', 'prohibited'],\n ['allowed', 'forbidden'],\n ['permit', 'deny'],\n ['allow', 'forbid'],\n ['allow', 'prohibit'],\n ['always', 'never'],\n ['should', 'should not'],\n ['must', 'must not'],\n ['required', 'optional'],\n ['required', 'forbidden'],\n ['valid', 'invalid'],\n ['safe', 'unsafe'],\n ['sync', 'async'],\n ['synchronous', 'asynchronous'],\n ['public', 'private']\n];\n\nconst NEGATION_PATTERNS = [\n /\\bnot\\b/i,\n /\\bnever\\b/i,\n /\\bno\\b/i,\n /\\bcannot\\b/i,\n /\\bwithout\\b/i,\n /\\bdisallow\\b/i,\n /\\bforbid\\b/i,\n /\\bprohibit\\b/i,\n /\\bavoid\\b/i\n];\n\n/**\n * Checks if two statements express opposite polarity or semantic contradiction.\n * Essential rule: High lexical similarity does NOT imply MERGE.\n * \"cache enabled in production\" vs \"cache disabled in production\" have opposite polarity.\n */\nexport function detectPolarContradiction(\n stmtA: string,\n stmtB: string\n): { contradicted: boolean; reason?: string } {\n const lowerA = stmtA.toLowerCase();\n const lowerB = stmtB.toLowerCase();\n\n // 1. Check known antonym pairs\n for (const [pos, neg] of POLAR_ANTONYMS) {\n const aHasPos = new RegExp(`\\\\b${pos}\\\\b`, 'i').test(lowerA);\n const aHasNeg = new RegExp(`\\\\b${neg}\\\\b`, 'i').test(lowerA);\n const bHasPos = new RegExp(`\\\\b${pos}\\\\b`, 'i').test(lowerB);\n const bHasNeg = new RegExp(`\\\\b${neg}\\\\b`, 'i').test(lowerB);\n\n if ((aHasPos && bHasNeg) || (aHasNeg && bHasPos)) {\n return {\n contradicted: true,\n reason: `Polar opposite terms detected: '${pos}' vs '${neg}'`\n };\n }\n }\n\n // 2. Check asymmetric negation (one statement has negation, the other does not)\n const aHasNegation = NEGATION_PATTERNS.some((p) => p.test(lowerA));\n const bHasNegation = NEGATION_PATTERNS.some((p) => p.test(lowerB));\n\n if (aHasNegation !== bHasNegation) {\n return {\n contradicted: true,\n reason: 'Asymmetric negation detected (one statement asserts, the other negates)'\n };\n }\n\n return { contradicted: false };\n}\n\n/**\n * Reconcile an incoming candidate lesson with existing knowledge.\n * Classifies the action as: NEW, MERGE, UPDATE, SUPPORT, CONTRADICT, SPECIALIZE, GENERALIZE, IGNORE.\n */\nexport function reconcileKnowledge(\n candidate: Partial<Knowledge> & { statement: string },\n existingList: Knowledge[]\n): ReconciliationResult {\n const candidateId = candidate.id?.trim();\n const candidateStmt = candidate.statement.trim();\n const candidateTokens = tokenize(candidateStmt);\n const candidatePos = new Set((candidate.positive ?? []).map((p) => p.trim().toLowerCase()));\n\n // 1. Direct ID match\n if (candidateId) {\n const directMatch = existingList.find((k) => k.id === candidateId);\n if (directMatch) {\n // Check for exact identical statement\n if (directMatch.statement.trim().toLowerCase() === candidateStmt.toLowerCase()) {\n // If evidence is identical and cues are identical, IGNORE to avoid duplicate bloat\n const hasNewEvidence = (candidate.evidence ?? []).some((e) => !directMatch.evidence.includes(e));\n if (!hasNewEvidence) {\n return {\n action: 'IGNORE',\n targetId: directMatch.id,\n knowledge: directMatch,\n reason: 'Identical statement and evidence already recorded'\n };\n }\n\n return {\n action: 'SUPPORT',\n targetId: directMatch.id,\n knowledge: directMatch,\n reason: 'Confirms existing knowledge with new evidence source'\n };\n }\n\n // Check if candidate contradicts existing statement (e.g. contains negation or opposing cues)\n const opposingPositive = (candidate.negative ?? []).some((n) => directMatch.positive.includes(n));\n const opposingNegative = (candidate.positive ?? []).some((p) => directMatch.negative.includes(p));\n const polarCheck = detectPolarContradiction(candidateStmt, directMatch.statement);\n\n if (opposingPositive || opposingNegative || polarCheck.contradicted) {\n // Check if contexts differ (e.g. dev vs prod) -> SPECIALIZE\n const distinctCues = Array.from(candidatePos).filter((c) => !directMatch.positive.includes(c));\n const mentionsEnvA = /(development|dev|local|staging|test)/i.test(candidateStmt);\n const mentionsEnvB = /(production|prod)/i.test(directMatch.statement);\n const mentionsEnvBDev = /(development|dev|local|staging|test)/i.test(directMatch.statement);\n const mentionsEnvAProd = /(production|prod)/i.test(candidateStmt);\n\n if (distinctCues.length > 0 || (mentionsEnvA && mentionsEnvB) || (mentionsEnvBDev && mentionsEnvAProd)) {\n return {\n action: 'SPECIALIZE',\n targetId: directMatch.id,\n knowledge: directMatch,\n reason: `Conflicting claim applies under specialized context cues: [${distinctCues.join(', ')}] (${polarCheck.reason || 'opposing polarity'})`\n };\n }\n\n return {\n action: 'CONTRADICT',\n targetId: directMatch.id,\n knowledge: directMatch,\n reason: `Contradicts existing statement (${polarCheck.reason || 'opposing polarity'}) for ID \"${directMatch.id}\"`\n };\n }\n\n return {\n action: 'UPDATE',\n targetId: directMatch.id,\n knowledge: directMatch,\n reason: 'Refines or updates existing knowledge statement'\n };\n }\n }\n\n // 2. Search for nearby existing knowledge by statement similarity and contextual overlap\n let bestMatch: Knowledge | null = null;\n let bestSim = 0;\n let bestPolarCheck: { contradicted: boolean; reason?: string } = { contradicted: false };\n\n for (const existing of existingList) {\n const existingTokens = getCachedTokens(existing);\n const sim = jaccardSimilarity(candidateTokens, existingTokens);\n\n // Explicit polar contradiction check: opposing polar assertions on same topic\n const polarCheck = detectPolarContradiction(candidateStmt, existing.statement);\n if (polarCheck.contradicted) {\n let sharedCount = 0;\n for (const t of candidateTokens) {\n if (existingTokens.has(t)) sharedCount++;\n }\n const sharedCues = (candidate.positive ?? []).filter((p) => existing.positive.includes(p));\n if (sharedCount >= 2 || (sharedCues.length >= 1 && sim >= 0.35) || sim >= 0.40) {\n bestMatch = existing;\n bestSim = Math.max(sim, 0.85);\n bestPolarCheck = polarCheck;\n break;\n }\n }\n\n if (sim > bestSim) {\n bestSim = sim;\n bestMatch = existing;\n bestPolarCheck = polarCheck;\n }\n }\n\n if (bestMatch && bestSim >= 0.70) {\n // CRITICAL: First evaluate contradiction and polar polarity BEFORE any merge decision!\n const polarCheck = bestPolarCheck.contradicted\n ? bestPolarCheck\n : detectPolarContradiction(candidateStmt, bestMatch.statement);\n const hasOpposingCues =\n (candidate.negative ?? []).some((n) => bestMatch!.positive.includes(n)) ||\n (candidate.positive ?? []).some((p) => bestMatch!.negative.includes(p));\n\n if (polarCheck.contradicted || hasOpposingCues) {\n // Check if contexts differ (e.g. dev vs prod) -> SPECIALIZE\n const distinctCues = Array.from(candidatePos).filter((c) => !bestMatch!.positive.includes(c));\n const mentionsEnvA = /(development|dev|local|staging|test)/i.test(candidateStmt);\n const mentionsEnvB = /(production|prod)/i.test(bestMatch.statement);\n const mentionsEnvBDev = /(development|dev|local|staging|test)/i.test(bestMatch.statement);\n const mentionsEnvAProd = /(production|prod)/i.test(candidateStmt);\n\n if (distinctCues.length > 0 || (mentionsEnvA && mentionsEnvB) || (mentionsEnvBDev && mentionsEnvAProd)) {\n return {\n action: 'SPECIALIZE',\n targetId: bestMatch.id,\n knowledge: bestMatch,\n reason: `High textual similarity (${Math.round(bestSim * 100)}%) with polar distinction across contexts (${polarCheck.reason || 'opposing cues'})`,\n score: bestSim\n };\n }\n\n return {\n action: 'CONTRADICT',\n targetId: bestMatch.id,\n knowledge: bestMatch,\n reason: `Contradicting statement (${polarCheck.reason || 'opposing cues'}) despite high textual similarity (${Math.round(bestSim * 100)}%)`,\n score: bestSim\n };\n }\n\n // Only if polarity is compatible and similarity is nearly identical:\n if (bestSim >= 0.90) {\n return {\n action: 'MERGE',\n targetId: bestMatch.id,\n knowledge: bestMatch,\n reason: `Nearly identical statement (${Math.round(bestSim * 100)}% match) with compatible polarity; merging cues and evidence`,\n score: bestSim\n };\n }\n\n return {\n action: 'SUPPORT',\n targetId: bestMatch.id,\n knowledge: bestMatch,\n reason: `Supports existing knowledge (${Math.round(bestSim * 100)}% similarity) with compatible polarity`,\n score: bestSim\n };\n }\n\n // 3. Fallback: completely new knowledge\n return {\n action: 'NEW',\n reason: 'No conflicting or matching knowledge found; creating new knowledge entry'\n };\n}\n\n/**\n * Apply reconciliation to knowledge base.\n */\nexport function applyReconciliation(\n reconciliation: ReconciliationResult,\n candidate: Partial<Knowledge> & { statement: string },\n existingList: Knowledge[],\n storage?: { appendMetricEvent(event: MetricEvent): Promise<void> }\n): { updatedKnowledge: Knowledge; action: ReconciliationAction; createdId: string } {\n const now = new Date().toISOString();\n\n switch (reconciliation.action) {\n case 'SUPPORT': {\n const target = existingList.find((k) => k.id === reconciliation.targetId)!;\n target.metrics.support_count++;\n target.metrics.last_used = now;\n storage?.appendMetricEvent({\n type: 'knowledge_strengthened',\n knowledgeId: target.id,\n timestamp: Date.now()\n });\n\n // Add new evidence refs\n if (candidate.evidence) {\n for (const e of candidate.evidence) {\n if (!target.evidence.includes(e)) {\n target.evidence.push(e);\n }\n }\n }\n\n // Merge positive/negative cues if any new\n if (candidate.positive) {\n for (const p of candidate.positive) {\n const lp = p.trim().toLowerCase();\n if (!target.positive.includes(lp)) target.positive.push(lp);\n }\n }\n\n if (!target.history) {\n target.history = [\n {\n timestamp: target.createdAt || now,\n stage: target.stage,\n status: target.status,\n reason: 'Initial knowledge recorded',\n source: target.evidence?.[0]\n }\n ];\n }\n\n const promotion = evaluatePromotion(target);\n if (promotion.promoted && promotion.newStage) {\n target.stage = promotion.newStage;\n if (target.stage === 'active' && target.status === 'candidate') {\n target.status = 'active';\n }\n target.history.push({\n timestamp: now,\n stage: target.stage,\n status: target.status,\n reason: promotion.reason || `Promoted to ${target.stage}`,\n source: candidate.evidence?.[0]\n });\n } else {\n target.history.push({\n timestamp: now,\n stage: target.stage,\n status: target.status,\n reason: reconciliation.reason || 'Confirmed with supporting evidence',\n source: candidate.evidence?.[0]\n });\n }\n\n target.confidence = calculateEffectiveConfidence(target);\n target.value = calculateKnowledgeValue(target);\n target.updatedAt = now;\n return { updatedKnowledge: target, action: 'SUPPORT', createdId: target.id };\n }\n\n case 'MERGE': {\n const target = existingList.find((k) => k.id === reconciliation.targetId)!;\n target.metrics.support_count++;\n target.metrics.last_used = now;\n storage?.appendMetricEvent({\n type: 'knowledge_merged',\n knowledgeId: target.id,\n targetId: reconciliation.targetId,\n timestamp: Date.now()\n });\n\n if (candidate.evidence) {\n for (const e of candidate.evidence) {\n if (!target.evidence.includes(e)) target.evidence.push(e);\n }\n }\n\n if (candidate.positive) {\n for (const p of candidate.positive) {\n const lp = p.trim().toLowerCase();\n if (!target.positive.includes(lp)) target.positive.push(lp);\n }\n }\n\n if (candidate.negative) {\n for (const n of candidate.negative) {\n const ln = n.trim().toLowerCase();\n if (!target.negative.includes(ln)) target.negative.push(ln);\n }\n }\n\n if (!target.history) {\n target.history = [\n {\n timestamp: target.createdAt || now,\n stage: target.stage,\n status: target.status,\n reason: 'Initial knowledge recorded',\n source: target.evidence?.[0]\n }\n ];\n }\n\n const promotion = evaluatePromotion(target);\n if (promotion.promoted && promotion.newStage) {\n target.stage = promotion.newStage;\n if (target.stage === 'active' && target.status === 'candidate') {\n target.status = 'active';\n }\n target.history.push({\n timestamp: now,\n stage: target.stage,\n status: target.status,\n reason: promotion.reason || `Promoted to ${target.stage}`,\n source: candidate.evidence?.[0]\n });\n } else {\n target.history.push({\n timestamp: now,\n stage: target.stage,\n status: target.status,\n reason: reconciliation.reason || 'Merged with compatible knowledge candidate',\n source: candidate.evidence?.[0]\n });\n }\n\n target.confidence = calculateEffectiveConfidence(target);\n target.value = calculateKnowledgeValue(target);\n target.updatedAt = now;\n return { updatedKnowledge: target, action: 'MERGE', createdId: target.id };\n }\n\n case 'UPDATE': {\n const target = existingList.find((k) => k.id === reconciliation.targetId)!;\n target.statement = candidate.statement;\n if (candidate.type) target.type = candidate.type;\n if (candidate.positive) {\n target.positive = Array.from(new Set([...target.positive, ...candidate.positive.map((p) => p.toLowerCase())]));\n }\n if (candidate.negative) {\n target.negative = Array.from(new Set([...target.negative, ...candidate.negative.map((n) => n.toLowerCase())]));\n }\n if (candidate.evidence) {\n target.evidence = Array.from(new Set([...target.evidence, ...candidate.evidence]));\n }\n\n target.temporal = {\n revision: (target.temporal?.revision ?? 1) + 1,\n valid_from: { timestamp: now }\n };\n\n if (!target.history) {\n target.history = [\n {\n timestamp: target.createdAt || now,\n stage: target.stage,\n status: target.status,\n reason: 'Initial knowledge recorded',\n source: target.evidence?.[0]\n }\n ];\n }\n target.history.push({\n timestamp: now,\n stage: target.stage,\n status: target.status,\n reason: reconciliation.reason || 'Updated statement and context',\n source: candidate.evidence?.[0]\n });\n\n target.updatedAt = now;\n target.confidence = calculateEffectiveConfidence(target);\n target.value = calculateKnowledgeValue(target);\n storage?.appendMetricEvent({\n type: 'knowledge_strengthened',\n knowledgeId: target.id,\n timestamp: Date.now()\n });\n return { updatedKnowledge: target, action: 'UPDATE', createdId: target.id };\n }\n\n case 'CONTRADICT': {\n const target = existingList.find((k) => k.id === reconciliation.targetId)!;\n target.metrics.contradiction_count++;\n if (candidate.evidence) {\n for (const e of candidate.evidence) {\n if (!target.evidence.includes(e)) target.evidence.push(e);\n }\n }\n\n if (target.metrics.contradiction_count > target.metrics.support_count) {\n target.status = 'contradicted';\n }\n\n if (!target.history) {\n target.history = [\n {\n timestamp: target.createdAt || now,\n stage: target.stage,\n status: target.status,\n reason: 'Initial knowledge recorded',\n source: target.evidence?.[0]\n }\n ];\n }\n target.history.push({\n timestamp: now,\n stage: target.stage,\n status: target.status,\n reason: reconciliation.reason || 'Contradicted by opposing claim',\n source: candidate.evidence?.[0]\n });\n\n target.confidence = calculateEffectiveConfidence(target);\n target.value = calculateKnowledgeValue(target);\n target.updatedAt = now;\n storage?.appendMetricEvent({\n type: 'contradiction_detected',\n knowledgeId: target.id,\n timestamp: Date.now()\n });\n return { updatedKnowledge: target, action: 'CONTRADICT', createdId: target.id };\n }\n\n case 'SPECIALIZE': {\n // Create specialized branch\n const parent = existingList.find((k) => k.id === reconciliation.targetId);\n const subContext = candidate.positive?.[0] || 'specialized';\n const newId =\n candidate.id && candidate.id !== parent?.id\n ? candidate.id\n : `${parent ? parent.id : 'knowledge'}.${subContext}`;\n\n const created = createKnowledge({\n id: newId,\n type: candidate.type ?? parent?.type ?? 'lesson',\n statement: candidate.statement,\n positive: candidate.positive ?? [],\n negative: candidate.negative ?? [],\n relations: parent ? [parent.id, ...(candidate.relations ?? [])] : (candidate.relations ?? []),\n confidence: candidate.confidence ?? 0.85,\n evidence: candidate.evidence ?? [],\n scope: candidate.scope ?? parent?.scope ?? 'project',\n tags: candidate.tags ?? parent?.tags ?? []\n });\n\n if (parent) {\n if (!parent.relations.includes(newId)) {\n parent.relations.push(newId);\n }\n if (!parent.history) {\n parent.history = [\n {\n timestamp: parent.createdAt || now,\n stage: parent.stage,\n status: parent.status,\n reason: 'Initial knowledge recorded'\n }\n ];\n }\n parent.history.push({\n timestamp: now,\n stage: parent.stage,\n status: parent.status,\n reason: `Specialized into contextual branch ${newId}`\n });\n }\n\n storage?.appendMetricEvent({\n type: 'knowledge_specialized',\n knowledgeId: created.id,\n timestamp: Date.now()\n });\n\n return { updatedKnowledge: created, action: 'SPECIALIZE', createdId: created.id };\n }\n\n case 'IGNORE': {\n const target = existingList.find((k) => k.id === reconciliation.targetId)!;\n storage?.appendMetricEvent({\n type: 'duplicate_ignored',\n timestamp: Date.now()\n });\n return { updatedKnowledge: target, action: 'IGNORE', createdId: target.id };\n }\n\n case 'NEW':\n default: {\n const newId = candidate.id || `kn_${hashString(candidate.statement)}`;\n const created = createKnowledge({\n id: newId,\n type: candidate.type,\n statement: candidate.statement,\n positive: candidate.positive,\n negative: candidate.negative,\n relations: candidate.relations,\n confidence: candidate.confidence,\n evidence: candidate.evidence,\n scope: candidate.scope,\n tags: candidate.tags\n });\n storage?.appendMetricEvent({\n type: 'knowledge_created',\n knowledgeId: created.id,\n timestamp: Date.now()\n });\n return { updatedKnowledge: created, action: 'NEW', createdId: created.id };\n }\n }\n}\n","import type {\n Knowledge,\n KnowledgeStage,\n OutcomeRecord,\n KnowledgeBudgetConfig\n} from './types.js';\n\n/**\n * Determines initial quarantine stage for a new knowledge item.\n * Deterministic facts (e.g. compiler config, explicit package manifests) skip probation directly to 'active'.\n * Speculative lessons, heuristics, and inferences start in 'candidate' stage.\n */\nexport function determineInitialStage(knowledge: Partial<Knowledge>): KnowledgeStage {\n if (\n knowledge.type === 'fact' ||\n knowledge.type === 'architecture' ||\n knowledge.confidenceTier === 'high' ||\n (knowledge.confidence !== undefined && knowledge.confidence >= 0.85)\n ) {\n return 'active';\n }\n if (\n knowledge.type === 'rule' &&\n ((knowledge.evidence?.length ?? 0) >= 2 || (knowledge.confidence !== undefined && knowledge.confidence >= 0.75))\n ) {\n return 'probation';\n }\n if (knowledge.confidence !== undefined && knowledge.confidence >= 0.70) {\n return 'probation';\n }\n return 'candidate';\n}\n\n/**\n * Evaluates whether a knowledge item qualifies for promotion along the quarantine ladder:\n * CANDIDATE -> PROBATION -> ACTIVE\n */\nexport function evaluatePromotion(knowledge: Knowledge): {\n promoted: boolean;\n newStage: KnowledgeStage;\n reason?: string;\n} {\n const stage = knowledge.stage ?? 'candidate';\n const supportCount = knowledge.metrics.support_count;\n const reuseCount = knowledge.metrics.reuse_count;\n const successCount = Math.max(knowledge.outcomesSummary?.successful ?? 0, knowledge.metrics.successful_outcomes ?? 0);\n const misleadingCount = Math.max(knowledge.outcomesSummary?.misleading ?? 0, knowledge.metrics.failed_outcomes ?? 0);\n\n if (stage === 'candidate') {\n // Promote to probation if supported by 2+ independent sources or high confidence evidence\n if (supportCount >= 2 || (knowledge.evidence && knowledge.evidence.length >= 2) || knowledge.confidence >= 0.85) {\n return {\n promoted: true,\n newStage: 'probation',\n reason: `Supported by ${supportCount} sources / ${knowledge.evidence.length} evidence nodes`\n };\n }\n } else if (stage === 'probation') {\n // Promote to active if successfully reused or confirmed by positive task outcome without misleading outcomes\n if ((successCount > 0 && misleadingCount === 0) || (reuseCount >= 2 && misleadingCount === 0)) {\n return {\n promoted: true,\n newStage: 'active',\n reason: `Verified by ${successCount} successful task outcomes and ${reuseCount} reuses`\n };\n }\n }\n\n return { promoted: false, newStage: stage };\n}\n\n/**\n * Calculates deterministic knowledge value metric.\n * Combines reuse frequency, evidence backing, successful task outcomes, and penalizes misleading outcomes.\n * Used during compaction and knowledge budget management.\n */\nexport function calculateKnowledgeValue(knowledge: Knowledge): number {\n const reuse = knowledge.metrics.reuse_count;\n const success = knowledge.outcomesSummary?.successful ?? knowledge.metrics.successful_outcomes;\n const misleading = knowledge.outcomesSummary?.misleading ?? knowledge.metrics.failed_outcomes;\n const evidenceCount = Math.min(knowledge.evidence.length, 6);\n const confidence = knowledge.confidence;\n\n let value = (reuse * 2.5) + (success * 4.0) + (evidenceCount * 1.5) + (confidence * 2.0) - (misleading * 5.0);\n\n if (knowledge.status === 'active') value += 5.0;\n if (knowledge.status === 'needs_revalidation') value -= 3.0;\n if (knowledge.status === 'contradicted') value -= 8.0;\n if (knowledge.status === 'stale') value -= 4.0;\n if (knowledge.stage === 'active') value += 3.0;\n if (knowledge.stage === 'candidate') value -= 1.0;\n\n return Math.round(value * 10) / 10;\n}\n\n/**\n * Applies a task outcome record to a knowledge item:\n * Updates outcome telemetry, recalculates value, and triggers promotion or demotion.\n */\nexport function recordOutcomeOnKnowledge(\n knowledge: Knowledge,\n outcome: OutcomeRecord\n): { updatedKnowledge: Knowledge; actionTaken?: string } {\n const now = new Date().toISOString();\n const summary = knowledge.outcomesSummary ?? {\n applied: 0,\n successful: 0,\n misleading: 0,\n neutral: 0\n };\n\n summary.applied++;\n let actionTaken: string | undefined;\n\n if (outcome.result === 'success') {\n summary.successful++;\n knowledge.metrics.successful_outcomes++;\n knowledge.metrics.reuse_count++;\n // Check if probation item qualifies for promotion\n const promo = evaluatePromotion({ ...knowledge, outcomesSummary: summary });\n if (promo.promoted) {\n knowledge.stage = promo.newStage;\n actionTaken = `Promoted to ${promo.newStage} (${promo.reason})`;\n const history = knowledge.history ?? [];\n history.push({\n timestamp: now,\n status: knowledge.status,\n action: 'promote',\n reason: promo.reason\n });\n knowledge.history = history;\n }\n } else if (outcome.result === 'failure' || outcome.result === 'reverted') {\n summary.misleading++;\n knowledge.metrics.failed_outcomes++;\n // Demote or mark needs_revalidation if misleading outcomes dominate\n if (summary.misleading >= 2 && summary.misleading > summary.successful) {\n knowledge.status = 'needs_revalidation';\n actionTaken = `Marked needs_revalidation: ${summary.misleading} misleading outcomes recorded`;\n const history = knowledge.history ?? [];\n history.push({\n timestamp: now,\n status: 'needs_revalidation',\n action: 'demote',\n reason: actionTaken\n });\n knowledge.history = history;\n }\n } else {\n summary.neutral++;\n }\n\n knowledge.outcomesSummary = summary;\n knowledge.value = calculateKnowledgeValue(knowledge);\n knowledge.updatedAt = now;\n\n return { updatedKnowledge: knowledge, actionTaken };\n}\n\n/**\n * Enforces knowledge budget without arbitrarily deleting provenance.\n * When active knowledge exceeds budget, demotes lowest-value items to probation/candidate.\n */\nexport function enforceKnowledgeBudget(\n knowledgeList: Knowledge[],\n budget?: KnowledgeBudgetConfig\n): { modifiedList: Knowledge[]; demotedCount: number } {\n if (!budget || !budget.active || budget.active <= 0) {\n return { modifiedList: knowledgeList, demotedCount: 0 };\n }\n\n const activeItems = knowledgeList.filter((k) => k.status === 'active' && k.stage === 'active');\n if (activeItems.length <= budget.active) {\n return { modifiedList: knowledgeList, demotedCount: 0 };\n }\n\n // Sort active items by value ascending (lowest value first)\n activeItems.sort((a, b) => calculateKnowledgeValue(a) - calculateKnowledgeValue(b));\n\n const excessCount = activeItems.length - budget.active;\n const toDemote = new Set(activeItems.slice(0, excessCount).map((k) => k.id));\n const now = new Date().toISOString();\n\n const modifiedList = knowledgeList.map((k) => {\n if (toDemote.has(k.id)) {\n const history = k.history ?? [];\n k.stage = 'probation';\n k.status = 'probation';\n k.updatedAt = now;\n k.history = [\n ...history,\n {\n timestamp: now,\n stage: 'probation',\n status: 'probation',\n action: 'budget_demotion',\n reason: `Active items exceeded budget (${budget.active}). Demoted to probation based on knowledge value.`\n }\n ];\n return k;\n }\n return k;\n });\n\n return { modifiedList, demotedCount: excessCount };\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport YAML from 'yaml';\nimport type { Observation, EvidenceRelation } from '../core/types.js';\nimport { createObservation } from '../core/knowledge.js';\n\nexport interface MarkdownEvidenceResult {\n observations: Observation[];\n relations?: EvidenceRelation[];\n}\n\nexport interface MarkdownHeading {\n level: number;\n text: string;\n line: number;\n}\n\nexport interface MarkdownAlert {\n type: 'WARNING' | 'CAUTION' | 'IMPORTANT' | 'NOTE' | 'TIP';\n body: string;\n line: number;\n heading?: string;\n}\n\nexport interface MarkdownCodeBlock {\n language: string;\n code: string;\n startLine: number;\n endLine: number;\n heading?: string;\n}\n\nexport interface MarkdownTable {\n headers: string[];\n rows: string[][];\n line: number;\n heading?: string;\n}\n\nexport interface MarkdownTaskItem {\n completed: boolean;\n text: string;\n line: number;\n heading?: string;\n}\n\nexport interface MarkdownLink {\n text: string;\n target: string;\n line: number;\n}\n\nexport interface MarkdownSection {\n heading: MarkdownHeading;\n content: string;\n lines: string[];\n startLine: number;\n endLine: number;\n}\n\nexport interface MarkdownDocument {\n filePath: string;\n relativePath: string;\n baseName: string;\n raw: string;\n lines: string[];\n frontmatter: Record<string, unknown>;\n headings: MarkdownHeading[];\n sections: MarkdownSection[];\n alerts: MarkdownAlert[];\n codeBlocks: MarkdownCodeBlock[];\n tables: MarkdownTable[];\n taskItems: MarkdownTaskItem[];\n links: MarkdownLink[];\n prohibitions: { rule: string; line: number; heading?: string }[];\n}\n\nexport interface MarkdownExtractorResult {\n observations: Observation[];\n relations?: EvidenceRelation[];\n}\n\nexport interface MarkdownExtractor {\n id: string;\n name: string;\n description?: string;\n extract(doc: MarkdownDocument): MarkdownExtractorResult | Promise<MarkdownExtractorResult>;\n}\n\n// --- Markdown Parser to Structured Document Model ---\n\nexport function parseMarkdownDocument(\n content: string,\n filePath: string,\n relativePath: string\n): MarkdownDocument {\n const lines = content.split('\\n');\n const baseName = path.basename(relativePath, '.md').toLowerCase();\n let frontmatter: Record<string, unknown> = {};\n\n const headings: MarkdownHeading[] = [];\n const alerts: MarkdownAlert[] = [];\n const codeBlocks: MarkdownCodeBlock[] = [];\n const tables: MarkdownTable[] = [];\n const taskItems: MarkdownTaskItem[] = [];\n const links: MarkdownLink[] = [];\n const prohibitions: { rule: string; line: number; heading?: string }[] = [];\n\n let currentHeadingText = '';\n let inCodeBlock = false;\n let codeBlockLang = '';\n let codeBlockLines: string[] = [];\n let codeBlockStart = 0;\n\n let inTable = false;\n let tableHeaders: string[] = [];\n let tableRows: string[][] = [];\n let tableStartLine = 0;\n\n let inFrontmatter = false;\n let frontmatterLines: string[] = [];\n let bodyStartIndex = 0;\n\n // 1. Extract Frontmatter if present\n if (lines.length > 0 && lines[0].trim() === '---') {\n inFrontmatter = true;\n for (let i = 1; i < lines.length; i++) {\n if (lines[i].trim() === '---') {\n inFrontmatter = false;\n bodyStartIndex = i + 1;\n try {\n const yamlText = frontmatterLines.join('\\n');\n const parsed = YAML.parse(yamlText);\n if (parsed && typeof parsed === 'object') {\n frontmatter = parsed as Record<string, unknown>;\n }\n } catch {\n // Ignore invalid frontmatter YAML\n }\n break;\n }\n frontmatterLines.push(lines[i]);\n }\n }\n\n // Helper to commit active table\n function commitTable() {\n if (inTable && tableHeaders.length > 0) {\n tables.push({\n headers: tableHeaders,\n rows: tableRows,\n line: tableStartLine,\n heading: currentHeadingText || undefined\n });\n inTable = false;\n tableHeaders = [];\n tableRows = [];\n }\n }\n\n // 2. Parse Document Body\n for (let i = bodyStartIndex; i < lines.length; i++) {\n const rawLine = lines[i];\n const line = rawLine.trim();\n\n // Code block fencing\n const codeMatch = line.match(/^```([a-zA-Z0-9_-]*)/);\n if (codeMatch) {\n if (!inCodeBlock) {\n commitTable();\n inCodeBlock = true;\n codeBlockLang = codeMatch[1] || '';\n codeBlockLines = [];\n codeBlockStart = i + 1;\n } else {\n inCodeBlock = false;\n codeBlocks.push({\n language: codeBlockLang,\n code: codeBlockLines.join('\\n'),\n startLine: codeBlockStart,\n endLine: i + 1,\n heading: currentHeadingText || undefined\n });\n }\n continue;\n }\n\n if (inCodeBlock) {\n codeBlockLines.push(rawLine);\n continue;\n }\n\n // Table parsing\n if (line.startsWith('|') && line.endsWith('|')) {\n const cells = line\n .split('|')\n .slice(1, -1)\n .map((c) => c.trim());\n\n // Check if delimiter row (| --- | --- |)\n const isDelimiter = cells.every((c) => /^:?-+:?$/.test(c));\n\n if (!inTable) {\n commitTable();\n inTable = true;\n tableHeaders = cells;\n tableRows = [];\n tableStartLine = i + 1;\n } else if (!isDelimiter) {\n tableRows.push(cells);\n }\n continue;\n } else {\n commitTable();\n }\n\n // Headings (e.g. # Title, ## Section)\n const headingMatch = line.match(/^(#{1,6})\\s+(.+)$/);\n if (headingMatch) {\n const level = headingMatch[1].length;\n currentHeadingText = headingMatch[2].trim();\n headings.push({\n level,\n text: currentHeadingText,\n line: i + 1\n });\n continue;\n }\n\n // GitHub-style alerts: > [!WARNING], > [!CAUTION], > [!IMPORTANT], > [!NOTE], > [!TIP]\n const alertMatch = line.match(/^>\\s*\\[!(WARNING|CAUTION|IMPORTANT|NOTE|TIP)\\]/i);\n if (alertMatch) {\n const alertStartLine = i + 1;\n const alertType = alertMatch[1].toUpperCase() as MarkdownAlert['type'];\n const alertLines: string[] = [];\n let j = i + 1;\n while (j < lines.length && lines[j].trim().startsWith('>')) {\n alertLines.push(lines[j].trim().replace(/^>\\s*/, ''));\n j++;\n }\n i = j - 1;\n\n alerts.push({\n type: alertType,\n body: alertLines.join(' ').trim(),\n line: alertStartLine,\n heading: currentHeadingText || undefined\n });\n continue;\n }\n\n // Task Items: - [ ] Open or - [x] Completed\n const taskMatch = line.match(/^[-*]\\s*\\[([ xX])\\]\\s*(.+)$/);\n if (taskMatch) {\n const completed = taskMatch[1].toLowerCase() === 'x';\n const text = taskMatch[2].trim();\n taskItems.push({\n completed,\n text,\n line: i + 1,\n heading: currentHeadingText || undefined\n });\n continue;\n }\n\n // Markdown Links: [text](target)\n const linkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n let match: RegExpExecArray | null;\n while ((match = linkRegex.exec(line)) !== null) {\n const linkText = match[1].trim();\n const linkTarget = match[2].trim();\n if (!linkTarget.startsWith('#')) {\n links.push({\n text: linkText,\n target: linkTarget,\n line: i + 1\n });\n }\n }\n\n // Explicit Prohibitions & Constraints (\"Never\", \"Do not\", \"Must not\", \"Avoid\")\n const prohibMatch = line.match(/\\b(Never|Must not|Do not|Cannot|Avoid)\\s+([^.!?]+[.!?]?)/i);\n if (prohibMatch && !line.startsWith('>')) {\n prohibitions.push({\n rule: `${prohibMatch[1]} ${prohibMatch[2].trim()}`,\n line: i + 1,\n heading: currentHeadingText || undefined\n });\n }\n }\n\n commitTable();\n\n // 3. Build Hierarchical Sections\n const sections: MarkdownSection[] = [];\n for (let idx = 0; idx < headings.length; idx++) {\n const h = headings[idx];\n const nextH = headings[idx + 1];\n const startLine = h.line;\n const endLine = nextH ? nextH.line - 1 : lines.length;\n const secLines = lines.slice(startLine - 1, endLine);\n\n sections.push({\n heading: h,\n content: secLines.join('\\n').trim(),\n lines: secLines,\n startLine,\n endLine\n });\n }\n\n return {\n filePath,\n relativePath,\n baseName,\n raw: content,\n lines,\n frontmatter,\n headings,\n sections,\n alerts,\n codeBlocks,\n tables,\n taskItems,\n links,\n prohibitions\n };\n}\n\n// --- Built-in Markdown Extractors ---\n\nexport const BUILTIN_MARKDOWN_EXTRACTORS: MarkdownExtractor[] = [\n // 1. Frontmatter Extractor\n {\n id: 'frontmatter',\n name: 'YAML Frontmatter Extractor',\n extract(doc) {\n const observations: Observation[] = [];\n const now = new Date().toISOString();\n const fm = doc.frontmatter;\n\n for (const [key, val] of Object.entries(fm)) {\n if (!val || typeof val === 'object' && !Array.isArray(val)) continue;\n const valStr = Array.isArray(val) ? val.join(', ') : String(val);\n const lowerKey = key.toLowerCase();\n\n observations.push(\n createObservation({\n source: `doc:${doc.relativePath}:frontmatter:${lowerKey}`,\n claim: `Document metadata (${lowerKey}): ${valStr}`,\n provenance: { type: 'doc', path: doc.relativePath, line: 1, timestamp: now },\n confidence: 0.92,\n positive: [doc.baseName, lowerKey, ...(Array.isArray(val) ? val.map(String) : [])],\n details: { frontmatterKey: lowerKey, value: val }\n })\n );\n }\n return { observations };\n }\n },\n\n // 2. GitHub Alerts Extractor (> [!WARNING], etc.)\n {\n id: 'github-alerts',\n name: 'GitHub Callouts & Alerts Extractor',\n extract(doc) {\n const observations: Observation[] = [];\n const now = new Date().toISOString();\n\n for (const alert of doc.alerts) {\n if (!alert.body) continue;\n const isCritical = alert.type === 'WARNING' || alert.type === 'CAUTION';\n observations.push(\n createObservation({\n source: `doc:${doc.relativePath}#L${alert.line}`,\n claim: `[${alert.type}] ${alert.body}`,\n provenance: { type: 'doc', path: doc.relativePath, line: alert.line, timestamp: now },\n confidence: isCritical ? 0.96 : 0.88,\n positive: [doc.baseName, alert.type.toLowerCase(), ...(alert.heading ? [alert.heading.toLowerCase()] : [])],\n details: { alertType: alert.type, heading: alert.heading, line: alert.line }\n })\n );\n }\n return { observations };\n }\n },\n\n // 3. ADR & Architectural Decisions Extractor\n {\n id: 'adr-decisions',\n name: 'Architecture Decision Record (ADR/MADR) Extractor',\n extract(doc) {\n const observations: Observation[] = [];\n const now = new Date().toISOString();\n\n let hasContext = false;\n let decision = '';\n let status = '';\n let adrLine = 1;\n\n for (const sec of doc.sections) {\n const lowerHead = sec.heading.text.toLowerCase();\n if (lowerHead.includes('context')) {\n hasContext = true;\n }\n\n if (lowerHead.includes('decision') && !lowerHead.includes('options')) {\n for (const line of sec.lines) {\n const clean = line.replace(/^#{1,6}\\s+/, '').trim();\n if (clean && clean.length > 5 && !clean.toLowerCase().includes('decision')) {\n decision = clean;\n adrLine = sec.heading.line;\n break;\n }\n }\n }\n\n if (lowerHead.includes('status')) {\n for (const line of sec.lines) {\n const clean = line.replace(/^#{1,6}\\s+/, '').trim();\n if (clean && clean.length > 2 && !clean.toLowerCase().includes('status')) {\n status = clean;\n break;\n }\n }\n }\n }\n\n if (hasContext && decision) {\n observations.push(\n createObservation({\n source: `doc:${doc.relativePath}:adr#L${adrLine}`,\n claim: `Architectural Decision in ${doc.relativePath}: ${decision}`,\n provenance: { type: 'doc', path: doc.relativePath, line: adrLine, timestamp: now },\n confidence: 0.95,\n positive: ['adr', 'architecture', 'decision', doc.baseName],\n details: { status: status || 'Accepted', decision }\n })\n );\n }\n\n return { observations };\n }\n },\n\n // 4. Task Lists Extractor (- [ ] and - [x])\n {\n id: 'task-items',\n name: 'Task Items & TODOs Extractor',\n extract(doc) {\n const observations: Observation[] = [];\n const now = new Date().toISOString();\n\n for (const item of doc.taskItems) {\n const tag = item.completed ? 'DONE' : 'TODO';\n observations.push(\n createObservation({\n source: `doc:${doc.relativePath}#L${item.line}:todo`,\n claim: `[${tag}] ${item.text}`,\n provenance: { type: 'doc', path: doc.relativePath, line: item.line, timestamp: now },\n confidence: item.completed ? 0.70 : 0.82,\n positive: ['todo', doc.baseName, ...(item.heading ? [item.heading.toLowerCase()] : [])],\n details: { completed: item.completed, heading: item.heading, line: item.line }\n })\n );\n }\n return { observations };\n }\n },\n\n // 5. Code Block Commands & Configurations\n {\n id: 'code-blocks',\n name: 'Code Block Commands Extractor',\n extract(doc) {\n const observations: Observation[] = [];\n const now = new Date().toISOString();\n\n for (const cb of doc.codeBlocks) {\n const lang = cb.language.toLowerCase();\n if (lang === 'bash' || lang === 'sh' || lang === 'shell' || lang === 'zsh') {\n const lines = cb.code.split('\\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));\n for (const line of lines.slice(0, 3)) {\n if (/^(npm|pnpm|yarn|bun|cargo|go|docker|make|npx)\\b/.test(line)) {\n observations.push(\n createObservation({\n source: `doc:${doc.relativePath}#L${cb.startLine}:cli`,\n claim: `Documented CLI command in ${doc.baseName}: ${line}`,\n provenance: { type: 'doc', path: doc.relativePath, line: cb.startLine, timestamp: now },\n confidence: 0.88,\n positive: ['command', 'cli', doc.baseName],\n details: { command: line, language: lang }\n })\n );\n }\n }\n }\n }\n return { observations };\n }\n },\n\n // 6. Markdown Tables (Configurations & Environment Variables)\n {\n id: 'markdown-tables',\n name: 'Markdown Table Key-Value Extractor',\n extract(doc) {\n const observations: Observation[] = [];\n const now = new Date().toISOString();\n\n for (const table of doc.tables) {\n if (table.headers.length < 2 || table.rows.length === 0) continue;\n const lowerHeaders = table.headers.map((h) => h.toLowerCase());\n\n // Check if table contains key-value configurations, env vars, options, or flags\n const isConfigTable = lowerHeaders.some(\n (h) =>\n h.includes('variable') ||\n h.includes('env') ||\n h.includes('setting') ||\n h.includes('option') ||\n h.includes('command') ||\n h.includes('param') ||\n h.includes('flag') ||\n h.includes('property') ||\n h.includes('key') ||\n h.includes('config')\n );\n\n if (isConfigTable) {\n for (const row of table.rows.slice(0, 10)) {\n const key = row[0];\n const val = row[1];\n const desc = row[2] ? ` (${row[2]})` : '';\n if (key && val) {\n observations.push(\n createObservation({\n source: `doc:${doc.relativePath}#L${table.line}:table:${key}`,\n claim: `Configuration in ${doc.baseName}: ${key} = ${val}${desc}`,\n provenance: { type: 'doc', path: doc.relativePath, line: table.line, timestamp: now },\n confidence: 0.88,\n positive: ['config', key.toLowerCase(), doc.baseName],\n details: { key, value: val, heading: table.heading }\n })\n );\n }\n }\n }\n }\n return { observations };\n }\n },\n\n // 7. Normative Rules & Prohibitions (\"Never\", \"Do not\", \"Must not\")\n {\n id: 'rules-and-prohibitions',\n name: 'Normative Rules & Prohibitions Extractor',\n extract(doc) {\n const observations: Observation[] = [];\n const now = new Date().toISOString();\n\n for (const p of doc.prohibitions) {\n observations.push(\n createObservation({\n source: `doc:${doc.relativePath}#L${p.line}:rule`,\n claim: `[RULE] in ${doc.baseName}: ${p.rule}`,\n provenance: { type: 'doc', path: doc.relativePath, line: p.line, timestamp: now },\n confidence: 0.90,\n positive: ['rule', 'constraint', doc.baseName],\n details: { rule: p.rule, heading: p.heading, line: p.line }\n })\n );\n }\n return { observations };\n }\n },\n\n // 8. Cross-Reference File Links\n {\n id: 'file-links',\n name: 'Cross-Reference File Links Extractor',\n extract(doc) {\n const relations: EvidenceRelation[] = [];\n\n for (const link of doc.links) {\n const target = link.target;\n // Check relative file links (ignore web urls and anchors)\n if (\n !target.startsWith('http://') &&\n !target.startsWith('https://') &&\n !target.startsWith('mailto:') &&\n (target.startsWith('.') || target.includes('/') || /\\.(md|ts|js|json|ya?ml|toml|rs|go|py)$/i.test(target))\n ) {\n const rawTarget = target.split('#')[0].split('?')[0].trim();\n if (rawTarget) {\n const dir = path.dirname(doc.relativePath);\n const resolved =\n dir === '.' || path.isAbsolute(rawTarget)\n ? rawTarget.replace(/^\\.\\//, '')\n : path.normalize(path.join(dir, rawTarget));\n relations.push({\n from: doc.relativePath,\n to: resolved,\n type: 'DOCUMENTS'\n });\n }\n }\n }\n return { observations: [], relations };\n }\n }\n];\n\n// --- Pluggable Markdown Registry ---\n\nexport class MarkdownRegistry {\n private extractors = new Map<string, MarkdownExtractor>();\n\n register(extractor: MarkdownExtractor): this {\n this.extractors.set(extractor.id, extractor);\n return this;\n }\n\n unregister(id: string): boolean {\n return this.extractors.delete(id);\n }\n\n get(id: string): MarkdownExtractor | undefined {\n return this.extractors.get(id);\n }\n\n list(): MarkdownExtractor[] {\n return Array.from(this.extractors.values());\n }\n\n async run(doc: MarkdownDocument): Promise<MarkdownEvidenceResult> {\n const observations: Observation[] = [];\n const relations: EvidenceRelation[] = [];\n\n for (const extractor of this.extractors.values()) {\n try {\n const result = await extractor.extract(doc);\n if (result.observations && result.observations.length > 0) {\n observations.push(...result.observations);\n }\n if (result.relations && result.relations.length > 0) {\n relations.push(...result.relations);\n }\n } catch {\n // Individual extractor failure does not abort scan\n }\n }\n\n return { observations, relations };\n }\n}\n\nexport const defaultMarkdownRegistry = new MarkdownRegistry();\nfor (const ext of BUILTIN_MARKDOWN_EXTRACTORS) {\n defaultMarkdownRegistry.register(ext);\n}\n\n/**\n * Convenience helper to register a new Markdown extractor globally.\n */\nexport function registerMarkdownExtractor(extractor: MarkdownExtractor): void {\n defaultMarkdownRegistry.register(extractor);\n}\n\n/**\n * Parses markdown files into structured evidence without dumping entire documents.\n * Extracts: Frontmatter, ADRs, GitHub alerts, code blocks, tables, task lists, and cross-references.\n */\nexport async function parseMarkdownFile(\n filePath: string,\n relativePath: string,\n registry: MarkdownRegistry = defaultMarkdownRegistry\n): Promise<MarkdownEvidenceResult> {\n let content = '';\n try {\n content = await fs.readFile(filePath, 'utf-8');\n } catch {\n return { observations: [], relations: [] };\n }\n\n const doc = parseMarkdownDocument(content, filePath, relativePath);\n return registry.run(doc);\n}\n","import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport type { Observation, EvidenceRelation } from '../core/types.js';\nimport { createObservation } from '../core/knowledge.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface GitCommit {\n hash: string;\n author: string;\n date: string;\n subject: string;\n files: string[];\n isMerge: boolean;\n}\n\nexport interface GitScanResult {\n isGitRepo: boolean;\n headCommit?: string;\n commitsScanned: number;\n observations: Observation[];\n relations: EvidenceRelation[];\n}\n\nasync function runGit(args: string[], cwd: string): Promise<string> {\n const { stdout } = await execFileAsync('git', args, {\n cwd,\n maxBuffer: 10 * 1024 * 1024\n });\n return stdout.trim();\n}\n\n/**\n * Checks if directory is inside a valid git repository.\n */\nexport async function isGitRepository(cwd: string): Promise<boolean> {\n try {\n const res = await runGit(['rev-parse', '--is-inside-work-tree'], cwd);\n return res === 'true';\n } catch {\n return false;\n }\n}\n\n/**\n * Inspects Git history for lessons, reverts, hotfixes, and co-changing file relationships.\n * Supports incremental scanning via lastScanCommit.\n */\nexport async function scanGitHistory(\n cwd: string,\n options: { lastScanCommit?: string; maxCommits?: number } = {}\n): Promise<GitScanResult> {\n const isRepo = await isGitRepository(cwd);\n if (!isRepo) {\n return {\n isGitRepo: false,\n commitsScanned: 0,\n observations: [],\n relations: []\n };\n }\n\n let headCommit = '';\n try {\n headCommit = await runGit(['rev-parse', 'HEAD'], cwd);\n } catch {\n // Empty repo with no commits yet\n return {\n isGitRepo: true,\n commitsScanned: 0,\n observations: [],\n relations: []\n };\n }\n\n // Determine git range\n let revisionRange: string[] = [];\n if (options.lastScanCommit && options.lastScanCommit !== headCommit) {\n try {\n // Verify lastScanCommit exists in history\n await runGit(['cat-file', '-e', `${options.lastScanCommit}^{commit}`], cwd);\n revisionRange = [`${options.lastScanCommit}..HEAD`];\n } catch {\n // Commit no longer reachable (e.g. rebased/force-pushed), fallback to recent HEAD\n revisionRange = ['-n', String(options.maxCommits ?? 100), 'HEAD'];\n }\n } else {\n revisionRange = ['-n', String(options.maxCommits ?? 100), 'HEAD'];\n }\n\n const logArgs = [\n 'log',\n ...revisionRange,\n '--name-only',\n '--pretty=format:COMMIT:%H|%an|%aI|%s'\n ];\n\n let rawLog = '';\n try {\n rawLog = await runGit(logArgs, cwd);\n } catch {\n return {\n isGitRepo: true,\n headCommit,\n commitsScanned: 0,\n observations: [],\n relations: []\n };\n }\n\n const commits: GitCommit[] = [];\n const lines = rawLog.split('\\n');\n let currentCommit: GitCommit | null = null;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n if (trimmed.startsWith('COMMIT:')) {\n if (currentCommit) commits.push(currentCommit);\n\n const parts = trimmed.substring('COMMIT:'.length).split('|');\n currentCommit = {\n hash: parts[0] || '',\n author: parts[1] || '',\n date: parts[2] || '',\n subject: parts.slice(3).join('|'),\n files: [],\n isMerge: false\n };\n } else if (currentCommit) {\n currentCommit.files.push(trimmed);\n }\n }\n if (currentCommit) commits.push(currentCommit);\n\n const observations: Observation[] = [];\n const relations: EvidenceRelation[] = [];\n const coChangeMap = new Map<string, number>();\n const fileFixCount = new Map<string, number>();\n\n // 1. Analyze commits\n for (const commit of commits) {\n // Avoid treating huge merge commits (> 15 files) as strong co-change evidence\n if (commit.files.length > 15) {\n commit.isMerge = true;\n continue;\n }\n\n const lowerSubject = commit.subject.toLowerCase();\n const isRevert = lowerSubject.startsWith('revert') || lowerSubject.includes('reverting');\n const isFix =\n lowerSubject.startsWith('fix') ||\n lowerSubject.startsWith('hotfix') ||\n lowerSubject.startsWith('bugfix') ||\n lowerSubject.includes('fix:');\n\n // Pattern 1: Change -> Revert\n if (isRevert && commit.files.length > 0) {\n observations.push(\n createObservation({\n source: `git:${commit.hash}`,\n claim: `Revert recorded in git: \"${commit.subject}\" affecting [${commit.files.slice(0, 5).join(', ')}]`,\n provenance: {\n type: 'git',\n commit: commit.hash,\n author: commit.author,\n timestamp: commit.date\n },\n confidence: 0.95,\n positive: ['revert', ...commit.files.map((f) => f.split('/').pop()?.toLowerCase() || f)],\n negative: ['fragile-change'],\n details: { commit: commit.hash, files: commit.files }\n })\n );\n }\n\n // Pattern 2: Bugfix -> Test Added\n if (isFix && commit.files.length > 1) {\n const testFiles = commit.files.filter((f) => f.includes('test') || f.includes('spec'));\n const srcFiles = commit.files.filter((f) => !f.includes('test') && !f.includes('spec'));\n\n if (testFiles.length > 0 && srcFiles.length > 0) {\n observations.push(\n createObservation({\n source: `git:${commit.hash}:bugfix-test`,\n claim: `Bugfix \"${commit.subject}\" included test verification in ${testFiles.join(', ')}`,\n provenance: {\n type: 'git',\n commit: commit.hash,\n author: commit.author,\n timestamp: commit.date\n },\n confidence: 0.92,\n positive: ['bugfix', 'test-added', ...srcFiles.map((f) => f.split('/').pop()?.toLowerCase() || f)],\n details: { srcFiles, testFiles }\n })\n );\n }\n }\n\n // Count fix occurrences per file for hotspot detection\n if (isFix) {\n for (const file of commit.files) {\n fileFixCount.set(file, (fileFixCount.get(file) ?? 0) + 1);\n }\n }\n\n // Track co-changes for pairs\n if (commit.files.length >= 2 && commit.files.length <= 8) {\n for (let i = 0; i < commit.files.length; i++) {\n for (let j = i + 1; j < commit.files.length; j++) {\n const a = commit.files[i];\n const b = commit.files[j];\n const key = a < b ? `${a} <-> ${b}` : `${b} <-> ${a}`;\n coChangeMap.set(key, (coChangeMap.get(key) ?? 0) + 1);\n }\n }\n }\n }\n\n // Pattern 3: Repeated Fixes Hotspot\n for (const [file, count] of fileFixCount.entries()) {\n if (count >= 3) {\n observations.push(\n createObservation({\n source: `git:hotspot:${file}`,\n claim: `Fragile hotspot: \"${file}\" required ${count} fixes in recent history`,\n provenance: { type: 'git', path: file, timestamp: new Date().toISOString() },\n confidence: 0.88,\n positive: ['hotspot', 'fragile', file.split('/').pop()?.toLowerCase() || file],\n details: { fixCount: count }\n })\n );\n }\n }\n\n // Co-change edges with weight >= 2\n for (const [key, count] of coChangeMap.entries()) {\n if (count >= 2) {\n const [from, to] = key.split(' <-> ');\n relations.push({\n from,\n to,\n type: 'CO_CHANGED',\n weight: count\n });\n relations.push({\n from: to,\n to: from,\n type: 'CO_CHANGED',\n weight: count\n });\n }\n }\n\n return {\n isGitRepo: true,\n headCommit,\n commitsScanned: commits.length,\n observations,\n relations\n };\n}\n","import * as fs from 'node:fs/promises';\nimport * as fsSync from 'node:fs';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport Parser from 'web-tree-sitter';\nimport type { Observation, EvidenceRelation } from '../core/types.js';\nimport { createObservation } from '../core/knowledge.js';\n\nexport interface SourceScanResult {\n observations: Observation[];\n relations: EvidenceRelation[];\n}\n\nconst SOURCE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',\n '.py', '.go', '.rs', '.java', '.c', '.cpp',\n '.h', '.hpp', '.rb', '.php', '.cs', '.swift',\n '.kt', '.scala', '.sh', '.bash', '.zsh', '.sql'\n]);\n\nexport function isSourceFile(ext: string): boolean {\n return SOURCE_EXTENSIONS.has(ext.toLowerCase());\n}\n\nconst EXT_TO_WASM: Record<string, string> = {\n '.ts': 'tree-sitter-typescript.wasm',\n '.mts': 'tree-sitter-typescript.wasm',\n '.cts': 'tree-sitter-typescript.wasm',\n '.tsx': 'tree-sitter-tsx.wasm',\n '.js': 'tree-sitter-javascript.wasm',\n '.mjs': 'tree-sitter-javascript.wasm',\n '.cjs': 'tree-sitter-javascript.wasm',\n '.jsx': 'tree-sitter-javascript.wasm',\n '.py': 'tree-sitter-python.wasm',\n '.go': 'tree-sitter-go.wasm',\n '.rs': 'tree-sitter-rust.wasm'\n};\n\n// Tree-sitter WASM Directory Resolution & Parser Cache\nlet wasmBaseDir: string | null = null;\nlet parserInitialized = false;\nlet parserInstance: Parser | null = null;\nconst languageCache = new Map<string, Parser.Language>();\n\nfunction getWasmDir(): string | null {\n if (wasmBaseDir) return wasmBaseDir;\n try {\n const req = createRequire(import.meta.url);\n const pkgJson = req.resolve('tree-sitter-wasms/package.json');\n const outDir = path.join(path.dirname(pkgJson), 'out');\n if (fsSync.existsSync(outDir)) {\n wasmBaseDir = outDir;\n return wasmBaseDir;\n }\n } catch {\n // Fallback to relative candidate paths\n }\n\n const candidateDirs = [\n path.resolve(process.cwd(), 'node_modules/tree-sitter-wasms/out'),\n path.resolve(process.cwd(), '../node_modules/tree-sitter-wasms/out')\n ];\n\n for (const dir of candidateDirs) {\n if (fsSync.existsSync(dir)) {\n wasmBaseDir = dir;\n return wasmBaseDir;\n }\n }\n\n return null;\n}\n\nasync function getParserForWasm(wasmName: string): Promise<Parser | null> {\n const wasmDir = getWasmDir();\n if (!wasmDir) return null;\n\n const wasmPath = path.join(wasmDir, wasmName);\n if (!fsSync.existsSync(wasmPath)) return null;\n\n try {\n if (!parserInitialized) {\n await Parser.init();\n parserInitialized = true;\n }\n\n if (!parserInstance) {\n parserInstance = new Parser();\n }\n\n let lang = languageCache.get(wasmName);\n if (!lang) {\n lang = await Parser.Language.load(wasmPath);\n languageCache.set(wasmName, lang);\n }\n\n parserInstance.setLanguage(lang);\n return parserInstance;\n } catch {\n return null;\n }\n}\n\nfunction cleanQuote(str: string): string {\n return str.replace(/^['\"`]|['\"`]$/g, '').trim();\n}\n\nfunction getEnclosingScope(node: Parser.SyntaxNode): string | undefined {\n let curr = node.parent;\n const parts: string[] = [];\n while (curr) {\n if (\n curr.type === 'class_declaration' ||\n curr.type === 'class_definition' ||\n curr.type === 'function_declaration' ||\n curr.type === 'function_definition' ||\n curr.type === 'method_definition' ||\n curr.type === 'interface_declaration' ||\n curr.type === 'struct_item' ||\n curr.type === 'impl_item'\n ) {\n const name = curr.childForFieldName('name')?.text;\n if (name) parts.unshift(name);\n }\n curr = curr.parent;\n }\n return parts.length > 0 ? parts.join('.') : undefined;\n}\n\nfunction extractCommentObservation(\n node: Parser.SyntaxNode,\n relativePath: string,\n baseName: string,\n now: string\n): Observation | null {\n const text = node.text;\n const match = text.match(/\\b(TODO|FIXME|HACK|DEPRECATED|WARN|NOTE|BUG)\\b:?\\s*(.*)$/i);\n if (!match) return null;\n\n const tag = match[1].toUpperCase();\n const commentText = match[2].trim() || 'Unspecified';\n const scope = getEnclosingScope(node);\n const line = node.startPosition.row + 1;\n const scopePrefix = scope ? ` in ${scope}` : '';\n\n const positive = [tag.toLowerCase(), baseName.toLowerCase()];\n if (scope) {\n for (const part of scope.split('.')) {\n if (part) positive.push(part.toLowerCase());\n }\n }\n\n const confidence = tag === 'DEPRECATED' || tag === 'FIXME' || tag === 'BUG' ? 0.90 : 0.80;\n\n return createObservation({\n source: `code:${relativePath}#L${line}`,\n claim: `[${tag}${scopePrefix}] in ${baseName}: ${commentText}`,\n provenance: { type: 'code', path: relativePath, line, timestamp: now },\n confidence,\n positive,\n details: { tag, text: commentText, scope, line }\n });\n}\n\n// --- AST Extractors ---\n\nfunction extractFromTsJs(\n root: Parser.SyntaxNode,\n relativePath: string,\n baseName: string,\n now: string,\n observations: Observation[],\n relations: EvidenceRelation[]\n) {\n function walk(node: Parser.SyntaxNode) {\n // 1. Imports\n if (node.type === 'import_statement') {\n const source = node.childForFieldName('source');\n if (source) {\n const target = cleanQuote(source.text);\n relations.push({ from: relativePath, to: target, type: 'IMPORTS' });\n }\n }\n\n // 2. Call expression (require / dynamic import)\n if (node.type === 'call_expression') {\n const fn = node.childForFieldName('function');\n if (fn && (fn.text === 'require' || fn.text === 'import')) {\n const args = node.childForFieldName('arguments');\n if (args && args.namedChildCount > 0) {\n const firstArg = args.namedChild(0);\n if (firstArg && (firstArg.type === 'string' || firstArg.type === 'template_string')) {\n const target = cleanQuote(firstArg.text);\n if (target) {\n relations.push({ from: relativePath, to: target, type: 'IMPORTS' });\n }\n }\n }\n }\n }\n\n // 3. Export statements (definitions & re-exports)\n if (node.type === 'export_statement') {\n const source = node.childForFieldName('source');\n if (source) {\n const target = cleanQuote(source.text);\n relations.push({ from: relativePath, to: target, type: 'IMPORTS' });\n }\n\n for (let i = 0; i < node.namedChildCount; i++) {\n const child = node.namedChild(i);\n if (!child) continue;\n\n if (\n child.type === 'function_declaration' ||\n child.type === 'class_declaration' ||\n child.type === 'interface_declaration' ||\n child.type === 'type_alias_declaration' ||\n child.type === 'enum_declaration'\n ) {\n const name = child.childForFieldName('name')?.text;\n const kind = child.type.replace('_declaration', '');\n const line = child.startPosition.row + 1;\n if (name) {\n observations.push(\n createObservation({\n source: `code:${relativePath}#L${line}`,\n claim: `[export ${kind}] ${name} in ${baseName}`,\n provenance: { type: 'code', path: relativePath, line, timestamp: now },\n confidence: 0.85,\n positive: [name.toLowerCase(), kind, baseName.toLowerCase()],\n details: { kind, name, exported: true, line }\n })\n );\n relations.push({\n from: relativePath,\n to: `${relativePath}#${name}`,\n type: 'DEFINES'\n });\n }\n } else if (child.type === 'lexical_declaration') {\n for (let j = 0; j < child.namedChildCount; j++) {\n const decl = child.namedChild(j);\n if (decl && decl.type === 'variable_declarator') {\n const name = decl.childForFieldName('name')?.text;\n const line = decl.startPosition.row + 1;\n if (name) {\n observations.push(\n createObservation({\n source: `code:${relativePath}#L${line}`,\n claim: `[export const] ${name} in ${baseName}`,\n provenance: { type: 'code', path: relativePath, line, timestamp: now },\n confidence: 0.80,\n positive: [name.toLowerCase(), 'const', baseName.toLowerCase()],\n details: { kind: 'const', name, exported: true, line }\n })\n );\n relations.push({\n from: relativePath,\n to: `${relativePath}#${name}`,\n type: 'DEFINES'\n });\n }\n }\n }\n }\n }\n }\n\n // 4. Actionable Comments\n if (node.type === 'comment') {\n const obs = extractCommentObservation(node, relativePath, baseName, now);\n if (obs) observations.push(obs);\n }\n\n // Traverse children\n for (let i = 0; i < node.childCount; i++) {\n const ch = node.child(i);\n if (ch) walk(ch);\n }\n }\n\n walk(root);\n}\n\nfunction extractFromPython(\n root: Parser.SyntaxNode,\n relativePath: string,\n baseName: string,\n now: string,\n observations: Observation[],\n relations: EvidenceRelation[]\n) {\n function walk(node: Parser.SyntaxNode) {\n if (node.type === 'import_statement') {\n for (let i = 0; i < node.namedChildCount; i++) {\n const child = node.namedChild(i);\n if (child && (child.type === 'dotted_name' || child.type === 'aliased_import')) {\n const target = child.type === 'aliased_import' ? child.childForFieldName('name')?.text : child.text;\n if (target) {\n relations.push({ from: relativePath, to: target, type: 'IMPORTS' });\n }\n }\n }\n }\n\n if (node.type === 'import_from_statement') {\n const moduleName = node.childForFieldName('module_name')?.text;\n if (moduleName) {\n relations.push({ from: relativePath, to: moduleName, type: 'IMPORTS' });\n }\n }\n\n if (node.type === 'class_definition' || node.type === 'function_definition') {\n const name = node.childForFieldName('name')?.text;\n const kind = node.type === 'class_definition' ? 'class' : 'def';\n const line = node.startPosition.row + 1;\n if (name && (node.parent?.type === 'module' || node.type === 'class_definition')) {\n observations.push(\n createObservation({\n source: `code:${relativePath}#L${line}`,\n claim: `[${kind}] ${name} in ${baseName}`,\n provenance: { type: 'code', path: relativePath, line, timestamp: now },\n confidence: 0.85,\n positive: [name.toLowerCase(), kind, baseName.toLowerCase()],\n details: { kind, name, line }\n })\n );\n relations.push({\n from: relativePath,\n to: `${relativePath}#${name}`,\n type: 'DEFINES'\n });\n }\n }\n\n if (node.type === 'comment') {\n const obs = extractCommentObservation(node, relativePath, baseName, now);\n if (obs) observations.push(obs);\n }\n\n for (let i = 0; i < node.childCount; i++) {\n const ch = node.child(i);\n if (ch) walk(ch);\n }\n }\n\n walk(root);\n}\n\nfunction extractFromGo(\n root: Parser.SyntaxNode,\n relativePath: string,\n baseName: string,\n now: string,\n observations: Observation[],\n relations: EvidenceRelation[]\n) {\n function walk(node: Parser.SyntaxNode) {\n if (node.type === 'import_spec') {\n const pathNode = node.childForFieldName('path');\n if (pathNode) {\n const target = cleanQuote(pathNode.text);\n relations.push({ from: relativePath, to: target, type: 'IMPORTS' });\n }\n }\n\n if (node.type === 'function_declaration' || node.type === 'method_declaration') {\n const name = node.childForFieldName('name')?.text;\n const line = node.startPosition.row + 1;\n if (name) {\n observations.push(\n createObservation({\n source: `code:${relativePath}#L${line}`,\n claim: `[func] ${name} in ${baseName}`,\n provenance: { type: 'code', path: relativePath, line, timestamp: now },\n confidence: 0.85,\n positive: [name.toLowerCase(), 'func', baseName.toLowerCase()],\n details: { kind: 'func', name, line }\n })\n );\n relations.push({\n from: relativePath,\n to: `${relativePath}#${name}`,\n type: 'DEFINES'\n });\n }\n }\n\n if (node.type === 'type_spec') {\n const name = node.childForFieldName('name')?.text;\n const line = node.startPosition.row + 1;\n if (name) {\n observations.push(\n createObservation({\n source: `code:${relativePath}#L${line}`,\n claim: `[type] ${name} in ${baseName}`,\n provenance: { type: 'code', path: relativePath, line, timestamp: now },\n confidence: 0.85,\n positive: [name.toLowerCase(), 'type', baseName.toLowerCase()],\n details: { kind: 'type', name, line }\n })\n );\n relations.push({\n from: relativePath,\n to: `${relativePath}#${name}`,\n type: 'DEFINES'\n });\n }\n }\n\n if (node.type === 'comment') {\n const obs = extractCommentObservation(node, relativePath, baseName, now);\n if (obs) observations.push(obs);\n }\n\n for (let i = 0; i < node.childCount; i++) {\n const ch = node.child(i);\n if (ch) walk(ch);\n }\n }\n\n walk(root);\n}\n\nfunction extractFromRust(\n root: Parser.SyntaxNode,\n relativePath: string,\n baseName: string,\n now: string,\n observations: Observation[],\n relations: EvidenceRelation[]\n) {\n function walk(node: Parser.SyntaxNode) {\n if (node.type === 'use_declaration') {\n const text = node.text.replace(/^use\\s+/, '').replace(/;$/, '').trim();\n const rootCrate = text.split('::')[0];\n if (rootCrate) {\n relations.push({ from: relativePath, to: rootCrate, type: 'IMPORTS' });\n }\n }\n\n if (\n node.type === 'function_item' ||\n node.type === 'struct_item' ||\n node.type === 'enum_item' ||\n node.type === 'trait_item'\n ) {\n const name = node.childForFieldName('name')?.text;\n const kind = node.type.replace('_item', '');\n const line = node.startPosition.row + 1;\n if (name) {\n observations.push(\n createObservation({\n source: `code:${relativePath}#L${line}`,\n claim: `[${kind}] ${name} in ${baseName}`,\n provenance: { type: 'code', path: relativePath, line, timestamp: now },\n confidence: 0.85,\n positive: [name.toLowerCase(), kind, baseName.toLowerCase()],\n details: { kind, name, line }\n })\n );\n relations.push({\n from: relativePath,\n to: `${relativePath}#${name}`,\n type: 'DEFINES'\n });\n }\n }\n\n if (node.type === 'line_comment' || node.type === 'block_comment') {\n const obs = extractCommentObservation(node, relativePath, baseName, now);\n if (obs) observations.push(obs);\n }\n\n for (let i = 0; i < node.childCount; i++) {\n const ch = node.child(i);\n if (ch) walk(ch);\n }\n }\n\n walk(root);\n}\n\n// --- Fallback Lexical Analyzer ---\n\nfunction analyzeSourceLexical(\n content: string,\n relativePath: string,\n baseName: string,\n now: string\n): SourceScanResult {\n const observations: Observation[] = [];\n const relations: EvidenceRelation[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n\n // 1. Imports (TS/JS, Python, Go, Rust, C/C++)\n const jsImportMatch = line.match(/(?:import\\s+.*?\\s+from\\s+['\"]([^'\"]+)['\"]|require\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\))/);\n if (jsImportMatch) {\n const target = jsImportMatch[1] || jsImportMatch[2];\n relations.push({ from: relativePath, to: target, type: 'IMPORTS' });\n }\n\n const pyImportMatch = line.match(/^(?:from\\s+([a-zA-Z0-9_.]+)\\s+import|import\\s+([a-zA-Z0-9_.]+))/);\n if (pyImportMatch && relativePath.endsWith('.py')) {\n const target = pyImportMatch[1] || pyImportMatch[2];\n relations.push({ from: relativePath, to: target, type: 'IMPORTS' });\n }\n\n const rustUseMatch = line.match(/^use\\s+([a-zA-Z0-9_]+)::/);\n if (rustUseMatch && relativePath.endsWith('.rs')) {\n relations.push({ from: relativePath, to: rustUseMatch[1], type: 'IMPORTS' });\n }\n\n const goImportMatch = line.match(/^import\\s+[\"']([^\"']+)[\"']/);\n if (goImportMatch && relativePath.endsWith('.go')) {\n relations.push({ from: relativePath, to: goImportMatch[1], type: 'IMPORTS' });\n }\n\n // 2. Actionable Code Comments\n const commentMatch = line.match(/\\b(TODO|FIXME|HACK|DEPRECATED|WARN|NOTE|BUG)\\b:?\\s*(.*)$/i);\n if (commentMatch) {\n const tag = commentMatch[1].toUpperCase();\n const text = commentMatch[2].trim() || 'Unspecified';\n const confidence = tag === 'DEPRECATED' || tag === 'FIXME' || tag === 'BUG' ? 0.90 : 0.80;\n observations.push(\n createObservation({\n source: `code:${relativePath}#L${i + 1}`,\n claim: `[${tag}] in ${baseName}: ${text}`,\n provenance: { type: 'code', path: relativePath, line: i + 1, timestamp: now },\n confidence,\n positive: [tag.toLowerCase(), baseName.toLowerCase()],\n details: { tag, text, line: i + 1 }\n })\n );\n }\n }\n\n return { observations, relations };\n}\n\n/**\n * High-performance source code analyzer powered by web-tree-sitter (WASM)\n * with robust lexical fallback. Extracts AST symbols, imports, definitions,\n * and scoped actionable comments without requiring language toolchains.\n */\nexport async function analyzeSourceFile(\n filePath: string,\n relativePath: string\n): Promise<SourceScanResult> {\n const observations: Observation[] = [];\n const relations: EvidenceRelation[] = [];\n\n let content = '';\n try {\n content = await fs.readFile(filePath, 'utf-8');\n } catch {\n return { observations, relations };\n }\n\n // Skip very large generated files (> 500KB)\n if (content.length > 500 * 1024) {\n return { observations, relations };\n }\n\n const now = new Date().toISOString();\n const baseName = path.basename(relativePath);\n const ext = path.extname(relativePath).toLowerCase();\n const wasmName = EXT_TO_WASM[ext];\n\n // Try Tree-sitter AST extraction if language is supported\n if (wasmName) {\n try {\n const parser = await getParserForWasm(wasmName);\n if (parser) {\n const tree = parser.parse(content);\n const root = tree.rootNode;\n\n if (ext === '.ts' || ext === '.mts' || ext === '.cts' || ext === '.tsx' || ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {\n extractFromTsJs(root, relativePath, baseName, now, observations, relations);\n } else if (ext === '.py') {\n extractFromPython(root, relativePath, baseName, now, observations, relations);\n } else if (ext === '.go') {\n extractFromGo(root, relativePath, baseName, now, observations, relations);\n } else if (ext === '.rs') {\n extractFromRust(root, relativePath, baseName, now, observations, relations);\n }\n\n return { observations, relations };\n }\n } catch {\n // Tree-sitter failed; fall back to lexical\n }\n }\n\n return analyzeSourceLexical(content, relativePath, baseName, now);\n}\n","import * as path from 'node:path';\nimport type {\n Observation,\n Evidence,\n EvidenceRelation,\n Knowledge,\n UnknownRecord\n} from '../core/types.js';\nimport { createEvidence, createKnowledge, reconcileKnowledge, applyReconciliation } from '../core/knowledge.js';\nimport { createUnknown } from '../core/unknown.js';\nimport { EvidenceGraph } from '../core/relations.js';\nimport { Storage } from '../storage/canonical.js';\nimport { SearchIndex } from '../search/indexer.js';\nimport { walkDirectory, analyzeProjectStructure, ProjectContext, type ScannedFileInfo } from './filesystem.js';\nimport { parseMarkdownFile } from './markdown.js';\nimport { scanGitHistory } from './git.js';\nimport { analyzeSourceFile, isSourceFile } from './source.js';\nimport { loadAllProjectRuleSets } from '../rules/loader.js';\nimport { evaluateRule, ruleToObservation, ruleToCandidateLesson } from '../rules/evaluator.js';\n\nexport interface ScanOptions {\n incremental?: boolean;\n maxCommits?: number;\n dryRun?: boolean;\n}\n\nexport interface ScanReport {\n filesScanned: number;\n observationsCreated: number;\n evidenceCreated: number;\n knowledgeCreated: number;\n knowledgeUpdated: number;\n unknownsCount: number;\n gitCommitsScanned: number;\n headCommit?: string;\n incremental: boolean;\n dryRun: boolean;\n plannedActions?: string[];\n}\n\n/**\n * Executes a comprehensive, conservative repository scan:\n * Sources -> Observations -> Evidence Graph -> Explicit Rule/ADR Candidates -> Reconcile -> Knowledge\n *\n * Core philosophy: Deterministik scan'in esas çıktısı observation/evidence'tır.\n * Scan her şeyden zoraki knowledge üretmez. Semantik olarak kesin olmayan sinyaller\n * gözlem ve kanıt olarak kalır (\"ederinden fazlasını vaat etmeme\").\n */\nexport async function scanRepository(\n rootDir: string = process.cwd(),\n options: ScanOptions = {}\n): Promise<ScanReport> {\n const storage = new Storage(rootDir);\n const dryRun = options.dryRun ?? false;\n const plannedActions: string[] = [];\n\n const config = dryRun ? (await storage.isInitialized() ? await storage.getConfig() : {\n schemaVersion: 1,\n projectName: path.basename(rootDir),\n defaultScope: 'project' as const,\n dataDir: path.join(rootDir, '.bilmem')\n }) : await storage.init();\n\n const incremental = options.incremental ?? false;\n const lastScanCommit = incremental ? config.lastScanCommit : undefined;\n\n // 1. Filesystem Scan\n const scannedFiles = await walkDirectory(rootDir);\n const fsObs = await analyzeProjectStructure(scannedFiles, rootDir);\n const projectContext = new ProjectContext(scannedFiles, rootDir);\n\n // 1.5. Declarative YAML Rule Sets Scan (.bilmem/rules/*.yml, bilmem.rules.yml, rules.yml)\n const ruleObs: Observation[] = [];\n const ruleCandidateLessons: Array<Partial<Knowledge> & { statement: string }> = [];\n const { ruleSets, sourceFiles } = await loadAllProjectRuleSets(rootDir, storage.getRulesDir());\n\n for (let idx = 0; idx < ruleSets.length; idx++) {\n const set = ruleSets[idx];\n const sourceFile = sourceFiles[idx] || 'rules.yml';\n for (const rule of set.rules) {\n const evalResult = await evaluateRule(rule, projectContext);\n if (evalResult.matched) {\n const obs = ruleToObservation(rule, evalResult, sourceFile);\n ruleObs.push(obs);\n ruleCandidateLessons.push(ruleToCandidateLesson(rule, evalResult, obs.source));\n }\n }\n }\n\n const mdObs: Observation[] = [];\n const srcObs: Observation[] = [];\n const relations: EvidenceRelation[] = [];\n\n for (const file of scannedFiles) {\n if (file.ext === '.md') {\n const res = await parseMarkdownFile(file.path, file.relativePath);\n mdObs.push(...res.observations);\n if (res.relations && res.relations.length > 0) {\n relations.push(...res.relations);\n }\n } else if (isSourceFile(file.ext)) {\n const res = await analyzeSourceFile(file.path, file.relativePath);\n srcObs.push(...res.observations);\n relations.push(...res.relations);\n }\n }\n\n // 2. Git History Scan\n const gitResult = await scanGitHistory(rootDir, {\n lastScanCommit,\n maxCommits: options.maxCommits ?? 100\n });\n relations.push(...gitResult.relations);\n\n // 3. Collect All Observations and Build Evidence Graph\n const allObs: Observation[] = [...fsObs, ...ruleObs, ...mdObs, ...srcObs, ...gitResult.observations];\n\n if (!dryRun) {\n for (const obs of allObs) {\n await storage.saveObservation(obs);\n }\n\n const graph = new EvidenceGraph(await storage.getRelations());\n for (const r of relations) {\n graph.addRelation(r);\n }\n await storage.saveRelations(graph.getAllRelations());\n } else {\n plannedActions.push(`Would persist ${allObs.length} observations`);\n plannedActions.push(`Would record ${relations.length} evidence relations`);\n }\n\n // 4. Create Evidence Nodes\n const evidenceNodes: Evidence[] = [];\n for (const obs of allObs) {\n const ev = createEvidence(obs, 'supports');\n if (!dryRun) {\n await storage.saveEvidence(ev);\n }\n evidenceNodes.push(ev);\n }\n if (dryRun) {\n plannedActions.push(`Would create ${evidenceNodes.length} evidence nodes`);\n }\n\n // 5. Conservative Knowledge Extraction\n // Primary output of scan is Observation/Evidence. Only verified, high-confidence\n // rule sets and explicit ADR decisions become candidate lessons for reconciliation.\n const candidateLessons: Array<Partial<Knowledge> & { statement: string }> = [\n ...ruleCandidateLessons\n ];\n\n // A. From explicit Markdown ADRs with decisions or documented warnings\n for (const o of mdObs) {\n if (o.source.includes(':adr') || o.claim.startsWith('[WARNING]') || o.claim.startsWith('[CAUTION]')) {\n const id = `decision.${path.basename(o.provenance.path || 'doc', '.md')}.${o.provenance.line || 'adr'}`;\n candidateLessons.push({\n id,\n type: 'decision',\n statement: o.claim,\n positive: o.positive ?? [],\n negative: o.negative ?? [],\n confidence: o.confidence,\n evidence: [o.source],\n scope: 'project'\n });\n }\n }\n\n // B. From Git Reverts (verified failure lesson)\n for (const o of gitResult.observations) {\n if (o.positive?.includes('revert')) {\n candidateLessons.push({\n id: `git.lesson.${o.provenance.commit || 'revert'}`,\n type: 'lesson',\n statement: `Caution: ${o.claim}`,\n positive: o.positive,\n negative: ['untested-assumption'],\n confidence: o.confidence,\n evidence: [o.source],\n scope: 'project'\n });\n }\n }\n\n // 6. Check for Unknowns (e.g. database migration, deployment pipeline)\n const relPaths = new Set(scannedFiles.map((f) => f.relativePath.toLowerCase()));\n const hasMigrations = Array.from(relPaths).some((p) => p.includes('migration') || p.includes('migrate'));\n const hasDb = Array.from(relPaths).some((p) => p.includes('db') || p.includes('database') || p.includes('sql'));\n let unknownCount = 0;\n\n if (hasDb && !hasMigrations) {\n unknownCount++;\n const unknownRec = createUnknown({\n id: 'project.database.migration',\n state: 'UNKNOWN',\n reason: 'UNRESOLVABLE_LOCALLY',\n statement: 'Database directory exists, but no explicit migration tool or folder was found locally.',\n checked: ['package.json', 'src/db/**', 'scripts/**'],\n next: {\n type: 'ask',\n question: 'How are database migrations performed in this project?'\n },\n scope: 'project'\n });\n if (!dryRun) {\n await storage.saveUnknown(unknownRec);\n } else {\n plannedActions.push(`Would register unknown: \"${unknownRec.statement}\"`);\n }\n }\n\n // 7. Reconciliation with Canonical Knowledge Base\n const existingKnowledge = await storage.getAllKnowledge();\n let createdCount = 0;\n let updatedCount = 0;\n\n for (const cand of candidateLessons) {\n const rec = reconcileKnowledge(cand, existingKnowledge);\n if (!dryRun) {\n const { updatedKnowledge, action } = applyReconciliation(rec, cand, existingKnowledge, storage);\n await storage.saveKnowledge(updatedKnowledge);\n\n if (action === 'NEW' || action === 'SPECIALIZE') {\n createdCount++;\n existingKnowledge.push(updatedKnowledge);\n } else if (action === 'SUPPORT' || action === 'UPDATE' || action === 'MERGE' || action === 'CONTRADICT') {\n updatedCount++;\n }\n } else {\n plannedActions.push(`Would reconcile [${rec.action}]: \"${cand.statement}\" (${rec.reason})`);\n if (rec.action === 'NEW' || rec.action === 'SPECIALIZE') {\n createdCount++;\n } else if (rec.action !== 'IGNORE') {\n updatedCount++;\n }\n }\n }\n\n if (!dryRun) {\n // 8. Rebuild Search Index\n const index = new SearchIndex();\n await index.buildIndex(existingKnowledge);\n\n // 9. Update Config with Last Scan Commit\n await storage.updateConfig({\n lastScanCommit: gitResult.headCommit ?? config.lastScanCommit,\n lastScanTimestamp: new Date().toISOString()\n });\n\n // 10. Record Revision Snapshot for Incremental Diff\n await storage.appendRevision({\n id: `rev_${Date.now().toString(36)}`,\n commit: gitResult.headCommit,\n timestamp: new Date().toISOString(),\n action: 'scan',\n observationCount: allObs.length,\n evidenceCount: evidenceNodes.length,\n knowledgeCount: existingKnowledge.length,\n activeCount: existingKnowledge.filter((k) => k.status === 'active').length,\n contradictedCount: existingKnowledge.filter((k) => k.status === 'contradicted').length,\n staleCount: existingKnowledge.filter((k) => k.status === 'stale').length,\n changesSummary: `Scanned ${scannedFiles.length} files: +${allObs.length} obs, +${createdCount} candidates, ~${updatedCount} updated.`\n });\n }\n\n const unknowns = dryRun ? [] : await storage.getAllUnknowns();\n\n return {\n filesScanned: scannedFiles.length,\n observationsCreated: allObs.length,\n evidenceCreated: evidenceNodes.length,\n knowledgeCreated: createdCount,\n knowledgeUpdated: updatedCount,\n unknownsCount: dryRun ? unknownCount : unknowns.length,\n gitCommitsScanned: gitResult.commitsScanned,\n headCommit: gitResult.headCommit,\n incremental,\n dryRun,\n plannedActions: dryRun ? plannedActions : undefined\n };\n}\n","import type {\n UnknownRecord,\n UnknownState,\n UnknownReason,\n UnknownNextAction,\n Scope\n} from './types.js';\n\nexport function createUnknown(params: {\n id: string;\n state?: UnknownState;\n reason?: UnknownReason;\n statement?: string;\n checked?: string[];\n next?: UnknownNextAction;\n scope?: Scope;\n}): UnknownRecord {\n const now = new Date().toISOString();\n return {\n id: params.id.trim(),\n state: params.state ?? 'UNKNOWN',\n reason: params.reason ?? 'NOT_OBSERVED',\n statement: params.statement?.trim(),\n checked: Array.from(new Set(params.checked?.map((c) => c.trim()) ?? [])),\n next: params.next,\n scope: params.scope ?? 'project',\n createdAt: now,\n updatedAt: now\n };\n}\n\n/**\n * Checks if a specific path or query was already investigated,\n * helping agents avoid repeating useless investigations.\n */\nexport function hasBeenInvestigated(\n unknowns: UnknownRecord[],\n target: string\n): { investigated: boolean; record?: UnknownRecord; reason?: string } {\n const normalizedTarget = target.trim().toLowerCase();\n\n for (const record of unknowns) {\n if (record.id.toLowerCase() === normalizedTarget) {\n return { investigated: true, record, reason: record.reason };\n }\n\n const checkedMatch = record.checked.some((c) => {\n const nc = c.toLowerCase();\n return nc === normalizedTarget || normalizedTarget.startsWith(nc.replace('/**', ''));\n });\n\n if (checkedMatch) {\n return { investigated: true, record, reason: record.reason };\n }\n }\n\n return { investigated: false };\n}\n\n/**\n * Update an existing unknown with new checked paths or update its state when partially known or resolved.\n */\nexport function updateUnknown(\n record: UnknownRecord,\n updates: {\n state?: UnknownState;\n reason?: UnknownReason;\n statement?: string;\n addChecked?: string[];\n next?: UnknownNextAction;\n }\n): UnknownRecord {\n const checked = new Set(record.checked);\n if (updates.addChecked) {\n for (const c of updates.addChecked) {\n checked.add(c.trim());\n }\n }\n\n return {\n ...record,\n state: updates.state ?? record.state,\n reason: updates.reason ?? record.reason,\n statement: updates.statement !== undefined ? updates.statement : record.statement,\n checked: Array.from(checked),\n next: updates.next !== undefined ? updates.next : record.next,\n updatedAt: new Date().toISOString()\n };\n}\n","import type { EvidenceRelation, RelationType } from './types.js';\n\n/**\n * Lightweight, in-memory graph structure for managing relations between\n * files, observations, evidence, and knowledge nodes.\n */\nexport class EvidenceGraph {\n private fromMap = new Map<string, EvidenceRelation[]>();\n private toMap = new Map<string, EvidenceRelation[]>();\n\n constructor(relations: EvidenceRelation[] = []) {\n for (const rel of relations) {\n this.addRelation(rel);\n }\n }\n\n addRelation(relation: EvidenceRelation): void {\n if (!relation || !relation.from || !relation.to || !relation.type) {\n return;\n }\n\n // Prevent identical duplicate edges\n const existing = this.getRelationsBetween(relation.from, relation.to);\n const dup = existing.find((r) => r.type === relation.type);\n if (dup) {\n // If weight differs, increase weight\n dup.weight = (dup.weight ?? 1) + (relation.weight ?? 1);\n return;\n }\n\n const fromList = this.fromMap.get(relation.from) ?? [];\n fromList.push(relation);\n this.fromMap.set(relation.from, fromList);\n\n const toList = this.toMap.get(relation.to) ?? [];\n toList.push(relation);\n this.toMap.set(relation.to, toList);\n }\n\n getRelationsFrom(fromId: string): EvidenceRelation[] {\n return this.fromMap.get(fromId) ?? [];\n }\n\n getRelationsTo(toId: string): EvidenceRelation[] {\n return this.toMap.get(toId) ?? [];\n }\n\n getRelationsBetween(fromId: string, toId: string): EvidenceRelation[] {\n const fromList = this.fromMap.get(fromId);\n if (!fromList) return [];\n return fromList.filter((r) => r.to === toId);\n }\n\n getAllRelations(): EvidenceRelation[] {\n const all: EvidenceRelation[] = [];\n for (const list of this.fromMap.values()) {\n all.push(...list);\n }\n return all;\n }\n\n findCoChanged(file: string, threshold = 1): Array<{ file: string; weight: number }> {\n const relations = this.getRelationsFrom(file).filter((r) => r.type === 'CO_CHANGED');\n const result: Array<{ file: string; weight: number }> = [];\n\n for (const rel of relations) {\n const w = rel.weight ?? 1;\n if (w >= threshold) {\n result.push({ file: rel.to, weight: w });\n }\n }\n\n return result.sort((a, b) => b.weight - a.weight);\n }\n\n findConnected(id: string, maxDepth = 2): string[] {\n const visited = new Set<string>();\n const queue: Array<{ node: string; depth: number }> = [{ node: id, depth: 0 }];\n\n while (queue.length > 0) {\n const { node, depth } = queue.shift()!;\n if (visited.has(node)) continue;\n visited.add(node);\n\n if (depth < maxDepth) {\n const outRels = this.getRelationsFrom(node);\n for (const r of outRels) {\n if (!visited.has(r.to)) {\n queue.push({ node: r.to, depth: depth + 1 });\n }\n }\n const inRels = this.getRelationsTo(node);\n for (const r of inRels) {\n if (!visited.has(r.from)) {\n queue.push({ node: r.from, depth: depth + 1 });\n }\n }\n }\n }\n\n visited.delete(id);\n return Array.from(visited);\n }\n\n toJSON(): EvidenceRelation[] {\n return this.getAllRelations();\n }\n\n static fromJSON(relations: EvidenceRelation[]): EvidenceGraph {\n return new EvidenceGraph(relations);\n }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type {\n Knowledge,\n Evidence,\n Observation,\n UnknownRecord,\n OutcomeRecord,\n EvidenceRelation,\n BilmemConfig,\n BilmemMetrics,\n RuleSet,\n RuleDefinition,\n RevisionSnapshot,\n KnowledgeDiff,\n InvestigationReceipt\n} from '../core/types.js';\nimport type { KnowledgeStoreProvider } from '../search/retriever.js';\nimport {\n loadRuleSetFile,\n stringifyRuleSetYaml,\n findRuleFiles\n} from '../rules/loader.js';\nimport type { MetricEvent } from '../stats/types.js';\nimport { readMetricEvents, resetMetricEvents } from '../stats/events.js';\n\nexport function sanitizeFileName(id: string): string {\n return encodeURIComponent(id).replace(/%/g, '_');\n}\n\nexport function desanitizeFileName(name: string): string {\n try {\n return decodeURIComponent(name.replace(/_/g, '%'));\n } catch {\n return name;\n }\n}\n\nexport class Storage implements KnowledgeStoreProvider {\n private baseDir: string;\n private knowledgeDir: string;\n private evidenceDir: string;\n private observationDir: string;\n private unknownDir: string;\n private rulesDir: string;\n private configFile: string;\n private relationsFile: string;\n private outcomesFile: string;\n private metricsFile: string;\n private revisionsFile: string;\n private knowledgeJsonlFile: string;\n private evidenceJsonlFile: string;\n private observationJsonlFile: string;\n private unknownsJsonlFile: string;\n private receiptsDir: string;\n private receiptsJsonlFile: string;\n private eventsFile: string;\n\n constructor(rootDir: string = process.cwd()) {\n this.baseDir = path.resolve(rootDir, '.bilmem');\n this.knowledgeDir = path.join(this.baseDir, 'knowledge');\n this.evidenceDir = path.join(this.baseDir, 'evidence');\n this.observationDir = path.join(this.baseDir, 'observations');\n this.unknownDir = path.join(this.baseDir, 'unknowns');\n this.rulesDir = path.join(this.baseDir, 'rules');\n this.receiptsDir = path.join(this.baseDir, 'receipts');\n this.configFile = path.join(this.baseDir, 'config.json');\n this.relationsFile = path.join(this.baseDir, 'relations.json');\n this.outcomesFile = path.join(this.baseDir, 'outcomes.jsonl');\n this.metricsFile = path.join(this.baseDir, 'metrics.json');\n this.revisionsFile = path.join(this.baseDir, 'revisions.jsonl');\n this.knowledgeJsonlFile = path.join(this.baseDir, 'knowledge.jsonl');\n this.evidenceJsonlFile = path.join(this.baseDir, 'evidence.jsonl');\n this.observationJsonlFile = path.join(this.baseDir, 'observations.jsonl');\n this.unknownsJsonlFile = path.join(this.baseDir, 'unknowns.jsonl');\n this.receiptsJsonlFile = path.join(this.baseDir, 'receipts.jsonl');\n this.eventsFile = path.join(this.baseDir, 'events.jsonl');\n }\n\n getBaseDir(): string {\n return this.baseDir;\n }\n\n async isInitialized(): Promise<boolean> {\n try {\n await fs.access(this.configFile);\n return true;\n } catch {\n return false;\n }\n }\n\n async init(options: { projectName?: string; defaultScope?: string } = {}): Promise<BilmemConfig> {\n await fs.mkdir(this.knowledgeDir, { recursive: true });\n await fs.mkdir(this.evidenceDir, { recursive: true });\n await fs.mkdir(this.observationDir, { recursive: true });\n await fs.mkdir(this.unknownDir, { recursive: true });\n await fs.mkdir(this.rulesDir, { recursive: true });\n await fs.mkdir(this.receiptsDir, { recursive: true });\n\n let config: BilmemConfig;\n if (await this.isInitialized()) {\n config = await this.getConfig();\n } else {\n config = {\n schemaVersion: 1,\n projectName: options.projectName ?? path.basename(path.dirname(this.baseDir)) ?? 'project',\n defaultScope: options.defaultScope ?? 'project',\n dataDir: this.baseDir\n };\n await this.saveConfig(config);\n }\n\n // Initialize relations & metrics if missing\n try {\n await fs.access(this.relationsFile);\n } catch {\n await fs.writeFile(this.relationsFile, JSON.stringify([], null, 2), 'utf-8');\n }\n\n try {\n await fs.access(this.metricsFile);\n } catch {\n const defaultMetrics: BilmemMetrics = {\n knowledgeHits: 0,\n knowledgeMisses: 0,\n knowledgeReused: 0,\n unknownsResolved: 0,\n repeatedInvestigationsPrevented: 0,\n candidateKnowledgeMerged: 0,\n staleKnowledgeDetected: 0,\n contradictionsDetected: 0,\n knowledgePromoted: 0,\n knowledgeSuperseded: 0\n };\n await fs.writeFile(this.metricsFile, JSON.stringify(defaultMetrics, null, 2), 'utf-8');\n }\n\n return config;\n }\n\n // --- Config ---\n\n async getConfig(): Promise<BilmemConfig> {\n const raw = await fs.readFile(this.configFile, 'utf-8');\n return JSON.parse(raw) as BilmemConfig;\n }\n\n async saveConfig(config: BilmemConfig): Promise<void> {\n await fs.writeFile(this.configFile, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n async updateConfig(updates: Partial<BilmemConfig>): Promise<BilmemConfig> {\n const current = await this.getConfig();\n const updated = { ...current, ...updates };\n await this.saveConfig(updated);\n return updated;\n }\n\n // --- Knowledge ---\n\n async saveKnowledge(knowledge: Knowledge): Promise<void> {\n await fs.mkdir(this.knowledgeDir, { recursive: true });\n const filename = `${sanitizeFileName(knowledge.id)}.json`;\n const filePath = path.join(this.knowledgeDir, filename);\n await fs.writeFile(filePath, JSON.stringify(knowledge, null, 2), 'utf-8');\n await fs.appendFile(this.knowledgeJsonlFile, JSON.stringify(knowledge) + '\\n', 'utf-8');\n }\n\n async getKnowledge(id: string): Promise<Knowledge | undefined> {\n const filename = `${sanitizeFileName(id)}.json`;\n const filePath = path.join(this.knowledgeDir, filename);\n try {\n const raw = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(raw) as Knowledge;\n } catch {\n return undefined;\n }\n }\n\n async getAllKnowledge(): Promise<Knowledge[]> {\n try {\n const files = await fs.readdir(this.knowledgeDir);\n const items: Knowledge[] = [];\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const raw = await fs.readFile(path.join(this.knowledgeDir, file), 'utf-8');\n try {\n items.push(JSON.parse(raw));\n } catch {\n // Ignore corrupt file\n }\n }\n return items;\n } catch {\n return [];\n }\n }\n\n async deleteKnowledge(id: string): Promise<boolean> {\n const filename = `${sanitizeFileName(id)}.json`;\n const filePath = path.join(this.knowledgeDir, filename);\n try {\n await fs.unlink(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n // --- Evidence ---\n\n async saveEvidence(evidence: Evidence): Promise<void> {\n await fs.mkdir(this.evidenceDir, { recursive: true });\n const filename = `${sanitizeFileName(evidence.id)}.json`;\n const filePath = path.join(this.evidenceDir, filename);\n await fs.writeFile(filePath, JSON.stringify(evidence, null, 2), 'utf-8');\n await fs.appendFile(this.evidenceJsonlFile, JSON.stringify(evidence) + '\\n', 'utf-8');\n }\n\n async getEvidence(id: string): Promise<Evidence | undefined> {\n const filename = `${sanitizeFileName(id)}.json`;\n const filePath = path.join(this.evidenceDir, filename);\n try {\n const raw = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(raw) as Evidence;\n } catch {\n return undefined;\n }\n }\n\n async getAllEvidence(): Promise<Evidence[]> {\n try {\n const files = await fs.readdir(this.evidenceDir);\n const items: Evidence[] = [];\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const raw = await fs.readFile(path.join(this.evidenceDir, file), 'utf-8');\n try {\n items.push(JSON.parse(raw));\n } catch {}\n }\n return items;\n } catch {\n return [];\n }\n }\n\n // --- Observations ---\n\n async saveObservation(obs: Observation): Promise<void> {\n await fs.mkdir(this.observationDir, { recursive: true });\n const filename = `${sanitizeFileName(obs.id)}.json`;\n const filePath = path.join(this.observationDir, filename);\n await fs.writeFile(filePath, JSON.stringify(obs, null, 2), 'utf-8');\n await fs.appendFile(this.observationJsonlFile, JSON.stringify(obs) + '\\n', 'utf-8');\n }\n\n async getObservation(id: string): Promise<Observation | undefined> {\n const filename = `${sanitizeFileName(id)}.json`;\n const filePath = path.join(this.observationDir, filename);\n try {\n const raw = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(raw) as Observation;\n } catch {\n return undefined;\n }\n }\n\n async getAllObservations(): Promise<Observation[]> {\n try {\n const files = await fs.readdir(this.observationDir);\n const items: Observation[] = [];\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const raw = await fs.readFile(path.join(this.observationDir, file), 'utf-8');\n try {\n items.push(JSON.parse(raw));\n } catch {}\n }\n return items;\n } catch {\n return [];\n }\n }\n\n async deleteObservation(id: string): Promise<boolean> {\n const filename = `${sanitizeFileName(id)}.json`;\n const filePath = path.join(this.observationDir, filename);\n try {\n await fs.unlink(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n // --- Unknowns ---\n\n async saveUnknown(record: UnknownRecord): Promise<void> {\n await fs.mkdir(this.unknownDir, { recursive: true });\n const filename = `${sanitizeFileName(record.id)}.json`;\n const filePath = path.join(this.unknownDir, filename);\n await fs.writeFile(filePath, JSON.stringify(record, null, 2), 'utf-8');\n await fs.appendFile(this.unknownsJsonlFile, JSON.stringify(record) + '\\n', 'utf-8');\n }\n\n async getUnknown(id: string): Promise<UnknownRecord | undefined> {\n const filename = `${sanitizeFileName(id)}.json`;\n const filePath = path.join(this.unknownDir, filename);\n try {\n const raw = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(raw) as UnknownRecord;\n } catch {\n return undefined;\n }\n }\n\n async getAllUnknowns(): Promise<UnknownRecord[]> {\n try {\n const files = await fs.readdir(this.unknownDir);\n const items: UnknownRecord[] = [];\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const raw = await fs.readFile(path.join(this.unknownDir, file), 'utf-8');\n try {\n items.push(JSON.parse(raw));\n } catch {}\n }\n return items;\n } catch {\n return [];\n }\n }\n\n async deleteUnknown(id: string): Promise<boolean> {\n const filename = `${sanitizeFileName(id)}.json`;\n const filePath = path.join(this.unknownDir, filename);\n try {\n await fs.unlink(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n // --- Outcomes (Append-oriented log) ---\n\n async appendOutcome(outcome: OutcomeRecord): Promise<void> {\n const line = JSON.stringify(outcome) + '\\n';\n await fs.appendFile(this.outcomesFile, line, 'utf-8');\n if (outcome.knowledgeId) {\n await this.appendMetricEvent({\n type: 'outcome',\n knowledgeId: outcome.knowledgeId,\n result: outcome.result,\n timestamp: Date.now()\n });\n if (outcome.result === 'success') {\n await this.appendMetricEvent({\n type: 'question_resolved',\n questionId: outcome.knowledgeId,\n timestamp: Date.now()\n });\n }\n }\n }\n\n async getAllOutcomes(): Promise<OutcomeRecord[]> {\n try {\n const raw = await fs.readFile(this.outcomesFile, 'utf-8');\n const lines = raw.split('\\n').filter((l) => l.trim().length > 0);\n return lines.map((l) => JSON.parse(l));\n } catch {\n return [];\n }\n }\n\n // --- Metric Events (Append-only local log) ---\n\n async appendMetricEvent(event: MetricEvent): Promise<void> {\n try {\n await fs.mkdir(this.baseDir, { recursive: true });\n await fs.appendFile(this.eventsFile, JSON.stringify(event) + '\\n', 'utf-8');\n } catch {\n // non-fatal\n }\n }\n\n async getMetricEvents(filter?: { sinceTimestamp?: number; knowledgeId?: string }): Promise<MetricEvent[]> {\n return readMetricEvents(path.dirname(this.baseDir), filter);\n }\n\n async resetMetricEvents(): Promise<void> {\n return resetMetricEvents(path.dirname(this.baseDir));\n }\n\n // --- Investigation Receipts ---\n\n async saveReceipt(receipt: InvestigationReceipt): Promise<void> {\n await fs.mkdir(this.receiptsDir, { recursive: true });\n const filename = `${sanitizeFileName(receipt.id)}.json`;\n const filePath = path.join(this.receiptsDir, filename);\n await fs.writeFile(filePath, JSON.stringify(receipt, null, 2), 'utf-8');\n await fs.appendFile(this.receiptsJsonlFile, JSON.stringify(receipt) + '\\n', 'utf-8');\n }\n\n async getReceipt(id: string): Promise<InvestigationReceipt | undefined> {\n const filename = `${sanitizeFileName(id)}.json`;\n const filePath = path.join(this.receiptsDir, filename);\n try {\n const raw = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(raw) as InvestigationReceipt;\n } catch {\n return undefined;\n }\n }\n\n async getAllReceipts(): Promise<InvestigationReceipt[]> {\n try {\n const files = await fs.readdir(this.receiptsDir);\n const items: InvestigationReceipt[] = [];\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const raw = await fs.readFile(path.join(this.receiptsDir, file), 'utf-8');\n try {\n items.push(JSON.parse(raw));\n } catch {}\n }\n return items;\n } catch {\n return [];\n }\n }\n\n // --- Relations ---\n\n async getRelations(): Promise<EvidenceRelation[]> {\n try {\n const raw = await fs.readFile(this.relationsFile, 'utf-8');\n return JSON.parse(raw) as EvidenceRelation[];\n } catch {\n return [];\n }\n }\n\n async saveRelations(relations: EvidenceRelation[]): Promise<void> {\n await fs.writeFile(this.relationsFile, JSON.stringify(relations, null, 2), 'utf-8');\n }\n\n // --- Metrics ---\n\n async getMetrics(): Promise<BilmemMetrics> {\n try {\n const raw = await fs.readFile(this.metricsFile, 'utf-8');\n return JSON.parse(raw) as BilmemMetrics;\n } catch {\n return {\n knowledgeHits: 0,\n knowledgeMisses: 0,\n knowledgeReused: 0,\n unknownsResolved: 0,\n repeatedInvestigationsPrevented: 0,\n candidateKnowledgeMerged: 0,\n staleKnowledgeDetected: 0,\n contradictionsDetected: 0,\n knowledgePromoted: 0,\n knowledgeSuperseded: 0\n };\n }\n }\n\n async saveMetrics(metrics: BilmemMetrics): Promise<void> {\n await fs.writeFile(this.metricsFile, JSON.stringify(metrics, null, 2), 'utf-8');\n }\n\n // --- Rules ---\n\n getRulesDir(): string {\n return this.rulesDir;\n }\n\n async loadRuleSets(): Promise<RuleSet[]> {\n const files = await findRuleFiles(path.dirname(this.baseDir), this.rulesDir);\n const sets: RuleSet[] = [];\n for (const f of files) {\n try {\n sets.push(await loadRuleSetFile(f));\n } catch {}\n }\n return sets;\n }\n\n async saveRuleSet(ruleSet: RuleSet, fileName: string = 'default.yml'): Promise<string> {\n await fs.mkdir(this.rulesDir, { recursive: true });\n const cleanName = fileName.endsWith('.yml') || fileName.endsWith('.yaml') ? fileName : `${fileName}.yml`;\n const targetPath = path.join(this.rulesDir, cleanName);\n const yaml = stringifyRuleSetYaml(ruleSet);\n await fs.writeFile(targetPath, yaml, 'utf-8');\n return targetPath;\n }\n\n async addRule(rule: RuleDefinition, fileName: string = 'default.yml'): Promise<string> {\n await fs.mkdir(this.rulesDir, { recursive: true });\n const cleanName = fileName.endsWith('.yml') || fileName.endsWith('.yaml') ? fileName : `${fileName}.yml`;\n const targetPath = path.join(this.rulesDir, cleanName);\n\n let existingSet: RuleSet;\n try {\n existingSet = await loadRuleSetFile(targetPath);\n } catch {\n existingSet = {\n name: path.basename(cleanName, path.extname(cleanName)),\n rules: []\n };\n }\n\n const existingIdx = existingSet.rules.findIndex((r) => r.id === rule.id);\n if (existingIdx >= 0) {\n existingSet.rules[existingIdx] = rule;\n } else {\n existingSet.rules.push(rule);\n }\n\n const yaml = stringifyRuleSetYaml(existingSet);\n await fs.writeFile(targetPath, yaml, 'utf-8');\n return targetPath;\n }\n\n // --- Revisions & Incremental Learning Diff ---\n\n async appendRevision(snapshot: RevisionSnapshot): Promise<void> {\n const line = JSON.stringify(snapshot) + '\\n';\n await fs.appendFile(this.revisionsFile, line, 'utf-8');\n }\n\n async getRevisions(): Promise<RevisionSnapshot[]> {\n try {\n const raw = await fs.readFile(this.revisionsFile, 'utf-8');\n const lines = raw.split('\\n').filter((l) => l.trim().length > 0);\n return lines.map((l) => JSON.parse(l));\n } catch {\n return [];\n }\n }\n\n async getLatestRevision(): Promise<RevisionSnapshot | undefined> {\n const revs = await this.getRevisions();\n return revs.length > 0 ? revs[revs.length - 1] : undefined;\n }\n\n async getDiff(sinceRef?: string): Promise<KnowledgeDiff> {\n const revisions = await this.getRevisions();\n let baselineSnapshot: RevisionSnapshot | undefined;\n let targetSnapshot: RevisionSnapshot | undefined;\n\n if (sinceRef && sinceRef.includes('..')) {\n const [startRef, endRef] = sinceRef.split('..').map((s) => s.trim().toLowerCase());\n baselineSnapshot = revisions.find(\n (r) =>\n r.id.toLowerCase() === startRef ||\n r.commit?.toLowerCase() === startRef ||\n r.commit?.toLowerCase().startsWith(startRef) ||\n r.id.toLowerCase().startsWith(startRef)\n );\n targetSnapshot = revisions.find(\n (r) =>\n r.id.toLowerCase() === endRef ||\n r.commit?.toLowerCase() === endRef ||\n r.commit?.toLowerCase().startsWith(endRef) ||\n r.id.toLowerCase().startsWith(endRef)\n );\n } else if (sinceRef) {\n const cleanRef = sinceRef.trim().toLowerCase();\n baselineSnapshot = revisions.find(\n (r) =>\n r.id.toLowerCase() === cleanRef ||\n r.commit?.toLowerCase() === cleanRef ||\n r.commit?.toLowerCase().startsWith(cleanRef) ||\n r.id.toLowerCase().startsWith(cleanRef)\n );\n } else {\n // If no ref provided, compare against the snapshot before the latest (if available)\n if (revisions.length >= 2) {\n baselineSnapshot = revisions[revisions.length - 2];\n } else if (revisions.length === 1) {\n baselineSnapshot = revisions[0];\n }\n }\n\n const baselineTimestamp = baselineSnapshot?.timestamp ?? '1970-01-01T00:00:00.000Z';\n const baselineTime = new Date(baselineTimestamp).getTime();\n const targetTime = targetSnapshot ? new Date(targetSnapshot.timestamp).getTime() : Date.now();\n\n const inWindow = (time: number) => time >= baselineTime && time <= targetTime;\n\n const allObservations = await this.getAllObservations();\n const allKnowledge = await this.getAllKnowledge();\n const allUnknowns = await this.getAllUnknowns();\n\n let observationsAdded = 0;\n for (const obs of allObservations) {\n const obsTime = new Date(obs.recordedAt || obs.provenance?.timestamp || 0).getTime();\n if (inWindow(obsTime)) {\n observationsAdded++;\n }\n }\n\n let candidatesAdded = 0;\n let strengthenedCount = 0;\n let revisedCount = 0;\n let contradictionCount = 0;\n let invalidatedCount = 0;\n let needsRevalidationCount = 0;\n\n const strengthened: string[] = [];\n const revised: string[] = [];\n const contradictions: string[] = [];\n const invalidated: string[] = [];\n const needsRevalidation: string[] = [];\n\n for (const k of allKnowledge) {\n const createdTime = new Date(k.createdAt).getTime();\n const updatedTime = new Date(k.updatedAt).getTime();\n\n if ((k.status === 'invalid' || k.status === 'invalidated') && inWindow(updatedTime)) {\n invalidatedCount++;\n invalidated.push(k.id);\n continue;\n }\n\n if (k.status === 'contradicted' && inWindow(updatedTime)) {\n contradictionCount++;\n contradictions.push(k.id);\n continue;\n }\n\n if ((k.status === 'needs_revalidation' || k.status === 'stale') && inWindow(updatedTime)) {\n needsRevalidationCount++;\n needsRevalidation.push(k.id);\n continue;\n }\n\n if (inWindow(createdTime)) {\n // Newly added knowledge candidate in this window\n candidatesAdded++;\n } else if (inWindow(updatedTime)) {\n // Pre-existing knowledge revised or strengthened\n if (k.metrics.support_count > 1 || k.confidence >= 0.85 || k.metrics.successful_outcomes > 0) {\n strengthenedCount++;\n strengthened.push(k.id);\n } else {\n revisedCount++;\n revised.push(k.id);\n }\n }\n }\n\n let unknownsCount = 0;\n const unknownsList: string[] = [];\n for (const u of allUnknowns) {\n const uTime = new Date(u.createdAt || u.updatedAt || 0).getTime();\n if (inWindow(uTime)) {\n unknownsCount++;\n unknownsList.push(u.id);\n }\n }\n\n const refLabel = sinceRef ?? (baselineSnapshot ? (baselineSnapshot.commit?.slice(0, 7) || baselineSnapshot.id.slice(0, 7)) : undefined);\n\n return {\n sinceRef: refLabel,\n observationsAdded,\n candidatesAdded,\n strengthenedCount,\n revisedCount,\n contradictionCount,\n unknownsCount,\n needsRevalidationCount,\n invalidatedCount,\n details: {\n strengthened,\n revised,\n contradictions,\n unknowns: unknownsList,\n needsRevalidation,\n invalidated\n }\n };\n }\n}\n\nexport function formatKnowledgeDiff(diff: KnowledgeDiff): string {\n const header = diff.sinceRef ? `Since ${diff.sinceRef}:` : 'Recent knowledge changes:';\n const lines = [\n header,\n '',\n `+ ${diff.observationsAdded} observations`,\n `+ ${diff.candidatesAdded} candidates`,\n `↑ ${diff.strengthenedCount} knowledge strengthened`,\n `~ ${diff.revisedCount} knowledge revised`,\n `! ${diff.contradictionCount} contradiction${diff.contradictionCount === 1 ? '' : 's'}`,\n `? ${diff.unknownsCount ?? 0} unknowns`,\n `× ${diff.needsRevalidationCount ?? 0} knowledge needs revalidation`,\n `- ${diff.invalidatedCount} invalidated`\n ];\n return lines.join('\\n');\n}\n\nexport { Storage as CanonicalStorage };\n\n","import YAML from 'yaml';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { RuleDefinition, RuleSet, KnowledgeType } from '../core/types.js';\n\nexport interface RuleValidationResult {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Validates whether an object conforms to the RuleDefinition specification.\n */\nexport function validateRuleDefinition(rule: unknown, index: number = 0): string[] {\n const errors: string[] = [];\n if (!rule || typeof rule !== 'object') {\n errors.push(`Rule at index ${index} must be an object.`);\n return errors;\n }\n\n const r = rule as Partial<RuleDefinition>;\n if (!r.id || typeof r.id !== 'string' || !r.id.trim()) {\n errors.push(`Rule at index ${index} requires a non-empty string 'id'.`);\n }\n\n if (!r.statement || typeof r.statement !== 'string' || !r.statement.trim()) {\n errors.push(`Rule '${r.id || index}' requires a non-empty string 'statement'.`);\n }\n\n if (r.type) {\n const validTypes: KnowledgeType[] = [\n 'rule',\n 'convention',\n 'decision',\n 'lesson',\n 'architecture',\n 'fact'\n ];\n if (!validTypes.includes(r.type)) {\n errors.push(`Rule '${r.id || index}' has invalid type '${r.type}'. Allowed: ${validTypes.join(', ')}.`);\n }\n }\n\n if (r.confidence !== undefined) {\n if (typeof r.confidence !== 'number' || r.confidence < 0 || r.confidence > 1) {\n errors.push(`Rule '${r.id || index}' confidence must be a number between 0.0 and 1.0.`);\n }\n }\n\n if (r.positive !== undefined && !Array.isArray(r.positive)) {\n errors.push(`Rule '${r.id || index}' positive cues must be an array of strings.`);\n }\n\n if (r.negative !== undefined && !Array.isArray(r.negative)) {\n errors.push(`Rule '${r.id || index}' negative cues must be an array of strings.`);\n }\n\n return errors;\n}\n\n/**\n * Validates a RuleSet structure.\n */\nexport function validateRuleSet(data: unknown): RuleValidationResult {\n const errors: string[] = [];\n if (!data || typeof data !== 'object') {\n return { valid: false, errors: ['RuleSet content must be an object or an array of rules.'] };\n }\n\n let rules: unknown[] = [];\n if (Array.isArray(data)) {\n rules = data;\n } else if ('rules' in data && Array.isArray((data as any).rules)) {\n rules = (data as any).rules;\n } else if ('id' in data && 'statement' in data) {\n rules = [data];\n } else {\n return { valid: false, errors: ['RuleSet must contain a \"rules\" array or be a list of rule definitions.'] };\n }\n\n if (rules.length === 0) {\n errors.push('RuleSet contains no rules.');\n }\n\n rules.forEach((rule, idx) => {\n errors.push(...validateRuleDefinition(rule, idx));\n });\n\n return {\n valid: errors.length === 0,\n errors\n };\n}\n\n/**\n * Parses a YAML string into a normalized RuleSet.\n */\nexport function parseRuleSetYaml(content: string, sourcePath: string = 'inline.yml'): RuleSet {\n let parsed: unknown;\n try {\n parsed = YAML.parse(content);\n } catch (err: any) {\n throw new Error(`YAML syntax error in ${sourcePath}: ${err.message}`);\n }\n\n const validation = validateRuleSet(parsed);\n if (!validation.valid) {\n throw new Error(`Invalid RuleSet in ${sourcePath}:\\n- ${validation.errors.join('\\n- ')}`);\n }\n\n if (Array.isArray(parsed)) {\n return {\n name: path.basename(sourcePath, path.extname(sourcePath)),\n rules: parsed as RuleDefinition[]\n };\n }\n\n if ('id' in (parsed as any) && 'statement' in (parsed as any) && !('rules' in (parsed as any))) {\n return {\n name: (parsed as any).id,\n rules: [parsed as RuleDefinition]\n };\n }\n\n const set = parsed as RuleSet;\n return {\n name: set.name ?? path.basename(sourcePath, path.extname(sourcePath)),\n version: set.version ?? 1,\n scope: set.scope ?? 'project',\n description: set.description,\n rules: set.rules\n };\n}\n\n/**\n * Formats a RuleSet into clean, Git-friendly YAML.\n */\nexport function stringifyRuleSetYaml(ruleSet: RuleSet): string {\n const payload: Record<string, unknown> = {};\n if (ruleSet.name) payload.name = ruleSet.name;\n if (ruleSet.version !== undefined) payload.version = ruleSet.version;\n if (ruleSet.scope) payload.scope = ruleSet.scope;\n if (ruleSet.description) payload.description = ruleSet.description;\n\n payload.rules = ruleSet.rules.map((r) => {\n const ruleObj: Record<string, unknown> = {\n id: r.id\n };\n if (r.name) ruleObj.name = r.name;\n ruleObj.statement = r.statement;\n if (r.type && r.type !== 'rule') ruleObj.type = r.type;\n if (r.confidence !== undefined && r.confidence !== 0.95) ruleObj.confidence = r.confidence;\n if (r.scope && r.scope !== 'project') ruleObj.scope = r.scope;\n if (r.positive && r.positive.length > 0) ruleObj.positive = r.positive;\n if (r.negative && r.negative.length > 0) ruleObj.negative = r.negative;\n if (r.tags && r.tags.length > 0) ruleObj.tags = r.tags;\n if (r.when && Object.keys(r.when).length > 0) ruleObj.when = r.when;\n if (r.details && Object.keys(r.details).length > 0) ruleObj.details = r.details;\n return ruleObj;\n });\n\n return YAML.stringify(payload, { indent: 2, lineWidth: 100 });\n}\n\n/**\n * Reads and parses a single YAML rule file.\n */\nexport async function loadRuleSetFile(filePath: string): Promise<RuleSet> {\n const content = await fs.readFile(filePath, 'utf-8');\n return parseRuleSetYaml(content, filePath);\n}\n\n/**\n * Finds all rule YAML files in standard bilmem locations.\n */\nexport async function findRuleFiles(rootDir: string, storageRulesDir?: string): Promise<string[]> {\n const candidates: string[] = [];\n\n // 1. Storage rules directory: .bilmem/rules/*.yml, *.yaml\n const rulesDir = storageRulesDir || path.resolve(rootDir, '.bilmem', 'rules');\n try {\n const entries = await fs.readdir(rulesDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile() && (entry.name.endsWith('.yml') || entry.name.endsWith('.yaml'))) {\n candidates.push(path.join(rulesDir, entry.name));\n }\n }\n } catch {\n // Directory might not exist yet\n }\n\n // 2. Storage root: .bilmem/rules.yml, .bilmem/rules.yaml\n for (const name of ['rules.yml', 'rules.yaml']) {\n const p = path.resolve(rootDir, '.bilmem', name);\n try {\n const st = await fs.stat(p);\n if (st.isFile()) candidates.push(p);\n } catch {}\n }\n\n // 3. Project root: rules.yml, rules.yaml, bilmem.rules.yml, bilmem.rules.yaml\n for (const name of ['bilmem.rules.yml', 'bilmem.rules.yaml', 'rules.yml', 'rules.yaml']) {\n const p = path.resolve(rootDir, name);\n try {\n const st = await fs.stat(p);\n if (st.isFile()) candidates.push(p);\n } catch {}\n }\n\n // Deduplicate canonical paths\n return Array.from(new Set(candidates));\n}\n\n/**\n * Loads and combines all rule sets discovered in project and storage.\n */\nexport async function loadAllProjectRuleSets(\n rootDir: string,\n storageRulesDir?: string\n): Promise<{ ruleSets: RuleSet[]; sourceFiles: string[] }> {\n const files = await findRuleFiles(rootDir, storageRulesDir);\n const ruleSets: RuleSet[] = [];\n const loadedFiles: string[] = [];\n\n for (const file of files) {\n try {\n const set = await loadRuleSetFile(file);\n ruleSets.push(set);\n loadedFiles.push(file);\n } catch (err: any) {\n // Log or keep error context without failing the entire scan\n console.warn(`[bilmem] Warning: Failed to load rule set from ${file}: ${err.message}`);\n }\n }\n\n return { ruleSets, sourceFiles: loadedFiles };\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { MetricEvent } from './types.js';\n\nexport function getEventsFilePath(rootDir: string): string {\n return path.join(rootDir, '.bilmem', 'events.jsonl');\n}\n\n/**\n * Appends a metric event to .bilmem/events.jsonl.\n * Fire-and-forget safe: will not crash caller if filesystem error occurs.\n */\nexport async function appendMetricEvent(\n rootDir: string,\n event: MetricEvent\n): Promise<void> {\n const filePath = getEventsFilePath(rootDir);\n try {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n const line = JSON.stringify(event) + '\\n';\n await fs.appendFile(filePath, line, 'utf-8');\n } catch {\n // Non-fatal logging failure: core operations must never fail due to metric tracking\n }\n}\n\n/**\n * Reads all metric events from .bilmem/events.jsonl with resilience against\n * corrupted tails, empty lines, and malformed entries.\n */\nexport async function readMetricEvents(\n rootDir: string,\n filter?: { sinceTimestamp?: number; knowledgeId?: string }\n): Promise<MetricEvent[]> {\n const filePath = getEventsFilePath(rootDir);\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf-8');\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n return [];\n }\n return [];\n }\n\n const lines = raw.split('\\n');\n const events: MetricEvent[] = [];\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n try {\n const parsed = JSON.parse(trimmed) as MetricEvent;\n if (!parsed || typeof parsed !== 'object' || typeof parsed.type !== 'string') {\n continue;\n }\n if (typeof parsed.timestamp !== 'number') {\n continue;\n }\n\n if (filter?.sinceTimestamp !== undefined && parsed.timestamp < filter.sinceTimestamp) {\n continue;\n }\n\n if (filter?.knowledgeId !== undefined) {\n const kid = (parsed as { knowledgeId?: string }).knowledgeId;\n if (kid !== filter.knowledgeId) {\n continue;\n }\n }\n\n events.push(parsed);\n } catch {\n // Gracefully ignore corrupted line / partial write\n continue;\n }\n }\n\n return events;\n}\n\n/**\n * Safely resets only the metric events log.\n * Preserves all knowledge, evidence, unknowns, rules, and receipts.\n */\nexport async function resetMetricEvents(rootDir: string): Promise<void> {\n const filePath = getEventsFilePath(rootDir);\n try {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, '', 'utf-8');\n } catch (err: any) {\n if (err.code !== 'ENOENT') throw err;\n }\n}\n","import { create, insert, remove, search, type AnyOrama } from '@orama/orama';\nimport type { Knowledge } from '../core/types.js';\n\n/**\n * Rebuildable in-memory search index powered by Orama.\n * Note: Orama is strictly a candidate retrieval cache, NEVER the canonical source of truth.\n */\nexport class SearchIndex {\n private db: AnyOrama | null = null;\n private idToDocId = new Map<string, string>();\n\n async init(): Promise<void> {\n this.db = await create({\n schema: {\n id: 'string',\n statement: 'string',\n type: 'string',\n scope: 'string',\n status: 'string',\n positive: 'string[]',\n negative: 'string[]',\n tags: 'string[]'\n }\n });\n this.idToDocId.clear();\n }\n\n async buildIndex(knowledgeList: Knowledge[]): Promise<void> {\n await this.init();\n for (const item of knowledgeList) {\n await this.upsert(item);\n }\n }\n\n async upsert(item: Knowledge): Promise<void> {\n if (!this.db) {\n await this.init();\n }\n\n // If already in index, remove first\n const existingDocId = this.idToDocId.get(item.id);\n if (existingDocId) {\n try {\n await remove(this.db!, existingDocId);\n } catch {\n // Ignore if already deleted\n }\n this.idToDocId.delete(item.id);\n }\n\n const docId = await insert(this.db!, {\n id: item.id,\n statement: item.statement,\n type: item.type,\n scope: item.scope,\n status: item.status,\n positive: item.positive,\n negative: item.negative,\n tags: item.tags ?? []\n });\n\n this.idToDocId.set(item.id, docId);\n }\n\n async delete(id: string): Promise<void> {\n if (!this.db) return;\n const docId = this.idToDocId.get(id);\n if (docId) {\n try {\n await remove(this.db, docId);\n } catch {\n // Ignore\n }\n this.idToDocId.delete(id);\n }\n }\n\n async searchCandidates(term: string, limit = 25): Promise<string[]> {\n if (!this.db) {\n return [];\n }\n\n const cleanTerm = term.trim();\n if (!cleanTerm) {\n return Array.from(this.idToDocId.keys()).slice(0, limit);\n }\n\n try {\n const results = await search(this.db, {\n term: cleanTerm,\n limit,\n threshold: 0.2\n });\n\n return results.hits.map((h) => (h.document as any).id as string);\n } catch {\n // Fallback: term might contain special characters or fail tokenization\n return Array.from(this.idToDocId.keys()).slice(0, limit);\n }\n }\n\n size(): number {\n return this.idToDocId.size;\n }\n}\n\nexport { SearchIndex as OramaIndex };\n\n","import type {\n RuleDefinition,\n RuleSet,\n EvaluatedRule,\n Observation,\n Knowledge\n} from '../core/types.js';\nimport { createObservation } from '../core/knowledge.js';\nimport type { ProjectContext } from '../scanner/filesystem.js';\n\n/**\n * Converts a simple glob-like pattern (e.g. *.sh, src/**\\/*.ts) into a regular expression.\n */\nfunction globToRegex(glob: string): RegExp {\n let pattern = glob.trim().replace(/^\\//, '').replace(/\\/$/, '');\n pattern = pattern.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n pattern = pattern.replace(/\\*\\*/g, '.*');\n pattern = pattern.replace(/\\*/g, '[^/]*');\n pattern = pattern.replace(/\\?/g, '[^/]');\n return new RegExp(`(^|/)${pattern}$`, 'i');\n}\n\n/**\n * Evaluates a single rule condition against the project context.\n */\nexport async function evaluateRule(\n rule: RuleDefinition,\n context: ProjectContext\n): Promise<EvaluatedRule> {\n const cond = rule.when;\n\n // Unconditional rules are always matched\n if (!cond || Object.keys(cond).length === 0) {\n return {\n rule,\n matched: true,\n reason: 'Always active project rule'\n };\n }\n\n const matchedFiles: string[] = [];\n\n // 1. Check has_file condition\n if (cond.has_file) {\n const files = Array.isArray(cond.has_file) ? cond.has_file : [cond.has_file];\n for (const f of files) {\n if (!context.hasFile(f)) {\n return {\n rule,\n matched: false,\n reason: `Required file '${f}' not found in project`\n };\n }\n matchedFiles.push(f);\n }\n }\n\n // 2. Check missing_file condition\n if (cond.missing_file) {\n const files = Array.isArray(cond.missing_file) ? cond.missing_file : [cond.missing_file];\n for (const f of files) {\n if (context.hasFile(f)) {\n return {\n rule,\n matched: false,\n reason: `Prohibited file '${f}' is present in project`\n };\n }\n }\n }\n\n // 3. Check any_file condition\n if (cond.any_file && cond.any_file.length > 0) {\n let anyFound = false;\n for (const f of cond.any_file) {\n if (context.hasFile(f)) {\n anyFound = true;\n matchedFiles.push(f);\n break;\n }\n }\n if (!anyFound) {\n return {\n rule,\n matched: false,\n reason: `None of the expected files were found: ${cond.any_file.join(', ')}`\n };\n }\n }\n\n // 4. Check file_pattern condition\n if (cond.file_pattern) {\n const regex = globToRegex(cond.file_pattern);\n const matches = context.files.filter(\n (f) => regex.test(f.relativePath) || regex.test(f.name)\n );\n if (matches.length === 0) {\n return {\n rule,\n matched: false,\n reason: `No files matched pattern '${cond.file_pattern}'`\n };\n }\n matchedFiles.push(...matches.slice(0, 5).map((m) => m.relativePath));\n }\n\n // 5. Check content_match condition\n if (cond.content_match) {\n const { files: targetFile, pattern } = cond.content_match;\n const regex = new RegExp(pattern, 'm');\n\n if (targetFile) {\n const content = await context.readText(targetFile);\n if (!content || !regex.test(content)) {\n return {\n rule,\n matched: false,\n reason: `Pattern '${pattern}' was not found in file '${targetFile}'`\n };\n }\n matchedFiles.push(targetFile);\n } else {\n // If no specific file target, search across top candidate files\n let contentFound = false;\n for (const file of context.files.slice(0, 20)) {\n const content = await context.readText(file.relativePath);\n if (content && regex.test(content)) {\n contentFound = true;\n matchedFiles.push(file.relativePath);\n break;\n }\n }\n if (!contentFound) {\n return {\n rule,\n matched: false,\n reason: `Pattern '${pattern}' was not found in project files`\n };\n }\n }\n }\n\n return {\n rule,\n matched: true,\n reason: 'Rule condition matched repository structure',\n matchedFiles: matchedFiles.length > 0 ? Array.from(new Set(matchedFiles)) : undefined\n };\n}\n\n/**\n * Evaluates all rules within a RuleSet against the project context.\n */\nexport async function evaluateRuleSet(\n ruleSet: RuleSet,\n context: ProjectContext\n): Promise<EvaluatedRule[]> {\n const results: EvaluatedRule[] = [];\n for (const rule of ruleSet.rules) {\n results.push(await evaluateRule(rule, context));\n }\n return results;\n}\n\n/**\n * Converts a matched rule into a standard Observation.\n */\nexport function ruleToObservation(\n rule: RuleDefinition,\n evaluated: EvaluatedRule,\n sourceFile: string\n): Observation {\n const now = new Date().toISOString();\n const ruleType = rule.type ?? 'rule';\n\n const positive = [\n ...(rule.positive ?? []),\n rule.id,\n ruleType,\n ...(rule.tags ?? [])\n ];\n\n return createObservation({\n source: `rule:${rule.id}`,\n claim: rule.statement,\n confidence: rule.confidence ?? 0.95,\n provenance: {\n type: 'file',\n path: sourceFile,\n timestamp: now\n },\n positive: Array.from(new Set(positive)),\n negative: rule.negative ? [...rule.negative] : [],\n details: {\n ruleId: rule.id,\n ruleName: rule.name,\n ruleType,\n matchedReason: evaluated.reason,\n matchedFiles: evaluated.matchedFiles,\n scope: rule.scope ?? 'project',\n ...(rule.details ?? {})\n }\n });\n}\n\n/**\n * Converts a matched rule into a candidate Knowledge item.\n */\nexport function ruleToCandidateLesson(\n rule: RuleDefinition,\n evaluated: EvaluatedRule,\n obsSource: string\n): Partial<Knowledge> & { statement: string } {\n const ruleType = rule.type ?? 'rule';\n const positive = [\n ...(rule.positive ?? []),\n rule.id,\n ruleType,\n ...(rule.tags ?? [])\n ];\n\n return {\n id: `rule.${rule.id}`,\n type: ruleType,\n statement: rule.statement,\n positive: Array.from(new Set(positive)),\n negative: rule.negative ? [...rule.negative] : [],\n confidence: rule.confidence ?? 0.95,\n evidence: [obsSource],\n scope: rule.scope ?? 'project',\n tags: rule.tags ? [...rule.tags] : []\n };\n}\n"],"mappings":";AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;;;ACDtB,SAAS,kBAAkB;;;ACYpB,SAAS,sBAAsB,WAA+C;AACnF,MACE,UAAU,SAAS,UACnB,UAAU,SAAS,kBACnB,UAAU,mBAAmB,UAC5B,UAAU,eAAe,UAAa,UAAU,cAAc,MAC/D;AACA,WAAO;AAAA,EACT;AACA,MACE,UAAU,SAAS,YACjB,UAAU,UAAU,UAAU,MAAM,KAAM,UAAU,eAAe,UAAa,UAAU,cAAc,OAC1G;AACA,WAAO;AAAA,EACT;AACA,MAAI,UAAU,eAAe,UAAa,UAAU,cAAc,KAAM;AACtE,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAMO,SAAS,kBAAkB,WAIhC;AACA,QAAM,QAAQ,UAAU,SAAS;AACjC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