@saptools/service-flow 0.1.68 → 0.1.69

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +11 -5
  3. package/TECHNICAL-NOTE.md +9 -0
  4. package/dist/{chunk-AEM4JY22.js → chunk-3N3B5KHV.js} +6983 -5500
  5. package/dist/chunk-3N3B5KHV.js.map +1 -0
  6. package/dist/cli.js +317 -105
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.d.ts +7 -1
  9. package/dist/index.js +1 -1
  10. package/package.json +1 -1
  11. package/src/cli/001-index-summary.ts +22 -0
  12. package/src/cli.ts +151 -87
  13. package/src/db/000-call-fact-repository.ts +45 -19
  14. package/src/db/003-current-fact-semantics.ts +1 -0
  15. package/src/db/004-package-target-invalidation.ts +10 -0
  16. package/src/db/006-relative-symbol-resolution.ts +28 -7
  17. package/src/db/008-relative-fact-semantics.ts +6 -3
  18. package/src/db/009-binding-fact-semantics.ts +5 -0
  19. package/src/db/012-binding-reference-proof.ts +4 -0
  20. package/src/db/013-index-publication-failure.ts +91 -0
  21. package/src/db/014-binding-helper-provenance.ts +17 -0
  22. package/src/db/repositories.ts +22 -5
  23. package/src/indexer/cds-extension-resolver.ts +27 -3
  24. package/src/indexer/repository-indexer.ts +66 -5
  25. package/src/indexer/workspace-indexer.ts +141 -29
  26. package/src/linker/004-event-subscription-handler-linker.ts +32 -11
  27. package/src/linker/006-event-template-link.ts +72 -0
  28. package/src/linker/007-call-edge-insertion.ts +568 -0
  29. package/src/linker/cross-repo-linker.ts +2 -165
  30. package/src/parsers/000-direct-query-execution.ts +11 -0
  31. package/src/parsers/006-binding-identity.ts +6 -1
  32. package/src/parsers/014-service-binding-helper-flow.ts +70 -4
  33. package/src/parsers/021-binding-visibility.ts +17 -1
  34. package/src/parsers/022-outbound-expression-analysis.ts +700 -0
  35. package/src/parsers/023-outbound-call-classifier.ts +692 -0
  36. package/src/parsers/outbound-call-parser.ts +146 -509
  37. package/src/parsers/symbol-parser.ts +37 -5
  38. package/src/trace/007-implementation-start-diagnostic.ts +1 -0
  39. package/src/trace/011-event-subscriber-traversal.ts +100 -8
  40. package/src/trace/013-trace-root-scopes.ts +2 -3
  41. package/src/trace/014-compact-contract.ts +6 -0
  42. package/src/trace/015-trace-edge-recorder.ts +61 -4
  43. package/src/trace/016-compact-projector.ts +2 -3
  44. package/src/trace/019-trace-edge-semantics.ts +6 -10
  45. package/src/trace/020-compact-field-projection.ts +74 -1
  46. package/src/trace/021-compact-decision-normalization.ts +75 -9
  47. package/src/trace/024-compact-observation-decision.ts +7 -2
  48. package/src/trace/026-trace-start-scope.ts +1 -0
  49. package/src/trace/027-trace-scope-execution.ts +33 -33
  50. package/src/trace/030-event-runtime-resolution.ts +151 -0
  51. package/src/trace/031-local-call-expansion.ts +37 -0
  52. package/src/trace/implementation-hints.ts +9 -6
  53. package/src/trace/selectors.ts +1 -0
  54. package/src/types.ts +2 -1
  55. package/src/version.ts +1 -1
  56. package/dist/chunk-AEM4JY22.js.map +0 -1
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/config/defaults.ts","../src/config/workspace-config.ts","../src/db/connection.ts","../src/db/repositories.ts","../src/discovery/classify-repository.ts","../src/utils/diagnostics.ts","../src/indexer/repository-indexer.ts","../src/parsers/symbol-parser.ts","../src/parsers/005-event-subscription-facts.ts","../src/parsers/016-local-symbol-reference.ts","../src/parsers/007-source-fact-reconciliation.ts","../src/parsers/006-binding-identity.ts","../src/parsers/009-symbol-call-facts.ts","../src/parsers/013-executable-body-eligibility.ts","../src/parsers/017-symbol-derived-contexts.ts","../src/parsers/008-package-surface-publication.ts","../src/utils/hashing.ts","../src/db/004-package-target-invalidation.ts","../src/indexer/cds-extension-resolver.ts","../src/indexer/workspace-indexer.ts","../src/cli/001-doctor-projection.ts","../src/cli/002-doctor-lifecycle.ts","../src/cli/003-doctor-package-resolution.ts","../src/cli/doctor.ts","../src/output/table-output.ts","../src/output/json-output.ts","../src/output/doctor-output.ts","../src/output/mermaid-output.ts","../src/output/000-stdout-policy.ts","../src/output/001-compact-json-output.ts","../src/cli/000-clean.ts"],"sourcesContent":["import { Command, Option } from 'commander';\nimport { DEFAULT_IGNORES } from './config/defaults.js';\nimport {\n createWorkspaceConfig,\n loadWorkspaceConfig,\n saveWorkspaceConfig,\n} from './config/workspace-config.js';\nimport { openDatabase, openReadOnlyDatabase, type Db } from './db/connection.js';\nimport {\n getWorkspace,\n listRepositories,\n reposByName,\n type RepoRow,\n upsertRepository,\n upsertWorkspace,\n} from './db/repositories.js';\nimport { discoverRepositories } from './discovery/discover-repositories.js';\nimport { parsePackageJson } from './parsers/package-json-parser.js';\nimport { classifyRepository } from './discovery/classify-repository.js';\nimport { indexWorkspace } from './indexer/workspace-indexer.js';\nimport { linkWorkspace } from './linker/cross-repo-linker.js';\nimport { doctorDiagnostics, linkUpgradeWarnings } from './cli/doctor.js';\nimport { trace } from './trace/trace-engine.js';\nimport { compactTrace } from './trace/018-compact-trace.js';\nimport {\n parseVars,\n selectorRepoAmbiguousDiagnostic,\n} from './trace/selectors.js';\nimport { parseImplementationHint } from './trace/implementation-hints.js';\nimport { renderTraceTable } from './output/table-output.js';\nimport { renderTraceJson, renderJson } from './output/json-output.js';\nimport { renderDoctorDiagnostics } from './output/doctor-output.js';\nimport { renderMermaid } from './output/mermaid-output.js';\nimport { createStdoutWriter } from './output/000-stdout-policy.js';\nimport { renderCompactJson } from './output/001-compact-json-output.js';\nimport { VERSION } from './version.js';\nimport type {\n DynamicMode,\n TraceOptions,\n TraceResult,\n TraceStart,\n} from './types.js';\nimport { cleanWorkspaceState } from './cli/000-clean.js';\n\nconst stdout = createStdoutWriter(process.stdout, fail);\nconst TRACE_FORMATS = ['table', 'json', 'mermaid', 'compact-json'] as const;\nconst GRAPH_FORMATS = ['mermaid', 'json', 'compact-json'] as const;\n\ntype TraceFormat = (typeof TRACE_FORMATS)[number];\ntype GraphFormat = (typeof GRAPH_FORMATS)[number];\n\ninterface TraceCommandOptions {\n workspace?: string;\n repo?: string;\n operation?: string;\n service?: string;\n path?: string;\n handler?: string;\n depth: string;\n format: TraceFormat;\n includeExternal?: boolean;\n includeDb?: boolean;\n includeAsync?: boolean;\n implementationRepo?: string;\n implementationHint: string[];\n var: string[];\n dynamicMode: string;\n maxDynamicCandidates: string;\n}\n\ninterface GraphCommandOptions {\n workspace?: string;\n repo?: string;\n operation?: string;\n service?: string;\n path?: string;\n format: GraphFormat;\n implementationRepo?: string;\n implementationHint: string[];\n var: string[];\n dynamicMode: string;\n maxDynamicCandidates: string;\n}\n\nfunction writeStdout(value: string): void {\n stdout.write(value);\n}\n\nasync function init(\n workspace: string,\n options: { db?: string; ignore?: string[] },\n): Promise<void> {\n const config = createWorkspaceConfig(\n workspace,\n options.db,\n options.ignore?.length ? options.ignore : [...DEFAULT_IGNORES],\n );\n const repos = await discoverRepositories(config.rootPath, config.ignore);\n await saveWorkspaceConfig(config);\n const db = openDatabase(config.dbPath);\n const workspaceId = upsertWorkspace(db, config.rootPath, config.dbPath);\n for (const repo of repos) {\n const pkg = await parsePackageJson(repo.absolutePath);\n const kind = await classifyRepository(repo.absolutePath, pkg);\n upsertRepository(db, workspaceId, {\n ...repo,\n packageName: pkg.packageName,\n packageVersion: pkg.packageVersion,\n dependencies: pkg.dependencies,\n kind,\n });\n }\n db.close();\n writeStdout(\n `Workspace: ${config.rootPath}\\nDatabase: ${config.dbPath}\\nRepositories: ${repos.length}\\nIgnored: ${config.ignore.join(', ')}\\nNext: service-flow index --workspace ${config.rootPath}\\n`,\n );\n}\nasync function withWorkspace<T>(\n workspace: string | undefined,\n fn: (\n db: ReturnType<typeof openDatabase>,\n workspaceId: number,\n rootPath: string,\n ) => Promise<T> | T,\n): Promise<T> {\n const config = await loadWorkspaceConfig(workspace);\n const db = openDatabase(config.dbPath);\n try {\n const row = getWorkspace(db, config.rootPath);\n const workspaceId =\n row?.id ?? upsertWorkspace(db, config.rootPath, config.dbPath);\n return await fn(db, workspaceId, config.rootPath);\n } finally {\n db.close();\n }\n}\nasync function withReadOnlyWorkspace<T>(\n workspace: string | undefined,\n fn: (db: ReturnType<typeof openDatabase>, workspaceId: number, rootPath: string) => Promise<T> | T,\n): Promise<T> {\n const config = await loadWorkspaceConfig(workspace);\n const db = openReadOnlyDatabase(config.dbPath);\n try {\n const row = getWorkspace(db, config.rootPath);\n if (!row) throw new Error(`Workspace is not initialized in ${config.dbPath}`);\n return await fn(db, row.id, config.rootPath);\n } finally {\n db.close();\n }\n}\nfunction selectRepository(db: Db, selector: string, workspaceId?: number): {\n repo?: RepoRow;\n diagnostic?: Record<string, unknown>;\n} {\n const candidates = reposByName(db, selector, workspaceId);\n if (candidates.length === 1) return { repo: candidates[0] };\n if (candidates.length === 0) return {\n diagnostic: {\n severity: 'warning',\n code: 'selector_repo_not_found',\n message: `Repository selector not found: ${selector}`,\n },\n };\n return {\n diagnostic: selectorRepoAmbiguousDiagnostic(\n selector,\n candidates.map((repo) => ({\n id: repo.id,\n name: repo.name,\n packageName: repo.package_name ?? undefined,\n })),\n ),\n };\n}\n\nfunction traceFormatOption(): Option {\n return new Option('--format <format>', TRACE_FORMATS.join('|'))\n .choices([...TRACE_FORMATS])\n .default('table');\n}\n\nfunction graphFormatOption(): Option {\n return new Option('--format <format>', GRAPH_FORMATS.join('|'))\n .choices([...GRAPH_FORMATS])\n .default('mermaid');\n}\n\nfunction writeTraceOutput(\n db: Db,\n start: TraceStart,\n options: TraceOptions,\n format: TraceFormat | GraphFormat,\n): void {\n if (format === 'compact-json') {\n writeStdout(renderCompactJson(compactTrace(db, start, options)));\n return;\n }\n const result = trace(db, start, options);\n writeStdout(renderDetailedTrace(result, format));\n}\n\nfunction renderDetailedTrace(\n result: TraceResult,\n format: Exclude<TraceFormat, 'compact-json'> | Exclude<GraphFormat, 'compact-json'>,\n): string {\n if (format === 'json') return renderTraceJson(result);\n if (format === 'mermaid') return renderMermaid(result);\n return renderTraceTable(result);\n}\n\nfunction runTraceCommand(opts: TraceCommandOptions): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const start: TraceStart = {\n repo: opts.repo, servicePath: opts.service, operation: opts.operation,\n operationPath: opts.path, handler: opts.handler,\n };\n const options: TraceOptions = {\n depth: Number(opts.depth), workspaceId, vars: parseVars(opts.var),\n includeExternal: Boolean(opts.includeExternal),\n includeDb: Boolean(opts.includeDb), includeAsync: Boolean(opts.includeAsync),\n implementationRepo: opts.implementationRepo,\n implementationHints: opts.implementationHint.map(parseImplementationHint),\n dynamicMode: parseDynamicMode(opts.dynamicMode),\n maxDynamicCandidates: parsePositiveInteger(opts.maxDynamicCandidates, 5),\n };\n writeTraceOutput(db, start, options, opts.format);\n });\n}\n\nfunction runGraphCommand(opts: GraphCommandOptions): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const start: TraceStart = {\n repo: opts.repo, operation: opts.operation, servicePath: opts.service,\n operationPath: opts.path,\n };\n const options: TraceOptions = {\n depth: 100, workspaceId, includeAsync: true, includeDb: true,\n includeExternal: true, vars: parseVars(opts.var),\n implementationRepo: opts.implementationRepo,\n implementationHints: opts.implementationHint.map(parseImplementationHint),\n dynamicMode: parseDynamicMode(opts.dynamicMode),\n maxDynamicCandidates: parsePositiveInteger(opts.maxDynamicCandidates, 5),\n };\n writeTraceOutput(db, start, options, opts.format);\n });\n}\n\nexport function createProgram(): Command {\n const program = new Command();\n program\n .name('service-flow')\n .description(\n 'Trace SAP CAP service-to-service flows across multi-repository workspaces',\n )\n .version(VERSION);\n program\n .command('init')\n .argument('<workspace>')\n .option('--db <path>')\n .option('--ignore <pattern...>')\n .action(\n (workspace: string, opts: { db?: string; ignore?: string[] }) =>\n void init(workspace, opts).catch(fail),\n );\n program\n .command('index')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--force')\n .action(\n (opts: { workspace?: string; repo?: string; force?: boolean }) =>\n void withWorkspace(opts.workspace, async (db, workspaceId) => {\n const r = await indexWorkspace(db, workspaceId, {\n repo: opts.repo,\n force: Boolean(opts.force),\n });\n writeStdout(\n `Indexed ${r.indexedCount} repositories, skipped ${r.skippedCount}, ${r.fileCount} files, ${r.diagnosticCount} diagnostics\\n`,\n );\n }).catch(fail),\n );\n program\n .command('link')\n .option('--workspace <path>')\n .option('--force')\n .action(\n (opts: { workspace?: string }) =>\n void withWorkspace(opts.workspace, (db, workspaceId) => {\n const r = linkWorkspace(db, workspaceId);\n const upgradeWarnings = linkUpgradeWarnings(db, workspaceId);\n writeStdout(\n `${upgradeWarnings.length ? `Warnings: ${upgradeWarnings.map((item) => String(item.code)).join(', ')}. Run service-flow doctor --strict for remediation.\\n` : ''}Linked ${r.edgeCount} edges: ${r.remoteResolvedCount} remote operation calls resolved, ${r.localResolvedCount} local operation calls resolved, ${r.unresolvedCount} unresolved operation calls, ${r.ambiguousCount} ambiguous operation calls, ${r.dynamicCount} dynamic operation calls, ${r.terminalCount} terminal call edges, ${r.dependencyResolvedCount} dependency resolved, ${r.dependencyAmbiguousCount} dependency ambiguous, ${r.implementationResolvedCount} implementation resolved, ${r.implementationAmbiguousCount} implementation ambiguous, ${r.implementationUnresolvedCount} implementation unresolved, ${r.subscriptionHandlerResolvedCount} subscription handlers resolved, ${r.subscriptionHandlerAmbiguousCount} subscription handlers ambiguous, ${r.subscriptionHandlerUnresolvedCount} subscription handlers unresolved, ${r.subscriptionHandlerMissingAssociationCount} subscription handler associations missing\\n`,\n );\n }).catch(fail),\n );\n program\n .command('trace')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--operation <name>')\n .option('--service <path>')\n .option('--path <operationPath>')\n .option('--handler <name>')\n .option('--depth <n>', 'trace depth', '25')\n .addOption(traceFormatOption())\n .option('--include-external')\n .option('--include-db')\n .option('--include-async')\n .option('--implementation-repo <name>')\n .option('--implementation-hint <scope>', 'scoped implementation hint', collect, [])\n .option('--var <key=value>', 'dynamic variable', collect, [])\n .option('--dynamic-mode <mode>', 'strict|candidates|infer', 'strict')\n .option('--max-dynamic-candidates <n>', 'maximum dynamic candidates to show', '5')\n .action((opts: TraceCommandOptions) => void runTraceCommand(opts).catch(fail));\n const list = program.command('list');\n list\n .command('repos')\n .option('--workspace <path>')\n .action(\n (opts: { workspace?: string }) =>\n void withReadOnlyWorkspace(opts.workspace, (db, workspaceId) =>\n writeStdout(\n renderJson(\n listRepositories(db, workspaceId).map((r) => ({\n name: r.name,\n kind: r.kind,\n packageName: r.package_name,\n })),\n ),\n ),\n ).catch(fail),\n );\n list\n .command('services')\n .option('--workspace <path>')\n .option('--repo <name>')\n .action(\n (opts: { workspace?: string; repo?: string }) =>\n void withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const selection = opts.repo\n ? selectRepository(db, opts.repo, workspaceId)\n : {};\n if (selection.diagnostic) {\n writeStdout(renderJson([selection.diagnostic]));\n return;\n }\n const repo = selection.repo;\n const rows = db\n .prepare(\n 'SELECT r.name repo,s.service_path servicePath,s.qualified_name qualifiedName FROM cds_services s JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND (? IS NULL OR s.repo_id=?) ORDER BY r.name,s.service_path',\n )\n .all(workspaceId, repo?.id, repo?.id);\n writeStdout(renderJson(rows));\n }).catch(fail),\n );\n list\n .command('operations')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--service <path>')\n .action(\n (opts: { workspace?: string; repo?: string; service?: string }) =>\n void withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const selection = opts.repo\n ? selectRepository(db, opts.repo, workspaceId)\n : {};\n if (selection.diagnostic) {\n writeStdout(renderJson([selection.diagnostic]));\n return;\n }\n const repo = selection.repo;\n const rows = db\n .prepare(\n 'SELECT r.name repo,s.service_path servicePath,o.operation_name operation,o.operation_path path FROM cds_operations o JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND (? IS NULL OR s.repo_id=?) AND (? IS NULL OR s.service_path=?)',\n )\n .all(workspaceId, repo?.id, repo?.id, opts.service, opts.service);\n writeStdout(renderJson(rows));\n }).catch(fail),\n );\n list\n .command('calls')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--operation <name>')\n .action(\n (opts: { workspace?: string; repo?: string; operation?: string }) =>\n void withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const selection = opts.repo\n ? selectRepository(db, opts.repo, workspaceId)\n : {};\n if (selection.diagnostic) {\n writeStdout(renderJson([selection.diagnostic]));\n return;\n }\n const repo = selection.repo;\n const rows = db\n .prepare(\n 'SELECT r.name repo,c.call_type type,c.operation_path_expr path,c.source_file file,c.source_line line FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id WHERE r.workspace_id=? AND (? IS NULL OR c.repo_id=?) AND (? IS NULL OR c.operation_path_expr=? OR c.operation_path_expr=? OR c.payload_summary LIKE ?)',\n )\n .all(\n workspaceId,\n repo?.id,\n repo?.id,\n opts.operation,\n opts.operation,\n opts.operation ? `/${opts.operation}` : undefined,\n opts.operation ? `%${opts.operation}%` : undefined,\n );\n writeStdout(renderJson(rows));\n }).catch(fail),\n );\n program\n .command('graph')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--operation <name>')\n .option('--service <path>')\n .option('--path <operationPath>')\n .addOption(graphFormatOption())\n .option('--implementation-repo <name>')\n .option('--implementation-hint <scope>', 'scoped implementation hint', collect, [])\n .option('--var <key=value>', 'dynamic variable', collect, [])\n .option('--dynamic-mode <mode>', 'strict|candidates|infer', 'strict')\n .option('--max-dynamic-candidates <n>', 'maximum dynamic candidates to show', '5')\n .action((opts: GraphCommandOptions) => void runGraphCommand(opts).catch(fail));\n const inspect = program.command('inspect');\n inspect\n .command('repo')\n .argument('<name>')\n .option('--workspace <path>')\n .action(\n (name: string, opts: { workspace?: string }) =>\n void withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const selection = selectRepository(db, name, workspaceId);\n writeStdout(renderJson(\n selection.repo ?? selection.diagnostic ?? { error: 'repo not found' },\n ));\n }).catch(fail),\n );\n inspect\n .command('operation')\n .argument('<selector>')\n .option('--workspace <path>')\n .action(\n (selector: string, opts: { workspace?: string }) =>\n void withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const rows = db\n .prepare(\n 'SELECT o.* FROM cds_operations o JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND (o.operation_name=? OR o.operation_path=?)',\n )\n .all(workspaceId, selector, selector);\n writeStdout(renderJson(rows));\n }).catch(fail),\n );\n program\n .command('doctor')\n .option('--workspace <path>')\n .option('--strict')\n .option('--detail')\n .option('--format <format>', 'json|table')\n .action(\n (opts: { workspace?: string; strict?: boolean; detail?: boolean; format?: string }) =>\n void withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const allDiagnostics = doctorDiagnostics(db, Boolean(opts.strict), {\n detail: Boolean(opts.detail), workspaceId,\n });\n writeStdout(renderDoctorDiagnostics(allDiagnostics, opts.format));\n }).catch(fail),\n );\n program\n .command('clean')\n .option('--workspace <path>')\n .option('--db-only')\n .action(\n (opts: { workspace?: string; dbOnly?: boolean }) =>\n void (async () => {\n const config = await loadWorkspaceConfig(opts.workspace);\n await cleanWorkspaceState(config, Boolean(opts.dbOnly));\n writeStdout('Cleaned service-flow state\\n');\n })().catch(fail),\n );\n return program;\n}\nfunction collect(value: string, previous: string[]): string[] {\n previous.push(value);\n return previous;\n}\nfunction parseDynamicMode(value: string | undefined): DynamicMode {\n if (value === undefined || value === 'strict') return 'strict';\n if (value === 'candidates' || value === 'infer') return value;\n throw new Error(`Invalid --dynamic-mode ${value}; expected strict, candidates, or infer`);\n}\nfunction parsePositiveInteger(value: string | undefined, fallback: number): number {\n const parsed = Number(value);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;\n}\nfunction fail(error: unknown): void {\n process.stderr.write(\n `${error instanceof Error ? error.message : String(error)}\\n`,\n );\n process.exitCode = 1;\n}\ncreateProgram().parse(process.argv);\n","export const DEFAULT_IGNORES = [\n 'node_modules',\n 'gen',\n 'dist',\n 'coverage',\n '.git',\n '.turbo',\n '.next',\n '.cache',\n '.service-flow'\n] as const;\nexport const CONFIG_DIR = '.service-flow';\nexport const CONFIG_FILE = 'config.json';\nexport const DEFAULT_DB_FILE = 'service-flow.db';\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport {\n CONFIG_DIR,\n CONFIG_FILE,\n DEFAULT_DB_FILE,\n DEFAULT_IGNORES,\n} from './defaults.js';\nconst schema = z.object({\n rootPath: z.string(),\n dbPath: z.string(),\n ignore: z.array(z.string()),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type WorkspaceConfig = z.infer<typeof schema>;\nexport function configPath(rootPath: string): string {\n return path.join(rootPath, CONFIG_DIR, CONFIG_FILE);\n}\nexport function defaultDbPath(rootPath: string): string {\n return path.join(rootPath, CONFIG_DIR, DEFAULT_DB_FILE);\n}\nexport async function saveWorkspaceConfig(\n config: WorkspaceConfig,\n): Promise<void> {\n await fs.mkdir(path.dirname(configPath(config.rootPath)), {\n recursive: true,\n });\n await fs.writeFile(\n configPath(config.rootPath),\n `${JSON.stringify(config, null, 2)}\\n`,\n );\n if (path.dirname(config.dbPath) === path.dirname(configPath(config.rootPath)))\n await fs.writeFile(\n path.join(path.dirname(config.dbPath), '.service-flow-state'),\n 'service-flow\\n',\n );\n}\nexport async function loadWorkspaceConfig(\n workspace?: string,\n): Promise<WorkspaceConfig> {\n const root = path.resolve(workspace ?? process.cwd());\n const data = await fs.readFile(configPath(root), 'utf8');\n return schema.parse(JSON.parse(data) as unknown);\n}\nexport function createWorkspaceConfig(\n rootPath: string,\n dbPath?: string,\n ignore: string[] = [...DEFAULT_IGNORES],\n): WorkspaceConfig {\n const now = new Date().toISOString();\n const root = path.resolve(rootPath);\n return {\n rootPath: root,\n dbPath: path.resolve(dbPath ?? defaultDbPath(root)),\n ignore,\n createdAt: now,\n updatedAt: now,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { migrate } from './migrations.js';\nimport { VERSION } from '../version.js';\n\ntype SqlValue = string | number | bigint | Buffer | null | undefined;\ninterface NativeStatement {\n run: (...params: SqlValue[]) => { changes: number };\n get: (...params: SqlValue[]) => Record<string, unknown> | undefined;\n all: (...params: SqlValue[]) => Array<Record<string, unknown>>;\n}\ninterface NativeDatabase {\n exec: (sql: string) => void;\n prepare: (sql: string) => NativeStatement;\n close: () => void;\n}\ninterface NodeSqliteModule {\n DatabaseSync: new (location: string, options?: { open?: boolean; readOnly?: boolean }) => NativeDatabase;\n}\n\nlet sqliteWarningFilterInstalled = false;\nfunction installSqliteWarningFilter(): void {\n if (sqliteWarningFilterInstalled) return;\n sqliteWarningFilterInstalled = true;\n const original = process.emitWarning.bind(process);\n process.emitWarning = ((warning: string | Error, ...args: unknown[]): void => {\n const text = warning instanceof Error ? warning.message : String(warning);\n if (text.includes('SQLite is an experimental feature')) return;\n Reflect.apply(original, process, [warning, ...args]);\n }) as typeof process.emitWarning;\n}\nexport interface Statement {\n run: (...params: unknown[]) => { changes: number };\n get: (...params: unknown[]) => Record<string, unknown> | undefined;\n all: (...params: unknown[]) => Array<Record<string, unknown>>;\n}\nexport interface Db {\n path: string;\n readonly: boolean;\n exec: (sql: string) => void;\n prepare: (sql: string) => Statement;\n pragma: (sql: string) => Array<Record<string, unknown>>;\n transaction: <T>(fn: () => T) => T;\n close: () => void;\n}\nexport interface OpenDatabaseOptions {\n readonly?: boolean;\n migrate?: boolean;\n}\nfunction loadSqlite(): NodeSqliteModule {\n try {\n installSqliteWarningFilter();\n const moduleValue = process.getBuiltinModule('node:sqlite') as unknown;\n if (!moduleValue || typeof moduleValue !== 'object' || !('DatabaseSync' in moduleValue))\n throw new Error('node:sqlite DatabaseSync is unavailable');\n const sqlite = moduleValue as NodeSqliteModule;\n if (typeof sqlite.DatabaseSync !== 'function')\n throw new Error('node:sqlite DatabaseSync is not a constructor');\n return sqlite;\n } catch (error) {\n throw new Error(\n `service-flow ${VERSION} requires Node.js >=24 with node:sqlite DatabaseSync support. Upgrade Node.js or install a service-flow build with a compatible SQLite driver.`,\n { cause: error },\n );\n }\n}\nfunction bindParams(params: unknown[]): SqlValue[] {\n return params.map((param) => {\n if (param === undefined || param === null) return null;\n if (typeof param === 'string' || typeof param === 'number' || typeof param === 'bigint' || Buffer.isBuffer(param)) return param;\n if (typeof param === 'boolean') return param ? 1 : 0;\n return JSON.stringify(param);\n });\n}\nexport function openDatabase(dbPath: string, options: OpenDatabaseOptions = {}): Db {\n fs.mkdirSync(path.dirname(dbPath), { recursive: true });\n const sqlite = loadSqlite();\n const native = new sqlite.DatabaseSync(dbPath, { readOnly: Boolean(options.readonly) });\n let inTransaction = false;\n const db: Db = {\n path: dbPath,\n readonly: Boolean(options.readonly),\n exec(sql: string): void {\n native.exec(sql);\n },\n prepare(sql: string): Statement {\n const statement = native.prepare(sql);\n return {\n run: (...params: unknown[]) => statement.run(...bindParams(params)),\n get: (...params: unknown[]) => statement.get(...bindParams(params)),\n all: (...params: unknown[]) => statement.all(...bindParams(params)),\n };\n },\n pragma(sql: string): Array<Record<string, unknown>> {\n const normalized = sql.trim().replace(/;$/, '');\n if (/=/.test(normalized)) {\n native.exec(`PRAGMA ${normalized}`);\n return [];\n }\n return native.prepare(`PRAGMA ${normalized}`).all();\n },\n transaction<T>(fn: () => T): T {\n if (inTransaction) return fn();\n native.exec('BEGIN IMMEDIATE');\n inTransaction = true;\n try {\n const result = fn();\n native.exec('COMMIT');\n return result;\n } catch (error) {\n native.exec('ROLLBACK');\n throw error;\n } finally {\n inTransaction = false;\n }\n },\n close(): void {\n native.close();\n },\n };\n db.pragma('busy_timeout = 10000');\n db.pragma('foreign_keys = ON');\n if (!options.readonly) {\n db.pragma('journal_mode = WAL');\n if (options.migrate !== false) migrate(db);\n }\n return db;\n}\nexport function openReadOnlyDatabase(dbPath: string): Db {\n return openDatabase(dbPath, { readonly: true, migrate: false });\n}\n","import type { Db } from './connection.js';\nimport type {\n CdsRequire,\n CdsServiceFact,\n HandlerClassFact,\n HandlerMethodFact,\n HandlerRegistrationFact,\n ServiceBindingFact,\n ExecutableSymbolFact,\n} from '../types.js';\nimport {\n selectCallOwner,\n type OwnerCandidate,\n} from '../parsers/004-fact-identity.js';\nexport interface RepoRow {\n id: number;\n name: string;\n absolute_path: string;\n relative_path: string;\n package_name: string | null;\n package_version: string | null;\n dependencies_json: string;\n kind: string;\n fingerprint?: string | null;\n fact_generation?: number;\n graph_generation?: number;\n graph_stale_reason?: string | null;\n fact_analyzer_version?: string | null;\n}\nexport interface WorkspaceRow {\n id: number;\n root_path: string;\n db_path: string;\n}\nfunction initialPackagePublicSurface(packageName?: string): string {\n return JSON.stringify({\n schema: 'service-flow/package-public-surface@1',\n status: packageName ? 'incomplete' : 'not_applicable',\n reason: packageName ? 'package_surface_pending_index' : null,\n recordCap: 256,\n total: 0,\n shown: 0,\n omitted: 0,\n packageName: packageName ?? null,\n exportsPresent: false,\n exportsAuthoritative: false,\n main: null,\n module: null,\n entries: [],\n scopes: [],\n });\n}\nexport function upsertWorkspace(\n db: Db,\n rootPath: string,\n dbPath: string,\n): number {\n const now = new Date().toISOString();\n db.prepare(\n 'INSERT INTO workspaces(root_path,db_path,created_at,updated_at) VALUES(?,?,?,?) ON CONFLICT(root_path) DO UPDATE SET db_path=excluded.db_path,updated_at=excluded.updated_at',\n ).run(rootPath, dbPath, now, now);\n return Number(\n db.prepare('SELECT id FROM workspaces WHERE root_path=?').get(rootPath)?.id,\n );\n}\nexport function getWorkspace(\n db: Db,\n rootPath: string,\n): WorkspaceRow | undefined {\n return db\n .prepare('SELECT * FROM workspaces WHERE root_path=?')\n .get(rootPath) as WorkspaceRow | undefined;\n}\nexport function upsertRepository(\n db: Db,\n workspaceId: number,\n r: {\n name: string;\n absolutePath: string;\n relativePath: string;\n isGitRepo: boolean;\n packageName?: string;\n packageVersion?: string;\n dependencies?: Record<string, string>;\n kind?: string;\n },\n): number {\n db.prepare(\n `INSERT INTO repositories(workspace_id,name,absolute_path,relative_path,\n package_name,package_version,dependencies_json,\n package_public_surface_json,kind,is_git_repo)\n VALUES(?,?,?,?,?,?,?,?,?,?)\n ON CONFLICT(workspace_id,absolute_path) DO UPDATE SET\n name=excluded.name,relative_path=excluded.relative_path,\n package_name=excluded.package_name,\n package_version=excluded.package_version,\n dependencies_json=excluded.dependencies_json,kind=excluded.kind`,\n ).run(\n workspaceId,\n r.name,\n r.absolutePath,\n r.relativePath,\n r.packageName,\n r.packageVersion,\n JSON.stringify(r.dependencies ?? {}),\n initialPackagePublicSurface(r.packageName),\n r.kind ?? 'unknown',\n r.isGitRepo ? 1 : 0,\n );\n return Number(\n db\n .prepare(\n 'SELECT id FROM repositories WHERE workspace_id=? AND absolute_path=?',\n )\n .get(workspaceId, r.absolutePath)?.id,\n );\n}\nexport function listRepositories(db: Db, workspaceId?: number): RepoRow[] {\n return db\n .prepare('SELECT * FROM repositories WHERE (? IS NULL OR workspace_id=?) ORDER BY name,absolute_path,id')\n .all(workspaceId, workspaceId) as unknown as RepoRow[];\n}\nexport function repoByName(\n db: Db,\n name: string,\n workspaceId?: number,\n): RepoRow | undefined {\n const matches = reposByName(db, name, workspaceId);\n return matches.length === 1 ? matches[0] : undefined;\n}\nexport function reposByName(\n db: Db,\n name: string,\n workspaceId?: number,\n): RepoRow[] {\n return db\n .prepare(`SELECT * FROM repositories\n WHERE (? IS NULL OR workspace_id=?) AND (name=? OR package_name=?)\n ORDER BY name,absolute_path,id`)\n .all(workspaceId, workspaceId, name, name) as unknown as RepoRow[];\n}\nexport function clearRepoFacts(db: Db, repoId: number): void {\n for (const t of [\n 'cds_requires',\n 'cds_services',\n 'handler_classes',\n 'outbound_calls',\n 'symbol_calls',\n 'handler_registrations',\n 'service_bindings',\n 'symbols',\n 'diagnostics',\n 'files',\n ])\n db.prepare(`DELETE FROM ${t} WHERE repo_id=?`).run(repoId);\n db.prepare('DELETE FROM search_index WHERE repo=?').run(String(repoId));\n}\nexport function insertRequires(\n db: Db,\n repoId: number,\n rows: CdsRequire[],\n): void {\n const stmt = db.prepare(\n 'INSERT INTO cds_requires(repo_id,alias,kind,model,destination,service_path,request_timeout,raw_json) VALUES(?,?,?,?,?,?,?,?)',\n );\n for (const r of rows)\n stmt.run(\n repoId,\n r.alias,\n r.kind,\n r.model,\n r.destination,\n r.servicePath,\n r.requestTimeout,\n r.rawJson,\n );\n}\nexport function insertService(\n db: Db,\n repoId: number,\n s: CdsServiceFact,\n): number {\n const id = Number(\n db\n .prepare(\n 'INSERT INTO cds_services(repo_id,namespace,service_name,qualified_name,service_path,is_extend,source_file,source_line,extension_local_ref,extension_imported_symbol,extension_local_alias,extension_module_specifier,extension_import_kind) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) RETURNING id',\n )\n .get(\n repoId,\n s.namespace,\n s.serviceName,\n s.qualifiedName,\n s.servicePath,\n s.isExtend ? 1 : 0,\n s.sourceFile,\n s.sourceLine,\n s.extension?.localReference,\n s.extension?.importedSymbol,\n s.extension?.localAlias,\n s.extension?.moduleSpecifier,\n s.extension?.importKind,\n )?.id,\n );\n const stmt = db.prepare(\n 'INSERT INTO cds_operations(service_id,operation_type,operation_name,operation_path,params_json,return_type,source_file,source_line,provenance,base_operation_id) VALUES(?,?,?,?,?,?,?,?,?,?)',\n );\n db.prepare(\n 'INSERT INTO search_index(kind,name,path,repo) VALUES(?,?,?,?)',\n ).run('service', s.qualifiedName, s.servicePath, String(repoId));\n for (const o of s.operations)\n stmt.run(\n id,\n o.operationType,\n o.operationName,\n o.operationPath,\n o.paramsJson,\n o.returnType,\n o.sourceFile,\n o.sourceLine,\n o.provenance ?? 'direct',\n o.baseOperationId ?? null,\n );\n const search = db.prepare(\n 'INSERT INTO search_index(kind,name,path,repo) VALUES(?,?,?,?)',\n );\n for (const o of s.operations)\n search.run('operation', o.operationName, o.operationPath, String(repoId));\n return id;\n}\nexport function insertHandler(\n db: Db,\n repoId: number,\n h: HandlerClassFact,\n): number {\n const sid = insertHandlerClassSymbol(db, repoId, h);\n const hid = Number(\n db\n .prepare(\n 'INSERT INTO handler_classes(repo_id,symbol_id,class_name,source_file,source_line) VALUES(?,?,?,?,?) RETURNING id',\n )\n .get(repoId, sid, h.className, h.sourceFile, h.sourceLine)?.id,\n );\n const stmt = db.prepare(\n 'INSERT INTO handler_methods(handler_class_id,method_name,decorator_kind,decorator_value,decorator_raw_expression,decorator_resolution_json,source_file,source_line) VALUES(?,?,?,?,?,?,?,?)',\n );\n for (const m of h.methods)\n stmt.run(\n hid,\n m.methodName,\n m.decoratorKind,\n m.decoratorValue,\n m.decoratorRawExpression,\n JSON.stringify(canonicalHandlerMethodResolution(m)),\n m.sourceFile,\n m.sourceLine,\n );\n insertHandlerIndexDiagnostic(db, repoId, h);\n return hid;\n}\nfunction insertHandlerClassSymbol(\n db: Db,\n repoId: number,\n h: HandlerClassFact,\n): number {\n const classEvidence = {\n hasHandlerDecorator: h.hasHandlerDecorator ?? false,\n classDecoratorNames: h.classDecoratorNames ?? [],\n observedDecoratorNames: h.observedDecoratorNames ?? [],\n unsupportedDecoratorNames: h.unsupportedDecoratorNames ?? [],\n unsupportedMethods: h.methods\n .filter((method) => !handlerMethodIsExecutable(method))\n .map((method) => ({\n methodName: method.methodName,\n decoratorKind: method.decoratorKind,\n sourceFile: method.sourceFile,\n sourceLine: method.sourceLine,\n reason: method.decoratorResolution.unresolvedReason,\n })),\n };\n return Number(\n db\n .prepare(\n 'INSERT INTO symbols(repo_id,kind,name,qualified_name,exported,start_line,end_line,source_file,evidence_json) VALUES(?,?,?,?,?,?,?,?,?) RETURNING id',\n )\n .get(\n repoId,\n 'class',\n h.className,\n h.className,\n 1,\n h.sourceLine,\n h.sourceLine,\n h.sourceFile,\n JSON.stringify(classEvidence),\n )?.id,\n );\n}\nfunction insertHandlerIndexDiagnostic(\n db: Db,\n repoId: number,\n h: HandlerClassFact,\n): void {\n if (!h.hasHandlerDecorator) return;\n const hasExecutable = h.methods.some(handlerMethodIsExecutable);\n const unsupported = h.methods.filter((method) =>\n !handlerMethodIsExecutable(method));\n if (hasExecutable && unsupported.length === 0) return;\n const code = hasExecutable\n ? 'handler_decorators_not_indexed'\n : 'handler_methods_not_indexed';\n const names = unsupported.map((method) => method.decoratorKind).sort();\n const detail = names.length > 0\n ? ` Unsupported decorators: ${[...new Set(names)].join(', ')}.`\n : '';\n db.prepare(\n 'INSERT INTO diagnostics(repo_id,severity,code,message,source_file,source_line) VALUES(?,?,?,?,?,?)',\n ).run(\n repoId,\n 'warning',\n code,\n hasExecutable\n ? `Handler class ${h.className} contains methods that were not indexed.${detail}`\n : `Handler class ${h.className} has no indexed executable methods; use a supported CAP handler decorator and re-index.${detail}`,\n h.sourceFile,\n h.sourceLine,\n );\n}\nexport function canonicalHandlerMethodResolution(\n method: HandlerMethodFact,\n): HandlerMethodFact['decoratorResolution'] {\n const handlerKind = method.handlerKind\n ?? method.decoratorResolution.handlerKind\n ?? legacyHandlerKind(method.decoratorKind);\n const executable = method.executable\n ?? method.decoratorResolution.executable\n ?? (handlerKind === 'operation' || handlerKind === 'event'\n || handlerKind === 'entity_lifecycle');\n return {\n ...method.decoratorResolution,\n handlerKind,\n executable,\n lifecyclePhase: method.lifecyclePhase\n ?? method.decoratorResolution.lifecyclePhase,\n lifecycleEvent: method.lifecycleEvent\n ?? method.decoratorResolution.lifecycleEvent,\n };\n}\nexport function handlerMethodIsExecutable(method: HandlerMethodFact): boolean {\n return canonicalHandlerMethodResolution(method).executable === true;\n}\nfunction legacyHandlerKind(kind: string): HandlerMethodFact['handlerKind'] {\n if (kind === 'Event') return 'event';\n if (['Action', 'Func', 'On'].includes(kind)) return 'operation';\n return 'unsupported_decorator';\n}\nexport function insertRegistrations(\n db: Db,\n repoId: number,\n rows: HandlerRegistrationFact[],\n): void {\n const stmt = db.prepare(\n 'INSERT INTO handler_registrations(repo_id,handler_class_id,class_name,import_source,registration_file,registration_line,registration_kind,confidence) VALUES(?,?,?,?,?,?,?,?)',\n );\n for (const r of rows) {\n const handlerClass = r.className\n ? (db\n .prepare(\n 'SELECT id FROM handler_classes WHERE repo_id=? AND class_name=? ORDER BY id',\n )\n .all(repoId, r.className) as Array<{ id: number }>)\n : [];\n stmt.run(\n repoId,\n handlerClass.length === 1 ? handlerClass[0]?.id : null,\n r.className,\n r.importSource,\n r.registrationFile,\n r.registrationLine,\n r.registrationKind,\n r.confidence,\n );\n }\n}\nexport function insertBindings(\n db: Db,\n repoId: number,\n rows: ServiceBindingFact[],\n): void {\n assertUniquePreparedBindingSites(rows);\n const stmt = db.prepare(\n 'INSERT INTO service_bindings(repo_id,symbol_id,variable_name,alias,alias_expr,destination_expr,service_path_expr,is_dynamic,placeholders_json,source_file,source_line,binding_site_start_offset,binding_site_end_offset,owner_resolution,helper_chain_json) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\n );\n for (const r of rows)\n stmt.run(\n repoId,\n bindingOwnerId(db, repoId, r),\n r.variableName,\n r.alias,\n r.aliasExpr,\n r.destinationExpr,\n r.servicePathExpr,\n r.isDynamic ? 1 : 0,\n JSON.stringify(r.placeholders),\n r.sourceFile,\n r.sourceLine,\n r.bindingSiteStartOffset,\n r.bindingSiteEndOffset,\n r.ownerResolution,\n r.helperChain ? JSON.stringify(r.helperChain) : null,\n );\n}\n\ninterface PersistedOwnerCandidate extends OwnerCandidate {\n id: number;\n}\n\nfunction persistedOwnerCandidates(\n db: Db,\n repoId: number,\n fact: ServiceBindingFact,\n): PersistedOwnerCandidate[] {\n const rows = db.prepare(`SELECT id,kind,qualified_name qualifiedName,\n start_offset startOffset,end_offset endOffset FROM symbols\n WHERE repo_id=? AND source_file=? AND start_offset<=? AND end_offset>=?`)\n .all(\n repoId, fact.sourceFile, fact.bindingSiteStartOffset,\n fact.bindingSiteEndOffset,\n );\n return rows.flatMap((row) =>\n typeof row.id === 'number' && typeof row.kind === 'string'\n && typeof row.qualifiedName === 'string'\n && typeof row.startOffset === 'number'\n && typeof row.endOffset === 'number'\n ? [{\n id: row.id,\n kind: row.kind,\n qualifiedName: row.qualifiedName,\n startOffset: row.startOffset,\n endOffset: row.endOffset,\n }]\n : []);\n}\n\nfunction bindingOwnerId(\n db: Db,\n repoId: number,\n fact: ServiceBindingFact,\n): number | null {\n const candidates = persistedOwnerCandidates(db, repoId, fact);\n const selected = selectCallOwner(\n candidates,\n fact.bindingSiteStartOffset ?? -1,\n fact.bindingSiteEndOffset ?? -1,\n );\n if (fact.ownerResolution === 'ownerless_file_scope') {\n if (selected.status !== 'none')\n throw new Error('invalid_prepared_repository_snapshot:binding_owner_mismatch');\n return null;\n }\n if (fact.ownerResolution !== 'owned_exact'\n || selected.status !== 'resolved'\n || selected.owner?.qualifiedName !== fact.sourceSymbolQualifiedName)\n throw new Error('invalid_prepared_repository_snapshot:binding_owner_mismatch');\n const owner = selected.owner;\n if (!owner)\n throw new Error('invalid_prepared_repository_snapshot:binding_owner_mismatch');\n return owner.id;\n}\n\nfunction assertUniquePreparedBindingSites(\n rows: readonly ServiceBindingFact[],\n): void {\n const seen = new Set<string>();\n for (const row of rows) {\n if (row.bindingSiteStartOffset === undefined\n || row.bindingSiteEndOffset === undefined)\n throw new Error('invalid_prepared_repository_snapshot:binding_site_missing');\n const key = [\n row.sourceFile, row.variableName,\n row.bindingSiteStartOffset, row.bindingSiteEndOffset,\n ].join('\\u0000');\n if (seen.has(key))\n throw new Error('invalid_prepared_repository_snapshot:duplicate_service_binding_site');\n seen.add(key);\n }\n}\nexport function insertExecutableSymbols(db: Db, repoId: number, rows: ExecutableSymbolFact[]): void {\n const stmt = db.prepare('INSERT INTO symbols(repo_id,file_id,kind,name,qualified_name,exported,start_line,end_line,start_offset,end_offset,source_file,exported_name,evidence_json) VALUES(?,(SELECT id FROM files WHERE repo_id=? AND relative_path=?),?,?,?,?,?,?,?,?,?,?,?)');\n for (const r of rows) stmt.run(repoId, repoId, r.sourceFile, r.kind, r.localName, r.qualifiedName, r.exported ? 1 : 0, r.startLine, r.endLine, r.startOffset, r.endOffset, r.sourceFile, r.exportedName, r.importExportEvidence ? JSON.stringify(r.importExportEvidence) : null);\n}\nexport { insertCalls, insertSymbolCalls } from './000-call-fact-repository.js';\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { PackageFacts, RepoKind } from '../types.js';\nexport async function classifyRepository(\n repoPath: string,\n facts: PackageFacts\n): Promise<RepoKind> {\n const hasCdsDep = Boolean(\n facts.dependencies['@sap/cds'] ??\n facts.dependencies.cds ??\n facts.dependencies['cds-routing-handlers']\n );\n const cdsFiles = await findFiles(repoPath, '.cds');\n const serverFiles = await Promise.all(\n ['srv/server.ts', 'srv/server.js', 'src/server.ts', 'src/server.js'].map(\n async (f) =>\n fs\n .access(path.join(repoPath, f))\n .then(() => true)\n .catch(() => false)\n )\n );\n const helper =\n Object.keys(facts.dependencies).includes('cds-routing-handlers') ||\n facts.packageName?.includes('helper') === true;\n if (helper && cdsFiles.length > 0) return 'mixed';\n if (helper) return 'helper-package';\n if (hasCdsDep && (cdsFiles.length > 0 || serverFiles.some(Boolean)))\n return 'cap-service';\n if (cdsFiles.length > 0)\n return serverFiles.some(Boolean) ? 'cap-service' : 'cap-db-model';\n return 'unknown';\n}\n\nasync function findFiles(root: string, suffix: string): Promise<string[]> {\n const out: string[] = [];\n async function walk(dir: string): Promise<void> {\n const entries = await fs\n .readdir(dir, { withFileTypes: true })\n .catch(() => []);\n for (const e of entries) {\n if (e.isDirectory()) {\n if (!['node_modules', 'dist', 'gen', '.git'].includes(e.name))\n await walk(path.join(dir, e.name));\n } else if (e.name.endsWith(suffix)) out.push(path.join(dir, e.name));\n }\n }\n await walk(root);\n return out;\n}\n","export interface DiagnosticInput {\n severity: 'info' | 'warning' | 'error';\n code: string;\n message: string;\n sourceFile?: string;\n sourceLine?: number;\n}\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { Db } from '../db/connection.js';\nimport {\n clearRepoFacts,\n insertBindings,\n insertCalls,\n insertExecutableSymbols,\n insertHandler,\n handlerMethodIsExecutable,\n insertRegistrations,\n insertSymbolCalls,\n insertRequires,\n insertService,\n type RepoRow,\n} from '../db/repositories.js';\nimport { classifyRepository } from '../discovery/classify-repository.js';\nimport { parseCdsFile } from '../parsers/cds-parser.js';\nimport { parseDecorators } from '../parsers/decorator-parser.js';\nimport { parseHandlerRegistrations } from '../parsers/handler-registration-parser.js';\nimport {\n classifyOutboundCallsInSource,\n parseOutboundCalls,\n} from '../parsers/outbound-call-parser.js';\nimport { parseExecutableSymbols } from '../parsers/symbol-parser.js';\nimport {\n loadPackageJsonSnapshot,\n} from '../parsers/package-json-parser.js';\nimport { parseServiceBindings } from '../parsers/service-binding-parser.js';\nimport { reconcileSourceFacts } from '../parsers/007-source-fact-reconciliation.js';\nimport {\n analyzeRepositoryPackageSurface,\n mergePackageSymbolEvidence,\n} from '../parsers/008-package-surface-publication.js';\nimport type {\n PackagePublicSurfaceFact,\n} from '../parsers/003-package-public-surface.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport { errorMessage } from '../utils/diagnostics.js';\nimport { sha256Text } from '../utils/hashing.js';\nimport { ANALYZER_VERSION } from '../version.js';\nimport {\n createPackageInvalidationBatch,\n finalizePackageTargetInvalidations,\n invalidatePackageTargetFacts,\n type PackageInvalidationBatch,\n} from '../db/004-package-target-invalidation.js';\nimport {\n loadRepositorySourceContext,\n type RepositorySourceContext,\n type SourceContextInstrumentation,\n} from '../parsers/ts-project.js';\nimport type { CdsServiceFact, HandlerClassFact, HandlerRegistrationFact, OutboundCallFact, PackageFacts, ServiceBindingFact, ExecutableSymbolFact, SymbolCallFact } from '../types.js';\nexport interface IndexRepoResult {\n fileCount: number;\n diagnosticCount: number;\n skipped: boolean;\n}\ninterface ParsedFacts {\n services: CdsServiceFact[];\n handlers: HandlerClassFact[];\n registrations: HandlerRegistrationFact[];\n bindings: ServiceBindingFact[];\n calls: OutboundCallFact[];\n symbols: ExecutableSymbolFact[];\n symbolCalls: SymbolCallFact[];\n fileRecords: Array<{ relativePath: string; extension: string; sha256: string; sizeBytes: number }>;\n}\nexport interface PreparedRepositoryIndex extends IndexRepoResult {\n repo: RepoRow;\n packageFacts?: PackageFacts;\n fingerprint?: string;\n kind?: string;\n parsed?: ParsedFacts;\n packagePublicSurface?: PackagePublicSurfaceFact;\n}\nexport async function indexRepository(\n db: Db,\n repo: RepoRow,\n force: boolean,\n instrumentation?: SourceContextInstrumentation,\n): Promise<IndexRepoResult> {\n try {\n const prepared = await prepareRepositoryIndex(repo, force, instrumentation);\n if (!prepared.skipped) db.transaction(() => {\n const batch = createPackageInvalidationBatch([prepared.repo.id]);\n publishPreparedRepositoryIndex(db, prepared, batch);\n finalizePackageTargetInvalidations(db, batch);\n });\n return { fileCount: prepared.fileCount, diagnosticCount: prepared.diagnosticCount, skipped: prepared.skipped };\n } catch (error) {\n recordIndexFailure(db, repo.id, error);\n return { fileCount: 0, diagnosticCount: 1, skipped: false };\n }\n}\nexport async function prepareRepositoryIndex(\n repo: RepoRow,\n force: boolean,\n instrumentation?: SourceContextInstrumentation,\n): Promise<PreparedRepositoryIndex> {\n const sourceFiles = await findSourceFiles(repo.absolute_path);\n const packageSnapshot = await loadPackageJsonSnapshot(repo.absolute_path, {\n strict: true,\n allowMissing: repo.package_name === null,\n });\n const packageFacts = packageSnapshot.facts;\n const sources = await loadRepositorySourceContext(\n repo.absolute_path, sourceFiles, instrumentation,\n );\n const fingerprint = repositoryFingerprint(\n sources, packageFacts, packageSnapshot.rawText,\n );\n if (!force && repo.fingerprint === fingerprint) return { repo, fileCount: 0, diagnosticCount: 0, skipped: true };\n const parsedFacts = await parseAllSourceFacts(repo.absolute_path, sources);\n const packageSurface = analyzeRepositoryPackageSurface(\n packageFacts, packageSnapshot.manifest, sources,\n );\n const parsed = {\n ...parsedFacts,\n symbols: mergePackageSymbolEvidence(parsedFacts.symbols, packageSurface),\n };\n return {\n repo,\n packageFacts,\n fingerprint,\n kind: await classifyRepository(repo.absolute_path, packageFacts),\n parsed,\n packagePublicSurface: packageSurface.surface,\n fileCount: sourceFiles.length,\n diagnosticCount: parsed.handlers.filter((handler) =>\n handler.hasHandlerDecorator\n && (handler.methods.length === 0\n || handler.methods.some((method) => !handlerMethodIsExecutable(method)))).length,\n skipped: false,\n };\n}\nexport function publishPreparedRepositoryIndex(\n db: Db,\n prepared: PreparedRepositoryIndex,\n invalidations: PackageInvalidationBatch,\n): void {\n if (prepared.skipped) return;\n if (!prepared.packageFacts || !prepared.parsed || !prepared.fingerprint\n || !prepared.kind || !prepared.packagePublicSurface)\n throw new Error('Prepared repository index is missing publication facts');\n const now = new Date().toISOString();\n const repoId = prepared.repo.id;\n invalidatePackageTargetFacts(\n db, repoId, prepared.packageFacts.packageName, invalidations,\n );\n db.prepare(`UPDATE repositories SET package_name=?, package_version=?,\n dependencies_json=?,package_public_surface_json=?,kind=?,index_status=?\n WHERE id=?`).run(\n prepared.packageFacts.packageName,\n prepared.packageFacts.packageVersion,\n JSON.stringify(prepared.packageFacts.dependencies),\n JSON.stringify(prepared.packagePublicSurface),\n prepared.kind,\n 'indexing',\n repoId,\n );\n clearRepoFacts(db, repoId);\n insertRequires(db, repoId, prepared.packageFacts.cdsRequires);\n const fileStmt = db.prepare('INSERT INTO files(repo_id,relative_path,extension,sha256,size_bytes,last_indexed_at) VALUES(?,?,?,?,?,?) ON CONFLICT(repo_id,relative_path) DO UPDATE SET sha256=excluded.sha256,size_bytes=excluded.size_bytes,last_indexed_at=excluded.last_indexed_at');\n for (const file of prepared.parsed.fileRecords) fileStmt.run(repoId, file.relativePath, file.extension, file.sha256, file.sizeBytes, now);\n for (const service of prepared.parsed.services) insertService(db, repoId, service);\n for (const handler of prepared.parsed.handlers) insertHandler(db, repoId, handler);\n insertExecutableSymbols(db, repoId, prepared.parsed.symbols);\n insertSymbolCalls(db, repoId, prepared.parsed.symbolCalls);\n insertRegistrations(db, repoId, prepared.parsed.registrations);\n insertBindings(db, repoId, prepared.parsed.bindings);\n insertCalls(db, repoId, prepared.parsed.calls);\n db.prepare(\"UPDATE repositories SET last_indexed_at=?, index_status='indexed', error_count=0, fingerprint=?, fact_generation=COALESCE(fact_generation,0)+1, graph_stale_reason='facts_changed', graph_stale_at=?, fact_analyzer_version=? WHERE id=?\").run(now, prepared.fingerprint, now, ANALYZER_VERSION, repoId);\n}\nexport function recordIndexFailure(db: Db, repoId: number, error: unknown): void {\n const message = errorMessage(error);\n db.prepare(\"UPDATE repositories SET index_status='failed', error_count=1 WHERE id=?\").run(repoId);\n db.prepare(\"DELETE FROM diagnostics WHERE repo_id=? AND code IN ('index_failed_snapshot_preserved','source_read_failed')\").run(repoId);\n db.prepare('INSERT INTO diagnostics(repo_id,severity,code,message) VALUES(?,?,?,?)').run(repoId, 'error', 'source_read_failed', `Index failed before publication; previous facts and fingerprint were preserved. ${message}`);\n}\nasync function parseAllSourceFacts(\n root: string,\n sources: RepositorySourceContext,\n): Promise<ParsedFacts> {\n const facts: ParsedFacts = { services: [], handlers: [], registrations: [], bindings: [], calls: [], symbols: [], symbolCalls: [], fileRecords: [] };\n for (const snapshot of sources.entries()) {\n const file = snapshot.filePath;\n facts.fileRecords.push({ relativePath: normalizePath(file), extension: path.extname(file), sha256: sha256Text(snapshot.text), sizeBytes: snapshot.sizeBytes });\n if (file.endsWith('.cds')) facts.services.push(...(await parseCdsFile(root, file, sources)));\n if (/\\.[jt]s$/.test(file)) {\n const source = snapshot.sourceFile();\n const classified = classifyOutboundCallsInSource(source, file);\n facts.handlers.push(...(await parseDecorators(root, file, sources)));\n facts.registrations.push(...(await parseHandlerRegistrations(root, file, sources)));\n const bindings = await parseServiceBindings(root, file, sources);\n const symbolFacts = await parseExecutableSymbols(\n root, file, sources, classified,\n );\n const outboundCalls = await parseOutboundCalls(\n root, file, sources, classified, bindings,\n );\n const reconciled = reconcileSourceFacts(\n source, classified, bindings, outboundCalls,\n symbolFacts.symbols, symbolFacts.calls,\n );\n facts.bindings.push(...reconciled.bindings);\n facts.symbols.push(...reconciled.symbols);\n facts.symbolCalls.push(...reconciled.symbolCalls);\n facts.calls.push(...reconciled.outboundCalls);\n }\n }\n return facts;\n}\nasync function findSourceFiles(root: string): Promise<string[]> {\n const out: string[] = [];\n async function walk(dir: string, prefix = ''): Promise<void> {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n const rel = prefix ? `${prefix}/${e.name}` : e.name;\n if (e.isDirectory()) {\n if (!['node_modules', 'dist', 'gen', 'coverage', '.git'].includes(e.name)) await walk(path.join(dir, e.name), rel);\n } else if (/\\.(cds|ts|js)$/.test(e.name) && !isDefaultTestFile(rel)) out.push(rel);\n }\n }\n await walk(root);\n return out.sort();\n}\nfunction isDefaultTestFile(relativeFile: string): boolean {\n const parts = relativeFile.split('/');\n if (parts.some((part) => ['test', 'tests', '__tests__'].includes(part))) return true;\n return /\\.(test|spec)\\.[jt]s$/.test(parts.at(-1) ?? '');\n}\nfunction repositoryFingerprint(\n sources: RepositorySourceContext,\n facts: PackageFacts,\n packageJsonText: string,\n): string {\n const normalizedFacts = {\n analyzerVersion: ANALYZER_VERSION,\n packageName: facts.packageName,\n packageVersion: facts.packageVersion,\n dependencies: Object.fromEntries(Object.entries(facts.dependencies).sort()),\n cdsRequires: [...facts.cdsRequires].sort((a, b) => a.alias.localeCompare(b.alias)),\n scripts: Object.fromEntries(Object.entries(facts.scripts).sort()),\n includeTests: false,\n packageJsonHash: sha256Text(packageJsonText),\n };\n const entries: string[] = [`facts:${JSON.stringify(normalizedFacts)}`];\n for (const snapshot of sources.entries())\n entries.push(`${snapshot.filePath}:${sha256Text(snapshot.text)}`);\n return sha256Text(entries.join('\\n'));\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport ts from 'typescript';\nimport type { ExecutableSymbolFact, SymbolCallFact } from '../types.js';\nimport {\n classifyOutboundCallsInSource,\n containsSupportedOutboundCall,\n type ClassifiedOutboundCall,\n} from './outbound-call-parser.js';\nimport type { RepositorySourceContext } from './ts-project.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport { reconcileEventSubscriptions } from './005-event-subscription-facts.js';\nimport { reconcileSymbolCallOwners } from './007-source-fact-reconciliation.js';\nimport {\n collectSymbolImportBindings,\n type SymbolImportBinding,\n} from './002-symbol-import-bindings.js';\nimport {\n collectSymbolCallFacts,\n symbolCallName,\n type SymbolCallProxy,\n type SymbolClassInstance,\n} from './009-symbol-call-facts.js';\nimport {\n executableBodyEligibility,\n} from './013-executable-body-eligibility.js';\nimport {\n collectDerivedSymbolContexts,\n} from './017-symbol-derived-contexts.js';\n\nfunction lineOf(source: ts.SourceFile, pos: number): number {\n return source.getLineAndCharacterOfPosition(pos).line + 1;\n}\nfunction nameOf(node: ts.PropertyName | ts.BindingName | undefined): string | undefined {\n if (!node) return undefined;\n if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return node.text;\n return undefined;\n}\nfunction isFunctionLike(node: ts.Node): node is ts.FunctionLikeDeclaration {\n return ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node);\n}\nfunction exported(node: ts.Node): boolean {\n return Boolean(ts.getCombinedModifierFlags(node as ts.Declaration) & ts.ModifierFlags.Export);\n}\nfunction isPublicClassMethod(node: ts.MethodDeclaration): boolean {\n const flags = ts.getCombinedModifierFlags(node);\n return (flags & ts.ModifierFlags.Private) === 0 && (flags & ts.ModifierFlags.Protected) === 0;\n}\nfunction exportDeclarations(source: ts.SourceFile): Map<string, string> {\n const exports = new Map<string, string>();\n const visit = (node: ts.Node): void => {\n if (ts.isExportDeclaration(node) && node.exportClause && ts.isNamedExports(node.exportClause)) {\n for (const el of node.exportClause.elements) exports.set((el.propertyName ?? el.name).text, el.name.text);\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return exports;\n}\nfunction isObjectFunction(\n node: ts.Node,\n): node is ts.FunctionExpression | ts.ArrowFunction | ts.MethodDeclaration {\n return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node);\n}\ntype ParameterBinding =\n | { index: number; kind: 'identifier'; name: string }\n | { index: number; kind: 'object_pattern'; properties: Array<{ property: string; local: string }> }\n | { index: number; kind: 'array_pattern'; elements: Array<{ index: number; local: string }> };\ntype ParameterPropertyAlias = { parameter: string; property: string; local: string; kind: 'object_parameter_destructure'; line: number };\nfunction requireSource(expr: ts.Expression): string | undefined {\n if (!ts.isCallExpression(expr) || !ts.isIdentifier(expr.expression) || expr.expression.text !== 'require') return undefined;\n const first = expr.arguments[0];\n return first && ts.isStringLiteral(first) ? first.text : undefined;\n}\nfunction bindingLocalName(name: ts.BindingName, initializer?: ts.Expression): string | undefined {\n if (ts.isIdentifier(name)) return name.text;\n if (initializer && ts.isIdentifier(initializer)) return initializer.text;\n return undefined;\n}\n\nfunction objectPatternAliases(pattern: ts.ObjectBindingPattern, parameter: string, source: ts.SourceFile, lineNode: ts.Node): ParameterPropertyAlias[] {\n return pattern.elements.flatMap((element): ParameterPropertyAlias[] => {\n if (element.dotDotDotToken || ts.isObjectBindingPattern(element.name) || ts.isArrayBindingPattern(element.name)) return [];\n const property = element.propertyName ? nameOf(element.propertyName) : nameOf(element.name);\n if (!property) return [];\n const local = bindingLocalName(element.name, element.initializer);\n return local ? [{ parameter, property, local, kind: 'object_parameter_destructure', line: lineOf(source, lineNode.getStart(source)) }] : [];\n });\n}\nfunction parameterPropertyAliases(fn: ts.FunctionLikeDeclaration, source: ts.SourceFile): ParameterPropertyAlias[] {\n const parameterNames = new Set(fn.parameters.flatMap((param) => ts.isIdentifier(param.name) ? [param.name.text] : []));\n if (!fn.body || parameterNames.size === 0) return [];\n const aliases: ParameterPropertyAlias[] = [];\n const addFromAssignment = (left: ts.Expression, right: ts.Expression, node: ts.Node): void => {\n if (!ts.isObjectLiteralExpression(left) || !ts.isIdentifier(right) || !parameterNames.has(right.text)) return;\n for (const prop of left.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const property = nameOf(prop.name);\n if (property && ts.isIdentifier(prop.initializer)) aliases.push({ parameter: right.text, property, local: prop.initializer.text, kind: 'object_parameter_destructure', line: lineOf(source, node.getStart(source)) });\n }\n };\n const visit = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer && ts.isIdentifier(node.initializer) && parameterNames.has(node.initializer.text)) aliases.push(...objectPatternAliases(node.name, node.initializer.text, source, node));\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) addFromAssignment(ts.isParenthesizedExpression(node.left) ? node.left.expression : node.left, node.right, node);\n ts.forEachChild(node, visit);\n };\n visit(fn.body);\n const seen = new Set<string>();\n return aliases.filter((alias) => { const key = `${alias.parameter}.${alias.property}:${alias.local}`; if (seen.has(key)) return false; seen.add(key); return true; });\n}\nfunction parameterBindings(params: ts.NodeArray<ts.ParameterDeclaration>): ParameterBinding[] {\n return params.flatMap((param, index): ParameterBinding[] => {\n if (ts.isIdentifier(param.name)) return [{ index, kind: 'identifier', name: param.name.text }];\n if (ts.isObjectBindingPattern(param.name)) {\n const properties = param.name.elements.flatMap((element): Array<{ property: string; local: string }> => {\n if (element.dotDotDotToken || ts.isObjectBindingPattern(element.name) || ts.isArrayBindingPattern(element.name)) return [];\n const property = element.propertyName ? nameOf(element.propertyName) : nameOf(element.name);\n if (!property) return [];\n const local = bindingLocalName(element.name, element.initializer);\n return local ? [{ property, local }] : [];\n });\n return properties.length > 0 ? [{ index, kind: 'object_pattern', properties }] : [];\n }\n if (ts.isArrayBindingPattern(param.name)) {\n const elements = param.name.elements.flatMap((element, elementIndex): Array<{ index: number; local: string }> =>\n ts.isBindingElement(element) && !element.dotDotDotToken && ts.isIdentifier(element.name)\n ? [{ index: elementIndex, local: element.name.text }]\n : []);\n return elements.length > 0 ? [{ index, kind: 'array_pattern', elements }] : [];\n }\n return [];\n });\n}\ninterface SymbolCollection {\n source: ts.SourceFile;\n sourceFile: string;\n symbols: ExecutableSymbolFact[];\n imports: Map<string, string>;\n importBindings: SymbolImportBinding[];\n classifiedCalls: readonly ClassifiedOutboundCall[];\n exportNames: Map<string, string>;\n objectExports: Set<string>;\n exportedClasses: Set<string>;\n declaredClasses: Set<string>;\n proxies: Map<string, SymbolCallProxy[]>;\n instances: Map<string, SymbolClassInstance[]>;\n}\n\nfunction symbolSourceEvidence(\n collection: SymbolCollection,\n node: ts.Node,\n options: {\n parentRoot: string;\n qualifiedName: string;\n declaredExportName?: string;\n classContainerExported: boolean; classMemberExported: boolean;\n objectExported: boolean;\n evidence?: Record<string, unknown>;\n },\n): Record<string, unknown> {\n if (options.evidence) return options.evidence;\n if (options.classMemberExported) return {\n source: 'exported_class_member',\n exportedClass: options.parentRoot,\n memberKind: ts.getCombinedModifierFlags(node as ts.Declaration)\n & ts.ModifierFlags.Static ? 'static_method' : 'class_method',\n };\n if (options.classContainerExported && ts.isMethodDeclaration(node)\n && isPublicClassMethod(node)) return {\n source: 'exported_class_instance_member', exportedClass: options.parentRoot,\n memberKind: 'class_method',\n };\n if (options.declaredExportName) return {\n exportedName: options.declaredExportName,\n source: 'export_declaration',\n };\n return options.objectExported\n ? { exportedName: options.qualifiedName, source: 'exported_object_literal' }\n : {};\n}\n\nfunction executableEvidence(\n node: ts.Node,\n source: ts.SourceFile,\n): Record<string, unknown> {\n if (!isFunctionLike(node)) return {};\n const bindings = parameterBindings(node.parameters);\n const parameters = bindings.flatMap((binding) =>\n binding.kind === 'identifier' ? [binding.name] : []);\n const aliases = parameterPropertyAliases(node, source);\n return {\n executableBodyEligibility: executableBodyEligibility(node, source),\n ...(bindings.length > 0 ? { parameters, parameterBindings: bindings } : {}),\n ...(aliases.length > 0 ? { parameterPropertyAliases: aliases } : {}),\n };\n}\n\ninterface SymbolNames {\n parentRoot: string;\n qualifiedName: string;\n declaredExportName?: string;\n objectExported: boolean;\n classContainerExported: boolean;\n classMemberExported: boolean;\n effectiveName?: string;\n}\n\nfunction exportedClassMember(\n collection: SymbolCollection,\n kind: string,\n parentName: string | undefined,\n parentRoot: string,\n node: ts.Node,\n): boolean {\n if (kind !== 'method' || !parentName\n || !collection.exportedClasses.has(parentRoot)\n || !ts.isMethodDeclaration(node)) return false;\n return Boolean(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Static)\n && isPublicClassMethod(node);\n}\n\nfunction symbolNames(\n collection: SymbolCollection,\n kind: string,\n localName: string,\n node: ts.Node,\n parentName?: string,\n exportedName?: string,\n): SymbolNames {\n const parentRoot = parentName?.split('.')[0] ?? '';\n const declaredExportName = exportedName ?? collection.exportNames.get(\n parentName ? parentRoot : localName,\n );\n const qualifiedName = parentName ? `${parentName}.${localName}` : localName;\n const objectExported = Boolean(\n parentName && collection.objectExports.has(parentRoot),\n );\n const classMemberExported = exportedClassMember(\n collection, kind, parentName, parentRoot, node,\n );\n const classContainerExported = Boolean(\n parentName && collection.exportedClasses.has(parentRoot),\n );\n return {\n parentRoot, declaredExportName, qualifiedName,\n objectExported, classContainerExported, classMemberExported,\n effectiveName: classMemberExported || objectExported\n ? qualifiedName : declaredExportName,\n };\n}\n\nfunction addExecutableSymbol(\n collection: SymbolCollection,\n kind: string,\n localName: string,\n node: ts.Node,\n parentName?: string,\n exportedName?: string,\n evidence?: Record<string, unknown>,\n): void {\n const names = symbolNames(\n collection, kind, localName, node, parentName, exportedName,\n );\n const sourceEvidence = symbolSourceEvidence(collection, node, {\n parentRoot: names.parentRoot,\n qualifiedName: names.qualifiedName,\n declaredExportName: names.declaredExportName,\n classContainerExported: names.classContainerExported,\n classMemberExported: names.classMemberExported,\n objectExported: names.objectExported,\n evidence,\n });\n collection.symbols.push({\n kind,\n localName: kind === 'object_method' ? names.qualifiedName : localName,\n exportedName: names.effectiveName,\n qualifiedName: names.qualifiedName,\n sourceFile: collection.sourceFile,\n startLine: lineOf(collection.source, node.getStart(collection.source)),\n endLine: lineOf(collection.source, node.getEnd()),\n startOffset: node.getStart(collection.source),\n endOffset: node.getEnd(),\n exported: exported(node) || Boolean(names.effectiveName),\n importExportEvidence: {\n ...sourceEvidence,\n ...executableEvidence(node, collection.source),\n },\n });\n}\n\nfunction addAliasSymbol(\n collection: SymbolCollection,\n objectName: string,\n propertyName: string,\n node: ts.Node,\n): void {\n collection.symbols.push({\n kind: 'object_alias',\n localName: propertyName,\n exportedName: propertyName,\n qualifiedName: `${objectName}.${propertyName}`,\n sourceFile: collection.sourceFile,\n startLine: lineOf(collection.source, node.getStart(collection.source)),\n endLine: lineOf(collection.source, node.getEnd()),\n startOffset: node.getStart(collection.source),\n endOffset: node.getEnd(),\n exported: true,\n importExportEvidence: {\n source: 'exported_object_shorthand',\n objectName,\n propertyName,\n targetImportSource: collection.imports.get(propertyName),\n },\n });\n}\n\nfunction collectImportSources(collection: SymbolCollection): void {\n const visit = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier))\n collectEsmImportSources(collection.imports, node);\n if (ts.isVariableStatement(node))\n collectCjsImportSources(collection.imports, node);\n ts.forEachChild(node, visit);\n };\n visit(collection.source);\n}\n\nfunction collectEsmImportSources(\n imports: Map<string, string>,\n node: ts.ImportDeclaration,\n): void {\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const source = node.moduleSpecifier.text;\n const clause = node.importClause;\n if (clause?.name) imports.set(clause.name.text, source);\n const named = clause?.namedBindings;\n if (named && ts.isNamedImports(named))\n for (const item of named.elements) imports.set(item.name.text, source);\n if (named && ts.isNamespaceImport(named))\n imports.set(named.name.text, source);\n}\n\nfunction collectCjsImportSources(\n imports: Map<string, string>,\n node: ts.VariableStatement,\n): void {\n for (const declaration of node.declarationList.declarations) {\n const source = declaration.initializer\n ? requireSource(declaration.initializer) : undefined;\n if (!source) continue;\n if (ts.isIdentifier(declaration.name))\n imports.set(declaration.name.text, source);\n if (ts.isObjectBindingPattern(declaration.name))\n for (const item of declaration.name.elements)\n if (ts.isIdentifier(item.name)) imports.set(item.name.text, source);\n }\n}\n\nfunction classPropertySymbol(\n collection: SymbolCollection,\n node: ts.PropertyDeclaration,\n parentClass: string,\n): void {\n const initializer = node.initializer;\n const localName = nameOf(node.name);\n if (!localName || !initializer\n || (!ts.isArrowFunction(initializer)\n && !ts.isFunctionExpression(initializer))) return;\n const staticPublic = publicStaticProperty(collection, node, parentClass);\n const memberKind = propertyMemberKind(initializer, staticPublic);\n addExecutableSymbol(\n collection, 'method', localName, initializer, parentClass,\n staticPublic ? `${parentClass}.${localName}` : undefined,\n staticPublic\n ? { source: 'exported_class_member', exportedClass: parentClass, memberKind }\n : { source: 'class_property_function', memberKind },\n );\n}\n\nfunction publicStaticProperty(\n collection: SymbolCollection,\n node: ts.PropertyDeclaration,\n parentClass: string,\n): boolean {\n const flags = ts.getCombinedModifierFlags(node);\n return collection.exportedClasses.has(parentClass)\n && Boolean(flags & ts.ModifierFlags.Static)\n && (flags & ts.ModifierFlags.Private) === 0\n && (flags & ts.ModifierFlags.Protected) === 0;\n}\n\nfunction propertyMemberKind(\n initializer: ts.ArrowFunction | ts.FunctionExpression,\n staticPublic: boolean,\n): string {\n if (ts.isArrowFunction(initializer))\n return staticPublic ? 'static_arrow_function' : 'arrow_function_property';\n return staticPublic\n ? 'static_function_expression'\n : 'function_expression_property';\n}\n\nfunction objectCallable(\n property: ts.ObjectLiteralElementLike,\n): ts.FunctionLikeDeclaration | undefined {\n if (ts.isMethodDeclaration(property)) return property;\n return ts.isPropertyAssignment(property)\n && isObjectFunction(property.initializer)\n ? property.initializer\n : undefined;\n}\n\nfunction objectLiteralSymbols(\n collection: SymbolCollection,\n objectName: string,\n object: ts.ObjectLiteralExpression,\n objectIsExported: boolean,\n): void {\n if (objectIsExported) collection.objectExports.add(objectName);\n for (const property of object.properties) {\n if (objectIsExported && ts.isShorthandPropertyAssignment(property))\n addAliasSymbol(collection, objectName, property.name.text, property.name);\n const callable = objectCallable(property);\n const propertyName = callable ? nameOf(property.name) : undefined;\n if (callable && propertyName)\n addExecutableSymbol(\n collection, 'object_method', propertyName, callable, objectName,\n );\n }\n}\n\nfunction variableSymbols(\n collection: SymbolCollection,\n node: ts.VariableStatement,\n): void {\n for (const declaration of node.declarationList.declarations) {\n const localName = nameOf(declaration.name);\n const initializer = declaration.initializer;\n if (!localName || !initializer) continue;\n if (isFunctionLike(initializer)) addExecutableSymbol(\n collection, 'function', localName, initializer, undefined,\n exported(node) ? localName : collection.exportNames.get(localName),\n );\n if (ts.isObjectLiteralExpression(initializer))\n objectLiteralSymbols(\n collection, localName, initializer,\n exported(node) || collection.exportNames.has(localName),\n );\n }\n}\n\nfunction collectClassDeclaration(\n collection: SymbolCollection,\n node: ts.Node,\n): boolean {\n if (!ts.isClassDeclaration(node) || !node.name) return false;\n collection.declaredClasses.add(node.name.text);\n if (exported(node) || collection.exportNames.has(node.name.text))\n collection.exportedClasses.add(node.name.text);\n for (const member of node.members)\n visitDeclaredSymbol(collection, member, node.name.text);\n return true;\n}\n\nfunction collectMethodDeclaration(\n collection: SymbolCollection,\n node: ts.Node,\n parentClass?: string,\n): boolean {\n if (!ts.isMethodDeclaration(node)) return false;\n const localName = nameOf(node.name);\n if (localName)\n addExecutableSymbol(collection, 'method', localName, node, parentClass);\n return true;\n}\n\nfunction visitDeclaredSymbol(\n collection: SymbolCollection,\n node: ts.Node,\n parentClass?: string,\n): void {\n if (collectClassDeclaration(collection, node)) return;\n if (collectMethodDeclaration(collection, node, parentClass)) return;\n if (ts.isPropertyDeclaration(node)) {\n if (parentClass) classPropertySymbol(collection, node, parentClass);\n return;\n }\n if (ts.isFunctionDeclaration(node) && node.name) {\n addExecutableSymbol(\n collection, 'function', node.name.text, node, undefined,\n exported(node) ? node.name.text : undefined,\n );\n return;\n }\n if (ts.isVariableStatement(node)) {\n variableSymbols(collection, node);\n return;\n }\n ts.forEachChild(node, (child) =>\n visitDeclaredSymbol(collection, child, parentClass));\n}\n\nfunction collectDeclaredSymbols(collection: SymbolCollection): void {\n visitDeclaredSymbol(collection, collection.source);\n}\n\nfunction isTopLevelCallback(\n node: ts.Node,\n): node is ts.ArrowFunction | ts.FunctionExpression {\n if ((!ts.isArrowFunction(node) && !ts.isFunctionExpression(node))\n || !ts.isCallExpression(node.parent)) return false;\n const callee = symbolCallName(node.parent.expression);\n const member = callee.member ?? callee.local;\n return Boolean(member && [\n 'bootstrap', 'served', 'connect', 'on', 'once', 'use',\n 'get', 'post', 'put', 'patch', 'delete', 'subscribe',\n ].includes(member));\n}\n\nfunction collectCallbackSymbols(collection: SymbolCollection): void {\n const visit = (node: ts.Node): void => {\n if (isTopLevelCallback(node)\n && containsSupportedOutboundCall(node, collection.classifiedCalls)) {\n const startLine = lineOf(\n collection.source, node.getStart(collection.source),\n );\n const name = `callback:${startLine}`;\n collection.symbols.push({\n kind: 'callback', localName: name,\n qualifiedName: `module:${collection.sourceFile}#${name}`,\n sourceFile: collection.sourceFile, startLine,\n endLine: lineOf(collection.source, node.getEnd()),\n startOffset: node.getStart(collection.source), endOffset: node.getEnd(),\n exported: false,\n importExportEvidence: {\n source: 'synthetic_outbound_callback', callbackLine: startLine,\n },\n });\n }\n ts.forEachChild(node, visit);\n };\n visit(collection.source);\n}\n\nfunction createCollection(\n source: ts.SourceFile,\n sourceFile: string,\n classifiedCalls: readonly ClassifiedOutboundCall[],\n): SymbolCollection {\n return {\n source, sourceFile, classifiedCalls,\n symbols: [], imports: new Map(),\n importBindings: collectSymbolImportBindings(source),\n exportNames: exportDeclarations(source),\n objectExports: new Set(), exportedClasses: new Set(),\n declaredClasses: new Set(), proxies: new Map(), instances: new Map(),\n };\n}\n\nfunction populateCollection(collection: SymbolCollection): void {\n collectImportSources(collection);\n collectDeclaredSymbols(collection);\n collectCallbackSymbols(collection);\n collectDerivedSymbolContexts(collection);\n}\n\nasync function sourceFile(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n): Promise<ts.SourceFile> {\n const snapshot = context?.get(filePath);\n const text = snapshot?.text\n ?? await fs.readFile(path.join(repoPath, filePath), 'utf8');\n return snapshot?.sourceFile() ?? ts.createSourceFile(\n filePath, text, ts.ScriptTarget.Latest, true,\n filePath.endsWith('.ts') ? ts.ScriptKind.TS : ts.ScriptKind.JS,\n );\n}\n\nexport async function parseExecutableSymbols(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n preparedOutboundCalls?: readonly ClassifiedOutboundCall[],\n): Promise<{ symbols: ExecutableSymbolFact[]; calls: SymbolCallFact[] }> {\n const source = await sourceFile(repoPath, filePath, context);\n const normalizedFile = normalizePath(filePath);\n const classified = preparedOutboundCalls\n ?? classifyOutboundCallsInSource(source, normalizedFile);\n const collection = createCollection(source, normalizedFile, classified);\n populateCollection(collection);\n const calls = collectSymbolCallFacts({\n source, sourceFile: normalizedFile,\n symbols: collection.symbols, imports: collection.imports,\n importBindings: collection.importBindings,\n proxies: collection.proxies, instances: collection.instances,\n });\n const events = reconcileEventSubscriptions(\n source, classified, collection.symbols, calls,\n );\n return {\n symbols: events.symbols,\n calls: reconcileSymbolCallOwners(events.calls, events.symbols),\n };\n}\n","import ts from 'typescript';\nimport type {\n ExecutableSymbolFact,\n HandlerReferenceStatus,\n SymbolCallFact,\n} from '../types.js';\nimport {\n collectSymbolImportBindings,\n symbolImportReference,\n type SymbolImportBinding,\n type SymbolImportReference,\n} from './002-symbol-import-bindings.js';\nimport type { ClassifiedOutboundCall } from './outbound-call-parser.js';\nimport {\n localSymbolTarget,\n type LocalSymbolTargetIdentity,\n} from './016-local-symbol-reference.js';\n\ninterface HandlerTarget {\n calleeExpression: string;\n calleeLocalName: string;\n importSource?: string;\n relation: string;\n referenceShape: string;\n wrapperFunction?: string;\n importBinding?: SymbolImportReference;\n localTargetIdentity?: LocalSymbolTargetIdentity;\n}\n\ninterface HandlerClassification {\n status: HandlerReferenceStatus;\n reason?: string;\n referenceShape: string;\n target?: HandlerTarget;\n}\n\nfunction lineOf(source: ts.SourceFile, node: ts.Node): number {\n return source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;\n}\n\nfunction lineAt(source: ts.SourceFile, position: number): number {\n return source.getLineAndCharacterOfPosition(position).line + 1;\n}\n\nfunction importRelation(binding: SymbolImportReference): string {\n if (binding.moduleKind === 'package') return 'package_import';\n return binding.referenceShape === 'namespace_member'\n ? 'relative_import_namespace_member'\n : 'relative_import';\n}\n\nfunction directTarget(\n expression: ts.Expression,\n source: ts.SourceFile,\n imports: readonly SymbolImportBinding[],\n symbols: readonly ExecutableSymbolFact[],\n): HandlerTarget | undefined {\n const imported = symbolImportReference(expression, imports);\n if (imported) return importedTarget(expression, source, imported);\n if (ts.isIdentifier(expression)) {\n const exact = localSymbolTarget(expression, source, symbols);\n return {\n calleeExpression: expression.text,\n calleeLocalName: expression.text,\n relation: exact\n ? 'indexed_local_symbol'\n : 'indexed_local_symbol_unproven',\n referenceShape: 'identifier',\n localTargetIdentity: exact,\n };\n }\n return propertyTarget(expression, source, symbols);\n}\n\nfunction importedTarget(\n expression: ts.Expression,\n source: ts.SourceFile,\n binding: SymbolImportReference,\n): HandlerTarget {\n return {\n calleeExpression: expression.getText(source),\n calleeLocalName: binding.requestedPublicName,\n importSource: binding.rawModuleSpecifier,\n relation: importRelation(binding),\n referenceShape: binding.referenceShape,\n importBinding: binding,\n };\n}\n\nfunction propertyTarget(\n expression: ts.Expression,\n source: ts.SourceFile,\n symbols: readonly ExecutableSymbolFact[],\n): HandlerTarget | undefined {\n if (!ts.isPropertyAccessExpression(expression) || expression.questionDotToken\n || !ts.isIdentifier(expression.expression)) return undefined;\n const exact = localSymbolTarget(expression, source, symbols);\n return {\n calleeExpression: expression.getText(source),\n calleeLocalName: `${expression.expression.text}.${expression.name.text}`,\n relation: exact\n ? 'indexed_local_symbol'\n : 'indexed_local_symbol_unproven',\n referenceShape: 'static_member',\n localTargetIdentity: exact,\n };\n}\n\nfunction unsupportedClassification(\n status: Exclude<HandlerReferenceStatus, 'role_required'>,\n reason: string,\n referenceShape: string,\n): HandlerClassification {\n return { status, reason, referenceShape };\n}\n\nexport function classifyHandlerReference(\n expression: ts.Expression | undefined,\n source: ts.SourceFile,\n imports = collectSymbolImportBindings(source),\n symbols: readonly ExecutableSymbolFact[] = [],\n): HandlerClassification {\n if (!expression)\n return unsupportedClassification(\n 'missing_argument', 'handler_argument_missing', 'missing',\n );\n if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression))\n return unsupportedClassification(\n 'unsupported_inline', 'inline_handler_body_not_indexed', 'inline_callback',\n );\n const direct = directTarget(expression, source, imports, symbols);\n if (direct)\n return { status: 'role_required', referenceShape: direct.referenceShape, target: direct };\n if (!ts.isCallExpression(expression))\n return unsupportedClassification(\n 'unsupported_reference_shape', 'handler_reference_shape_unsupported',\n 'unsupported_expression',\n );\n return classifyWrapperReference(expression, source, imports, symbols);\n}\n\nfunction classifyWrapperReference(\n expression: ts.CallExpression,\n source: ts.SourceFile,\n imports: readonly SymbolImportBinding[],\n symbols: readonly ExecutableSymbolFact[],\n): HandlerClassification {\n if (expression.questionDotToken || expression.arguments.length !== 1)\n return unsupportedClassification(\n 'unsupported_wrapper', 'wrapper_requires_one_reference', 'wrapper_call',\n );\n const inner = expression.arguments[0];\n const target = inner\n ? directTarget(inner, source, imports, symbols)\n : undefined;\n if (!target)\n return unsupportedClassification(\n 'unsupported_wrapper', 'wrapper_reference_shape_unsupported', 'wrapper_call',\n );\n return {\n status: 'role_required',\n referenceShape: `wrapped_${target.referenceShape}`,\n target: { ...target, wrapperFunction: expression.expression.getText(source) },\n };\n}\n\nfunction eventSymbol(\n source: ts.SourceFile,\n classified: ClassifiedOutboundCall,\n): ExecutableSymbolFact {\n const node = classified.node;\n const eventName = classified.fact.eventNameExpr ?? '';\n const line = lineOf(source, node);\n const safeName = eventName.replace(/[^A-Za-z0-9_$-]/g, '_');\n const name = `event:${safeName}:${line}`;\n const receiver = classified.fact.evidence?.receiver;\n return {\n kind: 'event_registration',\n localName: name,\n qualifiedName: `module:${classified.fact.sourceFile}#${name}`,\n sourceFile: classified.fact.sourceFile,\n startLine: line,\n endLine: lineAt(source, node.getEnd() - 1),\n startOffset: node.getStart(source),\n endOffset: node.getEnd(),\n exported: false,\n importExportEvidence: {\n source: 'synthetic_event_registration',\n eventName,\n registrationLine: line,\n receiver: typeof receiver === 'string' ? receiver : undefined,\n },\n };\n}\n\nfunction eventCall(\n classified: ClassifiedOutboundCall,\n owner: ExecutableSymbolFact,\n classification: HandlerClassification,\n): SymbolCallFact | undefined {\n const target = classification.target;\n if (!target) return undefined;\n return {\n callerQualifiedName: owner.qualifiedName,\n calleeExpression: target.calleeExpression,\n calleeLocalName: target.calleeLocalName,\n importSource: target.importSource,\n sourceFile: classified.fact.sourceFile,\n sourceLine: classified.fact.sourceLine,\n callSiteStartOffset: classified.fact.callSiteStartOffset,\n callSiteEndOffset: classified.fact.callSiteEndOffset,\n callRole: 'event_subscribe_handler',\n evidence: {\n relation: target.relation,\n caller: owner.qualifiedName,\n targetName: target.calleeLocalName,\n referenceShape: classification.referenceShape,\n ...(target.importBinding ? { importBinding: target.importBinding } : {}),\n ...(target.localTargetIdentity\n ? { localTargetIdentity: target.localTargetIdentity }\n : {}),\n ...(target.wrapperFunction ? { wrapperFunction: target.wrapperFunction } : {}),\n factOrigin: 'event_subscribe_handler_reference',\n },\n };\n}\n\nfunction enrichSubscription(\n source: ts.SourceFile,\n classified: ClassifiedOutboundCall,\n symbols: readonly ExecutableSymbolFact[],\n): { classified: ClassifiedOutboundCall; classification: HandlerClassification } {\n const classification = classifyHandlerReference(\n classified.node.arguments[1], source, undefined, symbols,\n );\n const evidence = {\n ...(classified.fact.evidence ?? {}),\n handlerReferenceStatus: classification.status,\n ...(classification.reason\n ? { handlerReferenceReason: classification.reason }\n : {}),\n handlerReferenceShape: classification.referenceShape,\n };\n return {\n classified: { ...classified, fact: { ...classified.fact, evidence } },\n classification,\n };\n}\n\nexport function reconcileEventSubscriptions(\n source: ts.SourceFile,\n classifications: readonly ClassifiedOutboundCall[],\n symbols: readonly ExecutableSymbolFact[],\n calls: readonly SymbolCallFact[],\n): {\n classifications: ClassifiedOutboundCall[];\n symbols: ExecutableSymbolFact[];\n calls: SymbolCallFact[];\n} {\n const subscriptions = classifications.filter(\n (item) => item.fact.callType === 'async_subscribe',\n ).map((item) => enrichSubscription(source, item, symbols));\n const eventSymbols = subscriptions.map((item) => eventSymbol(source, item.classified));\n const eventCalls = subscriptions.flatMap((item, index) => {\n const owner = eventSymbols[index];\n const call = owner\n ? eventCall(item.classified, owner, item.classification)\n : undefined;\n return call ? [call] : [];\n });\n return {\n classifications: classifications.map((item) =>\n subscriptions.find((candidate) => candidate.classified.node === item.node)\n ?.classified ?? item),\n symbols: [...symbols.filter((item) => item.kind !== 'event_registration'), ...eventSymbols],\n calls: [\n ...calls.filter((item) => item.callRole !== 'event_subscribe_handler'),\n ...eventCalls,\n ],\n };\n}\n","import ts from 'typescript';\nimport type { ExecutableSymbolFact } from '../types.js';\nimport {\n lexicalIdentifierDeclaration,\n lexicalIdentifierDeclarations,\n} from './002-symbol-import-bindings.js';\nimport { stableLocalValueReference } from './020-stable-local-value.js';\n\nexport interface LocalSymbolTargetIdentity {\n sourceFile: string;\n qualifiedName: string;\n startOffset: number;\n endOffset: number;\n}\n\nfunction functionTargetNode(\n declaration: ts.Identifier,\n): ts.Node | undefined {\n const parent = declaration.parent;\n if (ts.isFunctionDeclaration(parent)) return parent;\n if (!ts.isVariableDeclaration(parent)) return undefined;\n const initializer = parent.initializer;\n return initializer\n && (ts.isArrowFunction(initializer)\n || ts.isFunctionExpression(initializer))\n ? initializer\n : undefined;\n}\n\nfunction declarationKey(identifier: ts.Identifier): string {\n return `${identifier.getStart(identifier.getSourceFile())}:${identifier.getEnd()}`;\n}\n\nfunction unwrapAssignmentTarget(expression: ts.Expression): ts.Expression {\n if (ts.isParenthesizedExpression(expression)\n || ts.isAsExpression(expression)\n || ts.isSatisfiesExpression(expression)\n || ts.isTypeAssertionExpression(expression)\n || ts.isNonNullExpression(expression))\n return unwrapAssignmentTarget(expression.expression);\n return expression;\n}\n\nfunction objectAssignmentTargets(\n expression: ts.ObjectLiteralExpression,\n): ts.Identifier[] {\n return expression.properties.flatMap((property) => {\n if (ts.isShorthandPropertyAssignment(property)) return [property.name];\n if (ts.isPropertyAssignment(property))\n return assignmentTargets(property.initializer);\n return ts.isSpreadAssignment(property)\n ? assignmentTargets(property.expression) : [];\n });\n}\n\nfunction assignmentTargets(expression: ts.Expression): ts.Identifier[] {\n const target = unwrapAssignmentTarget(expression);\n if (ts.isIdentifier(target)) return [target];\n if (ts.isSpreadElement(target))\n return assignmentTargets(target.expression);\n if (ts.isBinaryExpression(target)\n && target.operatorToken.kind === ts.SyntaxKind.EqualsToken)\n return assignmentTargets(target.left);\n if (ts.isArrayLiteralExpression(target))\n return target.elements.flatMap((item) =>\n ts.isExpression(item) ? assignmentTargets(item) : []);\n return ts.isObjectLiteralExpression(target)\n ? objectAssignmentTargets(target) : [];\n}\n\nfunction assignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment\n && kind <= ts.SyntaxKind.LastAssignment;\n}\n\nfunction mutationUnary(\n node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression,\n): boolean {\n return node.operator === ts.SyntaxKind.PlusPlusToken\n || node.operator === ts.SyntaxKind.MinusMinusToken;\n}\n\ntype DeclarationMatcher = (identifier: ts.Identifier) => boolean;\n\nfunction binaryWritesDeclaration(\n node: ts.Node,\n matches: DeclarationMatcher,\n): boolean {\n if (!ts.isBinaryExpression(node)\n || !assignmentOperator(node.operatorToken.kind)) return false;\n return assignmentTargets(node.left).some(matches);\n}\n\nfunction unaryWritesDeclaration(\n node: ts.Node,\n matches: DeclarationMatcher,\n): boolean {\n if (!ts.isPrefixUnaryExpression(node)\n && !ts.isPostfixUnaryExpression(node)) return false;\n return mutationUnary(node)\n && ts.isIdentifier(node.operand)\n && matches(node.operand);\n}\n\nfunction loopWritesDeclaration(\n node: ts.Node,\n matches: DeclarationMatcher,\n): boolean {\n if (!ts.isForInStatement(node) && !ts.isForOfStatement(node)) return false;\n return !ts.isVariableDeclarationList(node.initializer)\n && assignmentTargets(node.initializer).some(matches);\n}\n\nfunction declarationWritten(\n source: ts.SourceFile,\n declarations: readonly ts.Identifier[],\n): boolean {\n const keys = new Set(declarations.map(declarationKey));\n let written = false;\n const matches = (identifier: ts.Identifier): boolean =>\n lexicalIdentifierDeclarations(identifier)\n .some((item) => keys.has(declarationKey(item)));\n const visit = (node: ts.Node): void => {\n if (written) return;\n written = binaryWritesDeclaration(node, matches)\n || unaryWritesDeclaration(node, matches)\n || loopWritesDeclaration(node, matches);\n if (!written) ts.forEachChild(node, visit);\n };\n visit(source);\n return written;\n}\n\nfunction singleImmutableDeclaration(\n declaration: ts.Identifier | undefined,\n): boolean {\n const parent = declaration?.parent;\n if (parent && ts.isClassDeclaration(parent)) return true;\n return Boolean(parent && ts.isVariableDeclaration(parent)\n && ts.isVariableDeclarationList(parent.parent)\n && (parent.parent.flags & ts.NodeFlags.Const) !== 0);\n}\n\nfunction immutableDeclarationSet(\n declarations: readonly ts.Identifier[],\n source: ts.SourceFile,\n): boolean {\n if (declarations.length === 0\n || declarationWritten(source, declarations)) return false;\n if (declarations.every((item) => ts.isFunctionDeclaration(item.parent)))\n return true;\n if (declarations.length !== 1) return false;\n return singleImmutableDeclaration(declarations[0]);\n}\n\nfunction propertyContainer(\n declaration: ts.Identifier,\n): ts.Node | undefined {\n const parent = declaration.parent;\n if (ts.isClassDeclaration(parent)) return parent;\n if (!ts.isVariableDeclaration(parent)) return undefined;\n const initializer = parent.initializer;\n return initializer\n && (ts.isObjectLiteralExpression(initializer)\n || ts.isClassExpression(initializer))\n ? initializer\n : undefined;\n}\n\nfunction identity(\n symbol: ExecutableSymbolFact,\n): LocalSymbolTargetIdentity {\n return {\n sourceFile: symbol.sourceFile,\n qualifiedName: symbol.qualifiedName,\n startOffset: symbol.startOffset,\n endOffset: symbol.endOffset,\n };\n}\n\nfunction executableBody(symbol: ExecutableSymbolFact): boolean {\n const value = symbol.importExportEvidence?.executableBodyEligibility;\n return Boolean(value && typeof value === 'object'\n && !Array.isArray(value)\n && 'eligible' in value\n && value.eligible === true);\n}\n\nfunction exactFunctionTarget(\n declarations: readonly ts.Identifier[],\n symbols: readonly ExecutableSymbolFact[],\n source: ts.SourceFile,\n): LocalSymbolTargetIdentity | undefined {\n if (!immutableDeclarationSet(declarations, source)) return undefined;\n const spans = declarations.flatMap((declaration) => {\n const target = functionTargetNode(declaration);\n return target\n ? [{ start: target.getStart(source), end: target.getEnd() }]\n : [];\n });\n const matches = symbols.filter((symbol) =>\n localFunctionMatches(symbol, spans, source.fileName));\n return matches.length === 1 && matches[0]\n ? identity(matches[0])\n : undefined;\n}\n\nfunction localFunctionMatches(\n symbol: ExecutableSymbolFact,\n spans: readonly { start: number; end: number }[],\n sourceFile: string,\n): boolean {\n if (symbol.sourceFile !== sourceFile || !executableBody(symbol))\n return false;\n return spans.some((span) =>\n symbol.startOffset === span.start && symbol.endOffset === span.end);\n}\n\nfunction exactPropertyTarget(\n expression: ts.PropertyAccessExpression,\n declaration: ts.Identifier,\n symbols: readonly ExecutableSymbolFact[],\n source: ts.SourceFile,\n): LocalSymbolTargetIdentity | undefined {\n if (!immutableDeclarationSet([declaration], source)\n || !stableLocalValueReference(source, declaration))\n return undefined;\n const container = propertyContainer(declaration);\n if (!container) return undefined;\n const qualifiedName = `${declaration.text}.${expression.name.text}`;\n const start = container.getStart(source);\n const end = container.getEnd();\n const matches = symbols.filter((symbol) =>\n symbol.sourceFile === source.fileName\n && symbol.qualifiedName === qualifiedName\n && symbol.startOffset >= start\n && symbol.endOffset <= end\n && executableBody(symbol));\n return matches.length === 1 && matches[0]\n ? identity(matches[0])\n : undefined;\n}\n\nexport function localSymbolTarget(\n expression: ts.Expression,\n source: ts.SourceFile,\n symbols: readonly ExecutableSymbolFact[],\n): LocalSymbolTargetIdentity | undefined {\n if (ts.isIdentifier(expression)) {\n return exactFunctionTarget(\n lexicalIdentifierDeclarations(expression), symbols, source,\n );\n }\n if (!ts.isPropertyAccessExpression(expression)\n || expression.questionDotToken\n || !ts.isIdentifier(expression.expression)) return undefined;\n const declaration = lexicalIdentifierDeclaration(expression.expression);\n return declaration\n ? exactPropertyTarget(expression, declaration, symbols, source)\n : undefined;\n}\n","import ts from 'typescript';\nimport type {\n ExecutableSymbolFact,\n OutboundCallFact,\n ServiceBindingFact,\n SymbolCallFact,\n} from '../types.js';\nimport {\n executableSymbolCandidates,\n selectCallOwner,\n} from './004-fact-identity.js';\nimport { reconcileEventSubscriptions } from './005-event-subscription-facts.js';\nimport { reconcileBindingAndCallIdentity } from './006-binding-identity.js';\nimport type { ClassifiedOutboundCall } from './outbound-call-parser.js';\n\nexport interface ReconciledSourceFacts {\n bindings: ServiceBindingFact[];\n outboundCalls: OutboundCallFact[];\n symbols: ExecutableSymbolFact[];\n symbolCalls: SymbolCallFact[];\n classifications: ClassifiedOutboundCall[];\n}\n\nfunction callKey(call: Pick<\n OutboundCallFact,\n 'callType' | 'callSiteStartOffset' | 'callSiteEndOffset'\n>): string {\n return `${call.callType}:${call.callSiteStartOffset}:${call.callSiteEndOffset}`;\n}\n\nfunction mergedOutboundCalls(\n existing: readonly OutboundCallFact[],\n classifications: readonly ClassifiedOutboundCall[],\n): OutboundCallFact[] {\n const classifiedKeys = new Set(\n classifications.map((item) => callKey(item.fact)),\n );\n return [\n ...classifications.map((item) => item.fact),\n ...existing.filter((call) => !classifiedKeys.has(callKey(call))),\n ];\n}\n\nfunction exactSymbolCallOwner(\n call: SymbolCallFact,\n symbols: readonly ExecutableSymbolFact[],\n): ExecutableSymbolFact | undefined {\n const start = call.callSiteStartOffset;\n const end = call.callSiteEndOffset;\n if (start === undefined || end === undefined) return undefined;\n const selected = selectCallOwner(\n executableSymbolCandidates(symbols, call.sourceFile),\n start,\n end,\n call.callRole === 'event_subscribe_handler',\n );\n if (selected.status === 'ambiguous')\n throw new Error('invalid_prepared_repository_snapshot:symbol_call_owner_ambiguous');\n if (call.callRole === 'event_subscribe_handler' && !selected.owner)\n throw new Error('invalid_prepared_repository_snapshot:handler_owner_missing');\n return selected.owner;\n}\n\nexport function reconcileSymbolCallOwners(\n calls: readonly SymbolCallFact[],\n symbols: readonly ExecutableSymbolFact[],\n): SymbolCallFact[] {\n return calls.flatMap((call) => {\n const owner = exactSymbolCallOwner(call, symbols);\n if (!owner) return [];\n return [{\n ...call,\n callerQualifiedName: owner.qualifiedName,\n evidence: {\n ...call.evidence,\n caller: owner.qualifiedName,\n callerResolution: 'full_span_containment',\n },\n }];\n });\n}\n\nexport function reconcileSourceFacts(\n source: ts.SourceFile,\n classifications: readonly ClassifiedOutboundCall[],\n bindings: readonly ServiceBindingFact[],\n outboundCalls: readonly OutboundCallFact[],\n symbols: readonly ExecutableSymbolFact[],\n symbolCalls: readonly SymbolCallFact[],\n): ReconciledSourceFacts {\n const events = reconcileEventSubscriptions(\n source, classifications, symbols, symbolCalls,\n );\n const allCalls = mergedOutboundCalls(outboundCalls, events.classifications);\n const identities = reconcileBindingAndCallIdentity(\n source, bindings, allCalls, events.symbols,\n );\n return {\n bindings: identities.bindings,\n outboundCalls: identities.calls,\n symbols: events.symbols,\n symbolCalls: reconcileSymbolCallOwners(events.calls, events.symbols),\n classifications: events.classifications,\n };\n}\n","import ts from 'typescript';\nimport type {\n ExecutableSymbolFact,\n LexicalScopeFact,\n OutboundCallFact,\n ServiceBindingFact,\n ServiceBindingReference,\n} from '../types.js';\nimport {\n executableSymbolCandidates,\n selectCallOwner,\n} from './004-fact-identity.js';\nimport {\n bindingSite,\n createBindingLexicalIndex,\n lexicalScopeChain,\n type BindingLexicalIndex,\n type BindingLexicalSite,\n type VisibleBinding,\n} from './011-binding-lexical-scope.js';\nimport { selectVisibleBinding } from './021-binding-visibility.js';\n\nconst scopeChainCap = 16;\n\ninterface PreparedBinding {\n fact: ServiceBindingFact;\n site: BindingLexicalSite;\n aliasProven: boolean;\n}\n\nfunction matchFactsToSites(\n index: BindingLexicalIndex,\n facts: readonly ServiceBindingFact[],\n): Array<{ fact: ServiceBindingFact; site: BindingLexicalSite }> {\n return facts.map((fact) => {\n if (fact.bindingSiteStartOffset === undefined\n || fact.bindingSiteEndOffset === undefined)\n throw new Error('invalid_prepared_repository_snapshot:binding_site_missing');\n const site = bindingSite(\n index,\n fact.variableName,\n fact.bindingSiteStartOffset,\n fact.bindingSiteEndOffset,\n );\n if (!site)\n throw new Error('invalid_prepared_repository_snapshot:binding_site_invalid');\n return { fact, site };\n });\n}\n\nfunction exactOwner(\n fact: ServiceBindingFact,\n site: BindingLexicalSite,\n symbols: readonly ExecutableSymbolFact[],\n): ServiceBindingFact {\n const candidates = executableSymbolCandidates(symbols, fact.sourceFile);\n const owner = selectCallOwner(\n candidates, site.startOffset, site.endOffset,\n );\n if (owner.status === 'ambiguous')\n throw new Error('invalid_prepared_repository_snapshot:binding_owner_ambiguous');\n return {\n ...fact,\n bindingSiteStartOffset: site.startOffset,\n bindingSiteEndOffset: site.endOffset,\n sourceSymbolQualifiedName: owner.owner?.qualifiedName,\n ownerResolution: owner.status === 'resolved'\n ? 'owned_exact'\n : 'ownerless_file_scope',\n };\n}\n\nfunction prepareBindings(\n index: BindingLexicalIndex,\n facts: readonly ServiceBindingFact[],\n symbols: readonly ExecutableSymbolFact[],\n): PreparedBinding[] {\n return matchFactsToSites(index, facts).map(({ fact, site }) => ({\n fact: exactOwner(fact, site, symbols),\n site,\n aliasProven: site.aliasSource === undefined,\n }));\n}\n\nfunction aliasStep(binding: PreparedBinding, source: PreparedBinding): Record<string, unknown> {\n const aliasKind = binding.site.aliasKind\n ?? (binding.site.flow === 'assignment'\n ? 'identity-assignment'\n : 'identity');\n return {\n callerVariable: binding.fact.variableName,\n aliasOf: source.fact.variableName,\n aliasKind,\n scopeRule: 'exact_lexical_scope',\n ...(aliasKind === 'transaction'\n ? { transactionAliasSource: source.fact.variableName }\n : {}),\n ...(binding.site.aliasArrayIndex === undefined ? {} : {\n sourceVariable: source.fact.variableName,\n arrayIndex: binding.site.aliasArrayIndex,\n promiseAll: binding.site.aliasPromiseAll ?? false,\n arrayContainer: binding.site.aliasPromiseAll\n ? 'Promise.all'\n : 'array_literal',\n }),\n };\n}\n\nfunction copyAliasProvenance(\n binding: PreparedBinding,\n source: PreparedBinding,\n): void {\n binding.fact = {\n ...binding.fact,\n alias: source.fact.alias,\n aliasExpr: source.fact.aliasExpr,\n destinationExpr: source.fact.destinationExpr,\n servicePathExpr: source.fact.servicePathExpr,\n isDynamic: source.fact.isDynamic,\n placeholders: source.fact.placeholders,\n helperChain: [\n ...(source.fact.helperChain ?? []),\n aliasStep(binding, source),\n ],\n };\n binding.aliasProven = true;\n}\n\nfunction bindingCandidates(\n bindings: readonly PreparedBinding[],\n): Array<{\n variableName: string;\n bindingSiteStartOffset: number;\n bindingSiteEndOffset: number;\n value: PreparedBinding;\n}> {\n return bindings.map((binding) => ({\n variableName: binding.fact.variableName,\n bindingSiteStartOffset: binding.site.startOffset,\n bindingSiteEndOffset: binding.site.endOffset,\n value: binding,\n }));\n}\n\nfunction resolvedAliasSource(\n selected: VisibleBinding<PreparedBinding>,\n): PreparedBinding | undefined {\n if (selected.status !== 'resolved') return undefined;\n if (!selected.site?.deterministic) return undefined;\n if (selected.declarationSite?.declarationKind === 'var') return undefined;\n const source = selected.candidate?.value;\n return source?.aliasProven ? source : undefined;\n}\n\nfunction reconcileAliases(\n index: BindingLexicalIndex,\n bindings: PreparedBinding[],\n): void {\n const candidates = bindingCandidates(bindings);\n for (const binding of bindings) {\n const sourceName = binding.site.aliasSource;\n if (!sourceName) continue;\n const selected = selectVisibleBinding(\n index, candidates, sourceName, binding.site.node,\n );\n const source = resolvedAliasSource(selected);\n if (source) copyAliasProvenance(binding, source);\n }\n}\n\nfunction assertUniqueSites(bindings: readonly PreparedBinding[]): void {\n const seen = new Set<string>();\n for (const binding of bindings) {\n const key = [\n binding.fact.sourceFile,\n binding.fact.variableName,\n binding.site.startOffset,\n binding.site.endOffset,\n ].join('\\u0000');\n if (seen.has(key))\n throw new Error('invalid_prepared_repository_snapshot:duplicate_service_binding_site');\n seen.add(key);\n }\n}\n\nfunction callNodeMap(source: ts.SourceFile): Map<string, ts.CallExpression> {\n const calls = new Map<string, ts.CallExpression>();\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node))\n calls.set(`${node.getStart(source)}:${node.getEnd()}`, node);\n ts.forEachChild(node, visit);\n };\n visit(source);\n return calls;\n}\n\nfunction emptyReference(\n call: OutboundCallFact,\n reason?: ServiceBindingReference['reason'],\n): ServiceBindingReference {\n return {\n status: call.serviceVariableName ? 'unresolved' : 'not_applicable',\n variableName: call.serviceVariableName,\n scopeChainTotal: 0,\n scopeChainShown: 0,\n scopeChainOmitted: 0,\n reason,\n };\n}\n\nfunction rejectedReference(\n call: OutboundCallFact,\n chain: LexicalScopeFact[],\n reason: ServiceBindingReference['reason'],\n status: 'ambiguous' | 'unresolved' = 'unresolved',\n): ServiceBindingReference {\n return {\n status,\n variableName: call.serviceVariableName,\n scopeChainTotal: chain.length,\n scopeChainShown: Math.min(chain.length, scopeChainCap),\n scopeChainOmitted: Math.max(0, chain.length - scopeChainCap),\n reason,\n };\n}\n\nfunction resolvedReference(\n call: OutboundCallFact,\n selected: PreparedBinding,\n chain: LexicalScopeFact[],\n scopeIndex: number,\n): ServiceBindingReference {\n return {\n status: 'resolved_exact',\n variableName: call.serviceVariableName,\n bindingSourceFile: selected.fact.sourceFile,\n bindingSiteStartOffset: selected.site.startOffset,\n bindingSiteEndOffset: selected.site.endOffset,\n resolutionStrategy: selected.site.flow === 'assignment'\n ? 'deterministic_reaching_assignment'\n : selected.site.aliasSource\n ? 'lexical_alias_declaration'\n : 'lexical_declaration',\n lexicalScopeChain: chain,\n bindingScopeIndex: scopeIndex,\n scopeChainTotal: chain.length,\n scopeChainShown: chain.length,\n scopeChainOmitted: 0,\n };\n}\n\nfunction selectedBindingReference(\n call: OutboundCallFact,\n chain: LexicalScopeFact[],\n chosen: VisibleBinding<PreparedBinding>,\n): ServiceBindingReference {\n const selected = chosen.candidate?.value;\n if (!selected) {\n return rejectedReference(\n call, chain, chosen.reason ?? 'binding_not_found',\n );\n }\n if (chosen.declarationSite?.declarationKind === 'var')\n return rejectedReference(call, chain, 'unsupported_var_binding');\n if (!selected.site.deterministic || !selected.aliasProven)\n return rejectedReference(call, chain, 'unsupported_reaching_assignment');\n return resolvedReference(call, selected, chain, chosen.scopeIndex ?? 0);\n}\n\nfunction bindingReference(\n call: OutboundCallFact,\n node: ts.CallExpression | undefined,\n index: BindingLexicalIndex,\n bindings: readonly PreparedBinding[],\n): ServiceBindingReference {\n if (!call.serviceVariableName) return emptyReference(call);\n if (!node) return emptyReference(call, 'binding_flow_unsupported');\n const chain = lexicalScopeChain(node, index.source);\n if (chain.length > scopeChainCap)\n return rejectedReference(call, chain, 'scope_chain_limit_exceeded');\n const chosen = selectVisibleBinding(\n index, bindingCandidates(bindings), call.serviceVariableName, node,\n );\n if (chosen.status === 'ambiguous')\n return rejectedReference(\n call, chain, 'binding_scope_ambiguous', 'ambiguous',\n );\n return selectedBindingReference(call, chain, chosen);\n}\n\nfunction exactCallOwner(\n call: OutboundCallFact,\n symbols: readonly ExecutableSymbolFact[],\n): { qualifiedName?: string; resolution: 'owned_exact' | 'ownerless_file_scope' } {\n const start = call.callSiteStartOffset;\n const end = call.callSiteEndOffset;\n if (start === undefined || end === undefined)\n return { resolution: 'ownerless_file_scope' };\n const selected = selectCallOwner(\n executableSymbolCandidates(symbols, call.sourceFile),\n start,\n end,\n call.callType === 'async_subscribe',\n );\n if (selected.status === 'ambiguous')\n throw new Error('invalid_prepared_repository_snapshot:outbound_owner_ambiguous');\n if (call.callType === 'async_subscribe' && selected.status !== 'resolved')\n throw new Error('invalid_prepared_repository_snapshot:subscription_owner_missing');\n return selected.owner\n ? { qualifiedName: selected.owner.qualifiedName, resolution: 'owned_exact' }\n : { resolution: 'ownerless_file_scope' };\n}\n\nexport function reconcileBindingAndCallIdentity(\n source: ts.SourceFile,\n bindingFacts: readonly ServiceBindingFact[],\n callFacts: readonly OutboundCallFact[],\n symbols: readonly ExecutableSymbolFact[],\n): { bindings: ServiceBindingFact[]; calls: OutboundCallFact[] } {\n const lexicalIndex = createBindingLexicalIndex(source);\n const bindings = prepareBindings(lexicalIndex, bindingFacts, symbols);\n reconcileAliases(lexicalIndex, bindings);\n assertUniqueSites(bindings);\n const nodes = callNodeMap(source);\n const calls = callFacts.map((call) => {\n const key = `${call.callSiteStartOffset}:${call.callSiteEndOffset}`;\n const reference = bindingReference(\n call, nodes.get(key), lexicalIndex, bindings,\n );\n const owner = exactCallOwner(call, symbols);\n return {\n ...call,\n sourceSymbolQualifiedName: owner.qualifiedName,\n serviceBindingReference: reference,\n evidence: {\n ...(call.evidence ?? {}),\n sourceOwnerResolution: owner.resolution,\n serviceBindingReference: reference,\n },\n };\n });\n return { bindings: bindings.map((binding) => binding.fact), calls };\n}\n","import ts from 'typescript';\nimport type {\n ExecutableSymbolFact,\n SymbolCallFact,\n} from '../types.js';\nimport {\n executableSymbolCandidates,\n selectCallOwner,\n} from './004-fact-identity.js';\nimport {\n derivedMemberImportReference,\n identifierMatchesDeclaration,\n symbolImportReference,\n type SymbolImportBinding,\n type SymbolImportReference,\n} from './002-symbol-import-bindings.js';\nimport {\n localSymbolTarget,\n type LocalSymbolTargetIdentity,\n} from './016-local-symbol-reference.js';\n\nexport interface SymbolCallProxy {\n importSource: string;\n importBinding: SymbolImportReference;\n factory: string;\n variableName: string;\n declarationStartOffset: number;\n declarationEndOffset: number;\n}\n\nexport interface SymbolClassInstance {\n className: string;\n importSource?: string;\n importBinding?: SymbolImportReference;\n propertyName?: string;\n declarationStartOffset: number;\n declarationEndOffset: number;\n containerStartOffset?: number;\n containerEndOffset?: number;\n}\n\ninterface CalleeName {\n expression: string;\n local?: string;\n member?: string;\n receiver?: string;\n}\n\ninterface CallCollection {\n source: ts.SourceFile;\n sourceFile: string;\n symbols: readonly ExecutableSymbolFact[];\n imports: ReadonlyMap<string, string>;\n importBindings: readonly SymbolImportBinding[];\n proxies: ReadonlyMap<string, readonly SymbolCallProxy[]>;\n instances: ReadonlyMap<string, readonly SymbolClassInstance[]>;\n}\n\ninterface CallContext {\n proxy?: SymbolCallProxy;\n instance?: SymbolClassInstance;\n reference?: SymbolImportReference;\n localTarget?: LocalSymbolTargetIdentity;\n}\n\nconst commonTerminalMembers = new Set([\n 'push', 'includes', 'find', 'findIndex', 'map', 'filter', 'reduce',\n 'forEach', 'some', 'every', 'toUpperCase', 'toLowerCase', 'trim',\n 'split', 'join', 'get', 'set', 'has',\n]);\nconst loggerMembers = new Set([\n 'trace', 'debug', 'info', 'warn', 'error', 'fatal', 'log',\n]);\nconst globalObjects = new Set([\n 'JSON', 'Object', 'Array', 'String', 'Number', 'Boolean', 'Math', 'Date',\n 'Promise', 'Reflect',\n]);\nconst capDslRoots = new Set([\n 'SELECT', 'INSERT', 'UPSERT', 'UPDATE', 'DELETE',\n]);\nconst requestHelpers = new Set([\n 'reject', 'error', 'info', 'warn', 'notify',\n]);\nconst transportMembers = new Set([\n 'emit', 'publish', 'send', 'on',\n]);\nconst cdsFrameworkPrefixes = [\n 'cds.connect.', 'cds.services.', 'cds.parse.',\n];\n\nexport function symbolCallName(expr: ts.Expression): CalleeName {\n if (ts.isIdentifier(expr)) return { expression: expr.text, local: expr.text };\n if (!ts.isPropertyAccessExpression(expr))\n return { expression: expr.getText() };\n const left = expr.expression.getText();\n return {\n expression: expr.getText(),\n local: left === 'this' ? undefined : left.split('.')[0],\n member: expr.name.text,\n receiver: left,\n };\n}\n\nfunction hasSetMember(\n value: string | undefined,\n values: ReadonlySet<string>,\n): boolean {\n return value ? values.has(value) : false;\n}\n\nfunction cdsFrameworkCall(callee: CalleeName): boolean {\n return callee.expression === 'cds.run'\n || cdsFrameworkPrefixes.some((prefix) =>\n callee.expression.startsWith(prefix));\n}\n\nfunction requestHelperCall(callee: CalleeName): boolean {\n return callee.local === 'req'\n && hasSetMember(callee.member, requestHelpers);\n}\n\nfunction ignoredFrameworkCall(callee: CalleeName): boolean {\n const checks = [\n hasSetMember(callee.local, capDslRoots),\n cdsFrameworkCall(callee),\n requestHelperCall(callee),\n hasSetMember(callee.member, transportMembers),\n hasSetMember(callee.local, globalObjects),\n callee.expression.startsWith('new Date().'),\n ];\n return checks.some(Boolean);\n}\n\nfunction argumentEvidence(\n args: ts.NodeArray<ts.Expression>,\n): Array<Record<string, unknown>> {\n return args.map((arg) => {\n if (ts.isIdentifier(arg)) return { kind: 'identifier', name: arg.text };\n if (ts.isArrayLiteralExpression(arg)) return {\n kind: 'array_literal',\n elements: arg.elements.flatMap((item, index) =>\n ts.isIdentifier(item)\n ? [{ index, kind: 'identifier', name: item.text }]\n : []),\n };\n if (ts.isObjectLiteralExpression(arg))\n return objectArgumentEvidence(arg);\n return { kind: 'unsupported', expression: arg.getText() };\n });\n}\n\nfunction objectArgumentEvidence(\n argument: ts.ObjectLiteralExpression,\n): Record<string, unknown> {\n const properties = argument.properties.flatMap((property) => {\n if (ts.isShorthandPropertyAssignment(property))\n return [{\n kind: 'shorthand',\n property: property.name.text,\n argument: property.name.text,\n }];\n if (!ts.isPropertyAssignment(property)\n || !ts.isIdentifier(property.initializer)) return [];\n const name = propertyName(property.name);\n return name ? [{\n kind: 'property_assignment',\n property: name,\n argument: property.initializer.text,\n }] : [];\n });\n return { kind: 'object_literal', properties };\n}\n\nfunction propertyName(name: ts.PropertyName): string | undefined {\n return ts.isIdentifier(name) || ts.isStringLiteralLike(name)\n || ts.isNumericLiteral(name) ? name.text : undefined;\n}\n\nfunction exactCaller(\n collection: CallCollection,\n node: ts.CallExpression,\n): ExecutableSymbolFact | undefined {\n const selected = selectCallOwner(\n executableSymbolCandidates(collection.symbols, collection.sourceFile),\n node.getStart(collection.source),\n node.getEnd(),\n );\n if (selected.status === 'ambiguous')\n throw new Error('invalid_prepared_repository_snapshot:symbol_call_owner_ambiguous');\n return selected.owner;\n}\n\nfunction relation(\n reference: SymbolImportReference | undefined,\n instance: SymbolClassInstance | undefined,\n proxy: SymbolCallProxy | undefined,\n localTarget: LocalSymbolTargetIdentity | undefined,\n provenThisMethod: boolean,\n): string {\n const derived = derivedRelation(instance, proxy);\n if (derived) return derived;\n if (reference?.moduleKind === 'package') return 'package_import';\n if (reference?.referenceShape === 'namespace_member')\n return 'relative_import_namespace_member';\n if (reference) return 'relative_import';\n if (localTarget) return 'indexed_local_symbol';\n return provenThisMethod ? 'indexed_this_method' : 'indexed_local_symbol';\n}\n\nfunction derivedRelation(\n instance: SymbolClassInstance | undefined,\n proxy: SymbolCallProxy | undefined,\n): string | undefined {\n if (instance?.importBinding?.moduleKind === 'package')\n return 'package_import_derived_member';\n if (instance) return 'class_instance_method';\n if (proxy?.importBinding.moduleKind === 'package')\n return 'package_import_derived_member';\n return proxy ? 'relative_import_proxy_member' : undefined;\n}\n\nfunction targetName(\n callee: CalleeName,\n reference: SymbolImportReference | undefined,\n instance: SymbolClassInstance | undefined,\n proxy: SymbolCallProxy | undefined,\n): string | undefined {\n if (instance && callee.member)\n return `${instance.className}.${callee.member}`;\n if (proxy && callee.member) return callee.member;\n if (callee.receiver === 'this') return callee.member;\n if (reference) return reference.requestedPublicName;\n return callee.member && callee.local\n ? `${callee.local}.${callee.member}`\n : callee.local;\n}\n\nfunction callFact(\n collection: CallCollection,\n node: ts.CallExpression,\n): SymbolCallFact | undefined {\n const caller = exactCaller(collection, node);\n if (!caller) return undefined;\n const callee = symbolCallName(node.expression);\n const proxy = callProxy(collection, node);\n const instance = callInstance(collection, node, callee);\n const reference = callImportReference(\n collection, node.expression, callee, instance, proxy,\n );\n const localTarget = reference || instance || proxy\n ? undefined\n : localSymbolTarget(node.expression, collection.source, collection.symbols);\n return retainedCallFact(collection, node, caller, callee, {\n proxy, instance, reference, localTarget,\n });\n}\n\nfunction expressionRoot(\n expression: ts.Expression,\n): ts.Identifier | undefined {\n let current = expression;\n while (ts.isPropertyAccessExpression(current))\n current = current.expression;\n return ts.isIdentifier(current) ? current : undefined;\n}\n\nfunction exactDeclaredContext<T extends {\n declarationStartOffset: number;\n declarationEndOffset: number;\n}>(\n identifier: ts.Identifier,\n candidates: readonly T[],\n): T | undefined {\n const matches = candidates.filter((candidate) =>\n identifierMatchesDeclaration(\n identifier,\n candidate.declarationStartOffset,\n candidate.declarationEndOffset,\n ));\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction callProxy(\n collection: CallCollection,\n node: ts.CallExpression,\n): SymbolCallProxy | undefined {\n const root = expressionRoot(node.expression);\n if (!root) return undefined;\n return exactDeclaredContext(\n root, collection.proxies.get(root.text) ?? [],\n );\n}\n\nfunction callInstance(\n collection: CallCollection,\n node: ts.CallExpression,\n callee: CalleeName,\n): SymbolClassInstance | undefined {\n const root = expressionRoot(node.expression);\n if (root && root.text !== 'this') {\n const exact = exactDeclaredContext(\n root, collection.instances.get(root.text) ?? [],\n );\n if (exact) return exact;\n }\n return callee.receiver\n ? thisPropertyInstance(collection, node, callee.receiver)\n : undefined;\n}\n\nfunction enclosingClass(node: ts.Node): ts.ClassLikeDeclaration | undefined {\n let current: ts.Node | undefined = node.parent;\n while (current && !ts.isSourceFile(current)) {\n if (ts.isClassLike(current)) return current;\n current = current.parent;\n }\n return undefined;\n}\n\nfunction thisPropertyInstance(\n collection: CallCollection,\n node: ts.CallExpression,\n receiver: string,\n): SymbolClassInstance | undefined {\n if (!receiver.startsWith('this.')) return undefined;\n const container = enclosingClass(node);\n if (!container) return undefined;\n const start = container.getStart(collection.source);\n const end = container.getEnd();\n const matches = (collection.instances.get(receiver) ?? []).filter(\n (candidate) => candidate.containerStartOffset === start\n && candidate.containerEndOffset === end,\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction callImportReference(\n collection: CallCollection,\n expression: ts.Expression,\n callee: CalleeName,\n instance: SymbolClassInstance | undefined,\n proxy: SymbolCallProxy | undefined,\n): SymbolImportReference | undefined {\n const direct = symbolImportReference(expression, collection.importBindings);\n if (direct || !callee.member) return direct;\n const inherited = instance?.importBinding ?? proxy?.importBinding;\n return inherited\n ? derivedMemberImportReference(inherited, callee.member)\n : undefined;\n}\n\nfunction retainedCallFact(\n collection: CallCollection,\n node: ts.CallExpression,\n caller: ExecutableSymbolFact,\n callee: CalleeName,\n context: CallContext,\n): SymbolCallFact | undefined {\n const target = targetName(\n callee, context.reference, context.instance, context.proxy,\n );\n const className = caller.qualifiedName.includes('.')\n ? caller.qualifiedName.split('.')[0] : undefined;\n const thisTarget = callee.receiver === 'this' && className && callee.member\n ? `${className}.${callee.member}` : undefined;\n const resolvedTarget = thisTarget ?? target;\n if (!resolvedTarget\n || !shouldRetainCall(\n collection, callee, resolvedTarget, context, Boolean(thisTarget),\n ))\n return undefined;\n return createCallFact(\n collection, node, caller, callee, resolvedTarget, thisTarget, context,\n );\n}\n\nfunction shouldRetainCall(\n collection: CallCollection,\n callee: CalleeName,\n target: string | undefined,\n context: CallContext,\n provenThisMethod: boolean,\n): boolean {\n if (!target || ignoredCall(callee)) return false;\n const callables = new Set(collection.symbols.flatMap((symbol) =>\n [symbol.localName, symbol.qualifiedName]));\n return provenThisMethod\n || Boolean(context.localTarget)\n || callables.has(target) && Boolean(context.instance)\n || hasImportedContext(context);\n}\n\nfunction ignoredCall(callee: CalleeName): boolean {\n return loggerCall(callee) || terminalCall(callee)\n || ignoredFrameworkCall(callee);\n}\n\nfunction loggerCall(callee: CalleeName): boolean {\n if (callee.local === 'logger') return true;\n if (callee.receiver?.endsWith('.logger')) return true;\n return callee.expression.startsWith('this.logger.')\n && hasSetMember(callee.member, loggerMembers);\n}\n\nfunction terminalCall(callee: CalleeName): boolean {\n return hasSetMember(callee.member, commonTerminalMembers)\n || hasSetMember(callee.member, loggerMembers);\n}\n\nfunction hasImportedContext(context: CallContext): boolean {\n return Boolean(context.reference ?? context.proxy ?? context.instance);\n}\n\nfunction createCallFact(\n collection: CallCollection,\n node: ts.CallExpression,\n caller: ExecutableSymbolFact,\n callee: CalleeName,\n target: string,\n thisTarget: string | undefined,\n context: CallContext,\n): SymbolCallFact {\n const importSource = context.instance?.importSource\n ?? context.proxy?.importSource\n ?? context.reference?.rawModuleSpecifier;\n return {\n callerQualifiedName: caller.qualifiedName,\n calleeExpression: callee.expression,\n calleeLocalName: target,\n receiverLocalName: callee.member ? callee.local ?? callee.receiver : undefined,\n importSource,\n sourceFile: collection.sourceFile,\n sourceLine: collection.source.getLineAndCharacterOfPosition(\n node.getStart(collection.source),\n ).line + 1,\n callSiteStartOffset: node.getStart(collection.source),\n callSiteEndOffset: node.getEnd(),\n callRole: 'ordinary_call',\n evidence: callEvidence(caller, callee, target, thisTarget, context, node),\n };\n}\n\nfunction callEvidence(\n caller: ExecutableSymbolFact,\n callee: CalleeName,\n target: string,\n thisTarget: string | undefined,\n context: CallContext,\n node: ts.CallExpression,\n): Record<string, unknown> {\n return {\n relation: relation(\n context.reference, context.instance, context.proxy,\n context.localTarget, Boolean(thisTarget),\n ),\n caller: caller.qualifiedName,\n targetName: target,\n ...importReferenceEvidence(context),\n ...instanceEvidence(context.instance, callee),\n callArguments: argumentEvidence(node.arguments),\n ...proxyEvidence(context.proxy),\n ...(context.localTarget\n ? { localTargetIdentity: context.localTarget }\n : {}),\n candidateStrategy: parserCandidateStrategy(context),\n };\n}\n\nfunction importReferenceEvidence(\n context: CallContext,\n): Record<string, unknown> {\n if (!context.reference) return {};\n const derived = context.instance ?? context.proxy;\n return derived && context.reference.moduleKind === 'package'\n ? { derivedImportBinding: context.reference }\n : { importBinding: context.reference };\n}\n\nfunction instanceEvidence(\n instance: SymbolClassInstance | undefined,\n callee: CalleeName,\n): Record<string, unknown> {\n if (!instance) return {};\n return {\n instanceVariable: instance.propertyName ?? callee.local,\n className: instance.className,\n methodName: callee.member,\n classImportSource: instance.importSource,\n classImportBinding: instance.importBinding,\n };\n}\n\nfunction proxyEvidence(\n proxy: SymbolCallProxy | undefined,\n): Record<string, unknown> {\n if (!proxy) return {};\n return {\n proxyVariableName: proxy.variableName,\n factory: proxy.factory,\n factoryExpression: proxy.factory,\n factoryImportSource: proxy.importSource,\n factoryImportBinding: proxy.importBinding,\n };\n}\n\nfunction parserCandidateStrategy(context: CallContext): string | undefined {\n if (context.instance?.importSource)\n return 'relative_import_class_instance_method';\n if (context.instance) return 'same_file_class_instance_method';\n return context.proxy\n ? 'proxy_member_exact_export_or_unique_member'\n : undefined;\n}\n\nexport function collectSymbolCallFacts(\n collection: CallCollection,\n): SymbolCallFact[] {\n const calls: SymbolCallFact[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node)) {\n const call = callFact(collection, node);\n if (call) calls.push(call);\n }\n ts.forEachChild(node, visit);\n };\n visit(collection.source);\n return calls;\n}\n","import ts from 'typescript';\n\nexport type ExecutableBodyEligibilityReason =\n | 'body_present'\n | 'declaration_only'\n | 'ambient_declaration'\n | 'abstract_bodyless'\n | 'overload_signature';\n\nexport interface ExecutableBodyEligibilityEvidence {\n eligible: boolean;\n reason: ExecutableBodyEligibilityReason;\n}\n\nfunction hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean {\n return ts.canHaveModifiers(node)\n && Boolean(ts.getModifiers(node)?.some((item) => item.kind === kind));\n}\n\nexport function executableBodyEligibility(\n node: ts.FunctionLikeDeclaration,\n source: ts.SourceFile,\n): ExecutableBodyEligibilityEvidence {\n if (node.body) return { eligible: true, reason: 'body_present' };\n if (hasModifier(node, ts.SyntaxKind.AbstractKeyword))\n return { eligible: false, reason: 'abstract_bodyless' };\n if (hasModifier(node, ts.SyntaxKind.DeclareKeyword))\n return { eligible: false, reason: 'ambient_declaration' };\n return {\n eligible: false,\n reason: source.isDeclarationFile\n ? 'declaration_only'\n : 'overload_signature',\n };\n}\n","import ts from 'typescript';\nimport {\n symbolCallName,\n type SymbolCallProxy,\n type SymbolClassInstance,\n} from './009-symbol-call-facts.js';\nimport {\n identifierMatchesDeclaration,\n symbolImportReference,\n type SymbolImportBinding,\n} from './002-symbol-import-bindings.js';\n\ninterface DerivedContextCollection {\n source: ts.SourceFile;\n importBindings: readonly SymbolImportBinding[];\n declaredClasses: ReadonlySet<string>;\n proxies: Map<string, SymbolCallProxy[]>;\n instances: Map<string, SymbolClassInstance[]>;\n}\n\nconst builtInConstructors = new Set([\n 'Set', 'Map', 'WeakSet', 'WeakMap',\n 'Date', 'RegExp', 'URL', 'URLSearchParams',\n 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError',\n 'TypeError', 'URIError', 'AggregateError',\n 'ArrayBuffer', 'SharedArrayBuffer', 'DataView',\n 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array',\n 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array',\n 'Float64Array', 'BigInt64Array', 'BigUint64Array',\n 'Promise', 'AbortController',\n]);\n\nfunction appendNamed<T>(\n values: Map<string, T[]>,\n name: string,\n value: T,\n): void {\n const matches = values.get(name) ?? [];\n matches.push(value);\n values.set(name, matches);\n}\n\nfunction assignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment\n && kind <= ts.SyntaxKind.LastAssignment;\n}\n\nfunction mutationUnary(\n node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression,\n): boolean {\n return node.operator === ts.SyntaxKind.PlusPlusToken\n || node.operator === ts.SyntaxKind.MinusMinusToken;\n}\n\nfunction receiverIdentifier(\n expression: ts.Expression,\n): ts.Identifier | undefined {\n let current = expression;\n while (ts.isPropertyAccessExpression(current)\n || ts.isElementAccessExpression(current))\n current = current.expression;\n return ts.isIdentifier(current) ? current : undefined;\n}\n\nfunction nodeWritesMember(\n node: ts.Node,\n matches: (expression: ts.Expression) => boolean,\n): boolean {\n if (ts.isBinaryExpression(node))\n return assignmentOperator(node.operatorToken.kind) && matches(node.left);\n if (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))\n return mutationUnary(node) && matches(node.operand);\n return ts.isDeleteExpression(node) && matches(node.expression);\n}\n\nfunction memberWrite(\n source: ts.SourceFile,\n declaration: ts.Identifier,\n): boolean {\n const start = declaration.getStart(source);\n const end = declaration.getEnd();\n const matches = (expression: ts.Expression): boolean => {\n const receiver = receiverIdentifier(expression);\n return Boolean(receiver && receiver !== expression\n && identifierMatchesDeclaration(receiver, start, end));\n };\n let written = false;\n const visit = (node: ts.Node): void => {\n if (written) return;\n written = nodeWritesMember(node, matches);\n if (!written) ts.forEachChild(node, visit);\n };\n visit(source);\n return written;\n}\n\nfunction stableVariable(\n collection: DerivedContextCollection,\n node: ts.VariableDeclaration,\n): node is ts.VariableDeclaration & { name: ts.Identifier } {\n return ts.isIdentifier(node.name)\n && ts.isVariableDeclarationList(node.parent)\n && (node.parent.flags & ts.NodeFlags.Const) !== 0\n && !memberWrite(collection.source, node.name);\n}\n\nfunction collectProxy(\n collection: DerivedContextCollection,\n node: ts.Node,\n): void {\n if (!ts.isVariableDeclaration(node) || !stableVariable(collection, node)\n || !node.initializer || !ts.isCallExpression(node.initializer)\n || !ts.isPropertyAccessExpression(node.initializer.expression)) return;\n const callee = symbolCallName(node.initializer.expression);\n const binding = symbolImportReference(\n node.initializer.expression, collection.importBindings,\n );\n if (!callee.member || !binding) return;\n appendNamed(collection.proxies, node.name.text, {\n importSource: binding.rawModuleSpecifier,\n importBinding: binding,\n factory: callee.expression,\n variableName: node.name.text,\n declarationStartOffset: node.name.getStart(collection.source),\n declarationEndOffset: node.name.getEnd(),\n });\n}\n\nfunction propertyContainer(\n declaration: ts.Identifier | ts.PropertyName,\n propertyName: string | undefined,\n): ts.ClassLikeDeclaration | undefined {\n const property = propertyName && ts.isPropertyDeclaration(declaration.parent)\n ? declaration.parent : undefined;\n return property && ts.isClassLike(property.parent)\n ? property.parent : undefined;\n}\n\nfunction eligibleClassName(\n collection: DerivedContextCollection,\n className: string,\n imported: ReturnType<typeof symbolImportReference>,\n): boolean {\n if (builtInConstructors.has(className)) return false;\n return Boolean(imported || collection.declaredClasses.has(className));\n}\n\nfunction resolvedClassName(\n className: string,\n imported: ReturnType<typeof symbolImportReference>,\n): string {\n const importedName = imported?.importedName;\n return importedName && importedName !== 'default'\n ? importedName : className;\n}\n\nfunction rememberInstance(\n collection: DerivedContextCollection,\n declaration: ts.Identifier | ts.PropertyName,\n classExpression: ts.Identifier,\n propertyName?: string,\n): void {\n const className = classExpression.text;\n const imported = symbolImportReference(\n classExpression, collection.importBindings,\n );\n if (!eligibleClassName(collection, className, imported)) return;\n const container = propertyContainer(declaration, propertyName);\n const variableName = propertyName\n ? `this.${propertyName}` : declaration.getText();\n appendNamed(collection.instances, variableName, {\n className: resolvedClassName(className, imported),\n importSource: imported?.rawModuleSpecifier,\n importBinding: imported,\n propertyName,\n declarationStartOffset: declaration.getStart(collection.source),\n declarationEndOffset: declaration.getEnd(),\n containerStartOffset: container?.getStart(collection.source),\n containerEndOffset: container?.getEnd(),\n });\n}\n\nfunction collectVariableInstance(\n collection: DerivedContextCollection,\n node: ts.Node,\n): void {\n if (!ts.isVariableDeclaration(node) || !stableVariable(collection, node))\n return;\n const initializer = node.initializer;\n if (initializer && ts.isNewExpression(initializer)\n && ts.isIdentifier(initializer.expression))\n rememberInstance(collection, node.name, initializer.expression);\n}\n\nfunction propertyName(name: ts.PropertyName): string | undefined {\n return ts.isIdentifier(name) || ts.isStringLiteralLike(name)\n || ts.isNumericLiteral(name) ? name.text : undefined;\n}\n\nfunction thisPropertyWrite(\n expression: ts.Expression,\n name: string,\n): boolean {\n if (ts.isPropertyAccessExpression(expression))\n return expression.expression.kind === ts.SyntaxKind.ThisKeyword\n && expression.name.text === name;\n return ts.isElementAccessExpression(expression)\n && expression.expression.kind === ts.SyntaxKind.ThisKeyword\n && Boolean(expression.argumentExpression\n && ts.isStringLiteralLike(expression.argumentExpression)\n && expression.argumentExpression.text === name);\n}\n\nfunction nodeWritesThisProperty(\n node: ts.Node,\n name: string,\n): boolean {\n if (ts.isBinaryExpression(node))\n return assignmentOperator(node.operatorToken.kind)\n && thisPropertyWrite(node.left, name);\n if (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))\n return mutationUnary(node) && thisPropertyWrite(node.operand, name);\n return ts.isDeleteExpression(node)\n && thisPropertyWrite(node.expression, name);\n}\n\nfunction stableProperty(\n node: ts.PropertyDeclaration,\n name: string,\n): boolean {\n const flags = ts.getCombinedModifierFlags(node);\n if ((flags & (ts.ModifierFlags.Private | ts.ModifierFlags.Readonly)) === 0\n || !ts.isClassLike(node.parent)) return false;\n let written = false;\n const visit = (child: ts.Node): void => {\n if (written || child === node) return;\n written = nodeWritesThisProperty(child, name);\n if (!written) ts.forEachChild(child, visit);\n };\n visit(node.parent);\n return !written;\n}\n\nfunction collectPropertyInstance(\n collection: DerivedContextCollection,\n node: ts.Node,\n): void {\n if (!ts.isPropertyDeclaration(node)) return;\n const initializer = node.initializer;\n if (!initializer || !ts.isNewExpression(initializer)\n || !ts.isIdentifier(initializer.expression)) return;\n const name = propertyName(node.name);\n if (name && stableProperty(node, name)) rememberInstance(\n collection, node.name, initializer.expression, name,\n );\n}\n\nexport function collectDerivedSymbolContexts(\n collection: DerivedContextCollection,\n): void {\n const visit = (node: ts.Node): void => {\n collectProxy(collection, node);\n collectVariableInstance(collection, node);\n collectPropertyInstance(collection, node);\n ts.forEachChild(node, visit);\n };\n visit(collection.source);\n}\n","import type {\n ExecutableSymbolFact,\n PackageFacts,\n} from '../types.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport type { PackageEntrypointManifest } from './package-json-parser.js';\nimport {\n analyzePackagePublicSurface,\n type PackagePublicSurfaceAnalysis,\n type SymbolPublicSurfaceEvidence,\n} from './003-package-public-surface.js';\nimport type { RepositorySourceContext } from './ts-project.js';\n\nfunction symbolIdentity(\n symbol: Pick<\n ExecutableSymbolFact,\n 'sourceFile' | 'kind' | 'qualifiedName' | 'startOffset' | 'endOffset'\n >,\n): string {\n return [\n symbol.sourceFile,\n symbol.kind,\n symbol.qualifiedName,\n symbol.startOffset,\n symbol.endOffset,\n ].join('\\0');\n}\n\nfunction exposureBySymbol(\n analysis: PackagePublicSurfaceAnalysis,\n): Map<string, SymbolPublicSurfaceEvidence> {\n return new Map(analysis.symbols.map((item) => [\n symbolIdentity({\n sourceFile: item.target.sourceFile,\n kind: item.target.kind,\n qualifiedName: item.target.qualifiedName,\n startOffset: item.target.startOffset,\n endOffset: item.target.endOffset,\n }),\n item,\n ]));\n}\n\nexport function analyzeRepositoryPackageSurface(\n facts: PackageFacts,\n manifest: PackageEntrypointManifest,\n sources: RepositorySourceContext,\n): PackagePublicSurfaceAnalysis {\n const modules = sources.entries()\n .filter((snapshot) => /\\.[jt]s$/.test(snapshot.filePath))\n .map((snapshot) => ({\n sourceFile: normalizePath(snapshot.filePath),\n source: snapshot.sourceFile(),\n }));\n return analyzePackagePublicSurface(facts.packageName, manifest, modules);\n}\n\nexport function mergePackageSymbolEvidence(\n symbols: readonly ExecutableSymbolFact[],\n analysis: PackagePublicSurfaceAnalysis,\n): ExecutableSymbolFact[] {\n const exposures = exposureBySymbol(analysis);\n return symbols.map((symbol) => {\n const exposure = exposures.get(symbolIdentity(symbol));\n if (!exposure) return symbol;\n return {\n ...symbol,\n importExportEvidence: {\n ...(symbol.importExportEvidence ?? {}),\n packagePublicSurface: {\n schema: analysis.surface.schema,\n recordCap: analysis.surface.recordCap,\n bodyEligibility: exposure.target.bodyEligibility,\n exposures: exposure.exposures,\n exposureTotal: exposure.exposureTotal,\n shownExposureCount: exposure.shownExposureCount,\n omittedExposureCount: exposure.omittedExposureCount,\n },\n },\n };\n });\n}\n","import { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nexport async function sha256File(filePath: string): Promise<string> {\n return createHash('sha256')\n .update(await readFile(filePath))\n .digest('hex');\n}\nexport function sha256Text(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n","import type { Db } from './connection.js';\nimport { ANALYZER_VERSION } from '../version.js';\nimport {\n parsePackageImportReference,\n} from '../parsers/012-package-fact-contract.js';\n\ninterface PackageCallRow {\n id: number;\n repoId: number;\n evidence: Record<string, unknown>;\n}\n\nexport interface PackageInvalidationBatch {\n publishingRepoIds: ReadonlySet<number>;\n affectedCallerRepoIds: Set<number>;\n affectedWorkspaceIds: Set<number>;\n}\n\nconst resolverKeys = new Set([\n 'candidateStrategy', 'candidateCount', 'eligibleCandidateCount',\n 'selectedCandidateCount', 'candidateSetComplete', 'resolvedModulePath',\n 'resolvedTargetRepositoryId', 'unresolvedReason',\n 'targetRepositoryCandidateCount', 'targetRepositoryCandidates',\n 'shownTargetRepositoryCandidateCount',\n 'omittedTargetRepositoryCandidateCount', 'publicSurface',\n]);\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown> : undefined;\n}\n\nfunction parsedEvidence(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== 'string') return undefined;\n try {\n return record(JSON.parse(value) as unknown);\n } catch {\n return undefined;\n }\n}\n\nfunction packageName(evidence: Record<string, unknown>): string | undefined {\n return parsePackageImportReference(evidence.importBinding)\n ?.requestedPackageName ?? undefined;\n}\n\nfunction packageCallEvidenceValid(\n evidence: Record<string, unknown>,\n): boolean {\n const binding = record(evidence.importBinding);\n const classified = evidence.relation === 'package_import'\n || binding?.moduleKind === 'package';\n return !classified || packageName(evidence) !== undefined;\n}\n\nfunction currentCalls(\n db: Db,\n workspaceId: number,\n targetRepoId: number,\n): PackageCallRow[] {\n const rows = db.prepare(`SELECT sc.id,sc.repo_id repoId,\n sc.evidence_json evidenceJson FROM symbol_calls sc\n JOIN repositories r ON r.id=sc.repo_id\n WHERE r.workspace_id=? AND r.id<>? AND r.fact_analyzer_version=?\n ORDER BY sc.id`).all(workspaceId, targetRepoId, ANALYZER_VERSION);\n return rows.flatMap((row) => {\n const evidence = parsedEvidence(row.evidenceJson);\n if (!evidence || typeof row.id !== 'number'\n || typeof row.repoId !== 'number')\n throw new Error('invalid_current_package_import_evidence');\n if (!packageCallEvidenceValid(evidence))\n throw new Error('invalid_current_package_import_evidence');\n return evidence.relation === 'package_import'\n || record(evidence.importBinding)?.moduleKind === 'package'\n ? [{ id: row.id, repoId: row.repoId, evidence }]\n : [];\n });\n}\n\nfunction pendingEvidence(evidence: Record<string, unknown>): string {\n const parser = Object.fromEntries(Object.entries(evidence).filter(\n ([key]) => !resolverKeys.has(key),\n ));\n if (!packageName(parser))\n throw new Error('invalid_current_package_import_evidence');\n return JSON.stringify({\n ...parser,\n candidateStrategy: 'package_import_pending',\n candidateCount: 0,\n eligibleCandidateCount: 0,\n selectedCandidateCount: 0,\n candidateSetComplete: false,\n unresolvedReason: 'package_resolution_pending',\n });\n}\n\nfunction targetWorkspace(\n db: Db,\n repoId: number,\n): { workspaceId: number; packageName?: string | null } {\n const row = db.prepare(`SELECT workspace_id workspaceId,\n package_name packageName FROM repositories WHERE id=?`).get(repoId);\n if (typeof row?.workspaceId !== 'number')\n throw new Error('Repository target is missing its workspace');\n return {\n workspaceId: row.workspaceId,\n packageName: typeof row.packageName === 'string'\n || row.packageName === null ? row.packageName : undefined,\n };\n}\n\nfunction packageIdentityChanged(\n previous: string | null | undefined,\n next: string | undefined,\n): boolean {\n const previousName = typeof previous === 'string' ? previous : null;\n const nextName = typeof next === 'string' ? next : null;\n return previousName !== nextName;\n}\n\nexport function invalidatePackageTargetFacts(\n db: Db,\n targetRepoId: number,\n newPackageName: string | undefined,\n batch: PackageInvalidationBatch,\n): void {\n const target = targetWorkspace(db, targetRepoId);\n const names = new Set(\n [target.packageName, newPackageName].filter(\n (value): value is string => typeof value === 'string' && value.length > 0,\n ),\n );\n if (names.size === 0) return;\n const update = db.prepare(`UPDATE symbol_calls SET callee_symbol_id=NULL,\n status='unresolved',unresolved_reason='package_resolution_pending',\n evidence_json=? WHERE id=?`);\n let matched = false;\n for (const call of currentCalls(db, target.workspaceId, targetRepoId)) {\n const requested = packageName(call.evidence);\n if (!requested || !names.has(requested)) continue;\n update.run(pendingEvidence(call.evidence), call.id);\n batch.affectedCallerRepoIds.add(call.repoId);\n matched = true;\n }\n if (matched || packageIdentityChanged(\n target.packageName, newPackageName,\n )) batch.affectedWorkspaceIds.add(target.workspaceId);\n}\n\nexport function createPackageInvalidationBatch(\n publishingRepoIds: readonly number[],\n): PackageInvalidationBatch {\n return {\n publishingRepoIds: new Set(publishingRepoIds),\n affectedCallerRepoIds: new Set(),\n affectedWorkspaceIds: new Set(),\n };\n}\n\nexport function finalizePackageTargetInvalidations(\n db: Db,\n batch: PackageInvalidationBatch,\n): void {\n const increment = db.prepare(`UPDATE repositories\n SET fact_generation=fact_generation+1 WHERE id=?`);\n for (const repoId of batch.affectedCallerRepoIds)\n if (!batch.publishingRepoIds.has(repoId)) increment.run(repoId);\n const stale = db.prepare(`UPDATE repositories\n SET graph_stale_reason='package_target_facts_changed',\n graph_stale_at=datetime('now') WHERE workspace_id=?`);\n for (const workspaceId of batch.affectedWorkspaceIds)\n stale.run(workspaceId);\n}\n","import type { Db } from '../db/connection.js';\n\ninterface ExtensionRow {\n id: number;\n repoId: number;\n serviceName: string;\n qualifiedName: string;\n sourceFile: string;\n moduleSpecifier?: string | null;\n importedSymbol?: string | null;\n importKind?: string | null;\n}\ninterface BaseRow { id: number; repoId: number }\n\ninterface DesiredOperation { id: number; operationType: string; operationName: string; operationPath: string; paramsJson: string; returnType: string | null; sourceFile: string; sourceLine: number }\ninterface ExistingOperation extends DesiredOperation { baseOperationId: number | null }\n\nexport function materializeCdsExtensionOperations(db: Db, workspaceId: number): void {\n const extensions = db.prepare(`SELECT s.id,r.id repoId,s.service_name serviceName,s.qualified_name qualifiedName,s.source_file sourceFile,s.extension_module_specifier moduleSpecifier,s.extension_imported_symbol importedSymbol,s.extension_import_kind importKind\n FROM cds_services s JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND s.is_extend=1`).all(workspaceId) as unknown as ExtensionRow[];\n db.transaction(() => {\n const changedRepos = new Set<number>();\n for (const extension of extensions) {\n if (reconcileExtension(db, workspaceId, extension)) changedRepos.add(extension.repoId);\n }\n for (const repoId of changedRepos) markRepositoryDerivedFactsChanged(db, repoId);\n });\n}\n\nfunction reconcileExtension(db: Db, workspaceId: number, extension: ExtensionRow): boolean {\n const bases = resolveBase(db, workspaceId, extension);\n const status = bases.length === 1 ? 'resolved' : bases.length > 1 ? 'ambiguous' : 'unresolved';\n const baseId = status === 'resolved' ? bases[0]?.id ?? null : null;\n const desired = baseId === null ? [] : desiredInheritedOperations(db, extension, baseId);\n const statusChanged = updateExtensionStatus(db, extension.id, status, baseId);\n const operationChanged = reconcileInheritedOperations(db, extension, desired);\n reconcileOperationSearchRows(db, extension.repoId);\n return statusChanged || operationChanged;\n}\n\nfunction desiredInheritedOperations(db: Db, extension: ExtensionRow, baseId: number): DesiredOperation[] {\n return db.prepare(\"SELECT id,operation_type operationType,operation_name operationName,operation_path operationPath,params_json paramsJson,return_type returnType,source_file sourceFile,source_line sourceLine FROM cds_operations WHERE service_id=? AND provenance='direct' AND NOT EXISTS (SELECT 1 FROM cds_operations direct WHERE direct.service_id=? AND direct.provenance='direct' AND direct.operation_name=cds_operations.operation_name AND direct.operation_path=cds_operations.operation_path) ORDER BY operation_name,operation_path,id\").all(baseId, extension.id) as unknown as DesiredOperation[];\n}\n\nfunction updateExtensionStatus(db: Db, serviceId: number, status: string, baseId: number | null): boolean {\n const row = db.prepare('SELECT extension_base_status status,extension_base_service_id baseId FROM cds_services WHERE id=?').get(serviceId) as { status?: string | null; baseId?: number | null } | undefined;\n if (row?.status === status && (row.baseId ?? null) === baseId) return false;\n db.prepare('UPDATE cds_services SET extension_base_status=?, extension_base_service_id=? WHERE id=?').run(status, baseId, serviceId);\n return true;\n}\n\nfunction reconcileInheritedOperations(db: Db, extension: ExtensionRow, desired: DesiredOperation[]): boolean {\n const existing = db.prepare(\"SELECT id,operation_type operationType,operation_name operationName,operation_path operationPath,params_json paramsJson,return_type returnType,source_file sourceFile,source_line sourceLine,base_operation_id baseOperationId FROM cds_operations WHERE service_id=? AND provenance='inherited'\").all(extension.id) as unknown as ExistingOperation[];\n const desiredKeys = new Set(desired.map((row) => `${row.operationName}\\0${row.operationPath}`));\n const byKey = new Map(existing.map((row) => [`${row.operationName}\\0${row.operationPath}`, row]));\n let changed = false;\n for (const row of existing) {\n if (desiredKeys.has(`${row.operationName}\\0${row.operationPath}`)) continue;\n db.prepare('DELETE FROM cds_operations WHERE id=?').run(row.id);\n changed = true;\n }\n const update = db.prepare('UPDATE cds_operations SET operation_type=?,params_json=?,return_type=?,source_file=?,source_line=?,base_operation_id=? WHERE id=?');\n const add = db.prepare(\"INSERT INTO cds_operations(service_id,operation_type,operation_name,operation_path,params_json,return_type,source_file,source_line,provenance,base_operation_id) VALUES(?,?,?,?,?,?,?,?,'inherited',?)\");\n for (const row of desired) {\n const current = byKey.get(`${row.operationName}\\0${row.operationPath}`);\n if (current && operationMatches(current, row)) continue;\n if (current) update.run(row.operationType, row.paramsJson, row.returnType, row.sourceFile, row.sourceLine, row.id, current.id);\n else add.run(extension.id, row.operationType, row.operationName, row.operationPath, row.paramsJson, row.returnType, row.sourceFile, row.sourceLine, row.id);\n changed = true;\n }\n return changed;\n}\n\nfunction operationMatches(current: ExistingOperation, desired: DesiredOperation): boolean {\n return current.operationType === desired.operationType && current.paramsJson === desired.paramsJson && current.returnType === desired.returnType && current.sourceFile === desired.sourceFile && current.sourceLine === desired.sourceLine && current.baseOperationId === desired.id;\n}\n\nfunction reconcileOperationSearchRows(db: Db, repoId: number): void {\n db.prepare(\"DELETE FROM search_index WHERE repo=? AND kind='operation'\").run(String(repoId));\n db.prepare(`INSERT INTO search_index(kind,name,path,repo)\n SELECT 'operation',o.operation_name,o.operation_path,?\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id\n WHERE s.repo_id=? ORDER BY o.operation_name,o.operation_path,o.id`).run(String(repoId), repoId);\n}\n\nfunction markRepositoryDerivedFactsChanged(db: Db, repoId: number): void {\n db.prepare(\"UPDATE repositories SET fact_generation=COALESCE(fact_generation,0)+1, graph_stale_reason='derived_facts_changed', graph_stale_at=? WHERE id=?\").run(new Date().toISOString(), repoId);\n}\n\nfunction resolveBase(db: Db, workspaceId: number, extension: ExtensionRow): BaseRow[] {\n const symbol = extension.importedSymbol ?? extension.serviceName;\n if (extension.importKind === 'relative' && extension.moduleSpecifier) return relativeBase(db, extension, symbol);\n if (extension.importKind === 'package' && extension.moduleSpecifier) return packageBase(db, workspaceId, extension.moduleSpecifier, symbol);\n return sameRepoBase(db, extension, symbol);\n}\n\nfunction relativeBase(db: Db, extension: ExtensionRow, symbol: string): BaseRow[] {\n const modulePath = normalizeModulePath(extension.sourceFile, extension.moduleSpecifier ?? '');\n return db.prepare(`SELECT s.id,s.repo_id repoId FROM cds_services s WHERE s.repo_id=? AND s.is_extend=0 AND (s.qualified_name=? OR s.service_name=?) AND (s.source_file=? OR s.source_file=?) ORDER BY s.id`).all(extension.repoId, symbol, symbol, modulePath, `${modulePath}.cds`) as unknown as BaseRow[];\n}\n\nfunction packageBase(db: Db, workspaceId: number, specifier: string, symbol: string): BaseRow[] {\n const packageName = packageNameFromSpecifier(specifier);\n const moduleSuffix = specifier.slice(packageName.length).replace(/^\\//, '');\n return db.prepare(`SELECT s.id,s.repo_id repoId FROM cds_services s JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND s.is_extend=0 AND r.package_name=? AND (s.qualified_name=? OR s.service_name=?) AND (?='' OR s.source_file=? OR s.source_file=?) ORDER BY s.id`).all(workspaceId, packageName, symbol, symbol, moduleSuffix, moduleSuffix, `${moduleSuffix}.cds`) as unknown as BaseRow[];\n}\n\nfunction sameRepoBase(db: Db, extension: ExtensionRow, symbol: string): BaseRow[] {\n return db.prepare('SELECT id,repo_id repoId FROM cds_services WHERE repo_id=? AND is_extend=0 AND (qualified_name=? OR service_name=?) ORDER BY id').all(extension.repoId, symbol, symbol) as unknown as BaseRow[];\n}\n\nfunction normalizeModulePath(sourceFile: string, specifier: string): string {\n const base = sourceFile.split('/').slice(0, -1).join('/');\n const parts = `${base}/${specifier}`.split('/');\n const out: string[] = [];\n for (const part of parts) {\n if (!part || part === '.') continue;\n if (part === '..') out.pop();\n else out.push(part);\n }\n return out.join('/').replace(/\\.cds$/, '');\n}\n\nfunction packageNameFromSpecifier(specifier: string): string {\n const parts = specifier.split('/');\n return specifier.startsWith('@') ? `${parts[0]}/${parts[1]}` : parts[0] ?? specifier;\n}\n","import type { Db } from '../db/connection.js';\nimport { listRepositories, reposByName } from '../db/repositories.js';\nimport { errorMessage } from '../utils/diagnostics.js';\nimport { prepareRepositoryIndex, publishPreparedRepositoryIndex, recordIndexFailure, type PreparedRepositoryIndex } from './repository-indexer.js';\nimport { materializeCdsExtensionOperations } from './cds-extension-resolver.js';\nimport {\n createPackageInvalidationBatch,\n finalizePackageTargetInvalidations,\n} from '../db/004-package-target-invalidation.js';\n// Ownerless rows predate PID coordination; this matches doctor's stale-run threshold without taking over a recent legacy writer.\nconst LEGACY_OWNER_RECOVERY_MS = 60 * 60 * 1_000;\ntype RunningIndexRow = Record<string, unknown>;\nfunction ownerPid(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n ? value\n : undefined;\n}\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // Only ESRCH proves that ownership ended; permission and platform errors must fail closed.\n const ownerIsMissing = typeof error === 'object'\n && error !== null\n && 'code' in error\n && error.code === 'ESRCH';\n return !ownerIsMissing;\n }\n}\nfunction isRecoverableRun(row: RunningIndexRow, now: number): boolean {\n const pid = ownerPid(row.ownerPid);\n if (pid !== undefined) return !processIsAlive(pid);\n if (typeof row.startedAt !== 'string') return false;\n const startedAt = Date.parse(row.startedAt);\n return Number.isFinite(startedAt) && now - startedAt >= LEGACY_OWNER_RECOVERY_MS;\n}\nfunction recoveredOwnerMessage(row: RunningIndexRow): string {\n const pid = ownerPid(row.ownerPid);\n return pid === undefined\n ? 'Recovered stale legacy index writer without owner process metadata.'\n : `Recovered stale index writer because owner process ${pid} is no longer running.`;\n}\nexport function claimIndexRun(\n db: Db,\n workspaceId: number,\n repoCount: number,\n): number {\n // The short write transaction serializes claims without holding a SQLite writer lock during source preparation.\n try {\n return db.transaction(() => {\n const now = Date.now();\n const rows = db\n .prepare(\"SELECT id,workspace_id workspaceId,owner_pid ownerPid,started_at startedAt FROM index_runs WHERE status='running' ORDER BY id\")\n .all();\n const active = rows.find((row) => !isRecoverableRun(row, now));\n if (active) {\n const pid = ownerPid(active.ownerPid);\n const owner = pid === undefined ? 'an unknown owner' : `process ${pid}`;\n throw new Error(`index_writer_active: this database is already being indexed for workspace ${String(active.workspaceId ?? 'unknown')} by ${owner}; wait for that writer to finish.`);\n }\n const finish = db.prepare(\n \"UPDATE index_runs SET finished_at=?,status='failed',error_message=? WHERE id=?\",\n );\n for (const row of rows)\n finish.run(new Date(now).toISOString(), recoveredOwnerMessage(row), row.id);\n const inserted = db\n .prepare('INSERT INTO index_runs(workspace_id,started_at,status,repo_count,file_count,diagnostic_count,owner_pid) VALUES(?,?,?,?,?,?,?) RETURNING id')\n .get(workspaceId, new Date(now).toISOString(), 'running', repoCount, 0, 0, process.pid);\n const runId = Number(inserted?.id);\n if (!Number.isSafeInteger(runId)) throw new Error('index_writer_claim_failed: SQLite did not return an index run identifier.');\n return runId;\n });\n } catch (error) {\n if (/\\b(?:locked|busy)\\b/i.test(errorMessage(error)))\n throw new Error(\n 'index_writer_coordination_failed: SQLite remained busy beyond the bounded writer-claim interval; wait for the active publication to finish.',\n { cause: error },\n );\n throw error;\n }\n}\nexport async function indexWorkspace(\n db: Db,\n workspaceId: number,\n options: { repo?: string; force: boolean; injectDerivedMaterializationFailure?: boolean },\n): Promise<{ repoCount: number; indexedCount: number; skippedCount: number; fileCount: number; diagnosticCount: number }> {\n const repos = selectedRepositories(db, workspaceId, options.repo);\n const runId = claimIndexRun(db, workspaceId, repos.length);\n const state: PreparationState = {\n fileCount: 0, diagnosticCount: 0, skippedCount: 0, rows: [],\n };\n try {\n await prepareRepositories(repos, options.force, state);\n publishPreparedRows(db, workspaceId, options, runId, state);\n return indexSummary(repos.length, state);\n } catch (error) {\n finishFailedRun(db, runId, state, error);\n if (state.activeRepoId && state.rows.length < repos.length)\n recordIndexFailure(db, state.activeRepoId, error);\n throw error;\n }\n}\n\ntype IndexRepository = ReturnType<typeof listRepositories>[number];\ninterface PreparationState {\n fileCount: number;\n diagnosticCount: number;\n skippedCount: number;\n rows: PreparedRepositoryIndex[];\n activeRepoId?: number;\n}\n\nfunction selectedRepositories(\n db: Db,\n workspaceId: number,\n repoName: string | undefined,\n): IndexRepository[] {\n const repos = repoName\n ? reposByName(db, repoName, workspaceId)\n : listRepositories(db, workspaceId);\n if (repoName && repos.length === 0)\n throw new Error(\n `selector_repo_not_found: no indexed repository matched ${repoName}.`,\n );\n if (repoName && repos.length > 1)\n throw new Error(\n `selector_repo_ambiguous: repository selector ${repoName} matched ${repos.length} repositories; use a unique repository name.`,\n );\n return repos;\n}\n\nasync function prepareRepositories(\n repos: readonly IndexRepository[],\n force: boolean,\n state: PreparationState,\n): Promise<void> {\n for (const repo of repos) {\n state.activeRepoId = repo.id;\n const result = await prepareRepositoryIndex(repo, force);\n state.rows.push(result);\n state.fileCount += result.fileCount;\n state.diagnosticCount += result.diagnosticCount;\n state.skippedCount += result.skipped ? 1 : 0;\n }\n}\n\nfunction publishPreparedRows(\n db: Db,\n workspaceId: number,\n options: { injectDerivedMaterializationFailure?: boolean },\n runId: number,\n state: PreparationState,\n): void {\n db.transaction(() => {\n const invalidations = createPackageInvalidationBatch(\n state.rows.filter((row) => !row.skipped).map((row) => row.repo.id),\n );\n for (const row of state.rows) {\n state.activeRepoId = row.repo.id;\n publishPreparedRepositoryIndex(db, row, invalidations);\n }\n if (options.injectDerivedMaterializationFailure)\n throw new Error('Injected derived materialization failure');\n materializeCdsExtensionOperations(db, workspaceId);\n finalizePackageTargetInvalidations(db, invalidations);\n finishSuccessfulRun(db, runId, state);\n });\n}\n\nfunction finishSuccessfulRun(\n db: Db,\n runId: number,\n state: PreparationState,\n): void {\n db.prepare(`UPDATE index_runs SET finished_at=?,status='success',\n file_count=?,diagnostic_count=? WHERE id=?`).run(\n new Date().toISOString(), state.fileCount, state.diagnosticCount, runId,\n );\n}\n\nfunction finishFailedRun(\n db: Db,\n runId: number,\n state: PreparationState,\n error: unknown,\n): void {\n db.prepare(`UPDATE index_runs SET finished_at=?,status='failed',\n file_count=?,diagnostic_count=?,error_message=? WHERE id=?`).run(\n new Date().toISOString(), state.fileCount, state.diagnosticCount + 1,\n errorMessage(error), runId,\n );\n}\n\nfunction indexSummary(\n repoCount: number,\n state: PreparationState,\n): {\n repoCount: number;\n indexedCount: number;\n skippedCount: number;\n fileCount: number;\n diagnosticCount: number;\n} {\n return {\n repoCount,\n indexedCount: repoCount - state.skippedCount,\n skippedCount: state.skippedCount,\n fileCount: state.fileCount,\n diagnosticCount: state.diagnosticCount,\n };\n}\n","import {\n projectBoundedInOrder,\n type BoundedProjection,\n} from '../utils/000-bounded-projection.js';\n\ntype Diagnostic = Record<string, unknown>;\n\nconst boundedDoctorArrayKeys = new Set([\n 'candidates',\n 'candidateScores',\n 'candidateFamilies',\n 'candidateEvidence',\n 'candidatePaths',\n 'candidateRawPaths',\n 'candidateNormalizedOperationPaths',\n 'normalizedCandidateOperations',\n 'candidateLiterals',\n 'bindingCandidates',\n 'bindingAlternatives',\n 'registrations',\n 'implementationHintSuggestions',\n 'selectableImplementationRepositories',\n 'matchedHints',\n 'candidateSuggestions',\n 'dynamicTargetCandidates',\n 'dynamicTargetCandidateSuggestions',\n 'rejectedCandidates',\n 'suggestedVarSets',\n 'copyableExamples',\n 'examples',\n 'expandedExamples',\n 'selectorSuggestions',\n 'serviceSuggestions',\n 'repositories',\n]);\n\nexport function boundDoctorDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] {\n return diagnostics.map(boundDoctorDiagnostic);\n}\n\nfunction boundDoctorDiagnostic(diagnostic: Diagnostic): Diagnostic {\n const bounded = boundDoctorValue(diagnostic);\n return isDiagnostic(bounded) ? bounded : {};\n}\n\nfunction boundDoctorValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(boundDoctorValue);\n if (!isDiagnostic(value)) return value;\n const input = value;\n const output: Diagnostic = {};\n for (const [key, child] of Object.entries(input)) {\n if (!Array.isArray(child) || !boundedDoctorArrayKeys.has(key)) {\n output[key] = boundDoctorValue(child);\n continue;\n }\n // Doctor producers already query or assemble deterministic semantic order.\n const projection = projectBoundedInOrder(child.map(boundDoctorValue));\n output[key] = projection.items;\n addProjectionMetadata(output, input, key, projection);\n }\n return output;\n}\n\nfunction isDiagnostic(value: unknown): value is Diagnostic {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction addProjectionMetadata(\n output: Diagnostic,\n input: Diagnostic,\n key: string,\n projection: BoundedProjection<unknown>,\n): void {\n const names = projectionNames(key);\n const total = Math.max(\n numericValue(input[names.total]),\n projection.totalCount,\n siblingCollectionCount(input, key),\n );\n output[names.total] = total;\n output[names.shown] = projection.shownCount;\n output[names.omitted] = Math.max(0, total - projection.shownCount);\n}\n\nfunction siblingCollectionCount(input: Diagnostic, key: string): number {\n if (key !== 'examples' || !Array.isArray(input.expandedExamples)) return 0;\n return input.expandedExamples.length;\n}\n\nfunction projectionNames(key: string): { total: string; shown: string; omitted: string } {\n const stem = projectionStem(key);\n return {\n total: `${stem}Count`,\n shown: `shown${upperFirst(stem)}Count`,\n omitted: `omitted${upperFirst(stem)}Count`,\n };\n}\n\nfunction projectionStem(key: string): string {\n const stems: Record<string, string> = {\n candidates: 'candidate',\n candidateScores: 'candidateScore',\n candidateFamilies: 'candidateFamily',\n candidateEvidence: 'candidateEvidence',\n candidatePaths: 'candidatePath',\n candidateRawPaths: 'candidateRawPath',\n candidateNormalizedOperationPaths: 'candidateNormalizedOperationPath',\n normalizedCandidateOperations: 'normalizedCandidateOperation',\n candidateLiterals: 'candidateLiteral',\n bindingCandidates: 'bindingCandidate',\n bindingAlternatives: 'bindingAlternative',\n registrations: 'registration',\n implementationHintSuggestions: 'implementationHintSuggestion',\n selectableImplementationRepositories: 'selectableImplementationRepository',\n matchedHints: 'matchedHint',\n candidateSuggestions: 'candidateSuggestion',\n dynamicTargetCandidates: 'dynamicTargetCandidate',\n dynamicTargetCandidateSuggestions: 'dynamicTargetCandidateSuggestion',\n rejectedCandidates: 'rejectedCandidate',\n suggestedVarSets: 'suggestedVarSet',\n copyableExamples: 'copyableExample',\n examples: 'example',\n expandedExamples: 'expandedExample',\n selectorSuggestions: 'selectorSuggestion',\n serviceSuggestions: 'serviceSuggestion',\n };\n return stems[key] ?? 'repository';\n}\n\nfunction numericValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction upperFirst(value: string): string {\n return value ? `${value[0]?.toUpperCase() ?? ''}${value.slice(1)}` : value;\n}\n","import type { Db } from '../db/connection.js';\nimport { factLifecycleDiagnostic } from '../db/001-fact-lifecycle.js';\nimport { ANALYZER_VERSION } from '../version.js';\n\ntype Diagnostic = Record<string, unknown>;\n\nexport function linkUpgradeWarnings(\n db: Db,\n workspaceId?: number,\n): Diagnostic[] {\n const lifecycle = factLifecycleDiagnostic(db, workspaceId);\n if (lifecycle) return [lifecycle];\n return [\n ...schemaDriftDiagnostics(db, true, workspaceId),\n ...analyzerVersionDiagnostics(db, true, workspaceId),\n ].filter((item) => [\n 'schema_legacy_columns_present',\n 'external_target_columns_missing_data',\n 'reindex_required_after_upgrade',\n 'reindex_required_after_analyzer_upgrade',\n ].includes(String(item.code)));\n}\n\nexport function schemaDriftDiagnostics(\n db: Db,\n strict: boolean,\n workspaceId?: number,\n): Diagnostic[] {\n if (!strict) return [];\n const columns = db.prepare('PRAGMA table_info(symbols)').all() as Array<{ name?: string }>;\n const legacy = columns.filter((row) => [\n 'external_target_kind', 'external_target_id', 'external_target_label',\n 'external_target_dynamic',\n ].includes(String(row.name))).map((row) => row.name);\n const missing = db.prepare(`SELECT c.id id,c.source_file sourceFile,\n c.source_line sourceLine FROM outbound_calls c\n JOIN repositories r ON r.id=c.repo_id\n WHERE c.call_type='external_http'\n AND (? IS NULL OR r.workspace_id=?)\n AND (c.external_target_id IS NULL OR c.external_target_label IS NULL\n OR c.external_target_kind IS NULL) LIMIT 20`).all(\n workspaceId, workspaceId,\n ) as Diagnostic[];\n const out: Diagnostic[] = [];\n if (legacy.length > 0) out.push({ severity: 'warning', code: 'schema_legacy_columns_present', message: 'Legacy external-target columns are present on symbols; run service-flow clean --db-only, then init/index/link to rebuild with the current schema.', scope: 'workspace', affectedColumns: legacy, remediation: 'service-flow clean --db-only && service-flow init <workspace> && service-flow index && service-flow link' });\n if (missing.length > 0) out.push({ severity: 'warning', code: 'external_target_columns_missing_data', message: 'External HTTP calls are missing queryable external target metadata; reindex is required after upgrade.', scope: 'workspace', affectedRows: missing, remediation: 'service-flow index --force && service-flow link' });\n if (legacy.length > 0 || missing.length > 0) out.push({ severity: 'warning', code: 'reindex_required_after_upgrade', message: 'This database cannot be made equivalent to a fresh index by relink alone.', scope: 'workspace', remediation: 'Rebuild or force reindex the workspace, then run service-flow doctor --strict.' });\n return out;\n}\n\nexport function analyzerVersionDiagnostics(\n db: Db,\n strict: boolean,\n workspaceId?: number,\n): Diagnostic[] {\n if (!strict) return [];\n const rows = db.prepare(`SELECT name,\n COALESCE(fact_analyzer_version,'legacy') factAnalyzerVersion\n FROM repositories WHERE index_status='indexed'\n AND (? IS NULL OR workspace_id=?)\n AND COALESCE(fact_analyzer_version,'legacy')<>?`).all(\n workspaceId, workspaceId, ANALYZER_VERSION,\n ) as Diagnostic[];\n if (rows.length === 0) return [];\n return [{ severity: 'warning', code: 'reindex_required_after_analyzer_upgrade', message: 'Repository facts were produced by an older or unknown analyzer; run service-flow index --force before relink to apply current parser semantics.', scope: 'workspace', affectedRepositoryCount: rows.length, currentAnalyzerVersion: ANALYZER_VERSION, repositories: rows, remediation: 'service-flow index --force && service-flow link' }];\n}\n","import type { Db } from '../db/connection.js';\n\ntype Diagnostic = Record<string, unknown>;\n\nfunction pendingPredicate(alias: string): string {\n return `${alias}.status='unresolved'\n AND ${alias}.callee_symbol_id IS NULL\n AND ${alias}.unresolved_reason='package_resolution_pending'\n AND json_extract(${alias}.evidence_json,'$.relation')='package_import'\n AND json_extract(${alias}.evidence_json,\n '$.importBinding.moduleKind')='package'\n AND json_extract(${alias}.evidence_json,\n '$.candidateStrategy')='package_import_pending'\n AND json_extract(${alias}.evidence_json,'$.candidateCount')=0\n AND json_extract(${alias}.evidence_json,'$.eligibleCandidateCount')=0\n AND json_extract(${alias}.evidence_json,'$.selectedCandidateCount')=0\n AND json_extract(${alias}.evidence_json,'$.candidateSetComplete')=0`;\n}\n\nfunction count(db: Db, sql: string): number {\n return Number(db.prepare(sql).get()?.count ?? 0);\n}\n\nexport function packagePendingDiagnostics(db: Db): Diagnostic[] {\n const pending = count(db, `SELECT COUNT(*) count FROM symbol_calls sc\n WHERE ${pendingPredicate('sc')}`);\n if (pending === 0) return [];\n const stale = count(db, `SELECT COUNT(*) count FROM repositories\n WHERE graph_stale_reason IS NOT NULL`);\n return [{\n severity: 'warning',\n code: 'package_import_resolution_pending',\n message: 'Package-import facts await workspace linking; terminal package-resolution quality is deferred.',\n packageResolutionState: 'pre_link_pending',\n pendingPackageImportCount: pending,\n graphState: 'stale',\n staleRepositoryCount: stale,\n requiredAction: 'relink',\n remediation: 'service-flow link --workspace /workspace --force',\n }];\n}\n\nexport function symbolCallQuality(db: Db): Diagnostic {\n const terminal = `NOT (${pendingPredicate('sc')})`;\n const row = db.prepare(`SELECT COUNT(*) total,\n SUM(CASE WHEN sc.status='resolved' THEN 1 ELSE 0 END) resolved,\n SUM(CASE WHEN sc.status='unresolved' THEN 1 ELSE 0 END) unresolved\n FROM symbol_calls sc WHERE ${terminal}`).get();\n const top = db.prepare(`SELECT sc.callee_expression calleeExpression,\n COUNT(*) count FROM symbol_calls sc\n WHERE sc.status='unresolved' AND ${terminal}\n GROUP BY sc.callee_expression\n ORDER BY count DESC,sc.callee_expression COLLATE BINARY LIMIT 5`).all();\n const total = Number(row?.total ?? 0);\n const unresolved = Number(row?.unresolved ?? 0);\n const ratio = total === 0 ? 0 : Number((unresolved / total).toFixed(4));\n return {\n severity: ratio > 0.05 ? 'warning' : 'info',\n code: 'strict_symbol_call_quality',\n message: 'Terminal symbol-call quality aggregate',\n total,\n resolved: Number(row?.resolved ?? 0),\n unresolved,\n unresolvedRatio: ratio,\n unresolvedRatioThreshold: 0.05,\n topUnresolvedCallees: top,\n };\n}\n","import type { Db } from '../db/connection.js';\nimport { classifyODataPathIntent, normalizeODataOperationInvocationPath } from '../linker/odata-path-normalizer.js';\nimport { implementationHintSuggestions } from '../trace/implementation-hints.js';\nimport { boundDoctorDiagnostics } from './001-doctor-projection.js';\nimport { factLifecycleDiagnostic } from '../db/001-fact-lifecycle.js';\nimport {\n analyzerVersionDiagnostics,\n schemaDriftDiagnostics,\n} from './002-doctor-lifecycle.js';\nimport {\n packagePendingDiagnostics,\n symbolCallQuality,\n} from './003-doctor-package-resolution.js';\nexport { linkUpgradeWarnings } from './002-doctor-lifecycle.js';\n\ntype Diagnostic = Record<string, unknown>;\ninterface DoctorOptions {\n detail?: boolean;\n workspaceId?: number;\n}\n\nexport function doctorDiagnostics(db: Db, strict: boolean, options: DoctorOptions = {}): Diagnostic[] {\n const lifecycle = factLifecycleDiagnostic(db, options.workspaceId);\n if (lifecycle) return boundDoctorDiagnostics([lifecycle]);\n const globalLifecycle = options.workspaceId === undefined\n ? undefined : factLifecycleDiagnostic(db);\n if (globalLifecycle) return boundDoctorDiagnostics([\n ...schemaDriftDiagnostics(db, strict, options.workspaceId),\n ...analyzerVersionDiagnostics(db, strict, options.workspaceId),\n {\n severity: 'warning',\n code: 'workspace_detail_checks_deferred',\n message: 'Selected-workspace lifecycle is valid, but JSON-dependent global detail checks were deferred because another workspace requires reindexing.',\n remediation: 'Run doctor for the affected workspace after force index and link.',\n },\n ]);\n const diagnostics = db.prepare('SELECT severity,code,message,source_file sourceFile,source_line sourceLine FROM diagnostics ORDER BY id').all() as Diagnostic[];\n return boundDoctorDiagnostics([\n ...diagnostics,\n ...packagePendingDiagnostics(db),\n ...healthDiagnostics(db, strict),\n ...remoteTargetWithoutImplementationDiagnostics(db, strict, Boolean(options.detail)),\n ...localServiceDiagnostics(db, strict),\n ...schemaDriftDiagnostics(db, strict, options.workspaceId),\n ...analyzerVersionDiagnostics(db, strict, options.workspaceId),\n ...parserQualityDiagnostics(db, strict, options),\n ]);\n}\n\nfunction healthDiagnostics(db: Db, strict: boolean): Diagnostic[] {\n return db.prepare(\n `SELECT 'info' severity,'entity_only_service' code,'CDS service has no action/function/event operations; this can be valid for entity-only services' message,s.source_file sourceFile,s.source_line sourceLine\n FROM cds_services s LEFT JOIN cds_operations o ON o.service_id=s.id WHERE o.id IS NULL AND ?\n UNION ALL\n SELECT 'warning','extend_service_unresolved_base','Extend service has no indexed local operations; verify base service resolution',s.source_file,s.source_line\n FROM cds_services s LEFT JOIN cds_operations o ON o.service_id=s.id WHERE o.id IS NULL AND s.is_extend=1 AND ?\n UNION ALL\n SELECT 'warning','handler_without_service','Repository has handlers but no CDS services',hc.source_file,hc.source_line\n FROM handler_classes hc JOIN repositories r ON r.id=hc.repo_id\n WHERE r.kind IN ('cap-service','mixed') AND NOT EXISTS (SELECT 1 FROM cds_services s WHERE s.repo_id=hc.repo_id)\n UNION ALL\n SELECT 'warning','search_index_empty','Search index is empty after indexing',NULL,NULL\n WHERE NOT EXISTS (SELECT 1 FROM search_index)\n UNION ALL\n SELECT 'error','foreign_key_violation','SQLite foreign_key_check reported integrity failures',NULL,NULL\n WHERE EXISTS (SELECT 1 FROM pragma_foreign_key_check)\n UNION ALL\n SELECT 'warning','legacy_schema_weaker_foreign_keys','Legacy table lacks fresh-schema foreign-key metadata; rebuild the database or re-run init/index in a new database',NULL,NULL\n WHERE (SELECT COUNT(*) FROM pragma_foreign_key_list('graph_edges'))=0 OR (SELECT COUNT(*) FROM pragma_foreign_key_list('index_runs'))=0 OR (SELECT COUNT(*) FROM pragma_foreign_key_list('diagnostics'))=0\n UNION ALL\n SELECT CASE WHEN ? THEN 'warning' ELSE 'error' END,'local_service_calls_all_unresolved','All local service calls are unresolved; verify local service alias parsing and linking',NULL,NULL\n WHERE EXISTS (SELECT 1 FROM outbound_calls WHERE call_type='local_service_call') AND NOT EXISTS (SELECT 1 FROM graph_edges e JOIN outbound_calls c ON e.from_kind='call' AND c.id=CAST(e.from_id AS INTEGER) WHERE c.call_type='local_service_call' AND e.status='resolved')\n UNION ALL\n SELECT 'error','local_service_accessor_misclassified','Entity accessor calls were indexed as /entities operations',source_file,source_line\n FROM outbound_calls WHERE call_type='local_service_call' AND operation_path_expr='/entities' AND (? OR 1)\n UNION ALL\n SELECT 'warning','outbound_calls_without_source_symbol','Outbound calls lack source symbol ownership: ' || COUNT(*),NULL,NULL\n FROM outbound_calls WHERE source_symbol_id IS NULL AND ? HAVING COUNT(*) >= 1\n UNION ALL\n SELECT 'warning','trace_scope_fell_back_to_file','Trace may fall back to source-file scope for calls without symbols',NULL,NULL\n WHERE EXISTS (SELECT 1 FROM outbound_calls WHERE source_symbol_id IS NULL) AND ?\n UNION ALL\n SELECT 'warning','graph_stale','Graph is stale after repository fact changes; run service-flow link',NULL,NULL\n WHERE EXISTS (SELECT 1 FROM repositories WHERE graph_stale_reason IS NOT NULL)\n UNION ALL\n SELECT 'warning','index_run_abandoned','Index run ' || id || ' started at ' || started_at || ' is still running after the 60 minute abandonment threshold',NULL,NULL\n FROM index_runs WHERE status='running' AND datetime(started_at) < datetime('now','-60 minutes')`,\n ).all(strict, strict, strict, strict, strict, strict) as Diagnostic[];\n}\n\n\nfunction remoteTargetWithoutImplementationDiagnostics(db: Db, strict: boolean, detail: boolean): Diagnostic[] {\n if (!strict) return [];\n const groups = db.prepare(`SELECT s.service_path servicePath,o.operation_path operationPath,o.source_file sourceFile,o.source_line sourceLine,COUNT(*) callSiteCount\n FROM graph_edges remote JOIN cds_operations o ON o.id=CAST(remote.to_id AS INTEGER) JOIN cds_services s ON s.id=o.service_id\n WHERE remote.edge_type='REMOTE_CALL_RESOLVES_TO_OPERATION' AND remote.to_kind='operation'\n AND NOT EXISTS (SELECT 1 FROM graph_edges impl WHERE impl.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND impl.from_kind='operation' AND impl.from_id=remote.to_id)\n GROUP BY s.service_path,o.operation_path,o.source_file,o.source_line\n ORDER BY s.service_path,o.operation_path`).all() as Array<{ servicePath?: string; operationPath?: string; sourceFile?: string | null; sourceLine?: number | null; callSiteCount?: number }>;\n return groups.map((group) => {\n const examples = remoteTargetWithoutImplementationExamples(db, String(group.servicePath ?? ''), String(group.operationPath ?? ''));\n return {\n severity: 'warning',\n code: 'remote_target_without_implementation',\n message: `Remote target operation has no implementation edge: ${String(group.servicePath ?? '')}${String(group.operationPath ?? '')}`,\n sourceFile: group.sourceFile,\n sourceLine: group.sourceLine,\n servicePath: group.servicePath,\n operationPath: group.operationPath,\n callSiteCount: Number(group.callSiteCount ?? 0),\n examples: examples.slice(0, 3),\n expandedExamples: detail ? examples : undefined,\n };\n });\n}\n\nfunction remoteTargetWithoutImplementationExamples(db: Db, servicePath: string, operationPath: string): Diagnostic[] {\n return db.prepare(`SELECT r.name repo,c.source_file sourceFile,c.source_line sourceLine,c.operation_path_expr operationPathExpr\n FROM graph_edges remote JOIN cds_operations o ON o.id=CAST(remote.to_id AS INTEGER) JOIN cds_services s ON s.id=o.service_id\n LEFT JOIN outbound_calls c ON remote.from_kind='call' AND c.id=CAST(remote.from_id AS INTEGER)\n LEFT JOIN repositories r ON r.id=c.repo_id\n WHERE remote.edge_type='REMOTE_CALL_RESOLVES_TO_OPERATION' AND remote.to_kind='operation'\n AND s.service_path=? AND o.operation_path=?\n AND NOT EXISTS (SELECT 1 FROM graph_edges impl WHERE impl.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND impl.from_kind='operation' AND impl.from_id=remote.to_id)\n ORDER BY r.name,c.source_file,c.source_line`).all(servicePath, operationPath) as Diagnostic[];\n}\n\nfunction localServiceDiagnostics(db: Db, strict: boolean): Diagnostic[] {\n const rows = db.prepare(\"SELECT e.status status,e.unresolved_reason reason,e.evidence_json evidenceJson FROM graph_edges e JOIN outbound_calls c ON e.from_kind='call' AND c.id=CAST(e.from_id AS INTEGER) WHERE c.call_type='local_service_call'\").all() as Array<{ status?: string; reason?: string | null; evidenceJson?: string }>;\n const implementationContext = rows.filter((row) => row.status === 'resolved' && String(row.evidenceJson ?? '').includes('implementation_context_caller_ownership')).length;\n const withoutOwnership = rows.filter((row) => row.reason === 'local_service_candidate_without_caller_ownership' || String(row.evidenceJson ?? '').includes('local_service_candidate_without_caller_ownership')).length;\n const unresolved = rows.filter((row) => row.status === 'unresolved').length;\n const outsideScope = rows.filter((row) => row.status === 'unresolved' && candidateCount(row.evidenceJson) > 0).length;\n const out: Diagnostic[] = [];\n if (withoutOwnership > 0) out.push({ severity: 'warning', code: 'local_service_candidate_without_caller_ownership', message: `Local service calls have operation candidates but no caller ownership evidence: ${withoutOwnership}` });\n if (outsideScope > 0) out.push({ severity: 'warning', code: 'local_service_candidates_outside_local_scope', message: `Local service calls found candidates outside same-repository scope: ${outsideScope}` });\n if (strict && unresolved > 0) out.push({ severity: 'warning', code: 'local_service_calls_unresolved', message: `Unresolved local service calls: ${unresolved}` });\n if (strict && implementationContext > 0) out.push({ severity: 'info', code: 'local_service_calls_resolved_by_implementation_context', message: `Local service calls resolved by implementation-context ownership: ${implementationContext}` });\n return out;\n}\n\nfunction parserQualityDiagnostics(db: Db, strict: boolean, options: DoctorOptions): Diagnostic[] {\n if (!strict) return [];\n const symbol = symbolCallQuality(db);\n const dbq = dbQueryQuality(db);\n const outbound = outboundOwnershipQuality(db);\n return [\n identityAliasBindingQuality(db),\n remoteActionNoBindingQuality(db),\n contextualImplementationQuality(db),\n implementationCandidateQuality(db, Boolean(options.detail)),\n classInstanceNoiseQuality(db),\n contextualBindingPropagationQuality(db),\n serviceBindingQuality(db, Boolean(options.detail)),\n decoratorResolutionQuality(db),\n handlerRegistrationPairingQuality(db),\n nestedThisReceiverQuality(db),\n wrapperPathPropagationQuality(db),\n remoteQueryTargetQuality(db),\n remoteEntityOperationCollisionQuality(db),\n remoteEntityDynamicOperationFalsePositiveQuality(db),\n remoteActionTargetQuality(db),\n externalHttpTargetQuality(db),\n odataInvocationResolutionQuality(db),\n ...jsonEvidenceQuality(db),\n eventReceiverQuality(db),\n graphDynamicFlagQuality(db),\n symbol,\n dbq,\n outbound,\n ];\n}\n\nfunction jsonEvidenceQuality(db: Db): Diagnostic[] {\n const symbol = db.prepare(\"SELECT COUNT(*) total, SUM(CASE WHEN json_valid(evidence_json)=0 OR json_type(evidence_json) <> 'object' THEN 1 ELSE 0 END) nonObject FROM symbol_calls\").get() as Record<string, unknown>;\n const outbound = db.prepare(\"SELECT COUNT(*) total, SUM(CASE WHEN evidence_json IS NULL THEN 1 ELSE 0 END) missing, SUM(CASE WHEN evidence_json IS NOT NULL AND json_valid(evidence_json)=0 THEN 1 ELSE 0 END) invalid, SUM(CASE WHEN evidence_json IS NOT NULL AND json_valid(evidence_json)=1 AND json_type(evidence_json) <> 'object' THEN 1 ELSE 0 END) nonObject FROM outbound_calls\").get() as Record<string, unknown>;\n const graph = db.prepare(\"SELECT COUNT(*) total, SUM(CASE WHEN e.evidence_json IS NULL OR json_valid(e.evidence_json)=0 OR json_type(e.evidence_json) <> 'object' THEN 1 ELSE 0 END) nonObject, SUM(CASE WHEN e.evidence_json IS NOT NULL AND json_valid(e.evidence_json)=1 AND json_extract(e.evidence_json,'$.outboundEvidence.parser') IS NOT NULL THEN 1 ELSE 0 END) withOutboundEvidence FROM graph_edges e WHERE e.from_kind='call'\").get() as Record<string, unknown>;\n const outboundExamples = db.prepare(\"SELECT call_type callType,source_file sourceFile,source_line sourceLine FROM outbound_calls WHERE evidence_json IS NULL OR json_valid(evidence_json)=0 OR json_type(evidence_json) <> 'object' ORDER BY source_file,source_line LIMIT 10\").all() as Diagnostic[];\n const graphExamples = db.prepare(\"SELECT c.call_type callType,c.source_file sourceFile,c.source_line sourceLine,e.edge_type edgeType FROM graph_edges e JOIN outbound_calls c ON e.from_kind='call' AND c.id=CAST(e.from_id AS INTEGER) WHERE e.evidence_json IS NULL OR json_valid(e.evidence_json)=0 OR json_type(e.evidence_json) <> 'object' OR json_extract(e.evidence_json,'$.outboundEvidence.parser') IS NULL ORDER BY c.source_file,c.source_line LIMIT 10\").all() as Diagnostic[];\n return [\n { severity: Number(symbol.nonObject ?? 0) > 0 ? 'warning' : 'info', code: 'strict_symbol_call_evidence_quality', message: 'Symbol-call evidence JSON object aggregate', total: Number(symbol.total ?? 0), nonObject: Number(symbol.nonObject ?? 0) },\n { severity: Number(outbound.missing ?? 0) + Number(outbound.invalid ?? 0) + Number(outbound.nonObject ?? 0) > 0 ? 'warning' : 'info', code: 'strict_outbound_evidence_quality', message: 'Outbound parser evidence JSON object aggregate', total: Number(outbound.total ?? 0), missing: Number(outbound.missing ?? 0), invalid: Number(outbound.invalid ?? 0), nonObject: Number(outbound.nonObject ?? 0), examples: outboundExamples },\n { severity: Number(graph.nonObject ?? 0) > 0 || Number(graph.withOutboundEvidence ?? 0) < Number(graph.total ?? 0) ? 'warning' : 'info', code: 'strict_graph_evidence_quality', message: 'Call-derived graph evidence and parser-evidence propagation aggregate', total: Number(graph.total ?? 0), nonObject: Number(graph.nonObject ?? 0), withOutboundEvidence: Number(graph.withOutboundEvidence ?? 0), examples: graphExamples },\n ];\n}\n\nfunction dbQueryQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) total, SUM(CASE WHEN query_entity IS NOT NULL THEN 1 ELSE 0 END) known, SUM(CASE WHEN query_entity IS NULL THEN 1 ELSE 0 END) unknown FROM outbound_calls WHERE call_type='local_db_query'\").get() as Record<string, unknown>;\n const total = Number(row.total ?? 0);\n const unknown = Number(row.unknown ?? 0);\n const ratio = total === 0 ? 0 : Number((unknown / total).toFixed(4));\n return { severity: ratio > 0.25 ? 'warning' : 'info', code: 'strict_db_query_quality', message: 'Local DB query quality aggregate', total, known: Number(row.known ?? 0), unknown, unknownRatio: ratio, unknownRatioThreshold: 0.25 };\n}\n\nfunction outboundOwnershipQuality(db: Db): Diagnostic {\n const row = db.prepare('SELECT COUNT(*) total, SUM(CASE WHEN source_symbol_id IS NULL THEN 1 ELSE 0 END) withoutOwnership FROM outbound_calls').get() as Record<string, unknown>;\n const byType = db.prepare('SELECT call_type callType, COUNT(*) count FROM outbound_calls WHERE source_symbol_id IS NULL GROUP BY call_type ORDER BY count DESC, call_type').all() as Diagnostic[];\n const examples = db.prepare('SELECT call_type callType,source_file sourceFile,source_line sourceLine,unresolved_reason unresolvedReason FROM outbound_calls WHERE source_symbol_id IS NULL ORDER BY source_file,source_line LIMIT 10').all() as Diagnostic[];\n const total = Number(row.total ?? 0);\n const without = Number(row.withoutOwnership ?? 0);\n const ratio = total === 0 ? 0 : Number((without / total).toFixed(4));\n return { severity: ratio > 0.01 ? 'warning' : 'info', code: 'strict_outbound_source_ownership_quality', message: 'Outbound call source-symbol ownership aggregate', total, withoutOwnership: without, withoutOwnershipRatio: ratio, withoutOwnershipRatioThreshold: 0.01, ownerlessByType: byType, ownerlessExamples: examples };\n}\n\nfunction eventReceiverQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT SUM(CASE WHEN call_type IN ('async_emit','async_subscribe') THEN 1 ELSE 0 END) eventTotal, SUM(CASE WHEN call_type IN ('async_emit','async_subscribe') AND (json_extract(evidence_json,'$.receiverClassification') IS NULL OR json_extract(evidence_json,'$.receiverClassification') <> 'cap_evidence') THEN 1 ELSE 0 END) questionable FROM outbound_calls\").get() as Record<string, unknown>;\n return { severity: Number(row.questionable ?? 0) > 0 ? 'warning' : 'info', code: 'strict_event_receiver_classification_quality', message: 'CAP event receiver classification aggregate', eventTotal: Number(row.eventTotal ?? 0), questionable: Number(row.questionable ?? 0) };\n}\n\nfunction graphDynamicFlagQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) count FROM graph_edges WHERE status='terminal' AND is_dynamic=1\").get() as Record<string, unknown>;\n return { severity: Number(row.count ?? 0) > 0 ? 'warning' : 'info', code: 'strict_graph_dynamic_flag_consistency', message: 'Graph dynamic flag consistency aggregate', dynamicTerminalEdges: Number(row.count ?? 0) };\n}\n\nfunction implementationCandidateQuality(db: Db, detail: boolean): Diagnostic {\n const categories = [...implementationEdgeCategories(db, detail), missingParameterMetadataCategory(db, detail), dynamicWrapperCategory(db, detail)].filter((item) => item.count > 0);\n const total = categories.reduce((sum, item) => sum + item.count, 0);\n return { severity: total > 0 ? 'warning' : 'info', code: 'strict_implementation_candidate_quality', message: 'Implementation candidate ambiguity and rejection aggregate', total, summary: implementationSummary(categories), categories };\n}\n\nfunction implementationEdgeCategories(db: Db, detail: boolean): Array<Diagnostic & { count: number }> {\n const rows = db.prepare(`SELECT e.status,e.unresolved_reason unresolvedReason,e.evidence_json evidenceJson,o.operation_name operationName,base.operation_name baseOperation,s.service_path servicePath\n FROM graph_edges e JOIN cds_operations o ON o.id=CAST(e.from_id AS INTEGER)\n JOIN cds_services s ON s.id=o.service_id LEFT JOIN cds_operations base ON base.id=o.base_operation_id\n WHERE e.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND e.status IN ('ambiguous','unresolved') ORDER BY s.service_path,o.operation_name,e.id`).all() as Diagnostic[];\n const grouped = new Map<string, Diagnostic & { count: number; servicePaths: string[]; examples: Diagnostic[] }>();\n for (const row of rows) addImplementationCategory(grouped, row);\n return [...grouped.values()].map(({ servicePaths, ...item }) => ({\n ...item,\n servicePathPattern: pathPattern(servicePaths),\n suggestedAction: categoryAction(String(item.category)),\n suggestedHints: suggestedHints(item.examples),\n examples: item.examples.slice(0, 3),\n expandedExamples: detail ? item.examples : undefined,\n }));\n}\n\nfunction addImplementationCategory(grouped: Map<string, Diagnostic & { count: number; servicePaths: string[]; examples: Diagnostic[] }>, row: Diagnostic): void {\n const evidence = parseObject(row.evidenceJson);\n const category = implementationCategory(row, evidence);\n const family = candidateFamily(evidence);\n const reason = category === 'duplicate_package_name_candidates' ? 'duplicate_package_name_candidates' : String(row.unresolvedReason ?? category);\n const baseOperation = String(row.baseOperation ?? row.operationName ?? evidence.operationName ?? 'unknown');\n const key = [category, baseOperation, reason, family].join('\\0');\n const current = grouped.get(key) ?? { category, baseOperation, reason, candidateFamily: family, count: 0, servicePaths: [], examples: [] };\n const hintSuggestions = implementationSuggestions(evidence);\n const candidates = asRecords(evidence.candidates);\n const candidateCount = Math.max(\n numericValue(evidence.candidateCount),\n candidates.length,\n );\n current.count += 1;\n current.servicePaths.push(String(row.servicePath ?? evidence.servicePath ?? ''));\n current.examples.push({\n servicePath: row.servicePath,\n operation: row.operationName,\n status: row.status,\n reason: row.unresolvedReason,\n candidateCount,\n shownCandidateCount: Math.min(\n candidateCount,\n numericValue(evidence.shownCandidateCount) || candidates.length,\n ),\n omittedCandidateCount: Math.max(\n 0,\n candidateCount - (numericValue(evidence.shownCandidateCount) || candidates.length),\n ),\n candidateEvidence: candidates.slice(0, 3),\n implementationHintSuggestions: hintSuggestions,\n });\n grouped.set(key, current);\n}\n\nfunction implementationSuggestions(evidence: Diagnostic): Diagnostic[] | undefined {\n const persisted = asRecords(evidence.implementationHintSuggestions);\n const suggestions = persisted.length ? persisted : implementationHintSuggestions(evidence);\n return suggestions.length ? suggestions : undefined;\n}\n\nfunction suggestedHints(examples: Diagnostic[]): string[] | undefined {\n const hints = examples.flatMap((example) =>\n asRecords(example.implementationHintSuggestions)\n .flatMap((suggestion) => typeof suggestion.cli === 'string' ? [String(suggestion.cli)] : []));\n const unique = [...new Set(hints)].slice(0, 3);\n return unique.length ? unique : undefined;\n}\n\nfunction missingParameterMetadataCategory(db: Db, detail = false): Diagnostic & { count: number } {\n const examples = db.prepare(`SELECT sc.source_file sourceFile,sc.source_line sourceLine,sc.callee_expression calleeExpression\n FROM symbol_calls sc JOIN symbols s ON s.id=sc.callee_symbol_id\n WHERE sc.status='resolved' AND json_extract(sc.evidence_json,'$.callArguments[0].kind') IN ('identifier','object_literal')\n AND (s.evidence_json IS NULL OR json_extract(s.evidence_json,'$.parameterBindings') IS NULL)\n ORDER BY sc.source_file,sc.source_line`).all() as Diagnostic[];\n const row = db.prepare(`SELECT COUNT(*) count FROM symbol_calls sc JOIN symbols s ON s.id=sc.callee_symbol_id\n WHERE sc.status='resolved' AND json_extract(sc.evidence_json,'$.callArguments[0].kind') IN ('identifier','object_literal')\n AND (s.evidence_json IS NULL OR json_extract(s.evidence_json,'$.parameterBindings') IS NULL)`).get() as { count?: number };\n return { category: 'missing_parameter_metadata', reason: 'callee symbol is missing parameter binding metadata', candidateFamily: 'symbol_parameter_metadata', count: Number(row.count ?? 0), suggestedAction: categoryAction('missing_parameter_metadata'), examples: examples.slice(0, 3), expandedExamples: detail ? examples : undefined };\n}\n\nfunction dynamicWrapperCategory(db: Db, detail: boolean): Diagnostic & { count: number } {\n const rows = db.prepare(`SELECT source_file sourceFile,source_line sourceLine,\n json_extract(evidence_json,'$.receiver') receiverName,\n COALESCE(json_extract(evidence_json,'$.missingPathIdentifier'),json_extract(evidence_json,'$.operationPathExpression')) pathIdentifier\n FROM outbound_calls WHERE call_type='remote_action' AND unresolved_reason='dynamic_operation_path_identifier'\n ORDER BY source_file,source_line`).all() as Diagnostic[];\n return { category: 'dynamic_wrapper_paths', reason: 'wrapper path cannot be proven statically', candidateFamily: 'wrapper_path', count: rows.length, suggestedAction: categoryAction('dynamic_wrapper_paths'), examples: rows.slice(0, 3), expandedExamples: detail ? rows : undefined };\n}\n\nfunction implementationSummary(categories: Array<Diagnostic & { count: number }>): Diagnostic[] {\n const grouped = new Map<string, Diagnostic & { count: number }>();\n for (const category of categories) {\n const key = [category.category, category.candidateFamily, category.reason].join('\\0');\n const current = grouped.get(key) ?? { category: category.category, candidateFamily: category.candidateFamily, reason: category.reason, severity: 'warning', suggestedAction: category.suggestedAction, count: 0 };\n current.count += category.count;\n grouped.set(key, current);\n }\n return [...grouped.values()].sort((left, right) => String(left.category).localeCompare(String(right.category)) || String(left.candidateFamily).localeCompare(String(right.candidateFamily)));\n}\n\nfunction categoryAction(category: string): string {\n if (category === 'duplicate_package_name_candidates') return 'Use scoped --implementation-hint fields to select one repository for each ambiguous hop.';\n if (category === 'missing_strong_ownership_evidence') return 'Add an explicit package dependency, local service-path ownership, or registration ownership evidence.';\n if (category === 'missing_parameter_metadata') return 'Export a statically analyzable helper with named or destructured parameters.';\n if (category === 'dynamic_wrapper_paths') return 'Pass a literal path or provide the reported runtime identifier with --var key=value.';\n return 'Inspect the capped examples and add stronger implementation ownership evidence.';\n}\n\nfunction implementationCategory(row: Diagnostic, evidence: Diagnostic): string {\n const reasons = JSON.stringify([evidence.ambiguityReasons, evidence.candidateFamilies, evidence.candidates, row.unresolvedReason]);\n if (reasons.includes('duplicate_package_name_candidates')) return 'duplicate_package_name_candidates';\n if (reasons.includes('missing direct ownership')) return 'missing_strong_ownership_evidence';\n return String(row.status) === 'ambiguous' ? 'ambiguous_implementation_candidates' : 'rejected_implementation_candidates';\n}\n\nfunction candidateFamily(evidence: Diagnostic): string {\n const families = asRecords(evidence.candidateFamilies);\n const duplicate = families.find((row) => typeof row.packageName === 'string');\n if (duplicate?.packageName) return String(duplicate.packageName);\n const candidates = asRecords(evidence.candidates);\n const first = candidates.find((row) => parseObject(row.handlerPackage).packageName);\n return String(parseObject(first?.handlerPackage).packageName ?? 'unknown');\n}\n\nfunction pathPattern(paths: string[]): string {\n const values = [...new Set(paths.filter(Boolean))].sort();\n if (values.length <= 1) return values[0] ?? '';\n const prefix = commonPrefix(values);\n const suffix = commonSuffix(values.map((value) => value.slice(prefix.length)));\n return `${prefix}*${suffix}`;\n}\n\nfunction commonPrefix(values: string[]): string {\n let prefix = values[0] ?? '';\n for (const value of values.slice(1)) while (!value.startsWith(prefix)) prefix = prefix.slice(0, -1);\n return prefix;\n}\n\nfunction commonSuffix(values: string[]): string {\n let suffix = values[0] ?? '';\n for (const value of values.slice(1)) while (!value.endsWith(suffix)) suffix = suffix.slice(1);\n return suffix;\n}\n\nfunction contextualImplementationQuality(db: Db): Diagnostic {\n const rows = db.prepare(\"SELECT status,COALESCE(unresolved_reason,status) reason,COUNT(*) count FROM graph_edges WHERE edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND status IN ('ambiguous','unresolved') GROUP BY status,reason ORDER BY status,count DESC,reason\").all() as Diagnostic[];\n const total = rows.reduce((sum, row) => sum + Number(row.count ?? 0), 0);\n return { severity: total > 0 ? 'warning' : 'info', code: 'strict_contextual_implementation_quality', message: 'Implementation hops stopped by ambiguous or unresolved implementation edges', total, breakdown: rows };\n}\n\nfunction classInstanceNoiseQuality(db: Db): Diagnostic {\n const builtIns = ['Set', 'Map', 'WeakSet', 'WeakMap', 'Date', 'RegExp', 'URL', 'URLSearchParams', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'AggregateError', 'ArrayBuffer', 'SharedArrayBuffer', 'DataView', 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array', 'Promise', 'AbortController'];\n const placeholders = builtIns.map(() => '?').join(',');\n const aggregate = db.prepare(`SELECT COUNT(*) total,\n SUM(CASE WHEN status='unresolved' THEN 1 ELSE 0 END) unresolved,\n SUM(CASE WHEN status='unresolved' AND json_extract(evidence_json,'$.className') IN (${placeholders}) THEN 1 ELSE 0 END) unresolvedBuiltIn\n FROM symbol_calls WHERE json_extract(evidence_json,'$.relation')='class_instance_method'`).get(...builtIns) as Diagnostic;\n const byConstructor = db.prepare(`SELECT json_extract(evidence_json,'$.className') constructorName,COUNT(*) unresolvedCount\n FROM symbol_calls WHERE status='unresolved' AND json_extract(evidence_json,'$.relation')='class_instance_method'\n GROUP BY constructorName ORDER BY unresolvedCount DESC,constructorName LIMIT 10`).all() as Diagnostic[];\n return { severity: Number(aggregate.unresolvedBuiltIn ?? 0) > 0 ? 'warning' : 'info', code: 'strict_class_instance_noise_quality', message: 'Class-instance symbol-call aggregate with built-in constructor guard', totalClassInstanceCalls: Number(aggregate.total ?? 0), unresolvedClassInstanceCalls: Number(aggregate.unresolved ?? 0), unresolvedBuiltInClassInstanceCalls: Number(aggregate.unresolvedBuiltIn ?? 0), unresolvedByConstructor: byConstructor };\n}\n\nfunction contextualBindingPropagationQuality(db: Db): Diagnostic {\n const missing = missingParameterMetadataCategory(db);\n const opportunities = db.prepare(\"SELECT c.source_file sourceFile,c.source_line sourceLine,json_extract(c.evidence_json,'$.receiver') receiverName,c.operation_path_expr operationPath FROM outbound_calls c WHERE c.call_type='remote_action' AND json_extract(c.evidence_json,'$.receiver') IS NOT NULL AND c.service_binding_id IS NULL ORDER BY c.source_file,c.source_line LIMIT 8\").all() as Diagnostic[];\n return { severity: missing.count + opportunities.length > 0 ? 'warning' : 'info', code: 'strict_contextual_binding_propagation_quality', message: 'Contextual service-client propagation opportunities for trace-time helper resolution', calleeSymbolsMissingParameterMetadata: missing.count, traceTimeContextualOpportunities: opportunities.length, examples: opportunities };\n}\n\nfunction serviceBindingQuality(db: Db, detail: boolean): Diagnostic {\n const rows = db.prepare(`\n SELECT c.source_file sourceFile,c.source_line sourceLine,\n c.unresolved_reason unresolvedReason,c.evidence_json evidenceJson,\n s.evidence_json symbolEvidenceJson\n FROM outbound_calls c\n LEFT JOIN symbols s ON s.id=c.source_symbol_id\n WHERE c.call_type='remote_action'\n AND c.operation_path_expr IS NOT NULL\n AND c.service_binding_id IS NULL\n ORDER BY c.source_file,c.source_line\n `).all() as Diagnostic[];\n const groups = new Map<string, Diagnostic[]>();\n for (const row of rows) {\n const category = bindingCategory(row);\n groups.set(category, [...(groups.get(category) ?? []), bindingExample(row)]);\n }\n const categories = [...groups.entries()].map(([category, examples]) => ({\n category,\n count: examples.length,\n severity: 'warning',\n suggestedAction: bindingCategoryAction(category),\n examples: examples.slice(0, 3),\n expandedExamples: detail ? examples : undefined,\n }));\n return {\n severity: rows.length > 0 ? 'warning' : 'info',\n code: 'strict_service_binding_quality',\n message: 'Remote service-client binding quality aggregate',\n total: rows.length,\n categories,\n };\n}\n\nfunction bindingCategory(row: Diagnostic): string {\n const evidence = parseObject(row.evidenceJson);\n const resolution = parseObject(evidence.serviceBindingResolution);\n const reference = parseObject(evidence.serviceBindingReference);\n if (resolution.status === 'rejected_future_binding') return 'direct_binding_missing';\n if (reference.reason === 'binding_declared_after_call')\n return 'direct_binding_missing';\n if (resolution.status === 'ambiguous' || reference.status === 'ambiguous'\n || reference.reason === 'unsupported_reaching_assignment')\n return 'ambiguous_binding_candidates';\n const receiver = evidence.receiver;\n const symbolEvidence = parseObject(row.symbolEvidenceJson);\n if (symbolHasReceiverParameter(symbolEvidence, receiver))\n return 'contextual_binding_recoverable';\n if (!Array.isArray(symbolEvidence.parameterBindings))\n return 'missing_symbol_parameter_metadata';\n return 'unrecoverable_binding';\n}\n\nfunction symbolHasReceiverParameter(evidence: Diagnostic, receiver: unknown): boolean {\n if (typeof receiver !== 'string' || !Array.isArray(evidence.parameterBindings))\n return false;\n return asRecords(evidence.parameterBindings).some((binding) => {\n if (binding.kind === 'identifier') return binding.name === receiver;\n if (binding.kind === 'object_pattern')\n return asRecords(binding.properties).some((property) => property.local === receiver);\n return asRecords(binding.elements).some((element) => element.local === receiver);\n });\n}\n\nfunction bindingExample(row: Diagnostic): Diagnostic {\n const evidence = parseObject(row.evidenceJson);\n return {\n sourceFile: row.sourceFile,\n sourceLine: row.sourceLine,\n receiver: evidence.receiver,\n unresolvedReason: row.unresolvedReason,\n bindingResolution: evidence.serviceBindingResolution,\n bindingReference: evidence.serviceBindingReference,\n };\n}\n\nfunction bindingCategoryAction(category: string): string {\n if (category === 'direct_binding_missing')\n return 'Move the binding before the call or bind the call to an earlier immutable client.';\n if (category === 'contextual_binding_recoverable')\n return 'Trace from the caller so parameter binding evidence can be applied.';\n if (category === 'ambiguous_binding_candidates')\n return 'Split mutable client alternatives or add a statically unique client assignment.';\n if (category === 'missing_symbol_parameter_metadata')\n return 'Use named or destructured parameters on an indexed helper symbol.';\n return 'Add a direct CAP client binding or statically provable helper-return binding.';\n}\n\nfunction decoratorResolutionQuality(db: Db): Diagnostic {\n const aggregate = db.prepare(`SELECT\n SUM(CASE WHEN json_extract(decorator_resolution_json,'$.resolutionKind')\n IN ('const_identifier','enum_member','const_object_property','generated_constant_name') THEN 1 ELSE 0 END) resolvedFromConstants,\n SUM(CASE WHEN json_extract(decorator_resolution_json,'$.resolutionKind')\n ='unresolved' THEN 1 ELSE 0 END) unresolvedExpressions\n FROM handler_methods`).get() as Diagnostic;\n const unresolved = Number(aggregate.unresolvedExpressions ?? 0);\n const examples = db.prepare(`SELECT hm.method_name methodName,\n hm.decorator_raw_expression rawExpression,\n json_extract(hm.decorator_resolution_json,'$.unresolvedReason') unresolvedReason,\n hm.source_file sourceFile,hm.source_line sourceLine\n FROM handler_methods hm\n WHERE json_extract(hm.decorator_resolution_json,'$.resolutionKind')='unresolved'\n ORDER BY hm.source_file,hm.source_line LIMIT 5`).all() as Diagnostic[];\n return {\n severity: unresolved > 0 ? 'warning' : 'info',\n code: 'strict_decorator_resolution_quality',\n message: 'Handler decorator string-resolution aggregate',\n resolvedFromConstants: Number(aggregate.resolvedFromConstants ?? 0),\n unresolvedExpressions: unresolved,\n unresolvedExamples: examples,\n };\n}\n\nfunction handlerRegistrationPairingQuality(db: Db): Diagnostic {\n const mismatch = db.prepare(`SELECT COUNT(*) count\n FROM handler_registrations hr\n JOIN handler_classes hc ON hc.id=hr.handler_class_id\n WHERE hr.handler_class_id IS NOT NULL\n AND (hc.repo_id<>hr.repo_id OR hc.class_name<>hr.class_name)`).get() as Diagnostic;\n const prevented = db.prepare(`SELECT COUNT(*) count\n FROM handler_registrations hr\n JOIN handler_classes exactClass ON exactClass.id=hr.handler_class_id\n JOIN handler_classes otherClass ON otherClass.class_name=hr.class_name\n AND otherClass.repo_id<>hr.repo_id\n WHERE hr.handler_class_id IS NOT NULL AND hr.import_source IS NOT NULL`).get() as Diagnostic;\n const mismatched = Number(mismatch.count ?? 0);\n return {\n severity: mismatched > 0 ? 'error' : 'info',\n code: 'strict_handler_registration_pairing_quality',\n message: 'Handler registration and class ownership aggregate',\n mismatchedExactRegistrations: mismatched,\n preventedSyntheticCrossRepositoryPairs: Number(prevented.count ?? 0),\n };\n}\n\nfunction wrapperPathPropagationQuality(db: Db): Diagnostic {\n const examples = db.prepare(\"SELECT source_file sourceFile,source_line sourceLine,json_extract(evidence_json,'$.receiver') receiverName,json_extract(evidence_json,'$.operationPathExpression') pathIdentifier FROM outbound_calls WHERE call_type='remote_action' AND unresolved_reason='dynamic_operation_path_identifier' ORDER BY source_file,source_line LIMIT 5\").all() as Diagnostic[];\n return { severity: examples.length > 0 ? 'warning' : 'info', code: 'strict_wrapper_path_propagation_quality', message: 'Dynamic path sends where send({ path }) used a path identifier', dynamicPathIdentifierCalls: examples.length, examples };\n}\n\nfunction nestedThisReceiverQuality(db: Db): Diagnostic {\n const aggregate = db.prepare(`SELECT COUNT(*) total,\n SUM(CASE WHEN json_extract(evidence_json,'$.relation')='indexed_this_method' THEN 1 ELSE 0 END) resolvedToCurrentClass,\n SUM(CASE WHEN json_extract(evidence_json,'$.relation')='class_instance_method' THEN 1 ELSE 0 END) withExplicitHelperInstanceEvidence\n FROM symbol_calls WHERE callee_expression LIKE 'this.%.%'`).get() as Diagnostic;\n const examples = db.prepare(`SELECT source_file sourceFile,source_line sourceLine,callee_expression calleeExpression,json_extract(evidence_json,'$.relation') relation,json_extract(evidence_json,'$.targetName') targetName\n FROM symbol_calls WHERE callee_expression LIKE 'this.%.%' AND json_extract(evidence_json,'$.relation')='indexed_this_method'\n ORDER BY source_file,source_line LIMIT 8`).all() as Diagnostic[];\n return { severity: Number(aggregate.resolvedToCurrentClass ?? 0) > 0 ? 'warning' : 'info', code: 'strict_nested_this_receiver_quality', message: 'Nested this receiver symbol-call aggregate', nestedThisReceiverCallsConsidered: Number(aggregate.total ?? 0), nestedThisResolvedToCurrentClass: Number(aggregate.resolvedToCurrentClass ?? 0), nestedThisWithExplicitHelperInstanceEvidence: Number(aggregate.withExplicitHelperInstanceEvidence ?? 0), warningExamples: examples };\n}\n\nfunction remoteQueryTargetQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) total,SUM(CASE WHEN e.edge_type='HANDLER_RUNS_REMOTE_QUERY' AND e.status='terminal' THEN 1 ELSE 0 END) terminal,SUM(CASE WHEN e.edge_type='HANDLER_RUNS_REMOTE_QUERY' AND e.to_id GLOB '[0-9]*' THEN 1 ELSE 0 END) numericTargets,SUM(CASE WHEN e.edge_type='UNRESOLVED_EDGE' OR e.status='unresolved' THEN 1 ELSE 0 END) unresolved FROM outbound_calls c LEFT JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT) WHERE c.call_type='remote_query'\").get() as Diagnostic;\n const numeric = Number(row.numericTargets ?? 0);\n const unresolved = Number(row.unresolved ?? 0);\n return { severity: numeric + unresolved > 0 ? 'warning' : 'info', code: 'strict_remote_query_target_quality', message: 'Remote query terminal target quality aggregate', totalRemoteQueryCalls: Number(row.total ?? 0), terminalRemoteQueryEdges: Number(row.terminal ?? 0), numericTargetCount: numeric, unresolvedRemoteQueryCount: unresolved };\n}\n\nfunction remoteEntityOperationCollisionQuality(db: Db): Diagnostic {\n const rows = db.prepare(`SELECT c.id callId,c.source_file sourceFile,c.source_line sourceLine,c.method method,c.operation_path_expr rawPath,c.query_entity entitySegment,e.to_id selectedTerminalEntityTarget,e.evidence_json evidenceJson\n FROM outbound_calls c JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT)\n WHERE c.call_type LIKE 'remote_entity_%' AND e.edge_type='HANDLER_ACCESSES_REMOTE_ENTITY' AND e.status='terminal'\n ORDER BY c.source_file,c.source_line LIMIT 100`).all() as Diagnostic[];\n const examples = rows.map((row) => operationCollisionExample(db, row)).filter((row): row is Diagnostic => Boolean(row)).slice(0, 10);\n return { severity: examples.length > 0 ? 'warning' : 'info', code: 'strict_remote_entity_operation_collision_quality', message: 'Terminal remote entity edges that look like indexed operation invocations', collisionCount: examples.length, examples };\n}\n\nfunction operationCollisionExample(db: Db, row: Diagnostic): Diagnostic | undefined {\n const rawPath = String(row.rawPath ?? '');\n const normalized = normalizeODataOperationInvocationPath(rawPath);\n const candidatePath = normalized?.wasInvocation ? normalized.normalizedOperationPath : rawPath;\n const name = candidatePath.replace(/^\\//, '');\n const simple = name.split('.').at(-1) ?? name;\n const candidates = db.prepare('SELECT COUNT(*) count FROM cds_operations WHERE operation_path IN (?,?) OR operation_name IN (?,?)').get(candidatePath, `/${simple}`, name, simple) as { count?: number };\n const candidateCount = Number(candidates.count ?? 0);\n if (!normalized?.wasInvocation && candidateCount === 0) return undefined;\n const evidence = parseObject(row.evidenceJson);\n return { callId: row.callId, sourceFile: row.sourceFile, sourceLine: row.sourceLine, method: row.method, rawPath, normalizedOperationPath: normalized?.wasInvocation ? normalized.normalizedOperationPath : candidatePath, entitySegment: row.entitySegment, operationCandidateCount: candidateCount, selectedTerminalEntityTarget: row.selectedTerminalEntityTarget, classifierReason: parseObject(evidence.odataPathIntent).reason };\n}\n\nfunction remoteEntityDynamicOperationFalsePositiveQuality(db: Db): Diagnostic {\n const rows = db.prepare(`SELECT c.source_file sourceFile,c.source_line sourceLine,c.method method,c.operation_path_expr rawPath,e.id graphEdgeId,e.unresolved_reason unresolvedReason,e.evidence_json evidenceJson\n FROM outbound_calls c JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT)\n WHERE c.call_type LIKE 'remote_entity_%' AND e.status IN ('dynamic','unresolved') AND e.to_kind='operation_candidate'\n ORDER BY c.source_file,c.source_line LIMIT 100`).all() as Diagnostic[];\n const examples = rows.filter(isRemoteEntityFalsePositive).map((row) => falsePositiveExample(row)).slice(0, 10);\n return { severity: examples.length > 0 ? 'warning' : 'info', code: 'strict_remote_entity_dynamic_operation_false_positive_quality', message: 'Parser-classified entity paths linked as dynamic operation candidates without indexed operation evidence', falsePositiveCount: examples.length, examples };\n}\n\nfunction isRemoteEntityFalsePositive(row: Diagnostic): boolean {\n const intent = classifyODataPathIntent(String(row.rawPath ?? ''), String(row.method ?? 'GET'));\n const entityIntent = ['entity_key_read', 'entity_navigation_query', 'entity_media'].includes(intent.kind) || (intent.kind === 'entity_mutation' && (intent.hasEntityKeyPredicate || intent.hasNavigationSuffix));\n const evidence = parseObject(row.evidenceJson);\n const candidateCount = Number(evidence.indexedOperationCandidateCount ?? evidence.candidateCount ?? 0);\n const reason = String(row.unresolvedReason ?? '');\n return entityIntent && candidateCount === 0 && (intent.keyPredicatePlaceholderKeys.length > 0 || reason.includes('runtime variable') || reason.includes('placeholder'));\n}\n\nfunction falsePositiveExample(row: Diagnostic): Diagnostic {\n const intent = classifyODataPathIntent(String(row.rawPath ?? ''), String(row.method ?? 'GET'));\n return { sourceFile: row.sourceFile, sourceLine: row.sourceLine, rawPath: row.rawPath, method: row.method, pathIntent: intent.kind, keyPlaceholderKeys: intent.keyPredicatePlaceholderKeys, navigationOrMediaSuffix: intent.navigationSuffix ?? intent.mediaOrPropertySuffix, graphEdgeId: row.graphEdgeId, operationCandidateCount: 0, recommendedRemediation: 'Reindex and relink with service-flow 0.1.35 or newer so entity key placeholders remain entity-addressing evidence.' };\n}\n\nfunction remoteActionTargetQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) total,SUM(CASE WHEN e.status='unresolved' THEN 1 ELSE 0 END) unresolved,SUM(CASE WHEN e.status='unresolved' AND e.to_id GLOB '[0-9]*' THEN 1 ELSE 0 END) numericTargets,SUM(CASE WHEN e.status='unresolved' AND (e.to_id='Remote action: unknown path' OR e.to_id='Remote action: dynamic path') THEN 1 ELSE 0 END) semanticTargets FROM outbound_calls c LEFT JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT) WHERE c.call_type='remote_action'\").get() as Diagnostic;\n const numeric = Number(row.numericTargets ?? 0);\n return { severity: numeric > 0 ? 'warning' : 'info', code: 'strict_remote_action_target_quality', message: 'Remote action unresolved target quality aggregate', totalRemoteActionCalls: Number(row.total ?? 0), unresolvedRemoteActionCalls: Number(row.unresolved ?? 0), numericUnresolvedTargetCount: numeric, semanticUnknownOrDynamicTargetCount: Number(row.semanticTargets ?? 0) };\n}\n\nfunction externalHttpTargetQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) total,SUM(CASE WHEN e.to_id GLOB '[0-9]*' THEN 1 ELSE 0 END) numericTargets,SUM(CASE WHEN e.evidence_json IS NULL OR json_valid(e.evidence_json)=0 OR json_extract(e.evidence_json,'$.externalTarget.kind') IS NULL THEN 1 ELSE 0 END) invalidEvidence FROM outbound_calls c LEFT JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT) WHERE c.call_type='external_http'\").get() as Diagnostic;\n const bad = Number(row.numericTargets ?? 0) + Number(row.invalidEvidence ?? 0);\n return { severity: bad > 0 ? 'warning' : 'info', code: 'strict_external_http_target_quality', message: 'External HTTP semantic target aggregate', totalExternalHttpCalls: Number(row.total ?? 0), numericTargetCount: Number(row.numericTargets ?? 0), invalidOrMissingExternalTargetEvidence: Number(row.invalidEvidence ?? 0) };\n}\n\nfunction odataInvocationResolutionQuality(db: Db): Diagnostic {\n const rows = db.prepare(`SELECT c.operation_path_expr operationPathExpr,\n c.source_file sourceFile,c.source_line sourceLine,e.id graphEdgeId,\n e.status status,e.evidence_json evidenceJson\n FROM outbound_calls c JOIN graph_edges e\n ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT)\n WHERE c.call_type='remote_action' AND c.operation_path_expr LIKE '%(%'\n ORDER BY c.source_file,c.source_line`).all() as Array<{\n operationPathExpr?: string;\n sourceFile?: string;\n sourceLine?: number;\n graphEdgeId?: number;\n status?: string;\n evidenceJson?: string;\n }>;\n const unresolved = rows.filter((row) => row.status === 'unresolved' && normalizeODataOperationInvocationPath(row.operationPathExpr)?.wasInvocation).length;\n const ambiguous = rows.filter((row) => row.status === 'ambiguous' && normalizeODataOperationInvocationPath(row.operationPathExpr)?.wasInvocation).length;\n const examples = rows\n .filter((row) => row.status === 'ambiguous' || row.status === 'unresolved')\n .map(odataInvocationExample)\n .slice(0, 5);\n return { severity: unresolved + ambiguous > 0 ? 'warning' : 'info', code: 'strict_odata_invocation_resolution_quality', message: 'OData invocation-path resolution quality aggregate', totalInvocationRemoteActions: rows.length, resolvedInvocationCalls: rows.filter((row) => row.status === 'resolved').length, dynamicInvocationCalls: rows.filter((row) => row.status === 'dynamic').length, ambiguousInvocationCalls: rows.filter((row) => row.status === 'ambiguous').length, unresolvedInvocationCalls: rows.filter((row) => row.status === 'unresolved').length, ambiguousNormalizedCalls: ambiguous, unresolvedNormalizedCallsWithIndexedCandidates: unresolved, examples };\n}\n\nfunction odataInvocationExample(row: {\n operationPathExpr?: string;\n sourceFile?: string;\n sourceLine?: number;\n graphEdgeId?: number;\n status?: string;\n evidenceJson?: string;\n}): Diagnostic {\n const evidence = parseObject(row.evidenceJson);\n const normalized = normalizeODataOperationInvocationPath(row.operationPathExpr);\n return {\n sourceFile: row.sourceFile,\n sourceLine: row.sourceLine,\n graphEdgeId: row.graphEdgeId,\n status: row.status,\n rawPath: row.operationPathExpr,\n normalizedOperationPath: normalized?.wasInvocation\n ? normalized.normalizedOperationPath\n : undefined,\n indexedOperationCandidateCount: evidence.indexedOperationCandidateCount,\n candidateScores: evidence.candidateScores,\n entityOperationPrecedence: evidence.entityOperationPrecedence,\n resolutionReasons: evidence.resolutionReasons,\n };\n}\n\nfunction identityAliasBindingQuality(db: Db): Diagnostic {\n const examples = db.prepare(\"SELECT c.source_file sourceFile,c.source_line sourceLine FROM outbound_calls c WHERE c.call_type='remote_action' AND c.service_binding_id IS NULL AND json_extract(c.evidence_json,'$.receiver') IS NOT NULL ORDER BY c.source_file,c.source_line LIMIT 5\").all() as Diagnostic[];\n return { severity: examples.length > 0 ? 'warning' : 'info', code: 'strict_identity_alias_binding_quality', message: 'Remote sends that look like missed same-file identity aliases', missedAliasBindingCalls: examples.length, examples };\n}\n\nfunction remoteActionNoBindingQuality(db: Db): Diagnostic {\n const rows = db.prepare(\"SELECT COALESCE(e.status,'missing_edge') status,COUNT(*) count FROM outbound_calls c LEFT JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT) WHERE c.call_type='remote_action' AND c.operation_path_expr IS NOT NULL AND c.service_binding_id IS NULL GROUP BY status ORDER BY count DESC,status\").all() as Diagnostic[];\n const total = rows.reduce((sum, row) => sum + Number(row.count ?? 0), 0);\n return { severity: total > 0 ? 'warning' : 'info', code: 'strict_remote_action_no_binding_quality', message: 'Remote actions with operation paths but no service binding id', total, breakdown: rows };\n}\n\nfunction candidateCount(value: unknown): number {\n return Number(parseObject(value).candidateCount ?? 0);\n}\n\nfunction numericValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction parseObject(value: unknown): Diagnostic {\n if (value && typeof value === 'object' && !Array.isArray(value)) return value as Diagnostic;\n try {\n const parsed = JSON.parse(String(value ?? '{}')) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Diagnostic : {};\n } catch {\n return {};\n }\n}\n\nfunction asRecords(value: unknown): Diagnostic[] {\n return Array.isArray(value) ? value.filter((item): item is Diagnostic => Boolean(item && typeof item === 'object' && !Array.isArray(item))) : [];\n}\n","import type { TraceResult } from '../types.js';\n\nfunction location(evidence: Record<string, unknown>): string {\n const selected = isRecord(evidence.selectedHandler)\n ? evidence.selectedHandler : undefined;\n const selectedFile = selected?.sourceFile;\n const selectedLine = selected?.sourceLine;\n if (selectedFile || selectedLine)\n return `${String(selectedFile ?? '')}:${String(selectedLine ?? '')}`;\n const file = evidence.file ?? evidence.sourceFile ?? evidence.handlerSourceFile ?? evidence.operationSourceFile ?? evidence.registrationSourceFile;\n const line = evidence.line ?? evidence.sourceLine ?? evidence.handlerSourceLine ?? evidence.operationSourceLine ?? evidence.registrationSourceLine;\n if (file || line) return `${String(file ?? '')}:${String(line ?? '')}`;\n const candidates = evidence.candidates;\n if (Array.isArray(candidates) && candidates.some((candidate) =>\n isRecord(candidate) && candidate.methodId !== undefined)) return ':';\n if (Array.isArray(candidates) && candidates.length > 0) {\n const first = candidates.find(isRecord);\n if (first)\n return `${String(first.sourceFile ?? '')}:${String(first.sourceLine ?? '')}`;\n }\n return ':';\n}\nexport function renderTraceTable(result: TraceResult): string {\n const lines = ['Step Type From To Evidence'];\n for (const e of result.edges) {\n lines.push(`${String(e.step).padEnd(5)} ${e.type.padEnd(20)} ${e.from.slice(0, 34).padEnd(35)} ${e.to.slice(0, 35).padEnd(36)} ${location(e.evidence)}`);\n if (e.unresolvedReason)\n lines.push(...hintLines(e.evidence).map((hint) => ` ${hint}`));\n }\n if (result.diagnostics.length > 0) lines.push('', 'Diagnostics:', ...result.diagnostics.flatMap(diagnosticLines));\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction diagnosticLines(diagnostic: Record<string, unknown>): string[] {\n const first = `${String(diagnostic.severity ?? 'info')} ${String(diagnostic.code ?? 'diagnostic')} ${String(diagnostic.message ?? '')}`;\n const details = diagnosticDetailLines(diagnostic);\n return [first, ...[...details, ...hintLines(diagnostic)]\n .map((hint) => ` ${hint}`)];\n}\n\nfunction diagnosticDetailLines(diagnostic: Record<string, unknown>): string[] {\n const lines: string[] = [];\n if (diagnostic.sourceFile || diagnostic.sourceLine)\n lines.push(`at ${String(diagnostic.sourceFile ?? '')}:${String(diagnostic.sourceLine ?? '')}`);\n const unsupported = stringList(diagnostic.unsupportedDecoratorNames);\n const observed = stringList(diagnostic.observedDecoratorNames);\n if (unsupported.length > 0)\n lines.push(`unsupported decorators: ${unsupported.join(', ')}`);\n else if (observed.length > 0)\n lines.push(`observed decorators: ${observed.join(', ')}`);\n if (typeof diagnostic.remediation === 'string')\n lines.push(`hint: ${diagnostic.remediation}`);\n return lines;\n}\n\nfunction stringList(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction hintLines(evidence: Record<string, unknown>): string[] {\n const dynamicLines = dynamicHintLines(evidence);\n const suggestions = evidence.implementationHintSuggestions;\n if (!Array.isArray(suggestions)) return dynamicLines;\n const hints = suggestions.flatMap((item) =>\n isRecord(item) && typeof item.cli === 'string'\n ? [item.cli]\n : []);\n const unique = [...new Set(hints)];\n const shown = unique.slice(0, 3).map((hint) => `try ${hint}`);\n const omitted = numberValue(evidence.omittedImplementationHintSuggestionCount);\n const remaining = Math.max(0, unique.length - shown.length) + omitted;\n if (remaining > 0)\n shown.push(`... ${remaining} additional hint(s) omitted; use a scoped --implementation-hint`);\n return [...dynamicLines, ...shown];\n}\n\nfunction dynamicHintLines(evidence: Record<string, unknown>): string[] {\n const exploration = isRecord(evidence.dynamicTargetExploration)\n ? evidence.dynamicTargetExploration\n : evidence;\n const count = numberValue(exploration.candidateCount);\n if (count === 0) return [];\n const shown = numberValue(exploration.shownCandidateCount);\n const omitted = numberValue(exploration.omittedCandidateCount);\n const rejected = numberValue(exploration.rejectedCandidateCount);\n const lines = [\n `viable candidates: ${shown} shown, ${omitted} omitted; rejected: ${rejected}`,\n ];\n lines.push(...varSetHints(exploration.suggestedVarSets));\n if (omitted > 0 || rejected > 0 || shown < count)\n lines.push('use --dynamic-mode candidates --max-dynamic-candidates 20 to explore candidate branches');\n return lines;\n}\n\nfunction varSetHints(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n const hints = value.flatMap((item) =>\n isRecord(item) && typeof item.cli === 'string' ? [`try ${item.cli}`] : []);\n return [...new Set(hints)].slice(0, 3);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction numberValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n","import type { TraceResult } from '../types.js';\nexport function renderJson(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\nexport function renderTraceJson(trace: TraceResult): string {\n return renderJson(trace);\n}\n","import pc from 'picocolors';\nimport { renderJson } from './json-output.js';\n\ntype Diagnostic = Record<string, unknown>;\n\nexport function renderDoctorDiagnostics(diagnostics: Diagnostic[], format: string | undefined): string {\n if (format === 'json') return renderJson(diagnostics);\n if (format === 'table') return renderDoctorTable(diagnostics);\n if (format) throw new Error(`Unsupported doctor format: ${format}. Expected json or table.`);\n return renderLegacyDoctorOutput(diagnostics);\n}\n\nfunction renderLegacyDoctorOutput(diagnostics: Diagnostic[]): string {\n if (diagnostics.length === 0) return cleanDoctorMessage();\n return renderJson(diagnostics);\n}\n\nexport function renderDoctorTable(diagnostics: Diagnostic[]): string {\n if (diagnostics.length === 0) return cleanDoctorMessage();\n const rows = diagnostics.map((diagnostic) => ({\n severity: String(diagnostic.severity ?? 'info'),\n code: String(diagnostic.code ?? 'diagnostic'),\n location: diagnosticLocation(diagnostic),\n message: compactMessage(diagnostic),\n hints: suggestedHintLines(diagnostic),\n }));\n const widths = {\n severity: columnWidth('Severity', rows.map((row) => row.severity), 10),\n code: columnWidth('Code', rows.map((row) => row.code), 44),\n location: columnWidth('Location', rows.map((row) => row.location), 28),\n };\n const lines = [\n `${'Severity'.padEnd(widths.severity)} ${'Code'.padEnd(widths.code)} ${'Location'.padEnd(widths.location)} Message`,\n `${'-'.repeat(widths.severity)} ${'-'.repeat(widths.code)} ${'-'.repeat(widths.location)} ${'-'.repeat(7)}`,\n ];\n for (const row of rows) {\n lines.push(`${truncate(row.severity, widths.severity).padEnd(widths.severity)} ${truncate(row.code, widths.code).padEnd(widths.code)} ${truncate(row.location, widths.location).padEnd(widths.location)} ${row.message}`);\n lines.push(...row.hints.map((hint) => ` try ${hint}`));\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction diagnosticLocation(diagnostic: Diagnostic): string {\n const file = diagnostic.sourceFile ?? diagnostic.file;\n const line = diagnostic.sourceLine ?? diagnostic.line;\n if (file || line) return `${String(file ?? '')}:${String(line ?? '')}`;\n return '-';\n}\n\nfunction compactMessage(diagnostic: Diagnostic): string {\n const message = String(diagnostic.message ?? '');\n const count = typeof diagnostic.count === 'number' ? ` count=${diagnostic.count}` : '';\n const total = typeof diagnostic.total === 'number' ? ` total=${diagnostic.total}` : '';\n return `${message}${count}${total}`.trim();\n}\n\nfunction suggestedHintLines(diagnostic: Diagnostic): string[] {\n const direct = cliHints(diagnostic.suggestedHints);\n const omitted = numericValue(diagnostic.omittedImplementationHintSuggestionCount);\n if (direct.length > 0) return cappedHints(direct, omitted);\n return cappedHints(\n cliHintsFromSuggestions(diagnostic.implementationHintSuggestions), omitted,\n );\n}\n\nfunction cliHints(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];\n}\n\nfunction cliHintsFromSuggestions(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((item) => {\n if (!isRecord(item)) return [];\n return typeof item.cli === 'string' ? [item.cli] : [];\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction cappedHints(hints: string[], omitted: number): string[] {\n const unique = [...new Set(hints)];\n const shown = unique.slice(0, 3);\n const remaining = Math.max(0, unique.length - shown.length) + omitted;\n if (remaining > 0)\n shown.push(`... ${remaining} additional hint(s) omitted; use a scoped --implementation-hint`);\n return shown;\n}\n\nfunction numericValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction cleanDoctorMessage(): string {\n return `${pc.green('No diagnostics recorded')}\\n`;\n}\n\nfunction columnWidth(header: string, values: string[], max: number): number {\n return Math.min(max, Math.max(header.length, ...values.map((value) => value.length)));\n}\n\nfunction truncate(value: string, width: number): string {\n if (value.length <= width) return value;\n if (width <= 1) return value.slice(0, width);\n return `${value.slice(0, width - 1)}…`;\n}\n","import type { TraceResult } from '../types.js';\nfunction label(trace: TraceResult, idOrLabel: string): string {\n const node = trace.nodes.find((item) => item.id === idOrLabel || item.label === idOrLabel);\n return String(node?.label ?? idOrLabel);\n}\nexport function renderMermaid(trace: TraceResult): string {\n const ids = new Map<string, string>();\n const nodeId = (value: string): string => {\n const existing = ids.get(value);\n if (existing) return existing;\n const id = `n${ids.size}`;\n ids.set(value, id);\n return id;\n };\n const lines = ['flowchart TD'];\n for (const e of trace.edges)\n lines.push(\n ` ${nodeId(e.from)}[\"${label(trace, e.from)}\"] -->|${e.type}| ${nodeId(e.to)}[\"${label(trace, e.to)}\"]`\n );\n return `${lines.join('\\n')}\\n`;\n}\n","import type { Writable } from 'node:stream';\n\nexport interface StdoutWriter {\n write(value: string): boolean;\n}\n\ninterface OutputState {\n blocked: boolean;\n unexpectedReported: boolean;\n}\n\ninterface WriterEntry {\n state: OutputState;\n writer: StdoutWriter;\n}\n\nconst writers = new WeakMap<Writable, WriterEntry>();\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction isBrokenPipe(error: Error): boolean {\n return isRecord(error) && error.code === 'EPIPE';\n}\n\nfunction asError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction handleStreamError(\n state: OutputState,\n error: Error,\n onUnexpectedError: (error: Error) => void,\n): void {\n state.blocked = true;\n if (isBrokenPipe(error) || state.unexpectedReported) return;\n state.unexpectedReported = true;\n onUnexpectedError(error);\n}\n\nexport function createStdoutWriter(\n stream: Writable,\n onUnexpectedError: (error: Error) => void,\n): StdoutWriter {\n const existing = writers.get(stream);\n if (existing) return existing.writer;\n const state: OutputState = { blocked: false, unexpectedReported: false };\n const writer: StdoutWriter = {\n write(value: string): boolean {\n if (state.blocked) return false;\n try {\n stream.write(value);\n return true;\n } catch (error) {\n handleStreamError(state, asError(error), onUnexpectedError);\n return false;\n }\n },\n };\n stream.on('error', (error: Error) =>\n handleStreamError(state, error, onUnexpectedError));\n writers.set(stream, { state, writer });\n return writer;\n}\n","import type { CompactGraphV1 } from '../trace/014-compact-contract.js';\nimport { redactValue } from '../utils/redaction.js';\n\nexport function renderCompactJson(value: CompactGraphV1): string {\n return `${JSON.stringify(redactValue(value))}\\n`;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { WorkspaceConfig } from '../config/workspace-config.js';\nimport { openDatabase } from '../db/connection.js';\nimport { getWorkspace, upsertWorkspace } from '../db/repositories.js';\nimport { claimIndexRun } from '../indexer/workspace-indexer.js';\nimport { errorMessage } from '../utils/diagnostics.js';\n\ntype CleanConfig = Pick<WorkspaceConfig, 'dbPath' | 'rootPath'>;\n\nexport async function cleanWorkspaceState(\n config: CleanConfig,\n dbOnly: boolean,\n): Promise<void> {\n const dbDir = path.resolve(path.dirname(config.dbPath));\n if (!dbOnly) await assertOwnedStateDirectory(dbDir, config.rootPath);\n const runId = claimCleanWriter(config);\n try {\n if (dbOnly) await removeDatabaseFiles(config.dbPath);\n else await fs.rm(dbDir, { recursive: true, force: true });\n } catch (error) {\n await markCleanClaimFailed(config.dbPath, runId, error);\n throw error;\n }\n}\n\nfunction claimCleanWriter(config: CleanConfig): number {\n const db = openDatabase(config.dbPath);\n try {\n const workspaceId = getWorkspace(db, config.rootPath)?.id\n ?? upsertWorkspace(db, config.rootPath, config.dbPath);\n return claimIndexRun(db, workspaceId, 0);\n } finally {\n db.close();\n }\n}\n\nasync function assertOwnedStateDirectory(\n dbDir: string,\n rootPath: string,\n): Promise<void> {\n const marker = path.join(dbDir, '.service-flow-state');\n const dangerous = new Set([\n path.parse(dbDir).root,\n '/tmp',\n process.env.HOME ? path.resolve(process.env.HOME) : '',\n path.resolve(rootPath),\n ]);\n const ownsState = await fs.stat(marker)\n .then((stat) => stat.isFile())\n .catch(() => false);\n if (!ownsState || dangerous.has(dbDir))\n throw new Error(\n `Refusing to recursively delete unowned or dangerous state directory: ${dbDir}. Use --db-only to remove only the database file.`,\n );\n}\n\nasync function removeDatabaseFiles(dbPath: string): Promise<void> {\n for (const suffix of ['-wal', '-shm', '-journal'])\n await fs.rm(`${dbPath}${suffix}`, { force: true });\n await fs.rm(dbPath, { force: true });\n}\n\nasync function markCleanClaimFailed(\n dbPath: string,\n runId: number,\n error: unknown,\n): Promise<void> {\n const exists = await fs.stat(dbPath).then(() => true).catch(() => false);\n if (!exists) return;\n const db = openDatabase(dbPath);\n try {\n db.prepare(`UPDATE index_runs SET finished_at=?,status='failed',\n error_message=? WHERE id=? AND status='running'`).run(\n new Date().toISOString(),\n `Clean failed after writer claim: ${errorMessage(error)}`,\n runId,\n );\n } finally {\n db.close();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,cAAc;;;ACAzB,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,aAAa;AACnB,IAAM,cAAc;AACpB,IAAM,kBAAkB;;;ACb/B,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,SAAS;AAOlB,IAAM,SAAS,EAAE,OAAO;AAAA,EACtB,UAAU,EAAE,OAAO;AAAA,EACnB,QAAQ,EAAE,OAAO;AAAA,EACjB,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,EAC1B,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,OAAO;AACtB,CAAC;AAEM,SAAS,WAAW,UAA0B;AACnD,SAAO,KAAK,KAAK,UAAU,YAAY,WAAW;AACpD;AACO,SAAS,cAAc,UAA0B;AACtD,SAAO,KAAK,KAAK,UAAU,YAAY,eAAe;AACxD;AACA,eAAsB,oBACpB,QACe;AACf,QAAM,GAAG,MAAM,KAAK,QAAQ,WAAW,OAAO,QAAQ,CAAC,GAAG;AAAA,IACxD,WAAW;AAAA,EACb,CAAC;AACD,QAAM,GAAG;AAAA,IACP,WAAW,OAAO,QAAQ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AAI;AACtE;AACA,SAAS,KAAK,OAAsB;AAClC,UAAQ,OAAO;AAAA,IACb,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA;AAAA,EAC3D;AACA,UAAQ,WAAW;AACrB;AACA,cAAc,EAAE,MAAM,QAAQ,IAAI;","names":["fs","path","fs","path","packageName","fs","path","fs","path","fs","path","ts","ts","sourceFile","ts","ts","ts","ts","ts","ts","ts","assignmentOperator","ts","mutationUnary","propertyContainer","propertyName","lineOf","ts","propertyName","sourceFile","fs","path","path","fs","packageName","sourceFile","candidateCount","numericValue","count","trace","count","numericValue","isRecord","trace","isRecord","fs","path","path","fs"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/config/defaults.ts","../src/config/workspace-config.ts","../src/db/connection.ts","../src/db/repositories.ts","../src/discovery/classify-repository.ts","../src/utils/diagnostics.ts","../src/indexer/repository-indexer.ts","../src/parsers/symbol-parser.ts","../src/parsers/005-event-subscription-facts.ts","../src/parsers/016-local-symbol-reference.ts","../src/parsers/007-source-fact-reconciliation.ts","../src/parsers/006-binding-identity.ts","../src/parsers/009-symbol-call-facts.ts","../src/parsers/013-executable-body-eligibility.ts","../src/parsers/017-symbol-derived-contexts.ts","../src/parsers/008-package-surface-publication.ts","../src/utils/hashing.ts","../src/db/004-package-target-invalidation.ts","../src/indexer/cds-extension-resolver.ts","../src/indexer/workspace-indexer.ts","../src/cli/001-doctor-projection.ts","../src/cli/002-doctor-lifecycle.ts","../src/cli/003-doctor-package-resolution.ts","../src/cli/doctor.ts","../src/output/table-output.ts","../src/output/json-output.ts","../src/output/doctor-output.ts","../src/output/mermaid-output.ts","../src/output/000-stdout-policy.ts","../src/output/001-compact-json-output.ts","../src/cli/000-clean.ts","../src/cli/001-index-summary.ts"],"sourcesContent":["import { Command, Option } from 'commander';\nimport { DEFAULT_IGNORES } from './config/defaults.js';\nimport {\n createWorkspaceConfig,\n loadWorkspaceConfig,\n saveWorkspaceConfig,\n} from './config/workspace-config.js';\nimport { openDatabase, openReadOnlyDatabase, type Db } from './db/connection.js';\nimport {\n getWorkspace,\n listRepositories,\n reposByName,\n type RepoRow,\n upsertRepository,\n upsertWorkspace,\n} from './db/repositories.js';\nimport { discoverRepositories } from './discovery/discover-repositories.js';\nimport { parsePackageJson } from './parsers/package-json-parser.js';\nimport { classifyRepository } from './discovery/classify-repository.js';\nimport { indexWorkspace } from './indexer/workspace-indexer.js';\nimport { linkWorkspace } from './linker/cross-repo-linker.js';\nimport { doctorDiagnostics, linkUpgradeWarnings } from './cli/doctor.js';\nimport { trace } from './trace/trace-engine.js';\nimport { compactTrace } from './trace/018-compact-trace.js';\nimport {\n parseVars,\n selectorRepoAmbiguousDiagnostic,\n} from './trace/selectors.js';\nimport { parseImplementationHint } from './trace/implementation-hints.js';\nimport { renderTraceTable } from './output/table-output.js';\nimport { renderTraceJson, renderJson } from './output/json-output.js';\nimport { renderDoctorDiagnostics } from './output/doctor-output.js';\nimport { renderMermaid } from './output/mermaid-output.js';\nimport { createStdoutWriter } from './output/000-stdout-policy.js';\nimport { renderCompactJson } from './output/001-compact-json-output.js';\nimport { VERSION } from './version.js';\nimport type {\n DynamicMode,\n TraceOptions,\n TraceResult,\n TraceStart,\n} from './types.js';\nimport { cleanWorkspaceState } from './cli/000-clean.js';\nimport { indexCommandOutcome } from './cli/001-index-summary.js';\n\nconst stdout = createStdoutWriter(process.stdout, fail);\nconst TRACE_FORMATS = ['table', 'json', 'mermaid', 'compact-json'] as const;\nconst GRAPH_FORMATS = ['mermaid', 'json', 'compact-json'] as const;\n\ntype TraceFormat = (typeof TRACE_FORMATS)[number];\ntype GraphFormat = (typeof GRAPH_FORMATS)[number];\n\ninterface TraceCommandOptions {\n workspace?: string;\n repo?: string;\n operation?: string;\n service?: string;\n path?: string;\n handler?: string;\n depth: string;\n format: TraceFormat;\n includeExternal?: boolean;\n includeDb?: boolean;\n includeAsync?: boolean;\n implementationRepo?: string;\n implementationHint: string[];\n var: string[];\n dynamicMode: string;\n maxDynamicCandidates: string;\n}\n\ninterface GraphCommandOptions {\n workspace?: string;\n repo?: string;\n operation?: string;\n service?: string;\n path?: string;\n format: GraphFormat;\n implementationRepo?: string;\n implementationHint: string[];\n var: string[];\n dynamicMode: string;\n maxDynamicCandidates: string;\n}\n\nfunction writeStdout(value: string): void {\n stdout.write(value);\n}\n\nasync function init(\n workspace: string,\n options: { db?: string; ignore?: string[] },\n): Promise<void> {\n const config = createWorkspaceConfig(\n workspace,\n options.db,\n options.ignore?.length ? options.ignore : [...DEFAULT_IGNORES],\n );\n const repos = await discoverRepositories(config.rootPath, config.ignore);\n await saveWorkspaceConfig(config);\n const db = openDatabase(config.dbPath);\n const workspaceId = upsertWorkspace(db, config.rootPath, config.dbPath);\n for (const repo of repos) {\n const pkg = await parsePackageJson(repo.absolutePath);\n const kind = await classifyRepository(repo.absolutePath, pkg);\n upsertRepository(db, workspaceId, {\n ...repo,\n packageName: pkg.packageName,\n packageVersion: pkg.packageVersion,\n dependencies: pkg.dependencies,\n kind,\n });\n }\n db.close();\n writeStdout(\n `Workspace: ${config.rootPath}\\nDatabase: ${config.dbPath}\\nRepositories: ${repos.length}\\nIgnored: ${config.ignore.join(', ')}\\nNext: service-flow index --workspace ${config.rootPath}\\n`,\n );\n}\nasync function withWorkspace<T>(\n workspace: string | undefined,\n fn: (\n db: ReturnType<typeof openDatabase>,\n workspaceId: number,\n rootPath: string,\n ) => Promise<T> | T,\n): Promise<T> {\n const config = await loadWorkspaceConfig(workspace);\n const db = openDatabase(config.dbPath);\n try {\n const row = getWorkspace(db, config.rootPath);\n const workspaceId =\n row?.id ?? upsertWorkspace(db, config.rootPath, config.dbPath);\n return await fn(db, workspaceId, config.rootPath);\n } finally {\n db.close();\n }\n}\nasync function withReadOnlyWorkspace<T>(\n workspace: string | undefined,\n fn: (db: ReturnType<typeof openDatabase>, workspaceId: number, rootPath: string) => Promise<T> | T,\n): Promise<T> {\n const config = await loadWorkspaceConfig(workspace);\n const db = openReadOnlyDatabase(config.dbPath);\n try {\n const row = getWorkspace(db, config.rootPath);\n if (!row) throw new Error(`Workspace is not initialized in ${config.dbPath}`);\n return await fn(db, row.id, config.rootPath);\n } finally {\n db.close();\n }\n}\nfunction selectRepository(db: Db, selector: string, workspaceId?: number): {\n repo?: RepoRow;\n diagnostic?: Record<string, unknown>;\n} {\n const candidates = reposByName(db, selector, workspaceId);\n if (candidates.length === 1) return { repo: candidates[0] };\n if (candidates.length === 0) return {\n diagnostic: {\n severity: 'warning',\n code: 'selector_repo_not_found',\n message: `Repository selector not found: ${selector}`,\n },\n };\n return {\n diagnostic: selectorRepoAmbiguousDiagnostic(\n selector,\n candidates.map((repo) => ({\n id: repo.id,\n name: repo.name,\n packageName: repo.package_name ?? undefined,\n })),\n ),\n };\n}\n\nfunction traceFormatOption(): Option {\n return new Option('--format <format>', TRACE_FORMATS.join('|'))\n .choices([...TRACE_FORMATS])\n .default('table');\n}\n\nfunction graphFormatOption(): Option {\n return new Option('--format <format>', GRAPH_FORMATS.join('|'))\n .choices([...GRAPH_FORMATS])\n .default('mermaid');\n}\n\nfunction writeTraceOutput(\n db: Db,\n start: TraceStart,\n options: TraceOptions,\n format: TraceFormat | GraphFormat,\n): void {\n if (format === 'compact-json') {\n writeStdout(renderCompactJson(compactTrace(db, start, options)));\n return;\n }\n const result = trace(db, start, options);\n writeStdout(renderDetailedTrace(result, format));\n}\n\nfunction renderDetailedTrace(\n result: TraceResult,\n format: Exclude<TraceFormat, 'compact-json'> | Exclude<GraphFormat, 'compact-json'>,\n): string {\n if (format === 'json') return renderTraceJson(result);\n if (format === 'mermaid') return renderMermaid(result);\n return renderTraceTable(result);\n}\n\nfunction runTraceCommand(opts: TraceCommandOptions): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const start: TraceStart = {\n repo: opts.repo, servicePath: opts.service, operation: opts.operation,\n operationPath: opts.path, handler: opts.handler,\n };\n const options: TraceOptions = {\n depth: Number(opts.depth), workspaceId, vars: parseVars(opts.var),\n includeExternal: Boolean(opts.includeExternal),\n includeDb: Boolean(opts.includeDb), includeAsync: Boolean(opts.includeAsync),\n implementationRepo: opts.implementationRepo,\n implementationHints: opts.implementationHint.map(parseImplementationHint),\n dynamicMode: parseDynamicMode(opts.dynamicMode),\n maxDynamicCandidates: parsePositiveInteger(opts.maxDynamicCandidates, 5),\n };\n writeTraceOutput(db, start, options, opts.format);\n });\n}\n\nfunction runGraphCommand(opts: GraphCommandOptions): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const start: TraceStart = {\n repo: opts.repo, operation: opts.operation, servicePath: opts.service,\n operationPath: opts.path,\n };\n const options: TraceOptions = {\n depth: 100, workspaceId, includeAsync: true, includeDb: true,\n includeExternal: true, vars: parseVars(opts.var),\n implementationRepo: opts.implementationRepo,\n implementationHints: opts.implementationHint.map(parseImplementationHint),\n dynamicMode: parseDynamicMode(opts.dynamicMode),\n maxDynamicCandidates: parsePositiveInteger(opts.maxDynamicCandidates, 5),\n };\n writeTraceOutput(db, start, options, opts.format);\n });\n}\n\nfunction configuredProgram(): Command {\n return new Command()\n .name('service-flow')\n .description(\n 'Trace SAP CAP service-to-service flows across multi-repository workspaces',\n )\n .version(VERSION);\n}\n\nfunction registerInitCommand(program: Command): void {\n program\n .command('init')\n .argument('<workspace>')\n .option('--db <path>')\n .option('--ignore <pattern...>')\n .action(\n (workspace: string, opts: { db?: string; ignore?: string[] }) =>\n void init(workspace, opts).catch(fail),\n );\n}\n\nfunction registerIndexCommand(program: Command): void {\n program\n .command('index')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--force')\n .action(\n (opts: { workspace?: string; repo?: string; force?: boolean }) =>\n void withWorkspace(opts.workspace, async (db, workspaceId) => {\n const r = await indexWorkspace(db, workspaceId, {\n repo: opts.repo,\n force: Boolean(opts.force),\n });\n const outcome = indexCommandOutcome(r);\n writeStdout(outcome.stdout);\n if (outcome.exitCode !== 0) process.exitCode = outcome.exitCode;\n }).catch(fail),\n );\n}\n\nfunction registerLinkCommand(program: Command): void {\n program\n .command('link')\n .option('--workspace <path>')\n .option('--force')\n .action(\n (opts: { workspace?: string }) =>\n void withWorkspace(opts.workspace, (db, workspaceId) => {\n const r = linkWorkspace(db, workspaceId);\n const upgradeWarnings = linkUpgradeWarnings(db, workspaceId);\n writeStdout(\n `${upgradeWarnings.length ? `Warnings: ${upgradeWarnings.map((item) => String(item.code)).join(', ')}. Run service-flow doctor --strict for remediation.\\n` : ''}Linked ${r.edgeCount} edges: ${r.remoteResolvedCount} remote operation calls resolved, ${r.localResolvedCount} local operation calls resolved, ${r.unresolvedCount} unresolved operation calls, ${r.ambiguousCount} ambiguous operation calls, ${r.dynamicCount} dynamic operation calls, ${r.terminalCount} terminal call edges, ${r.dependencyResolvedCount} dependency resolved, ${r.dependencyAmbiguousCount} dependency ambiguous, ${r.implementationResolvedCount} implementation resolved, ${r.implementationAmbiguousCount} implementation ambiguous, ${r.implementationUnresolvedCount} implementation unresolved, ${r.subscriptionHandlerResolvedCount} subscription handlers resolved, ${r.subscriptionHandlerAmbiguousCount} subscription handlers ambiguous, ${r.subscriptionHandlerUnresolvedCount} subscription handlers unresolved, ${r.subscriptionHandlerMissingAssociationCount} subscription handler associations missing\\n`,\n );\n }).catch(fail),\n );\n}\n\nfunction registerTraceCommand(program: Command): void {\n program\n .command('trace')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--operation <name>')\n .option('--service <path>')\n .option('--path <operationPath>')\n .option('--handler <name>')\n .option('--depth <n>', 'trace depth', '25')\n .addOption(traceFormatOption())\n .option('--include-external')\n .option('--include-db')\n .option('--include-async')\n .option('--implementation-repo <name>')\n .option('--implementation-hint <scope>', 'scoped implementation hint', collect, [])\n .option('--var <key=value>', 'dynamic variable', collect, [])\n .option('--dynamic-mode <mode>', 'strict|candidates|infer', 'strict')\n .option('--max-dynamic-candidates <n>', 'maximum dynamic candidates to show', '5')\n .action((opts: TraceCommandOptions) => void runTraceCommand(opts).catch(fail));\n}\n\nfunction listRepositoriesCommand(\n opts: { workspace?: string },\n): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) =>\n writeStdout(\n renderJson(\n listRepositories(db, workspaceId).map((repo) => ({\n name: repo.name,\n kind: repo.kind,\n packageName: repo.package_name,\n })),\n ),\n ));\n}\n\nfunction listServicesCommand(\n opts: { workspace?: string; repo?: string },\n): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const selection = opts.repo\n ? selectRepository(db, opts.repo, workspaceId) : {};\n if (selection.diagnostic) {\n writeStdout(renderJson([selection.diagnostic]));\n return;\n }\n const repo = selection.repo;\n const rows = db.prepare(\n 'SELECT r.name repo,s.service_path servicePath,s.qualified_name qualifiedName FROM cds_services s JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND (? IS NULL OR s.repo_id=?) ORDER BY r.name,s.service_path',\n ).all(workspaceId, repo?.id, repo?.id);\n writeStdout(renderJson(rows));\n });\n}\n\nfunction listOperationsCommand(\n opts: { workspace?: string; repo?: string; service?: string },\n): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const selection = opts.repo\n ? selectRepository(db, opts.repo, workspaceId) : {};\n if (selection.diagnostic) {\n writeStdout(renderJson([selection.diagnostic]));\n return;\n }\n const repo = selection.repo;\n const rows = db.prepare(\n 'SELECT r.name repo,s.service_path servicePath,o.operation_name operation,o.operation_path path FROM cds_operations o JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND (? IS NULL OR s.repo_id=?) AND (? IS NULL OR s.service_path=?)',\n ).all(\n workspaceId, repo?.id, repo?.id, opts.service, opts.service,\n );\n writeStdout(renderJson(rows));\n });\n}\n\nfunction listCallsCommand(\n opts: { workspace?: string; repo?: string; operation?: string },\n): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const selection = opts.repo\n ? selectRepository(db, opts.repo, workspaceId) : {};\n if (selection.diagnostic) {\n writeStdout(renderJson([selection.diagnostic]));\n return;\n }\n const repo = selection.repo;\n const rows = db.prepare(\n 'SELECT r.name repo,c.call_type type,c.operation_path_expr path,c.source_file file,c.source_line line FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id WHERE r.workspace_id=? AND (? IS NULL OR c.repo_id=?) AND (? IS NULL OR c.operation_path_expr=? OR c.operation_path_expr=? OR c.payload_summary LIKE ?)',\n ).all(\n workspaceId, repo?.id, repo?.id, opts.operation, opts.operation,\n opts.operation ? `/${opts.operation}` : undefined,\n opts.operation ? `%${opts.operation}%` : undefined,\n );\n writeStdout(renderJson(rows));\n });\n}\n\nfunction registerListCommands(program: Command): void {\n const list = program.command('list');\n list\n .command('repos')\n .option('--workspace <path>')\n .action(\n (opts: { workspace?: string }) =>\n void listRepositoriesCommand(opts).catch(fail),\n );\n list\n .command('services')\n .option('--workspace <path>')\n .option('--repo <name>')\n .action(\n (opts: { workspace?: string; repo?: string }) =>\n void listServicesCommand(opts).catch(fail),\n );\n list\n .command('operations')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--service <path>')\n .action(\n (opts: { workspace?: string; repo?: string; service?: string }) =>\n void listOperationsCommand(opts).catch(fail),\n );\n list\n .command('calls')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--operation <name>')\n .action(\n (opts: { workspace?: string; repo?: string; operation?: string }) =>\n void listCallsCommand(opts).catch(fail),\n );\n}\n\nfunction registerGraphCommand(program: Command): void {\n program\n .command('graph')\n .option('--workspace <path>')\n .option('--repo <name>')\n .option('--operation <name>')\n .option('--service <path>')\n .option('--path <operationPath>')\n .addOption(graphFormatOption())\n .option('--implementation-repo <name>')\n .option('--implementation-hint <scope>', 'scoped implementation hint', collect, [])\n .option('--var <key=value>', 'dynamic variable', collect, [])\n .option('--dynamic-mode <mode>', 'strict|candidates|infer', 'strict')\n .option('--max-dynamic-candidates <n>', 'maximum dynamic candidates to show', '5')\n .action((opts: GraphCommandOptions) => void runGraphCommand(opts).catch(fail));\n}\n\nfunction inspectRepositoryCommand(\n name: string,\n opts: { workspace?: string },\n): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const selection = selectRepository(db, name, workspaceId);\n writeStdout(renderJson(\n selection.repo ?? selection.diagnostic ?? { error: 'repo not found' },\n ));\n });\n}\n\nfunction inspectOperationCommand(\n selector: string,\n opts: { workspace?: string },\n): Promise<void> {\n return withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const rows = db.prepare(\n 'SELECT o.* FROM cds_operations o JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND (o.operation_name=? OR o.operation_path=?)',\n ).all(workspaceId, selector, selector);\n writeStdout(renderJson(rows));\n });\n}\n\nfunction registerInspectCommands(program: Command): void {\n const inspect = program.command('inspect');\n inspect\n .command('repo')\n .argument('<name>')\n .option('--workspace <path>')\n .action(\n (name: string, opts: { workspace?: string }) =>\n void inspectRepositoryCommand(name, opts).catch(fail),\n );\n inspect\n .command('operation')\n .argument('<selector>')\n .option('--workspace <path>')\n .action(\n (selector: string, opts: { workspace?: string }) =>\n void inspectOperationCommand(selector, opts).catch(fail),\n );\n}\n\nfunction registerDoctorCommand(program: Command): void {\n program\n .command('doctor')\n .option('--workspace <path>')\n .option('--strict')\n .option('--detail')\n .option('--format <format>', 'json|table')\n .action(\n (opts: { workspace?: string; strict?: boolean; detail?: boolean; format?: string }) =>\n void withReadOnlyWorkspace(opts.workspace, (db, workspaceId) => {\n const allDiagnostics = doctorDiagnostics(db, Boolean(opts.strict), {\n detail: Boolean(opts.detail), workspaceId,\n });\n writeStdout(renderDoctorDiagnostics(allDiagnostics, opts.format));\n }).catch(fail),\n );\n}\n\nfunction registerCleanCommand(program: Command): void {\n program\n .command('clean')\n .option('--workspace <path>')\n .option('--db-only')\n .action(\n (opts: { workspace?: string; dbOnly?: boolean }) =>\n void (async () => {\n const config = await loadWorkspaceConfig(opts.workspace);\n await cleanWorkspaceState(config, Boolean(opts.dbOnly));\n writeStdout('Cleaned service-flow state\\n');\n })().catch(fail),\n );\n}\n\nexport function createProgram(): Command {\n const program = configuredProgram();\n registerInitCommand(program);\n registerIndexCommand(program);\n registerLinkCommand(program);\n registerTraceCommand(program);\n registerListCommands(program);\n registerGraphCommand(program);\n registerInspectCommands(program);\n registerDoctorCommand(program);\n registerCleanCommand(program);\n return program;\n}\nfunction collect(value: string, previous: string[]): string[] {\n previous.push(value);\n return previous;\n}\nfunction parseDynamicMode(value: string | undefined): DynamicMode {\n if (value === undefined || value === 'strict') return 'strict';\n if (value === 'candidates' || value === 'infer') return value;\n throw new Error(`Invalid --dynamic-mode ${value}; expected strict, candidates, or infer`);\n}\nfunction parsePositiveInteger(value: string | undefined, fallback: number): number {\n const parsed = Number(value);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;\n}\nfunction fail(error: unknown): void {\n process.stderr.write(\n `${error instanceof Error ? error.message : String(error)}\\n`,\n );\n process.exitCode = 1;\n}\ncreateProgram().parse(process.argv);\n","export const DEFAULT_IGNORES = [\n 'node_modules',\n 'gen',\n 'dist',\n 'coverage',\n '.git',\n '.turbo',\n '.next',\n '.cache',\n '.service-flow'\n] as const;\nexport const CONFIG_DIR = '.service-flow';\nexport const CONFIG_FILE = 'config.json';\nexport const DEFAULT_DB_FILE = 'service-flow.db';\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport {\n CONFIG_DIR,\n CONFIG_FILE,\n DEFAULT_DB_FILE,\n DEFAULT_IGNORES,\n} from './defaults.js';\nconst schema = z.object({\n rootPath: z.string(),\n dbPath: z.string(),\n ignore: z.array(z.string()),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type WorkspaceConfig = z.infer<typeof schema>;\nexport function configPath(rootPath: string): string {\n return path.join(rootPath, CONFIG_DIR, CONFIG_FILE);\n}\nexport function defaultDbPath(rootPath: string): string {\n return path.join(rootPath, CONFIG_DIR, DEFAULT_DB_FILE);\n}\nexport async function saveWorkspaceConfig(\n config: WorkspaceConfig,\n): Promise<void> {\n await fs.mkdir(path.dirname(configPath(config.rootPath)), {\n recursive: true,\n });\n await fs.writeFile(\n configPath(config.rootPath),\n `${JSON.stringify(config, null, 2)}\\n`,\n );\n if (path.dirname(config.dbPath) === path.dirname(configPath(config.rootPath)))\n await fs.writeFile(\n path.join(path.dirname(config.dbPath), '.service-flow-state'),\n 'service-flow\\n',\n );\n}\nexport async function loadWorkspaceConfig(\n workspace?: string,\n): Promise<WorkspaceConfig> {\n const root = path.resolve(workspace ?? process.cwd());\n const data = await fs.readFile(configPath(root), 'utf8');\n return schema.parse(JSON.parse(data) as unknown);\n}\nexport function createWorkspaceConfig(\n rootPath: string,\n dbPath?: string,\n ignore: string[] = [...DEFAULT_IGNORES],\n): WorkspaceConfig {\n const now = new Date().toISOString();\n const root = path.resolve(rootPath);\n return {\n rootPath: root,\n dbPath: path.resolve(dbPath ?? defaultDbPath(root)),\n ignore,\n createdAt: now,\n updatedAt: now,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { migrate } from './migrations.js';\nimport { VERSION } from '../version.js';\n\ntype SqlValue = string | number | bigint | Buffer | null | undefined;\ninterface NativeStatement {\n run: (...params: SqlValue[]) => { changes: number };\n get: (...params: SqlValue[]) => Record<string, unknown> | undefined;\n all: (...params: SqlValue[]) => Array<Record<string, unknown>>;\n}\ninterface NativeDatabase {\n exec: (sql: string) => void;\n prepare: (sql: string) => NativeStatement;\n close: () => void;\n}\ninterface NodeSqliteModule {\n DatabaseSync: new (location: string, options?: { open?: boolean; readOnly?: boolean }) => NativeDatabase;\n}\n\nlet sqliteWarningFilterInstalled = false;\nfunction installSqliteWarningFilter(): void {\n if (sqliteWarningFilterInstalled) return;\n sqliteWarningFilterInstalled = true;\n const original = process.emitWarning.bind(process);\n process.emitWarning = ((warning: string | Error, ...args: unknown[]): void => {\n const text = warning instanceof Error ? warning.message : String(warning);\n if (text.includes('SQLite is an experimental feature')) return;\n Reflect.apply(original, process, [warning, ...args]);\n }) as typeof process.emitWarning;\n}\nexport interface Statement {\n run: (...params: unknown[]) => { changes: number };\n get: (...params: unknown[]) => Record<string, unknown> | undefined;\n all: (...params: unknown[]) => Array<Record<string, unknown>>;\n}\nexport interface Db {\n path: string;\n readonly: boolean;\n exec: (sql: string) => void;\n prepare: (sql: string) => Statement;\n pragma: (sql: string) => Array<Record<string, unknown>>;\n transaction: <T>(fn: () => T) => T;\n close: () => void;\n}\nexport interface OpenDatabaseOptions {\n readonly?: boolean;\n migrate?: boolean;\n}\nfunction loadSqlite(): NodeSqliteModule {\n try {\n installSqliteWarningFilter();\n const moduleValue = process.getBuiltinModule('node:sqlite') as unknown;\n if (!moduleValue || typeof moduleValue !== 'object' || !('DatabaseSync' in moduleValue))\n throw new Error('node:sqlite DatabaseSync is unavailable');\n const sqlite = moduleValue as NodeSqliteModule;\n if (typeof sqlite.DatabaseSync !== 'function')\n throw new Error('node:sqlite DatabaseSync is not a constructor');\n return sqlite;\n } catch (error) {\n throw new Error(\n `service-flow ${VERSION} requires Node.js >=24 with node:sqlite DatabaseSync support. Upgrade Node.js or install a service-flow build with a compatible SQLite driver.`,\n { cause: error },\n );\n }\n}\nfunction bindParams(params: unknown[]): SqlValue[] {\n return params.map((param) => {\n if (param === undefined || param === null) return null;\n if (typeof param === 'string' || typeof param === 'number' || typeof param === 'bigint' || Buffer.isBuffer(param)) return param;\n if (typeof param === 'boolean') return param ? 1 : 0;\n return JSON.stringify(param);\n });\n}\nexport function openDatabase(dbPath: string, options: OpenDatabaseOptions = {}): Db {\n fs.mkdirSync(path.dirname(dbPath), { recursive: true });\n const sqlite = loadSqlite();\n const native = new sqlite.DatabaseSync(dbPath, { readOnly: Boolean(options.readonly) });\n let inTransaction = false;\n const db: Db = {\n path: dbPath,\n readonly: Boolean(options.readonly),\n exec(sql: string): void {\n native.exec(sql);\n },\n prepare(sql: string): Statement {\n const statement = native.prepare(sql);\n return {\n run: (...params: unknown[]) => statement.run(...bindParams(params)),\n get: (...params: unknown[]) => statement.get(...bindParams(params)),\n all: (...params: unknown[]) => statement.all(...bindParams(params)),\n };\n },\n pragma(sql: string): Array<Record<string, unknown>> {\n const normalized = sql.trim().replace(/;$/, '');\n if (/=/.test(normalized)) {\n native.exec(`PRAGMA ${normalized}`);\n return [];\n }\n return native.prepare(`PRAGMA ${normalized}`).all();\n },\n transaction<T>(fn: () => T): T {\n if (inTransaction) return fn();\n native.exec('BEGIN IMMEDIATE');\n inTransaction = true;\n try {\n const result = fn();\n native.exec('COMMIT');\n return result;\n } catch (error) {\n native.exec('ROLLBACK');\n throw error;\n } finally {\n inTransaction = false;\n }\n },\n close(): void {\n native.close();\n },\n };\n db.pragma('busy_timeout = 10000');\n db.pragma('foreign_keys = ON');\n if (!options.readonly) {\n db.pragma('journal_mode = WAL');\n if (options.migrate !== false) migrate(db);\n }\n return db;\n}\nexport function openReadOnlyDatabase(dbPath: string): Db {\n return openDatabase(dbPath, { readonly: true, migrate: false });\n}\n","import type { Db } from './connection.js';\nimport type {\n CdsRequire,\n CdsServiceFact,\n HandlerClassFact,\n HandlerMethodFact,\n HandlerRegistrationFact,\n ServiceBindingFact,\n ExecutableSymbolFact,\n} from '../types.js';\nimport {\n selectCallOwner,\n type OwnerCandidate,\n} from '../parsers/004-fact-identity.js';\nimport {\n PreparedRepositorySnapshotError,\n type PreparedSnapshotFailureCode,\n} from './013-index-publication-failure.js';\nexport interface RepoRow {\n id: number;\n name: string;\n absolute_path: string;\n relative_path: string;\n package_name: string | null;\n package_version: string | null;\n dependencies_json: string;\n kind: string;\n fingerprint?: string | null;\n fact_generation?: number;\n graph_generation?: number;\n graph_stale_reason?: string | null;\n fact_analyzer_version?: string | null;\n}\nexport interface WorkspaceRow {\n id: number;\n root_path: string;\n db_path: string;\n}\nfunction initialPackagePublicSurface(packageName?: string): string {\n return JSON.stringify({\n schema: 'service-flow/package-public-surface@1',\n status: packageName ? 'incomplete' : 'not_applicable',\n reason: packageName ? 'package_surface_pending_index' : null,\n recordCap: 256,\n total: 0,\n shown: 0,\n omitted: 0,\n packageName: packageName ?? null,\n exportsPresent: false,\n exportsAuthoritative: false,\n main: null,\n module: null,\n entries: [],\n scopes: [],\n });\n}\nexport function upsertWorkspace(\n db: Db,\n rootPath: string,\n dbPath: string,\n): number {\n const now = new Date().toISOString();\n db.prepare(\n 'INSERT INTO workspaces(root_path,db_path,created_at,updated_at) VALUES(?,?,?,?) ON CONFLICT(root_path) DO UPDATE SET db_path=excluded.db_path,updated_at=excluded.updated_at',\n ).run(rootPath, dbPath, now, now);\n return Number(\n db.prepare('SELECT id FROM workspaces WHERE root_path=?').get(rootPath)?.id,\n );\n}\nexport function getWorkspace(\n db: Db,\n rootPath: string,\n): WorkspaceRow | undefined {\n return db\n .prepare('SELECT * FROM workspaces WHERE root_path=?')\n .get(rootPath) as WorkspaceRow | undefined;\n}\nexport function upsertRepository(\n db: Db,\n workspaceId: number,\n r: {\n name: string;\n absolutePath: string;\n relativePath: string;\n isGitRepo: boolean;\n packageName?: string;\n packageVersion?: string;\n dependencies?: Record<string, string>;\n kind?: string;\n },\n): number {\n db.prepare(\n `INSERT INTO repositories(workspace_id,name,absolute_path,relative_path,\n package_name,package_version,dependencies_json,\n package_public_surface_json,kind,is_git_repo)\n VALUES(?,?,?,?,?,?,?,?,?,?)\n ON CONFLICT(workspace_id,absolute_path) DO UPDATE SET\n name=excluded.name,relative_path=excluded.relative_path,\n package_name=excluded.package_name,\n package_version=excluded.package_version,\n dependencies_json=excluded.dependencies_json,kind=excluded.kind`,\n ).run(\n workspaceId,\n r.name,\n r.absolutePath,\n r.relativePath,\n r.packageName,\n r.packageVersion,\n JSON.stringify(r.dependencies ?? {}),\n initialPackagePublicSurface(r.packageName),\n r.kind ?? 'unknown',\n r.isGitRepo ? 1 : 0,\n );\n return Number(\n db\n .prepare(\n 'SELECT id FROM repositories WHERE workspace_id=? AND absolute_path=?',\n )\n .get(workspaceId, r.absolutePath)?.id,\n );\n}\nexport function listRepositories(db: Db, workspaceId?: number): RepoRow[] {\n return db\n .prepare('SELECT * FROM repositories WHERE (? IS NULL OR workspace_id=?) ORDER BY name,absolute_path,id')\n .all(workspaceId, workspaceId) as unknown as RepoRow[];\n}\nexport function repoByName(\n db: Db,\n name: string,\n workspaceId?: number,\n): RepoRow | undefined {\n const matches = reposByName(db, name, workspaceId);\n return matches.length === 1 ? matches[0] : undefined;\n}\nexport function reposByName(\n db: Db,\n name: string,\n workspaceId?: number,\n): RepoRow[] {\n return db\n .prepare(`SELECT * FROM repositories\n WHERE (? IS NULL OR workspace_id=?) AND (name=? OR package_name=?)\n ORDER BY name,absolute_path,id`)\n .all(workspaceId, workspaceId, name, name) as unknown as RepoRow[];\n}\nexport function clearRepoFacts(db: Db, repoId: number): void {\n for (const t of [\n 'cds_requires',\n 'cds_services',\n 'handler_classes',\n 'outbound_calls',\n 'symbol_calls',\n 'handler_registrations',\n 'service_bindings',\n 'symbols',\n 'diagnostics',\n 'files',\n ])\n db.prepare(`DELETE FROM ${t} WHERE repo_id=?`).run(repoId);\n db.prepare('DELETE FROM search_index WHERE repo=?').run(String(repoId));\n}\nexport function insertRequires(\n db: Db,\n repoId: number,\n rows: CdsRequire[],\n): void {\n const stmt = db.prepare(\n 'INSERT INTO cds_requires(repo_id,alias,kind,model,destination,service_path,request_timeout,raw_json) VALUES(?,?,?,?,?,?,?,?)',\n );\n for (const r of rows)\n stmt.run(\n repoId,\n r.alias,\n r.kind,\n r.model,\n r.destination,\n r.servicePath,\n r.requestTimeout,\n r.rawJson,\n );\n}\nexport function insertService(\n db: Db,\n repoId: number,\n s: CdsServiceFact,\n): number {\n const id = Number(\n db\n .prepare(\n 'INSERT INTO cds_services(repo_id,namespace,service_name,qualified_name,service_path,is_extend,source_file,source_line,extension_local_ref,extension_imported_symbol,extension_local_alias,extension_module_specifier,extension_import_kind) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) RETURNING id',\n )\n .get(\n repoId,\n s.namespace,\n s.serviceName,\n s.qualifiedName,\n s.servicePath,\n s.isExtend ? 1 : 0,\n s.sourceFile,\n s.sourceLine,\n s.extension?.localReference,\n s.extension?.importedSymbol,\n s.extension?.localAlias,\n s.extension?.moduleSpecifier,\n s.extension?.importKind,\n )?.id,\n );\n const stmt = db.prepare(\n 'INSERT INTO cds_operations(service_id,operation_type,operation_name,operation_path,params_json,return_type,source_file,source_line,provenance,base_operation_id) VALUES(?,?,?,?,?,?,?,?,?,?)',\n );\n db.prepare(\n 'INSERT INTO search_index(kind,name,path,repo) VALUES(?,?,?,?)',\n ).run('service', s.qualifiedName, s.servicePath, String(repoId));\n for (const o of s.operations)\n stmt.run(\n id,\n o.operationType,\n o.operationName,\n o.operationPath,\n o.paramsJson,\n o.returnType,\n o.sourceFile,\n o.sourceLine,\n o.provenance ?? 'direct',\n o.baseOperationId ?? null,\n );\n const search = db.prepare(\n 'INSERT INTO search_index(kind,name,path,repo) VALUES(?,?,?,?)',\n );\n for (const o of s.operations)\n search.run('operation', o.operationName, o.operationPath, String(repoId));\n return id;\n}\nexport function insertHandler(\n db: Db,\n repoId: number,\n h: HandlerClassFact,\n): number {\n const sid = insertHandlerClassSymbol(db, repoId, h);\n const hid = Number(\n db\n .prepare(\n 'INSERT INTO handler_classes(repo_id,symbol_id,class_name,source_file,source_line) VALUES(?,?,?,?,?) RETURNING id',\n )\n .get(repoId, sid, h.className, h.sourceFile, h.sourceLine)?.id,\n );\n const stmt = db.prepare(\n 'INSERT INTO handler_methods(handler_class_id,method_name,decorator_kind,decorator_value,decorator_raw_expression,decorator_resolution_json,source_file,source_line) VALUES(?,?,?,?,?,?,?,?)',\n );\n for (const m of h.methods)\n stmt.run(\n hid,\n m.methodName,\n m.decoratorKind,\n m.decoratorValue,\n m.decoratorRawExpression,\n JSON.stringify(canonicalHandlerMethodResolution(m)),\n m.sourceFile,\n m.sourceLine,\n );\n insertHandlerIndexDiagnostic(db, repoId, h);\n return hid;\n}\nfunction insertHandlerClassSymbol(\n db: Db,\n repoId: number,\n h: HandlerClassFact,\n): number {\n const classEvidence = {\n hasHandlerDecorator: h.hasHandlerDecorator ?? false,\n classDecoratorNames: h.classDecoratorNames ?? [],\n observedDecoratorNames: h.observedDecoratorNames ?? [],\n unsupportedDecoratorNames: h.unsupportedDecoratorNames ?? [],\n unsupportedMethods: h.methods\n .filter((method) => !handlerMethodIsExecutable(method))\n .map((method) => ({\n methodName: method.methodName,\n decoratorKind: method.decoratorKind,\n sourceFile: method.sourceFile,\n sourceLine: method.sourceLine,\n reason: method.decoratorResolution.unresolvedReason,\n })),\n };\n return Number(\n db\n .prepare(\n 'INSERT INTO symbols(repo_id,kind,name,qualified_name,exported,start_line,end_line,source_file,evidence_json) VALUES(?,?,?,?,?,?,?,?,?) RETURNING id',\n )\n .get(\n repoId,\n 'class',\n h.className,\n h.className,\n 1,\n h.sourceLine,\n h.sourceLine,\n h.sourceFile,\n JSON.stringify(classEvidence),\n )?.id,\n );\n}\nfunction insertHandlerIndexDiagnostic(\n db: Db,\n repoId: number,\n h: HandlerClassFact,\n): void {\n if (!h.hasHandlerDecorator) return;\n const hasExecutable = h.methods.some(handlerMethodIsExecutable);\n const unsupported = h.methods.filter((method) =>\n !handlerMethodIsExecutable(method));\n if (hasExecutable && unsupported.length === 0) return;\n const code = hasExecutable\n ? 'handler_decorators_not_indexed'\n : 'handler_methods_not_indexed';\n const names = unsupported.map((method) => method.decoratorKind).sort();\n const detail = names.length > 0\n ? ` Unsupported decorators: ${[...new Set(names)].join(', ')}.`\n : '';\n db.prepare(\n 'INSERT INTO diagnostics(repo_id,severity,code,message,source_file,source_line) VALUES(?,?,?,?,?,?)',\n ).run(\n repoId,\n 'warning',\n code,\n hasExecutable\n ? `Handler class ${h.className} contains methods that were not indexed.${detail}`\n : `Handler class ${h.className} has no indexed executable methods; use a supported CAP handler decorator and re-index.${detail}`,\n h.sourceFile,\n h.sourceLine,\n );\n}\nexport function canonicalHandlerMethodResolution(\n method: HandlerMethodFact,\n): HandlerMethodFact['decoratorResolution'] {\n const handlerKind = method.handlerKind\n ?? method.decoratorResolution.handlerKind\n ?? legacyHandlerKind(method.decoratorKind);\n const executable = method.executable\n ?? method.decoratorResolution.executable\n ?? (handlerKind === 'operation' || handlerKind === 'event'\n || handlerKind === 'entity_lifecycle');\n return {\n ...method.decoratorResolution,\n handlerKind,\n executable,\n lifecyclePhase: method.lifecyclePhase\n ?? method.decoratorResolution.lifecyclePhase,\n lifecycleEvent: method.lifecycleEvent\n ?? method.decoratorResolution.lifecycleEvent,\n };\n}\nexport function handlerMethodIsExecutable(method: HandlerMethodFact): boolean {\n return canonicalHandlerMethodResolution(method).executable === true;\n}\nfunction legacyHandlerKind(kind: string): HandlerMethodFact['handlerKind'] {\n if (kind === 'Event') return 'event';\n if (['Action', 'Func', 'On'].includes(kind)) return 'operation';\n return 'unsupported_decorator';\n}\nexport function insertRegistrations(\n db: Db,\n repoId: number,\n rows: HandlerRegistrationFact[],\n): void {\n const stmt = db.prepare(\n 'INSERT INTO handler_registrations(repo_id,handler_class_id,class_name,import_source,registration_file,registration_line,registration_kind,confidence) VALUES(?,?,?,?,?,?,?,?)',\n );\n for (const r of rows) {\n const handlerClass = r.className\n ? (db\n .prepare(\n 'SELECT id FROM handler_classes WHERE repo_id=? AND class_name=? ORDER BY id',\n )\n .all(repoId, r.className) as Array<{ id: number }>)\n : [];\n stmt.run(\n repoId,\n handlerClass.length === 1 ? handlerClass[0]?.id : null,\n r.className,\n r.importSource,\n r.registrationFile,\n r.registrationLine,\n r.registrationKind,\n r.confidence,\n );\n }\n}\nexport function insertBindings(\n db: Db,\n repoId: number,\n rows: ServiceBindingFact[],\n): void {\n assertUniquePreparedBindingSites(rows);\n const stmt = db.prepare(\n 'INSERT INTO service_bindings(repo_id,symbol_id,variable_name,alias,alias_expr,destination_expr,service_path_expr,is_dynamic,placeholders_json,source_file,source_line,binding_site_start_offset,binding_site_end_offset,owner_resolution,helper_chain_json) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\n );\n for (const r of rows)\n stmt.run(\n repoId,\n bindingOwnerId(db, repoId, r),\n r.variableName,\n r.alias,\n r.aliasExpr,\n r.destinationExpr,\n r.servicePathExpr,\n r.isDynamic ? 1 : 0,\n JSON.stringify(r.placeholders),\n r.sourceFile,\n r.sourceLine,\n r.bindingSiteStartOffset,\n r.bindingSiteEndOffset,\n r.ownerResolution,\n r.helperChain ? JSON.stringify(r.helperChain) : null,\n );\n}\n\ninterface PersistedOwnerCandidate extends OwnerCandidate {\n id: number;\n}\n\nfunction bindingSnapshotError(\n failureCode: PreparedSnapshotFailureCode,\n fact: ServiceBindingFact,\n): PreparedRepositorySnapshotError {\n return new PreparedRepositorySnapshotError(failureCode, {\n factKind: 'service_binding',\n sourceFile: fact.sourceFile,\n sourceLine: fact.sourceLine,\n callSiteStartOffset: fact.bindingSiteStartOffset,\n callSiteEndOffset: fact.bindingSiteEndOffset,\n });\n}\n\nfunction persistedOwnerCandidates(\n db: Db,\n repoId: number,\n fact: ServiceBindingFact,\n): PersistedOwnerCandidate[] {\n const rows = db.prepare(`SELECT id,kind,qualified_name qualifiedName,\n start_offset startOffset,end_offset endOffset FROM symbols\n WHERE repo_id=? AND source_file=? AND start_offset<=? AND end_offset>=?`)\n .all(\n repoId, fact.sourceFile, fact.bindingSiteStartOffset,\n fact.bindingSiteEndOffset,\n );\n return rows.flatMap((row) =>\n typeof row.id === 'number' && typeof row.kind === 'string'\n && typeof row.qualifiedName === 'string'\n && typeof row.startOffset === 'number'\n && typeof row.endOffset === 'number'\n ? [{\n id: row.id,\n kind: row.kind,\n qualifiedName: row.qualifiedName,\n startOffset: row.startOffset,\n endOffset: row.endOffset,\n }]\n : []);\n}\n\nfunction bindingOwnerId(\n db: Db,\n repoId: number,\n fact: ServiceBindingFact,\n): number | null {\n const candidates = persistedOwnerCandidates(db, repoId, fact);\n const selected = selectCallOwner(\n candidates,\n fact.bindingSiteStartOffset ?? -1,\n fact.bindingSiteEndOffset ?? -1,\n );\n if (fact.ownerResolution === 'ownerless_file_scope') {\n if (selected.status !== 'none')\n throw bindingSnapshotError('binding_owner_mismatch', fact);\n return null;\n }\n if (fact.ownerResolution !== 'owned_exact'\n || selected.status !== 'resolved'\n || selected.owner?.qualifiedName !== fact.sourceSymbolQualifiedName)\n throw bindingSnapshotError('binding_owner_mismatch', fact);\n const owner = selected.owner;\n if (!owner)\n throw bindingSnapshotError('binding_owner_mismatch', fact);\n return owner.id;\n}\n\nfunction assertUniquePreparedBindingSites(\n rows: readonly ServiceBindingFact[],\n): void {\n const seen = new Set<string>();\n for (const row of rows) {\n if (row.bindingSiteStartOffset === undefined\n || row.bindingSiteEndOffset === undefined)\n throw bindingSnapshotError('binding_site_missing', row);\n const key = [\n row.sourceFile, row.variableName,\n row.bindingSiteStartOffset, row.bindingSiteEndOffset,\n ].join('\\u0000');\n if (seen.has(key))\n throw bindingSnapshotError('duplicate_service_binding_site', row);\n seen.add(key);\n }\n}\nexport function insertExecutableSymbols(db: Db, repoId: number, rows: ExecutableSymbolFact[]): void {\n const stmt = db.prepare('INSERT INTO symbols(repo_id,file_id,kind,name,qualified_name,exported,start_line,end_line,start_offset,end_offset,source_file,exported_name,evidence_json) VALUES(?,(SELECT id FROM files WHERE repo_id=? AND relative_path=?),?,?,?,?,?,?,?,?,?,?,?)');\n for (const r of rows) stmt.run(repoId, repoId, r.sourceFile, r.kind, r.localName, r.qualifiedName, r.exported ? 1 : 0, r.startLine, r.endLine, r.startOffset, r.endOffset, r.sourceFile, r.exportedName, r.importExportEvidence ? JSON.stringify(r.importExportEvidence) : null);\n}\nexport { insertCalls, insertSymbolCalls } from './000-call-fact-repository.js';\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { PackageFacts, RepoKind } from '../types.js';\nexport async function classifyRepository(\n repoPath: string,\n facts: PackageFacts\n): Promise<RepoKind> {\n const hasCdsDep = Boolean(\n facts.dependencies['@sap/cds'] ??\n facts.dependencies.cds ??\n facts.dependencies['cds-routing-handlers']\n );\n const cdsFiles = await findFiles(repoPath, '.cds');\n const serverFiles = await Promise.all(\n ['srv/server.ts', 'srv/server.js', 'src/server.ts', 'src/server.js'].map(\n async (f) =>\n fs\n .access(path.join(repoPath, f))\n .then(() => true)\n .catch(() => false)\n )\n );\n const helper =\n Object.keys(facts.dependencies).includes('cds-routing-handlers') ||\n facts.packageName?.includes('helper') === true;\n if (helper && cdsFiles.length > 0) return 'mixed';\n if (helper) return 'helper-package';\n if (hasCdsDep && (cdsFiles.length > 0 || serverFiles.some(Boolean)))\n return 'cap-service';\n if (cdsFiles.length > 0)\n return serverFiles.some(Boolean) ? 'cap-service' : 'cap-db-model';\n return 'unknown';\n}\n\nasync function findFiles(root: string, suffix: string): Promise<string[]> {\n const out: string[] = [];\n async function walk(dir: string): Promise<void> {\n const entries = await fs\n .readdir(dir, { withFileTypes: true })\n .catch(() => []);\n for (const e of entries) {\n if (e.isDirectory()) {\n if (!['node_modules', 'dist', 'gen', '.git'].includes(e.name))\n await walk(path.join(dir, e.name));\n } else if (e.name.endsWith(suffix)) out.push(path.join(dir, e.name));\n }\n }\n await walk(root);\n return out;\n}\n","export interface DiagnosticInput {\n severity: 'info' | 'warning' | 'error';\n code: string;\n message: string;\n sourceFile?: string;\n sourceLine?: number;\n}\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { Db } from '../db/connection.js';\nimport {\n clearRepoFacts,\n insertBindings,\n insertCalls,\n insertExecutableSymbols,\n insertHandler,\n handlerMethodIsExecutable,\n insertRegistrations,\n insertSymbolCalls,\n insertRequires,\n insertService,\n type RepoRow,\n} from '../db/repositories.js';\nimport { classifyRepository } from '../discovery/classify-repository.js';\nimport { parseCdsFile } from '../parsers/cds-parser.js';\nimport { parseDecorators } from '../parsers/decorator-parser.js';\nimport { parseHandlerRegistrations } from '../parsers/handler-registration-parser.js';\nimport {\n classifyOutboundCallsInSource,\n parseOutboundCalls,\n} from '../parsers/outbound-call-parser.js';\nimport { parseExecutableSymbols } from '../parsers/symbol-parser.js';\nimport {\n loadPackageJsonSnapshot,\n} from '../parsers/package-json-parser.js';\nimport { parseServiceBindings } from '../parsers/service-binding-parser.js';\nimport { reconcileSourceFacts } from '../parsers/007-source-fact-reconciliation.js';\nimport {\n analyzeRepositoryPackageSurface,\n mergePackageSymbolEvidence,\n} from '../parsers/008-package-surface-publication.js';\nimport type {\n PackagePublicSurfaceFact,\n} from '../parsers/003-package-public-surface.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport { errorMessage } from '../utils/diagnostics.js';\nimport { sha256Text } from '../utils/hashing.js';\nimport { ANALYZER_VERSION } from '../version.js';\nimport {\n createPackageInvalidationBatch,\n finalizePackageTargetInvalidations,\n invalidatePackageTargetFacts,\n type PackageInvalidationBatch,\n} from '../db/004-package-target-invalidation.js';\nimport {\n isPreparedRepositorySnapshotError,\n recordPreparedSnapshotFailure,\n} from '../db/013-index-publication-failure.js';\nimport {\n loadRepositorySourceContext,\n type RepositorySourceContext,\n type SourceContextInstrumentation,\n} from '../parsers/ts-project.js';\nimport type { CdsServiceFact, HandlerClassFact, HandlerRegistrationFact, OutboundCallFact, PackageFacts, ServiceBindingFact, ExecutableSymbolFact, SymbolCallFact } from '../types.js';\nexport interface IndexRepoResult {\n fileCount: number;\n diagnosticCount: number;\n skipped: boolean;\n}\ninterface ParsedFacts {\n services: CdsServiceFact[];\n handlers: HandlerClassFact[];\n registrations: HandlerRegistrationFact[];\n bindings: ServiceBindingFact[];\n calls: OutboundCallFact[];\n symbols: ExecutableSymbolFact[];\n symbolCalls: SymbolCallFact[];\n fileRecords: Array<{ relativePath: string; extension: string; sha256: string; sizeBytes: number }>;\n}\nexport interface PreparedRepositoryIndex extends IndexRepoResult {\n repo: RepoRow;\n packageFacts?: PackageFacts;\n fingerprint?: string;\n kind?: string;\n parsed?: ParsedFacts;\n packagePublicSurface?: PackagePublicSurfaceFact;\n}\nexport async function indexRepository(\n db: Db,\n repo: RepoRow,\n force: boolean,\n instrumentation?: SourceContextInstrumentation,\n): Promise<IndexRepoResult> {\n try {\n const prepared = await prepareRepositoryIndex(repo, force, instrumentation);\n if (prepared.skipped)\n return { fileCount: 0, diagnosticCount: 0, skipped: true };\n const outcome = db.transaction(() => {\n const batch = createPackageInvalidationBatch([prepared.repo.id]);\n const published = publishOneRepository(db, prepared, batch);\n if (published.ok) finalizePackageTargetInvalidations(db, batch);\n return published;\n });\n return outcome.ok\n ? {\n fileCount: prepared.fileCount,\n diagnosticCount: prepared.diagnosticCount,\n skipped: false,\n }\n : { fileCount: 0, diagnosticCount: 1, skipped: false };\n } catch (error) {\n recordIndexFailure(db, repo.id, error);\n return { fileCount: 0, diagnosticCount: 1, skipped: false };\n }\n}\nexport async function prepareRepositoryIndex(\n repo: RepoRow,\n force: boolean,\n instrumentation?: SourceContextInstrumentation,\n): Promise<PreparedRepositoryIndex> {\n const sourceFiles = await findSourceFiles(repo.absolute_path);\n const packageSnapshot = await loadPackageJsonSnapshot(repo.absolute_path, {\n strict: true,\n allowMissing: repo.package_name === null,\n });\n const packageFacts = packageSnapshot.facts;\n const sources = await loadRepositorySourceContext(\n repo.absolute_path, sourceFiles, instrumentation,\n );\n const fingerprint = repositoryFingerprint(\n sources, packageFacts, packageSnapshot.rawText,\n );\n if (!force && repo.fingerprint === fingerprint) return { repo, fileCount: 0, diagnosticCount: 0, skipped: true };\n const parsedFacts = await parseAllSourceFacts(repo.absolute_path, sources);\n const packageSurface = analyzeRepositoryPackageSurface(\n packageFacts, packageSnapshot.manifest, sources,\n );\n const parsed = {\n ...parsedFacts,\n symbols: mergePackageSymbolEvidence(parsedFacts.symbols, packageSurface),\n };\n return {\n repo,\n packageFacts,\n fingerprint,\n kind: await classifyRepository(repo.absolute_path, packageFacts),\n parsed,\n packagePublicSurface: packageSurface.surface,\n fileCount: sourceFiles.length,\n diagnosticCount: parsed.handlers.filter((handler) =>\n handler.hasHandlerDecorator\n && (handler.methods.length === 0\n || handler.methods.some((method) => !handlerMethodIsExecutable(method)))).length,\n skipped: false,\n };\n}\nexport function publishPreparedRepositoryIndex(\n db: Db,\n prepared: PreparedRepositoryIndex,\n invalidations: PackageInvalidationBatch,\n): void {\n if (prepared.skipped) return;\n if (!prepared.packageFacts || !prepared.parsed || !prepared.fingerprint\n || !prepared.kind || !prepared.packagePublicSurface)\n throw new Error('Prepared repository index is missing publication facts');\n const now = new Date().toISOString();\n const repoId = prepared.repo.id;\n invalidatePackageTargetFacts(\n db, repoId, prepared.packageFacts.packageName, invalidations,\n );\n db.prepare(`UPDATE repositories SET package_name=?, package_version=?,\n dependencies_json=?,package_public_surface_json=?,kind=?,index_status=?\n WHERE id=?`).run(\n prepared.packageFacts.packageName,\n prepared.packageFacts.packageVersion,\n JSON.stringify(prepared.packageFacts.dependencies),\n JSON.stringify(prepared.packagePublicSurface),\n prepared.kind,\n 'indexing',\n repoId,\n );\n clearRepoFacts(db, repoId);\n insertRequires(db, repoId, prepared.packageFacts.cdsRequires);\n const fileStmt = db.prepare('INSERT INTO files(repo_id,relative_path,extension,sha256,size_bytes,last_indexed_at) VALUES(?,?,?,?,?,?) ON CONFLICT(repo_id,relative_path) DO UPDATE SET sha256=excluded.sha256,size_bytes=excluded.size_bytes,last_indexed_at=excluded.last_indexed_at');\n for (const file of prepared.parsed.fileRecords) fileStmt.run(repoId, file.relativePath, file.extension, file.sha256, file.sizeBytes, now);\n for (const service of prepared.parsed.services) insertService(db, repoId, service);\n for (const handler of prepared.parsed.handlers) insertHandler(db, repoId, handler);\n insertExecutableSymbols(db, repoId, prepared.parsed.symbols);\n insertSymbolCalls(db, repoId, prepared.parsed.symbolCalls);\n insertRegistrations(db, repoId, prepared.parsed.registrations);\n insertBindings(db, repoId, prepared.parsed.bindings);\n insertCalls(db, repoId, prepared.parsed.calls);\n db.prepare(\"UPDATE repositories SET last_indexed_at=?, index_status='indexed', error_count=0, fingerprint=?, fact_generation=COALESCE(fact_generation,0)+1, graph_stale_reason='facts_changed', graph_stale_at=?, fact_analyzer_version=? WHERE id=?\").run(now, prepared.fingerprint, now, ANALYZER_VERSION, repoId);\n}\n\nexport type RepositoryPublicationOutcome =\n | { ok: true }\n | { ok: false; error: unknown };\n\nexport function publishOneRepository(\n db: Db,\n prepared: PreparedRepositoryIndex,\n invalidations: PackageInvalidationBatch,\n): RepositoryPublicationOutcome {\n try {\n db.transaction(() => withPublicationSavepoint(\n db,\n prepared.repo.id,\n () => publishPreparedRepositoryIndex(db, prepared, invalidations),\n ));\n return { ok: true };\n } catch (error) {\n recordIndexFailure(db, prepared.repo.id, error);\n return { ok: false, error };\n }\n}\n\nfunction withPublicationSavepoint<T>(\n db: Db,\n repoId: number,\n publish: () => T,\n): T {\n const name = `service_flow_repository_${repoId}`;\n db.exec(`SAVEPOINT ${name}`);\n try {\n const result = publish();\n db.exec(`RELEASE SAVEPOINT ${name}`);\n return result;\n } catch (error) {\n db.exec(`ROLLBACK TO SAVEPOINT ${name}`);\n db.exec(`RELEASE SAVEPOINT ${name}`);\n throw error;\n }\n}\n\nexport function recordIndexFailure(db: Db, repoId: number, error: unknown): void {\n if (isPreparedRepositorySnapshotError(error)) {\n recordPreparedSnapshotFailure(db, repoId, error);\n return;\n }\n const message = errorMessage(error);\n db.prepare(\"UPDATE repositories SET index_status='failed', error_count=1 WHERE id=?\").run(repoId);\n db.prepare(`DELETE FROM diagnostics WHERE repo_id=? AND (\n code IN ('index_failed_snapshot_preserved','source_read_failed')\n OR code GLOB 'invalid_prepared_repository_snapshot:*'\n )`).run(repoId);\n db.prepare('INSERT INTO diagnostics(repo_id,severity,code,message) VALUES(?,?,?,?)').run(repoId, 'error', 'source_read_failed', `Index failed before publication; previous facts and fingerprint were preserved. ${message}`);\n}\nasync function parseAllSourceFacts(\n root: string,\n sources: RepositorySourceContext,\n): Promise<ParsedFacts> {\n const facts: ParsedFacts = { services: [], handlers: [], registrations: [], bindings: [], calls: [], symbols: [], symbolCalls: [], fileRecords: [] };\n for (const snapshot of sources.entries()) {\n const file = snapshot.filePath;\n facts.fileRecords.push({ relativePath: normalizePath(file), extension: path.extname(file), sha256: sha256Text(snapshot.text), sizeBytes: snapshot.sizeBytes });\n if (file.endsWith('.cds')) facts.services.push(...(await parseCdsFile(root, file, sources)));\n if (/\\.[jt]s$/.test(file)) {\n const source = snapshot.sourceFile();\n const classified = classifyOutboundCallsInSource(source, file);\n facts.handlers.push(...(await parseDecorators(root, file, sources)));\n facts.registrations.push(...(await parseHandlerRegistrations(root, file, sources)));\n const bindings = await parseServiceBindings(root, file, sources);\n const symbolFacts = await parseExecutableSymbols(\n root, file, sources, classified,\n );\n const outboundCalls = await parseOutboundCalls(\n root, file, sources, classified, bindings,\n );\n const reconciled = reconcileSourceFacts(\n source, classified, bindings, outboundCalls,\n symbolFacts.symbols, symbolFacts.calls,\n );\n facts.bindings.push(...reconciled.bindings);\n facts.symbols.push(...reconciled.symbols);\n facts.symbolCalls.push(...reconciled.symbolCalls);\n facts.calls.push(...reconciled.outboundCalls);\n }\n }\n return facts;\n}\nasync function findSourceFiles(root: string): Promise<string[]> {\n const out: string[] = [];\n async function walk(dir: string, prefix = ''): Promise<void> {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n const rel = prefix ? `${prefix}/${e.name}` : e.name;\n if (e.isDirectory()) {\n if (!['node_modules', 'dist', 'gen', 'coverage', '.git'].includes(e.name)) await walk(path.join(dir, e.name), rel);\n } else if (/\\.(cds|ts|js)$/.test(e.name) && !isDefaultTestFile(rel)) out.push(rel);\n }\n }\n await walk(root);\n return out.sort();\n}\nfunction isDefaultTestFile(relativeFile: string): boolean {\n const parts = relativeFile.split('/');\n if (parts.some((part) => ['test', 'tests', '__tests__'].includes(part))) return true;\n return /\\.(test|spec)\\.[jt]s$/.test(parts.at(-1) ?? '');\n}\nfunction repositoryFingerprint(\n sources: RepositorySourceContext,\n facts: PackageFacts,\n packageJsonText: string,\n): string {\n const normalizedFacts = {\n analyzerVersion: ANALYZER_VERSION,\n packageName: facts.packageName,\n packageVersion: facts.packageVersion,\n dependencies: Object.fromEntries(Object.entries(facts.dependencies).sort()),\n cdsRequires: [...facts.cdsRequires].sort((a, b) => a.alias.localeCompare(b.alias)),\n scripts: Object.fromEntries(Object.entries(facts.scripts).sort()),\n includeTests: false,\n packageJsonHash: sha256Text(packageJsonText),\n };\n const entries: string[] = [`facts:${JSON.stringify(normalizedFacts)}`];\n for (const snapshot of sources.entries())\n entries.push(`${snapshot.filePath}:${sha256Text(snapshot.text)}`);\n return sha256Text(entries.join('\\n'));\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport ts from 'typescript';\nimport type { ExecutableSymbolFact, SymbolCallFact } from '../types.js';\nimport {\n classifyOutboundCallsInSource,\n containsSupportedOutboundCall,\n type ClassifiedOutboundCall,\n} from './outbound-call-parser.js';\nimport type { RepositorySourceContext } from './ts-project.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport { reconcileEventSubscriptions } from './005-event-subscription-facts.js';\nimport { reconcileSymbolCallOwners } from './007-source-fact-reconciliation.js';\nimport {\n collectSymbolImportBindings,\n type SymbolImportBinding,\n} from './002-symbol-import-bindings.js';\nimport {\n collectSymbolCallFacts,\n symbolCallName,\n type SymbolCallProxy,\n type SymbolClassInstance,\n} from './009-symbol-call-facts.js';\nimport {\n executableBodyEligibility,\n} from './013-executable-body-eligibility.js';\nimport {\n collectDerivedSymbolContexts,\n} from './017-symbol-derived-contexts.js';\n\nfunction lineOf(source: ts.SourceFile, pos: number): number {\n return source.getLineAndCharacterOfPosition(pos).line + 1;\n}\nfunction nameOf(node: ts.PropertyName | ts.BindingName | undefined): string | undefined {\n if (!node) return undefined;\n if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return node.text;\n return undefined;\n}\nfunction isFunctionLike(node: ts.Node): node is ts.FunctionLikeDeclaration {\n return ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node);\n}\nfunction exported(node: ts.Node): boolean {\n return Boolean(ts.getCombinedModifierFlags(node as ts.Declaration) & ts.ModifierFlags.Export);\n}\nfunction defaultExported(node: ts.Node): boolean {\n return Boolean(\n ts.getCombinedModifierFlags(node as ts.Declaration)\n & ts.ModifierFlags.Default,\n );\n}\nfunction isPublicClassMethod(node: ts.MethodDeclaration): boolean {\n const flags = ts.getCombinedModifierFlags(node);\n return (flags & ts.ModifierFlags.Private) === 0 && (flags & ts.ModifierFlags.Protected) === 0;\n}\nfunction exportDeclarations(source: ts.SourceFile): Map<string, string> {\n const exports = new Map<string, string>();\n const visit = (node: ts.Node): void => {\n if (ts.isExportDeclaration(node) && node.exportClause && ts.isNamedExports(node.exportClause)) {\n for (const el of node.exportClause.elements) exports.set((el.propertyName ?? el.name).text, el.name.text);\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return exports;\n}\nfunction isObjectFunction(\n node: ts.Node,\n): node is ts.FunctionExpression | ts.ArrowFunction | ts.MethodDeclaration {\n return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node);\n}\ntype ParameterBinding =\n | { index: number; kind: 'identifier'; name: string }\n | { index: number; kind: 'object_pattern'; properties: Array<{ property: string; local: string }> }\n | { index: number; kind: 'array_pattern'; elements: Array<{ index: number; local: string }> };\ntype ParameterPropertyAlias = { parameter: string; property: string; local: string; kind: 'object_parameter_destructure'; line: number };\nfunction requireSource(expr: ts.Expression): string | undefined {\n if (!ts.isCallExpression(expr) || !ts.isIdentifier(expr.expression) || expr.expression.text !== 'require') return undefined;\n const first = expr.arguments[0];\n return first && ts.isStringLiteral(first) ? first.text : undefined;\n}\nfunction bindingLocalName(name: ts.BindingName, initializer?: ts.Expression): string | undefined {\n if (ts.isIdentifier(name)) return name.text;\n if (initializer && ts.isIdentifier(initializer)) return initializer.text;\n return undefined;\n}\n\nfunction objectPatternAliases(pattern: ts.ObjectBindingPattern, parameter: string, source: ts.SourceFile, lineNode: ts.Node): ParameterPropertyAlias[] {\n return pattern.elements.flatMap((element): ParameterPropertyAlias[] => {\n if (element.dotDotDotToken || ts.isObjectBindingPattern(element.name) || ts.isArrayBindingPattern(element.name)) return [];\n const property = element.propertyName ? nameOf(element.propertyName) : nameOf(element.name);\n if (!property) return [];\n const local = bindingLocalName(element.name, element.initializer);\n return local ? [{ parameter, property, local, kind: 'object_parameter_destructure', line: lineOf(source, lineNode.getStart(source)) }] : [];\n });\n}\nfunction parameterPropertyAliases(fn: ts.FunctionLikeDeclaration, source: ts.SourceFile): ParameterPropertyAlias[] {\n const parameterNames = new Set(fn.parameters.flatMap((param) => ts.isIdentifier(param.name) ? [param.name.text] : []));\n if (!fn.body || parameterNames.size === 0) return [];\n const aliases: ParameterPropertyAlias[] = [];\n const addFromAssignment = (left: ts.Expression, right: ts.Expression, node: ts.Node): void => {\n if (!ts.isObjectLiteralExpression(left) || !ts.isIdentifier(right) || !parameterNames.has(right.text)) return;\n for (const prop of left.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const property = nameOf(prop.name);\n if (property && ts.isIdentifier(prop.initializer)) aliases.push({ parameter: right.text, property, local: prop.initializer.text, kind: 'object_parameter_destructure', line: lineOf(source, node.getStart(source)) });\n }\n };\n const visit = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer && ts.isIdentifier(node.initializer) && parameterNames.has(node.initializer.text)) aliases.push(...objectPatternAliases(node.name, node.initializer.text, source, node));\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) addFromAssignment(ts.isParenthesizedExpression(node.left) ? node.left.expression : node.left, node.right, node);\n ts.forEachChild(node, visit);\n };\n visit(fn.body);\n const seen = new Set<string>();\n return aliases.filter((alias) => { const key = `${alias.parameter}.${alias.property}:${alias.local}`; if (seen.has(key)) return false; seen.add(key); return true; });\n}\nfunction parameterBindings(params: ts.NodeArray<ts.ParameterDeclaration>): ParameterBinding[] {\n return params.flatMap((param, index): ParameterBinding[] => {\n if (ts.isIdentifier(param.name)) return [{ index, kind: 'identifier', name: param.name.text }];\n if (ts.isObjectBindingPattern(param.name)) {\n const properties = param.name.elements.flatMap((element): Array<{ property: string; local: string }> => {\n if (element.dotDotDotToken || ts.isObjectBindingPattern(element.name) || ts.isArrayBindingPattern(element.name)) return [];\n const property = element.propertyName ? nameOf(element.propertyName) : nameOf(element.name);\n if (!property) return [];\n const local = bindingLocalName(element.name, element.initializer);\n return local ? [{ property, local }] : [];\n });\n return properties.length > 0 ? [{ index, kind: 'object_pattern', properties }] : [];\n }\n if (ts.isArrayBindingPattern(param.name)) {\n const elements = param.name.elements.flatMap((element, elementIndex): Array<{ index: number; local: string }> =>\n ts.isBindingElement(element) && !element.dotDotDotToken && ts.isIdentifier(element.name)\n ? [{ index: elementIndex, local: element.name.text }]\n : []);\n return elements.length > 0 ? [{ index, kind: 'array_pattern', elements }] : [];\n }\n return [];\n });\n}\ninterface SymbolCollection {\n source: ts.SourceFile;\n sourceFile: string;\n symbols: ExecutableSymbolFact[];\n imports: Map<string, string>;\n importBindings: SymbolImportBinding[];\n classifiedCalls: readonly ClassifiedOutboundCall[];\n exportNames: Map<string, string>;\n objectExports: Set<string>;\n exportedClasses: Set<string>;\n defaultExportedClasses: Set<string>;\n declaredClasses: Set<string>;\n proxies: Map<string, SymbolCallProxy[]>;\n instances: Map<string, SymbolClassInstance[]>;\n}\n\nfunction symbolSourceEvidence(\n collection: SymbolCollection,\n node: ts.Node,\n options: {\n parentRoot: string;\n qualifiedName: string;\n declaredExportName?: string;\n classContainerExported: boolean; classContainerDefaultExported: boolean;\n classMemberExported: boolean;\n objectExported: boolean;\n evidence?: Record<string, unknown>;\n },\n): Record<string, unknown> {\n if (options.evidence) return options.evidence;\n if (options.classMemberExported) return {\n source: 'exported_class_member',\n exportedClass: options.parentRoot,\n memberKind: ts.getCombinedModifierFlags(node as ts.Declaration)\n & ts.ModifierFlags.Static ? 'static_method' : 'class_method',\n };\n if (options.classContainerExported && ts.isMethodDeclaration(node)\n && isPublicClassMethod(node)) return {\n source: 'exported_class_instance_member', exportedClass: options.parentRoot,\n exportedClassExportKind: options.classContainerDefaultExported\n ? 'default' : 'named',\n memberKind: 'class_method',\n };\n if (options.declaredExportName) return {\n exportedName: options.declaredExportName,\n source: 'export_declaration',\n };\n return options.objectExported\n ? { exportedName: options.qualifiedName, source: 'exported_object_literal' }\n : {};\n}\n\nfunction executableEvidence(\n node: ts.Node,\n source: ts.SourceFile,\n): Record<string, unknown> {\n if (!isFunctionLike(node)) return {};\n const bindings = parameterBindings(node.parameters);\n const parameters = bindings.flatMap((binding) =>\n binding.kind === 'identifier' ? [binding.name] : []);\n const aliases = parameterPropertyAliases(node, source);\n return {\n executableBodyEligibility: executableBodyEligibility(node, source),\n ...(bindings.length > 0 ? { parameters, parameterBindings: bindings } : {}),\n ...(aliases.length > 0 ? { parameterPropertyAliases: aliases } : {}),\n };\n}\n\ninterface SymbolNames {\n parentRoot: string;\n qualifiedName: string;\n declaredExportName?: string;\n objectExported: boolean;\n classContainerExported: boolean;\n classContainerDefaultExported: boolean;\n classMemberExported: boolean;\n effectiveName?: string;\n}\n\nfunction exportedClassMember(\n collection: SymbolCollection,\n kind: string,\n parentName: string | undefined,\n parentRoot: string,\n node: ts.Node,\n): boolean {\n if (kind !== 'method' || !parentName\n || !collection.exportedClasses.has(parentRoot)\n || !ts.isMethodDeclaration(node)) return false;\n return Boolean(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Static)\n && isPublicClassMethod(node);\n}\n\nfunction classExportState(\n collection: SymbolCollection,\n parentName: string | undefined,\n parentRoot: string,\n): {\n classContainerExported: boolean;\n classContainerDefaultExported: boolean;\n} {\n return {\n classContainerExported: Boolean(\n parentName && collection.exportedClasses.has(parentRoot),\n ),\n classContainerDefaultExported: Boolean(\n parentName && collection.defaultExportedClasses.has(parentRoot),\n ),\n };\n}\n\nfunction symbolNames(\n collection: SymbolCollection,\n kind: string,\n localName: string,\n node: ts.Node,\n parentName?: string,\n exportedName?: string,\n): SymbolNames {\n const parentRoot = parentName?.split('.')[0] ?? '';\n const declaredExportName = exportedName ?? collection.exportNames.get(\n parentName ? parentRoot : localName,\n );\n const qualifiedName = parentName ? `${parentName}.${localName}` : localName;\n const objectExported = Boolean(\n parentName && collection.objectExports.has(parentRoot),\n );\n const classMemberExported = exportedClassMember(\n collection, kind, parentName, parentRoot, node,\n );\n const classState = classExportState(collection, parentName, parentRoot);\n return {\n parentRoot, declaredExportName, qualifiedName,\n objectExported, ...classState,\n classMemberExported,\n effectiveName: classMemberExported || objectExported\n ? qualifiedName : declaredExportName,\n };\n}\n\nfunction addExecutableSymbol(\n collection: SymbolCollection,\n kind: string,\n localName: string,\n node: ts.Node,\n parentName?: string,\n exportedName?: string,\n evidence?: Record<string, unknown>,\n): void {\n const names = symbolNames(\n collection, kind, localName, node, parentName, exportedName,\n );\n const sourceEvidence = symbolSourceEvidence(collection, node, {\n parentRoot: names.parentRoot,\n qualifiedName: names.qualifiedName,\n declaredExportName: names.declaredExportName,\n classContainerExported: names.classContainerExported,\n classContainerDefaultExported: names.classContainerDefaultExported,\n classMemberExported: names.classMemberExported,\n objectExported: names.objectExported,\n evidence,\n });\n collection.symbols.push({\n kind,\n localName: kind === 'object_method' ? names.qualifiedName : localName,\n exportedName: names.effectiveName,\n qualifiedName: names.qualifiedName,\n sourceFile: collection.sourceFile,\n startLine: lineOf(collection.source, node.getStart(collection.source)),\n endLine: lineOf(collection.source, node.getEnd()),\n startOffset: node.getStart(collection.source),\n endOffset: node.getEnd(),\n exported: exported(node) || Boolean(names.effectiveName),\n importExportEvidence: {\n ...sourceEvidence,\n ...executableEvidence(node, collection.source),\n },\n });\n}\n\nfunction addAliasSymbol(\n collection: SymbolCollection,\n objectName: string,\n propertyName: string,\n node: ts.Node,\n): void {\n collection.symbols.push({\n kind: 'object_alias',\n localName: propertyName,\n exportedName: propertyName,\n qualifiedName: `${objectName}.${propertyName}`,\n sourceFile: collection.sourceFile,\n startLine: lineOf(collection.source, node.getStart(collection.source)),\n endLine: lineOf(collection.source, node.getEnd()),\n startOffset: node.getStart(collection.source),\n endOffset: node.getEnd(),\n exported: true,\n importExportEvidence: {\n source: 'exported_object_shorthand',\n objectName,\n propertyName,\n targetImportSource: collection.imports.get(propertyName),\n },\n });\n}\n\nfunction collectImportSources(collection: SymbolCollection): void {\n const visit = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier))\n collectEsmImportSources(collection.imports, node);\n if (ts.isVariableStatement(node))\n collectCjsImportSources(collection.imports, node);\n ts.forEachChild(node, visit);\n };\n visit(collection.source);\n}\n\nfunction collectEsmImportSources(\n imports: Map<string, string>,\n node: ts.ImportDeclaration,\n): void {\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const source = node.moduleSpecifier.text;\n const clause = node.importClause;\n if (clause?.name) imports.set(clause.name.text, source);\n const named = clause?.namedBindings;\n if (named && ts.isNamedImports(named))\n for (const item of named.elements) imports.set(item.name.text, source);\n if (named && ts.isNamespaceImport(named))\n imports.set(named.name.text, source);\n}\n\nfunction collectCjsImportSources(\n imports: Map<string, string>,\n node: ts.VariableStatement,\n): void {\n for (const declaration of node.declarationList.declarations) {\n const source = declaration.initializer\n ? requireSource(declaration.initializer) : undefined;\n if (!source) continue;\n if (ts.isIdentifier(declaration.name))\n imports.set(declaration.name.text, source);\n if (ts.isObjectBindingPattern(declaration.name))\n for (const item of declaration.name.elements)\n if (ts.isIdentifier(item.name)) imports.set(item.name.text, source);\n }\n}\n\nfunction classPropertySymbol(\n collection: SymbolCollection,\n node: ts.PropertyDeclaration,\n parentClass: string,\n): void {\n const initializer = node.initializer;\n const localName = nameOf(node.name);\n if (!localName || !initializer\n || (!ts.isArrowFunction(initializer)\n && !ts.isFunctionExpression(initializer))) return;\n const staticPublic = publicStaticProperty(collection, node, parentClass);\n const memberKind = propertyMemberKind(initializer, staticPublic);\n addExecutableSymbol(\n collection, 'method', localName, initializer, parentClass,\n staticPublic ? `${parentClass}.${localName}` : undefined,\n staticPublic\n ? { source: 'exported_class_member', exportedClass: parentClass, memberKind }\n : { source: 'class_property_function', memberKind },\n );\n}\n\nfunction publicStaticProperty(\n collection: SymbolCollection,\n node: ts.PropertyDeclaration,\n parentClass: string,\n): boolean {\n const flags = ts.getCombinedModifierFlags(node);\n return collection.exportedClasses.has(parentClass)\n && Boolean(flags & ts.ModifierFlags.Static)\n && (flags & ts.ModifierFlags.Private) === 0\n && (flags & ts.ModifierFlags.Protected) === 0;\n}\n\nfunction propertyMemberKind(\n initializer: ts.ArrowFunction | ts.FunctionExpression,\n staticPublic: boolean,\n): string {\n if (ts.isArrowFunction(initializer))\n return staticPublic ? 'static_arrow_function' : 'arrow_function_property';\n return staticPublic\n ? 'static_function_expression'\n : 'function_expression_property';\n}\n\nfunction objectCallable(\n property: ts.ObjectLiteralElementLike,\n): ts.FunctionLikeDeclaration | undefined {\n if (ts.isMethodDeclaration(property)) return property;\n return ts.isPropertyAssignment(property)\n && isObjectFunction(property.initializer)\n ? property.initializer\n : undefined;\n}\n\nfunction objectLiteralSymbols(\n collection: SymbolCollection,\n objectName: string,\n object: ts.ObjectLiteralExpression,\n objectIsExported: boolean,\n): void {\n if (objectIsExported) collection.objectExports.add(objectName);\n for (const property of object.properties) {\n if (objectIsExported && ts.isShorthandPropertyAssignment(property))\n addAliasSymbol(collection, objectName, property.name.text, property.name);\n const callable = objectCallable(property);\n const propertyName = callable ? nameOf(property.name) : undefined;\n if (callable && propertyName)\n addExecutableSymbol(\n collection, 'object_method', propertyName, callable, objectName,\n );\n }\n}\n\nfunction variableSymbols(\n collection: SymbolCollection,\n node: ts.VariableStatement,\n): void {\n for (const declaration of node.declarationList.declarations) {\n const localName = nameOf(declaration.name);\n const initializer = declaration.initializer;\n if (!localName || !initializer) continue;\n if (isFunctionLike(initializer)) addExecutableSymbol(\n collection, 'function', localName, initializer, undefined,\n exported(node) ? localName : collection.exportNames.get(localName),\n );\n if (ts.isObjectLiteralExpression(initializer))\n objectLiteralSymbols(\n collection, localName, initializer,\n exported(node) || collection.exportNames.has(localName),\n );\n }\n}\n\nfunction collectClassDeclaration(\n collection: SymbolCollection,\n node: ts.Node,\n): boolean {\n if (!ts.isClassDeclaration(node) || !node.name) return false;\n collection.declaredClasses.add(node.name.text);\n if (exported(node) || collection.exportNames.has(node.name.text))\n collection.exportedClasses.add(node.name.text);\n if (defaultExported(node))\n collection.defaultExportedClasses.add(node.name.text);\n for (const member of node.members)\n visitDeclaredSymbol(collection, member, node.name.text);\n return true;\n}\n\nfunction collectMethodDeclaration(\n collection: SymbolCollection,\n node: ts.Node,\n parentClass?: string,\n): boolean {\n if (!ts.isMethodDeclaration(node)) return false;\n const localName = nameOf(node.name);\n if (localName)\n addExecutableSymbol(collection, 'method', localName, node, parentClass);\n return true;\n}\n\nfunction visitDeclaredSymbol(\n collection: SymbolCollection,\n node: ts.Node,\n parentClass?: string,\n): void {\n if (collectClassDeclaration(collection, node)) return;\n if (collectMethodDeclaration(collection, node, parentClass)) return;\n if (ts.isPropertyDeclaration(node)) {\n if (parentClass) classPropertySymbol(collection, node, parentClass);\n return;\n }\n if (ts.isFunctionDeclaration(node) && node.name) {\n addExecutableSymbol(\n collection, 'function', node.name.text, node, undefined,\n exported(node) ? node.name.text : undefined,\n );\n return;\n }\n if (ts.isVariableStatement(node)) {\n variableSymbols(collection, node);\n return;\n }\n ts.forEachChild(node, (child) =>\n visitDeclaredSymbol(collection, child, parentClass));\n}\n\nfunction collectDeclaredSymbols(collection: SymbolCollection): void {\n visitDeclaredSymbol(collection, collection.source);\n}\n\nfunction isTopLevelCallback(\n node: ts.Node,\n): node is ts.ArrowFunction | ts.FunctionExpression {\n if ((!ts.isArrowFunction(node) && !ts.isFunctionExpression(node))\n || !ts.isCallExpression(node.parent)) return false;\n const callee = symbolCallName(node.parent.expression);\n const member = callee.member ?? callee.local;\n return Boolean(member && [\n 'bootstrap', 'served', 'connect', 'on', 'once', 'use',\n 'get', 'post', 'put', 'patch', 'delete', 'subscribe',\n ].includes(member));\n}\n\nfunction collectCallbackSymbols(collection: SymbolCollection): void {\n const visit = (node: ts.Node): void => {\n if (isTopLevelCallback(node)\n && containsSupportedOutboundCall(node, collection.classifiedCalls)) {\n const startLine = lineOf(\n collection.source, node.getStart(collection.source),\n );\n const name = `callback:${startLine}`;\n collection.symbols.push({\n kind: 'callback', localName: name,\n qualifiedName: `module:${collection.sourceFile}#${name}`,\n sourceFile: collection.sourceFile, startLine,\n endLine: lineOf(collection.source, node.getEnd()),\n startOffset: node.getStart(collection.source), endOffset: node.getEnd(),\n exported: false,\n importExportEvidence: {\n source: 'synthetic_outbound_callback', callbackLine: startLine,\n },\n });\n }\n ts.forEachChild(node, visit);\n };\n visit(collection.source);\n}\n\nfunction createCollection(\n source: ts.SourceFile,\n sourceFile: string,\n classifiedCalls: readonly ClassifiedOutboundCall[],\n): SymbolCollection {\n return {\n source, sourceFile, classifiedCalls,\n symbols: [], imports: new Map(),\n importBindings: collectSymbolImportBindings(source),\n exportNames: exportDeclarations(source),\n objectExports: new Set(), exportedClasses: new Set(),\n defaultExportedClasses: new Set(),\n declaredClasses: new Set(), proxies: new Map(), instances: new Map(),\n };\n}\n\nfunction populateCollection(collection: SymbolCollection): void {\n collectImportSources(collection);\n collectDeclaredSymbols(collection);\n collectCallbackSymbols(collection);\n collectDerivedSymbolContexts(collection);\n}\n\nasync function sourceFile(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n): Promise<ts.SourceFile> {\n const snapshot = context?.get(filePath);\n const text = snapshot?.text\n ?? await fs.readFile(path.join(repoPath, filePath), 'utf8');\n return snapshot?.sourceFile() ?? ts.createSourceFile(\n filePath, text, ts.ScriptTarget.Latest, true,\n filePath.endsWith('.ts') ? ts.ScriptKind.TS : ts.ScriptKind.JS,\n );\n}\n\nexport async function parseExecutableSymbols(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n preparedOutboundCalls?: readonly ClassifiedOutboundCall[],\n): Promise<{ symbols: ExecutableSymbolFact[]; calls: SymbolCallFact[] }> {\n const source = await sourceFile(repoPath, filePath, context);\n const normalizedFile = normalizePath(filePath);\n const classified = preparedOutboundCalls\n ?? classifyOutboundCallsInSource(source, normalizedFile);\n const collection = createCollection(source, normalizedFile, classified);\n populateCollection(collection);\n const calls = collectSymbolCallFacts({\n source, sourceFile: normalizedFile,\n symbols: collection.symbols, imports: collection.imports,\n importBindings: collection.importBindings,\n proxies: collection.proxies, instances: collection.instances,\n });\n const events = reconcileEventSubscriptions(\n source, classified, collection.symbols, calls,\n );\n return {\n symbols: events.symbols,\n calls: reconcileSymbolCallOwners(events.calls, events.symbols),\n };\n}\n","import ts from 'typescript';\nimport type {\n ExecutableSymbolFact,\n HandlerReferenceStatus,\n SymbolCallFact,\n} from '../types.js';\nimport {\n collectSymbolImportBindings,\n symbolImportReference,\n type SymbolImportBinding,\n type SymbolImportReference,\n} from './002-symbol-import-bindings.js';\nimport type { ClassifiedOutboundCall } from './outbound-call-parser.js';\nimport {\n localSymbolTarget,\n type LocalSymbolTargetIdentity,\n} from './016-local-symbol-reference.js';\n\ninterface HandlerTarget {\n calleeExpression: string;\n calleeLocalName: string;\n importSource?: string;\n relation: string;\n referenceShape: string;\n wrapperFunction?: string;\n importBinding?: SymbolImportReference;\n localTargetIdentity?: LocalSymbolTargetIdentity;\n}\n\ninterface HandlerClassification {\n status: HandlerReferenceStatus;\n reason?: string;\n referenceShape: string;\n target?: HandlerTarget;\n}\n\nfunction lineOf(source: ts.SourceFile, node: ts.Node): number {\n return source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;\n}\n\nfunction lineAt(source: ts.SourceFile, position: number): number {\n return source.getLineAndCharacterOfPosition(position).line + 1;\n}\n\nfunction importRelation(binding: SymbolImportReference): string {\n if (binding.moduleKind === 'package') return 'package_import';\n return binding.referenceShape === 'namespace_member'\n ? 'relative_import_namespace_member'\n : 'relative_import';\n}\n\nfunction directTarget(\n expression: ts.Expression,\n source: ts.SourceFile,\n imports: readonly SymbolImportBinding[],\n symbols: readonly ExecutableSymbolFact[],\n): HandlerTarget | undefined {\n const imported = symbolImportReference(expression, imports);\n if (imported) return importedTarget(expression, source, imported);\n if (ts.isIdentifier(expression)) {\n const exact = localSymbolTarget(expression, source, symbols);\n return {\n calleeExpression: expression.text,\n calleeLocalName: expression.text,\n relation: exact\n ? 'indexed_local_symbol'\n : 'indexed_local_symbol_unproven',\n referenceShape: 'identifier',\n localTargetIdentity: exact,\n };\n }\n return propertyTarget(expression, source, symbols);\n}\n\nfunction importedTarget(\n expression: ts.Expression,\n source: ts.SourceFile,\n binding: SymbolImportReference,\n): HandlerTarget {\n return {\n calleeExpression: expression.getText(source),\n calleeLocalName: binding.requestedPublicName,\n importSource: binding.rawModuleSpecifier,\n relation: importRelation(binding),\n referenceShape: binding.referenceShape,\n importBinding: binding,\n };\n}\n\nfunction propertyTarget(\n expression: ts.Expression,\n source: ts.SourceFile,\n symbols: readonly ExecutableSymbolFact[],\n): HandlerTarget | undefined {\n if (!ts.isPropertyAccessExpression(expression) || expression.questionDotToken\n || !ts.isIdentifier(expression.expression)) return undefined;\n const exact = localSymbolTarget(expression, source, symbols);\n return {\n calleeExpression: expression.getText(source),\n calleeLocalName: `${expression.expression.text}.${expression.name.text}`,\n relation: exact\n ? 'indexed_local_symbol'\n : 'indexed_local_symbol_unproven',\n referenceShape: 'static_member',\n localTargetIdentity: exact,\n };\n}\n\nfunction unsupportedClassification(\n status: Exclude<HandlerReferenceStatus, 'role_required'>,\n reason: string,\n referenceShape: string,\n): HandlerClassification {\n return { status, reason, referenceShape };\n}\n\nexport function classifyHandlerReference(\n expression: ts.Expression | undefined,\n source: ts.SourceFile,\n imports = collectSymbolImportBindings(source),\n symbols: readonly ExecutableSymbolFact[] = [],\n): HandlerClassification {\n if (!expression)\n return unsupportedClassification(\n 'missing_argument', 'handler_argument_missing', 'missing',\n );\n if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression))\n return unsupportedClassification(\n 'unsupported_inline', 'inline_handler_body_not_indexed', 'inline_callback',\n );\n const direct = directTarget(expression, source, imports, symbols);\n if (direct)\n return { status: 'role_required', referenceShape: direct.referenceShape, target: direct };\n if (!ts.isCallExpression(expression))\n return unsupportedClassification(\n 'unsupported_reference_shape', 'handler_reference_shape_unsupported',\n 'unsupported_expression',\n );\n return classifyWrapperReference(expression, source, imports, symbols);\n}\n\nfunction classifyWrapperReference(\n expression: ts.CallExpression,\n source: ts.SourceFile,\n imports: readonly SymbolImportBinding[],\n symbols: readonly ExecutableSymbolFact[],\n): HandlerClassification {\n if (expression.questionDotToken || expression.arguments.length !== 1)\n return unsupportedClassification(\n 'unsupported_wrapper', 'wrapper_requires_one_reference', 'wrapper_call',\n );\n const inner = expression.arguments[0];\n const target = inner\n ? directTarget(inner, source, imports, symbols)\n : undefined;\n if (!target)\n return unsupportedClassification(\n 'unsupported_wrapper', 'wrapper_reference_shape_unsupported', 'wrapper_call',\n );\n return {\n status: 'role_required',\n referenceShape: `wrapped_${target.referenceShape}`,\n target: { ...target, wrapperFunction: expression.expression.getText(source) },\n };\n}\n\nfunction eventSymbol(\n source: ts.SourceFile,\n classified: ClassifiedOutboundCall,\n): ExecutableSymbolFact {\n const node = classified.node;\n const eventName = classified.fact.eventNameExpr ?? '';\n const line = lineOf(source, node);\n const safeName = eventName.replace(/[^A-Za-z0-9_$-]/g, '_');\n const name = `event:${safeName}:${line}`;\n const receiver = classified.fact.evidence?.receiver;\n return {\n kind: 'event_registration',\n localName: name,\n qualifiedName: `module:${classified.fact.sourceFile}#${name}`,\n sourceFile: classified.fact.sourceFile,\n startLine: line,\n endLine: lineAt(source, node.getEnd() - 1),\n startOffset: node.getStart(source),\n endOffset: node.getEnd(),\n exported: false,\n importExportEvidence: {\n source: 'synthetic_event_registration',\n eventName,\n registrationLine: line,\n receiver: typeof receiver === 'string' ? receiver : undefined,\n },\n };\n}\n\nfunction eventCall(\n classified: ClassifiedOutboundCall,\n owner: ExecutableSymbolFact,\n classification: HandlerClassification,\n): SymbolCallFact | undefined {\n const target = classification.target;\n if (!target) return undefined;\n return {\n callerQualifiedName: owner.qualifiedName,\n calleeExpression: target.calleeExpression,\n calleeLocalName: target.calleeLocalName,\n importSource: target.importSource,\n sourceFile: classified.fact.sourceFile,\n sourceLine: classified.fact.sourceLine,\n callSiteStartOffset: classified.fact.callSiteStartOffset,\n callSiteEndOffset: classified.fact.callSiteEndOffset,\n callRole: 'event_subscribe_handler',\n evidence: {\n relation: target.relation,\n caller: owner.qualifiedName,\n targetName: target.calleeLocalName,\n referenceShape: classification.referenceShape,\n ...(target.importBinding ? { importBinding: target.importBinding } : {}),\n ...(target.localTargetIdentity\n ? { localTargetIdentity: target.localTargetIdentity }\n : {}),\n ...(target.wrapperFunction ? { wrapperFunction: target.wrapperFunction } : {}),\n factOrigin: 'event_subscribe_handler_reference',\n },\n };\n}\n\nfunction enrichSubscription(\n source: ts.SourceFile,\n classified: ClassifiedOutboundCall,\n symbols: readonly ExecutableSymbolFact[],\n): { classified: ClassifiedOutboundCall; classification: HandlerClassification } {\n const classification = classifyHandlerReference(\n classified.node.arguments[1], source, undefined, symbols,\n );\n const evidence = {\n ...(classified.fact.evidence ?? {}),\n handlerReferenceStatus: classification.status,\n ...(classification.reason\n ? { handlerReferenceReason: classification.reason }\n : {}),\n handlerReferenceShape: classification.referenceShape,\n };\n return {\n classified: { ...classified, fact: { ...classified.fact, evidence } },\n classification,\n };\n}\n\nexport function reconcileEventSubscriptions(\n source: ts.SourceFile,\n classifications: readonly ClassifiedOutboundCall[],\n symbols: readonly ExecutableSymbolFact[],\n calls: readonly SymbolCallFact[],\n): {\n classifications: ClassifiedOutboundCall[];\n symbols: ExecutableSymbolFact[];\n calls: SymbolCallFact[];\n} {\n const subscriptions = classifications.filter(\n (item) => item.fact.callType === 'async_subscribe',\n ).map((item) => enrichSubscription(source, item, symbols));\n const eventSymbols = subscriptions.map((item) => eventSymbol(source, item.classified));\n const eventCalls = subscriptions.flatMap((item, index) => {\n const owner = eventSymbols[index];\n const call = owner\n ? eventCall(item.classified, owner, item.classification)\n : undefined;\n return call ? [call] : [];\n });\n return {\n classifications: classifications.map((item) =>\n subscriptions.find((candidate) => candidate.classified.node === item.node)\n ?.classified ?? item),\n symbols: [...symbols.filter((item) => item.kind !== 'event_registration'), ...eventSymbols],\n calls: [\n ...calls.filter((item) => item.callRole !== 'event_subscribe_handler'),\n ...eventCalls,\n ],\n };\n}\n","import ts from 'typescript';\nimport type { ExecutableSymbolFact } from '../types.js';\nimport {\n lexicalIdentifierDeclaration,\n lexicalIdentifierDeclarations,\n} from './002-symbol-import-bindings.js';\nimport { stableLocalValueReference } from './020-stable-local-value.js';\n\nexport interface LocalSymbolTargetIdentity {\n sourceFile: string;\n qualifiedName: string;\n startOffset: number;\n endOffset: number;\n}\n\nfunction functionTargetNode(\n declaration: ts.Identifier,\n): ts.Node | undefined {\n const parent = declaration.parent;\n if (ts.isFunctionDeclaration(parent)) return parent;\n if (!ts.isVariableDeclaration(parent)) return undefined;\n const initializer = parent.initializer;\n return initializer\n && (ts.isArrowFunction(initializer)\n || ts.isFunctionExpression(initializer))\n ? initializer\n : undefined;\n}\n\nfunction declarationKey(identifier: ts.Identifier): string {\n return `${identifier.getStart(identifier.getSourceFile())}:${identifier.getEnd()}`;\n}\n\nfunction unwrapAssignmentTarget(expression: ts.Expression): ts.Expression {\n if (ts.isParenthesizedExpression(expression)\n || ts.isAsExpression(expression)\n || ts.isSatisfiesExpression(expression)\n || ts.isTypeAssertionExpression(expression)\n || ts.isNonNullExpression(expression))\n return unwrapAssignmentTarget(expression.expression);\n return expression;\n}\n\nfunction objectAssignmentTargets(\n expression: ts.ObjectLiteralExpression,\n): ts.Identifier[] {\n return expression.properties.flatMap((property) => {\n if (ts.isShorthandPropertyAssignment(property)) return [property.name];\n if (ts.isPropertyAssignment(property))\n return assignmentTargets(property.initializer);\n return ts.isSpreadAssignment(property)\n ? assignmentTargets(property.expression) : [];\n });\n}\n\nfunction assignmentTargets(expression: ts.Expression): ts.Identifier[] {\n const target = unwrapAssignmentTarget(expression);\n if (ts.isIdentifier(target)) return [target];\n if (ts.isSpreadElement(target))\n return assignmentTargets(target.expression);\n if (ts.isBinaryExpression(target)\n && target.operatorToken.kind === ts.SyntaxKind.EqualsToken)\n return assignmentTargets(target.left);\n if (ts.isArrayLiteralExpression(target))\n return target.elements.flatMap((item) =>\n ts.isExpression(item) ? assignmentTargets(item) : []);\n return ts.isObjectLiteralExpression(target)\n ? objectAssignmentTargets(target) : [];\n}\n\nfunction assignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment\n && kind <= ts.SyntaxKind.LastAssignment;\n}\n\nfunction mutationUnary(\n node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression,\n): boolean {\n return node.operator === ts.SyntaxKind.PlusPlusToken\n || node.operator === ts.SyntaxKind.MinusMinusToken;\n}\n\ntype DeclarationMatcher = (identifier: ts.Identifier) => boolean;\n\nfunction binaryWritesDeclaration(\n node: ts.Node,\n matches: DeclarationMatcher,\n): boolean {\n if (!ts.isBinaryExpression(node)\n || !assignmentOperator(node.operatorToken.kind)) return false;\n return assignmentTargets(node.left).some(matches);\n}\n\nfunction unaryWritesDeclaration(\n node: ts.Node,\n matches: DeclarationMatcher,\n): boolean {\n if (!ts.isPrefixUnaryExpression(node)\n && !ts.isPostfixUnaryExpression(node)) return false;\n return mutationUnary(node)\n && ts.isIdentifier(node.operand)\n && matches(node.operand);\n}\n\nfunction loopWritesDeclaration(\n node: ts.Node,\n matches: DeclarationMatcher,\n): boolean {\n if (!ts.isForInStatement(node) && !ts.isForOfStatement(node)) return false;\n return !ts.isVariableDeclarationList(node.initializer)\n && assignmentTargets(node.initializer).some(matches);\n}\n\nfunction declarationWritten(\n source: ts.SourceFile,\n declarations: readonly ts.Identifier[],\n): boolean {\n const keys = new Set(declarations.map(declarationKey));\n let written = false;\n const matches = (identifier: ts.Identifier): boolean =>\n lexicalIdentifierDeclarations(identifier)\n .some((item) => keys.has(declarationKey(item)));\n const visit = (node: ts.Node): void => {\n if (written) return;\n written = binaryWritesDeclaration(node, matches)\n || unaryWritesDeclaration(node, matches)\n || loopWritesDeclaration(node, matches);\n if (!written) ts.forEachChild(node, visit);\n };\n visit(source);\n return written;\n}\n\nfunction singleImmutableDeclaration(\n declaration: ts.Identifier | undefined,\n): boolean {\n const parent = declaration?.parent;\n if (parent && ts.isClassDeclaration(parent)) return true;\n return Boolean(parent && ts.isVariableDeclaration(parent)\n && ts.isVariableDeclarationList(parent.parent)\n && (parent.parent.flags & ts.NodeFlags.Const) !== 0);\n}\n\nfunction immutableDeclarationSet(\n declarations: readonly ts.Identifier[],\n source: ts.SourceFile,\n): boolean {\n if (declarations.length === 0\n || declarationWritten(source, declarations)) return false;\n if (declarations.every((item) => ts.isFunctionDeclaration(item.parent)))\n return true;\n if (declarations.length !== 1) return false;\n return singleImmutableDeclaration(declarations[0]);\n}\n\nfunction propertyContainer(\n declaration: ts.Identifier,\n): ts.Node | undefined {\n const parent = declaration.parent;\n if (ts.isClassDeclaration(parent)) return parent;\n if (!ts.isVariableDeclaration(parent)) return undefined;\n const initializer = parent.initializer;\n return initializer\n && (ts.isObjectLiteralExpression(initializer)\n || ts.isClassExpression(initializer))\n ? initializer\n : undefined;\n}\n\nfunction identity(\n symbol: ExecutableSymbolFact,\n): LocalSymbolTargetIdentity {\n return {\n sourceFile: symbol.sourceFile,\n qualifiedName: symbol.qualifiedName,\n startOffset: symbol.startOffset,\n endOffset: symbol.endOffset,\n };\n}\n\nfunction executableBody(symbol: ExecutableSymbolFact): boolean {\n const value = symbol.importExportEvidence?.executableBodyEligibility;\n return Boolean(value && typeof value === 'object'\n && !Array.isArray(value)\n && 'eligible' in value\n && value.eligible === true);\n}\n\nfunction exactFunctionTarget(\n declarations: readonly ts.Identifier[],\n symbols: readonly ExecutableSymbolFact[],\n source: ts.SourceFile,\n): LocalSymbolTargetIdentity | undefined {\n if (!immutableDeclarationSet(declarations, source)) return undefined;\n const spans = declarations.flatMap((declaration) => {\n const target = functionTargetNode(declaration);\n return target\n ? [{ start: target.getStart(source), end: target.getEnd() }]\n : [];\n });\n const matches = symbols.filter((symbol) =>\n localFunctionMatches(symbol, spans, source.fileName));\n return matches.length === 1 && matches[0]\n ? identity(matches[0])\n : undefined;\n}\n\nfunction localFunctionMatches(\n symbol: ExecutableSymbolFact,\n spans: readonly { start: number; end: number }[],\n sourceFile: string,\n): boolean {\n if (symbol.sourceFile !== sourceFile || !executableBody(symbol))\n return false;\n return spans.some((span) =>\n symbol.startOffset === span.start && symbol.endOffset === span.end);\n}\n\nfunction exactPropertyTarget(\n expression: ts.PropertyAccessExpression,\n declaration: ts.Identifier,\n symbols: readonly ExecutableSymbolFact[],\n source: ts.SourceFile,\n): LocalSymbolTargetIdentity | undefined {\n if (!immutableDeclarationSet([declaration], source)\n || !stableLocalValueReference(source, declaration))\n return undefined;\n const container = propertyContainer(declaration);\n if (!container) return undefined;\n const qualifiedName = `${declaration.text}.${expression.name.text}`;\n const start = container.getStart(source);\n const end = container.getEnd();\n const matches = symbols.filter((symbol) =>\n symbol.sourceFile === source.fileName\n && symbol.qualifiedName === qualifiedName\n && symbol.startOffset >= start\n && symbol.endOffset <= end\n && executableBody(symbol));\n return matches.length === 1 && matches[0]\n ? identity(matches[0])\n : undefined;\n}\n\nexport function localSymbolTarget(\n expression: ts.Expression,\n source: ts.SourceFile,\n symbols: readonly ExecutableSymbolFact[],\n): LocalSymbolTargetIdentity | undefined {\n if (ts.isIdentifier(expression)) {\n return exactFunctionTarget(\n lexicalIdentifierDeclarations(expression), symbols, source,\n );\n }\n if (!ts.isPropertyAccessExpression(expression)\n || expression.questionDotToken\n || !ts.isIdentifier(expression.expression)) return undefined;\n const declaration = lexicalIdentifierDeclaration(expression.expression);\n return declaration\n ? exactPropertyTarget(expression, declaration, symbols, source)\n : undefined;\n}\n","import ts from 'typescript';\nimport type {\n ExecutableSymbolFact,\n OutboundCallFact,\n ServiceBindingFact,\n SymbolCallFact,\n} from '../types.js';\nimport {\n executableSymbolCandidates,\n selectCallOwner,\n} from './004-fact-identity.js';\nimport { reconcileEventSubscriptions } from './005-event-subscription-facts.js';\nimport { reconcileBindingAndCallIdentity } from './006-binding-identity.js';\nimport type { ClassifiedOutboundCall } from './outbound-call-parser.js';\n\nexport interface ReconciledSourceFacts {\n bindings: ServiceBindingFact[];\n outboundCalls: OutboundCallFact[];\n symbols: ExecutableSymbolFact[];\n symbolCalls: SymbolCallFact[];\n classifications: ClassifiedOutboundCall[];\n}\n\nfunction callKey(call: Pick<\n OutboundCallFact,\n 'callType' | 'callSiteStartOffset' | 'callSiteEndOffset'\n>): string {\n return `${call.callType}:${call.callSiteStartOffset}:${call.callSiteEndOffset}`;\n}\n\nfunction mergedOutboundCalls(\n existing: readonly OutboundCallFact[],\n classifications: readonly ClassifiedOutboundCall[],\n): OutboundCallFact[] {\n const classifiedKeys = new Set(\n classifications.map((item) => callKey(item.fact)),\n );\n return [\n ...classifications.map((item) => item.fact),\n ...existing.filter((call) => !classifiedKeys.has(callKey(call))),\n ];\n}\n\nfunction exactSymbolCallOwner(\n call: SymbolCallFact,\n symbols: readonly ExecutableSymbolFact[],\n): ExecutableSymbolFact | undefined {\n const start = call.callSiteStartOffset;\n const end = call.callSiteEndOffset;\n if (start === undefined || end === undefined) return undefined;\n const selected = selectCallOwner(\n executableSymbolCandidates(symbols, call.sourceFile),\n start,\n end,\n call.callRole === 'event_subscribe_handler',\n );\n if (selected.status === 'ambiguous')\n throw new Error('invalid_prepared_repository_snapshot:symbol_call_owner_ambiguous');\n if (call.callRole === 'event_subscribe_handler' && !selected.owner)\n throw new Error('invalid_prepared_repository_snapshot:handler_owner_missing');\n return selected.owner;\n}\n\nexport function reconcileSymbolCallOwners(\n calls: readonly SymbolCallFact[],\n symbols: readonly ExecutableSymbolFact[],\n): SymbolCallFact[] {\n return calls.flatMap((call) => {\n const owner = exactSymbolCallOwner(call, symbols);\n if (!owner) return [];\n return [{\n ...call,\n callerQualifiedName: owner.qualifiedName,\n evidence: {\n ...call.evidence,\n caller: owner.qualifiedName,\n callerResolution: 'full_span_containment',\n },\n }];\n });\n}\n\nexport function reconcileSourceFacts(\n source: ts.SourceFile,\n classifications: readonly ClassifiedOutboundCall[],\n bindings: readonly ServiceBindingFact[],\n outboundCalls: readonly OutboundCallFact[],\n symbols: readonly ExecutableSymbolFact[],\n symbolCalls: readonly SymbolCallFact[],\n): ReconciledSourceFacts {\n const events = reconcileEventSubscriptions(\n source, classifications, symbols, symbolCalls,\n );\n const allCalls = mergedOutboundCalls(outboundCalls, events.classifications);\n const identities = reconcileBindingAndCallIdentity(\n source, bindings, allCalls, events.symbols,\n );\n return {\n bindings: identities.bindings,\n outboundCalls: identities.calls,\n symbols: events.symbols,\n symbolCalls: reconcileSymbolCallOwners(events.calls, events.symbols),\n classifications: events.classifications,\n };\n}\n","import ts from 'typescript';\nimport type {\n ExecutableSymbolFact,\n LexicalScopeFact,\n OutboundCallFact,\n ServiceBindingFact,\n ServiceBindingReference,\n} from '../types.js';\nimport {\n executableSymbolCandidates,\n selectCallOwner,\n} from './004-fact-identity.js';\nimport {\n bindingSite,\n createBindingLexicalIndex,\n lexicalScopeChain,\n type BindingLexicalIndex,\n type BindingLexicalSite,\n type VisibleBinding,\n} from './011-binding-lexical-scope.js';\nimport { selectVisibleBinding } from './021-binding-visibility.js';\n\nconst scopeChainCap = 16;\n\ninterface PreparedBinding {\n fact: ServiceBindingFact;\n site: BindingLexicalSite;\n aliasProven: boolean;\n}\n\nfunction matchFactsToSites(\n index: BindingLexicalIndex,\n facts: readonly ServiceBindingFact[],\n): Array<{ fact: ServiceBindingFact; site: BindingLexicalSite }> {\n return facts.map((fact) => {\n if (fact.bindingSiteStartOffset === undefined\n || fact.bindingSiteEndOffset === undefined)\n throw new Error('invalid_prepared_repository_snapshot:binding_site_missing');\n const site = bindingSite(\n index,\n fact.variableName,\n fact.bindingSiteStartOffset,\n fact.bindingSiteEndOffset,\n );\n if (!site)\n throw new Error('invalid_prepared_repository_snapshot:binding_site_invalid');\n return { fact, site };\n });\n}\n\nfunction exactOwner(\n fact: ServiceBindingFact,\n site: BindingLexicalSite,\n symbols: readonly ExecutableSymbolFact[],\n): ServiceBindingFact {\n const candidates = executableSymbolCandidates(symbols, fact.sourceFile);\n const owner = selectCallOwner(\n candidates, site.startOffset, site.endOffset,\n );\n if (owner.status === 'ambiguous')\n throw new Error('invalid_prepared_repository_snapshot:binding_owner_ambiguous');\n return {\n ...fact,\n bindingSiteStartOffset: site.startOffset,\n bindingSiteEndOffset: site.endOffset,\n sourceSymbolQualifiedName: owner.owner?.qualifiedName,\n ownerResolution: owner.status === 'resolved'\n ? 'owned_exact'\n : 'ownerless_file_scope',\n };\n}\n\nfunction prepareBindings(\n index: BindingLexicalIndex,\n facts: readonly ServiceBindingFact[],\n symbols: readonly ExecutableSymbolFact[],\n): PreparedBinding[] {\n return matchFactsToSites(index, facts).map(({ fact, site }) => ({\n fact: exactOwner(fact, site, symbols),\n site,\n aliasProven: site.aliasSource === undefined,\n }));\n}\n\nfunction aliasStep(binding: PreparedBinding, source: PreparedBinding): Record<string, unknown> {\n const aliasKind = binding.site.aliasKind\n ?? (binding.site.flow === 'assignment'\n ? 'identity-assignment'\n : 'identity');\n return {\n callerVariable: binding.fact.variableName,\n aliasOf: source.fact.variableName,\n aliasKind,\n scopeRule: 'exact_lexical_scope',\n ...(aliasKind === 'transaction'\n ? { transactionAliasSource: source.fact.variableName }\n : {}),\n ...(binding.site.aliasArrayIndex === undefined ? {} : {\n sourceVariable: source.fact.variableName,\n arrayIndex: binding.site.aliasArrayIndex,\n promiseAll: binding.site.aliasPromiseAll ?? false,\n arrayContainer: binding.site.aliasPromiseAll\n ? 'Promise.all'\n : 'array_literal',\n }),\n };\n}\n\nfunction copyAliasProvenance(\n binding: PreparedBinding,\n source: PreparedBinding,\n): void {\n binding.fact = {\n ...binding.fact,\n alias: source.fact.alias,\n aliasExpr: source.fact.aliasExpr,\n destinationExpr: source.fact.destinationExpr,\n servicePathExpr: source.fact.servicePathExpr,\n isDynamic: source.fact.isDynamic,\n placeholders: source.fact.placeholders,\n helperChain: [\n ...(source.fact.helperChain ?? []),\n aliasStep(binding, source),\n ],\n };\n binding.aliasProven = true;\n}\n\nfunction bindingCandidates(\n bindings: readonly PreparedBinding[],\n): Array<{\n variableName: string;\n bindingSiteStartOffset: number;\n bindingSiteEndOffset: number;\n value: PreparedBinding;\n}> {\n return bindings.map((binding) => ({\n variableName: binding.fact.variableName,\n bindingSiteStartOffset: binding.site.startOffset,\n bindingSiteEndOffset: binding.site.endOffset,\n value: binding,\n }));\n}\n\nfunction resolvedAliasSource(\n selected: VisibleBinding<PreparedBinding>,\n): PreparedBinding | undefined {\n if (selected.status !== 'resolved') return undefined;\n if (!selected.site?.deterministic) return undefined;\n if (selected.declarationSite?.declarationKind === 'var') return undefined;\n const source = selected.candidate?.value;\n return source?.aliasProven ? source : undefined;\n}\n\nfunction reconcileAliases(\n index: BindingLexicalIndex,\n bindings: PreparedBinding[],\n): void {\n const candidates = bindingCandidates(bindings);\n for (const binding of bindings) {\n const sourceName = binding.site.aliasSource;\n if (!sourceName) continue;\n const selected = selectVisibleBinding(\n index, candidates, sourceName, binding.site.node,\n );\n const source = resolvedAliasSource(selected);\n if (source) copyAliasProvenance(binding, source);\n }\n}\n\nfunction assertUniqueSites(bindings: readonly PreparedBinding[]): void {\n const seen = new Set<string>();\n for (const binding of bindings) {\n const key = [\n binding.fact.sourceFile,\n binding.fact.variableName,\n binding.site.startOffset,\n binding.site.endOffset,\n ].join('\\u0000');\n if (seen.has(key))\n throw new Error('invalid_prepared_repository_snapshot:duplicate_service_binding_site');\n seen.add(key);\n }\n}\n\nfunction callNodeMap(source: ts.SourceFile): Map<string, ts.CallExpression> {\n const calls = new Map<string, ts.CallExpression>();\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node))\n calls.set(`${node.getStart(source)}:${node.getEnd()}`, node);\n ts.forEachChild(node, visit);\n };\n visit(source);\n return calls;\n}\n\nfunction emptyReference(\n call: OutboundCallFact,\n reason?: ServiceBindingReference['reason'],\n): ServiceBindingReference {\n return {\n status: call.serviceVariableName ? 'unresolved' : 'not_applicable',\n variableName: call.serviceVariableName,\n scopeChainTotal: 0,\n scopeChainShown: 0,\n scopeChainOmitted: 0,\n reason,\n };\n}\n\nfunction rejectedReference(\n call: OutboundCallFact,\n chain: LexicalScopeFact[],\n reason: ServiceBindingReference['reason'],\n status: 'ambiguous' | 'unresolved' = 'unresolved',\n): ServiceBindingReference {\n return {\n status,\n variableName: call.serviceVariableName,\n scopeChainTotal: chain.length,\n scopeChainShown: Math.min(chain.length, scopeChainCap),\n scopeChainOmitted: Math.max(0, chain.length - scopeChainCap),\n reason,\n };\n}\n\nfunction resolvedReference(\n call: OutboundCallFact,\n selected: PreparedBinding,\n chain: LexicalScopeFact[],\n scopeIndex: number,\n): ServiceBindingReference {\n const helperReturn = selected.fact.helperChain?.some(\n (step) => step.bindingOrigin === 'single_hop_helper_return',\n ) ?? false;\n return {\n status: 'resolved_exact',\n variableName: call.serviceVariableName,\n bindingSourceFile: selected.fact.sourceFile,\n bindingSiteStartOffset: selected.site.startOffset,\n bindingSiteEndOffset: selected.site.endOffset,\n resolutionStrategy: selected.site.flow === 'assignment'\n ? 'deterministic_reaching_assignment'\n : selected.site.aliasSource\n ? 'lexical_alias_declaration'\n : helperReturn\n ? 'single_hop_helper_return'\n : 'lexical_declaration',\n lexicalScopeChain: chain,\n bindingScopeIndex: scopeIndex,\n scopeChainTotal: chain.length,\n scopeChainShown: chain.length,\n scopeChainOmitted: 0,\n };\n}\n\nfunction selectedBindingReference(\n call: OutboundCallFact,\n chain: LexicalScopeFact[],\n chosen: VisibleBinding<PreparedBinding>,\n): ServiceBindingReference {\n const selected = chosen.candidate?.value;\n if (!selected) {\n return rejectedReference(\n call, chain, chosen.reason ?? 'binding_not_found',\n );\n }\n if (chosen.declarationSite?.declarationKind === 'var')\n return rejectedReference(call, chain, 'unsupported_var_binding');\n if (!selected.site.deterministic || !selected.aliasProven)\n return rejectedReference(call, chain, 'unsupported_reaching_assignment');\n return resolvedReference(call, selected, chain, chosen.scopeIndex ?? 0);\n}\n\nfunction bindingReference(\n call: OutboundCallFact,\n node: ts.CallExpression | undefined,\n index: BindingLexicalIndex,\n bindings: readonly PreparedBinding[],\n): ServiceBindingReference {\n if (!call.serviceVariableName) return emptyReference(call);\n if (!node) return emptyReference(call, 'binding_flow_unsupported');\n const chain = lexicalScopeChain(node, index.source);\n if (chain.length > scopeChainCap)\n return rejectedReference(call, chain, 'scope_chain_limit_exceeded');\n const chosen = selectVisibleBinding(\n index, bindingCandidates(bindings), call.serviceVariableName, node,\n );\n if (chosen.status === 'ambiguous')\n return rejectedReference(\n call, chain, 'binding_scope_ambiguous', 'ambiguous',\n );\n return selectedBindingReference(call, chain, chosen);\n}\n\nfunction exactCallOwner(\n call: OutboundCallFact,\n symbols: readonly ExecutableSymbolFact[],\n): { qualifiedName?: string; resolution: 'owned_exact' | 'ownerless_file_scope' } {\n const start = call.callSiteStartOffset;\n const end = call.callSiteEndOffset;\n if (start === undefined || end === undefined)\n return { resolution: 'ownerless_file_scope' };\n const selected = selectCallOwner(\n executableSymbolCandidates(symbols, call.sourceFile),\n start,\n end,\n call.callType === 'async_subscribe',\n );\n if (selected.status === 'ambiguous')\n throw new Error('invalid_prepared_repository_snapshot:outbound_owner_ambiguous');\n if (call.callType === 'async_subscribe' && selected.status !== 'resolved')\n throw new Error('invalid_prepared_repository_snapshot:subscription_owner_missing');\n return selected.owner\n ? { qualifiedName: selected.owner.qualifiedName, resolution: 'owned_exact' }\n : { resolution: 'ownerless_file_scope' };\n}\n\nexport function reconcileBindingAndCallIdentity(\n source: ts.SourceFile,\n bindingFacts: readonly ServiceBindingFact[],\n callFacts: readonly OutboundCallFact[],\n symbols: readonly ExecutableSymbolFact[],\n): { bindings: ServiceBindingFact[]; calls: OutboundCallFact[] } {\n const lexicalIndex = createBindingLexicalIndex(source);\n const bindings = prepareBindings(lexicalIndex, bindingFacts, symbols);\n reconcileAliases(lexicalIndex, bindings);\n assertUniqueSites(bindings);\n const nodes = callNodeMap(source);\n const calls = callFacts.map((call) => {\n const key = `${call.callSiteStartOffset}:${call.callSiteEndOffset}`;\n const reference = bindingReference(\n call, nodes.get(key), lexicalIndex, bindings,\n );\n const owner = exactCallOwner(call, symbols);\n return {\n ...call,\n sourceSymbolQualifiedName: owner.qualifiedName,\n serviceBindingReference: reference,\n evidence: {\n ...(call.evidence ?? {}),\n sourceOwnerResolution: owner.resolution,\n serviceBindingReference: reference,\n },\n };\n });\n return { bindings: bindings.map((binding) => binding.fact), calls };\n}\n","import ts from 'typescript';\nimport type {\n ExecutableSymbolFact,\n SymbolCallFact,\n} from '../types.js';\nimport {\n executableSymbolCandidates,\n selectCallOwner,\n} from './004-fact-identity.js';\nimport {\n derivedMemberImportReference,\n identifierMatchesDeclaration,\n symbolImportReference,\n type SymbolImportBinding,\n type SymbolImportReference,\n} from './002-symbol-import-bindings.js';\nimport {\n localSymbolTarget,\n type LocalSymbolTargetIdentity,\n} from './016-local-symbol-reference.js';\n\nexport interface SymbolCallProxy {\n importSource: string;\n importBinding: SymbolImportReference;\n factory: string;\n variableName: string;\n declarationStartOffset: number;\n declarationEndOffset: number;\n}\n\nexport interface SymbolClassInstance {\n className: string;\n importSource?: string;\n importBinding?: SymbolImportReference;\n propertyName?: string;\n declarationStartOffset: number;\n declarationEndOffset: number;\n containerStartOffset?: number;\n containerEndOffset?: number;\n}\n\ninterface CalleeName {\n expression: string;\n local?: string;\n member?: string;\n receiver?: string;\n}\n\ninterface CallCollection {\n source: ts.SourceFile;\n sourceFile: string;\n symbols: readonly ExecutableSymbolFact[];\n imports: ReadonlyMap<string, string>;\n importBindings: readonly SymbolImportBinding[];\n proxies: ReadonlyMap<string, readonly SymbolCallProxy[]>;\n instances: ReadonlyMap<string, readonly SymbolClassInstance[]>;\n}\n\ninterface CallContext {\n proxy?: SymbolCallProxy;\n instance?: SymbolClassInstance;\n reference?: SymbolImportReference;\n localTarget?: LocalSymbolTargetIdentity;\n}\n\nconst commonTerminalMembers = new Set([\n 'push', 'includes', 'find', 'findIndex', 'map', 'filter', 'reduce',\n 'forEach', 'some', 'every', 'toUpperCase', 'toLowerCase', 'trim',\n 'split', 'join', 'get', 'set', 'has',\n]);\nconst loggerMembers = new Set([\n 'trace', 'debug', 'info', 'warn', 'error', 'fatal', 'log',\n]);\nconst globalObjects = new Set([\n 'JSON', 'Object', 'Array', 'String', 'Number', 'Boolean', 'Math', 'Date',\n 'Promise', 'Reflect',\n]);\nconst capDslRoots = new Set([\n 'SELECT', 'INSERT', 'UPSERT', 'UPDATE', 'DELETE',\n]);\nconst requestHelpers = new Set([\n 'reject', 'error', 'info', 'warn', 'notify',\n]);\nconst transportMembers = new Set([\n 'emit', 'publish', 'send', 'on',\n]);\nconst cdsFrameworkPrefixes = [\n 'cds.connect.', 'cds.services.', 'cds.parse.',\n];\n\nexport function symbolCallName(expr: ts.Expression): CalleeName {\n if (ts.isIdentifier(expr)) return { expression: expr.text, local: expr.text };\n if (!ts.isPropertyAccessExpression(expr))\n return { expression: expr.getText() };\n const left = expr.expression.getText();\n return {\n expression: expr.getText(),\n local: left === 'this' ? undefined : left.split('.')[0],\n member: expr.name.text,\n receiver: left,\n };\n}\n\nfunction hasSetMember(\n value: string | undefined,\n values: ReadonlySet<string>,\n): boolean {\n return value ? values.has(value) : false;\n}\n\nfunction cdsFrameworkCall(callee: CalleeName): boolean {\n return callee.expression === 'cds.run'\n || cdsFrameworkPrefixes.some((prefix) =>\n callee.expression.startsWith(prefix));\n}\n\nfunction requestHelperCall(callee: CalleeName): boolean {\n return callee.local === 'req'\n && hasSetMember(callee.member, requestHelpers);\n}\n\nfunction ignoredFrameworkCall(callee: CalleeName): boolean {\n const checks = [\n hasSetMember(callee.local, capDslRoots),\n cdsFrameworkCall(callee),\n requestHelperCall(callee),\n hasSetMember(callee.member, transportMembers),\n hasSetMember(callee.local, globalObjects),\n callee.expression.startsWith('new Date().'),\n ];\n return checks.some(Boolean);\n}\n\nfunction argumentEvidence(\n args: ts.NodeArray<ts.Expression>,\n): Array<Record<string, unknown>> {\n return args.map((arg) => {\n if (ts.isIdentifier(arg)) return { kind: 'identifier', name: arg.text };\n if (ts.isArrayLiteralExpression(arg)) return {\n kind: 'array_literal',\n elements: arg.elements.flatMap((item, index) =>\n ts.isIdentifier(item)\n ? [{ index, kind: 'identifier', name: item.text }]\n : []),\n };\n if (ts.isObjectLiteralExpression(arg))\n return objectArgumentEvidence(arg);\n return { kind: 'unsupported', expression: arg.getText() };\n });\n}\n\nfunction objectArgumentEvidence(\n argument: ts.ObjectLiteralExpression,\n): Record<string, unknown> {\n const properties = argument.properties.flatMap((property) => {\n if (ts.isShorthandPropertyAssignment(property))\n return [{\n kind: 'shorthand',\n property: property.name.text,\n argument: property.name.text,\n }];\n if (!ts.isPropertyAssignment(property)\n || !ts.isIdentifier(property.initializer)) return [];\n const name = propertyName(property.name);\n return name ? [{\n kind: 'property_assignment',\n property: name,\n argument: property.initializer.text,\n }] : [];\n });\n return { kind: 'object_literal', properties };\n}\n\nfunction propertyName(name: ts.PropertyName): string | undefined {\n return ts.isIdentifier(name) || ts.isStringLiteralLike(name)\n || ts.isNumericLiteral(name) ? name.text : undefined;\n}\n\nfunction exactCaller(\n collection: CallCollection,\n node: ts.CallExpression,\n): ExecutableSymbolFact | undefined {\n const selected = selectCallOwner(\n executableSymbolCandidates(collection.symbols, collection.sourceFile),\n node.getStart(collection.source),\n node.getEnd(),\n );\n if (selected.status === 'ambiguous')\n throw new Error('invalid_prepared_repository_snapshot:symbol_call_owner_ambiguous');\n return selected.owner;\n}\n\nfunction relation(\n reference: SymbolImportReference | undefined,\n instance: SymbolClassInstance | undefined,\n proxy: SymbolCallProxy | undefined,\n localTarget: LocalSymbolTargetIdentity | undefined,\n provenThisMethod: boolean,\n): string {\n const derived = derivedRelation(instance, proxy);\n if (derived) return derived;\n if (reference?.moduleKind === 'package') return 'package_import';\n if (reference?.referenceShape === 'namespace_member')\n return 'relative_import_namespace_member';\n if (reference) return 'relative_import';\n if (localTarget) return 'indexed_local_symbol';\n return provenThisMethod ? 'indexed_this_method' : 'indexed_local_symbol';\n}\n\nfunction derivedRelation(\n instance: SymbolClassInstance | undefined,\n proxy: SymbolCallProxy | undefined,\n): string | undefined {\n if (instance?.importBinding?.moduleKind === 'package')\n return 'package_import_derived_member';\n if (instance) return 'class_instance_method';\n if (proxy?.importBinding.moduleKind === 'package')\n return 'package_import_derived_member';\n return proxy ? 'relative_import_proxy_member' : undefined;\n}\n\nfunction targetName(\n callee: CalleeName,\n reference: SymbolImportReference | undefined,\n instance: SymbolClassInstance | undefined,\n proxy: SymbolCallProxy | undefined,\n): string | undefined {\n if (instance && callee.member)\n return `${instance.className}.${callee.member}`;\n if (proxy && callee.member) return callee.member;\n if (callee.receiver === 'this') return callee.member;\n if (reference) return reference.requestedPublicName;\n return callee.member && callee.local\n ? `${callee.local}.${callee.member}`\n : callee.local;\n}\n\nfunction callFact(\n collection: CallCollection,\n node: ts.CallExpression,\n): SymbolCallFact | undefined {\n const caller = exactCaller(collection, node);\n if (!caller) return undefined;\n const callee = symbolCallName(node.expression);\n const proxy = callProxy(collection, node);\n const instance = callInstance(collection, node, callee);\n const reference = callImportReference(\n collection, node.expression, callee, instance, proxy,\n );\n const localTarget = reference || instance || proxy\n ? undefined\n : localSymbolTarget(node.expression, collection.source, collection.symbols);\n return retainedCallFact(collection, node, caller, callee, {\n proxy, instance, reference, localTarget,\n });\n}\n\nfunction expressionRoot(\n expression: ts.Expression,\n): ts.Identifier | undefined {\n let current = expression;\n while (ts.isPropertyAccessExpression(current))\n current = current.expression;\n return ts.isIdentifier(current) ? current : undefined;\n}\n\nfunction exactDeclaredContext<T extends {\n declarationStartOffset: number;\n declarationEndOffset: number;\n}>(\n identifier: ts.Identifier,\n candidates: readonly T[],\n): T | undefined {\n const matches = candidates.filter((candidate) =>\n identifierMatchesDeclaration(\n identifier,\n candidate.declarationStartOffset,\n candidate.declarationEndOffset,\n ));\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction callProxy(\n collection: CallCollection,\n node: ts.CallExpression,\n): SymbolCallProxy | undefined {\n const root = expressionRoot(node.expression);\n if (!root) return undefined;\n return exactDeclaredContext(\n root, collection.proxies.get(root.text) ?? [],\n );\n}\n\nfunction callInstance(\n collection: CallCollection,\n node: ts.CallExpression,\n callee: CalleeName,\n): SymbolClassInstance | undefined {\n const root = expressionRoot(node.expression);\n if (root && root.text !== 'this') {\n const exact = exactDeclaredContext(\n root, collection.instances.get(root.text) ?? [],\n );\n if (exact) return exact;\n }\n return callee.receiver\n ? thisPropertyInstance(collection, node, callee.receiver)\n : undefined;\n}\n\nfunction enclosingClass(node: ts.Node): ts.ClassLikeDeclaration | undefined {\n let current: ts.Node | undefined = node.parent;\n while (current && !ts.isSourceFile(current)) {\n if (ts.isClassLike(current)) return current;\n current = current.parent;\n }\n return undefined;\n}\n\nfunction thisPropertyInstance(\n collection: CallCollection,\n node: ts.CallExpression,\n receiver: string,\n): SymbolClassInstance | undefined {\n if (!receiver.startsWith('this.')) return undefined;\n const container = enclosingClass(node);\n if (!container) return undefined;\n const start = container.getStart(collection.source);\n const end = container.getEnd();\n const matches = (collection.instances.get(receiver) ?? []).filter(\n (candidate) => candidate.containerStartOffset === start\n && candidate.containerEndOffset === end,\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction callImportReference(\n collection: CallCollection,\n expression: ts.Expression,\n callee: CalleeName,\n instance: SymbolClassInstance | undefined,\n proxy: SymbolCallProxy | undefined,\n): SymbolImportReference | undefined {\n const direct = symbolImportReference(expression, collection.importBindings);\n if (direct || !callee.member) return direct;\n const inherited = instance?.importBinding ?? proxy?.importBinding;\n return inherited\n ? derivedMemberImportReference(inherited, callee.member)\n : undefined;\n}\n\nfunction retainedCallFact(\n collection: CallCollection,\n node: ts.CallExpression,\n caller: ExecutableSymbolFact,\n callee: CalleeName,\n context: CallContext,\n): SymbolCallFact | undefined {\n const target = targetName(\n callee, context.reference, context.instance, context.proxy,\n );\n const className = caller.qualifiedName.includes('.')\n ? caller.qualifiedName.split('.')[0] : undefined;\n const thisTarget = callee.receiver === 'this' && className && callee.member\n ? `${className}.${callee.member}` : undefined;\n const resolvedTarget = thisTarget ?? target;\n if (!resolvedTarget\n || !shouldRetainCall(\n collection, callee, resolvedTarget, context, Boolean(thisTarget),\n ))\n return undefined;\n return createCallFact(\n collection, node, caller, callee, resolvedTarget, thisTarget, context,\n );\n}\n\nfunction shouldRetainCall(\n collection: CallCollection,\n callee: CalleeName,\n target: string | undefined,\n context: CallContext,\n provenThisMethod: boolean,\n): boolean {\n if (!target || ignoredCall(callee)) return false;\n const callables = new Set(collection.symbols.flatMap((symbol) =>\n [symbol.localName, symbol.qualifiedName]));\n return provenThisMethod\n || Boolean(context.localTarget)\n || callables.has(target) && Boolean(context.instance)\n || hasImportedContext(context);\n}\n\nfunction ignoredCall(callee: CalleeName): boolean {\n return loggerCall(callee) || terminalCall(callee)\n || ignoredFrameworkCall(callee);\n}\n\nfunction loggerCall(callee: CalleeName): boolean {\n if (callee.local === 'logger') return true;\n if (callee.receiver?.endsWith('.logger')) return true;\n return callee.expression.startsWith('this.logger.')\n && hasSetMember(callee.member, loggerMembers);\n}\n\nfunction terminalCall(callee: CalleeName): boolean {\n return hasSetMember(callee.member, commonTerminalMembers)\n || hasSetMember(callee.member, loggerMembers);\n}\n\nfunction hasImportedContext(context: CallContext): boolean {\n return Boolean(context.reference ?? context.proxy ?? context.instance);\n}\n\nfunction createCallFact(\n collection: CallCollection,\n node: ts.CallExpression,\n caller: ExecutableSymbolFact,\n callee: CalleeName,\n target: string,\n thisTarget: string | undefined,\n context: CallContext,\n): SymbolCallFact {\n const importSource = context.instance?.importSource\n ?? context.proxy?.importSource\n ?? context.reference?.rawModuleSpecifier;\n return {\n callerQualifiedName: caller.qualifiedName,\n calleeExpression: callee.expression,\n calleeLocalName: target,\n receiverLocalName: callee.member ? callee.local ?? callee.receiver : undefined,\n importSource,\n sourceFile: collection.sourceFile,\n sourceLine: collection.source.getLineAndCharacterOfPosition(\n node.getStart(collection.source),\n ).line + 1,\n callSiteStartOffset: node.getStart(collection.source),\n callSiteEndOffset: node.getEnd(),\n callRole: 'ordinary_call',\n evidence: callEvidence(caller, callee, target, thisTarget, context, node),\n };\n}\n\nfunction callEvidence(\n caller: ExecutableSymbolFact,\n callee: CalleeName,\n target: string,\n thisTarget: string | undefined,\n context: CallContext,\n node: ts.CallExpression,\n): Record<string, unknown> {\n return {\n relation: relation(\n context.reference, context.instance, context.proxy,\n context.localTarget, Boolean(thisTarget),\n ),\n caller: caller.qualifiedName,\n targetName: target,\n ...importReferenceEvidence(context),\n ...instanceEvidence(context.instance, callee),\n callArguments: argumentEvidence(node.arguments),\n ...proxyEvidence(context.proxy),\n ...(context.localTarget\n ? { localTargetIdentity: context.localTarget }\n : {}),\n candidateStrategy: parserCandidateStrategy(context),\n };\n}\n\nfunction importReferenceEvidence(\n context: CallContext,\n): Record<string, unknown> {\n if (!context.reference) return {};\n const derived = context.instance ?? context.proxy;\n return derived && context.reference.moduleKind === 'package'\n ? { derivedImportBinding: context.reference }\n : { importBinding: context.reference };\n}\n\nfunction instanceEvidence(\n instance: SymbolClassInstance | undefined,\n callee: CalleeName,\n): Record<string, unknown> {\n if (!instance) return {};\n return {\n instanceVariable: instance.propertyName ?? callee.local,\n className: instance.className,\n methodName: callee.member,\n classImportSource: instance.importSource,\n classImportBinding: instance.importBinding,\n };\n}\n\nfunction proxyEvidence(\n proxy: SymbolCallProxy | undefined,\n): Record<string, unknown> {\n if (!proxy) return {};\n return {\n proxyVariableName: proxy.variableName,\n factory: proxy.factory,\n factoryExpression: proxy.factory,\n factoryImportSource: proxy.importSource,\n factoryImportBinding: proxy.importBinding,\n };\n}\n\nfunction parserCandidateStrategy(context: CallContext): string | undefined {\n if (context.instance?.importSource)\n return 'relative_import_class_instance_method';\n if (context.instance) return 'same_file_class_instance_method';\n return context.proxy\n ? 'proxy_member_exact_export_or_unique_member'\n : undefined;\n}\n\nexport function collectSymbolCallFacts(\n collection: CallCollection,\n): SymbolCallFact[] {\n const calls: SymbolCallFact[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node)) {\n const call = callFact(collection, node);\n if (call) calls.push(call);\n }\n ts.forEachChild(node, visit);\n };\n visit(collection.source);\n return calls;\n}\n","import ts from 'typescript';\n\nexport type ExecutableBodyEligibilityReason =\n | 'body_present'\n | 'declaration_only'\n | 'ambient_declaration'\n | 'abstract_bodyless'\n | 'overload_signature';\n\nexport interface ExecutableBodyEligibilityEvidence {\n eligible: boolean;\n reason: ExecutableBodyEligibilityReason;\n}\n\nfunction hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean {\n return ts.canHaveModifiers(node)\n && Boolean(ts.getModifiers(node)?.some((item) => item.kind === kind));\n}\n\nexport function executableBodyEligibility(\n node: ts.FunctionLikeDeclaration,\n source: ts.SourceFile,\n): ExecutableBodyEligibilityEvidence {\n if (node.body) return { eligible: true, reason: 'body_present' };\n if (hasModifier(node, ts.SyntaxKind.AbstractKeyword))\n return { eligible: false, reason: 'abstract_bodyless' };\n if (hasModifier(node, ts.SyntaxKind.DeclareKeyword))\n return { eligible: false, reason: 'ambient_declaration' };\n return {\n eligible: false,\n reason: source.isDeclarationFile\n ? 'declaration_only'\n : 'overload_signature',\n };\n}\n","import ts from 'typescript';\nimport {\n symbolCallName,\n type SymbolCallProxy,\n type SymbolClassInstance,\n} from './009-symbol-call-facts.js';\nimport {\n identifierMatchesDeclaration,\n symbolImportReference,\n type SymbolImportBinding,\n} from './002-symbol-import-bindings.js';\n\ninterface DerivedContextCollection {\n source: ts.SourceFile;\n importBindings: readonly SymbolImportBinding[];\n declaredClasses: ReadonlySet<string>;\n proxies: Map<string, SymbolCallProxy[]>;\n instances: Map<string, SymbolClassInstance[]>;\n}\n\nconst builtInConstructors = new Set([\n 'Set', 'Map', 'WeakSet', 'WeakMap',\n 'Date', 'RegExp', 'URL', 'URLSearchParams',\n 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError',\n 'TypeError', 'URIError', 'AggregateError',\n 'ArrayBuffer', 'SharedArrayBuffer', 'DataView',\n 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array',\n 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array',\n 'Float64Array', 'BigInt64Array', 'BigUint64Array',\n 'Promise', 'AbortController',\n]);\n\nfunction appendNamed<T>(\n values: Map<string, T[]>,\n name: string,\n value: T,\n): void {\n const matches = values.get(name) ?? [];\n matches.push(value);\n values.set(name, matches);\n}\n\nfunction assignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment\n && kind <= ts.SyntaxKind.LastAssignment;\n}\n\nfunction mutationUnary(\n node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression,\n): boolean {\n return node.operator === ts.SyntaxKind.PlusPlusToken\n || node.operator === ts.SyntaxKind.MinusMinusToken;\n}\n\nfunction receiverIdentifier(\n expression: ts.Expression,\n): ts.Identifier | undefined {\n let current = expression;\n while (ts.isPropertyAccessExpression(current)\n || ts.isElementAccessExpression(current))\n current = current.expression;\n return ts.isIdentifier(current) ? current : undefined;\n}\n\nfunction nodeWritesMember(\n node: ts.Node,\n matches: (expression: ts.Expression) => boolean,\n): boolean {\n if (ts.isBinaryExpression(node))\n return assignmentOperator(node.operatorToken.kind) && matches(node.left);\n if (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))\n return mutationUnary(node) && matches(node.operand);\n return ts.isDeleteExpression(node) && matches(node.expression);\n}\n\nfunction memberWrite(\n source: ts.SourceFile,\n declaration: ts.Identifier,\n): boolean {\n const start = declaration.getStart(source);\n const end = declaration.getEnd();\n const matches = (expression: ts.Expression): boolean => {\n const receiver = receiverIdentifier(expression);\n return Boolean(receiver && receiver !== expression\n && identifierMatchesDeclaration(receiver, start, end));\n };\n let written = false;\n const visit = (node: ts.Node): void => {\n if (written) return;\n written = nodeWritesMember(node, matches);\n if (!written) ts.forEachChild(node, visit);\n };\n visit(source);\n return written;\n}\n\nfunction stableVariable(\n collection: DerivedContextCollection,\n node: ts.VariableDeclaration,\n): node is ts.VariableDeclaration & { name: ts.Identifier } {\n return ts.isIdentifier(node.name)\n && ts.isVariableDeclarationList(node.parent)\n && (node.parent.flags & ts.NodeFlags.Const) !== 0\n && !memberWrite(collection.source, node.name);\n}\n\nfunction collectProxy(\n collection: DerivedContextCollection,\n node: ts.Node,\n): void {\n if (!ts.isVariableDeclaration(node) || !stableVariable(collection, node)\n || !node.initializer || !ts.isCallExpression(node.initializer)\n || !ts.isPropertyAccessExpression(node.initializer.expression)) return;\n const callee = symbolCallName(node.initializer.expression);\n const binding = symbolImportReference(\n node.initializer.expression, collection.importBindings,\n );\n if (!callee.member || !binding) return;\n appendNamed(collection.proxies, node.name.text, {\n importSource: binding.rawModuleSpecifier,\n importBinding: binding,\n factory: callee.expression,\n variableName: node.name.text,\n declarationStartOffset: node.name.getStart(collection.source),\n declarationEndOffset: node.name.getEnd(),\n });\n}\n\nfunction propertyContainer(\n declaration: ts.Identifier | ts.PropertyName,\n propertyName: string | undefined,\n): ts.ClassLikeDeclaration | undefined {\n const property = propertyName && ts.isPropertyDeclaration(declaration.parent)\n ? declaration.parent : undefined;\n return property && ts.isClassLike(property.parent)\n ? property.parent : undefined;\n}\n\nfunction eligibleClassName(\n collection: DerivedContextCollection,\n className: string,\n imported: ReturnType<typeof symbolImportReference>,\n): boolean {\n if (builtInConstructors.has(className)) return false;\n return Boolean(imported || collection.declaredClasses.has(className));\n}\n\nfunction resolvedClassName(\n className: string,\n imported: ReturnType<typeof symbolImportReference>,\n): string {\n const importedName = imported?.importedName;\n return importedName && importedName !== 'default'\n ? importedName : className;\n}\n\nfunction rememberInstance(\n collection: DerivedContextCollection,\n declaration: ts.Identifier | ts.PropertyName,\n classExpression: ts.Identifier,\n propertyName?: string,\n): void {\n const className = classExpression.text;\n const imported = symbolImportReference(\n classExpression, collection.importBindings,\n );\n if (!eligibleClassName(collection, className, imported)) return;\n const container = propertyContainer(declaration, propertyName);\n const variableName = propertyName\n ? `this.${propertyName}` : declaration.getText();\n appendNamed(collection.instances, variableName, {\n className: resolvedClassName(className, imported),\n importSource: imported?.rawModuleSpecifier,\n importBinding: imported,\n propertyName,\n declarationStartOffset: declaration.getStart(collection.source),\n declarationEndOffset: declaration.getEnd(),\n containerStartOffset: container?.getStart(collection.source),\n containerEndOffset: container?.getEnd(),\n });\n}\n\nfunction collectVariableInstance(\n collection: DerivedContextCollection,\n node: ts.Node,\n): void {\n if (!ts.isVariableDeclaration(node) || !stableVariable(collection, node))\n return;\n const initializer = node.initializer;\n if (initializer && ts.isNewExpression(initializer)\n && ts.isIdentifier(initializer.expression))\n rememberInstance(collection, node.name, initializer.expression);\n}\n\nfunction propertyName(name: ts.PropertyName): string | undefined {\n return ts.isIdentifier(name) || ts.isStringLiteralLike(name)\n || ts.isNumericLiteral(name) ? name.text : undefined;\n}\n\nfunction thisPropertyWrite(\n expression: ts.Expression,\n name: string,\n): boolean {\n if (ts.isPropertyAccessExpression(expression))\n return expression.expression.kind === ts.SyntaxKind.ThisKeyword\n && expression.name.text === name;\n return ts.isElementAccessExpression(expression)\n && expression.expression.kind === ts.SyntaxKind.ThisKeyword\n && Boolean(expression.argumentExpression\n && ts.isStringLiteralLike(expression.argumentExpression)\n && expression.argumentExpression.text === name);\n}\n\nfunction nodeWritesThisProperty(\n node: ts.Node,\n name: string,\n): boolean {\n if (ts.isBinaryExpression(node))\n return assignmentOperator(node.operatorToken.kind)\n && thisPropertyWrite(node.left, name);\n if (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))\n return mutationUnary(node) && thisPropertyWrite(node.operand, name);\n return ts.isDeleteExpression(node)\n && thisPropertyWrite(node.expression, name);\n}\n\nfunction stableProperty(\n node: ts.PropertyDeclaration,\n name: string,\n): boolean {\n const flags = ts.getCombinedModifierFlags(node);\n if ((flags & (ts.ModifierFlags.Private | ts.ModifierFlags.Readonly)) === 0\n || !ts.isClassLike(node.parent)) return false;\n let written = false;\n const visit = (child: ts.Node): void => {\n if (written || child === node) return;\n written = nodeWritesThisProperty(child, name);\n if (!written) ts.forEachChild(child, visit);\n };\n visit(node.parent);\n return !written;\n}\n\nfunction collectPropertyInstance(\n collection: DerivedContextCollection,\n node: ts.Node,\n): void {\n if (!ts.isPropertyDeclaration(node)) return;\n const initializer = node.initializer;\n if (!initializer || !ts.isNewExpression(initializer)\n || !ts.isIdentifier(initializer.expression)) return;\n const name = propertyName(node.name);\n if (name && stableProperty(node, name)) rememberInstance(\n collection, node.name, initializer.expression, name,\n );\n}\n\nexport function collectDerivedSymbolContexts(\n collection: DerivedContextCollection,\n): void {\n const visit = (node: ts.Node): void => {\n collectProxy(collection, node);\n collectVariableInstance(collection, node);\n collectPropertyInstance(collection, node);\n ts.forEachChild(node, visit);\n };\n visit(collection.source);\n}\n","import type {\n ExecutableSymbolFact,\n PackageFacts,\n} from '../types.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport type { PackageEntrypointManifest } from './package-json-parser.js';\nimport {\n analyzePackagePublicSurface,\n type PackagePublicSurfaceAnalysis,\n type SymbolPublicSurfaceEvidence,\n} from './003-package-public-surface.js';\nimport type { RepositorySourceContext } from './ts-project.js';\n\nfunction symbolIdentity(\n symbol: Pick<\n ExecutableSymbolFact,\n 'sourceFile' | 'kind' | 'qualifiedName' | 'startOffset' | 'endOffset'\n >,\n): string {\n return [\n symbol.sourceFile,\n symbol.kind,\n symbol.qualifiedName,\n symbol.startOffset,\n symbol.endOffset,\n ].join('\\0');\n}\n\nfunction exposureBySymbol(\n analysis: PackagePublicSurfaceAnalysis,\n): Map<string, SymbolPublicSurfaceEvidence> {\n return new Map(analysis.symbols.map((item) => [\n symbolIdentity({\n sourceFile: item.target.sourceFile,\n kind: item.target.kind,\n qualifiedName: item.target.qualifiedName,\n startOffset: item.target.startOffset,\n endOffset: item.target.endOffset,\n }),\n item,\n ]));\n}\n\nexport function analyzeRepositoryPackageSurface(\n facts: PackageFacts,\n manifest: PackageEntrypointManifest,\n sources: RepositorySourceContext,\n): PackagePublicSurfaceAnalysis {\n const modules = sources.entries()\n .filter((snapshot) => /\\.[jt]s$/.test(snapshot.filePath))\n .map((snapshot) => ({\n sourceFile: normalizePath(snapshot.filePath),\n source: snapshot.sourceFile(),\n }));\n return analyzePackagePublicSurface(facts.packageName, manifest, modules);\n}\n\nexport function mergePackageSymbolEvidence(\n symbols: readonly ExecutableSymbolFact[],\n analysis: PackagePublicSurfaceAnalysis,\n): ExecutableSymbolFact[] {\n const exposures = exposureBySymbol(analysis);\n return symbols.map((symbol) => {\n const exposure = exposures.get(symbolIdentity(symbol));\n if (!exposure) return symbol;\n return {\n ...symbol,\n importExportEvidence: {\n ...(symbol.importExportEvidence ?? {}),\n packagePublicSurface: {\n schema: analysis.surface.schema,\n recordCap: analysis.surface.recordCap,\n bodyEligibility: exposure.target.bodyEligibility,\n exposures: exposure.exposures,\n exposureTotal: exposure.exposureTotal,\n shownExposureCount: exposure.shownExposureCount,\n omittedExposureCount: exposure.omittedExposureCount,\n },\n },\n };\n });\n}\n","import { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nexport async function sha256File(filePath: string): Promise<string> {\n return createHash('sha256')\n .update(await readFile(filePath))\n .digest('hex');\n}\nexport function sha256Text(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n","import type { Db } from './connection.js';\nimport { ANALYZER_VERSION } from '../version.js';\nimport {\n parsePackageImportReference,\n} from '../parsers/012-package-fact-contract.js';\n\ninterface PackageCallRow {\n id: number;\n repoId: number;\n evidence: Record<string, unknown>;\n}\n\nexport interface PackageInvalidationBatch {\n publishingRepoIds: ReadonlySet<number>;\n affectedCallerRepoIds: Set<number>;\n affectedWorkspaceIds: Set<number>;\n}\n\nconst resolverKeys = new Set([\n 'candidateStrategy', 'candidateCount', 'eligibleCandidateCount',\n 'selectedCandidateCount', 'candidateSetComplete', 'resolvedModulePath',\n 'resolvedTargetRepositoryId', 'unresolvedReason',\n 'targetRepositoryCandidateCount', 'targetRepositoryCandidates',\n 'shownTargetRepositoryCandidateCount',\n 'omittedTargetRepositoryCandidateCount', 'publicSurface',\n]);\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown> : undefined;\n}\n\nfunction parsedEvidence(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== 'string') return undefined;\n try {\n return record(JSON.parse(value) as unknown);\n } catch {\n return undefined;\n }\n}\n\nfunction packageName(evidence: Record<string, unknown>): string | undefined {\n return parsePackageImportReference(evidence.importBinding)\n ?.requestedPackageName ?? undefined;\n}\n\nfunction packageCallEvidenceValid(\n evidence: Record<string, unknown>,\n): boolean {\n const binding = record(evidence.importBinding);\n const classified = evidence.relation === 'package_import'\n || binding?.moduleKind === 'package';\n return !classified || packageName(evidence) !== undefined;\n}\n\nfunction currentCalls(\n db: Db,\n workspaceId: number,\n targetRepoId: number,\n): PackageCallRow[] {\n const rows = db.prepare(`SELECT sc.id,sc.repo_id repoId,\n sc.evidence_json evidenceJson FROM symbol_calls sc\n JOIN repositories r ON r.id=sc.repo_id\n WHERE r.workspace_id=? AND r.id<>? AND r.fact_analyzer_version=?\n ORDER BY sc.id`).all(workspaceId, targetRepoId, ANALYZER_VERSION);\n return rows.flatMap((row) => {\n const evidence = parsedEvidence(row.evidenceJson);\n if (!evidence || typeof row.id !== 'number'\n || typeof row.repoId !== 'number')\n throw new Error('invalid_current_package_import_evidence');\n if (!packageCallEvidenceValid(evidence))\n throw new Error('invalid_current_package_import_evidence');\n return evidence.relation === 'package_import'\n || record(evidence.importBinding)?.moduleKind === 'package'\n ? [{ id: row.id, repoId: row.repoId, evidence }]\n : [];\n });\n}\n\nfunction pendingEvidence(evidence: Record<string, unknown>): string {\n const parser = Object.fromEntries(Object.entries(evidence).filter(\n ([key]) => !resolverKeys.has(key),\n ));\n if (!packageName(parser))\n throw new Error('invalid_current_package_import_evidence');\n return JSON.stringify({\n ...parser,\n candidateStrategy: 'package_import_pending',\n candidateCount: 0,\n eligibleCandidateCount: 0,\n selectedCandidateCount: 0,\n candidateSetComplete: false,\n unresolvedReason: 'package_resolution_pending',\n });\n}\n\nfunction targetWorkspace(\n db: Db,\n repoId: number,\n): { workspaceId: number; packageName?: string | null } {\n const row = db.prepare(`SELECT workspace_id workspaceId,\n package_name packageName FROM repositories WHERE id=?`).get(repoId);\n if (typeof row?.workspaceId !== 'number')\n throw new Error('Repository target is missing its workspace');\n return {\n workspaceId: row.workspaceId,\n packageName: typeof row.packageName === 'string'\n || row.packageName === null ? row.packageName : undefined,\n };\n}\n\nfunction packageIdentityChanged(\n previous: string | null | undefined,\n next: string | undefined,\n): boolean {\n const previousName = typeof previous === 'string' ? previous : null;\n const nextName = typeof next === 'string' ? next : null;\n return previousName !== nextName;\n}\n\nexport function invalidatePackageTargetFacts(\n db: Db,\n targetRepoId: number,\n newPackageName: string | undefined,\n batch: PackageInvalidationBatch,\n): void {\n const target = targetWorkspace(db, targetRepoId);\n const names = new Set(\n [target.packageName, newPackageName].filter(\n (value): value is string => typeof value === 'string' && value.length > 0,\n ),\n );\n if (names.size === 0) return;\n const update = db.prepare(`UPDATE symbol_calls SET callee_symbol_id=NULL,\n status='unresolved',unresolved_reason='package_resolution_pending',\n evidence_json=? WHERE id=?`);\n let matched = false;\n for (const call of currentCalls(db, target.workspaceId, targetRepoId)) {\n const requested = packageName(call.evidence);\n if (!requested || !names.has(requested)) continue;\n update.run(pendingEvidence(call.evidence), call.id);\n batch.affectedCallerRepoIds.add(call.repoId);\n matched = true;\n }\n if (matched || packageIdentityChanged(\n target.packageName, newPackageName,\n )) batch.affectedWorkspaceIds.add(target.workspaceId);\n}\n\nexport function createPackageInvalidationBatch(\n publishingRepoIds: readonly number[],\n): PackageInvalidationBatch {\n return {\n publishingRepoIds: new Set(publishingRepoIds),\n affectedCallerRepoIds: new Set(),\n affectedWorkspaceIds: new Set(),\n };\n}\n\nexport function mergePackageInvalidationEffects(\n target: PackageInvalidationBatch,\n source: PackageInvalidationBatch,\n): void {\n for (const repoId of source.affectedCallerRepoIds)\n target.affectedCallerRepoIds.add(repoId);\n for (const workspaceId of source.affectedWorkspaceIds)\n target.affectedWorkspaceIds.add(workspaceId);\n}\n\nexport function finalizePackageTargetInvalidations(\n db: Db,\n batch: PackageInvalidationBatch,\n): void {\n const increment = db.prepare(`UPDATE repositories\n SET fact_generation=fact_generation+1 WHERE id=?`);\n for (const repoId of batch.affectedCallerRepoIds)\n if (!batch.publishingRepoIds.has(repoId)) increment.run(repoId);\n const stale = db.prepare(`UPDATE repositories\n SET graph_stale_reason='package_target_facts_changed',\n graph_stale_at=datetime('now') WHERE workspace_id=?`);\n for (const workspaceId of batch.affectedWorkspaceIds)\n stale.run(workspaceId);\n}\n","import type { Db } from '../db/connection.js';\n\ninterface ExtensionRow {\n id: number;\n repoId: number;\n serviceName: string;\n qualifiedName: string;\n sourceFile: string;\n moduleSpecifier?: string | null;\n importedSymbol?: string | null;\n importKind?: string | null;\n}\ninterface BaseRow { id: number; repoId: number }\n\ninterface DesiredOperation { id: number; operationType: string; operationName: string; operationPath: string; paramsJson: string; returnType: string | null; sourceFile: string; sourceLine: number }\ninterface ExistingOperation extends DesiredOperation { baseOperationId: number | null }\n\nexport function materializeCdsExtensionOperations(\n db: Db,\n workspaceId: number,\n excludedRepoIds: ReadonlySet<number> = new Set(),\n): void {\n const extensions = extensionRows(db, workspaceId, excludedRepoIds);\n db.transaction(() => {\n const changedRepos = new Set<number>();\n for (const extension of extensions) {\n if (reconcileExtension(db, workspaceId, extension)) changedRepos.add(extension.repoId);\n }\n for (const repoId of changedRepos) markRepositoryDerivedFactsChanged(db, repoId);\n });\n}\n\nfunction extensionRows(\n db: Db,\n workspaceId: number,\n excludedRepoIds: ReadonlySet<number>,\n): ExtensionRow[] {\n const excluded = [...excludedRepoIds].sort((left, right) => left - right);\n const exclusion = excluded.length > 0\n ? ` AND r.id NOT IN (${excluded.map(() => '?').join(',')})`\n : '';\n return db.prepare(`SELECT s.id,r.id repoId,s.service_name serviceName,\n s.qualified_name qualifiedName,s.source_file sourceFile,\n s.extension_module_specifier moduleSpecifier,\n s.extension_imported_symbol importedSymbol,\n s.extension_import_kind importKind\n FROM cds_services s JOIN repositories r ON r.id=s.repo_id\n WHERE r.workspace_id=? AND s.is_extend=1${exclusion}\n ORDER BY r.id,s.id`).all(\n workspaceId, ...excluded,\n ) as unknown as ExtensionRow[];\n}\n\nfunction reconcileExtension(db: Db, workspaceId: number, extension: ExtensionRow): boolean {\n const bases = resolveBase(db, workspaceId, extension);\n const status = bases.length === 1 ? 'resolved' : bases.length > 1 ? 'ambiguous' : 'unresolved';\n const baseId = status === 'resolved' ? bases[0]?.id ?? null : null;\n const desired = baseId === null ? [] : desiredInheritedOperations(db, extension, baseId);\n const statusChanged = updateExtensionStatus(db, extension.id, status, baseId);\n const operationChanged = reconcileInheritedOperations(db, extension, desired);\n reconcileOperationSearchRows(db, extension.repoId);\n return statusChanged || operationChanged;\n}\n\nfunction desiredInheritedOperations(db: Db, extension: ExtensionRow, baseId: number): DesiredOperation[] {\n return db.prepare(\"SELECT id,operation_type operationType,operation_name operationName,operation_path operationPath,params_json paramsJson,return_type returnType,source_file sourceFile,source_line sourceLine FROM cds_operations WHERE service_id=? AND provenance='direct' AND NOT EXISTS (SELECT 1 FROM cds_operations direct WHERE direct.service_id=? AND direct.provenance='direct' AND direct.operation_name=cds_operations.operation_name AND direct.operation_path=cds_operations.operation_path) ORDER BY operation_name,operation_path,id\").all(baseId, extension.id) as unknown as DesiredOperation[];\n}\n\nfunction updateExtensionStatus(db: Db, serviceId: number, status: string, baseId: number | null): boolean {\n const row = db.prepare('SELECT extension_base_status status,extension_base_service_id baseId FROM cds_services WHERE id=?').get(serviceId) as { status?: string | null; baseId?: number | null } | undefined;\n if (row?.status === status && (row.baseId ?? null) === baseId) return false;\n db.prepare('UPDATE cds_services SET extension_base_status=?, extension_base_service_id=? WHERE id=?').run(status, baseId, serviceId);\n return true;\n}\n\nfunction reconcileInheritedOperations(db: Db, extension: ExtensionRow, desired: DesiredOperation[]): boolean {\n const existing = db.prepare(\"SELECT id,operation_type operationType,operation_name operationName,operation_path operationPath,params_json paramsJson,return_type returnType,source_file sourceFile,source_line sourceLine,base_operation_id baseOperationId FROM cds_operations WHERE service_id=? AND provenance='inherited'\").all(extension.id) as unknown as ExistingOperation[];\n const desiredKeys = new Set(desired.map((row) => `${row.operationName}\\0${row.operationPath}`));\n const byKey = new Map(existing.map((row) => [`${row.operationName}\\0${row.operationPath}`, row]));\n let changed = false;\n for (const row of existing) {\n if (desiredKeys.has(`${row.operationName}\\0${row.operationPath}`)) continue;\n db.prepare('DELETE FROM cds_operations WHERE id=?').run(row.id);\n changed = true;\n }\n const update = db.prepare('UPDATE cds_operations SET operation_type=?,params_json=?,return_type=?,source_file=?,source_line=?,base_operation_id=? WHERE id=?');\n const add = db.prepare(\"INSERT INTO cds_operations(service_id,operation_type,operation_name,operation_path,params_json,return_type,source_file,source_line,provenance,base_operation_id) VALUES(?,?,?,?,?,?,?,?,'inherited',?)\");\n for (const row of desired) {\n const current = byKey.get(`${row.operationName}\\0${row.operationPath}`);\n if (current && operationMatches(current, row)) continue;\n if (current) update.run(row.operationType, row.paramsJson, row.returnType, row.sourceFile, row.sourceLine, row.id, current.id);\n else add.run(extension.id, row.operationType, row.operationName, row.operationPath, row.paramsJson, row.returnType, row.sourceFile, row.sourceLine, row.id);\n changed = true;\n }\n return changed;\n}\n\nfunction operationMatches(current: ExistingOperation, desired: DesiredOperation): boolean {\n return current.operationType === desired.operationType && current.paramsJson === desired.paramsJson && current.returnType === desired.returnType && current.sourceFile === desired.sourceFile && current.sourceLine === desired.sourceLine && current.baseOperationId === desired.id;\n}\n\nfunction reconcileOperationSearchRows(db: Db, repoId: number): void {\n db.prepare(\"DELETE FROM search_index WHERE repo=? AND kind='operation'\").run(String(repoId));\n db.prepare(`INSERT INTO search_index(kind,name,path,repo)\n SELECT 'operation',o.operation_name,o.operation_path,?\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id\n WHERE s.repo_id=? ORDER BY o.operation_name,o.operation_path,o.id`).run(String(repoId), repoId);\n}\n\nfunction markRepositoryDerivedFactsChanged(db: Db, repoId: number): void {\n db.prepare(\"UPDATE repositories SET fact_generation=COALESCE(fact_generation,0)+1, graph_stale_reason='derived_facts_changed', graph_stale_at=? WHERE id=?\").run(new Date().toISOString(), repoId);\n}\n\nfunction resolveBase(db: Db, workspaceId: number, extension: ExtensionRow): BaseRow[] {\n const symbol = extension.importedSymbol ?? extension.serviceName;\n if (extension.importKind === 'relative' && extension.moduleSpecifier) return relativeBase(db, extension, symbol);\n if (extension.importKind === 'package' && extension.moduleSpecifier) return packageBase(db, workspaceId, extension.moduleSpecifier, symbol);\n return sameRepoBase(db, extension, symbol);\n}\n\nfunction relativeBase(db: Db, extension: ExtensionRow, symbol: string): BaseRow[] {\n const modulePath = normalizeModulePath(extension.sourceFile, extension.moduleSpecifier ?? '');\n return db.prepare(`SELECT s.id,s.repo_id repoId FROM cds_services s WHERE s.repo_id=? AND s.is_extend=0 AND (s.qualified_name=? OR s.service_name=?) AND (s.source_file=? OR s.source_file=?) ORDER BY s.id`).all(extension.repoId, symbol, symbol, modulePath, `${modulePath}.cds`) as unknown as BaseRow[];\n}\n\nfunction packageBase(db: Db, workspaceId: number, specifier: string, symbol: string): BaseRow[] {\n const packageName = packageNameFromSpecifier(specifier);\n const moduleSuffix = specifier.slice(packageName.length).replace(/^\\//, '');\n return db.prepare(`SELECT s.id,s.repo_id repoId FROM cds_services s JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=? AND s.is_extend=0 AND r.package_name=? AND (s.qualified_name=? OR s.service_name=?) AND (?='' OR s.source_file=? OR s.source_file=?) ORDER BY s.id`).all(workspaceId, packageName, symbol, symbol, moduleSuffix, moduleSuffix, `${moduleSuffix}.cds`) as unknown as BaseRow[];\n}\n\nfunction sameRepoBase(db: Db, extension: ExtensionRow, symbol: string): BaseRow[] {\n return db.prepare('SELECT id,repo_id repoId FROM cds_services WHERE repo_id=? AND is_extend=0 AND (qualified_name=? OR service_name=?) ORDER BY id').all(extension.repoId, symbol, symbol) as unknown as BaseRow[];\n}\n\nfunction normalizeModulePath(sourceFile: string, specifier: string): string {\n const base = sourceFile.split('/').slice(0, -1).join('/');\n const parts = `${base}/${specifier}`.split('/');\n const out: string[] = [];\n for (const part of parts) {\n if (!part || part === '.') continue;\n if (part === '..') out.pop();\n else out.push(part);\n }\n return out.join('/').replace(/\\.cds$/, '');\n}\n\nfunction packageNameFromSpecifier(specifier: string): string {\n const parts = specifier.split('/');\n return specifier.startsWith('@') ? `${parts[0]}/${parts[1]}` : parts[0] ?? specifier;\n}\n","import type { Db } from '../db/connection.js';\nimport { listRepositories, reposByName } from '../db/repositories.js';\nimport { errorMessage } from '../utils/diagnostics.js';\nimport {\n prepareRepositoryIndex,\n publishOneRepository,\n recordIndexFailure,\n type PreparedRepositoryIndex,\n} from './repository-indexer.js';\nimport { materializeCdsExtensionOperations } from './cds-extension-resolver.js';\nimport {\n createPackageInvalidationBatch,\n finalizePackageTargetInvalidations,\n mergePackageInvalidationEffects,\n type PackageInvalidationBatch,\n} from '../db/004-package-target-invalidation.js';\nimport {\n isPreparedRepositorySnapshotError,\n} from '../db/013-index-publication-failure.js';\nimport { binaryCompare } from '../parsers/004-fact-identity.js';\n// Ownerless rows predate PID coordination; this matches doctor's stale-run threshold without taking over a recent legacy writer.\nconst LEGACY_OWNER_RECOVERY_MS = 60 * 60 * 1_000;\ntype RunningIndexRow = Record<string, unknown>;\nfunction ownerPid(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n ? value\n : undefined;\n}\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // Only ESRCH proves that ownership ended; permission and platform errors must fail closed.\n const ownerIsMissing = typeof error === 'object'\n && error !== null\n && 'code' in error\n && error.code === 'ESRCH';\n return !ownerIsMissing;\n }\n}\nfunction isRecoverableRun(row: RunningIndexRow, now: number): boolean {\n const pid = ownerPid(row.ownerPid);\n if (pid !== undefined) return !processIsAlive(pid);\n if (typeof row.startedAt !== 'string') return false;\n const startedAt = Date.parse(row.startedAt);\n return Number.isFinite(startedAt) && now - startedAt >= LEGACY_OWNER_RECOVERY_MS;\n}\nfunction recoveredOwnerMessage(row: RunningIndexRow): string {\n const pid = ownerPid(row.ownerPid);\n return pid === undefined\n ? 'Recovered stale legacy index writer without owner process metadata.'\n : `Recovered stale index writer because owner process ${pid} is no longer running.`;\n}\nexport function claimIndexRun(\n db: Db,\n workspaceId: number,\n repoCount: number,\n): number {\n // The short write transaction serializes claims without holding a SQLite writer lock during source preparation.\n try {\n return db.transaction(() => {\n const now = Date.now();\n const rows = db\n .prepare(\"SELECT id,workspace_id workspaceId,owner_pid ownerPid,started_at startedAt FROM index_runs WHERE status='running' ORDER BY id\")\n .all();\n const active = rows.find((row) => !isRecoverableRun(row, now));\n if (active) {\n const pid = ownerPid(active.ownerPid);\n const owner = pid === undefined ? 'an unknown owner' : `process ${pid}`;\n throw new Error(`index_writer_active: this database is already being indexed for workspace ${String(active.workspaceId ?? 'unknown')} by ${owner}; wait for that writer to finish.`);\n }\n const finish = db.prepare(\n \"UPDATE index_runs SET finished_at=?,status='failed',error_message=? WHERE id=?\",\n );\n for (const row of rows)\n finish.run(new Date(now).toISOString(), recoveredOwnerMessage(row), row.id);\n const inserted = db\n .prepare('INSERT INTO index_runs(workspace_id,started_at,status,repo_count,file_count,diagnostic_count,owner_pid) VALUES(?,?,?,?,?,?,?) RETURNING id')\n .get(workspaceId, new Date(now).toISOString(), 'running', repoCount, 0, 0, process.pid);\n const runId = Number(inserted?.id);\n if (!Number.isSafeInteger(runId)) throw new Error('index_writer_claim_failed: SQLite did not return an index run identifier.');\n return runId;\n });\n } catch (error) {\n if (/\\b(?:locked|busy)\\b/i.test(errorMessage(error)))\n throw new Error(\n 'index_writer_coordination_failed: SQLite remained busy beyond the bounded writer-claim interval; wait for the active publication to finish.',\n { cause: error },\n );\n throw error;\n }\n}\nexport interface IndexWorkspaceSummary {\n repoCount: number;\n indexedCount: number;\n skippedCount: number;\n failedCount: number;\n failedRepos: Array<{ name: string; code: string }>;\n fileCount: number;\n diagnosticCount: number;\n}\n\nexport async function indexWorkspace(\n db: Db,\n workspaceId: number,\n options: { repo?: string; force: boolean; injectDerivedMaterializationFailure?: boolean },\n): Promise<IndexWorkspaceSummary> {\n const repos = selectedRepositories(db, workspaceId, options.repo);\n const runId = claimIndexRun(db, workspaceId, repos.length);\n const state: PreparationState = {\n fileCount: 0, diagnosticCount: 0, skippedCount: 0, rows: [],\n };\n try {\n await prepareRepositories(repos, options.force, state);\n return publishPreparedWorkspaceRows(\n db, workspaceId, runId, state.rows, options,\n );\n } catch (error) {\n finishFailedRun(db, runId, state, error);\n if (state.activeRepoId && state.rows.length < repos.length)\n recordIndexFailure(db, state.activeRepoId, error);\n throw error;\n }\n}\n\ntype IndexRepository = ReturnType<typeof listRepositories>[number];\ninterface PreparationState {\n fileCount: number;\n diagnosticCount: number;\n skippedCount: number;\n rows: PreparedRepositoryIndex[];\n activeRepoId?: number;\n}\n\ninterface PublicationState {\n fileCount: number;\n diagnosticCount: number;\n skippedCount: number;\n indexedCount: number;\n publicationFailureCount: number;\n failedRepoIds: Set<number>;\n failedRepos: Array<{ name: string; code: string }>;\n rows: readonly PreparedRepositoryIndex[];\n activeRepoId?: number;\n}\n\nfunction selectedRepositories(\n db: Db,\n workspaceId: number,\n repoName: string | undefined,\n): IndexRepository[] {\n const repos = repoName\n ? reposByName(db, repoName, workspaceId)\n : listRepositories(db, workspaceId);\n if (repoName && repos.length === 0)\n throw new Error(\n `selector_repo_not_found: no indexed repository matched ${repoName}.`,\n );\n if (repoName && repos.length > 1)\n throw new Error(\n `selector_repo_ambiguous: repository selector ${repoName} matched ${repos.length} repositories; use a unique repository name.`,\n );\n return repos;\n}\n\nasync function prepareRepositories(\n repos: readonly IndexRepository[],\n force: boolean,\n state: PreparationState,\n): Promise<void> {\n for (const repo of repos) {\n state.activeRepoId = repo.id;\n const result = await prepareRepositoryIndex(repo, force);\n state.rows.push(result);\n state.fileCount += result.fileCount;\n state.diagnosticCount += result.diagnosticCount;\n state.skippedCount += result.skipped ? 1 : 0;\n }\n}\n\nexport function publishPreparedWorkspaceRows(\n db: Db,\n workspaceId: number,\n runId: number,\n rows: readonly PreparedRepositoryIndex[],\n options: { injectDerivedMaterializationFailure?: boolean } = {},\n): IndexWorkspaceSummary {\n const state = publicationState(rows);\n db.transaction(() => {\n const effects = createPackageInvalidationBatch([]);\n const publishedRepoIds: number[] = [];\n for (const row of state.rows) {\n state.activeRepoId = row.repo.id;\n if (row.skipped) continue;\n const result = publishPreparedRow(db, row);\n if (result.status === 'failed') {\n recordPublicationFailure(db, state, row, result.error);\n continue;\n }\n state.indexedCount += 1;\n publishedRepoIds.push(row.repo.id);\n mergePackageInvalidationEffects(effects, result.effects);\n }\n if (options.injectDerivedMaterializationFailure)\n throw new Error('Injected derived materialization failure');\n materializeCdsExtensionOperations(\n db, workspaceId, state.failedRepoIds,\n );\n const invalidations = createPackageInvalidationBatch(publishedRepoIds);\n mergePackageInvalidationEffects(invalidations, effects);\n finalizePackageTargetInvalidations(db, invalidations);\n finishCompletedRun(db, runId, state);\n });\n return indexSummary(rows.length, state);\n}\n\nfunction publicationState(\n rows: readonly PreparedRepositoryIndex[],\n): PublicationState {\n return {\n rows,\n fileCount: rows.reduce((total, row) => total + row.fileCount, 0),\n diagnosticCount: rows.reduce(\n (total, row) => total + row.diagnosticCount, 0,\n ),\n skippedCount: rows.filter((row) => row.skipped).length,\n indexedCount: 0,\n publicationFailureCount: 0,\n failedRepoIds: new Set(),\n failedRepos: [],\n };\n}\n\ntype PublicationResult =\n | { status: 'published'; effects: PackageInvalidationBatch }\n | { status: 'failed'; error: unknown };\n\nfunction publishPreparedRow(\n db: Db,\n row: PreparedRepositoryIndex,\n): PublicationResult {\n const effects = createPackageInvalidationBatch([row.repo.id]);\n const outcome = publishOneRepository(db, row, effects);\n if (!outcome.ok && !isPreparedRepositorySnapshotError(outcome.error))\n throw outcome.error;\n return outcome.ok\n ? { status: 'published', effects }\n : { status: 'failed', error: outcome.error };\n}\n\nfunction recordPublicationFailure(\n db: Db,\n state: PublicationState,\n row: PreparedRepositoryIndex,\n error: unknown,\n): void {\n state.failedRepoIds.add(row.repo.id);\n state.failedRepos.push({\n name: row.repo.name,\n code: isPreparedRepositorySnapshotError(error)\n ? error.message : 'source_read_failed',\n });\n state.publicationFailureCount += 1;\n}\n\nfunction finishCompletedRun(\n db: Db,\n runId: number,\n state: PublicationState,\n): void {\n const status = completedRunStatus(\n state.rows.length, state.publicationFailureCount,\n );\n const error = status === 'success' ? null\n : `${state.publicationFailureCount} repositories failed index publication.`;\n db.prepare(`UPDATE index_runs SET finished_at=?,status=?,\n file_count=?,diagnostic_count=?,error_message=? WHERE id=?`).run(\n new Date().toISOString(), status, state.fileCount,\n completedDiagnosticCount(state), error, runId,\n );\n}\n\nfunction completedRunStatus(\n repoCount: number,\n failedCount: number,\n): 'success' | 'partial_failure' | 'failed' {\n if (failedCount === 0) return 'success';\n return failedCount === repoCount ? 'failed' : 'partial_failure';\n}\n\nfunction completedDiagnosticCount(state: PublicationState): number {\n return state.diagnosticCount + state.publicationFailureCount;\n}\n\nfunction finishFailedRun(\n db: Db,\n runId: number,\n state: PreparationState,\n error: unknown,\n): void {\n db.prepare(`UPDATE index_runs SET finished_at=?,status='failed',\n file_count=?,diagnostic_count=?,error_message=? WHERE id=?`).run(\n new Date().toISOString(), state.fileCount, state.diagnosticCount + 1,\n errorMessage(error), runId,\n );\n}\n\nfunction indexSummary(\n repoCount: number,\n state: PublicationState,\n): IndexWorkspaceSummary {\n return {\n repoCount,\n indexedCount: state.indexedCount,\n skippedCount: state.skippedCount,\n failedCount: state.publicationFailureCount,\n failedRepos: [...state.failedRepos].sort((left, right) =>\n binaryCompare(left.name, right.name)\n || binaryCompare(left.code, right.code)),\n fileCount: state.fileCount,\n diagnosticCount: completedDiagnosticCount(state),\n };\n}\n","import {\n projectBoundedInOrder,\n type BoundedProjection,\n} from '../utils/000-bounded-projection.js';\n\ntype Diagnostic = Record<string, unknown>;\n\nconst boundedDoctorArrayKeys = new Set([\n 'candidates',\n 'candidateScores',\n 'candidateFamilies',\n 'candidateEvidence',\n 'candidatePaths',\n 'candidateRawPaths',\n 'candidateNormalizedOperationPaths',\n 'normalizedCandidateOperations',\n 'candidateLiterals',\n 'bindingCandidates',\n 'bindingAlternatives',\n 'registrations',\n 'implementationHintSuggestions',\n 'selectableImplementationRepositories',\n 'matchedHints',\n 'candidateSuggestions',\n 'dynamicTargetCandidates',\n 'dynamicTargetCandidateSuggestions',\n 'rejectedCandidates',\n 'suggestedVarSets',\n 'copyableExamples',\n 'examples',\n 'expandedExamples',\n 'selectorSuggestions',\n 'serviceSuggestions',\n 'repositories',\n]);\n\nexport function boundDoctorDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] {\n return diagnostics.map(boundDoctorDiagnostic);\n}\n\nfunction boundDoctorDiagnostic(diagnostic: Diagnostic): Diagnostic {\n const bounded = boundDoctorValue(diagnostic);\n return isDiagnostic(bounded) ? bounded : {};\n}\n\nfunction boundDoctorValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(boundDoctorValue);\n if (!isDiagnostic(value)) return value;\n const input = value;\n const output: Diagnostic = {};\n for (const [key, child] of Object.entries(input)) {\n if (!Array.isArray(child) || !boundedDoctorArrayKeys.has(key)) {\n output[key] = boundDoctorValue(child);\n continue;\n }\n // Doctor producers already query or assemble deterministic semantic order.\n const projection = projectBoundedInOrder(child.map(boundDoctorValue));\n output[key] = projection.items;\n addProjectionMetadata(output, input, key, projection);\n }\n return output;\n}\n\nfunction isDiagnostic(value: unknown): value is Diagnostic {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction addProjectionMetadata(\n output: Diagnostic,\n input: Diagnostic,\n key: string,\n projection: BoundedProjection<unknown>,\n): void {\n const names = projectionNames(key);\n const total = Math.max(\n numericValue(input[names.total]),\n projection.totalCount,\n siblingCollectionCount(input, key),\n );\n output[names.total] = total;\n output[names.shown] = projection.shownCount;\n output[names.omitted] = Math.max(0, total - projection.shownCount);\n}\n\nfunction siblingCollectionCount(input: Diagnostic, key: string): number {\n if (key !== 'examples' || !Array.isArray(input.expandedExamples)) return 0;\n return input.expandedExamples.length;\n}\n\nfunction projectionNames(key: string): { total: string; shown: string; omitted: string } {\n const stem = projectionStem(key);\n return {\n total: `${stem}Count`,\n shown: `shown${upperFirst(stem)}Count`,\n omitted: `omitted${upperFirst(stem)}Count`,\n };\n}\n\nfunction projectionStem(key: string): string {\n const stems: Record<string, string> = {\n candidates: 'candidate',\n candidateScores: 'candidateScore',\n candidateFamilies: 'candidateFamily',\n candidateEvidence: 'candidateEvidence',\n candidatePaths: 'candidatePath',\n candidateRawPaths: 'candidateRawPath',\n candidateNormalizedOperationPaths: 'candidateNormalizedOperationPath',\n normalizedCandidateOperations: 'normalizedCandidateOperation',\n candidateLiterals: 'candidateLiteral',\n bindingCandidates: 'bindingCandidate',\n bindingAlternatives: 'bindingAlternative',\n registrations: 'registration',\n implementationHintSuggestions: 'implementationHintSuggestion',\n selectableImplementationRepositories: 'selectableImplementationRepository',\n matchedHints: 'matchedHint',\n candidateSuggestions: 'candidateSuggestion',\n dynamicTargetCandidates: 'dynamicTargetCandidate',\n dynamicTargetCandidateSuggestions: 'dynamicTargetCandidateSuggestion',\n rejectedCandidates: 'rejectedCandidate',\n suggestedVarSets: 'suggestedVarSet',\n copyableExamples: 'copyableExample',\n examples: 'example',\n expandedExamples: 'expandedExample',\n selectorSuggestions: 'selectorSuggestion',\n serviceSuggestions: 'serviceSuggestion',\n };\n return stems[key] ?? 'repository';\n}\n\nfunction numericValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction upperFirst(value: string): string {\n return value ? `${value[0]?.toUpperCase() ?? ''}${value.slice(1)}` : value;\n}\n","import type { Db } from '../db/connection.js';\nimport { factLifecycleDiagnostic } from '../db/001-fact-lifecycle.js';\nimport { ANALYZER_VERSION } from '../version.js';\n\ntype Diagnostic = Record<string, unknown>;\n\nexport function linkUpgradeWarnings(\n db: Db,\n workspaceId?: number,\n): Diagnostic[] {\n const lifecycle = factLifecycleDiagnostic(db, workspaceId);\n if (lifecycle) return [lifecycle];\n return [\n ...schemaDriftDiagnostics(db, true, workspaceId),\n ...analyzerVersionDiagnostics(db, true, workspaceId),\n ].filter((item) => [\n 'schema_legacy_columns_present',\n 'external_target_columns_missing_data',\n 'reindex_required_after_upgrade',\n 'reindex_required_after_analyzer_upgrade',\n ].includes(String(item.code)));\n}\n\nexport function schemaDriftDiagnostics(\n db: Db,\n strict: boolean,\n workspaceId?: number,\n): Diagnostic[] {\n if (!strict) return [];\n const columns = db.prepare('PRAGMA table_info(symbols)').all() as Array<{ name?: string }>;\n const legacy = columns.filter((row) => [\n 'external_target_kind', 'external_target_id', 'external_target_label',\n 'external_target_dynamic',\n ].includes(String(row.name))).map((row) => row.name);\n const missing = db.prepare(`SELECT c.id id,c.source_file sourceFile,\n c.source_line sourceLine FROM outbound_calls c\n JOIN repositories r ON r.id=c.repo_id\n WHERE c.call_type='external_http'\n AND (? IS NULL OR r.workspace_id=?)\n AND (c.external_target_id IS NULL OR c.external_target_label IS NULL\n OR c.external_target_kind IS NULL) LIMIT 20`).all(\n workspaceId, workspaceId,\n ) as Diagnostic[];\n const out: Diagnostic[] = [];\n if (legacy.length > 0) out.push({ severity: 'warning', code: 'schema_legacy_columns_present', message: 'Legacy external-target columns are present on symbols; run service-flow clean --db-only, then init/index/link to rebuild with the current schema.', scope: 'workspace', affectedColumns: legacy, remediation: 'service-flow clean --db-only && service-flow init <workspace> && service-flow index && service-flow link' });\n if (missing.length > 0) out.push({ severity: 'warning', code: 'external_target_columns_missing_data', message: 'External HTTP calls are missing queryable external target metadata; reindex is required after upgrade.', scope: 'workspace', affectedRows: missing, remediation: 'service-flow index --force && service-flow link' });\n if (legacy.length > 0 || missing.length > 0) out.push({ severity: 'warning', code: 'reindex_required_after_upgrade', message: 'This database cannot be made equivalent to a fresh index by relink alone.', scope: 'workspace', remediation: 'Rebuild or force reindex the workspace, then run service-flow doctor --strict.' });\n return out;\n}\n\nexport function analyzerVersionDiagnostics(\n db: Db,\n strict: boolean,\n workspaceId?: number,\n): Diagnostic[] {\n if (!strict) return [];\n const rows = db.prepare(`SELECT name,\n COALESCE(fact_analyzer_version,'legacy') factAnalyzerVersion\n FROM repositories WHERE index_status='indexed'\n AND (? IS NULL OR workspace_id=?)\n AND COALESCE(fact_analyzer_version,'legacy')<>?`).all(\n workspaceId, workspaceId, ANALYZER_VERSION,\n ) as Diagnostic[];\n if (rows.length === 0) return [];\n return [{ severity: 'warning', code: 'reindex_required_after_analyzer_upgrade', message: 'Repository facts were produced by an older or unknown analyzer; run service-flow index --force before relink to apply current parser semantics.', scope: 'workspace', affectedRepositoryCount: rows.length, currentAnalyzerVersion: ANALYZER_VERSION, repositories: rows, remediation: 'service-flow index --force && service-flow link' }];\n}\n","import type { Db } from '../db/connection.js';\n\ntype Diagnostic = Record<string, unknown>;\n\nfunction pendingPredicate(alias: string): string {\n return `${alias}.status='unresolved'\n AND ${alias}.callee_symbol_id IS NULL\n AND ${alias}.unresolved_reason='package_resolution_pending'\n AND json_extract(${alias}.evidence_json,'$.relation')='package_import'\n AND json_extract(${alias}.evidence_json,\n '$.importBinding.moduleKind')='package'\n AND json_extract(${alias}.evidence_json,\n '$.candidateStrategy')='package_import_pending'\n AND json_extract(${alias}.evidence_json,'$.candidateCount')=0\n AND json_extract(${alias}.evidence_json,'$.eligibleCandidateCount')=0\n AND json_extract(${alias}.evidence_json,'$.selectedCandidateCount')=0\n AND json_extract(${alias}.evidence_json,'$.candidateSetComplete')=0`;\n}\n\nfunction count(db: Db, sql: string): number {\n return Number(db.prepare(sql).get()?.count ?? 0);\n}\n\nexport function packagePendingDiagnostics(db: Db): Diagnostic[] {\n const pending = count(db, `SELECT COUNT(*) count FROM symbol_calls sc\n WHERE ${pendingPredicate('sc')}`);\n if (pending === 0) return [];\n const stale = count(db, `SELECT COUNT(*) count FROM repositories\n WHERE graph_stale_reason IS NOT NULL`);\n return [{\n severity: 'warning',\n code: 'package_import_resolution_pending',\n message: 'Package-import facts await workspace linking; terminal package-resolution quality is deferred.',\n packageResolutionState: 'pre_link_pending',\n pendingPackageImportCount: pending,\n graphState: 'stale',\n staleRepositoryCount: stale,\n requiredAction: 'relink',\n remediation: 'service-flow link --workspace /workspace --force',\n }];\n}\n\nexport function symbolCallQuality(db: Db): Diagnostic {\n const terminal = `NOT (${pendingPredicate('sc')})`;\n const row = db.prepare(`SELECT COUNT(*) total,\n SUM(CASE WHEN sc.status='resolved' THEN 1 ELSE 0 END) resolved,\n SUM(CASE WHEN sc.status='unresolved' THEN 1 ELSE 0 END) unresolved\n FROM symbol_calls sc WHERE ${terminal}`).get();\n const top = db.prepare(`SELECT sc.callee_expression calleeExpression,\n COUNT(*) count FROM symbol_calls sc\n WHERE sc.status='unresolved' AND ${terminal}\n GROUP BY sc.callee_expression\n ORDER BY count DESC,sc.callee_expression COLLATE BINARY LIMIT 5`).all();\n const total = Number(row?.total ?? 0);\n const unresolved = Number(row?.unresolved ?? 0);\n const ratio = total === 0 ? 0 : Number((unresolved / total).toFixed(4));\n return {\n severity: ratio > 0.05 ? 'warning' : 'info',\n code: 'strict_symbol_call_quality',\n message: 'Terminal symbol-call quality aggregate',\n total,\n resolved: Number(row?.resolved ?? 0),\n unresolved,\n unresolvedRatio: ratio,\n unresolvedRatioThreshold: 0.05,\n topUnresolvedCallees: top,\n };\n}\n","import type { Db } from '../db/connection.js';\nimport { classifyODataPathIntent, normalizeODataOperationInvocationPath } from '../linker/odata-path-normalizer.js';\nimport { implementationHintSuggestions } from '../trace/implementation-hints.js';\nimport { boundDoctorDiagnostics } from './001-doctor-projection.js';\nimport { factLifecycleDiagnostic } from '../db/001-fact-lifecycle.js';\nimport {\n analyzerVersionDiagnostics,\n schemaDriftDiagnostics,\n} from './002-doctor-lifecycle.js';\nimport {\n packagePendingDiagnostics,\n symbolCallQuality,\n} from './003-doctor-package-resolution.js';\nexport { linkUpgradeWarnings } from './002-doctor-lifecycle.js';\n\ntype Diagnostic = Record<string, unknown>;\ninterface DoctorOptions {\n detail?: boolean;\n workspaceId?: number;\n}\n\nexport function doctorDiagnostics(db: Db, strict: boolean, options: DoctorOptions = {}): Diagnostic[] {\n const lifecycle = factLifecycleDiagnostic(db, options.workspaceId);\n if (lifecycle) return boundDoctorDiagnostics([lifecycle]);\n const globalLifecycle = options.workspaceId === undefined\n ? undefined : factLifecycleDiagnostic(db);\n if (globalLifecycle) return boundDoctorDiagnostics([\n ...schemaDriftDiagnostics(db, strict, options.workspaceId),\n ...analyzerVersionDiagnostics(db, strict, options.workspaceId),\n {\n severity: 'warning',\n code: 'workspace_detail_checks_deferred',\n message: 'Selected-workspace lifecycle is valid, but JSON-dependent global detail checks were deferred because another workspace requires reindexing.',\n remediation: 'Run doctor for the affected workspace after force index and link.',\n },\n ]);\n const diagnostics = db.prepare('SELECT severity,code,message,source_file sourceFile,source_line sourceLine FROM diagnostics ORDER BY id').all() as Diagnostic[];\n return boundDoctorDiagnostics([\n ...diagnostics,\n ...packagePendingDiagnostics(db),\n ...healthDiagnostics(db, strict),\n ...remoteTargetWithoutImplementationDiagnostics(db, strict, Boolean(options.detail)),\n ...localServiceDiagnostics(db, strict),\n ...schemaDriftDiagnostics(db, strict, options.workspaceId),\n ...analyzerVersionDiagnostics(db, strict, options.workspaceId),\n ...parserQualityDiagnostics(db, strict, options),\n ]);\n}\n\nfunction healthDiagnostics(db: Db, strict: boolean): Diagnostic[] {\n return db.prepare(\n `SELECT 'info' severity,'entity_only_service' code,'CDS service has no action/function/event operations; this can be valid for entity-only services' message,s.source_file sourceFile,s.source_line sourceLine\n FROM cds_services s LEFT JOIN cds_operations o ON o.service_id=s.id WHERE o.id IS NULL AND ?\n UNION ALL\n SELECT 'warning','extend_service_unresolved_base','Extend service has no indexed local operations; verify base service resolution',s.source_file,s.source_line\n FROM cds_services s LEFT JOIN cds_operations o ON o.service_id=s.id WHERE o.id IS NULL AND s.is_extend=1 AND ?\n UNION ALL\n SELECT 'warning','handler_without_service','Repository has handlers but no CDS services',hc.source_file,hc.source_line\n FROM handler_classes hc JOIN repositories r ON r.id=hc.repo_id\n WHERE r.kind IN ('cap-service','mixed') AND NOT EXISTS (SELECT 1 FROM cds_services s WHERE s.repo_id=hc.repo_id)\n UNION ALL\n SELECT 'warning','search_index_empty','Search index is empty after indexing',NULL,NULL\n WHERE NOT EXISTS (SELECT 1 FROM search_index)\n UNION ALL\n SELECT 'error','foreign_key_violation','SQLite foreign_key_check reported integrity failures',NULL,NULL\n WHERE EXISTS (SELECT 1 FROM pragma_foreign_key_check)\n UNION ALL\n SELECT 'warning','legacy_schema_weaker_foreign_keys','Legacy table lacks fresh-schema foreign-key metadata; rebuild the database or re-run init/index in a new database',NULL,NULL\n WHERE (SELECT COUNT(*) FROM pragma_foreign_key_list('graph_edges'))=0 OR (SELECT COUNT(*) FROM pragma_foreign_key_list('index_runs'))=0 OR (SELECT COUNT(*) FROM pragma_foreign_key_list('diagnostics'))=0\n UNION ALL\n SELECT CASE WHEN ? THEN 'warning' ELSE 'error' END,'local_service_calls_all_unresolved','All local service calls are unresolved; verify local service alias parsing and linking',NULL,NULL\n WHERE EXISTS (SELECT 1 FROM outbound_calls WHERE call_type='local_service_call') AND NOT EXISTS (SELECT 1 FROM graph_edges e JOIN outbound_calls c ON e.from_kind='call' AND c.id=CAST(e.from_id AS INTEGER) WHERE c.call_type='local_service_call' AND e.status='resolved')\n UNION ALL\n SELECT 'error','local_service_accessor_misclassified','Entity accessor calls were indexed as /entities operations',source_file,source_line\n FROM outbound_calls WHERE call_type='local_service_call' AND operation_path_expr='/entities' AND (? OR 1)\n UNION ALL\n SELECT 'warning','outbound_calls_without_source_symbol','Outbound calls lack source symbol ownership: ' || COUNT(*),NULL,NULL\n FROM outbound_calls WHERE source_symbol_id IS NULL AND ? HAVING COUNT(*) >= 1\n UNION ALL\n SELECT 'warning','trace_scope_fell_back_to_file','Trace may fall back to source-file scope for calls without symbols',NULL,NULL\n WHERE EXISTS (SELECT 1 FROM outbound_calls WHERE source_symbol_id IS NULL) AND ?\n UNION ALL\n SELECT 'warning','graph_stale','Graph is stale after repository fact changes; run service-flow link',NULL,NULL\n WHERE EXISTS (SELECT 1 FROM repositories WHERE graph_stale_reason IS NOT NULL)\n UNION ALL\n SELECT 'warning','index_run_abandoned','Index run ' || id || ' started at ' || started_at || ' is still running after the 60 minute abandonment threshold',NULL,NULL\n FROM index_runs WHERE status='running' AND datetime(started_at) < datetime('now','-60 minutes')`,\n ).all(strict, strict, strict, strict, strict, strict) as Diagnostic[];\n}\n\n\nfunction remoteTargetWithoutImplementationDiagnostics(db: Db, strict: boolean, detail: boolean): Diagnostic[] {\n if (!strict) return [];\n const groups = db.prepare(`SELECT s.service_path servicePath,o.operation_path operationPath,o.source_file sourceFile,o.source_line sourceLine,COUNT(*) callSiteCount\n FROM graph_edges remote JOIN cds_operations o ON o.id=CAST(remote.to_id AS INTEGER) JOIN cds_services s ON s.id=o.service_id\n WHERE remote.edge_type='REMOTE_CALL_RESOLVES_TO_OPERATION' AND remote.to_kind='operation'\n AND NOT EXISTS (SELECT 1 FROM graph_edges impl WHERE impl.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND impl.from_kind='operation' AND impl.from_id=remote.to_id)\n GROUP BY s.service_path,o.operation_path,o.source_file,o.source_line\n ORDER BY s.service_path,o.operation_path`).all() as Array<{ servicePath?: string; operationPath?: string; sourceFile?: string | null; sourceLine?: number | null; callSiteCount?: number }>;\n return groups.map((group) => {\n const examples = remoteTargetWithoutImplementationExamples(db, String(group.servicePath ?? ''), String(group.operationPath ?? ''));\n return {\n severity: 'warning',\n code: 'remote_target_without_implementation',\n message: `Remote target operation has no implementation edge: ${String(group.servicePath ?? '')}${String(group.operationPath ?? '')}`,\n sourceFile: group.sourceFile,\n sourceLine: group.sourceLine,\n servicePath: group.servicePath,\n operationPath: group.operationPath,\n callSiteCount: Number(group.callSiteCount ?? 0),\n examples: examples.slice(0, 3),\n expandedExamples: detail ? examples : undefined,\n };\n });\n}\n\nfunction remoteTargetWithoutImplementationExamples(db: Db, servicePath: string, operationPath: string): Diagnostic[] {\n return db.prepare(`SELECT r.name repo,c.source_file sourceFile,c.source_line sourceLine,c.operation_path_expr operationPathExpr\n FROM graph_edges remote JOIN cds_operations o ON o.id=CAST(remote.to_id AS INTEGER) JOIN cds_services s ON s.id=o.service_id\n LEFT JOIN outbound_calls c ON remote.from_kind='call' AND c.id=CAST(remote.from_id AS INTEGER)\n LEFT JOIN repositories r ON r.id=c.repo_id\n WHERE remote.edge_type='REMOTE_CALL_RESOLVES_TO_OPERATION' AND remote.to_kind='operation'\n AND s.service_path=? AND o.operation_path=?\n AND NOT EXISTS (SELECT 1 FROM graph_edges impl WHERE impl.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND impl.from_kind='operation' AND impl.from_id=remote.to_id)\n ORDER BY r.name,c.source_file,c.source_line`).all(servicePath, operationPath) as Diagnostic[];\n}\n\nfunction localServiceDiagnostics(db: Db, strict: boolean): Diagnostic[] {\n const rows = db.prepare(\"SELECT e.status status,e.unresolved_reason reason,e.evidence_json evidenceJson FROM graph_edges e JOIN outbound_calls c ON e.from_kind='call' AND c.id=CAST(e.from_id AS INTEGER) WHERE c.call_type='local_service_call'\").all() as Array<{ status?: string; reason?: string | null; evidenceJson?: string }>;\n const implementationContext = rows.filter((row) => row.status === 'resolved' && String(row.evidenceJson ?? '').includes('implementation_context_caller_ownership')).length;\n const withoutOwnership = rows.filter((row) => row.reason === 'local_service_candidate_without_caller_ownership' || String(row.evidenceJson ?? '').includes('local_service_candidate_without_caller_ownership')).length;\n const unresolved = rows.filter((row) => row.status === 'unresolved').length;\n const outsideScope = rows.filter((row) => row.status === 'unresolved' && candidateCount(row.evidenceJson) > 0).length;\n const out: Diagnostic[] = [];\n if (withoutOwnership > 0) out.push({ severity: 'warning', code: 'local_service_candidate_without_caller_ownership', message: `Local service calls have operation candidates but no caller ownership evidence: ${withoutOwnership}` });\n if (outsideScope > 0) out.push({ severity: 'warning', code: 'local_service_candidates_outside_local_scope', message: `Local service calls found candidates outside same-repository scope: ${outsideScope}` });\n if (strict && unresolved > 0) out.push({ severity: 'warning', code: 'local_service_calls_unresolved', message: `Unresolved local service calls: ${unresolved}` });\n if (strict && implementationContext > 0) out.push({ severity: 'info', code: 'local_service_calls_resolved_by_implementation_context', message: `Local service calls resolved by implementation-context ownership: ${implementationContext}` });\n return out;\n}\n\nfunction parserQualityDiagnostics(db: Db, strict: boolean, options: DoctorOptions): Diagnostic[] {\n if (!strict) return [];\n const symbol = symbolCallQuality(db);\n const dbq = dbQueryQuality(db);\n const outbound = outboundOwnershipQuality(db);\n return [\n identityAliasBindingQuality(db),\n remoteActionNoBindingQuality(db),\n contextualImplementationQuality(db),\n implementationCandidateQuality(db, Boolean(options.detail)),\n classInstanceNoiseQuality(db),\n contextualBindingPropagationQuality(db),\n serviceBindingQuality(db, Boolean(options.detail)),\n decoratorResolutionQuality(db),\n handlerRegistrationPairingQuality(db),\n nestedThisReceiverQuality(db),\n wrapperPathPropagationQuality(db),\n remoteQueryTargetQuality(db),\n remoteEntityOperationCollisionQuality(db),\n remoteEntityDynamicOperationFalsePositiveQuality(db),\n remoteActionTargetQuality(db),\n externalHttpTargetQuality(db),\n odataInvocationResolutionQuality(db),\n ...jsonEvidenceQuality(db),\n eventReceiverQuality(db),\n graphDynamicFlagQuality(db),\n symbol,\n dbq,\n outbound,\n ];\n}\n\nfunction jsonEvidenceQuality(db: Db): Diagnostic[] {\n const symbol = db.prepare(\"SELECT COUNT(*) total, SUM(CASE WHEN json_valid(evidence_json)=0 OR json_type(evidence_json) <> 'object' THEN 1 ELSE 0 END) nonObject FROM symbol_calls\").get() as Record<string, unknown>;\n const outbound = db.prepare(\"SELECT COUNT(*) total, SUM(CASE WHEN evidence_json IS NULL THEN 1 ELSE 0 END) missing, SUM(CASE WHEN evidence_json IS NOT NULL AND json_valid(evidence_json)=0 THEN 1 ELSE 0 END) invalid, SUM(CASE WHEN evidence_json IS NOT NULL AND json_valid(evidence_json)=1 AND json_type(evidence_json) <> 'object' THEN 1 ELSE 0 END) nonObject FROM outbound_calls\").get() as Record<string, unknown>;\n const graph = db.prepare(\"SELECT COUNT(*) total, SUM(CASE WHEN e.evidence_json IS NULL OR json_valid(e.evidence_json)=0 OR json_type(e.evidence_json) <> 'object' THEN 1 ELSE 0 END) nonObject, SUM(CASE WHEN e.evidence_json IS NOT NULL AND json_valid(e.evidence_json)=1 AND json_extract(e.evidence_json,'$.outboundEvidence.parser') IS NOT NULL THEN 1 ELSE 0 END) withOutboundEvidence FROM graph_edges e WHERE e.from_kind='call'\").get() as Record<string, unknown>;\n const outboundExamples = db.prepare(\"SELECT call_type callType,source_file sourceFile,source_line sourceLine FROM outbound_calls WHERE evidence_json IS NULL OR json_valid(evidence_json)=0 OR json_type(evidence_json) <> 'object' ORDER BY source_file,source_line LIMIT 10\").all() as Diagnostic[];\n const graphExamples = db.prepare(\"SELECT c.call_type callType,c.source_file sourceFile,c.source_line sourceLine,e.edge_type edgeType FROM graph_edges e JOIN outbound_calls c ON e.from_kind='call' AND c.id=CAST(e.from_id AS INTEGER) WHERE e.evidence_json IS NULL OR json_valid(e.evidence_json)=0 OR json_type(e.evidence_json) <> 'object' OR json_extract(e.evidence_json,'$.outboundEvidence.parser') IS NULL ORDER BY c.source_file,c.source_line LIMIT 10\").all() as Diagnostic[];\n return [\n { severity: Number(symbol.nonObject ?? 0) > 0 ? 'warning' : 'info', code: 'strict_symbol_call_evidence_quality', message: 'Symbol-call evidence JSON object aggregate', total: Number(symbol.total ?? 0), nonObject: Number(symbol.nonObject ?? 0) },\n { severity: Number(outbound.missing ?? 0) + Number(outbound.invalid ?? 0) + Number(outbound.nonObject ?? 0) > 0 ? 'warning' : 'info', code: 'strict_outbound_evidence_quality', message: 'Outbound parser evidence JSON object aggregate', total: Number(outbound.total ?? 0), missing: Number(outbound.missing ?? 0), invalid: Number(outbound.invalid ?? 0), nonObject: Number(outbound.nonObject ?? 0), examples: outboundExamples },\n { severity: Number(graph.nonObject ?? 0) > 0 || Number(graph.withOutboundEvidence ?? 0) < Number(graph.total ?? 0) ? 'warning' : 'info', code: 'strict_graph_evidence_quality', message: 'Call-derived graph evidence and parser-evidence propagation aggregate', total: Number(graph.total ?? 0), nonObject: Number(graph.nonObject ?? 0), withOutboundEvidence: Number(graph.withOutboundEvidence ?? 0), examples: graphExamples },\n ];\n}\n\nfunction dbQueryQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) total, SUM(CASE WHEN query_entity IS NOT NULL THEN 1 ELSE 0 END) known, SUM(CASE WHEN query_entity IS NULL THEN 1 ELSE 0 END) unknown FROM outbound_calls WHERE call_type='local_db_query'\").get() as Record<string, unknown>;\n const total = Number(row.total ?? 0);\n const unknown = Number(row.unknown ?? 0);\n const ratio = total === 0 ? 0 : Number((unknown / total).toFixed(4));\n return { severity: ratio > 0.25 ? 'warning' : 'info', code: 'strict_db_query_quality', message: 'Local DB query quality aggregate', total, known: Number(row.known ?? 0), unknown, unknownRatio: ratio, unknownRatioThreshold: 0.25 };\n}\n\nfunction outboundOwnershipQuality(db: Db): Diagnostic {\n const row = db.prepare('SELECT COUNT(*) total, SUM(CASE WHEN source_symbol_id IS NULL THEN 1 ELSE 0 END) withoutOwnership FROM outbound_calls').get() as Record<string, unknown>;\n const byType = db.prepare('SELECT call_type callType, COUNT(*) count FROM outbound_calls WHERE source_symbol_id IS NULL GROUP BY call_type ORDER BY count DESC, call_type').all() as Diagnostic[];\n const examples = db.prepare('SELECT call_type callType,source_file sourceFile,source_line sourceLine,unresolved_reason unresolvedReason FROM outbound_calls WHERE source_symbol_id IS NULL ORDER BY source_file,source_line LIMIT 10').all() as Diagnostic[];\n const total = Number(row.total ?? 0);\n const without = Number(row.withoutOwnership ?? 0);\n const ratio = total === 0 ? 0 : Number((without / total).toFixed(4));\n return { severity: ratio > 0.01 ? 'warning' : 'info', code: 'strict_outbound_source_ownership_quality', message: 'Outbound call source-symbol ownership aggregate', total, withoutOwnership: without, withoutOwnershipRatio: ratio, withoutOwnershipRatioThreshold: 0.01, ownerlessByType: byType, ownerlessExamples: examples };\n}\n\nfunction eventReceiverQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT SUM(CASE WHEN call_type IN ('async_emit','async_subscribe') THEN 1 ELSE 0 END) eventTotal, SUM(CASE WHEN call_type IN ('async_emit','async_subscribe') AND (json_extract(evidence_json,'$.receiverClassification') IS NULL OR json_extract(evidence_json,'$.receiverClassification') <> 'cap_evidence') THEN 1 ELSE 0 END) questionable FROM outbound_calls\").get() as Record<string, unknown>;\n return { severity: Number(row.questionable ?? 0) > 0 ? 'warning' : 'info', code: 'strict_event_receiver_classification_quality', message: 'CAP event receiver classification aggregate', eventTotal: Number(row.eventTotal ?? 0), questionable: Number(row.questionable ?? 0) };\n}\n\nfunction graphDynamicFlagQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) count FROM graph_edges WHERE status='terminal' AND is_dynamic=1\").get() as Record<string, unknown>;\n return { severity: Number(row.count ?? 0) > 0 ? 'warning' : 'info', code: 'strict_graph_dynamic_flag_consistency', message: 'Graph dynamic flag consistency aggregate', dynamicTerminalEdges: Number(row.count ?? 0) };\n}\n\nfunction implementationCandidateQuality(db: Db, detail: boolean): Diagnostic {\n const categories = [...implementationEdgeCategories(db, detail), missingParameterMetadataCategory(db, detail), dynamicWrapperCategory(db, detail)].filter((item) => item.count > 0);\n const total = categories.reduce((sum, item) => sum + item.count, 0);\n return { severity: total > 0 ? 'warning' : 'info', code: 'strict_implementation_candidate_quality', message: 'Implementation candidate ambiguity and rejection aggregate', total, summary: implementationSummary(categories), categories };\n}\n\nfunction implementationEdgeCategories(db: Db, detail: boolean): Array<Diagnostic & { count: number }> {\n const rows = db.prepare(`SELECT e.status,e.unresolved_reason unresolvedReason,e.evidence_json evidenceJson,o.operation_name operationName,base.operation_name baseOperation,s.service_path servicePath\n FROM graph_edges e JOIN cds_operations o ON o.id=CAST(e.from_id AS INTEGER)\n JOIN cds_services s ON s.id=o.service_id LEFT JOIN cds_operations base ON base.id=o.base_operation_id\n WHERE e.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND e.status IN ('ambiguous','unresolved') ORDER BY s.service_path,o.operation_name,e.id`).all() as Diagnostic[];\n const grouped = new Map<string, Diagnostic & { count: number; servicePaths: string[]; examples: Diagnostic[] }>();\n for (const row of rows) addImplementationCategory(grouped, row);\n return [...grouped.values()].map(({ servicePaths, ...item }) => ({\n ...item,\n servicePathPattern: pathPattern(servicePaths),\n suggestedAction: categoryAction(String(item.category)),\n suggestedHints: suggestedHints(item.examples),\n examples: item.examples.slice(0, 3),\n expandedExamples: detail ? item.examples : undefined,\n }));\n}\n\nfunction addImplementationCategory(grouped: Map<string, Diagnostic & { count: number; servicePaths: string[]; examples: Diagnostic[] }>, row: Diagnostic): void {\n const evidence = parseObject(row.evidenceJson);\n const category = implementationCategory(row, evidence);\n const family = candidateFamily(evidence);\n const reason = category === 'duplicate_package_name_candidates' ? 'duplicate_package_name_candidates' : String(row.unresolvedReason ?? category);\n const baseOperation = String(row.baseOperation ?? row.operationName ?? evidence.operationName ?? 'unknown');\n const key = [category, baseOperation, reason, family].join('\\0');\n const current = grouped.get(key) ?? { category, baseOperation, reason, candidateFamily: family, count: 0, servicePaths: [], examples: [] };\n const hintSuggestions = implementationSuggestions(evidence);\n const candidates = asRecords(evidence.candidates);\n const candidateCount = Math.max(\n numericValue(evidence.candidateCount),\n candidates.length,\n );\n current.count += 1;\n current.servicePaths.push(String(row.servicePath ?? evidence.servicePath ?? ''));\n current.examples.push({\n servicePath: row.servicePath,\n operation: row.operationName,\n status: row.status,\n reason: row.unresolvedReason,\n candidateCount,\n shownCandidateCount: Math.min(\n candidateCount,\n numericValue(evidence.shownCandidateCount) || candidates.length,\n ),\n omittedCandidateCount: Math.max(\n 0,\n candidateCount - (numericValue(evidence.shownCandidateCount) || candidates.length),\n ),\n candidateEvidence: candidates.slice(0, 3),\n implementationHintSuggestions: hintSuggestions,\n });\n grouped.set(key, current);\n}\n\nfunction implementationSuggestions(evidence: Diagnostic): Diagnostic[] | undefined {\n const persisted = asRecords(evidence.implementationHintSuggestions);\n const suggestions = persisted.length ? persisted : implementationHintSuggestions(evidence);\n return suggestions.length ? suggestions : undefined;\n}\n\nfunction suggestedHints(examples: Diagnostic[]): string[] | undefined {\n const hints = examples.flatMap((example) =>\n asRecords(example.implementationHintSuggestions)\n .flatMap((suggestion) => typeof suggestion.cli === 'string' ? [String(suggestion.cli)] : []));\n const unique = [...new Set(hints)].slice(0, 3);\n return unique.length ? unique : undefined;\n}\n\nfunction missingParameterMetadataCategory(db: Db, detail = false): Diagnostic & { count: number } {\n const examples = db.prepare(`SELECT sc.source_file sourceFile,sc.source_line sourceLine,sc.callee_expression calleeExpression\n FROM symbol_calls sc JOIN symbols s ON s.id=sc.callee_symbol_id\n WHERE sc.status='resolved' AND json_extract(sc.evidence_json,'$.callArguments[0].kind') IN ('identifier','object_literal')\n AND (s.evidence_json IS NULL OR json_extract(s.evidence_json,'$.parameterBindings') IS NULL)\n ORDER BY sc.source_file,sc.source_line`).all() as Diagnostic[];\n const row = db.prepare(`SELECT COUNT(*) count FROM symbol_calls sc JOIN symbols s ON s.id=sc.callee_symbol_id\n WHERE sc.status='resolved' AND json_extract(sc.evidence_json,'$.callArguments[0].kind') IN ('identifier','object_literal')\n AND (s.evidence_json IS NULL OR json_extract(s.evidence_json,'$.parameterBindings') IS NULL)`).get() as { count?: number };\n return { category: 'missing_parameter_metadata', reason: 'callee symbol is missing parameter binding metadata', candidateFamily: 'symbol_parameter_metadata', count: Number(row.count ?? 0), suggestedAction: categoryAction('missing_parameter_metadata'), examples: examples.slice(0, 3), expandedExamples: detail ? examples : undefined };\n}\n\nfunction dynamicWrapperCategory(db: Db, detail: boolean): Diagnostic & { count: number } {\n const rows = db.prepare(`SELECT source_file sourceFile,source_line sourceLine,\n json_extract(evidence_json,'$.receiver') receiverName,\n COALESCE(json_extract(evidence_json,'$.missingPathIdentifier'),json_extract(evidence_json,'$.operationPathExpression')) pathIdentifier\n FROM outbound_calls WHERE call_type='remote_action' AND unresolved_reason='dynamic_operation_path_identifier'\n ORDER BY source_file,source_line`).all() as Diagnostic[];\n return { category: 'dynamic_wrapper_paths', reason: 'wrapper path cannot be proven statically', candidateFamily: 'wrapper_path', count: rows.length, suggestedAction: categoryAction('dynamic_wrapper_paths'), examples: rows.slice(0, 3), expandedExamples: detail ? rows : undefined };\n}\n\nfunction implementationSummary(categories: Array<Diagnostic & { count: number }>): Diagnostic[] {\n const grouped = new Map<string, Diagnostic & { count: number }>();\n for (const category of categories) {\n const key = [category.category, category.candidateFamily, category.reason].join('\\0');\n const current = grouped.get(key) ?? { category: category.category, candidateFamily: category.candidateFamily, reason: category.reason, severity: 'warning', suggestedAction: category.suggestedAction, count: 0 };\n current.count += category.count;\n grouped.set(key, current);\n }\n return [...grouped.values()].sort((left, right) => String(left.category).localeCompare(String(right.category)) || String(left.candidateFamily).localeCompare(String(right.candidateFamily)));\n}\n\nfunction categoryAction(category: string): string {\n if (category === 'duplicate_package_name_candidates') return 'Use scoped --implementation-hint fields to select one repository for each ambiguous hop.';\n if (category === 'missing_strong_ownership_evidence') return 'Add an explicit package dependency, local service-path ownership, or registration ownership evidence.';\n if (category === 'missing_parameter_metadata') return 'Export a statically analyzable helper with named or destructured parameters.';\n if (category === 'dynamic_wrapper_paths') return 'Pass a literal path or provide the reported runtime identifier with --var key=value.';\n return 'Inspect the capped examples and add stronger implementation ownership evidence.';\n}\n\nfunction implementationCategory(row: Diagnostic, evidence: Diagnostic): string {\n const reasons = JSON.stringify([evidence.ambiguityReasons, evidence.candidateFamilies, evidence.candidates, row.unresolvedReason]);\n if (reasons.includes('duplicate_package_name_candidates')) return 'duplicate_package_name_candidates';\n if (reasons.includes('missing direct ownership')) return 'missing_strong_ownership_evidence';\n return String(row.status) === 'ambiguous' ? 'ambiguous_implementation_candidates' : 'rejected_implementation_candidates';\n}\n\nfunction candidateFamily(evidence: Diagnostic): string {\n const families = asRecords(evidence.candidateFamilies);\n const duplicate = families.find((row) => typeof row.packageName === 'string');\n if (duplicate?.packageName) return String(duplicate.packageName);\n const candidates = asRecords(evidence.candidates);\n const first = candidates.find((row) => parseObject(row.handlerPackage).packageName);\n return String(parseObject(first?.handlerPackage).packageName ?? 'unknown');\n}\n\nfunction pathPattern(paths: string[]): string {\n const values = [...new Set(paths.filter(Boolean))].sort();\n if (values.length <= 1) return values[0] ?? '';\n const prefix = commonPrefix(values);\n const suffix = commonSuffix(values.map((value) => value.slice(prefix.length)));\n return `${prefix}*${suffix}`;\n}\n\nfunction commonPrefix(values: string[]): string {\n let prefix = values[0] ?? '';\n for (const value of values.slice(1)) while (!value.startsWith(prefix)) prefix = prefix.slice(0, -1);\n return prefix;\n}\n\nfunction commonSuffix(values: string[]): string {\n let suffix = values[0] ?? '';\n for (const value of values.slice(1)) while (!value.endsWith(suffix)) suffix = suffix.slice(1);\n return suffix;\n}\n\nfunction contextualImplementationQuality(db: Db): Diagnostic {\n const rows = db.prepare(\"SELECT status,COALESCE(unresolved_reason,status) reason,COUNT(*) count FROM graph_edges WHERE edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND status IN ('ambiguous','unresolved') GROUP BY status,reason ORDER BY status,count DESC,reason\").all() as Diagnostic[];\n const total = rows.reduce((sum, row) => sum + Number(row.count ?? 0), 0);\n return { severity: total > 0 ? 'warning' : 'info', code: 'strict_contextual_implementation_quality', message: 'Implementation hops stopped by ambiguous or unresolved implementation edges', total, breakdown: rows };\n}\n\nfunction classInstanceNoiseQuality(db: Db): Diagnostic {\n const builtIns = ['Set', 'Map', 'WeakSet', 'WeakMap', 'Date', 'RegExp', 'URL', 'URLSearchParams', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'AggregateError', 'ArrayBuffer', 'SharedArrayBuffer', 'DataView', 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array', 'Promise', 'AbortController'];\n const placeholders = builtIns.map(() => '?').join(',');\n const aggregate = db.prepare(`SELECT COUNT(*) total,\n SUM(CASE WHEN status='unresolved' THEN 1 ELSE 0 END) unresolved,\n SUM(CASE WHEN status='unresolved' AND json_extract(evidence_json,'$.className') IN (${placeholders}) THEN 1 ELSE 0 END) unresolvedBuiltIn\n FROM symbol_calls WHERE json_extract(evidence_json,'$.relation')='class_instance_method'`).get(...builtIns) as Diagnostic;\n const byConstructor = db.prepare(`SELECT json_extract(evidence_json,'$.className') constructorName,COUNT(*) unresolvedCount\n FROM symbol_calls WHERE status='unresolved' AND json_extract(evidence_json,'$.relation')='class_instance_method'\n GROUP BY constructorName ORDER BY unresolvedCount DESC,constructorName LIMIT 10`).all() as Diagnostic[];\n return { severity: Number(aggregate.unresolvedBuiltIn ?? 0) > 0 ? 'warning' : 'info', code: 'strict_class_instance_noise_quality', message: 'Class-instance symbol-call aggregate with built-in constructor guard', totalClassInstanceCalls: Number(aggregate.total ?? 0), unresolvedClassInstanceCalls: Number(aggregate.unresolved ?? 0), unresolvedBuiltInClassInstanceCalls: Number(aggregate.unresolvedBuiltIn ?? 0), unresolvedByConstructor: byConstructor };\n}\n\nfunction contextualBindingPropagationQuality(db: Db): Diagnostic {\n const missing = missingParameterMetadataCategory(db);\n const opportunities = db.prepare(\"SELECT c.source_file sourceFile,c.source_line sourceLine,json_extract(c.evidence_json,'$.receiver') receiverName,c.operation_path_expr operationPath FROM outbound_calls c WHERE c.call_type='remote_action' AND json_extract(c.evidence_json,'$.receiver') IS NOT NULL AND c.service_binding_id IS NULL ORDER BY c.source_file,c.source_line LIMIT 8\").all() as Diagnostic[];\n return { severity: missing.count + opportunities.length > 0 ? 'warning' : 'info', code: 'strict_contextual_binding_propagation_quality', message: 'Contextual service-client propagation opportunities for trace-time helper resolution', calleeSymbolsMissingParameterMetadata: missing.count, traceTimeContextualOpportunities: opportunities.length, examples: opportunities };\n}\n\nfunction serviceBindingQuality(db: Db, detail: boolean): Diagnostic {\n const rows = db.prepare(`\n SELECT c.source_file sourceFile,c.source_line sourceLine,\n c.unresolved_reason unresolvedReason,c.evidence_json evidenceJson,\n s.evidence_json symbolEvidenceJson\n FROM outbound_calls c\n LEFT JOIN symbols s ON s.id=c.source_symbol_id\n WHERE c.call_type='remote_action'\n AND c.operation_path_expr IS NOT NULL\n AND c.service_binding_id IS NULL\n ORDER BY c.source_file,c.source_line\n `).all() as Diagnostic[];\n const groups = new Map<string, Diagnostic[]>();\n for (const row of rows) {\n const category = bindingCategory(row);\n groups.set(category, [...(groups.get(category) ?? []), bindingExample(row)]);\n }\n const categories = [...groups.entries()].map(([category, examples]) => ({\n category,\n count: examples.length,\n severity: 'warning',\n suggestedAction: bindingCategoryAction(category),\n examples: examples.slice(0, 3),\n expandedExamples: detail ? examples : undefined,\n }));\n return {\n severity: rows.length > 0 ? 'warning' : 'info',\n code: 'strict_service_binding_quality',\n message: 'Remote service-client binding quality aggregate',\n total: rows.length,\n categories,\n };\n}\n\nfunction bindingCategory(row: Diagnostic): string {\n const evidence = parseObject(row.evidenceJson);\n const resolution = parseObject(evidence.serviceBindingResolution);\n const reference = parseObject(evidence.serviceBindingReference);\n if (resolution.status === 'rejected_future_binding') return 'direct_binding_missing';\n if (reference.reason === 'binding_declared_after_call')\n return 'direct_binding_missing';\n if (resolution.status === 'ambiguous' || reference.status === 'ambiguous'\n || reference.reason === 'unsupported_reaching_assignment')\n return 'ambiguous_binding_candidates';\n const receiver = evidence.receiver;\n const symbolEvidence = parseObject(row.symbolEvidenceJson);\n if (symbolHasReceiverParameter(symbolEvidence, receiver))\n return 'contextual_binding_recoverable';\n if (!Array.isArray(symbolEvidence.parameterBindings))\n return 'missing_symbol_parameter_metadata';\n return 'unrecoverable_binding';\n}\n\nfunction symbolHasReceiverParameter(evidence: Diagnostic, receiver: unknown): boolean {\n if (typeof receiver !== 'string' || !Array.isArray(evidence.parameterBindings))\n return false;\n return asRecords(evidence.parameterBindings).some((binding) => {\n if (binding.kind === 'identifier') return binding.name === receiver;\n if (binding.kind === 'object_pattern')\n return asRecords(binding.properties).some((property) => property.local === receiver);\n return asRecords(binding.elements).some((element) => element.local === receiver);\n });\n}\n\nfunction bindingExample(row: Diagnostic): Diagnostic {\n const evidence = parseObject(row.evidenceJson);\n return {\n sourceFile: row.sourceFile,\n sourceLine: row.sourceLine,\n receiver: evidence.receiver,\n unresolvedReason: row.unresolvedReason,\n bindingResolution: evidence.serviceBindingResolution,\n bindingReference: evidence.serviceBindingReference,\n };\n}\n\nfunction bindingCategoryAction(category: string): string {\n if (category === 'direct_binding_missing')\n return 'Move the binding before the call or bind the call to an earlier immutable client.';\n if (category === 'contextual_binding_recoverable')\n return 'Trace from the caller so parameter binding evidence can be applied.';\n if (category === 'ambiguous_binding_candidates')\n return 'Split mutable client alternatives or add a statically unique client assignment.';\n if (category === 'missing_symbol_parameter_metadata')\n return 'Use named or destructured parameters on an indexed helper symbol.';\n return 'Add a direct CAP client binding or statically provable helper-return binding.';\n}\n\nfunction decoratorResolutionQuality(db: Db): Diagnostic {\n const aggregate = db.prepare(`SELECT\n SUM(CASE WHEN json_extract(decorator_resolution_json,'$.resolutionKind')\n IN ('const_identifier','enum_member','const_object_property','generated_constant_name') THEN 1 ELSE 0 END) resolvedFromConstants,\n SUM(CASE WHEN json_extract(decorator_resolution_json,'$.resolutionKind')\n ='unresolved' THEN 1 ELSE 0 END) unresolvedExpressions\n FROM handler_methods`).get() as Diagnostic;\n const unresolved = Number(aggregate.unresolvedExpressions ?? 0);\n const examples = db.prepare(`SELECT hm.method_name methodName,\n hm.decorator_raw_expression rawExpression,\n json_extract(hm.decorator_resolution_json,'$.unresolvedReason') unresolvedReason,\n hm.source_file sourceFile,hm.source_line sourceLine\n FROM handler_methods hm\n WHERE json_extract(hm.decorator_resolution_json,'$.resolutionKind')='unresolved'\n ORDER BY hm.source_file,hm.source_line LIMIT 5`).all() as Diagnostic[];\n return {\n severity: unresolved > 0 ? 'warning' : 'info',\n code: 'strict_decorator_resolution_quality',\n message: 'Handler decorator string-resolution aggregate',\n resolvedFromConstants: Number(aggregate.resolvedFromConstants ?? 0),\n unresolvedExpressions: unresolved,\n unresolvedExamples: examples,\n };\n}\n\nfunction handlerRegistrationPairingQuality(db: Db): Diagnostic {\n const mismatch = db.prepare(`SELECT COUNT(*) count\n FROM handler_registrations hr\n JOIN handler_classes hc ON hc.id=hr.handler_class_id\n WHERE hr.handler_class_id IS NOT NULL\n AND (hc.repo_id<>hr.repo_id OR hc.class_name<>hr.class_name)`).get() as Diagnostic;\n const prevented = db.prepare(`SELECT COUNT(*) count\n FROM handler_registrations hr\n JOIN handler_classes exactClass ON exactClass.id=hr.handler_class_id\n JOIN handler_classes otherClass ON otherClass.class_name=hr.class_name\n AND otherClass.repo_id<>hr.repo_id\n WHERE hr.handler_class_id IS NOT NULL AND hr.import_source IS NOT NULL`).get() as Diagnostic;\n const mismatched = Number(mismatch.count ?? 0);\n return {\n severity: mismatched > 0 ? 'error' : 'info',\n code: 'strict_handler_registration_pairing_quality',\n message: 'Handler registration and class ownership aggregate',\n mismatchedExactRegistrations: mismatched,\n preventedSyntheticCrossRepositoryPairs: Number(prevented.count ?? 0),\n };\n}\n\nfunction wrapperPathPropagationQuality(db: Db): Diagnostic {\n const examples = db.prepare(\"SELECT source_file sourceFile,source_line sourceLine,json_extract(evidence_json,'$.receiver') receiverName,json_extract(evidence_json,'$.operationPathExpression') pathIdentifier FROM outbound_calls WHERE call_type='remote_action' AND unresolved_reason='dynamic_operation_path_identifier' ORDER BY source_file,source_line LIMIT 5\").all() as Diagnostic[];\n return { severity: examples.length > 0 ? 'warning' : 'info', code: 'strict_wrapper_path_propagation_quality', message: 'Dynamic path sends where send({ path }) used a path identifier', dynamicPathIdentifierCalls: examples.length, examples };\n}\n\nfunction nestedThisReceiverQuality(db: Db): Diagnostic {\n const aggregate = db.prepare(`SELECT COUNT(*) total,\n SUM(CASE WHEN json_extract(evidence_json,'$.relation')='indexed_this_method' THEN 1 ELSE 0 END) resolvedToCurrentClass,\n SUM(CASE WHEN json_extract(evidence_json,'$.relation')='class_instance_method' THEN 1 ELSE 0 END) withExplicitHelperInstanceEvidence\n FROM symbol_calls WHERE callee_expression LIKE 'this.%.%'`).get() as Diagnostic;\n const examples = db.prepare(`SELECT source_file sourceFile,source_line sourceLine,callee_expression calleeExpression,json_extract(evidence_json,'$.relation') relation,json_extract(evidence_json,'$.targetName') targetName\n FROM symbol_calls WHERE callee_expression LIKE 'this.%.%' AND json_extract(evidence_json,'$.relation')='indexed_this_method'\n ORDER BY source_file,source_line LIMIT 8`).all() as Diagnostic[];\n return { severity: Number(aggregate.resolvedToCurrentClass ?? 0) > 0 ? 'warning' : 'info', code: 'strict_nested_this_receiver_quality', message: 'Nested this receiver symbol-call aggregate', nestedThisReceiverCallsConsidered: Number(aggregate.total ?? 0), nestedThisResolvedToCurrentClass: Number(aggregate.resolvedToCurrentClass ?? 0), nestedThisWithExplicitHelperInstanceEvidence: Number(aggregate.withExplicitHelperInstanceEvidence ?? 0), warningExamples: examples };\n}\n\nfunction remoteQueryTargetQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) total,SUM(CASE WHEN e.edge_type='HANDLER_RUNS_REMOTE_QUERY' AND e.status='terminal' THEN 1 ELSE 0 END) terminal,SUM(CASE WHEN e.edge_type='HANDLER_RUNS_REMOTE_QUERY' AND e.to_id GLOB '[0-9]*' THEN 1 ELSE 0 END) numericTargets,SUM(CASE WHEN e.edge_type='UNRESOLVED_EDGE' OR e.status='unresolved' THEN 1 ELSE 0 END) unresolved FROM outbound_calls c LEFT JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT) WHERE c.call_type='remote_query'\").get() as Diagnostic;\n const numeric = Number(row.numericTargets ?? 0);\n const unresolved = Number(row.unresolved ?? 0);\n return { severity: numeric + unresolved > 0 ? 'warning' : 'info', code: 'strict_remote_query_target_quality', message: 'Remote query terminal target quality aggregate', totalRemoteQueryCalls: Number(row.total ?? 0), terminalRemoteQueryEdges: Number(row.terminal ?? 0), numericTargetCount: numeric, unresolvedRemoteQueryCount: unresolved };\n}\n\nfunction remoteEntityOperationCollisionQuality(db: Db): Diagnostic {\n const rows = db.prepare(`SELECT c.id callId,c.source_file sourceFile,c.source_line sourceLine,c.method method,c.operation_path_expr rawPath,c.query_entity entitySegment,e.to_id selectedTerminalEntityTarget,e.evidence_json evidenceJson\n FROM outbound_calls c JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT)\n WHERE c.call_type LIKE 'remote_entity_%' AND e.edge_type='HANDLER_ACCESSES_REMOTE_ENTITY' AND e.status='terminal'\n ORDER BY c.source_file,c.source_line LIMIT 100`).all() as Diagnostic[];\n const examples = rows.map((row) => operationCollisionExample(db, row)).filter((row): row is Diagnostic => Boolean(row)).slice(0, 10);\n return { severity: examples.length > 0 ? 'warning' : 'info', code: 'strict_remote_entity_operation_collision_quality', message: 'Terminal remote entity edges that look like indexed operation invocations', collisionCount: examples.length, examples };\n}\n\nfunction operationCollisionExample(db: Db, row: Diagnostic): Diagnostic | undefined {\n const rawPath = String(row.rawPath ?? '');\n const normalized = normalizeODataOperationInvocationPath(rawPath);\n const candidatePath = normalized?.wasInvocation ? normalized.normalizedOperationPath : rawPath;\n const name = candidatePath.replace(/^\\//, '');\n const simple = name.split('.').at(-1) ?? name;\n const candidates = db.prepare('SELECT COUNT(*) count FROM cds_operations WHERE operation_path IN (?,?) OR operation_name IN (?,?)').get(candidatePath, `/${simple}`, name, simple) as { count?: number };\n const candidateCount = Number(candidates.count ?? 0);\n if (!normalized?.wasInvocation && candidateCount === 0) return undefined;\n const evidence = parseObject(row.evidenceJson);\n return { callId: row.callId, sourceFile: row.sourceFile, sourceLine: row.sourceLine, method: row.method, rawPath, normalizedOperationPath: normalized?.wasInvocation ? normalized.normalizedOperationPath : candidatePath, entitySegment: row.entitySegment, operationCandidateCount: candidateCount, selectedTerminalEntityTarget: row.selectedTerminalEntityTarget, classifierReason: parseObject(evidence.odataPathIntent).reason };\n}\n\nfunction remoteEntityDynamicOperationFalsePositiveQuality(db: Db): Diagnostic {\n const rows = db.prepare(`SELECT c.source_file sourceFile,c.source_line sourceLine,c.method method,c.operation_path_expr rawPath,e.id graphEdgeId,e.unresolved_reason unresolvedReason,e.evidence_json evidenceJson\n FROM outbound_calls c JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT)\n WHERE c.call_type LIKE 'remote_entity_%' AND e.status IN ('dynamic','unresolved') AND e.to_kind='operation_candidate'\n ORDER BY c.source_file,c.source_line LIMIT 100`).all() as Diagnostic[];\n const examples = rows.filter(isRemoteEntityFalsePositive).map((row) => falsePositiveExample(row)).slice(0, 10);\n return { severity: examples.length > 0 ? 'warning' : 'info', code: 'strict_remote_entity_dynamic_operation_false_positive_quality', message: 'Parser-classified entity paths linked as dynamic operation candidates without indexed operation evidence', falsePositiveCount: examples.length, examples };\n}\n\nfunction isRemoteEntityFalsePositive(row: Diagnostic): boolean {\n const intent = classifyODataPathIntent(String(row.rawPath ?? ''), String(row.method ?? 'GET'));\n const entityIntent = ['entity_key_read', 'entity_navigation_query', 'entity_media'].includes(intent.kind) || (intent.kind === 'entity_mutation' && (intent.hasEntityKeyPredicate || intent.hasNavigationSuffix));\n const evidence = parseObject(row.evidenceJson);\n const candidateCount = Number(evidence.indexedOperationCandidateCount ?? evidence.candidateCount ?? 0);\n const reason = String(row.unresolvedReason ?? '');\n return entityIntent && candidateCount === 0 && (intent.keyPredicatePlaceholderKeys.length > 0 || reason.includes('runtime variable') || reason.includes('placeholder'));\n}\n\nfunction falsePositiveExample(row: Diagnostic): Diagnostic {\n const intent = classifyODataPathIntent(String(row.rawPath ?? ''), String(row.method ?? 'GET'));\n return { sourceFile: row.sourceFile, sourceLine: row.sourceLine, rawPath: row.rawPath, method: row.method, pathIntent: intent.kind, keyPlaceholderKeys: intent.keyPredicatePlaceholderKeys, navigationOrMediaSuffix: intent.navigationSuffix ?? intent.mediaOrPropertySuffix, graphEdgeId: row.graphEdgeId, operationCandidateCount: 0, recommendedRemediation: 'Reindex and relink with service-flow 0.1.35 or newer so entity key placeholders remain entity-addressing evidence.' };\n}\n\nfunction remoteActionTargetQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) total,SUM(CASE WHEN e.status='unresolved' THEN 1 ELSE 0 END) unresolved,SUM(CASE WHEN e.status='unresolved' AND e.to_id GLOB '[0-9]*' THEN 1 ELSE 0 END) numericTargets,SUM(CASE WHEN e.status='unresolved' AND (e.to_id='Remote action: unknown path' OR e.to_id='Remote action: dynamic path') THEN 1 ELSE 0 END) semanticTargets FROM outbound_calls c LEFT JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT) WHERE c.call_type='remote_action'\").get() as Diagnostic;\n const numeric = Number(row.numericTargets ?? 0);\n return { severity: numeric > 0 ? 'warning' : 'info', code: 'strict_remote_action_target_quality', message: 'Remote action unresolved target quality aggregate', totalRemoteActionCalls: Number(row.total ?? 0), unresolvedRemoteActionCalls: Number(row.unresolved ?? 0), numericUnresolvedTargetCount: numeric, semanticUnknownOrDynamicTargetCount: Number(row.semanticTargets ?? 0) };\n}\n\nfunction externalHttpTargetQuality(db: Db): Diagnostic {\n const row = db.prepare(\"SELECT COUNT(*) total,SUM(CASE WHEN e.to_id GLOB '[0-9]*' THEN 1 ELSE 0 END) numericTargets,SUM(CASE WHEN e.evidence_json IS NULL OR json_valid(e.evidence_json)=0 OR json_extract(e.evidence_json,'$.externalTarget.kind') IS NULL THEN 1 ELSE 0 END) invalidEvidence FROM outbound_calls c LEFT JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT) WHERE c.call_type='external_http'\").get() as Diagnostic;\n const bad = Number(row.numericTargets ?? 0) + Number(row.invalidEvidence ?? 0);\n return { severity: bad > 0 ? 'warning' : 'info', code: 'strict_external_http_target_quality', message: 'External HTTP semantic target aggregate', totalExternalHttpCalls: Number(row.total ?? 0), numericTargetCount: Number(row.numericTargets ?? 0), invalidOrMissingExternalTargetEvidence: Number(row.invalidEvidence ?? 0) };\n}\n\nfunction odataInvocationResolutionQuality(db: Db): Diagnostic {\n const rows = db.prepare(`SELECT c.operation_path_expr operationPathExpr,\n c.source_file sourceFile,c.source_line sourceLine,e.id graphEdgeId,\n e.status status,e.evidence_json evidenceJson\n FROM outbound_calls c JOIN graph_edges e\n ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT)\n WHERE c.call_type='remote_action' AND c.operation_path_expr LIKE '%(%'\n ORDER BY c.source_file,c.source_line`).all() as Array<{\n operationPathExpr?: string;\n sourceFile?: string;\n sourceLine?: number;\n graphEdgeId?: number;\n status?: string;\n evidenceJson?: string;\n }>;\n const unresolved = rows.filter((row) => row.status === 'unresolved' && normalizeODataOperationInvocationPath(row.operationPathExpr)?.wasInvocation).length;\n const ambiguous = rows.filter((row) => row.status === 'ambiguous' && normalizeODataOperationInvocationPath(row.operationPathExpr)?.wasInvocation).length;\n const examples = rows\n .filter((row) => row.status === 'ambiguous' || row.status === 'unresolved')\n .map(odataInvocationExample)\n .slice(0, 5);\n return { severity: unresolved + ambiguous > 0 ? 'warning' : 'info', code: 'strict_odata_invocation_resolution_quality', message: 'OData invocation-path resolution quality aggregate', totalInvocationRemoteActions: rows.length, resolvedInvocationCalls: rows.filter((row) => row.status === 'resolved').length, dynamicInvocationCalls: rows.filter((row) => row.status === 'dynamic').length, ambiguousInvocationCalls: rows.filter((row) => row.status === 'ambiguous').length, unresolvedInvocationCalls: rows.filter((row) => row.status === 'unresolved').length, ambiguousNormalizedCalls: ambiguous, unresolvedNormalizedCallsWithIndexedCandidates: unresolved, examples };\n}\n\nfunction odataInvocationExample(row: {\n operationPathExpr?: string;\n sourceFile?: string;\n sourceLine?: number;\n graphEdgeId?: number;\n status?: string;\n evidenceJson?: string;\n}): Diagnostic {\n const evidence = parseObject(row.evidenceJson);\n const normalized = normalizeODataOperationInvocationPath(row.operationPathExpr);\n return {\n sourceFile: row.sourceFile,\n sourceLine: row.sourceLine,\n graphEdgeId: row.graphEdgeId,\n status: row.status,\n rawPath: row.operationPathExpr,\n normalizedOperationPath: normalized?.wasInvocation\n ? normalized.normalizedOperationPath\n : undefined,\n indexedOperationCandidateCount: evidence.indexedOperationCandidateCount,\n candidateScores: evidence.candidateScores,\n entityOperationPrecedence: evidence.entityOperationPrecedence,\n resolutionReasons: evidence.resolutionReasons,\n };\n}\n\nfunction identityAliasBindingQuality(db: Db): Diagnostic {\n const examples = db.prepare(\"SELECT c.source_file sourceFile,c.source_line sourceLine FROM outbound_calls c WHERE c.call_type='remote_action' AND c.service_binding_id IS NULL AND json_extract(c.evidence_json,'$.receiver') IS NOT NULL ORDER BY c.source_file,c.source_line LIMIT 5\").all() as Diagnostic[];\n return { severity: examples.length > 0 ? 'warning' : 'info', code: 'strict_identity_alias_binding_quality', message: 'Remote sends that look like missed same-file identity aliases', missedAliasBindingCalls: examples.length, examples };\n}\n\nfunction remoteActionNoBindingQuality(db: Db): Diagnostic {\n const rows = db.prepare(\"SELECT COALESCE(e.status,'missing_edge') status,COUNT(*) count FROM outbound_calls c LEFT JOIN graph_edges e ON e.from_kind='call' AND e.from_id=CAST(c.id AS TEXT) WHERE c.call_type='remote_action' AND c.operation_path_expr IS NOT NULL AND c.service_binding_id IS NULL GROUP BY status ORDER BY count DESC,status\").all() as Diagnostic[];\n const total = rows.reduce((sum, row) => sum + Number(row.count ?? 0), 0);\n return { severity: total > 0 ? 'warning' : 'info', code: 'strict_remote_action_no_binding_quality', message: 'Remote actions with operation paths but no service binding id', total, breakdown: rows };\n}\n\nfunction candidateCount(value: unknown): number {\n return Number(parseObject(value).candidateCount ?? 0);\n}\n\nfunction numericValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction parseObject(value: unknown): Diagnostic {\n if (value && typeof value === 'object' && !Array.isArray(value)) return value as Diagnostic;\n try {\n const parsed = JSON.parse(String(value ?? '{}')) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Diagnostic : {};\n } catch {\n return {};\n }\n}\n\nfunction asRecords(value: unknown): Diagnostic[] {\n return Array.isArray(value) ? value.filter((item): item is Diagnostic => Boolean(item && typeof item === 'object' && !Array.isArray(item))) : [];\n}\n","import type { TraceResult } from '../types.js';\n\nfunction location(evidence: Record<string, unknown>): string {\n const selected = isRecord(evidence.selectedHandler)\n ? evidence.selectedHandler : undefined;\n const selectedFile = selected?.sourceFile;\n const selectedLine = selected?.sourceLine;\n if (selectedFile || selectedLine)\n return `${String(selectedFile ?? '')}:${String(selectedLine ?? '')}`;\n const file = evidence.file ?? evidence.sourceFile ?? evidence.handlerSourceFile ?? evidence.operationSourceFile ?? evidence.registrationSourceFile;\n const line = evidence.line ?? evidence.sourceLine ?? evidence.handlerSourceLine ?? evidence.operationSourceLine ?? evidence.registrationSourceLine;\n if (file || line) return `${String(file ?? '')}:${String(line ?? '')}`;\n const candidates = evidence.candidates;\n if (Array.isArray(candidates) && candidates.some((candidate) =>\n isRecord(candidate) && candidate.methodId !== undefined)) return ':';\n if (Array.isArray(candidates) && candidates.length > 0) {\n const first = candidates.find(isRecord);\n if (first)\n return `${String(first.sourceFile ?? '')}:${String(first.sourceLine ?? '')}`;\n }\n return ':';\n}\nexport function renderTraceTable(result: TraceResult): string {\n const lines = ['Step Type From To Evidence'];\n for (const e of result.edges) {\n lines.push(`${String(e.step).padEnd(5)} ${e.type.padEnd(20)} ${e.from.slice(0, 34).padEnd(35)} ${e.to.slice(0, 35).padEnd(36)} ${location(e.evidence)}`);\n if (e.unresolvedReason)\n lines.push(...hintLines(e.evidence).map((hint) => ` ${hint}`));\n }\n if (result.diagnostics.length > 0) lines.push('', 'Diagnostics:', ...result.diagnostics.flatMap(diagnosticLines));\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction diagnosticLines(diagnostic: Record<string, unknown>): string[] {\n const first = `${String(diagnostic.severity ?? 'info')} ${String(diagnostic.code ?? 'diagnostic')} ${String(diagnostic.message ?? '')}`;\n const details = diagnosticDetailLines(diagnostic);\n return [first, ...[...details, ...hintLines(diagnostic)]\n .map((hint) => ` ${hint}`)];\n}\n\nfunction diagnosticDetailLines(diagnostic: Record<string, unknown>): string[] {\n const lines: string[] = [];\n if (diagnostic.sourceFile || diagnostic.sourceLine)\n lines.push(`at ${String(diagnostic.sourceFile ?? '')}:${String(diagnostic.sourceLine ?? '')}`);\n const unsupported = stringList(diagnostic.unsupportedDecoratorNames);\n const observed = stringList(diagnostic.observedDecoratorNames);\n if (unsupported.length > 0)\n lines.push(`unsupported decorators: ${unsupported.join(', ')}`);\n else if (observed.length > 0)\n lines.push(`observed decorators: ${observed.join(', ')}`);\n if (typeof diagnostic.remediation === 'string')\n lines.push(`hint: ${diagnostic.remediation}`);\n return lines;\n}\n\nfunction stringList(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction hintLines(evidence: Record<string, unknown>): string[] {\n const dynamicLines = dynamicHintLines(evidence);\n const suggestions = evidence.implementationHintSuggestions;\n if (!Array.isArray(suggestions)) return dynamicLines;\n const hints = suggestions.flatMap((item) =>\n isRecord(item) && typeof item.cli === 'string'\n ? [item.cli]\n : []);\n const unique = [...new Set(hints)];\n const shown = unique.slice(0, 3).map((hint) => `try ${hint}`);\n const omitted = numberValue(evidence.omittedImplementationHintSuggestionCount);\n const remaining = Math.max(0, unique.length - shown.length) + omitted;\n if (remaining > 0)\n shown.push(`... ${remaining} additional hint(s) omitted; use a scoped --implementation-hint`);\n return [...dynamicLines, ...shown];\n}\n\nfunction dynamicHintLines(evidence: Record<string, unknown>): string[] {\n const exploration = isRecord(evidence.dynamicTargetExploration)\n ? evidence.dynamicTargetExploration\n : evidence;\n const count = numberValue(exploration.candidateCount);\n if (count === 0) return [];\n const shown = numberValue(exploration.shownCandidateCount);\n const omitted = numberValue(exploration.omittedCandidateCount);\n const rejected = numberValue(exploration.rejectedCandidateCount);\n const lines = [\n `viable candidates: ${shown} shown, ${omitted} omitted; rejected: ${rejected}`,\n ];\n lines.push(...varSetHints(exploration.suggestedVarSets));\n if (omitted > 0 || rejected > 0 || shown < count)\n lines.push('use --dynamic-mode candidates --max-dynamic-candidates 20 to explore candidate branches');\n return lines;\n}\n\nfunction varSetHints(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n const hints = value.flatMap((item) =>\n isRecord(item) && typeof item.cli === 'string' ? [`try ${item.cli}`] : []);\n return [...new Set(hints)].slice(0, 3);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction numberValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n","import type { TraceResult } from '../types.js';\nexport function renderJson(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\nexport function renderTraceJson(trace: TraceResult): string {\n return renderJson(trace);\n}\n","import pc from 'picocolors';\nimport { renderJson } from './json-output.js';\n\ntype Diagnostic = Record<string, unknown>;\n\nexport function renderDoctorDiagnostics(diagnostics: Diagnostic[], format: string | undefined): string {\n if (format === 'json') return renderJson(diagnostics);\n if (format === 'table') return renderDoctorTable(diagnostics);\n if (format) throw new Error(`Unsupported doctor format: ${format}. Expected json or table.`);\n return renderLegacyDoctorOutput(diagnostics);\n}\n\nfunction renderLegacyDoctorOutput(diagnostics: Diagnostic[]): string {\n if (diagnostics.length === 0) return cleanDoctorMessage();\n return renderJson(diagnostics);\n}\n\nexport function renderDoctorTable(diagnostics: Diagnostic[]): string {\n if (diagnostics.length === 0) return cleanDoctorMessage();\n const rows = diagnostics.map((diagnostic) => ({\n severity: String(diagnostic.severity ?? 'info'),\n code: String(diagnostic.code ?? 'diagnostic'),\n location: diagnosticLocation(diagnostic),\n message: compactMessage(diagnostic),\n hints: suggestedHintLines(diagnostic),\n }));\n const widths = {\n severity: columnWidth('Severity', rows.map((row) => row.severity), 10),\n code: columnWidth('Code', rows.map((row) => row.code), 44),\n location: columnWidth('Location', rows.map((row) => row.location), 28),\n };\n const lines = [\n `${'Severity'.padEnd(widths.severity)} ${'Code'.padEnd(widths.code)} ${'Location'.padEnd(widths.location)} Message`,\n `${'-'.repeat(widths.severity)} ${'-'.repeat(widths.code)} ${'-'.repeat(widths.location)} ${'-'.repeat(7)}`,\n ];\n for (const row of rows) {\n lines.push(`${truncate(row.severity, widths.severity).padEnd(widths.severity)} ${truncate(row.code, widths.code).padEnd(widths.code)} ${truncate(row.location, widths.location).padEnd(widths.location)} ${row.message}`);\n lines.push(...row.hints.map((hint) => ` try ${hint}`));\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction diagnosticLocation(diagnostic: Diagnostic): string {\n const file = diagnostic.sourceFile ?? diagnostic.file;\n const line = diagnostic.sourceLine ?? diagnostic.line;\n if (file || line) return `${String(file ?? '')}:${String(line ?? '')}`;\n return '-';\n}\n\nfunction compactMessage(diagnostic: Diagnostic): string {\n const message = String(diagnostic.message ?? '');\n const count = typeof diagnostic.count === 'number' ? ` count=${diagnostic.count}` : '';\n const total = typeof diagnostic.total === 'number' ? ` total=${diagnostic.total}` : '';\n return `${message}${count}${total}`.trim();\n}\n\nfunction suggestedHintLines(diagnostic: Diagnostic): string[] {\n const direct = cliHints(diagnostic.suggestedHints);\n const omitted = numericValue(diagnostic.omittedImplementationHintSuggestionCount);\n if (direct.length > 0) return cappedHints(direct, omitted);\n return cappedHints(\n cliHintsFromSuggestions(diagnostic.implementationHintSuggestions), omitted,\n );\n}\n\nfunction cliHints(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];\n}\n\nfunction cliHintsFromSuggestions(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((item) => {\n if (!isRecord(item)) return [];\n return typeof item.cli === 'string' ? [item.cli] : [];\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction cappedHints(hints: string[], omitted: number): string[] {\n const unique = [...new Set(hints)];\n const shown = unique.slice(0, 3);\n const remaining = Math.max(0, unique.length - shown.length) + omitted;\n if (remaining > 0)\n shown.push(`... ${remaining} additional hint(s) omitted; use a scoped --implementation-hint`);\n return shown;\n}\n\nfunction numericValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction cleanDoctorMessage(): string {\n return `${pc.green('No diagnostics recorded')}\\n`;\n}\n\nfunction columnWidth(header: string, values: string[], max: number): number {\n return Math.min(max, Math.max(header.length, ...values.map((value) => value.length)));\n}\n\nfunction truncate(value: string, width: number): string {\n if (value.length <= width) return value;\n if (width <= 1) return value.slice(0, width);\n return `${value.slice(0, width - 1)}…`;\n}\n","import type { TraceResult } from '../types.js';\nfunction label(trace: TraceResult, idOrLabel: string): string {\n const node = trace.nodes.find((item) => item.id === idOrLabel || item.label === idOrLabel);\n return String(node?.label ?? idOrLabel);\n}\nexport function renderMermaid(trace: TraceResult): string {\n const ids = new Map<string, string>();\n const nodeId = (value: string): string => {\n const existing = ids.get(value);\n if (existing) return existing;\n const id = `n${ids.size}`;\n ids.set(value, id);\n return id;\n };\n const lines = ['flowchart TD'];\n for (const e of trace.edges)\n lines.push(\n ` ${nodeId(e.from)}[\"${label(trace, e.from)}\"] -->|${e.type}| ${nodeId(e.to)}[\"${label(trace, e.to)}\"]`\n );\n return `${lines.join('\\n')}\\n`;\n}\n","import type { Writable } from 'node:stream';\n\nexport interface StdoutWriter {\n write(value: string): boolean;\n}\n\ninterface OutputState {\n blocked: boolean;\n unexpectedReported: boolean;\n}\n\ninterface WriterEntry {\n state: OutputState;\n writer: StdoutWriter;\n}\n\nconst writers = new WeakMap<Writable, WriterEntry>();\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction isBrokenPipe(error: Error): boolean {\n return isRecord(error) && error.code === 'EPIPE';\n}\n\nfunction asError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction handleStreamError(\n state: OutputState,\n error: Error,\n onUnexpectedError: (error: Error) => void,\n): void {\n state.blocked = true;\n if (isBrokenPipe(error) || state.unexpectedReported) return;\n state.unexpectedReported = true;\n onUnexpectedError(error);\n}\n\nexport function createStdoutWriter(\n stream: Writable,\n onUnexpectedError: (error: Error) => void,\n): StdoutWriter {\n const existing = writers.get(stream);\n if (existing) return existing.writer;\n const state: OutputState = { blocked: false, unexpectedReported: false };\n const writer: StdoutWriter = {\n write(value: string): boolean {\n if (state.blocked) return false;\n try {\n stream.write(value);\n return true;\n } catch (error) {\n handleStreamError(state, asError(error), onUnexpectedError);\n return false;\n }\n },\n };\n stream.on('error', (error: Error) =>\n handleStreamError(state, error, onUnexpectedError));\n writers.set(stream, { state, writer });\n return writer;\n}\n","import type { CompactGraphV1 } from '../trace/014-compact-contract.js';\nimport { redactValue } from '../utils/redaction.js';\n\nexport function renderCompactJson(value: CompactGraphV1): string {\n return `${JSON.stringify(redactValue(value))}\\n`;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { WorkspaceConfig } from '../config/workspace-config.js';\nimport { openDatabase } from '../db/connection.js';\nimport { getWorkspace, upsertWorkspace } from '../db/repositories.js';\nimport { claimIndexRun } from '../indexer/workspace-indexer.js';\nimport { errorMessage } from '../utils/diagnostics.js';\n\ntype CleanConfig = Pick<WorkspaceConfig, 'dbPath' | 'rootPath'>;\n\nexport async function cleanWorkspaceState(\n config: CleanConfig,\n dbOnly: boolean,\n): Promise<void> {\n const dbDir = path.resolve(path.dirname(config.dbPath));\n if (!dbOnly) await assertOwnedStateDirectory(dbDir, config.rootPath);\n const runId = claimCleanWriter(config);\n try {\n if (dbOnly) await removeDatabaseFiles(config.dbPath);\n else await fs.rm(dbDir, { recursive: true, force: true });\n } catch (error) {\n await markCleanClaimFailed(config.dbPath, runId, error);\n throw error;\n }\n}\n\nfunction claimCleanWriter(config: CleanConfig): number {\n const db = openDatabase(config.dbPath);\n try {\n const workspaceId = getWorkspace(db, config.rootPath)?.id\n ?? upsertWorkspace(db, config.rootPath, config.dbPath);\n return claimIndexRun(db, workspaceId, 0);\n } finally {\n db.close();\n }\n}\n\nasync function assertOwnedStateDirectory(\n dbDir: string,\n rootPath: string,\n): Promise<void> {\n const marker = path.join(dbDir, '.service-flow-state');\n const dangerous = new Set([\n path.parse(dbDir).root,\n '/tmp',\n process.env.HOME ? path.resolve(process.env.HOME) : '',\n path.resolve(rootPath),\n ]);\n const ownsState = await fs.stat(marker)\n .then((stat) => stat.isFile())\n .catch(() => false);\n if (!ownsState || dangerous.has(dbDir))\n throw new Error(\n `Refusing to recursively delete unowned or dangerous state directory: ${dbDir}. Use --db-only to remove only the database file.`,\n );\n}\n\nasync function removeDatabaseFiles(dbPath: string): Promise<void> {\n for (const suffix of ['-wal', '-shm', '-journal'])\n await fs.rm(`${dbPath}${suffix}`, { force: true });\n await fs.rm(dbPath, { force: true });\n}\n\nasync function markCleanClaimFailed(\n dbPath: string,\n runId: number,\n error: unknown,\n): Promise<void> {\n const exists = await fs.stat(dbPath).then(() => true).catch(() => false);\n if (!exists) return;\n const db = openDatabase(dbPath);\n try {\n db.prepare(`UPDATE index_runs SET finished_at=?,status='failed',\n error_message=? WHERE id=? AND status='running'`).run(\n new Date().toISOString(),\n `Clean failed after writer claim: ${errorMessage(error)}`,\n runId,\n );\n } finally {\n db.close();\n }\n}\n","import type {\n IndexWorkspaceSummary,\n} from '../indexer/workspace-indexer.js';\n\nexport interface IndexCommandOutcome {\n stdout: string;\n exitCode: 0 | 1;\n}\n\nexport function indexCommandOutcome(\n summary: IndexWorkspaceSummary,\n): IndexCommandOutcome {\n const failed = summary.failedCount > 0\n ? `, failed ${summary.failedCount} (${\n summary.failedRepos.map(({ name, code }) => `${name}: ${code}`).join(', ')\n })`\n : '';\n return {\n stdout: `Indexed ${summary.indexedCount} repositories, skipped ${summary.skippedCount}${failed}, ${summary.fileCount} files, ${summary.diagnosticCount} diagnostics\\n`,\n exitCode: summary.failedCount > 0 ? 1 : 0,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,cAAc;;;ACAzB,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,aAAa;AACnB,IAAM,cAAc;AACpB,IAAM,kBAAkB;;;ACb/B,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,SAAS;AAOlB,IAAM,SAAS,EAAE,OAAO;AAAA,EACtB,UAAU,EAAE,OAAO;AAAA,EACnB,QAAQ,EAAE,OAAO;AAAA,EACjB,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,EAC1B,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,OAAO;AACtB,CAAC;AAEM,SAAS,WAAW,UAA0B;AACnD,SAAO,KAAK,KAAK,UAAU,YAAY,WAAW;AACpD;AACO,SAAS,cAAc,UAA0B;AACtD,SAAO,KAAK,KAAK,UAAU,YAAY,eAAe;AACxD;AACA,eAAsB,oBACpB,QACe;AACf,QAAM,GAAG,MAAM,KAAK,QAAQ,WAAW,OAAO,QAAQ,CAAC,GAAG;AAAA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AAU,QAAO;AACtD,MAAI,UAAU,gBAAgB,UAAU,QAAS,QAAO;AACxD,QAAM,IAAI,MAAM,0BAA0B,KAAK,yCAAyC;AAC1F;AACA,SAAS,qBAAqB,OAA2B,UAA0B;AACjF,QAAM,SAAS,OAAO,KAAK;AAC3B,SAAO,OAAO,SAAS,MAAM,KAAK,SAAS,IAAI,KAAK,MAAM,MAAM,IAAI;AACtE;AACA,SAAS,KAAK,OAAsB;AAClC,UAAQ,OAAO;AAAA,IACb,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA;AAAA,EAC3D;AACA,UAAQ,WAAW;AACrB;AACA,cAAc,EAAE,MAAM,QAAQ,IAAI;","names":["fs","path","fs","path","packageName","fs","path","fs","path","fs","path","ts","ts","sourceFile","ts","ts","ts","ts","ts","ts","ts","assignmentOperator","ts","mutationUnary","propertyContainer","propertyName","lineOf","ts","propertyName","sourceFile","fs","path","path","fs","packageName","sourceFile","candidateCount","numericValue","count","trace","count","numericValue","isRecord","trace","isRecord","fs","path","path","fs"]}