@saptools/service-flow 0.1.67 → 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.
- package/CHANGELOG.md +20 -0
- package/README.md +27 -9
- package/TECHNICAL-NOTE.md +36 -0
- package/dist/chunk-3N3B5KHV.js +19596 -0
- package/dist/chunk-3N3B5KHV.js.map +1 -0
- package/dist/cli.js +2645 -521
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +67 -2
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/src/cli/001-index-summary.ts +22 -0
- package/src/cli/003-doctor-package-resolution.ts +68 -0
- package/src/cli/doctor.ts +25 -14
- package/src/cli.ts +151 -87
- package/src/db/000-call-fact-repository.ts +499 -340
- package/src/db/001-fact-lifecycle.ts +60 -30
- package/src/db/002-fact-json-inventory.ts +169 -0
- package/src/db/003-current-fact-semantics.ts +699 -0
- package/src/db/004-package-target-invalidation.ts +183 -0
- package/src/db/005-schema-structure.ts +201 -0
- package/src/db/006-relative-symbol-resolution.ts +464 -0
- package/src/db/007-package-fact-semantics.ts +573 -0
- package/src/db/008-relative-fact-semantics.ts +210 -0
- package/src/db/009-binding-fact-semantics.ts +352 -0
- package/src/db/010-package-symbol-surface-semantics.ts +320 -0
- package/src/db/011-symbol-call-semantics.ts +144 -0
- package/src/db/012-binding-reference-proof.ts +268 -0
- package/src/db/013-index-publication-failure.ts +91 -0
- package/src/db/014-binding-helper-provenance.ts +17 -0
- package/src/db/migrations.ts +16 -3
- package/src/db/repositories.ts +130 -6
- package/src/db/schema.ts +4 -2
- package/src/index.ts +12 -0
- package/src/indexer/cds-extension-resolver.ts +27 -3
- package/src/indexer/repository-indexer.ts +135 -13
- package/src/indexer/workspace-indexer.ts +237 -34
- package/src/linker/003-package-import-symbol-resolver.ts +363 -131
- package/src/linker/004-event-subscription-handler-linker.ts +34 -11
- package/src/linker/005-odata-path-structure.ts +371 -0
- package/src/linker/006-event-template-link.ts +72 -0
- package/src/linker/007-call-edge-insertion.ts +568 -0
- package/src/linker/cross-repo-linker.ts +4 -166
- package/src/linker/odata-path-normalizer.ts +273 -180
- package/src/linker/service-resolver.ts +197 -77
- package/src/parsers/000-direct-query-execution.ts +11 -0
- package/src/parsers/002-symbol-import-bindings.ts +516 -0
- package/src/parsers/003-package-public-surface.ts +661 -0
- package/src/parsers/004-fact-identity.ts +108 -0
- package/src/parsers/005-event-subscription-facts.ts +281 -0
- package/src/parsers/006-binding-identity.ts +348 -0
- package/src/parsers/007-source-fact-reconciliation.ts +105 -0
- package/src/parsers/008-package-surface-publication.ts +82 -0
- package/src/parsers/009-symbol-call-facts.ts +528 -0
- package/src/parsers/010-package-public-surface-analysis.ts +352 -0
- package/src/parsers/011-binding-lexical-scope.ts +583 -0
- package/src/parsers/012-package-fact-contract.ts +306 -0
- package/src/parsers/013-executable-body-eligibility.ts +35 -0
- package/src/parsers/014-service-binding-helper-flow.ts +306 -0
- package/src/parsers/015-service-binding-collector.ts +693 -0
- package/src/parsers/016-local-symbol-reference.ts +261 -0
- package/src/parsers/017-symbol-derived-contexts.ts +268 -0
- package/src/parsers/018-package-commonjs-syntax.ts +142 -0
- package/src/parsers/019-binding-assignment-targets.ts +76 -0
- package/src/parsers/020-stable-local-value.ts +217 -0
- package/src/parsers/021-binding-visibility.ts +168 -0
- package/src/parsers/022-outbound-expression-analysis.ts +700 -0
- package/src/parsers/023-outbound-call-classifier.ts +692 -0
- package/src/parsers/operation-path-analysis.ts +6 -1
- package/src/parsers/outbound-call-parser.ts +162 -512
- package/src/parsers/package-json-parser.ts +45 -3
- package/src/parsers/service-binding-parser-helpers.ts +86 -15
- package/src/parsers/service-binding-parser.ts +147 -597
- package/src/parsers/symbol-parser.ts +513 -352
- package/src/trace/002-trace-diagnostics.ts +36 -1
- package/src/trace/007-implementation-start-diagnostic.ts +1 -0
- package/src/trace/011-event-subscriber-traversal.ts +100 -8
- package/src/trace/013-trace-root-scopes.ts +2 -3
- package/src/trace/014-compact-contract.ts +6 -0
- package/src/trace/015-trace-edge-recorder.ts +61 -4
- package/src/trace/016-compact-projector.ts +15 -17
- package/src/trace/019-trace-edge-semantics.ts +6 -10
- package/src/trace/020-compact-field-projection.ts +122 -38
- package/src/trace/021-compact-decision-normalization.ts +171 -0
- package/src/trace/022-trace-fact-preflight.ts +21 -0
- package/src/trace/023-nested-event-scopes.ts +23 -0
- package/src/trace/024-compact-observation-decision.ts +81 -0
- package/src/trace/025-trace-implementation-scope.ts +123 -0
- package/src/trace/026-trace-start-scope.ts +336 -0
- package/src/trace/027-trace-scope-execution.ts +566 -0
- package/src/trace/028-trace-operation-execution.ts +336 -0
- package/src/trace/029-trace-start-implementation.ts +172 -0
- package/src/trace/030-event-runtime-resolution.ts +151 -0
- package/src/trace/031-local-call-expansion.ts +37 -0
- package/src/trace/implementation-hints.ts +9 -6
- package/src/trace/selectors.ts +1 -0
- package/src/trace/trace-engine.ts +122 -624
- package/src/types.ts +57 -0
- package/src/utils/001-placeholders.ts +188 -10
- package/src/version.ts +1 -1
- package/dist/chunk-ZQABU7MR.js +0 -12151
- package/dist/chunk-ZQABU7MR.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json","../src/version.ts","../src/db/000-call-fact-repository.ts","../src/utils/000-bounded-projection.ts","../src/db/repositories.ts","../src/discovery/discover-repositories.ts","../src/utils/path-utils.ts","../src/parsers/package-json-parser.ts","../src/parsers/cds-parser.ts","../src/parsers/decorator-parser.ts","../src/linker/operation-decorator-normalizer.ts","../src/parsers/ts-project.ts","../src/parsers/handler-registration-parser.ts","../src/utils/redaction.ts","../src/parsers/service-binding-parser.ts","../src/parsers/service-binding-parser-helpers.ts","../src/utils/001-placeholders.ts","../src/parsers/outbound-call-parser.ts","../src/linker/external-http-target.ts","../src/linker/odata-path-normalizer.ts","../src/parsers/imported-wrapper-parser.ts","../src/parsers/operation-path-analysis.ts","../src/parsers/000-direct-query-execution.ts","../src/parsers/001-query-entity-resolution.ts","../src/linker/dynamic-edge-resolver.ts","../src/trace/implementation-hints.ts","../src/linker/remote-query-target.ts","../src/linker/001-implementation-evidence-projection.ts","../src/linker/000-implementation-candidates.ts","../src/linker/service-resolver.ts","../src/linker/helper-package-linker.ts","../src/linker/002-call-evidence.ts","../src/linker/003-package-import-symbol-resolver.ts","../src/linker/004-event-subscription-handler-linker.ts","../src/db/schema.ts","../src/db/migrations.ts","../src/db/001-fact-lifecycle.ts","../src/linker/cross-repo-linker.ts","../src/trace/selectors.ts","../src/trace/004-dynamic-candidate-sources.ts","../src/trace/001-dynamic-identity.ts","../src/trace/003-dynamic-references.ts","../src/trace/dynamic-targets.ts","../src/trace/006-contextual-projection.ts","../src/trace/008-contextual-runtime-state.ts","../src/trace/evidence.ts","../src/trace/dynamic-branches.ts","../src/trace/002-trace-diagnostics.ts","../src/trace/005-implementation-selection.ts","../src/trace/007-implementation-start-diagnostic.ts","../src/trace/009-selected-handler-provenance.ts","../src/trace/010-traversal-scope.ts","../src/trace/011-event-subscriber-traversal.ts","../src/trace/012-trace-graph-lookups.ts","../src/trace/013-trace-root-scopes.ts","../src/trace/017-trace-context.ts","../src/trace/015-trace-edge-recorder.ts","../src/trace/019-trace-edge-semantics.ts","../src/trace/trace-engine.ts","../src/trace/014-compact-contract.ts","../src/trace/020-compact-field-projection.ts","../src/trace/016-compact-projector.ts","../src/trace/018-compact-trace.ts"],"sourcesContent":["{\n \"name\": \"@saptools/service-flow\",\n \"version\": \"0.1.67\",\n \"description\": \"Trace SAP CAP service-to-service flows across multi-repository workspaces with runtime-aware graph resolution\",\n \"type\": \"module\",\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n },\n \"bin\": {\n \"service-flow\": \"dist/cli.js\"\n },\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"files\": [\n \"CHANGELOG.md\",\n \"README.md\",\n \"TECHNICAL-NOTE.md\",\n \"dist\",\n \"src\"\n ],\n \"engines\": {\n \"node\": \">=24.0.0\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint src tests\",\n \"test\": \"vitest run tests/unit\",\n \"test:unit\": \"vitest run tests/unit\",\n \"test:e2e\": \"vitest run tests/e2e\",\n \"test:e2e:fake\": \"vitest run tests/e2e\"\n },\n \"keywords\": [\n \"sap\",\n \"cap\",\n \"cds\",\n \"btp\",\n \"cli\",\n \"service-graph\",\n \"call-graph\",\n \"sqlite\",\n \"saptools\"\n ],\n \"author\": \"Dong Tran\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/dongitran/saptools.git\",\n \"directory\": \"packages/service-flow\"\n },\n \"homepage\": \"https://github.com/dongitran/saptools/tree/main/packages/service-flow#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/dongitran/saptools/issues\"\n },\n \"dependencies\": {\n \"commander\": \"13.1.0\",\n \"picocolors\": \"1.1.1\",\n \"typescript\": \"5.9.3\",\n \"zod\": \"4.4.3\"\n },\n \"devDependencies\": {\n \"@vitest/coverage-v8\": \"3.2.4\",\n \"tsup\": \"8.5.1\",\n \"vitest\": \"3.2.4\"\n }\n}\n","import packageJson from '../package.json' with { type: 'json' };\n\nexport const VERSION = packageJson.version;\nexport const ANALYZER_VERSION = '0.1.66-facts.1';\n","import { posix } from 'node:path';\nimport type { OutboundCallFact, SymbolCallFact } from '../types.js';\nimport { projectBounded } from '../utils/000-bounded-projection.js';\nimport type { Db, Statement } from './connection.js';\n\nexport function insertSymbolCalls(db: Db, repoId: number, rows: SymbolCallFact[]): void {\n const callerStmt = db.prepare('SELECT id FROM symbols WHERE repo_id=? AND source_file=? AND qualified_name=? ORDER BY id LIMIT 1');\n const insertStmt = db.prepare('INSERT INTO symbol_calls(repo_id,caller_symbol_id,callee_symbol_id,callee_expression,import_source,source_file,source_line,call_site_start_offset,call_site_end_offset,call_role,status,confidence,evidence_json,unresolved_reason) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)');\n for (const r of rows) {\n const caller = callerStmt.get(repoId, r.sourceFile, r.callerQualifiedName) as { id?: number } | undefined;\n const target = resolveSymbolCallTarget(db, repoId, r);\n insertStmt.run(\n repoId,\n caller?.id,\n target.id,\n r.calleeExpression,\n r.importSource,\n r.sourceFile,\n r.sourceLine,\n r.callSiteStartOffset,\n r.callSiteEndOffset,\n r.callRole,\n target.status,\n 0.8,\n JSON.stringify({\n ...r.evidence,\n candidateStrategy: target.strategy,\n candidateCount: target.candidateCount,\n resolvedModulePath: target.resolvedModulePath,\n }),\n target.reason,\n );\n }\n}\n\ninterface SymbolTargetRow {\n id: number;\n kind?: string;\n sourceFile?: string | null;\n evidenceJson?: string | null;\n}\n\ninterface SymbolCallResolution {\n id: number | null;\n status: 'resolved' | 'ambiguous' | 'unresolved';\n reason: string | null;\n strategy: string;\n candidateCount: number;\n resolvedModulePath?: string;\n}\n\nconst stripExt = (value: string): string => value.replace(/\\.(ts|tsx|js|jsx|cds)$/, '');\n\nfunction symbolTargetRows(rows: Array<Record<string, unknown>>): SymbolTargetRow[] {\n return rows.flatMap((row) => typeof row.id === 'number' ? [{\n id: row.id,\n kind: typeof row.kind === 'string' ? row.kind : undefined,\n sourceFile: nullableString(row.sourceFile),\n evidenceJson: nullableString(row.evidenceJson),\n }] : []);\n}\n\nfunction relativeModuleTargets(callerSourceFile: string, importSource: string): Set<string> {\n const base = posix.dirname(callerSourceFile);\n const joined = stripExt(posix.normalize(posix.join(base, importSource)));\n return new Set([joined, `${joined}/index`]);\n}\n\nfunction moduleRows(rows: SymbolTargetRow[], r: SymbolCallFact): SymbolTargetRow[] {\n if (!r.importSource) return [];\n const targets = relativeModuleTargets(r.sourceFile, r.importSource);\n return rows.filter((row) => typeof row.sourceFile === 'string'\n && targets.has(stripExt(row.sourceFile)));\n}\n\nfunction resolvedSymbol(\n row: SymbolTargetRow,\n strategy: string,\n candidateCount: number,\n moduleScoped = false,\n): SymbolCallResolution {\n return {\n id: row.id,\n status: 'resolved',\n reason: null,\n strategy,\n candidateCount,\n resolvedModulePath: moduleScoped && row.sourceFile\n ? stripExt(row.sourceFile)\n : undefined,\n };\n}\n\nfunction exportedSymbolRows(db: Db, repoId: number, r: SymbolCallFact): SymbolTargetRow[] {\n return symbolTargetRows(db.prepare('SELECT id,kind,source_file sourceFile,evidence_json evidenceJson FROM symbols WHERE repo_id=? AND source_file<>? AND exported=1 AND (exported_name=? OR name=? OR qualified_name=?) ORDER BY id').all(repoId, r.sourceFile, r.calleeLocalName, r.calleeLocalName, r.calleeLocalName));\n}\n\nfunction isRelativeImportedSymbolCall(r: SymbolCallFact): boolean {\n return Boolean(r.importSource?.startsWith('.'));\n}\n\nfunction sameFileResolution(\n db: Db,\n repoId: number,\n r: SymbolCallFact,\n relation: unknown,\n): SymbolCallResolution | undefined {\n const bareImport = relation === 'relative_import' && isRelativeImportedSymbolCall(r)\n && !String(r.calleeLocalName).includes('.');\n if (bareImport || relation === 'relative_import_namespace_member'\n || relation === 'package_import') return undefined;\n const rows = symbolTargetRows(db.prepare('SELECT id FROM symbols WHERE repo_id=? AND source_file=? AND (name=? OR qualified_name=?) ORDER BY id').all(repoId, r.sourceFile, r.calleeLocalName, r.calleeLocalName));\n if (rows.length === 1 && rows[0]) return resolvedSymbol(rows[0], 'same_file_exact', 1);\n return rows.length > 1\n ? {\n id: null,\n status: 'ambiguous',\n reason: 'Multiple same-file symbol targets matched exactly',\n strategy: 'same_file_exact',\n candidateCount: rows.length,\n }\n : undefined;\n}\n\nfunction classInstanceResolution(\n db: Db,\n repoId: number,\n r: SymbolCallFact,\n relation: unknown,\n): SymbolCallResolution | undefined {\n if (relation !== 'class_instance_method' || !isRelativeImportedSymbolCall(r))\n return undefined;\n const rows = symbolTargetRows(db.prepare('SELECT id FROM symbols WHERE repo_id=? AND source_file<>? AND qualified_name=? ORDER BY id').all(repoId, r.sourceFile, r.calleeLocalName));\n if (rows.length === 1 && rows[0])\n return resolvedSymbol(rows[0], 'relative_import_class_instance_method', 1);\n return rows.length > 1\n ? {\n id: null,\n status: 'ambiguous',\n reason: 'Multiple relative class instance method targets matched exactly',\n strategy: 'relative_import_class_instance_method',\n candidateCount: rows.length,\n }\n : undefined;\n}\n\nfunction namespaceResolution(\n db: Db,\n repoId: number,\n r: SymbolCallFact,\n relation: unknown,\n): SymbolCallResolution | undefined {\n if (relation !== 'relative_import_namespace_member'\n || !isRelativeImportedSymbolCall(r)) return undefined;\n const rows = moduleRows(exportedSymbolRows(db, repoId, r), r);\n if (rows.length === 1 && rows[0])\n return resolvedSymbol(rows[0], 'relative_import_namespace_member', 1, true);\n if (rows.length > 1) return {\n id: null,\n status: 'ambiguous',\n reason: 'Multiple namespace member targets matched the imported module',\n strategy: 'relative_import_namespace_member',\n candidateCount: rows.length,\n };\n return {\n id: null,\n status: 'unresolved',\n reason: 'No namespace member target matched the imported module',\n strategy: 'relative_import_namespace_member',\n candidateCount: 0,\n };\n}\n\nfunction proxyResolution(\n rows: SymbolTargetRow[],\n r: SymbolCallFact,\n relation: unknown,\n): SymbolCallResolution | undefined {\n if (relation !== 'relative_import_proxy_member' || rows.length <= 1) return undefined;\n const mapped = rows.filter(isExportedObjectMapping);\n if (mapped.length > 0) {\n const concrete = rows.find((row) => row.kind !== 'object_alias') ?? mapped[0];\n return {\n id: concrete?.id ?? null,\n status: 'resolved',\n reason: null,\n strategy: 'proxy_member_exported_object_map',\n candidateCount: rows.length,\n };\n }\n const scoped = moduleRows(rows, r);\n if (scoped.length === 1 && scoped[0])\n return resolvedSymbol(scoped[0], 'relative_import_path_disambiguated', rows.length, true);\n return {\n id: null,\n status: 'ambiguous',\n reason: 'Proxy member target requires explicit factory/module/type evidence; global member name is ambiguous',\n strategy: 'proxy_member_no_global_name_fallback',\n candidateCount: rows.length,\n };\n}\n\nfunction isExportedObjectMapping(row: SymbolTargetRow): boolean {\n const evidence = String(row.evidenceJson ?? '');\n return evidence.includes('exported_object_shorthand')\n || evidence.includes('exported_object_literal');\n}\n\nfunction exportedResolution(\n rows: SymbolTargetRow[],\n r: SymbolCallFact,\n relation: unknown,\n): SymbolCallResolution | undefined {\n if (rows.length === 1 && rows[0]) return resolvedSymbol(\n rows[0],\n relation === 'relative_import_proxy_member'\n ? 'proxy_member_unique_exported_candidate'\n : 'relative_import_exported_exact',\n 1,\n moduleRows(rows, r).length === 1,\n );\n if (rows.length <= 1) return undefined;\n const scoped = isRelativeImportedSymbolCall(r) ? moduleRows(rows, r) : [];\n if (scoped.length === 1 && scoped[0])\n return resolvedSymbol(scoped[0], 'relative_import_path_disambiguated', rows.length, true);\n return {\n id: null,\n status: 'ambiguous',\n reason: 'Multiple exported symbol targets matched exactly',\n strategy: 'exported_exact',\n candidateCount: rows.length,\n };\n}\n\nfunction accessorResolution(\n db: Db,\n repoId: number,\n r: SymbolCallFact,\n relation: unknown,\n): SymbolCallResolution | undefined {\n if (relation !== 'relative_import' || !isRelativeImportedSymbolCall(r)\n || !/^[^.]+\\.[^.]+$/.test(String(r.calleeLocalName))) return undefined;\n const methodRows = symbolTargetRows(db.prepare(\"SELECT id,kind,source_file sourceFile FROM symbols WHERE repo_id=? AND source_file<>? AND kind='method' AND qualified_name=? ORDER BY id\").all(repoId, r.sourceFile, r.calleeLocalName));\n const scoped = moduleRows(methodRows, r);\n if (scoped.length === 1 && scoped[0]) return resolvedSymbol(\n scoped[0],\n 'relative_import_static_accessor_instance_method',\n 1,\n true,\n );\n return scoped.length > 1\n ? {\n id: null,\n status: 'ambiguous',\n reason: 'Multiple static-accessor instance method targets matched the imported module',\n strategy: 'relative_import_static_accessor_instance_method',\n candidateCount: scoped.length,\n }\n : undefined;\n}\n\nfunction resolveSymbolCallTarget(\n db: Db,\n repoId: number,\n r: SymbolCallFact,\n): SymbolCallResolution {\n const relation = r.evidence.relation;\n const early = sameFileResolution(db, repoId, r, relation)\n ?? classInstanceResolution(db, repoId, r, relation)\n ?? namespaceResolution(db, repoId, r, relation);\n if (early) return early;\n const rows = relation === 'package_import' ? [] : exportedSymbolRows(db, repoId, r);\n const matched = proxyResolution(rows, r, relation)\n ?? exportedResolution(rows, r, relation)\n ?? accessorResolution(db, repoId, r, relation);\n if (matched) return matched;\n if (relation === 'package_import') return {\n id: null,\n status: 'unresolved',\n reason: 'Package import target resolution requires a post-publication workspace pass',\n strategy: 'package_import_unresolved',\n candidateCount: 0,\n };\n return {\n id: null,\n status: 'unresolved',\n reason: 'No local symbol target matched exactly',\n strategy: relation === 'relative_import_proxy_member'\n ? 'proxy_member_no_global_name_fallback'\n : 'exact_symbol_match',\n candidateCount: 0,\n };\n}\n\nexport function insertCalls(\n db: Db,\n repoId: number,\n rows: OutboundCallFact[],\n): void {\n const stmt = outboundCallInsertStatement(db);\n for (const row of rows) insertOutboundCall(db, stmt, repoId, row);\n}\n\nfunction outboundCallInsertStatement(db: Db): Statement {\n return db.prepare(`INSERT INTO outbound_calls(\n repo_id,source_symbol_id,call_type,method,operation_path_expr,query_entity,\n event_name_expr,payload_summary,source_file,source_line,call_site_start_offset,\n call_site_end_offset,confidence,unresolved_reason,local_service_name,\n local_service_lookup,alias_chain_json,evidence_json,external_target_kind,\n external_target_id,external_target_label,external_target_dynamic,service_binding_id\n ) VALUES(\n ?,COALESCE(\n (SELECT id FROM symbols WHERE repo_id=? AND source_file=? AND qualified_name=? ORDER BY id LIMIT 1),\n (SELECT id FROM symbols WHERE repo_id=? AND source_file=? AND start_line<=? AND end_line>=? ORDER BY (end_line-start_line),id LIMIT 1)\n ),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?\n )`);\n}\n\nfunction insertOutboundCall(\n db: Db,\n stmt: Statement,\n repoId: number,\n call: OutboundCallFact,\n): void {\n const binding = resolvePersistedBinding(db, repoId, call);\n const external = externalTargetValues(call.externalTarget);\n const evidence = {\n ...(call.evidence ?? {}),\n serviceBindingResolution: binding.evidence,\n };\n stmt.run(\n repoId, repoId, call.sourceFile, call.sourceSymbolQualifiedName,\n repoId, call.sourceFile, call.sourceLine, call.sourceLine,\n call.callType, call.method, call.operationPathExpr, call.queryEntity,\n call.eventNameExpr, call.payloadSummary, call.sourceFile, call.sourceLine,\n call.callSiteStartOffset, call.callSiteEndOffset, call.confidence,\n call.unresolvedReason ?? binding.unresolvedReason,\n call.localServiceName, call.localServiceLookup,\n serializedAliasChain(call.aliasChain),\n JSON.stringify(evidence), external.kind, external.stableId, external.label,\n external.dynamic, binding.bindingId,\n );\n}\n\nfunction serializedAliasChain(\n aliasChain: OutboundCallFact['aliasChain'],\n): string | null {\n return aliasChain ? JSON.stringify(aliasChain) : null;\n}\n\nfunction externalTargetValues(\n target: OutboundCallFact['externalTarget'],\n): { kind: string | null; stableId: string | null; label: string | null;\n dynamic: number } {\n if (!target) return { kind: null, stableId: null, label: null, dynamic: 0 };\n return {\n kind: target.kind, stableId: target.stableId, label: target.label,\n dynamic: target.dynamic ? 1 : 0,\n };\n}\n\ninterface BindingCandidate {\n id: number;\n symbolId?: number | null;\n variableName: string;\n alias?: string | null;\n aliasExpr?: string | null;\n destinationExpr?: string | null;\n servicePathExpr?: string | null;\n sourceFile: string;\n sourceLine: number;\n helperChainJson?: string | null;\n}\n\nfunction resolvePersistedBinding(\n db: Db,\n repoId: number,\n call: OutboundCallFact,\n): {\n bindingId: number | null;\n unresolvedReason?: string;\n evidence: Record<string, unknown>;\n} {\n if (!call.serviceVariableName)\n return { bindingId: null, evidence: { status: 'not_applicable', candidateCount: 0 } };\n const candidates = bindingCandidates(db, repoId, call);\n const prior = candidates.filter((candidate) => candidate.sourceLine <= call.sourceLine);\n const families = new Set(prior.map(bindingSignature));\n if (prior.length > 0 && families.size === 1) {\n const selected = prior.at(-1);\n return {\n bindingId: selected?.id ?? null,\n evidence: bindingEvidence('selected', prior, selected),\n };\n }\n if (prior.length > 1) {\n return {\n bindingId: null,\n unresolvedReason: 'ambiguous_service_binding_candidates',\n evidence: bindingEvidence('ambiguous', prior),\n };\n }\n if (candidates.length > 0) {\n return {\n bindingId: null,\n unresolvedReason: 'service_binding_declared_after_call',\n evidence: bindingEvidence('rejected_future_binding', candidates),\n };\n }\n return {\n bindingId: null,\n evidence: bindingEvidence('unrecoverable', []),\n };\n}\n\nfunction bindingCandidates(\n db: Db,\n repoId: number,\n call: OutboundCallFact,\n): BindingCandidate[] {\n const ownerId = callSymbolId(db, repoId, call);\n const rows = db.prepare(`\n SELECT id,symbol_id symbolId,variable_name variableName,alias,alias_expr aliasExpr,\n destination_expr destinationExpr,service_path_expr servicePathExpr,\n source_file sourceFile,source_line sourceLine,helper_chain_json helperChainJson\n FROM service_bindings\n WHERE repo_id=? AND variable_name=? AND source_file=?\n AND (? IS NULL OR symbol_id IS NULL OR symbol_id=?)\n ORDER BY source_line,id\n `).all(\n repoId,\n call.serviceVariableName,\n call.sourceFile,\n ownerId,\n ownerId,\n ) as Array<Record<string, unknown>>;\n return rows.flatMap((row) => {\n if (typeof row.id !== 'number' || typeof row.variableName !== 'string'\n || typeof row.sourceFile !== 'string' || typeof row.sourceLine !== 'number')\n return [];\n return [{\n id: row.id,\n symbolId: nullableNumber(row.symbolId),\n variableName: row.variableName,\n alias: nullableString(row.alias),\n aliasExpr: nullableString(row.aliasExpr),\n destinationExpr: nullableString(row.destinationExpr),\n servicePathExpr: nullableString(row.servicePathExpr),\n sourceFile: row.sourceFile,\n sourceLine: row.sourceLine,\n helperChainJson: nullableString(row.helperChainJson),\n }];\n });\n}\n\nfunction nullableString(value: unknown): string | null | undefined {\n return value === null || typeof value === 'string' ? value : undefined;\n}\n\nfunction nullableNumber(value: unknown): number | null | undefined {\n return value === null || typeof value === 'number' ? value : undefined;\n}\n\nfunction callSymbolId(\n db: Db,\n repoId: number,\n call: OutboundCallFact,\n): number | undefined {\n const row = db.prepare(`\n SELECT id FROM symbols\n WHERE repo_id=? AND source_file=?\n AND ((? IS NOT NULL AND qualified_name=?)\n OR (start_line<=? AND end_line>=?))\n ORDER BY CASE WHEN qualified_name=? THEN 0 ELSE 1 END,\n (end_line-start_line),id\n LIMIT 1\n `).get(\n repoId,\n call.sourceFile,\n call.sourceSymbolQualifiedName,\n call.sourceSymbolQualifiedName,\n call.sourceLine,\n call.sourceLine,\n call.sourceSymbolQualifiedName,\n );\n return typeof row?.id === 'number' ? row.id : undefined;\n}\n\nfunction bindingEvidence(\n status: string,\n candidates: BindingCandidate[],\n selected?: BindingCandidate,\n): Record<string, unknown> {\n const projection = projectBounded(candidates, (left, right) =>\n Number(right.id === selected?.id) - Number(left.id === selected?.id)\n || left.sourceFile.localeCompare(right.sourceFile)\n || left.sourceLine - right.sourceLine\n || left.id - right.id);\n return {\n status,\n candidateCount: projection.totalCount,\n shownCandidateCount: projection.shownCount,\n omittedCandidateCount: projection.omittedCount,\n selectedBindingId: selected?.id,\n sourceOrderRule: 'binding_source_line_must_not_follow_call',\n candidates: projection.items.map((candidate) => ({\n bindingId: candidate.id,\n symbolId: candidate.symbolId,\n variableName: candidate.variableName,\n alias: candidate.alias,\n aliasExpr: candidate.aliasExpr,\n destinationExpr: candidate.destinationExpr,\n servicePathExpr: candidate.servicePathExpr,\n sourceFile: candidate.sourceFile,\n sourceLine: candidate.sourceLine,\n helperChain: parseBindingChain(candidate.helperChainJson),\n })),\n };\n}\n\nfunction bindingSignature(candidate: BindingCandidate): string {\n return JSON.stringify([\n candidate.alias,\n candidate.aliasExpr,\n candidate.destinationExpr,\n candidate.servicePathExpr,\n ]);\n}\n\nfunction parseBindingChain(value: string | null | undefined): unknown {\n if (!value) return undefined;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return undefined;\n }\n}\n","export const DEFAULT_EVIDENCE_CANDIDATE_LIMIT = 5;\n\nexport interface BoundedProjection<T> {\n totalCount: number;\n shownCount: number;\n omittedCount: number;\n items: T[];\n}\n\nexport function projectBounded<T>(\n values: readonly T[],\n compare: (left: T, right: T) => number,\n limit = DEFAULT_EVIDENCE_CANDIDATE_LIMIT,\n): BoundedProjection<T> {\n const normalizedLimit = positiveLimit(limit);\n const sorted = [...values].sort(compare);\n const items = sorted.slice(0, normalizedLimit);\n return {\n totalCount: sorted.length,\n shownCount: items.length,\n omittedCount: Math.max(0, sorted.length - items.length),\n items,\n };\n}\n\n/**\n * Evidence producers establish semantic order before calling the generic\n * recursive bounder. Re-sorting here would make a selected decision appear\n * to be explained by a different candidate.\n */\nexport function projectBoundedInOrder<T>(\n values: readonly T[],\n limit = DEFAULT_EVIDENCE_CANDIDATE_LIMIT,\n): BoundedProjection<T> {\n const normalizedLimit = positiveLimit(limit);\n const items = values.slice(0, normalizedLimit);\n return {\n totalCount: values.length,\n shownCount: items.length,\n omittedCount: Math.max(0, values.length - items.length),\n items,\n };\n}\n\nexport function positiveLimit(value: number | undefined): number {\n return Number.isFinite(value) && Number(value) > 0\n ? Math.floor(Number(value))\n : DEFAULT_EVIDENCE_CANDIDATE_LIMIT;\n}\n\nconst candidateLikeCollections = 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 'implementationHintSuggestions',\n 'selectableImplementationRepositories',\n 'matchedHints',\n 'candidateSuggestions',\n 'dynamicTargetCandidates',\n 'dynamicTargetCandidateSuggestions',\n 'rejectedCandidates',\n 'suggestedVarSets',\n 'copyableExamples',\n 'selectorSuggestions',\n 'serviceSuggestions',\n 'repositories',\n 'examples',\n 'expandedExamples',\n 'registrations',\n]);\n\n/**\n * Parser facts are retained in their tables; graph evidence only carries a\n * deterministic explanation. This prevents nested parser alternatives from\n * bypassing the graph evidence cap while leaving canonical facts queryable.\n */\nexport function boundCandidateLikeEvidence(\n evidence: Record<string, unknown>,\n limit = DEFAULT_EVIDENCE_CANDIDATE_LIMIT,\n): Record<string, unknown> {\n const output: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(evidence)) {\n if (!Array.isArray(value) || !candidateLikeCollections.has(key)) {\n output[key] = boundNestedEvidence(value, limit);\n continue;\n }\n const projection = projectBoundedInOrder(value, limit);\n output[key] = projection.items.map((item) => boundNestedEvidence(item, limit));\n addCollectionCounts(output, evidence, key, projection);\n }\n return output;\n}\n\nfunction boundNestedEvidence(value: unknown, limit: number): unknown {\n if (Array.isArray(value)) return value.map((item) => boundNestedEvidence(item, limit));\n if (!isEvidenceRecord(value)) return value;\n return boundCandidateLikeEvidence(value, limit);\n}\n\nfunction isEvidenceRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction addCollectionCounts(\n output: Record<string, unknown>,\n input: Record<string, unknown>,\n key: string,\n projection: BoundedProjection<unknown>,\n): void {\n const stem = collectionStem(key);\n const countName = `${stem}Count`;\n const shownName = `shown${upperFirst(stem)}Count`;\n const omittedName = `omitted${upperFirst(stem)}Count`;\n const total = Math.max(numericValue(input[countName]), projection.totalCount);\n output[countName] = total;\n output[shownName] = projection.shownCount;\n output[omittedName] = Math.max(0, total - projection.shownCount);\n}\n\nfunction collectionStem(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 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 selectorSuggestions: 'selectorSuggestion',\n serviceSuggestions: 'serviceSuggestion',\n repositories: 'repository',\n examples: 'example',\n expandedExamples: 'expandedExample',\n registrations: 'registration',\n };\n return stems[key] ?? 'candidate';\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 './connection.js';\nimport type {\n CdsRequire,\n CdsServiceFact,\n HandlerClassFact,\n HandlerMethodFact,\n HandlerRegistrationFact,\n ServiceBindingFact,\n ExecutableSymbolFact,\n} from '../types.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}\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,package_name,package_version,dependencies_json,kind,is_git_repo) VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(workspace_id,absolute_path) DO UPDATE SET name=excluded.name,relative_path=excluded.relative_path,package_name=excluded.package_name,package_version=excluded.package_version,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 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 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,helper_chain_json) VALUES(?,(SELECT id FROM symbols WHERE repo_id=? AND source_file=? AND start_line<=? AND end_line>=? ORDER BY (end_line-start_line),id LIMIT 1),?,?,?,?,?,?,?,?,?,?)',\n );\n for (const r of rows)\n stmt.run(\n repoId,\n repoId,\n r.sourceFile,\n r.sourceLine,\n r.sourceLine,\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.helperChain ? JSON.stringify(r.helperChain) : null,\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 { DiscoveredRepository } from '../types.js';\nimport { relativePath } from '../utils/path-utils.js';\nexport async function discoverRepositories(\n rootPath: string,\n ignore: readonly string[]\n): Promise<DiscoveredRepository[]> {\n const root = path.resolve(rootPath);\n const ignored = new Set(ignore);\n const found: DiscoveredRepository[] = [];\n async function isRealGitMarker(dir: string): Promise<boolean> {\n const gitPath = path.join(dir, '.git');\n try {\n const st = await fs.stat(gitPath);\n if (st.isDirectory()) {\n const children = await fs.readdir(gitPath);\n return children.includes('HEAD') || children.includes('config');\n }\n if (st.isFile()) {\n const text = await fs.readFile(gitPath, 'utf8');\n return text.trimStart().startsWith('gitdir:');\n }\n } catch {\n /* not a normal git marker */\n }\n try {\n const fixture = await fs.stat(path.join(dir, '.git-fixture'));\n return fixture.isFile() || fixture.isDirectory();\n } catch {\n return false;\n }\n }\n async function walk(dir: string): Promise<void> {\n const rel = relativePath(root, dir);\n if (rel !== '.' && rel.split('/').some((part) => ignored.has(part))) return;\n let entries: Array<{ name: string; isDirectory: () => boolean }>;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n const hasMarker = entries.some((e) => e.name === '.git' || e.name === '.git-fixture');\n if (hasMarker && await isRealGitMarker(dir)) {\n found.push({\n name: path.basename(dir),\n absolutePath: dir,\n relativePath: relativePath(root, dir),\n isGitRepo: true\n });\n }\n for (const entry of entries)\n if (entry.isDirectory() && !ignore.includes(entry.name))\n await walk(path.join(dir, entry.name));\n }\n await walk(root);\n return found.sort((a, b) => a.relativePath.localeCompare(b.relativePath));\n}\n","import path from 'node:path';\nexport function normalizePath(value: string): string {\n return value.split(path.sep).join('/');\n}\nexport function relativePath(root: string, value: string): string {\n return normalizePath(path.relative(root, value) || '.');\n}\nexport function ensureLeadingSlash(value: string): string {\n return value.startsWith('/') ? value : `/${value}`;\n}\nexport function stripQuotes(value: string): string {\n return value.replace(/^['\"`]|['\"`]$/g, '');\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { CdsRequire, PackageFacts } from '../types.js';\ninterface ParsePackageJsonOptions {\n strict?: boolean;\n allowMissing?: boolean;\n}\nexport interface PackageJsonSnapshot {\n facts: PackageFacts;\n rawText: string;\n}\nfunction emptyPackageFacts(): PackageFacts {\n return { dependencies: {}, cdsRequires: [], scripts: {} };\n}\nfunction recordOfString(value: unknown): Record<string, string> {\n if (!value || typeof value !== 'object') return {};\n return Object.fromEntries(\n Object.entries(value).filter(([, v]) => typeof v === 'string')\n ) as Record<string, string>;\n}\nfunction readRequires(cds: unknown): CdsRequire[] {\n const requires =\n cds && typeof cds === 'object' && 'requires' in cds\n ? (cds as { requires?: unknown }).requires\n : undefined;\n if (!requires || typeof requires !== 'object') return [];\n return Object.entries(requires).flatMap(([alias, raw]) => {\n if (!raw || typeof raw !== 'object') return [];\n const obj = raw as Record<string, unknown>;\n const credentials =\n obj.credentials && typeof obj.credentials === 'object'\n ? (obj.credentials as Record<string, unknown>)\n : {};\n return [\n {\n alias,\n kind: typeof obj.kind === 'string' ? obj.kind : undefined,\n model: typeof obj.model === 'string' ? obj.model : undefined,\n destination:\n typeof credentials.destination === 'string'\n ? credentials.destination\n : undefined,\n servicePath:\n typeof credentials.path === 'string' ? credentials.path : undefined,\n requestTimeout:\n typeof credentials.requestTimeout === 'number'\n ? credentials.requestTimeout\n : undefined,\n rawJson: JSON.stringify(raw)\n }\n ];\n });\n}\nexport async function parsePackageJson(\n repoPath: string,\n options: ParsePackageJsonOptions = {},\n): Promise<PackageFacts> {\n return (await loadPackageJsonSnapshot(repoPath, options)).facts;\n}\nexport async function loadPackageJsonSnapshot(\n repoPath: string,\n options: ParsePackageJsonOptions = {},\n): Promise<PackageJsonSnapshot> {\n try {\n const raw = await fs.readFile(path.join(repoPath, 'package.json'), 'utf8');\n const json = JSON.parse(raw) as Record<string, unknown>;\n return {\n rawText: raw,\n facts: {\n packageName: typeof json.name === 'string' ? json.name : undefined,\n packageVersion:\n typeof json.version === 'string' ? json.version : undefined,\n dependencies: {\n ...recordOfString(json.dependencies),\n ...recordOfString(json.devDependencies),\n },\n cdsRequires: readRequires(json.cds),\n scripts: recordOfString(json.scripts),\n },\n };\n } catch (error) {\n const missing = typeof error === 'object' && error !== null\n && 'code' in error && error.code === 'ENOENT';\n if (!options.strict || (options.allowMissing && missing))\n return { facts: emptyPackageFacts(), rawText: '' };\n throw error;\n }\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { CdsOperationFact, CdsServiceFact } from '../types.js';\nimport { ensureLeadingSlash, normalizePath } from '../utils/path-utils.js';\nimport type { RepositorySourceContext } from './ts-project.js';\n\nfunction lineOf(text: string, index: number): number {\n return text.slice(0, index).split('\\n').length;\n}\n\nfunction maskCommentsAndStrings(text: string): string {\n let out = '';\n let mode: 'code' | 'line' | 'block' | 'single' | 'double' | 'template' =\n 'code';\n for (let i = 0; i < text.length; i += 1) {\n const c = text[i] ?? '';\n const n = text[i + 1] ?? '';\n if (mode === 'code' && c === '/' && n === '/') {\n mode = 'line';\n out += ' ';\n i += 1;\n continue;\n }\n if (mode === 'code' && c === '/' && n === '*') {\n mode = 'block';\n out += ' ';\n i += 1;\n continue;\n }\n if (mode === 'line' && c === '\\n') mode = 'code';\n if (mode === 'block' && c === '*' && n === '/') {\n mode = 'code';\n out += ' ';\n i += 1;\n continue;\n }\n if (mode === 'code' && (c === \"'\" || c === '\"' || c === '`')) {\n mode = c === \"'\" ? 'single' : c === '\"' ? 'double' : 'template';\n out += ' ';\n continue;\n }\n if ((mode === 'single' && c === \"'\") || (mode === 'double' && c === '\"') || (mode === 'template' && c === '`'))\n mode = 'code';\n out += mode === 'code' || c === '\\n' ? c : ' ';\n }\n return out;\n}\n\nfunction maskComments(text: string): string {\n let out = '';\n let mode: 'code' | 'line' | 'block' | 'single' | 'double' | 'template' = 'code';\n for (let i = 0; i < text.length; i += 1) {\n const c = text[i] ?? '';\n const n = text[i + 1] ?? '';\n if (mode === 'code' && c === '/' && n === '/') { mode = 'line'; out += ' '; i += 1; continue; }\n if (mode === 'code' && c === '/' && n === '*') { mode = 'block'; out += ' '; i += 1; continue; }\n if (mode === 'line' && c === '\\n') mode = 'code';\n if (mode === 'block' && c === '*' && n === '/') { mode = 'code'; out += ' '; i += 1; continue; }\n if (mode === 'code' && (c === \"'\" || c === '\"' || c === '`')) mode = c === \"'\" ? 'single' : c === '\"' ? 'double' : 'template';\n else if ((mode === 'single' && c === \"'\") || (mode === 'double' && c === '\"') || (mode === 'template' && c === '`')) mode = 'code';\n out += mode === 'line' || mode === 'block' ? (c === '\\n' ? '\\n' : ' ') : c;\n }\n return out;\n}\n\nfunction readAnnotation(text: string, index: number): { end: number; raw: string } | undefined {\n if (text[index] !== '@') return undefined;\n let i = index + 1;\n while (/\\s/.test(text[i] ?? '')) i += 1;\n if (text[i] !== '(') return undefined;\n let depth = 0;\n for (; i < text.length; i += 1) {\n if (text[i] === '(') depth += 1;\n if (text[i] === ')') depth -= 1;\n if (depth === 0) return { end: i + 1, raw: text.slice(index, i + 1) };\n }\n return undefined;\n}\n\nfunction collectAnnotations(text: string, index: number): { end: number; raw: string } {\n let i = index;\n let raw = '';\n while (i < text.length) {\n while (/\\s/.test(text[i] ?? '')) i += 1;\n const annotation = readAnnotation(text, i);\n if (!annotation) break;\n raw += annotation.raw;\n i = annotation.end;\n }\n return { end: i, raw };\n}\n\nfunction pathAnnotation(raw: string): string | undefined {\n return /path\\s*:\\s*(['\"])(.*?)\\1/s.exec(raw)?.[2];\n}\n\nfunction matchingBrace(maskedText: string, open: number): number {\n let depth = 0;\n for (let i = open; i < maskedText.length; i += 1) {\n if (maskedText[i] === '{') depth += 1;\n if (maskedText[i] === '}') depth -= 1;\n if (depth === 0) return i;\n }\n return maskedText.length - 1;\n}\nfunction annotationRawAt(original: string, masked: string, index: number): { end: number; raw: string } {\n const collected = collectAnnotations(masked, index);\n return { end: collected.end, raw: original.slice(index, collected.end) };\n}\n\n\ninterface CdsUsing { importedSymbol: string; localAlias: string; moduleSpecifier: string; importKind: 'relative' | 'package' }\nfunction collectUsings(masked: string): Map<string, CdsUsing> {\n const imports = new Map<string, CdsUsing>();\n for (const m of masked.matchAll(/\\busing\\s*\\{([^}]*)\\}\\s*from\\s*(['\"])(.*?)\\2\\s*;/gs)) {\n const moduleSpecifier = m[3] ?? '';\n for (const part of (m[1] ?? '').split(',')) {\n const text = part.trim();\n if (!text) continue;\n const alias = /^(\\w+)\\s+as\\s+(\\w+)$/.exec(text) ?? /^(\\w+)\\s*:\\s*(\\w+)$/.exec(text);\n const importedSymbol = alias?.[1] ?? text;\n const localAlias = alias?.[2] ?? importedSymbol;\n imports.set(localAlias, { importedSymbol, localAlias, moduleSpecifier, importKind: moduleSpecifier.startsWith('.') ? 'relative' : 'package' });\n }\n }\n return imports;\n}\nfunction operationsFromBody(text: string, maskedBody: string, bodyOffset: number, filePath: string): CdsOperationFact[] {\n return [...maskedBody.matchAll(/\\b(action|function|event)\\s+(\\w+)\\s*(?:\\(([^)]*)\\))?\\s*(?:returns\\s+([^;{]+))?/g)].map((m) => ({\n operationType: (m[1] as 'action' | 'function' | 'event') ?? 'action',\n operationName: m[2] ?? 'unknown',\n operationPath: ensureLeadingSlash(m[2] ?? 'unknown'),\n paramsJson: JSON.stringify((m[3] ?? '').split(',').map((part) => part.trim()).filter(Boolean)),\n returnType: m[4]?.trim(),\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(text, bodyOffset + (m.index ?? 0))\n }));\n}\n\nexport async function parseCdsFile(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n): Promise<CdsServiceFact[]> {\n const absolute = path.join(repoPath, filePath);\n const text = context?.get(filePath)?.text\n ?? await fs.readFile(absolute, 'utf8');\n const masked = maskCommentsAndStrings(text);\n const namespace = /namespace\\s+([\\w.]+)\\s*;/.exec(masked)?.[1];\n const services: CdsServiceFact[] = [];\n const pendingAnnotations: Array<{ end: number; raw: string }> = [];\n const usings = collectUsings(maskComments(text));\n for (const a of masked.matchAll(/@\\s*\\(/g)) pendingAnnotations.push(annotationRawAt(text, masked, a.index ?? 0));\n const serviceRegex = /\\b(?:(extend)\\s+)?(?:(service)\\s+)?([A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*)\\b/g;\n let match: RegExpExecArray | null;\n while ((match = serviceRegex.exec(masked))) {\n const isExtend = match[1] === 'extend';\n const hasServiceKeyword = match[2] === 'service';\n if (!isExtend && !hasServiceKeyword) continue;\n const afterName = annotationRawAt(text, masked, serviceRegex.lastIndex);\n const open = masked.indexOf('{', afterName.end);\n if (open === -1) continue;\n const between = masked.slice(afterName.end, open).trim();\n if (between.length > 0) continue;\n const matchIndex = match.index;\n const prefix = pendingAnnotations\n .filter((a) => a.end <= matchIndex && matchIndex - a.end < 8)\n .map((a) => a.raw)\n .join('');\n const annotations = `${prefix}${afterName.raw}`;\n const end = matchingBrace(masked, open);\n const body = masked.slice(open + 1, end);\n const name = match[3] ?? 'UnknownService';\n const serviceName = name.split('.').pop() ?? name;\n const imported = isExtend ? usings.get(name) ?? usings.get(serviceName) : undefined;\n const servicePath = ensureLeadingSlash(pathAnnotation(annotations) ?? serviceName);\n services.push({\n namespace,\n serviceName,\n qualifiedName: name.includes('.') ? name : namespace ? `${namespace}.${name}` : name,\n servicePath,\n isExtend,\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(text, match.index),\n operations: operationsFromBody(text, body, open + 1, filePath),\n extension: isExtend ? { localReference: name, importedSymbol: imported?.importedSymbol, localAlias: imported?.localAlias, moduleSpecifier: imported?.moduleSpecifier, importKind: imported?.importKind ?? 'none' } : undefined\n });\n serviceRegex.lastIndex = end + 1;\n }\n const baseOps = new Map(services.filter((s) => !s.isExtend).map((s) => [s.qualifiedName, s.operations]));\n for (const service of services.filter((s) => s.isExtend && s.operations.length === 0)) {\n if (service.extension?.moduleSpecifier) continue;\n const inherited = baseOps.get(service.qualifiedName) ?? baseOps.get(service.serviceName);\n if (inherited) service.operations = inherited.map((op) => ({ ...op, provenance: 'inherited' }));\n }\n return services;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport ts from 'typescript';\nimport type {\n HandlerClassFact,\n HandlerLifecycleEvent,\n HandlerLifecyclePhase,\n HandlerMethodFact,\n HandlerMethodKind,\n} from '../types.js';\nimport { generatedOperationNameFromConstant } from '../linker/operation-decorator-normalizer.js';\nimport {\n createSourceFile,\n type RepositorySourceContext,\n} from './ts-project.js';\nimport { normalizePath } from '../utils/path-utils.js';\n\ntype DecoratorResolution = HandlerMethodFact['decoratorResolution'];\ntype ResolvedArgumentKind = Exclude<\n DecoratorResolution['resolutionKind'],\n 'lifecycle_implicit' | 'unresolved'\n>;\ninterface StringLookups {\n identifiers: Map<string, string>;\n enumMembers: Map<string, string>;\n objectProperties: Map<string, string>;\n capDecoratorNames: Map<string, string>;\n capDecoratorNamespaces: Set<string>;\n}\ninterface LifecycleMetadata {\n phase: HandlerLifecyclePhase;\n event: HandlerLifecycleEvent;\n}\ninterface MethodClassification {\n handlerKind: HandlerMethodKind;\n executable: boolean;\n lifecyclePhase?: HandlerLifecyclePhase;\n lifecycleEvent?: HandlerLifecycleEvent;\n}\ninterface ParsedMethodDecorator {\n classification: MethodClassification;\n resolution: DecoratorResolution;\n decoratorKind: string;\n importedKind?: string;\n}\n\nconst OPERATION_DECORATORS = new Set(['Action', 'Func', 'On']);\nconst EVENT_DECORATORS = new Set(['Event']);\nconst LIFECYCLE_DECORATORS = new Map<string, LifecycleMetadata>([\n ['BeforeCreate', { phase: 'before', event: 'CREATE' }],\n ['OnCreate', { phase: 'on', event: 'CREATE' }],\n ['AfterCreate', { phase: 'after', event: 'CREATE' }],\n ['BeforeRead', { phase: 'before', event: 'READ' }],\n ['OnRead', { phase: 'on', event: 'READ' }],\n ['AfterRead', { phase: 'after', event: 'READ' }],\n ['BeforeUpdate', { phase: 'before', event: 'UPDATE' }],\n ['OnUpdate', { phase: 'on', event: 'UPDATE' }],\n ['AfterUpdate', { phase: 'after', event: 'UPDATE' }],\n ['BeforeDelete', { phase: 'before', event: 'DELETE' }],\n ['OnDelete', { phase: 'on', event: 'DELETE' }],\n ['AfterDelete', { phase: 'after', event: 'DELETE' }],\n]);\n\nfunction line(sf: ts.SourceFile, pos: number): number {\n return sf.getLineAndCharacterOfPosition(pos).line + 1;\n}\nfunction decs(node: ts.Node): ts.Decorator[] {\n return ts.canHaveDecorators(node) ? [...(ts.getDecorators(node) ?? [])] : [];\n}\nfunction callName(d: ts.Decorator): string {\n const e = d.expression;\n return ts.isCallExpression(e) ? e.expression.getText() : e.getText();\n}\nfunction firstArg(d: ts.Decorator): ts.Expression | undefined {\n const e = d.expression;\n return ts.isCallExpression(e) ? e.arguments[0] : undefined;\n}\nfunction decoratorArguments(d: ts.Decorator): readonly ts.Expression[] | undefined {\n return ts.isCallExpression(d.expression) ? d.expression.arguments : undefined;\n}\nfunction methodName(name: ts.PropertyName): string {\n return ts.isIdentifier(name) || ts.isStringLiteralLike(name)\n || ts.isNumericLiteral(name)\n ? name.text\n : name.getText();\n}\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression;\n while (\n ts.isParenthesizedExpression(current)\n || ts.isAsExpression(current)\n || ts.isTypeAssertionExpression(current)\n || ts.isSatisfiesExpression(current)\n ) current = current.expression;\n return current;\n}\nfunction stringValue(expression: ts.Expression | undefined): string | undefined {\n if (!expression) return undefined;\n const unwrapped = unwrapExpression(expression);\n return ts.isStringLiteralLike(unwrapped) ? unwrapped.text : undefined;\n}\nfunction propertyName(node: ts.PropertyName): string | undefined {\n if (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) return node.text;\n return undefined;\n}\nfunction collectEnumMembers(\n statement: ts.EnumDeclaration,\n lookups: StringLookups,\n): void {\n for (const member of statement.members) {\n const name = propertyName(member.name);\n const value = stringValue(member.initializer);\n if (name && value !== undefined)\n lookups.enumMembers.set(`${statement.name.text}.${name}`, value);\n }\n}\nfunction collectObjectProperties(\n name: string,\n initializer: ts.Expression,\n lookups: StringLookups,\n): void {\n const object = unwrapExpression(initializer);\n if (!ts.isObjectLiteralExpression(object)) return;\n for (const property of object.properties) {\n if (!ts.isPropertyAssignment(property)) continue;\n const key = propertyName(property.name);\n const value = stringValue(property.initializer);\n if (key && value !== undefined)\n lookups.objectProperties.set(`${name}.${key}`, value);\n }\n}\nfunction collectStringLookups(source: ts.SourceFile): StringLookups {\n const lookups: StringLookups = {\n identifiers: new Map(),\n enumMembers: new Map(),\n objectProperties: new Map(),\n capDecoratorNames: new Map(),\n capDecoratorNamespaces: new Set(),\n };\n for (const statement of source.statements) {\n collectCapDecoratorImports(statement, lookups);\n if (ts.isEnumDeclaration(statement)) collectEnumMembers(statement, lookups);\n if (!ts.isVariableStatement(statement)\n || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;\n const value = stringValue(declaration.initializer);\n if (value !== undefined) lookups.identifiers.set(declaration.name.text, value);\n collectObjectProperties(declaration.name.text, declaration.initializer, lookups);\n }\n }\n return lookups;\n}\nfunction collectCapDecoratorImports(\n statement: ts.Statement,\n lookups: StringLookups,\n): void {\n if (!ts.isImportDeclaration(statement)\n || !ts.isStringLiteral(statement.moduleSpecifier)\n || statement.moduleSpecifier.text !== 'cds-routing-handlers') return;\n const clause = statement.importClause;\n if (!clause || clause.isTypeOnly) return;\n const bindings = clause.namedBindings;\n if (bindings && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) {\n if (element.isTypeOnly) continue;\n lookups.capDecoratorNames.set(\n element.name.text,\n element.propertyName?.text ?? element.name.text,\n );\n }\n }\n if (bindings && ts.isNamespaceImport(bindings))\n lookups.capDecoratorNamespaces.add(bindings.name.text);\n}\nfunction capDecoratorName(\n decorator: ts.Decorator,\n lookups: StringLookups,\n): string | undefined {\n const expression = ts.isCallExpression(decorator.expression)\n ? decorator.expression.expression\n : decorator.expression;\n if (ts.isIdentifier(expression))\n return lookups.capDecoratorNames.get(expression.text);\n if (ts.isPropertyAccessExpression(expression)\n && ts.isIdentifier(expression.expression)\n && lookups.capDecoratorNamespaces.has(expression.expression.text))\n return expression.name.text;\n return undefined;\n}\nfunction unresolved(\n rawExpression: string,\n reason: string,\n argumentExpression?: string,\n): DecoratorResolution {\n return {\n rawExpression,\n argumentExpression,\n resolutionKind: 'unresolved',\n unresolvedReason: reason,\n };\n}\nfunction resolved(\n rawExpression: string,\n argumentExpression: string,\n resolvedValue: string,\n resolutionKind: ResolvedArgumentKind,\n): DecoratorResolution {\n return { rawExpression, argumentExpression, resolvedValue, resolutionKind };\n}\nfunction generatedConstant(rawExpression: string): string | undefined {\n const match = /(?:^|\\.)(Action[A-Z][\\w$]*|Func[A-Z][\\w$]*)\\.name$/\n .exec(rawExpression.trim());\n return match?.[1]\n ? generatedOperationNameFromConstant(match[1])\n : undefined;\n}\nfunction resolveDecoratorArgument(\n argument: ts.Expression | undefined,\n lookups: StringLookups,\n rawExpression: string,\n): DecoratorResolution {\n if (!argument) return unresolved(rawExpression, 'decorator_argument_missing');\n const argumentExpression = argument.getText();\n const expression = unwrapExpression(argument);\n if (ts.isStringLiteralLike(expression))\n return resolved(rawExpression, argumentExpression, expression.text, 'literal');\n if (ts.isIdentifier(expression)) {\n const value = lookups.identifiers.get(expression.text);\n return value === undefined\n ? unresolved(rawExpression, 'identifier_not_resolved_to_local_const_string', argumentExpression)\n : resolved(rawExpression, argumentExpression, value, 'const_identifier');\n }\n if (ts.isPropertyAccessExpression(expression)\n && ts.isIdentifier(expression.expression)) {\n const key = `${expression.expression.text}.${expression.name.text}`;\n const enumValue = lookups.enumMembers.get(key);\n if (enumValue !== undefined)\n return resolved(rawExpression, argumentExpression, enumValue, 'enum_member');\n const objectValue = lookups.objectProperties.get(key);\n if (objectValue !== undefined)\n return resolved(rawExpression, argumentExpression, objectValue, 'const_object_property');\n }\n const generatedValue = generatedConstant(argumentExpression);\n if (generatedValue !== undefined)\n return resolved(\n rawExpression,\n argumentExpression,\n generatedValue,\n 'generated_constant_name',\n );\n if (ts.isPropertyAccessExpression(expression))\n return unresolved(\n rawExpression,\n 'property_access_not_resolved_to_local_string',\n argumentExpression,\n );\n return unresolved(rawExpression, 'unsupported_decorator_expression', argumentExpression);\n}\nfunction classificationFor(name: string): MethodClassification | undefined {\n if (OPERATION_DECORATORS.has(name))\n return { handlerKind: 'operation', executable: true };\n if (EVENT_DECORATORS.has(name))\n return { handlerKind: 'event', executable: true };\n const lifecycle = LIFECYCLE_DECORATORS.get(name);\n if (!lifecycle) return undefined;\n return {\n handlerKind: 'entity_lifecycle',\n executable: true,\n lifecyclePhase: lifecycle.phase,\n lifecycleEvent: lifecycle.event,\n };\n}\nfunction lifecycleLikePhase(name: string): HandlerLifecyclePhase | undefined {\n if (/^On[A-Z]/.test(name)) return 'on';\n if (/^Before[A-Z]/.test(name)) return 'before';\n if (/^After[A-Z]/.test(name)) return 'after';\n return undefined;\n}\nfunction withClassification(\n resolution: DecoratorResolution,\n classification: MethodClassification,\n): DecoratorResolution {\n return {\n ...resolution,\n handlerKind: classification.handlerKind,\n executable: classification.executable,\n lifecyclePhase: classification.lifecyclePhase,\n lifecycleEvent: classification.lifecycleEvent,\n };\n}\nfunction withDecoratorEvidence(\n resolution: DecoratorResolution,\n decorator: ts.Decorator,\n resolvedDecoratorKind: string | undefined,\n): DecoratorResolution {\n return {\n ...resolution,\n decoratorExpression: decorator.expression.getText(),\n resolvedDecoratorKind,\n decoratorImportSource: resolvedDecoratorKind\n ? 'cds-routing-handlers'\n : undefined,\n };\n}\nfunction lifecycleDecoratorResolution(\n decorator: ts.Decorator,\n lookups: StringLookups,\n classification: MethodClassification,\n): { classification: MethodClassification; resolution: DecoratorResolution } {\n const rawExpression = decorator.expression.getText();\n const args = decoratorArguments(decorator);\n if (args?.length === 0)\n return {\n classification,\n resolution: withClassification({\n rawExpression,\n resolutionKind: 'lifecycle_implicit',\n }, classification),\n };\n const resolution = args?.length === 1\n ? resolveDecoratorArgument(args[0], lookups, rawExpression)\n : unresolved(rawExpression, args ? 'unsupported_lifecycle_argument_count' : 'lifecycle_decorator_call_required');\n const unsupported = { ...classification, handlerKind: 'unsupported_lifecycle', executable: false } as const;\n const unsupportedResolution = args?.length === 1\n ? { ...resolution, unresolvedReason: 'lifecycle_decorator_arguments_not_supported' }\n : resolution;\n return {\n classification: unsupported,\n resolution: withClassification(unsupportedResolution, unsupported),\n };\n}\nfunction unsupportedLifecycleResolution(\n decorator: ts.Decorator,\n phase: HandlerLifecyclePhase,\n): { classification: MethodClassification; resolution: DecoratorResolution } {\n const classification: MethodClassification = {\n handlerKind: 'unsupported_lifecycle',\n executable: false,\n lifecyclePhase: phase,\n };\n const resolution = unresolved(\n decorator.expression.getText(),\n 'lifecycle_decorator_not_allowlisted',\n );\n return { classification, resolution: withClassification(resolution, classification) };\n}\nfunction unsupportedDecoratorResolution(\n decorator: ts.Decorator,\n reason: string,\n phase?: HandlerLifecyclePhase,\n): { classification: MethodClassification; resolution: DecoratorResolution } {\n const classification: MethodClassification = {\n handlerKind: phase ? 'unsupported_lifecycle' : 'unsupported_decorator',\n executable: false,\n lifecyclePhase: phase,\n };\n return {\n classification,\n resolution: withClassification(\n unresolved(decorator.expression.getText(), reason),\n classification,\n ),\n };\n}\nfunction parseMethodDecorator(\n decorator: ts.Decorator,\n lookups: StringLookups,\n handlerClass: boolean,\n allowLifecycle: boolean,\n): ParsedMethodDecorator | undefined {\n const decoratorKind = callName(decorator);\n const importedKind = capDecoratorName(decorator, lookups);\n const resolvedKind = importedKind ?? decoratorKind;\n const base = classificationFor(resolvedKind);\n const phase = lifecycleLikePhase(resolvedKind);\n const isLifecycle = base?.handlerKind === 'entity_lifecycle' || Boolean(phase && !base);\n if (!handlerClass && isLifecycle) return undefined;\n const parsed = isLifecycle && (!allowLifecycle || !importedKind)\n ? unsupportedDecoratorResolution(\n decorator, 'lifecycle_decorator_import_not_supported', phase,\n )\n : base?.handlerKind === 'entity_lifecycle'\n ? lifecycleDecoratorResolution(decorator, lookups, base)\n : phase && !base\n ? unsupportedLifecycleResolution(decorator, phase)\n : !base && handlerClass\n ? unsupportedDecoratorResolution(decorator, 'decorator_not_allowlisted')\n : {\n classification: base,\n resolution: resolveDecoratorArgument(\n firstArg(decorator),\n lookups,\n firstArg(decorator)?.getText() ?? decorator.expression.getText(),\n ),\n };\n if (!parsed.classification) return undefined;\n return {\n classification: parsed.classification,\n resolution: parsed.resolution,\n decoratorKind,\n importedKind,\n };\n}\nfunction methodDecoratorFact(\n method: ts.MethodDeclaration,\n decorator: ts.Decorator,\n lookups: StringLookups,\n source: ts.SourceFile,\n filePath: string,\n handlerClass: boolean,\n allowLifecycle: boolean,\n): HandlerMethodFact | undefined {\n const parsed = parseMethodDecorator(decorator, lookups, handlerClass, allowLifecycle);\n if (!parsed) return undefined;\n const classification = method.body\n ? parsed.classification\n : { ...parsed.classification, executable: false };\n const resolution = method.body\n ? parsed.resolution\n : { ...parsed.resolution, unresolvedReason: 'handler_method_body_missing' };\n const argumentExpression = firstArg(decorator)?.getText();\n return {\n methodName: methodName(method.name),\n decoratorKind: parsed.decoratorKind,\n decoratorValue: parsed.resolution.resolvedValue,\n decoratorRawExpression: argumentExpression ?? decorator.expression.getText(),\n handlerKind: classification.handlerKind,\n executable: classification.executable,\n lifecyclePhase: classification.lifecyclePhase,\n lifecycleEvent: classification.lifecycleEvent,\n decoratorResolution: withDecoratorEvidence(\n withClassification(resolution, classification),\n decorator,\n parsed.importedKind,\n ),\n sourceFile: normalizePath(filePath),\n sourceLine: line(source, method.getStart()),\n };\n}\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\nfunction parseClassMethods(\n node: ts.ClassDeclaration,\n lookups: StringLookups,\n source: ts.SourceFile,\n filePath: string,\n handlerClass: boolean,\n allowLifecycle: boolean,\n): Pick<HandlerClassFact, 'methods' | 'observedDecoratorNames' | 'unsupportedDecoratorNames'> {\n const methods: HandlerMethodFact[] = [];\n const observed: string[] = [];\n const unsupported: string[] = [];\n for (const method of node.members.filter(ts.isMethodDeclaration)) {\n for (const decorator of decs(method)) {\n observed.push(callName(decorator));\n const fact = methodDecoratorFact(\n method, decorator, lookups, source, filePath, handlerClass, allowLifecycle,\n );\n if (fact) methods.push(fact);\n if (!fact?.executable) unsupported.push(callName(decorator));\n }\n }\n return {\n methods,\n observedDecoratorNames: unique(observed),\n unsupportedDecoratorNames: unique(unsupported),\n };\n}\nfunction parseHandlerClass(\n node: ts.ClassDeclaration,\n lookups: StringLookups,\n source: ts.SourceFile,\n filePath: string,\n): HandlerClassFact | undefined {\n const classDecoratorNames = unique(decs(node).map(callName));\n const classDecorators = decs(node);\n const hasImportedHandler = classDecorators.some((decorator) =>\n capDecoratorName(decorator, lookups) === 'Handler');\n const hasHandlerDecorator = hasImportedHandler\n || classDecoratorNames.includes('Handler');\n const parsed = parseClassMethods(\n node, lookups, source, filePath, hasHandlerDecorator, hasImportedHandler,\n );\n if (!hasHandlerDecorator && parsed.methods.length === 0) return undefined;\n return {\n className: node.name?.text ?? 'AnonymousHandler',\n sourceFile: normalizePath(filePath),\n sourceLine: line(source, node.getStart()),\n ...parsed,\n hasHandlerDecorator,\n classDecoratorNames,\n };\n}\nexport async function parseDecorators(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n): Promise<HandlerClassFact[]> {\n const snapshot = context?.get(filePath);\n const text = snapshot?.text\n ?? await fs.readFile(path.join(repoPath, filePath), 'utf8');\n const sf = snapshot?.sourceFile() ?? createSourceFile(filePath, text);\n const lookups = collectStringLookups(sf);\n const handlers: HandlerClassFact[] = [];\n function visit(node: ts.Node): void {\n if (ts.isClassDeclaration(node)) {\n const handler = parseHandlerClass(node, lookups, sf, filePath);\n if (handler) handlers.push(handler);\n }\n ts.forEachChild(node, visit);\n }\n visit(sf);\n return handlers;\n}\n","function lowerFirst(value: string): string {\n return value ? `${value[0]?.toLowerCase() ?? ''}${value.slice(1)}` : value;\n}\nexport type DecoratorOperationSignal =\n | { status: 'resolved'; operationName: string; raw?: string }\n | { status: 'none'; raw?: string }\n | { status: 'unsupported'; raw: string; reason: string }\n | { status: 'malformed'; raw: string; reason: string };\nexport function normalizedOperationName(value: string): string {\n return value.replace(/^\\//, '');\n}\nfunction clean(value: string): string {\n return value.replace(/^[`'\"]|[`'\"]$/g, '');\n}\nexport function generatedOperationNameFromConstant(value: string): string | undefined {\n for (const prefix of ['Action', 'Func']) {\n if (value.startsWith(prefix) && value.length > prefix.length && /^[A-Z]/.test(value.slice(prefix.length))) return lowerFirst(value.slice(prefix.length));\n }\n return undefined;\n}\nfunction resolved(value: string, raw?: string): DecoratorOperationSignal {\n const literal = clean(value);\n const generated = generatedOperationNameFromConstant(literal);\n return { status: 'resolved', operationName: generated ?? normalizedOperationName(literal), raw };\n}\nexport function normalizeDecoratorOperationSignal(value: string | undefined, raw: string | undefined, candidateOperation?: string): DecoratorOperationSignal {\n if (value) return resolved(value, raw);\n if (!raw || raw.trim().length === 0) return { status: 'none', raw };\n const expression = raw.trim();\n const nameMatch = /(?:^|\\.)(Action[A-Z][\\w$]*|Func[A-Z][\\w$]*)\\.name$/.exec(expression);\n if (nameMatch?.[1]) return resolved(nameMatch[1], expression);\n const stringMatch = /^String\\(([A-Za-z_$][\\w$]*)\\)$/.exec(expression);\n if (stringMatch?.[1]) {\n const identifier = stringMatch[1];\n const generated = generatedOperationNameFromConstant(identifier);\n const normalizedCandidate = candidateOperation ? normalizedOperationName(candidateOperation) : undefined;\n if (generated) return { status: 'resolved', operationName: generated, raw: expression };\n if (normalizedCandidate && identifier === normalizedCandidate) return { status: 'resolved', operationName: identifier, raw: expression };\n return { status: 'unsupported', raw: expression, reason: 'string_wrapper_identifier_not_resolved' };\n }\n if (/^[`'\"]/.test(expression) && !/[`'\"]$/.test(expression)) return { status: 'malformed', raw: expression, reason: 'unterminated_literal' };\n return { status: 'unsupported', raw: expression, reason: 'unsupported_decorator_expression' };\n}\nexport function normalizeDecoratorOperation(value: string | undefined, raw: string | undefined): string | undefined {\n const signal = normalizeDecoratorOperationSignal(value, raw);\n return signal.status === 'resolved' ? signal.operationName : undefined;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport ts from 'typescript';\nimport { normalizePath } from '../utils/path-utils.js';\n\nexport interface SourceContextInstrumentation {\n onSourceRead?: (\n repoPath: string,\n filePath: string,\n ) => void | Promise<void>;\n onAstCreated?: (repoPath: string, filePath: string) => void;\n}\n\nexport interface SourceFileSnapshot {\n repoPath: string;\n filePath: string;\n text: string;\n sizeBytes: number;\n sourceFile: () => ts.SourceFile;\n}\n\nexport interface RepositorySourceContext {\n get: (filePath: string) => SourceFileSnapshot | undefined;\n entries: () => SourceFileSnapshot[];\n}\n\nexport async function loadRepositorySourceContext(\n repoPath: string,\n filePaths: string[],\n instrumentation?: SourceContextInstrumentation,\n): Promise<RepositorySourceContext> {\n const snapshots = new Map<string, SourceFileSnapshot>();\n for (const inputPath of filePaths) {\n const filePath = normalizePath(inputPath);\n await instrumentation?.onSourceRead?.(repoPath, filePath);\n const text = await fs.readFile(path.join(repoPath, filePath), 'utf8');\n let ast: ts.SourceFile | undefined;\n snapshots.set(filePath, {\n repoPath,\n filePath,\n text,\n sizeBytes: Buffer.byteLength(text),\n sourceFile: () => {\n if (ast) return ast;\n instrumentation?.onAstCreated?.(repoPath, filePath);\n ast = createSourceFile(filePath, text);\n return ast;\n },\n });\n }\n return {\n get: (filePath) => snapshots.get(normalizePath(filePath)),\n entries: () => [...snapshots.values()],\n };\n}\nexport function createSourceFile(\n filePath: string,\n text: string\n): ts.SourceFile {\n return ts.createSourceFile(\n filePath,\n text,\n ts.ScriptTarget.Latest,\n true,\n filePath.endsWith('.js') ? ts.ScriptKind.JS : ts.ScriptKind.TS\n );\n}\n","import fsSync from 'node:fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport ts from 'typescript';\nimport type { HandlerRegistrationFact } from '../types.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport type { RepositorySourceContext } from './ts-project.js';\n\ninterface ImportEvidence { importedName: string; source: string }\ninterface ClassEvidence { className: string; importSource?: string }\ninterface FileExports { arrays: Map<string, ClassEvidence[]>; defaultArray?: ClassEvidence[]; aliases: Map<string, string> }\n\nconst MAX_EXPORT_DEPTH = 5;\n\nfunction lineOf(sourceFile: ts.SourceFile, node: ts.Node): number {\n return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;\n}\nfunction isRelative(source: string): boolean {\n return source.startsWith('./') || source.startsWith('../');\n}\nfunction sourceText(node: ts.PropertyName, sourceFile: ts.SourceFile): string | undefined {\n if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return node.text;\n return node.getText(sourceFile);\n}\nfunction importSourceFor(identifier: string, imports: Map<string, ImportEvidence>): string | undefined {\n const evidence = imports.get(identifier);\n return evidence ? `${evidence.source}#${evidence.importedName}` : undefined;\n}\n\nexport async function parseHandlerRegistrations(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n): Promise<HandlerRegistrationFact[]> {\n const absolutePath = path.join(repoPath, filePath);\n const snapshot = context?.get(filePath);\n const text = snapshot?.text ?? await fs.readFile(absolutePath, 'utf8');\n const sourceFile = snapshot?.sourceFile() ?? ts.createSourceFile(\n filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS,\n );\n const imports = collectImports(sourceFile);\n const localArrays = collectLocalArrays(\n sourceFile, imports, new Map(), repoPath, filePath, context,\n );\n const out: HandlerRegistrationFact[] = [];\n function emitFromExpression(expression: ts.Expression, call: ts.CallExpression): void {\n const classes = resolveArrayExpression(\n expression, localArrays, imports, repoPath, filePath, new Set(), context,\n );\n for (const cls of classes) {\n out.push({\n className: cls.className,\n importSource: cls.importSource,\n registrationFile: normalizePath(filePath),\n registrationLine: lineOf(sourceFile, call),\n registrationKind: 'combined-handler-class',\n confidence: 0.95,\n });\n }\n if (classes.length === 0) {\n out.push({\n registrationFile: normalizePath(filePath),\n registrationLine: lineOf(sourceFile, call),\n registrationKind: 'combined-handler',\n confidence: 0.75,\n });\n }\n }\n function visit(node: ts.Node): void {\n if (ts.isCallExpression(node) && isRegistrationCall(node)) {\n const handlerExpr = handlerExpression(node, sourceFile);\n if (handlerExpr) emitFromExpression(handlerExpr, node);\n else out.push({ registrationFile: normalizePath(filePath), registrationLine: lineOf(sourceFile, node), registrationKind: 'combined-handler', confidence: 0.75 });\n }\n ts.forEachChild(node, visit);\n }\n visit(sourceFile);\n return out;\n}\n\nfunction isRegistrationCall(call: ts.CallExpression): boolean {\n const text = call.expression.getText();\n return text.endsWith('createCombinedHandler') || text.endsWith('srv.prepend') || text.endsWith('cds.serve');\n}\nfunction handlerExpression(call: ts.CallExpression, sourceFile: ts.SourceFile): ts.Expression | undefined {\n for (const arg of call.arguments) {\n if (!ts.isObjectLiteralExpression(arg)) continue;\n for (const prop of arg.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n if (sourceText(prop.name, sourceFile) === 'handler') return prop.initializer;\n }\n }\n return undefined;\n}\nfunction collectImports(sourceFile: ts.SourceFile): Map<string, ImportEvidence> {\n const imports = new Map<string, ImportEvidence>();\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;\n const source = statement.moduleSpecifier.text;\n const clause = statement.importClause;\n if (!clause) continue;\n if (clause.name) imports.set(clause.name.text, { importedName: 'default', source });\n const named = clause.namedBindings;\n if (named && ts.isNamedImports(named)) {\n for (const element of named.elements) imports.set(element.name.text, { importedName: element.propertyName?.text ?? element.name.text, source });\n }\n if (named && ts.isNamespaceImport(named)) imports.set(named.name.text, { importedName: '*', source });\n }\n return imports;\n}\nfunction collectLocalArrays(sourceFile: ts.SourceFile, imports: Map<string, ImportEvidence>, seed: Map<string, ClassEvidence[]>, repoPath = '', fromFile = '', context?: RepositorySourceContext): Map<string, ClassEvidence[]> {\n const arrays = new Map(seed);\n for (const statement of sourceFile.statements) {\n if (ts.isVariableStatement(statement)) {\n for (const decl of statement.declarationList.declarations) {\n if (ts.isIdentifier(decl.name) && decl.initializer && ts.isArrayLiteralExpression(decl.initializer)) {\n arrays.set(decl.name.text, resolveArrayLiteral(\n decl.initializer, arrays, imports, repoPath, fromFile, new Set(), context,\n ));\n }\n }\n }\n }\n return arrays;\n}\nfunction resolveArrayExpression(expr: ts.Expression, arrays: Map<string, ClassEvidence[]>, imports: Map<string, ImportEvidence>, repoPath: string, fromFile: string, seen: Set<string>, context?: RepositorySourceContext): ClassEvidence[] {\n if (ts.isArrayLiteralExpression(expr)) return resolveArrayLiteral(expr, arrays, imports, repoPath, fromFile, seen, context);\n if (ts.isIdentifier(expr)) {\n const local = arrays.get(expr.text);\n if (local) return local;\n const evidence = imports.get(expr.text);\n if (evidence && isRelative(evidence.source)) return resolveImportedArray(repoPath, fromFile, evidence, seen, context);\n if (evidence) return [{ className: evidence.importedName === 'default' ? expr.text : evidence.importedName, importSource: `${evidence.source}#${evidence.importedName}` }];\n }\n return [];\n}\nfunction resolveArrayLiteral(array: ts.ArrayLiteralExpression, arrays: Map<string, ClassEvidence[]>, imports: Map<string, ImportEvidence>, repoPath: string, fromFile: string, seen: Set<string>, context?: RepositorySourceContext): ClassEvidence[] {\n const out: ClassEvidence[] = [];\n for (const element of array.elements) {\n if (ts.isSpreadElement(element)) out.push(...resolveArrayExpression(element.expression, arrays, imports, repoPath, fromFile, seen, context));\n else if (ts.isIdentifier(element)) out.push({ className: element.text, importSource: importSourceFor(element.text, imports) });\n }\n return out;\n}\nfunction resolveImportedArray(repoPath: string, fromFile: string, evidence: ImportEvidence, seen: Set<string>, context?: RepositorySourceContext): ClassEvidence[] {\n const moduleFile = resolveRelativeModule(repoPath, fromFile, evidence.source);\n if (!moduleFile) return [];\n const key = `${moduleFile}:${evidence.importedName}`;\n if (seen.has(key) || seen.size > MAX_EXPORT_DEPTH) return [];\n seen.add(key);\n const exports = readExports(repoPath, moduleFile, seen, context);\n if (evidence.importedName === 'default') return exports.defaultArray ?? [];\n return exports.arrays.get(evidence.importedName) ?? exports.arrays.get(exports.aliases.get(evidence.importedName) ?? evidence.importedName) ?? [];\n}\nfunction resolveRelativeModule(repoPath: string, fromFile: string, specifier: string): string | undefined {\n const base = path.resolve(repoPath, path.dirname(fromFile), specifier);\n for (const candidate of [base, `${base}.ts`, `${base}.js`, path.join(base, 'index.ts'), path.join(base, 'index.js')]) {\n try {\n const stat = fsSync.statSync(candidate);\n if (stat.isFile()) return normalizePath(path.relative(repoPath, candidate));\n } catch { /* ignore missing candidate */ }\n }\n return undefined;\n}\nfunction readExports(repoPath: string, filePath: string, seen: Set<string>, context?: RepositorySourceContext): FileExports {\n const absolute = path.join(repoPath, filePath);\n let text: string;\n const snapshot = context?.get(filePath);\n try { text = snapshot?.text ?? fsSync.readFileSync(absolute, 'utf8'); } catch { return { arrays: new Map(), aliases: new Map() }; }\n const sourceFile = snapshot?.sourceFile() ?? ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const imports = collectImports(sourceFile);\n const arrays = collectLocalArrays(\n sourceFile, imports, new Map(), repoPath, filePath, context,\n );\n const aliases = new Map<string, string>();\n let defaultArray: ClassEvidence[] | undefined;\n for (const statement of sourceFile.statements) {\n if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) defaultArray = arrays.get(statement.expression.text);\n if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n const module = statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : undefined;\n for (const element of statement.exportClause.elements) {\n const local = element.propertyName?.text ?? element.name.text;\n aliases.set(element.name.text, local);\n if (module && isRelative(module)) {\n const imported = resolveImportedArray(\n repoPath, filePath, { source: module, importedName: local }, seen, context,\n );\n if (imported.length > 0) arrays.set(element.name.text, imported);\n }\n }\n }\n }\n return { arrays, defaultArray, aliases };\n}\n","const SENSITIVE = /authorization|cookie|token|secret|password|key|credential/i;\nconst SENSITIVE_KEYWORD = /authorization|cookie|token|secret|password|key|credential/gi;\n\ninterface RedactionSpan {\n readonly start: number;\n readonly end: number;\n readonly keyword: string;\n}\n\nfunction isWhitespace(value: string | undefined): boolean {\n return value !== undefined && /\\s/u.test(value);\n}\n\nfunction redactionSpan(text: string, start: number, keyword: string): RedactionSpan | undefined {\n let cursor = start + keyword.length;\n while (isWhitespace(text[cursor])) cursor += 1;\n if (text[cursor] !== ':' && text[cursor] !== '=') return undefined;\n cursor += 1;\n while (isWhitespace(text[cursor])) cursor += 1;\n const candidateQuote = text[cursor];\n const quote = candidateQuote === \"'\" || candidateQuote === '\"' || candidateQuote === '`'\n ? candidateQuote\n : undefined;\n if (quote !== undefined) cursor += 1;\n const valueStart = cursor;\n while (cursor < text.length && !/[,'\"`}\\s]/u.test(text[cursor] ?? '')) cursor += 1;\n if (cursor === valueStart) return undefined;\n if (quote !== undefined) {\n if (text[cursor] !== quote) return undefined;\n cursor += 1;\n }\n return { start, end: cursor, keyword };\n}\n\nexport function redactText(text: string): string {\n let cursor = 0;\n let output = '';\n for (const match of text.matchAll(SENSITIVE_KEYWORD)) {\n const start = match.index ?? 0;\n if (start < cursor) continue;\n const span = redactionSpan(text, start, match[0]);\n if (span === undefined) continue;\n output += text.slice(cursor, span.start) + `${span.keyword}: [REDACTED]`;\n cursor = span.end;\n }\n return output + text.slice(cursor);\n}\nexport function redactValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactValue);\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value))\n out[k] = SENSITIVE.test(k) ? '[REDACTED]' : redactValue(v);\n return out;\n }\n return typeof value === 'string' ? redactText(value) : value;\n}\nexport function summarizeExpression(text: string): string {\n return redactText(text).slice(0, 240);\n}\n","import path from 'node:path';\nimport ts from 'typescript';\nimport type { ServiceBindingFact } from '../types.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport {\n connectFactFromCall,\n findConnectInExpression,\n importsFor,\n lineOf,\n readSource,\n transactionReceiverName,\n unwrapCall,\n unwrapIdentityExpression,\n type ClassHelperReturn,\n type HelperBinding,\n type ImportBinding,\n} from './service-binding-parser-helpers.js';\nimport type { RepositorySourceContext } from './ts-project.js';\n\nfunction collectLocalBindingFacts(\n fn: ts.FunctionLikeDeclaration,\n): Map<string, Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'>> {\n const bindings = new Map<string, Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'>>();\n function visit(node: ts.Node): void {\n if (node !== fn && (ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node)))\n return;\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {\n const fact = findConnectInExpression(node.initializer);\n if (fact) bindings.set(node.name.text, fact);\n const sourceName = transactionReceiverName(node.initializer);\n if (sourceName) {\n const source = bindings.get(sourceName);\n if (source) bindings.set(node.name.text, { ...source, helperChain: [...(source.helperChain ?? []), { aliasOf: sourceName, callerVariable: node.name.text, aliasKind: 'transaction', transactionAliasSource: sourceName }] });\n }\n }\n ts.forEachChild(node, visit);\n }\n visit(fn);\n return bindings;\n}\n\nfunction collectReturnedObjectBindings(\n fn: ts.FunctionLikeDeclaration,\n): Map<string, Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'>> {\n const bindings = collectLocalBindingFacts(fn);\n const returns = new Map<string, string>();\n function visit(node: ts.Node): void {\n if (node !== fn && (ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node)))\n return;\n if (ts.isReturnStatement(node) && node.expression && ts.isObjectLiteralExpression(node.expression)) {\n for (const prop of node.expression.properties) {\n if (ts.isShorthandPropertyAssignment(prop)) returns.set(prop.name.text, prop.name.text);\n if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.initializer)) {\n const propertyName = ts.isIdentifier(prop.name) || ts.isStringLiteralLike(prop.name) ? prop.name.text : undefined;\n if (propertyName) returns.set(propertyName, prop.initializer.text);\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n visit(fn);\n const out = new Map<string, Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'>>();\n for (const [propertyName, variableName] of returns) {\n const fact = bindings.get(variableName);\n if (fact) out.set(propertyName, fact);\n }\n return out;\n}\n\nfunction functionLikeInitializer(\n expr: ts.Expression | undefined,\n): ts.FunctionLikeDeclaration | undefined {\n if (!expr) return undefined;\n if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) return expr;\n return undefined;\n}\n\nfunction directReturnConnectFact(\n fn: ts.FunctionLikeDeclaration,\n): Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'> | undefined {\n const localBindings = collectLocalBindingFacts(fn);\n let returned: ts.Expression | undefined;\n function visit(node: ts.Node): void {\n if (node !== fn && (ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node)))\n return;\n if (!returned && ts.isReturnStatement(node) && node.expression)\n returned = node.expression;\n if (!returned) ts.forEachChild(node, visit);\n }\n visit(fn);\n if (!returned) return undefined;\n if (ts.isIdentifier(returned)) return localBindings.get(returned.text);\n return findConnectInExpression(returned);\n}\n\nfunction directConnectFactFromFunctionLike(\n fn: ts.FunctionLikeDeclaration,\n): Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'> | undefined {\n if (ts.isArrowFunction(fn) && fn.body && !ts.isBlock(fn.body))\n return findConnectInExpression(fn.body);\n return directReturnConnectFact(fn);\n}\n\nfunction exportedLocalNames(sf: ts.SourceFile): Map<string, string> {\n const exports = new Map<string, string>();\n for (const stmt of sf.statements) {\n const direct = ts.canHaveModifiers(stmt)\n ? (ts\n .getModifiers(stmt)\n ?.some(\n (m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ExportKeyword,\n ) ?? false)\n : false;\n if (direct && ts.isFunctionDeclaration(stmt) && stmt.name)\n exports.set(stmt.name.text, stmt.name.text);\n if (direct && ts.isVariableStatement(stmt))\n for (const decl of stmt.declarationList.declarations)\n if (ts.isIdentifier(decl.name)) exports.set(decl.name.text, decl.name.text);\n if (!ts.isExportDeclaration(stmt) || !stmt.exportClause) continue;\n if (!ts.isNamedExports(stmt.exportClause)) continue;\n for (const el of stmt.exportClause.elements)\n exports.set(el.name.text, el.propertyName?.text ?? el.name.text);\n }\n return exports;\n}\nasync function helperBindings(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n): Promise<HelperBinding[]> {\n const sf = await readSource(path.join(repoPath, filePath), context, filePath);\n if (!sf) return [];\n const sourceFileAst = sf;\n const out: HelperBinding[] = [];\n const exportedLocals = exportedLocalNames(sf);\n const factsByLocal = new Map<\n string,\n Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'> & {\n sourceLine: number;\n }\n >();\n for (const stmt of sf.statements) {\n if (ts.isFunctionDeclaration(stmt) && stmt.name) {\n const fact = directConnectFactFromFunctionLike(stmt);\n if (fact) factsByLocal.set(stmt.name.text, { ...fact, sourceLine: lineOf(sf, stmt) });\n for (const [returnedProperty, objectFact] of collectReturnedObjectBindings(stmt))\n factsByLocal.set(`${stmt.name.text}#${returnedProperty}`, { ...objectFact, returnedProperty, sourceLine: lineOf(sf, stmt) });\n }\n if (ts.isVariableStatement(stmt))\n for (const decl of stmt.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;\n const helper = functionLikeInitializer(decl.initializer);\n if (helper) {\n const directReturn = directConnectFactFromFunctionLike(helper);\n if (directReturn)\n factsByLocal.set(decl.name.text, {\n ...directReturn,\n sourceLine: lineOf(sourceFileAst, decl),\n });\n for (const [returnedProperty, objectFact] of collectReturnedObjectBindings(helper))\n factsByLocal.set(`${decl.name.text}#${returnedProperty}`, {\n ...objectFact,\n returnedProperty,\n sourceLine: lineOf(sourceFileAst, decl),\n });\n continue;\n }\n const fact = findConnectInExpression(decl.initializer);\n if (fact)\n factsByLocal.set(decl.name.text, {\n ...fact,\n sourceLine: lineOf(sourceFileAst, decl),\n });\n }\n }\n for (const [exportedName, localName] of exportedLocals) {\n const fact = factsByLocal.get(localName);\n if (fact)\n out.push({\n ...fact,\n exportedName,\n sourceFile: normalizePath(filePath),\n sourceLine: fact.sourceLine,\n });\n }\n for (const [key, fact] of factsByLocal) {\n const [localName, returnedProperty] = key.split('#');\n if (!returnedProperty) continue;\n for (const [exportedName, exportedLocal] of exportedLocals) {\n if (exportedLocal !== localName) continue;\n out.push({ ...fact, exportedName, returnedProperty, sourceFile: normalizePath(filePath), sourceLine: fact.sourceLine });\n }\n }\n return out;\n}\n\nexport async function parseServiceBindings(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n): Promise<ServiceBindingFact[]> {\n const sf = await readSource(path.join(repoPath, filePath), context, filePath);\n if (!sf) return [];\n const sourceFileAst = sf;\n const out: ServiceBindingFact[] = [];\n const imports = await importsFor(repoPath, filePath, sf);\n const helperCache = new Map<string, HelperBinding[]>();\n const classHelpers = collectClassHelpers(sourceFileAst);\n const localObjectHelpers = new Map<string, HelperBinding[]>();\n const localDirectHelpers = new Map<string, HelperBinding>();\n const objectHelperVariables = new Map<string, Array<{ helper: HelperBinding; imp?: ImportBinding }>>();\n for (const stmt of sourceFileAst.statements) {\n if (ts.isFunctionDeclaration(stmt) && stmt.name) {\n const directFact = directConnectFactFromFunctionLike(stmt);\n if (directFact) localDirectHelpers.set(stmt.name.text, { ...directFact, exportedName: stmt.name.text, sourceFile: normalizePath(filePath), sourceLine: lineOf(sourceFileAst, stmt) });\n const rows: HelperBinding[] = [];\n for (const [returnedProperty, fact] of collectReturnedObjectBindings(stmt))\n rows.push({ ...fact, exportedName: stmt.name.text, returnedProperty, sourceFile: normalizePath(filePath), sourceLine: lineOf(sourceFileAst, stmt) });\n if (rows.length > 0) localObjectHelpers.set(stmt.name.text, rows);\n }\n if (ts.isVariableStatement(stmt)) {\n for (const decl of stmt.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name)) continue;\n const helper = functionLikeInitializer(decl.initializer);\n if (!helper) continue;\n const directFact = directConnectFactFromFunctionLike(helper);\n if (directFact) localDirectHelpers.set(decl.name.text, { ...directFact, exportedName: decl.name.text, sourceFile: normalizePath(filePath), sourceLine: lineOf(sourceFileAst, decl) });\n const rows: HelperBinding[] = [];\n for (const [returnedProperty, fact] of collectReturnedObjectBindings(helper))\n rows.push({ ...fact, exportedName: decl.name.text, returnedProperty, sourceFile: normalizePath(filePath), sourceLine: lineOf(sourceFileAst, decl) });\n if (rows.length > 0) localObjectHelpers.set(decl.name.text, rows);\n }\n }\n }\n async function importedHelpers(\n localName: string,\n ): Promise<Array<{ imp: ImportBinding; helper: HelperBinding }>> {\n const imp = imports.find((i) => i.localName === localName && i.sourceFile);\n if (!imp?.sourceFile) return [];\n if (!helperCache.has(imp.sourceFile))\n helperCache.set(\n imp.sourceFile,\n await helperBindings(repoPath, imp.sourceFile, context),\n );\n return (helperCache.get(imp.sourceFile) ?? [])\n .filter((h) => h.exportedName === imp.exportedName)\n .map((helper) => ({ imp, helper }));\n }\n async function importedHelper(\n localName: string,\n ): Promise<{ imp: ImportBinding; helper: HelperBinding } | undefined> {\n return (await importedHelpers(localName)).find((row) => !row.helper.returnedProperty);\n }\n function bindingForVariable(variableName: string): ServiceBindingFact | undefined {\n const sourceFile = normalizePath(filePath);\n return [...out]\n .reverse()\n .find((row) => row.variableName === variableName && row.sourceFile === sourceFile);\n }\n function cloneAliasBinding(targetName: string, sourceName: string, aliasKind: 'identity' | 'identity-assignment' | 'transaction', node: ts.Node): void {\n const existing = bindingForVariable(sourceName);\n if (!existing) return;\n out.push({\n ...existing,\n variableName: targetName,\n sourceLine: lineOf(sourceFileAst, node),\n helperChain: [\n ...(existing.helperChain ?? []),\n {\n callerVariable: targetName,\n aliasOf: sourceName,\n aliasKind,\n scopeRule: 'same-file-source-order',\n ...(aliasKind === 'transaction' ? { transactionAliasSource: sourceName } : {}),\n },\n ],\n });\n }\n function recordIdentityAlias(decl: ts.VariableDeclaration): void {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) return;\n const unwrapped = unwrapIdentityExpression(decl.initializer);\n if (!ts.isIdentifier(unwrapped)) return;\n cloneAliasBinding(decl.name.text, unwrapped.text, 'identity', decl);\n }\n\n async function recordBindingFromExpression(targetName: string, expr: ts.Expression, node: ts.Node, aliasKind: 'declaration' | 'assignment'): Promise<void> {\n const call = unwrapCall(expr);\n if (!call) return;\n const direct = connectFactFromCall(call);\n if (direct)\n out.push({\n variableName: targetName,\n ...direct,\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(sourceFileAst, node),\n helperChain: aliasKind === 'assignment'\n ? [{ callerVariable: targetName, assignedFrom: call.expression.getText(sourceFileAst), aliasKind, scopeRule: 'same-file-source-order' }]\n : undefined,\n });\n else if (ts.isIdentifier(call.expression)) {\n const localDirect = localDirectHelpers.get(call.expression.text);\n const resolved = localDirect ? { helper: localDirect, imp: undefined } : await importedHelper(call.expression.text);\n if (resolved)\n out.push({\n variableName: targetName,\n alias: resolved.helper.alias,\n aliasExpr: resolved.helper.aliasExpr,\n destinationExpr: resolved.helper.destinationExpr,\n servicePathExpr: resolved.helper.servicePathExpr,\n isDynamic: resolved.helper.isDynamic,\n placeholders: resolved.helper.placeholders,\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(sourceFileAst, node),\n helperChain: [\n ...(resolved.helper.helperChain ?? []),\n {\n callerVariable: targetName,\n ...(aliasKind === 'assignment' ? { assignedFrom: call.expression.text, aliasKind, scopeRule: 'same-file-source-order' } : {}),\n importedHelper: call.expression.text,\n importSource: resolved.imp?.sourceFile,\n exportedSymbol: resolved.imp?.exportedName ?? resolved.helper.exportedName,\n helperSourceFile: resolved.helper.sourceFile,\n helperSourceLine: resolved.helper.sourceLine,\n },\n ],\n });\n }\n }\n async function recordVariable(decl: ts.VariableDeclaration): Promise<void> {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) return;\n await recordBindingFromExpression(decl.name.text, decl.initializer, decl, 'declaration');\n }\n\n async function helpersForCall(call: ts.CallExpression): Promise<Array<{ helper: HelperBinding; imp?: ImportBinding }>> {\n if (!ts.isIdentifier(call.expression)) return [];\n const local = localObjectHelpers.get(call.expression.text) ?? [];\n const imported = await importedHelpers(call.expression.text);\n return [...local.map((helper) => ({ helper })), ...imported];\n }\n async function rememberObjectHelperVariable(decl: ts.VariableDeclaration): Promise<void> {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) return;\n const call = unwrapCall(decl.initializer);\n if (!call) return;\n const helpers = (await helpersForCall(call)).filter((row) => row.helper.returnedProperty);\n if (helpers.length > 0) objectHelperVariables.set(decl.name.text, helpers);\n }\n function recordObjectPropertyBinding(targetName: string, expr: ts.Expression, node: ts.Node): boolean {\n const unwrapped = unwrapIdentityExpression(expr);\n if (!ts.isPropertyAccessExpression(unwrapped) || !ts.isIdentifier(unwrapped.expression)) return false;\n const helpers = objectHelperVariables.get(unwrapped.expression.text) ?? [];\n const matches = helpers.filter((row) => row.helper.returnedProperty === unwrapped.name.text);\n if (matches.length !== 1) return false;\n const resolved = matches[0];\n out.push({\n variableName: targetName,\n alias: resolved.helper.alias,\n aliasExpr: resolved.helper.aliasExpr,\n destinationExpr: resolved.helper.destinationExpr,\n servicePathExpr: resolved.helper.servicePathExpr,\n isDynamic: resolved.helper.isDynamic,\n placeholders: resolved.helper.placeholders,\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(sourceFileAst, node),\n helperChain: [\n ...(resolved.helper.helperChain ?? []),\n {\n callerVariable: targetName,\n sourceVariable: unwrapped.expression.text,\n returnedProperty: unwrapped.name.text,\n assignedFromProperty: unwrapped.getText(sourceFileAst),\n importSource: resolved.imp?.sourceFile,\n exportedSymbol: resolved.imp?.exportedName,\n helperSourceFile: resolved.helper.sourceFile,\n helperSourceLine: resolved.helper.sourceLine,\n },\n ],\n });\n return true;\n }\n async function recordDestructuredHelper(decl: ts.VariableDeclaration): Promise<void> {\n if (!ts.isObjectBindingPattern(decl.name) || !decl.initializer) return;\n const call = unwrapCall(decl.initializer);\n if (!call) return;\n const helpers = await helpersForCall(call);\n if (helpers.length === 0) return;\n for (const el of decl.name.elements) {\n if (!ts.isIdentifier(el.name)) continue;\n const propertyName = el.propertyName && ts.isIdentifier(el.propertyName) ? el.propertyName.text : el.name.text;\n const matches = helpers.filter((row) => row.helper.returnedProperty === propertyName);\n if (matches.length !== 1) continue;\n const resolved = matches[0];\n out.push({\n variableName: el.name.text,\n alias: resolved.helper.alias,\n aliasExpr: resolved.helper.aliasExpr,\n destinationExpr: resolved.helper.destinationExpr,\n servicePathExpr: resolved.helper.servicePathExpr,\n isDynamic: resolved.helper.isDynamic,\n placeholders: resolved.helper.placeholders,\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(sourceFileAst, decl),\n helperChain: [...(resolved.helper.helperChain ?? []), { callerVariable: el.name.text, helperFunction: call.expression.getText(sourceFileAst), returnedProperty: propertyName, importSource: resolved.imp?.sourceFile, exportedSymbol: resolved.imp?.exportedName, helperSourceFile: resolved.helper.sourceFile, helperSourceLine: resolved.helper.sourceLine }],\n });\n }\n }\n async function recordDestructuredAssignment(pattern: ts.ObjectLiteralExpression, expr: ts.Expression, node: ts.Node): Promise<void> {\n const call = unwrapCall(expr);\n if (!call) return;\n const helpers = await helpersForCall(call);\n if (helpers.length === 0) return;\n for (const prop of pattern.properties) {\n let propertyName: string | undefined;\n let targetName: string | undefined;\n if (ts.isShorthandPropertyAssignment(prop)) {\n propertyName = prop.name.text;\n targetName = prop.name.text;\n } else if (ts.isPropertyAssignment(prop)) {\n propertyName = ts.isIdentifier(prop.name) || ts.isStringLiteralLike(prop.name) ? prop.name.text : undefined;\n targetName = ts.isIdentifier(prop.initializer) ? prop.initializer.text : undefined;\n }\n if (!propertyName || !targetName) continue;\n const matches = helpers.filter((row) => row.helper.returnedProperty === propertyName);\n if (matches.length !== 1) continue;\n const resolved = matches[0];\n out.push({\n variableName: targetName,\n alias: resolved.helper.alias,\n aliasExpr: resolved.helper.aliasExpr,\n destinationExpr: resolved.helper.destinationExpr,\n servicePathExpr: resolved.helper.servicePathExpr,\n isDynamic: resolved.helper.isDynamic,\n placeholders: resolved.helper.placeholders,\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(sourceFileAst, node),\n helperChain: [...(resolved.helper.helperChain ?? []), { callerVariable: targetName, assignedFrom: call.expression.getText(sourceFileAst), aliasKind: 'assignment', scopeRule: 'same-file-source-order', returnedProperty: propertyName, importSource: resolved.imp?.sourceFile, exportedSymbol: resolved.imp?.exportedName, helperSourceFile: resolved.helper.sourceFile, helperSourceLine: resolved.helper.sourceLine }],\n });\n }\n }\n function recordDestructuredClassHelper(decl: ts.VariableDeclaration): void {\n if (!ts.isObjectBindingPattern(decl.name) || !decl.initializer) return;\n const call = unwrapCall(decl.initializer);\n if (!call || !ts.isPropertyAccessExpression(call.expression)) return;\n const target = call.expression;\n if (target.expression.kind !== ts.SyntaxKind.ThisKeyword) return;\n for (const el of decl.name.elements) {\n if (!ts.isIdentifier(el.name)) continue;\n const propertyName = el.propertyName && ts.isIdentifier(el.propertyName)\n ? el.propertyName.text\n : el.name.text;\n const helper = classHelpers.find(\n (h) => h.helperName === target.name.text && h.propertyName === propertyName,\n );\n if (!helper) continue;\n out.push({\n variableName: el.name.text,\n ...helper.fact,\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(sourceFileAst, decl),\n helperChain: [\n {\n callerVariable: el.name.text,\n className: helper.className,\n classHelper: helper.helperName,\n returnedProperty: helper.propertyName,\n helperVariable: helper.variableName,\n helperSourceFile: normalizePath(filePath),\n helperSourceLine: helper.sourceLine,\n },\n ],\n });\n }\n }\n\n function arrayElementsFromExpression(expr: ts.Expression): { elements: ts.NodeArray<ts.Expression>; promiseAll: boolean } | undefined {\n const unwrapped = unwrapIdentityExpression(expr);\n if (ts.isArrayLiteralExpression(unwrapped)) return { elements: unwrapped.elements, promiseAll: false };\n const call = unwrapCall(expr);\n if (!call) return undefined;\n if (!ts.isPropertyAccessExpression(call.expression) || call.expression.name.text !== 'all' || call.expression.expression.getText(sourceFileAst) !== 'Promise') return undefined;\n const first = call.arguments[0];\n if (!first) return undefined;\n const container = unwrapIdentityExpression(first);\n if (!ts.isArrayLiteralExpression(container)) return undefined;\n return { elements: container.elements, promiseAll: true };\n }\n\n async function recordArrayElementBinding(targetName: string, expr: ts.Expression, node: ts.Node, arrayIndex: number, promiseAll: boolean): Promise<void> {\n const before = out.length;\n await recordBindingFromExpression(targetName, expr, node, 'declaration');\n if (out.length > before) {\n const row = out[out.length - 1];\n row.helperChain = [\n ...(row.helperChain ?? []),\n { callerVariable: targetName, targetVariable: targetName, arrayIndex, promiseAll, arrayContainer: promiseAll ? 'Promise.all' : 'array_literal' },\n ];\n return;\n }\n const unwrapped = unwrapIdentityExpression(expr);\n if (ts.isIdentifier(unwrapped)) {\n const existing = bindingForVariable(unwrapped.text);\n if (!existing) return;\n out.push({\n ...existing,\n variableName: targetName,\n sourceLine: lineOf(sourceFileAst, node),\n helperChain: [\n ...(existing.helperChain ?? []),\n { callerVariable: targetName, targetVariable: targetName, sourceVariable: unwrapped.text, aliasKind: 'array-destructuring', arrayIndex, promiseAll, arrayContainer: promiseAll ? 'Promise.all' : 'array_literal' },\n ],\n });\n }\n }\n\n async function recordArrayDestructuredVariable(decl: ts.VariableDeclaration): Promise<void> {\n if (!ts.isArrayBindingPattern(decl.name) || !decl.initializer) return;\n const container = arrayElementsFromExpression(decl.initializer);\n if (!container) return;\n for (let index = 0; index < decl.name.elements.length; index += 1) {\n const el = decl.name.elements[index];\n if (!el || ts.isOmittedExpression(el) || ts.isBindingElement(el) && el.dotDotDotToken) continue;\n if (!ts.isBindingElement(el) || !ts.isIdentifier(el.name)) continue;\n const source = container.elements[index];\n if (!source || ts.isOmittedExpression(source)) continue;\n await recordArrayElementBinding(el.name.text, source, decl, index, container.promiseAll);\n }\n }\n\n async function recordArrayDestructuredAssignment(pattern: ts.ArrayLiteralExpression, expr: ts.Expression, node: ts.Node): Promise<void> {\n const container = arrayElementsFromExpression(expr);\n if (!container) return;\n for (let index = 0; index < pattern.elements.length; index += 1) {\n const el = pattern.elements[index];\n if (!el || ts.isOmittedExpression(el) || ts.isSpreadElement(el) || !ts.isIdentifier(el)) continue;\n const source = container.elements[index];\n if (!source || ts.isOmittedExpression(source)) continue;\n await recordArrayElementBinding(el.text, source, node, index, container.promiseAll);\n }\n }\n\n const events: Array<{ pos: number; node: ts.VariableDeclaration | ts.BinaryExpression }> = [];\n function collectEvents(node: ts.Node): void {\n if (ts.isVariableDeclaration(node)) events.push({ pos: node.getStart(sourceFileAst), node });\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken)\n events.push({ pos: node.getStart(sourceFileAst), node });\n ts.forEachChild(node, collectEvents);\n }\n collectEvents(sourceFileAst);\n events.sort((a, b) => a.pos - b.pos);\n for (const event of events) {\n if (ts.isVariableDeclaration(event.node)) {\n const decl = event.node;\n await recordDestructuredHelper(decl);\n await recordArrayDestructuredVariable(decl);\n recordDestructuredClassHelper(decl);\n await rememberObjectHelperVariable(decl);\n if (ts.isIdentifier(decl.name) && decl.initializer) recordObjectPropertyBinding(decl.name.text, decl.initializer, decl);\n await recordVariable(decl);\n recordIdentityAlias(decl);\n if (ts.isIdentifier(decl.name) && decl.initializer) {\n const sourceName = transactionReceiverName(decl.initializer);\n if (sourceName) cloneAliasBinding(decl.name.text, sourceName, 'transaction', decl);\n }\n continue;\n }\n const assignment = event.node;\n if (ts.isIdentifier(assignment.left)) {\n const rhs = unwrapIdentityExpression(assignment.right);\n if (ts.isIdentifier(rhs)) {\n cloneAliasBinding(assignment.left.text, rhs.text, 'identity-assignment', assignment);\n continue;\n }\n if (recordObjectPropertyBinding(assignment.left.text, assignment.right, assignment)) continue;\n await recordBindingFromExpression(assignment.left.text, assignment.right, assignment, 'assignment');\n continue;\n }\n const left = ts.isParenthesizedExpression(assignment.left) ? assignment.left.expression : assignment.left;\n if (ts.isObjectLiteralExpression(left))\n await recordDestructuredAssignment(left, assignment.right, assignment);\n if (ts.isArrayLiteralExpression(left))\n await recordArrayDestructuredAssignment(left, assignment.right, assignment);\n }\n return out;\n}\n\nfunction collectClassHelpers(sf: ts.SourceFile): ClassHelperReturn[] {\n const helpers: ClassHelperReturn[] = [];\n for (const stmt of sf.statements) {\n if (!ts.isClassDeclaration(stmt) || !stmt.name) continue;\n for (const member of stmt.members) {\n if (!ts.isPropertyDeclaration(member) || !member.initializer) continue;\n if (!ts.isIdentifier(member.name)) continue;\n const className = stmt.name.text;\n const helperName = member.name.text;\n const initializer = member.initializer;\n if (!ts.isArrowFunction(initializer) && !ts.isFunctionExpression(initializer))\n continue;\n const bindings = new Map<\n string,\n Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'>\n >();\n function visit(node: ts.Node): void {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {\n const fact = findConnectInExpression(node.initializer);\n if (fact) bindings.set(node.name.text, fact);\n }\n if (ts.isReturnStatement(node) && node.expression && ts.isObjectLiteralExpression(node.expression)) {\n for (const prop of node.expression.properties) {\n if (ts.isShorthandPropertyAssignment(prop)) {\n const fact = bindings.get(prop.name.text);\n if (fact)\n helpers.push({\n className,\n helperName,\n propertyName: prop.name.text,\n variableName: prop.name.text,\n fact,\n sourceLine: lineOf(sf, prop),\n });\n }\n if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.initializer)) {\n const propertyName =\n ts.isIdentifier(prop.name) || ts.isStringLiteralLike(prop.name)\n ? prop.name.text\n : undefined;\n const fact = propertyName ? bindings.get(prop.initializer.text) : undefined;\n if (propertyName && fact)\n helpers.push({\n className,\n helperName,\n propertyName,\n variableName: prop.initializer.text,\n fact,\n sourceLine: lineOf(sf, prop),\n });\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n visit(initializer);\n }\n }\n return helpers;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport ts from 'typescript';\nimport { normalizePath } from '../utils/path-utils.js';\nimport { extractPlaceholderKeys } from '../utils/001-placeholders.js';\nimport type { RepositorySourceContext } from './ts-project.js';\n\nexport interface HelperBinding {\n exportedName: string;\n returnedProperty?: string;\n alias?: string;\n aliasExpr?: string;\n destinationExpr?: string;\n servicePathExpr?: string;\n isDynamic: boolean;\n placeholders: string[];\n helperChain?: Array<Record<string, unknown>>;\n sourceFile: string;\n sourceLine: number;\n}\nexport interface ImportBinding {\n localName: string;\n exportedName: string;\n sourceFile?: string;\n}\nexport interface ClassHelperReturn {\n className: string;\n helperName: string;\n propertyName: string;\n variableName: string;\n fact: Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'>;\n sourceLine: number;\n}\n\nexport function lineOf(sf: ts.SourceFile, node: ts.Node): number {\n return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n}\n\nfunction stringValue(node: ts.Expression | undefined): string | undefined {\n if (!node) return undefined;\n if (ts.isStringLiteralLike(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;\n if (ts.isTemplateExpression(node)) return node.getText().replace(/^`|`$/g, '');\n return node.getText();\n}\n\nfunction placeholders(value?: string): string[] {\n return extractPlaceholderKeys(value);\n}\n\nexport function connectFactFromCall(call: ts.CallExpression): Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'> | undefined {\n const expr = call.expression;\n if (!ts.isPropertyAccessExpression(expr) || expr.name.text !== 'to') return undefined;\n const inner = expr.expression;\n if (!ts.isPropertyAccessExpression(inner) || inner.name.text !== 'connect' || inner.expression.getText() !== 'cds') return undefined;\n const first = call.arguments[0];\n if (!first) return undefined;\n const second = call.arguments[1];\n const objectArg = ts.isObjectLiteralExpression(first) ? first : second && ts.isObjectLiteralExpression(second) ? second : undefined;\n let alias: string | undefined;\n let aliasExpr: string | undefined;\n if (ts.isStringLiteralLike(first) || ts.isNoSubstitutionTemplateLiteral(first)) alias = first.text;\n else if (!ts.isObjectLiteralExpression(first)) aliasExpr = stringValue(first);\n if ((ts.isStringLiteralLike(first) || ts.isNoSubstitutionTemplateLiteral(first)) && !objectArg) return { alias: first.text, isDynamic: false, placeholders: [] };\n if (!objectArg && aliasExpr) return { aliasExpr, isDynamic: true, placeholders: placeholders(aliasExpr) };\n const expressions = objectArg ? objectExpressions(objectArg) : {};\n const ph = [...placeholders(aliasExpr ?? alias), ...placeholders(expressions.destinationExpr), ...placeholders(expressions.servicePathExpr)];\n return { alias, aliasExpr, ...expressions, isDynamic: ph.length > 0 || (!expressions.destinationExpr && !expressions.servicePathExpr), placeholders: ph };\n}\n\nfunction objectExpressions(objectArg: ts.ObjectLiteralExpression): { destinationExpr?: string; servicePathExpr?: string } {\n const out: { destinationExpr?: string; servicePathExpr?: string } = {};\n function visitObject(obj: ts.ObjectLiteralExpression): void {\n for (const prop of obj.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const name = ts.isIdentifier(prop.name) || ts.isStringLiteralLike(prop.name) ? prop.name.text : undefined;\n if (name === 'destination') out.destinationExpr = stringValue(prop.initializer);\n if (name === 'path' || name === 'servicePath') out.servicePathExpr = stringValue(prop.initializer);\n if (ts.isObjectLiteralExpression(prop.initializer)) visitObject(prop.initializer);\n }\n }\n visitObject(objectArg);\n return out;\n}\n\nexport function unwrapCall(expr: ts.Expression): ts.CallExpression | undefined {\n if (ts.isAwaitExpression(expr)) return unwrapCall(expr.expression);\n if (ts.isParenthesizedExpression(expr)) return unwrapCall(expr.expression);\n if (ts.isAsExpression(expr) || ts.isSatisfiesExpression(expr)) return unwrapCall(expr.expression);\n if (ts.isTypeAssertionExpression(expr)) return unwrapCall(expr.expression);\n if (ts.isCallExpression(expr)) return expr;\n return undefined;\n}\n\nexport function unwrapIdentityExpression(expr: ts.Expression): ts.Expression {\n if (ts.isAwaitExpression(expr)) return unwrapIdentityExpression(expr.expression);\n if (ts.isParenthesizedExpression(expr)) return unwrapIdentityExpression(expr.expression);\n if (ts.isAsExpression(expr) || ts.isSatisfiesExpression(expr)) return unwrapIdentityExpression(expr.expression);\n if (ts.isTypeAssertionExpression(expr)) return unwrapIdentityExpression(expr.expression);\n return expr;\n}\n\nexport function transactionReceiverName(expr: ts.Expression): string | undefined {\n const call = unwrapCall(expr);\n if (call && ts.isPropertyAccessExpression(call.expression) && ['tx', 'transaction'].includes(call.expression.name.text) && ts.isIdentifier(call.expression.expression)) return call.expression.expression.text;\n const unwrapped = unwrapIdentityExpression(expr);\n if (!ts.isConditionalExpression(unwrapped)) return undefined;\n const left = transactionReceiverName(unwrapped.whenTrue);\n const right = transactionReceiverName(unwrapped.whenFalse);\n return left && left === right ? left : undefined;\n}\n\nexport function findConnectInExpression(expr: ts.Expression): Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'> | undefined {\n const direct = unwrapCall(expr);\n if (direct) {\n const fact = connectFactFromCall(direct);\n if (fact) return fact;\n }\n let found: Omit<HelperBinding, 'exportedName' | 'sourceFile' | 'sourceLine'> | undefined;\n function visit(node: ts.Node): void {\n if (found) return;\n if (ts.isCallExpression(node)) found = connectFactFromCall(node);\n if (!found) ts.forEachChild(node, visit);\n }\n visit(expr);\n return found;\n}\n\nexport async function readSource(\n abs: string,\n context?: RepositorySourceContext,\n filePath?: string,\n): Promise<ts.SourceFile | undefined> {\n const snapshot = filePath ? context?.get(filePath) : undefined;\n if (snapshot) return snapshot.sourceFile();\n try {\n const text = await fs.readFile(abs, 'utf8');\n return ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n } catch {\n return undefined;\n }\n}\n\nasync function resolveImport(repoPath: string, fromFile: string, spec: string): Promise<string | undefined> {\n if (!spec.startsWith('.')) return undefined;\n const rawBase = path.resolve(repoPath, path.dirname(fromFile), spec);\n const parsed = path.parse(rawBase);\n const base = ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(parsed.ext) ? path.join(parsed.dir, parsed.name) : rawBase;\n for (const candidate of [base, `${base}.ts`, `${base}.js`, path.join(base, 'index.ts'), path.join(base, 'index.js')]) {\n const stat = await fs.stat(candidate).catch(() => undefined);\n if (stat?.isFile()) return normalizePath(path.relative(repoPath, candidate));\n }\n return undefined;\n}\n\nexport async function importsFor(repoPath: string, filePath: string, sf: ts.SourceFile): Promise<ImportBinding[]> {\n const imports: ImportBinding[] = [];\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteralLike(stmt.moduleSpecifier)) continue;\n const sourceFile = await resolveImport(repoPath, filePath, stmt.moduleSpecifier.text);\n const clause = stmt.importClause;\n if (!clause) continue;\n if (clause.name) imports.push({ localName: clause.name.text, exportedName: 'default', sourceFile });\n const bindings = clause.namedBindings;\n if (bindings && ts.isNamedImports(bindings))\n for (const el of bindings.elements) imports.push({ localName: el.name.text, exportedName: el.propertyName?.text ?? el.name.text, sourceFile });\n }\n return imports;\n}\n","export interface PlaceholderSpan {\n readonly start: number;\n readonly end: number;\n readonly key: string;\n}\n\nexport function scanPlaceholders(value: string | undefined): readonly PlaceholderSpan[] {\n const input = value ?? '';\n const spans: PlaceholderSpan[] = [];\n let cursor = 0;\n while (cursor < input.length) {\n const start = input.indexOf('${', cursor);\n if (start < 0) break;\n const closingBrace = input.indexOf('}', start + 2);\n if (closingBrace < 0) break;\n spans.push({\n start,\n end: closingBrace + 1,\n key: input.slice(start + 2, closingBrace),\n });\n cursor = closingBrace + 1;\n }\n return spans;\n}\n\nexport function extractPlaceholderKeys(value: string | undefined): string[] {\n return scanPlaceholders(value)\n .map((span) => span.key.trim())\n .filter(Boolean);\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport ts from 'typescript';\nimport { externalHttpTarget } from '../linker/external-http-target.js';\nimport type { OutboundCallFact } from '../types.js';\nimport { normalizePath, stripQuotes } from '../utils/path-utils.js';\nimport { summarizeExpression } from '../utils/redaction.js';\nimport { classifyODataPathIntent } from '../linker/odata-path-normalizer.js';\nimport { parseServiceBindings } from './service-binding-parser.js';\nimport { parseImportedWrapperCalls } from './imported-wrapper-parser.js';\nimport {\n directQueryBuilderStatement,\n queryBuilderRoot,\n type DirectQueryBuilderStatement,\n} from './000-direct-query-execution.js';\nimport {\n expressionName,\n maxAliasDepth,\n queryEntityFromAst,\n resolveBinding,\n variableInitializers,\n} from './001-query-entity-resolution.js';\nimport type { RepositorySourceContext } from './ts-project.js';\nimport {\n analyzeOperationPath,\n operationPathExpression,\n pathUnresolvedReason,\n type OperationPathAnalysis,\n} from './operation-path-analysis.js';\nfunction lineOf(text: string, idx: number): number {\n return text.slice(0, idx).split('\\n').length;\n}\nfunction queryBuilderEvidence(source: ts.SourceFile, statement: DirectQueryBuilderStatement): Record<string, unknown> {\n return {\n classifier: 'cap_query_builder_direct',\n queryDispatch: 'direct_query_builder',\n queryRoot: expressionName(statement.root.expression),\n queryRootStartOffset: statement.root.getStart(source),\n queryRootEndOffset: statement.root.getEnd(),\n queryStatementStartOffset: statement.statement.getStart(source),\n queryStatementEndOffset: statement.statement.getEnd(),\n queryExecutionContext: statement.executionContext,\n };\n}\nfunction queryRunEvidence(\n source: ts.SourceFile,\n argument: ts.Expression | undefined,\n): Record<string, unknown> {\n const root = argument ? queryBuilderRoot(argument) : undefined;\n return {\n classifier: 'cap_query_run_wrapper',\n queryDispatch: 'cds_run_wrapper',\n ...(root ? {\n queryRoot: expressionName(root.expression),\n queryRootStartOffset: root.getStart(source),\n queryRootEndOffset: root.getEnd(),\n } : {}),\n };\n}\nfunction queryWarning(expr: string): string {\n if (/^\\s*[`'\"]/.test(expr)) return 'raw_sql_or_cql_expression';\n if (/^\\s*\\w+\\s*$/.test(expr)) return 'query_variable_without_static_initializer';\n return 'dynamic_entity_expression';\n}\nexport interface ClassifiedOutboundCall {\n fact: OutboundCallFact;\n node: ts.CallExpression;\n}\nfunction parserEvidence(source: ts.SourceFile, node: ts.CallExpression, extra?: Record<string, unknown>): Record<string, unknown> {\n return { parser: 'typescript_ast', startOffset: node.getStart(source), endOffset: node.getEnd(), ...extra };\n}\nfunction isStringLike(expr: ts.Expression | undefined): expr is ts.StringLiteral | ts.NoSubstitutionTemplateLiteral {\n return Boolean(expr && (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)));\n}\nfunction literalText(expr: ts.Expression | undefined): string | undefined {\n if (isStringLike(expr)) return expr.text;\n return undefined;\n}\nconst CDS_LIFECYCLE_EVENTS = new Set([\n 'bootstrap', 'loaded', 'connect', 'serving', 'served', 'listening', 'shutdown',\n]);\nfunction objectPropertyIsShorthand(object: ts.ObjectLiteralExpression, key: string): boolean {\n return object.properties.some((property) => ts.isShorthandPropertyAssignment(property) && property.name.text === key);\n}\nfunction nameOfProperty(name: ts.PropertyName): string | undefined {\n if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text;\n return undefined;\n}\ntype ExpressionStatus = 'static' | 'dynamic' | 'ambiguous' | 'unknown';\ntype ExpressionSourceKind = 'string_literal' | 'no_substitution_template' | 'template_with_substitutions' | 'const_alias' | 'conditional_candidates' | 'dynamic_expression';\ninterface ExpressionResolution { status: ExpressionStatus; sourceKind: ExpressionSourceKind; value?: string; rawExpression?: string; placeholderKeys: string[]; evidence: string[]; constName?: string }\nfunction safeRaw(expr: ts.Expression): string | undefined {\n if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr) || ts.isIdentifier(expr) || ts.isTemplateExpression(expr)) return expr.getText(expr.getSourceFile());\n return undefined;\n}\nfunction placeholders(expr: ts.TemplateExpression): string[] {\n return expr.templateSpans.map((span) => span.expression.getText(expr.getSourceFile()));\n}\nfunction resolveExpression(expr: ts.Expression | undefined, use: ts.Node, policy: 'operation_path' | 'external' | 'literal', depth = 0, seen = new Set<ts.Node>()): ExpressionResolution {\n if (!expr) return { status: 'unknown', sourceKind: 'dynamic_expression', placeholderKeys: [], evidence: ['expression_missing'] };\n if (ts.isStringLiteral(expr)) return { status: 'static', sourceKind: 'string_literal', value: expr.text, rawExpression: safeRaw(expr), placeholderKeys: [], evidence: ['string_literal'] };\n if (ts.isNoSubstitutionTemplateLiteral(expr)) return { status: 'static', sourceKind: 'no_substitution_template', value: expr.text, rawExpression: safeRaw(expr), placeholderKeys: [], evidence: ['no_substitution_template'] };\n if (ts.isTemplateExpression(expr)) {\n const keys = placeholders(expr);\n if (policy === 'operation_path') return { status: 'dynamic', sourceKind: 'template_with_substitutions', value: stripQuotes(expr.getText(expr.getSourceFile())), rawExpression: safeRaw(expr), placeholderKeys: keys, evidence: ['operation_path_template_placeholders_retained'] };\n return { status: 'dynamic', sourceKind: 'template_with_substitutions', placeholderKeys: keys, evidence: ['template_substitutions_not_static_external_target'] };\n }\n if (ts.isIdentifier(expr)) {\n if (depth >= maxAliasDepth) return { status: 'unknown', sourceKind: 'const_alias', rawExpression: safeRaw(expr), placeholderKeys: [], evidence: ['alias_depth_exceeded'], constName: expr.text };\n const binding = resolveBinding(expr, use);\n if (!binding.declaration || !binding.initializer || !binding.immutable) return { status: 'dynamic', sourceKind: 'dynamic_expression', rawExpression: safeRaw(expr), placeholderKeys: [], evidence: binding.evidence, constName: expr.text };\n if (seen.has(binding.declaration)) return { status: 'unknown', sourceKind: 'const_alias', rawExpression: safeRaw(expr), placeholderKeys: [], evidence: ['alias_cycle_detected'], constName: expr.text };\n seen.add(binding.declaration);\n const resolved = resolveExpression(binding.initializer, binding.declaration, policy, depth + 1, seen);\n return { ...resolved, sourceKind: 'const_alias', rawExpression: safeRaw(expr), constName: expr.text, evidence: [...binding.evidence, ...resolved.evidence] };\n }\n return { status: 'dynamic', sourceKind: 'dynamic_expression', rawExpression: safeRaw(expr), placeholderKeys: [], evidence: [`unsupported_${ts.SyntaxKind[expr.kind] ?? 'expression'}`] };\n}\nfunction staticExpressionText(expr: ts.Expression | undefined, initializers: Map<string, ts.Expression>): string | undefined {\n if (!expr) return undefined;\n if (isStringLike(expr)) return expr.text;\n if (ts.isIdentifier(expr) && initializers.has(expr.text)) return staticExpressionText(initializers.get(expr.text), initializers);\n return undefined;\n}\nfunction operationPathFromStatic(text: string | undefined): string | undefined {\n return text ? `/${stripQuotes(text).replace(/^\\//, '')}` : undefined;\n}\nfunction destinationExpressionShape(expr: ts.Expression | undefined): string | undefined {\n if (!expr) return undefined;\n if (ts.isIdentifier(expr)) return 'identifier';\n if (ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr)) return 'property_read';\n if (ts.isCallExpression(expr)) return 'function_call';\n if (ts.isConditionalExpression(expr)) return 'conditional';\n if (ts.isBinaryExpression(expr)) return 'binary_expression';\n if (ts.isTemplateExpression(expr)) return 'template_expression';\n return ts.SyntaxKind[expr.kind] ?? 'expression';\n}\nfunction staticConditionalCandidates(expr: ts.Expression | undefined, initializers: Map<string, ts.Expression>): string[] | undefined {\n const resolved = expr && ts.isIdentifier(expr) && initializers.has(expr.text) ? initializers.get(expr.text) : expr;\n if (!resolved || !ts.isConditionalExpression(resolved)) return undefined;\n const left = staticExpressionText(resolved.whenTrue, initializers);\n const right = staticExpressionText(resolved.whenFalse, initializers);\n if (!left || !right) return undefined;\n return [...new Set([left, right])];\n}\nfunction propertyInitializer(object: ts.ObjectLiteralExpression, key: string): ts.Expression | undefined {\n for (const property of object.properties) {\n if (ts.isPropertyAssignment(property) && nameOfProperty(property.name) === key) return property.initializer;\n if (ts.isShorthandPropertyAssignment(property) && property.name.text === key) return property.name;\n }\n return undefined;\n}\nfunction httpMethodFromObject(object: ts.ObjectLiteralExpression, use: ts.Node): string | undefined {\n const text = resolveExpression(propertyInitializer(object, 'method'), use, 'literal').value;\n return text ? stripQuotes(text).toUpperCase() : undefined;\n}\nconst supportedHttpMethods = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD']);\nfunction safeOperationName(value: string | undefined): string | undefined {\n if (!value || !/^[A-Za-z_$][\\w$]*(?:[./][A-Za-z_$][\\w$]*)*$/.test(value)) return undefined;\n return operationPathFromStatic(value);\n}\nfunction wrapperSourceKind(sourceKind: string): string {\n if (sourceKind.includes('const_alias')) return 'const';\n if (sourceKind.includes('template')) return 'template';\n if (sourceKind.includes('string_literal')) return 'literal';\n return sourceKind.includes('conditional') ? 'ambiguous' : 'dynamic';\n}\nfunction literalPathSource(analysis: OperationPathAnalysis): string | undefined {\n if (analysis.status !== 'static') return undefined;\n if (analysis.sourceKind.includes('const_alias')) return 'same_scope_const_initializer';\n if (analysis.sourceKind.includes('no_substitution_template')) return 'template';\n return analysis.sourceKind.includes('string_literal') ? 'literal' : analysis.sourceKind;\n}\nfunction legacyPathCandidates(analysis: OperationPathAnalysis): Record<string, unknown> | undefined {\n if (analysis.candidateRawPaths.length < 2 && analysis.dynamicReassignments.length === 0)\n return undefined;\n return {\n candidatePaths: analysis.candidateRawPaths,\n normalizedCandidateOperations: analysis.candidateNormalizedOperationPaths\n .map((value) => value.replace(/^\\//, '')),\n candidateSourceKind: analysis.sourceKind,\n candidateIdentifier: analysis.candidateIdentifier,\n hasDynamicAssignments: analysis.dynamicReassignments.length > 0,\n conservativeReason: analysis.dynamicReassignments.length > 0\n ? 'dynamic_assignment_observed'\n : 'candidate_tie',\n };\n}\nfunction hasTemplatePlaceholder(value: string): boolean { return /\\$\\{|%7B|%7D/i.test(value); }\nfunction urlTargetFromExpression(expr: ts.Expression | undefined, use: ts.Node): Record<string, unknown> {\n const resolved = resolveExpression(expr, use, 'external');\n if (resolved.status === 'static' && resolved.value && !hasTemplatePlaceholder(resolved.value)) return { kind: 'static_url', expression: resolved.value, dynamic: false, sourceKind: resolved.sourceKind };\n if (expr) return { kind: 'url_expression', dynamic: true, expression: `${resolved.sourceKind}:${resolved.placeholderKeys.join('|')}`, expressionShape: resolved.sourceKind, placeholderKeys: resolved.placeholderKeys };\n return { kind: 'unknown', dynamic: false };\n}\nfunction destinationTargetFromExpression(expr: ts.Expression | undefined, use: ts.Node): Record<string, unknown> | undefined {\n const resolved = resolveExpression(expr, use, 'external');\n const text = resolved.value;\n if (resolved.status === 'static' && text && !hasTemplatePlaceholder(text)) return { kind: 'destination', expression: text, dynamic: false, sourceKind: resolved.sourceKind };\n const candidates = staticConditionalCandidates(expr, new Map<string, ts.Expression>());\n if (candidates) return { kind: 'destination', dynamic: true, expressionShape: 'conditional', candidateLiterals: candidates };\n const shape = destinationExpressionShape(expr);\n if (shape) return { kind: 'destination', dynamic: true, expressionShape: shape };\n return undefined;\n}\nfunction externalHttpEvidence(node: ts.CallExpression, source: ts.SourceFile): { method?: string; externalTarget: Record<string, unknown>; classifier: string; sourceCallShape: string } | undefined {\n const expr = node.expression;\n const exprText = expr.getText(source);\n if (exprText === 'useOrFetchDestination') {\n const objectArg = node.arguments[0];\n if (objectArg && ts.isObjectLiteralExpression(objectArg)) {\n const destination = destinationTargetFromExpression(propertyInitializer(objectArg, 'destinationName'), node);\n return { externalTarget: destination ?? { kind: 'unknown', dynamic: false }, classifier: 'sap_destination_lookup', sourceCallShape: 'useOrFetchDestination' };\n }\n }\n if (exprText === 'executeHttpRequest') {\n const destination = destinationTargetFromExpression(node.arguments[0], node);\n const config = node.arguments[1];\n const method = config && ts.isObjectLiteralExpression(config) ? httpMethodFromObject(config, node) : undefined;\n const url = config && ts.isObjectLiteralExpression(config) ? urlTargetFromExpression(propertyInitializer(config, 'url'), node) : { kind: 'unknown', dynamic: false };\n return { method, externalTarget: destination ? { ...url, destination } : url, classifier: 'sap_execute_http_request', sourceCallShape: 'executeHttpRequest' };\n }\n if (exprText === 'axios') {\n const config = node.arguments[0];\n if (config && ts.isObjectLiteralExpression(config)) {\n const method = httpMethodFromObject(config, node);\n return { method, externalTarget: urlTargetFromExpression(propertyInitializer(config, 'url'), node), classifier: 'axios_config_call', sourceCallShape: 'axios(config)' };\n }\n return { externalTarget: { kind: 'unknown', dynamic: false }, classifier: 'axios_unknown_call', sourceCallShape: 'axios(...)' };\n }\n if (exprText === 'fetch') {\n const init = node.arguments[1];\n const method = init && ts.isObjectLiteralExpression(init) ? httpMethodFromObject(init, node) : undefined;\n return { method, externalTarget: urlTargetFromExpression(node.arguments[0], node), classifier: 'fetch_call', sourceCallShape: 'fetch' };\n }\n if (ts.isPropertyAccessExpression(expr) && ['get','post','put','patch','delete','head'].includes(expr.name.text) && expr.expression.getText(source) === 'axios') {\n return { method: expr.name.text.toUpperCase(), externalTarget: urlTargetFromExpression(node.arguments[0], node), classifier: 'axios_member_call', sourceCallShape: `axios.${expr.name.text}` };\n }\n return undefined;\n}\nfunction collectServiceVariables(source: ts.SourceFile): Set<string> {\n const vars = new Set<string>(['cds', 'messaging', 'messageClient', 'eventClient']);\n const visit = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {\n const text = node.initializer.getText(source);\n if (/cds\\.connect\\.(to|messaging)\\s*\\(/.test(text)) vars.add(node.name.text);\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return vars;\n}\nfunction receiverName(expr: ts.Expression): string | undefined {\n if (ts.isIdentifier(expr)) return expr.text;\n if (ts.isPropertyAccessExpression(expr)) return expr.getText(sourceOf(expr));\n return undefined;\n}\nfunction sourceOf(node: ts.Node): ts.SourceFile {\n return node.getSourceFile();\n}\nfunction rootReceiverName(expr: ts.Expression): string | undefined {\n if (ts.isIdentifier(expr)) return expr.text;\n if (ts.isPropertyAccessExpression(expr)) return rootReceiverName(expr.expression);\n if (ts.isCallExpression(expr)) return rootReceiverName(expr.expression);\n return undefined;\n}\nfunction isSupportedEventReceiver(receiver: string | undefined, rootReceiver: string | undefined, serviceVariables: Set<string>): boolean {\n const candidate = rootReceiver ?? receiver;\n if (!candidate) return false;\n if (candidate === 'cds') return true;\n if (serviceVariables.has(candidate)) return true;\n if (receiver && serviceVariables.has(receiver)) return true;\n if (/^(srv|service|serviceClient|messaging|messageClient|eventClient)$/.test(candidate)) return true;\n return false;\n}\ninterface WrapperSpec { clientIndex?: number; clientName?: string; pathIndex: number; methodIndex?: number; methodName?: string; methodLiteral?: string; nestedWrapperFunction?: string; definitionLine: number; internalStart: number; internalEnd: number }\nfunction collectWrapperSpecs(source: ts.SourceFile): Map<string, WrapperSpec> {\n const specs = new Map<string, WrapperSpec>();\n const serviceVariables = collectServiceVariables(source);\n const calledNames = new Set<string>();\n const collectCalls = (node: ts.Node): void => {\n if (ts.isCallExpression(node) && ts.isIdentifier(node.expression))\n calledNames.add(node.expression.text);\n if (ts.isCallExpression(node) && ts.isCallExpression(node.expression)\n && ts.isIdentifier(node.expression.expression))\n calledNames.add(node.expression.expression.text);\n ts.forEachChild(node, collectCalls);\n };\n collectCalls(source);\n const scanFunction = (name: string, fn: ts.FunctionLikeDeclaration): void => {\n if (!calledNames.has(name) && !isExportedWrapper(fn)) return;\n const params = fn.parameters.map((param) => ts.isIdentifier(param.name) ? param.name.text : undefined);\n const sends: Array<{ client: string; path: string; method?: string; methodLiteral?: string; nestedWrapperFunction?: string; start: number; end: number }> = [];\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'send' && ts.isIdentifier(node.expression.expression)) {\n const objectArg = node.arguments[0];\n if (objectArg && ts.isObjectLiteralExpression(objectArg)) {\n const pathProp = propertyInitializer(objectArg, 'path');\n const methodProp = propertyInitializer(objectArg, 'method');\n const pathName = pathProp && ts.isIdentifier(pathProp) ? pathProp.text : undefined;\n const methodName = methodProp && ts.isIdentifier(methodProp) ? methodProp.text : undefined;\n const methodLiteral = resolveExpression(methodProp, node, 'literal').value;\n if (pathName) sends.push({ client: node.expression.expression.text, path: pathName, method: methodName, methodLiteral, start: node.getStart(source), end: node.getEnd() });\n }\n }\n if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && specs.has(node.expression.text)) {\n const nested = specs.get(node.expression.text);\n const pathArg = nested ? node.arguments[nested.pathIndex] : undefined;\n const clientArg = nested?.clientIndex === undefined ? undefined : node.arguments[nested.clientIndex];\n const pathName = pathArg && ts.isIdentifier(pathArg) ? pathArg.text : undefined;\n const clientName = clientArg && ts.isIdentifier(clientArg) ? clientArg.text : nested?.clientName;\n if (nested && pathName && clientName) sends.push({ client: clientName, path: pathName, method: nested.methodName, methodLiteral: nested.methodLiteral, nestedWrapperFunction: node.expression.text, start: node.getStart(source), end: node.getEnd() });\n }\n ts.forEachChild(node, visit);\n };\n visit(fn);\n if (sends.length !== 1) return;\n const found = sends[0];\n const clientIndex = params.indexOf(found.client);\n const pathIndex = params.indexOf(found.path);\n const methodIndex = found.method ? params.indexOf(found.method) : -1;\n const capturesKnownClient = serviceVariables.has(found.client) || /^(srv|service|serviceClient|client|.*Client)$/.test(found.client);\n if (pathIndex >= 0 && (clientIndex >= 0 || capturesKnownClient)) specs.set(name, { clientIndex: clientIndex >= 0 ? clientIndex : undefined, clientName: clientIndex >= 0 ? undefined : found.client, pathIndex, methodIndex: methodIndex >= 0 ? methodIndex : undefined, methodName: found.method, methodLiteral: found.methodLiteral, nestedWrapperFunction: found.nestedWrapperFunction, definitionLine: lineOf(source.text, fn.getStart(source)), internalStart: found.start, internalEnd: found.end });\n };\n const visitTop = (node: ts.Node): void => {\n if (ts.isFunctionDeclaration(node) && node.name) scanFunction(node.name.text, node);\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))) scanFunction(node.name.text, node.initializer);\n ts.forEachChild(node, visitTop);\n };\n visitTop(source);\n return specs;\n}\nfunction isExportedWrapper(fn: ts.FunctionLikeDeclaration): boolean {\n const declaration = ts.isFunctionDeclaration(fn)\n ? fn\n : ts.isVariableDeclaration(fn.parent)\n ? fn.parent.parent.parent\n : undefined;\n if (!declaration || !ts.canHaveModifiers(declaration)) return false;\n return ts.getModifiers(declaration)?.some((modifier) =>\n modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;\n}\nexport function classifyOutboundCallsInSource(source: ts.SourceFile, filePath: string): ClassifiedOutboundCall[] {\n const calls: ClassifiedOutboundCall[] = [];\n const sourceFile = normalizePath(filePath);\n const initializers = variableInitializers(source);\n const serviceVariables = collectServiceVariables(source);\n const wrapperSpecs = collectWrapperSpecs(source);\n const wrapperInternalRanges = [...wrapperSpecs.values()].map((spec) => ({ start: spec.internalStart, end: spec.internalEnd }));\n const add = (node: ts.CallExpression, fact: Omit<OutboundCallFact, 'sourceFile' | 'sourceLine' | 'confidence'> & { confidence?: number }, extra?: Record<string, unknown>): void => {\n calls.push({ node, fact: {\n ...fact,\n sourceFile,\n sourceLine: lineOf(source.text, node.getStart(source)),\n callSiteStartOffset: node.getStart(source),\n callSiteEndOffset: node.getEnd(),\n confidence: fact.confidence ?? 0.8,\n evidence: parserEvidence(source, node, extra),\n } });\n };\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node)) {\n if (wrapperInternalRanges.some((range) => node.getStart(source) >= range.start && node.getEnd() <= range.end)) {\n return;\n }\n const expr = node.expression;\n const exprText = expr.getText(source);\n const directQuery = directQueryBuilderStatement(node);\n if (exprText === 'cds.run') {\n const arg = node.arguments[0];\n const entity = arg ? queryEntityFromAst(arg, initializers) : undefined;\n const payload = arg?.getText(source) ?? '';\n add(node, { callType: 'local_db_query', queryEntity: entity, payloadSummary: summarizeExpression(payload), confidence: entity ? 0.9 : 0.55, unresolvedReason: entity ? undefined : queryWarning(payload) }, queryRunEvidence(source, arg));\n } else if (directQuery) {\n const entity = queryEntityFromAst(directQuery.logicalCall, initializers);\n const payload = directQuery.logicalCall.getText(source);\n add(directQuery.logicalCall, { callType: 'local_db_query', queryEntity: entity, payloadSummary: summarizeExpression(payload), confidence: entity ? 0.9 : 0.55, unresolvedReason: entity ? undefined : queryWarning(payload) }, queryBuilderEvidence(source, directQuery));\n } else if (ts.isPropertyAccessExpression(expr) && expr.name.text === 'send' && (ts.isIdentifier(expr.expression) || ts.isPropertyAccessExpression(expr.expression))) {\n const objectArg = node.arguments[0];\n if (objectArg && ts.isObjectLiteralExpression(objectArg)) {\n const receiver = receiverName(expr.expression);\n const queryExpression = propertyInitializer(objectArg, 'query');\n const methodExpression = propertyInitializer(objectArg, 'method');\n const methodResolution = resolveExpression(methodExpression, node, 'literal');\n const method = stripQuotes(methodResolution.value ?? 'POST');\n const dynamicMethodDefaulted = Boolean(methodExpression && methodResolution.value === undefined);\n const pathExpr = propertyInitializer(objectArg, 'path') ?? propertyInitializer(objectArg, 'event');\n const pathAnalysis = analyzeOperationPath(pathExpr, node, method);\n const op = pathExpr ? operationPathExpression(pathAnalysis) ?? pathExpr.getText(source) : undefined;\n const shorthandPath = objectPropertyIsShorthand(objectArg, 'path');\n const operationPathExpr = operationPathExpression(pathAnalysis);\n const intent = classifyODataPathIntent(operationPathExpr, method);\n const entityCallTypes: Record<string, OutboundCallFact['callType']> = { entity_mutation: 'remote_entity_mutation', entity_delete: 'remote_entity_delete', entity_media: 'remote_entity_media', entity_candidate: 'remote_entity_candidate' };\n const entityCallType = entityCallTypes[intent.kind];\n const isODataQueryRead = method.toUpperCase() === 'GET' && ['entity_query', 'entity_key_read', 'entity_navigation_query'].includes(intent.kind);\n const queryEntity = queryExpression\n ? queryEntityFromAst(queryExpression, initializers)\n : isODataQueryRead ? intent.entitySegment : undefined;\n const unresolvedReason = queryExpression\n ? queryEntity ? undefined : queryWarning(queryExpression.getText(source))\n : pathExpr ? pathUnresolvedReason(pathAnalysis) : undefined;\n add(node, { callType: queryExpression ? 'remote_query' : entityCallType ?? (isODataQueryRead ? 'remote_query' : 'remote_action'), serviceVariableName: receiver, method, operationPathExpr, queryEntity, payloadSummary: summarizeExpression(objectArg.getText(source)), confidence: op || queryExpression ? 0.8 : 0.4, unresolvedReason }, { receiver, classifier: 'service_client_send_object', operationPathExpression: shorthandPath ? op : undefined, rawPathExpression: pathAnalysis.rawExpression, literalPathSource: literalPathSource(pathAnalysis), odataPathIntent: operationPathExpr ? intent : undefined, pathAnalysis, staticPathCandidates: legacyPathCandidates(pathAnalysis), parserWarning: unresolvedReason, ...(dynamicMethodDefaulted ? { dynamicMethodDefaulted: true } : {}) });\n } else {\n const receiver = receiverName(expr.expression);\n const rootReceiver = rootReceiverName(expr.expression);\n const firstArg = resolveExpression(node.arguments[0], node, 'literal');\n const method = firstArg.value?.toUpperCase();\n const pathArg = node.arguments[1];\n const supported = method && supportedHttpMethods.has(method);\n if (receiver && supported && serviceVariables.has(rootReceiver ?? receiver)) {\n const pathAnalysis = analyzeOperationPath(pathArg, node, method);\n const operationPathExpr = operationPathExpression(pathAnalysis);\n const intent = classifyODataPathIntent(operationPathExpr, method);\n const unresolvedReason = pathUnresolvedReason(pathAnalysis);\n add(node, { callType: 'remote_action', serviceVariableName: rootReceiver ?? receiver, method, operationPathExpr, payloadSummary: summarizeExpression(node.getText(source)), confidence: operationPathExpr ? 0.8 : 0.45, unresolvedReason }, { receiver, rootReceiver, classifier: 'service_client_send_method_path', rawPathExpression: pathAnalysis.rawExpression, literalPathSource: literalPathSource(pathAnalysis), odataPathIntent: operationPathExpr ? intent : undefined, pathAnalysis, staticPathCandidates: legacyPathCandidates(pathAnalysis), parserWarning: unresolvedReason });\n } else if (receiver && serviceVariables.has(rootReceiver ?? receiver)) {\n const operationPathExpr = safeOperationName(firstArg.value);\n add(node, { callType: 'remote_action', serviceVariableName: rootReceiver ?? receiver, operationPathExpr, payloadSummary: summarizeExpression(node.getText(source)), confidence: operationPathExpr ? 0.75 : 0.35, unresolvedReason: operationPathExpr ? undefined : 'unsupported_cap_send_signature' }, { receiver, rootReceiver, classifier: operationPathExpr ? 'service_client_send_operation_event' : 'service_client_send_unsupported_signature', rawOperationExpression: firstArg.rawExpression, literalOperationSource: firstArg.value ? firstArg.sourceKind : undefined, parserWarning: operationPathExpr ? undefined : 'unsupported_cap_send_signature' });\n }\n }\n } else if (((ts.isCallExpression(expr) && ts.isIdentifier(expr.expression) && wrapperSpecs.has(expr.expression.text)) || (ts.isIdentifier(expr) && wrapperSpecs.has(expr.text)))) {\n const wrapperName = ts.isIdentifier(expr) ? expr.text : ts.isCallExpression(expr) && ts.isIdentifier(expr.expression) ? expr.expression.text : '';\n const wrapperArgs = ts.isIdentifier(expr) ? node.arguments : ts.isCallExpression(expr) ? expr.arguments : node.arguments;\n const spec = wrapperSpecs.get(wrapperName);\n const clientArg = spec?.clientIndex === undefined ? undefined : wrapperArgs[spec.clientIndex];\n const pathArg = spec ? wrapperArgs[spec.pathIndex] : undefined;\n const methodArg = spec?.methodIndex === undefined ? undefined : wrapperArgs[spec.methodIndex];\n const receiver = clientArg && ts.isIdentifier(clientArg) ? clientArg.text : spec?.clientName;\n const method = stripQuotes(resolveExpression(methodArg, node, 'literal').value ?? spec?.methodLiteral ?? 'POST');\n const pathAnalysis = analyzeOperationPath(pathArg, node, method);\n const operationPathExpr = operationPathExpression(pathAnalysis);\n const normalizedOperationPath = operationPathExpr ? classifyODataPathIntent(operationPathExpr, method).topLevelOperationName : undefined;\n const unresolvedReason = pathUnresolvedReason(pathAnalysis);\n if (spec && receiver && operationPathExpr) {\n add(node, { callType: 'remote_action', serviceVariableName: receiver, method, operationPathExpr, payloadSummary: summarizeExpression(node.getText(source)), confidence: 0.75, unresolvedReason }, { receiver, classifier: pathAnalysis.sourceKind.includes('string_literal') ? 'higher_order_wrapper_literal_path' : 'higher_order_wrapper_static_path', wrapperFunction: wrapperName, nestedWrapperFunction: spec.nestedWrapperFunction, wrapperDefinitionLine: spec.definitionLine, callerLine: lineOf(source.text, node.getStart(source)), wrapperPathSourceKind: wrapperSourceKind(pathAnalysis.sourceKind), rawPathExpression: pathAnalysis.rawExpression, normalizedOperationPath, literalPathSource: pathAnalysis.sourceKind.includes('const_alias') ? 'same_scope_const_initializer' : `wrapper_call_${wrapperSourceKind(pathAnalysis.sourceKind)}`, literalCallerArgumentDetected: true, pathAnalysis });\n } else if (spec && receiver) {\n add(node, { callType: 'remote_action', serviceVariableName: receiver, method, payloadSummary: summarizeExpression(node.getText(source)), confidence: 0.45, unresolvedReason }, { receiver, classifier: pathAnalysis.status === 'ambiguous' ? 'higher_order_wrapper_ambiguous_path' : 'higher_order_wrapper_dynamic_path', wrapperFunction: wrapperName, wrapperDefinitionLine: spec.definitionLine, callerLine: lineOf(source.text, node.getStart(source)), wrapperPathSourceKind: wrapperSourceKind(pathAnalysis.sourceKind), rawPathExpression: pathAnalysis.rawExpression, pathAnalysis, parserWarning: unresolvedReason });\n }\n } else if (ts.isPropertyAccessExpression(expr) && ['emit', 'publish', 'on'].includes(expr.name.text)) {\n const receiver = receiverName(expr.expression);\n const rootReceiver = rootReceiverName(expr.expression);\n if (isSupportedEventReceiver(receiver, rootReceiver, serviceVariables)) {\n const eventName = literalText(node.arguments[0]);\n const effectiveReceiver = rootReceiver ?? receiver;\n const lifecycleHook = effectiveReceiver === 'cds'\n && CDS_LIFECYCLE_EVENTS.has(eventName ?? '');\n const errorHook = expr.name.text === 'on' && eventName === 'error';\n if (eventName && !lifecycleHook && !errorHook) add(node, { callType: expr.name.text === 'on' ? 'async_subscribe' : 'async_emit', serviceVariableName: effectiveReceiver, eventNameExpr: eventName }, { receiver, rootReceiver, classifier: expr.name.text === 'on' ? 'cap_service_event_subscription' : 'cap_service_event_emit', receiverClassification: 'cap_evidence' });\n }\n } else {\n const external = externalHttpEvidence(node, source);\n if (external) {\n const evidenceTarget = { ...external.externalTarget, method: external.method, parserClassifier: external.classifier, sourceCallShape: external.sourceCallShape };\n const safeTarget = externalHttpTarget({ method: external.method, evidence_json: JSON.stringify({ externalTarget: evidenceTarget }) });\n add(node, { callType: 'external_http', method: external.method, payloadSummary: undefined, confidence: 0.7, unresolvedReason: 'External HTTP destination is outside indexed CAP services', externalTarget: { kind: safeTarget.kind, stableId: safeTarget.toId, label: safeTarget.label, dynamic: safeTarget.dynamic } }, { classifier: external.classifier, externalTarget: safeTarget, sourceCallShape: external.sourceCallShape });\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return calls;\n}\nexport function containsSupportedOutboundCall(node: ts.Node): boolean {\n const source = node.getSourceFile();\n const start = node.getFullStart();\n const end = node.getEnd();\n return classifyOutboundCallsInSource(source, source.fileName).some((call) => call.node.getStart(source) >= start && call.node.getEnd() <= end);\n}\nexport async function parseOutboundCalls(\n repoPath: string,\n filePath: string,\n context?: RepositorySourceContext,\n): Promise<OutboundCallFact[]> {\n const snapshot = context?.get(filePath);\n const text = snapshot?.text\n ?? await fs.readFile(path.join(repoPath, filePath), 'utf8');\n const source = snapshot?.sourceFile() ?? ts.createSourceFile(\n filePath, text, ts.ScriptTarget.Latest, true,\n filePath.endsWith('.ts') ? ts.ScriptKind.TS : ts.ScriptKind.JS,\n );\n const bindingNames = new Set((await parseServiceBindings(\n repoPath, filePath, context,\n )).map((binding) => binding.variableName));\n const importedWrappers = await parseImportedWrapperCalls(\n repoPath, filePath, source, bindingNames, context,\n );\n return [...classifyOutboundCallsInSource(source, filePath).map((call) => call.fact), ...importedWrappers, ...parseLocalServiceCalls(text, filePath, source)];\n}\nfunction parseLocalServiceCalls(\n text: string,\n filePath: string,\n source = ts.createSourceFile(\n filePath, text, ts.ScriptTarget.Latest, true,\n filePath.endsWith('.ts') ? ts.ScriptKind.TS : ts.ScriptKind.JS,\n ),\n): OutboundCallFact[] {\n const aliases = new Map<string, { service: string; lookup: string; chain: string[] }>();\n const calls: OutboundCallFact[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {\n const origin = serviceLookup(node.initializer, aliases);\n if (origin) aliases.set(node.name.text, { ...origin, chain: [...origin.chain, node.name.text] });\n }\n if (ts.isCallExpression(node)) {\n const parsed = serviceOperationCall(node, aliases);\n if (parsed && parsed.operation !== 'entities') calls.push({\n callType: 'local_service_call',\n operationPathExpr: `/${parsed.operation}`,\n payloadSummary: parsed.service,\n localServiceName: parsed.service,\n localServiceLookup: parsed.lookup,\n aliasChain: parsed.chain,\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(text, node.getStart(source)),\n callSiteStartOffset: node.getStart(source),\n callSiteEndOffset: node.getEnd(),\n confidence: 0.9,\n unresolvedReason: ['send', 'emit', 'publish', 'on'].includes(parsed.operation) ? 'transport_client_method' : undefined,\n evidence: parserEvidence(source, node, {\n classifier: parsed.classifier,\n parserCallType: parsed.operation === 'send' ? 'transport_client_method' : parsed.classifier,\n localServiceLookup: parsed.lookup,\n localServiceName: parsed.service,\n operation: parsed.operation,\n aliasChain: parsed.chain,\n }),\n });\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return calls;\n}\nfunction serviceLookup(expr: ts.Expression, aliases: Map<string, { service: string; lookup: string; chain: string[] }>): { service: string; lookup: string; chain: string[] } | undefined {\n if (ts.isIdentifier(expr)) return aliases.get(expr.text);\n if (ts.isPropertyAccessExpression(expr) && expr.expression.getText() === 'cds.services') return { service: expr.name.text, lookup: expr.getText(), chain: [expr.getText()] };\n if (ts.isElementAccessExpression(expr) && expr.expression.getText() === 'cds.services' && ts.isStringLiteral(expr.argumentExpression)) return { service: expr.argumentExpression.text, lookup: expr.getText(), chain: [expr.getText()] };\n return undefined;\n}\nfunction serviceOperationCall(node: ts.CallExpression, aliases: Map<string, { service: string; lookup: string; chain: string[] }>): { service: string; lookup: string; chain: string[]; operation: string; classifier: string } | undefined {\n const expr = node.expression;\n if (!ts.isPropertyAccessExpression(expr)) return undefined;\n const origin = serviceLookup(expr.expression, aliases);\n if (!origin) return undefined;\n if (expr.name.text === 'send') {\n const first = literalText(node.arguments[0]);\n const second = literalText(node.arguments[1]);\n const method = first?.toUpperCase();\n if (method && ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'].includes(method) && second) return { ...origin, operation: second.replace(/^\\//, ''), classifier: 'cap_service_send_method_path' };\n if (first) return { ...origin, operation: first.replace(/^\\//, ''), classifier: 'cap_service_send_local_dispatch' };\n }\n return { ...origin, operation: expr.name.text, classifier: 'local_cap_service_call' };\n}\n","import { createHash } from 'node:crypto';\nimport { projectBounded } from '../utils/000-bounded-projection.js';\n\nexport type ExternalTargetKind = 'destination' | 'static_url' | 'url_expression' | 'unknown';\nexport interface ExternalHttpTarget { kind: ExternalTargetKind; toKind: 'external_destination' | 'external_endpoint'; toId: string; label: string; method?: string; dynamic: boolean; expression?: string; candidateLiteralCount?: number; shownCandidateLiteralCount?: number; omittedCandidateLiteralCount?: number; }\nconst sensitiveKeys = new Set(['token','access_token','id_token','api_key','apikey','key','password','passwd','pwd','secret','client_secret','authorization','cookie','signature']);\nfunction hash(value: string): string { return createHash('sha256').update(value).digest('hex').slice(0, 12); }\nfunction methodPrefix(method: unknown): string { return typeof method === 'string' && method.length > 0 ? `${method.toUpperCase()} ` : ''; }\nexport function redactUrl(value: string): string {\n try {\n const url = new URL(value, value.startsWith('/') ? 'https://relative.invalid' : undefined);\n url.username = ''; url.password = '';\n for (const key of [...url.searchParams.keys()]) url.searchParams.set(key, sensitiveKeys.has(key.toLowerCase()) ? '<redacted>' : '<redacted>');\n const path = `${url.pathname}${url.search ? url.search : ''}`;\n return value.startsWith('/') ? path : `${url.origin}${path}`;\n } catch {\n return value.replace(/([?&][^=;&]*(?:token|key|password|secret|cookie|authorization)[^=;&]*=)[^&]*/gi, '$1<redacted>');\n }\n}\nexport function externalHttpTarget(call: Record<string, unknown>): ExternalHttpTarget {\n const evidence = typeof call.evidence_json === 'string' ? safeParse(call.evidence_json) : {};\n const target = evidence.externalTarget && typeof evidence.externalTarget === 'object' && !Array.isArray(evidence.externalTarget) ? evidence.externalTarget as Record<string, unknown> : {};\n const method = typeof call.method === 'string' ? call.method : typeof target.method === 'string' ? target.method : undefined;\n const kind = typeof target.kind === 'string' ? target.kind : 'unknown';\n const expression = typeof target.expression === 'string' ? target.expression : undefined;\n if (kind === 'destination' && target.dynamic === true) {\n const shape = typeof target.expressionShape === 'string' ? target.expressionShape : 'expression';\n const candidates = staticDestinationCandidates(target.candidateLiterals);\n const projection = projectBounded(candidates, (left, right) => left.localeCompare(right));\n return {\n kind,\n toKind: 'external_destination',\n toId: `destination:dynamic:${hash(`${shape}:${candidates.join('|')}`)}`,\n label: 'External destination: dynamic destination',\n method,\n dynamic: true,\n expression: projection.items.length\n ? `candidates:${projection.items.join('|')}`\n : `shape:${shape}`,\n candidateLiteralCount: projection.totalCount,\n shownCandidateLiteralCount: projection.shownCount,\n omittedCandidateLiteralCount: projection.omittedCount,\n };\n }\n if (kind === 'destination' && expression) return { kind, toKind: 'external_destination', toId: `destination:${expression}`, label: `External destination: ${expression}`, method, dynamic: false, expression };\n if (kind === 'static_url' && expression) {\n const redacted = redactUrl(expression);\n return { kind, toKind: 'external_endpoint', toId: `endpoint:${hash(`${method ?? ''}:${redacted}`)}`, label: `External endpoint: ${methodPrefix(method)}${redacted}`, method, dynamic: false, expression: redacted };\n }\n if (kind === 'url_expression' && expression) return { kind, toKind: 'external_endpoint', toId: `dynamic:${hash(expression)}`, label: `External endpoint: ${methodPrefix(method)}dynamic URL`, method, dynamic: true, expression: `expr:${hash(expression)}` };\n return { kind: 'unknown', toKind: 'external_endpoint', toId: 'unknown', label: 'External endpoint: unknown', method, dynamic: false };\n}\nfunction staticDestinationCandidates(value: unknown): string[] {\n const candidates = Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n return [...new Set(candidates)].sort();\n}\nfunction safeParse(value: string): Record<string, unknown> { try { const parsed = JSON.parse(value) as unknown; return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {}; } catch { return {}; } }\n","export interface NormalizedODataOperationPath {\n rawOperationPath: string;\n normalizedOperationPath: string;\n wasInvocation: boolean;\n invocationArguments?: string;\n invocationArgumentPlaceholderKeys: string[];\n normalizationReason?: string;\n normalizationRejectedReason?: string;\n}\n\nexport type ODataPathIntentKind = 'operation_invocation' | 'entity_query' | 'entity_key_read' | 'entity_navigation_query' | 'entity_mutation' | 'entity_delete' | 'entity_media' | 'entity_candidate' | 'unknown';\n\nexport interface ODataPathIntent {\n kind: ODataPathIntentKind;\n rawPath: string;\n method: string;\n pathWithoutQuery: string;\n queryString?: string;\n hasQueryString: boolean;\n entitySegment?: string;\n placeholderKeys: string[];\n keyPredicatePlaceholderKeys: string[];\n invocationArgumentPlaceholderKeys: string[];\n invocationArguments?: string;\n navigationSuffix?: string;\n mediaOrPropertySuffix?: string;\n hasEntityKeyPredicate: boolean;\n hasNavigationSuffix: boolean;\n hasMediaOrPropertySuffix: boolean;\n topLevelOperationName?: string;\n topLevelOperationNameCandidate: boolean;\n topLevelOperationInvocation: boolean;\n reason: string;\n}\n\nexport function normalizeODataOperationInvocationPath(path: string | undefined): NormalizedODataOperationPath | undefined {\n if (path === undefined) return undefined;\n const raw = path.trim();\n if (!raw) return undefined;\n const rejected = (reason: string): NormalizedODataOperationPath => ({ rawOperationPath: raw, normalizedOperationPath: raw, wasInvocation: false, invocationArgumentPlaceholderKeys: [], normalizationRejectedReason: reason });\n const open = raw.indexOf('(');\n if (open < 0) return rejected('no_top_level_parenthesis');\n const query = topLevelQueryIndex(raw);\n if (query >= 0) return rejected('query_string_paths_are_not_operation_invocations');\n if (!raw.startsWith('/')) return rejected('path_is_not_absolute');\n if (raw.slice(1, open).includes('/')) return rejected('operation_segment_contains_navigation_separator');\n const close = matchingClose(raw, open);\n if (close === undefined) return rejected('top_level_invocation_parenthesis_is_unbalanced');\n if (raw.slice(close + 1).trim().length > 0) return rejected('top_level_invocation_does_not_cover_remaining_path');\n const operationSegment = raw.slice(0, open).trim();\n if (operationSegment.length <= 1) return rejected('operation_segment_is_empty');\n return {\n rawOperationPath: raw,\n normalizedOperationPath: operationSegment,\n wasInvocation: true,\n invocationArguments: raw.slice(open + 1, close),\n invocationArgumentPlaceholderKeys: [...new Set(extractTemplatePlaceholders(raw.slice(open + 1, close)))],\n normalizationReason: 'balanced_top_level_operation_invocation',\n };\n}\n\nexport function classifyODataPathIntent(path: string | undefined, method: string | undefined): ODataPathIntent {\n const rawPath = (path ?? '').trim();\n const normalizedMethod = (method ?? 'GET').trim().toUpperCase() || 'GET';\n const queryIndex = rawPath.indexOf('?');\n const pathWithoutQuery = queryIndex >= 0 ? rawPath.slice(0, queryIndex) : rawPath;\n const queryString = queryIndex >= 0 ? rawPath.slice(queryIndex + 1) : undefined;\n const segments = pathWithoutQuery.replace(/^\\//, '').split('/').filter(Boolean);\n const firstSegment = segments[0] ?? '';\n const hasNavigationSegments = segments.length > 1;\n const entitySegment = entitySegmentFromPath(pathWithoutQuery);\n const placeholderKeys = [...new Set(extractTemplatePlaceholders(rawPath))];\n const firstOpen = firstSegment.indexOf('(');\n const firstClose = firstOpen >= 0 ? matchingClose(firstSegment, firstOpen) : undefined;\n const keyPredicateText = firstOpen >= 0 && firstClose !== undefined ? firstSegment.slice(firstOpen + 1, firstClose) : '';\n const rawKeyPredicatePlaceholderKeys = [...new Set(extractTemplatePlaceholders(keyPredicateText))];\n const navigationSuffix = hasNavigationSegments ? segments.slice(1).join('/') : undefined;\n const lastSegment = segments.at(-1) ?? '';\n const mediaOrPropertySuffix = hasNavigationSegments ? lastSegment : undefined;\n const invocation = normalizeODataOperationInvocationPath(pathWithoutQuery);\n const operationNameFromInvocation = invocation?.wasInvocation ? invocation.normalizedOperationPath.replace(/^\\//, '').split('.').at(-1) : undefined;\n const topLevelName = firstSegment.split('(')[0]?.replace(/^\\//, '');\n const topLevelOperationName = operationNameFromInvocation ?? (!hasNavigationSegments && !firstSegment.includes('(') ? topLevelName : undefined);\n const topLevelOperationInvocation = Boolean(invocation?.wasInvocation && looksLikeLowerCamelInvocation(firstSegment));\n const keyPredicatePlaceholderKeys = topLevelOperationInvocation ? [] : rawKeyPredicatePlaceholderKeys;\n const topLevelOperationNameCandidate = Boolean(topLevelOperationName && !hasNavigationSegments && !firstSegment.includes('('));\n const base = { rawPath, method: normalizedMethod, pathWithoutQuery, queryString, hasQueryString: queryIndex >= 0, entitySegment, placeholderKeys, keyPredicatePlaceholderKeys, invocationArguments: invocation?.invocationArguments, invocationArgumentPlaceholderKeys: invocation?.invocationArgumentPlaceholderKeys ?? [], navigationSuffix, mediaOrPropertySuffix, hasEntityKeyPredicate: firstOpen >= 0 && firstClose !== undefined, hasNavigationSuffix: hasNavigationSegments, hasMediaOrPropertySuffix: Boolean(mediaOrPropertySuffix && isMediaOrPropertySuffix(mediaOrPropertySuffix)), topLevelOperationName, topLevelOperationNameCandidate, topLevelOperationInvocation };\n if (!rawPath || !rawPath.startsWith('/')) return { ...base, kind: 'unknown', reason: 'path_missing_or_not_absolute' };\n const upperEntityLike = /^[A-Z][A-Za-z0-9_]*$/.test(entitySegment ?? firstSegment);\n const mediaLike = isMediaOrPropertySuffix(segments.at(-1) ?? '');\n if (normalizedMethod !== 'GET') {\n if (invocation?.wasInvocation && looksLikeLowerCamelInvocation(firstSegment)) return { ...base, kind: 'operation_invocation', reason: 'non_get_balanced_top_level_operation_invocation' };\n if (mediaLike) return { ...base, kind: 'entity_media', reason: 'non_get_entity_media_stream_path' };\n if (hasNavigationSegments || firstSegment.includes('(')) return { ...base, kind: normalizedMethod === 'DELETE' ? 'entity_delete' : 'entity_mutation', reason: firstSegment.includes('(') ? 'non_get_entity_key_or_navigation_path_shape' : 'non_get_entity_navigation_path_shape' };\n if (upperEntityLike) return { ...base, kind: normalizedMethod === 'DELETE' ? 'entity_delete' : 'entity_mutation', reason: 'non_get_entity_path_shape' };\n return { ...base, kind: 'operation_invocation', reason: 'non_get_lowercase_path_may_be_operation' };\n }\n if (queryIndex >= 0) {\n if (hasNavigationSegments) return { ...base, kind: 'entity_navigation_query', reason: 'get_path_has_navigation_and_query_string' };\n if (looksLikeLowerCamelInvocation(firstSegment)) return { ...base, kind: 'unknown', reason: 'get_invocation_with_query_string_requires_indexed_operation_evidence' };\n return { ...base, kind: 'entity_query', reason: 'get_collection_path_has_query_string' };\n }\n if (hasNavigationSegments) return mediaLike ? { ...base, kind: 'entity_media', reason: 'get_entity_media_stream_path' } : { ...base, kind: 'entity_navigation_query', reason: 'get_path_has_navigation_segments' };\n if (firstSegment.includes('(')) {\n if (invocation?.wasInvocation && looksLikeLowerCamelInvocation(firstSegment)) return { ...base, kind: 'operation_invocation', reason: 'get_balanced_top_level_operation_invocation' };\n return looksLikeLowerCamelInvocation(firstSegment)\n ? { ...base, kind: 'operation_invocation', reason: 'get_single_lower_camel_segment_has_top_level_invocation' }\n : { ...base, kind: 'entity_key_read', reason: 'get_entity_segment_has_key_predicate' };\n }\n if (/^[A-Z][A-Za-z0-9_]*$/.test(firstSegment)) return { ...base, kind: 'entity_candidate', reason: 'uppercase_collection_segment_without_indexed_entity_evidence' };\n return { ...base, kind: 'unknown', reason: 'get_path_has_no_query_key_or_navigation_signal' };\n}\n\nfunction entitySegmentFromPath(path: string): string | undefined {\n const first = path.replace(/^\\//, '').split('/')[0]?.trim();\n if (!first) return undefined;\n const open = first.indexOf('(');\n const entity = (open >= 0 ? first.slice(0, open) : first).trim();\n return entity || undefined;\n}\n\nfunction isMediaOrPropertySuffix(segment: string): boolean {\n return ['file', 'content', '$value', 'metadata', 'items'].includes(segment.toLowerCase());\n}\n\nfunction looksLikeLowerCamelInvocation(segment: string): boolean {\n const open = segment.indexOf('(');\n if (open <= 0) return false;\n const name = segment.slice(0, open).split('.').at(-1) ?? segment.slice(0, open);\n return /^[a-z][A-Za-z0-9_]*$/.test(name);\n}\n\nfunction extractTemplatePlaceholders(text: string): string[] {\n const keys: string[] = [];\n for (let index = 0; index < text.length - 1; index += 1) {\n if (text[index] !== '$' || text[index + 1] !== '{') continue;\n const close = matchingPlaceholderClose(text, index + 1);\n if (close === undefined) continue;\n const key = text.slice(index + 2, close).trim();\n if (key) keys.push(key);\n index = close;\n }\n return keys;\n}\n\nfunction matchingClose(text: string, openIndex: number): number | undefined {\n let depth = 0;\n let quote: 'single' | 'double' | 'template' | undefined;\n for (let index = openIndex; index < text.length; index += 1) {\n const char = text[index];\n const prev = text[index - 1];\n if (quote) {\n if (prev === '\\\\') continue;\n if (quote === 'template' && char === '$' && text[index + 1] === '{') {\n const close = matchingPlaceholderClose(text, index + 1);\n if (close === undefined) return undefined;\n index = close;\n continue;\n }\n if ((quote === 'single' && char === \"'\") || (quote === 'double' && char === '\"') || (quote === 'template' && char === '`')) quote = undefined;\n continue;\n }\n if (char === '$' && text[index + 1] === '{') {\n const close = matchingPlaceholderClose(text, index + 1);\n if (close === undefined) return undefined;\n index = close;\n continue;\n }\n if (char === \"'\") { quote = 'single'; continue; }\n if (char === '\"') { quote = 'double'; continue; }\n if (char === '`') { quote = 'template'; continue; }\n if (char === '(') depth += 1;\n if (char === ')') {\n depth -= 1;\n if (depth === 0) return index;\n if (depth < 0) return undefined;\n }\n }\n return undefined;\n}\n\nfunction matchingPlaceholderClose(text: string, openBraceIndex: number): number | undefined {\n let depth = 0;\n let quote: 'single' | 'double' | 'template' | undefined;\n for (let index = openBraceIndex; index < text.length; index += 1) {\n const char = text[index];\n const prev = text[index - 1];\n if (quote) {\n if (prev === '\\\\') continue;\n if (quote === 'template' && char === '$' && text[index + 1] === '{') {\n depth += 1;\n index += 1;\n continue;\n }\n if ((quote === 'single' && char === \"'\") || (quote === 'double' && char === '\"') || (quote === 'template' && char === '`')) quote = undefined;\n continue;\n }\n if (char === \"'\") { quote = 'single'; continue; }\n if (char === '\"') { quote = 'double'; continue; }\n if (char === '`') { quote = 'template'; continue; }\n if (char === '{') depth += 1;\n if (char === '}') {\n depth -= 1;\n if (depth === 0) return index;\n if (depth < 0) return undefined;\n }\n }\n return undefined;\n}\n\nfunction topLevelQueryIndex(text: string): number {\n let quote: 'single' | 'double' | 'template' | undefined;\n for (let index = 0; index < text.length; index += 1) {\n const char = text[index];\n const prev = text[index - 1];\n if (quote) {\n if (prev === '\\\\') continue;\n if (quote === 'template' && char === '$' && text[index + 1] === '{') {\n const close = matchingPlaceholderClose(text, index + 1);\n if (close === undefined) return -1;\n index = close;\n continue;\n }\n if ((quote === 'single' && char === \"'\") || (quote === 'double' && char === '\"') || (quote === 'template' && char === '`')) quote = undefined;\n continue;\n }\n if (char === '$' && text[index + 1] === '{') {\n const close = matchingPlaceholderClose(text, index + 1);\n if (close === undefined) return -1;\n index = close;\n continue;\n }\n if (char === \"'\") { quote = 'single'; continue; }\n if (char === '\"') { quote = 'double'; continue; }\n if (char === '`') { quote = 'template'; continue; }\n if (char === '?') return index;\n }\n return -1;\n}\n","import path from 'node:path';\nimport ts from 'typescript';\nimport { classifyODataPathIntent } from '../linker/odata-path-normalizer.js';\nimport type { OutboundCallFact } from '../types.js';\nimport { normalizePath } from '../utils/path-utils.js';\nimport { importsFor, lineOf, readSource, type ImportBinding } from './service-binding-parser-helpers.js';\nimport type { RepositorySourceContext } from './ts-project.js';\nimport {\n analyzeOperationPath,\n operationPathExpression,\n pathUnresolvedReason,\n} from './operation-path-analysis.js';\n\ninterface WrapperSpec {\n clientIndex: number;\n pathIndex: number;\n methodIndex?: number;\n methodLiteral?: string;\n sourceFile: string;\n sourceLine: number;\n chain: string[];\n}\n\nexport async function parseImportedWrapperCalls(\n repoPath: string,\n filePath: string,\n source: ts.SourceFile,\n serviceBindings: Set<string>,\n context?: RepositorySourceContext,\n): Promise<OutboundCallFact[]> {\n const imports = await importsFor(repoPath, filePath, source);\n const importedByLocal = new Map(imports.filter((item) => item.sourceFile).map((item) => [item.localName, item]));\n const calls = collectImportedCalls(source, importedByLocal);\n const out: OutboundCallFact[] = [];\n const cache = new Map<string, Promise<WrapperSpec | undefined>>();\n for (const call of calls) {\n if (!ts.isIdentifier(call.expression)) continue;\n const imported = importedByLocal.get(call.expression.text);\n if (!imported?.sourceFile) continue;\n const spec = await loadWrapperSpec(repoPath, imported, cache, 0, context);\n const fact = spec ? wrapperCallFact(source, filePath, call, spec, serviceBindings) : undefined;\n if (fact) out.push(fact);\n }\n return out;\n}\n\nfunction collectImportedCalls(source: ts.SourceFile, imports: Map<string, ImportBinding>): ts.CallExpression[] {\n const calls: ts.CallExpression[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && imports.has(node.expression.text)) calls.push(node);\n ts.forEachChild(node, visit);\n };\n visit(source);\n return calls;\n}\n\nasync function loadWrapperSpec(\n repoPath: string,\n imported: ImportBinding,\n cache: Map<string, Promise<WrapperSpec | undefined>>,\n depth: number,\n context?: RepositorySourceContext,\n): Promise<WrapperSpec | undefined> {\n if (!imported.sourceFile || depth > 5) return undefined;\n const key = `${imported.sourceFile}#${imported.exportedName}`;\n const existing = cache.get(key);\n if (existing) return existing;\n const pending = inspectWrapper(\n repoPath, imported.sourceFile, imported.exportedName, cache, depth, context,\n );\n cache.set(key, pending);\n return pending;\n}\n\nasync function inspectWrapper(\n repoPath: string,\n sourceFile: string,\n exportedName: string,\n cache: Map<string, Promise<WrapperSpec | undefined>>,\n depth: number,\n context?: RepositorySourceContext,\n): Promise<WrapperSpec | undefined> {\n const source = await readSource(\n path.join(repoPath, sourceFile), context, sourceFile,\n );\n if (!source) return undefined;\n const named = findFunction(source, exportedName);\n if (!named) return undefined;\n const direct = directSendSpec(source, sourceFile, named.name, named.fn);\n if (direct) return direct;\n return nestedSendSpec(\n repoPath, sourceFile, source, named.name, named.fn, cache, depth, context,\n );\n}\n\nfunction directSendSpec(source: ts.SourceFile, sourceFile: string, name: string, fn: ts.FunctionLikeDeclaration): WrapperSpec | undefined {\n const params = parameterNames(fn);\n const sends: ts.CallExpression[] = [];\n visitFunctionBody(fn, (node) => {\n if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'send') sends.push(node);\n });\n if (sends.length !== 1) return undefined;\n const send = sends[0];\n const receiver = send && ts.isPropertyAccessExpression(send.expression) && ts.isIdentifier(send.expression.expression) ? send.expression.expression.text : undefined;\n const object = send?.arguments[0];\n if (!receiver || !object || !ts.isObjectLiteralExpression(object)) return undefined;\n const pathExpr = propertyExpression(object, 'path');\n const methodExpr = propertyExpression(object, 'method');\n const pathName = pathExpr && ts.isIdentifier(pathExpr) ? pathExpr.text : undefined;\n const clientIndex = params.indexOf(receiver);\n const pathIndex = pathName ? params.indexOf(pathName) : -1;\n if (clientIndex < 0 || pathIndex < 0) return undefined;\n const methodName = methodExpr && ts.isIdentifier(methodExpr) ? methodExpr.text : undefined;\n const methodIndex = methodName ? params.indexOf(methodName) : -1;\n return { clientIndex, pathIndex, methodIndex: methodIndex >= 0 ? methodIndex : undefined, methodLiteral: literal(methodExpr), sourceFile, sourceLine: lineOf(source, fn), chain: [name] };\n}\n\nasync function nestedSendSpec(\n repoPath: string,\n sourceFile: string,\n source: ts.SourceFile,\n name: string,\n fn: ts.FunctionLikeDeclaration,\n cache: Map<string, Promise<WrapperSpec | undefined>>,\n depth: number,\n context?: RepositorySourceContext,\n): Promise<WrapperSpec | undefined> {\n const imports = await importsFor(repoPath, sourceFile, source);\n const byLocal = new Map(imports.filter((item) => item.sourceFile).map((item) => [item.localName, item]));\n const calls: ts.CallExpression[] = [];\n visitFunctionBody(fn, (node) => {\n if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && byLocal.has(node.expression.text)) calls.push(node);\n });\n if (calls.length !== 1) return undefined;\n const call = calls[0];\n const imported = call && ts.isIdentifier(call.expression) ? byLocal.get(call.expression.text) : undefined;\n const nested = imported\n ? await loadWrapperSpec(repoPath, imported, cache, depth + 1, context)\n : undefined;\n if (!call || !nested) return undefined;\n const params = parameterNames(fn);\n const clientIndex = mappedParameterIndex(call.arguments[nested.clientIndex], params);\n const pathIndex = mappedParameterIndex(call.arguments[nested.pathIndex], params);\n if (clientIndex < 0 || pathIndex < 0) return undefined;\n const methodIndex = nested.methodIndex === undefined ? undefined : mappedParameterIndex(call.arguments[nested.methodIndex], params);\n return { clientIndex, pathIndex, methodIndex: methodIndex !== undefined && methodIndex >= 0 ? methodIndex : undefined, methodLiteral: nested.methodLiteral, sourceFile, sourceLine: lineOf(source, fn), chain: [name, ...nested.chain] };\n}\n\nfunction wrapperCallFact(\n source: ts.SourceFile,\n filePath: string,\n call: ts.CallExpression,\n spec: WrapperSpec,\n serviceBindings: Set<string>,\n): OutboundCallFact | undefined {\n const client = call.arguments[spec.clientIndex];\n if (!client || !ts.isIdentifier(client) || !serviceBindings.has(client.text)) return undefined;\n const methodValue = spec.methodIndex === undefined ? spec.methodLiteral : literal(call.arguments[spec.methodIndex]);\n const method = (methodValue ?? 'POST').toUpperCase();\n const pathAnalysis = analyzeOperationPath(call.arguments[spec.pathIndex], call, method);\n const operationPathExpr = operationPathExpression(pathAnalysis);\n const unresolvedReason = pathUnresolvedReason(pathAnalysis);\n return {\n callType: 'remote_action',\n serviceVariableName: client.text,\n method,\n operationPathExpr,\n payloadSummary: call.getText(source),\n sourceFile: normalizePath(filePath),\n sourceLine: lineOf(source, call),\n callSiteStartOffset: call.getStart(source),\n callSiteEndOffset: call.getEnd(),\n confidence: operationPathExpr ? 0.85 : 0.5,\n unresolvedReason,\n evidence: {\n parser: 'typescript_ast',\n startOffset: call.getStart(source),\n endOffset: call.getEnd(),\n classifier: importedWrapperClassifier(pathAnalysis.status),\n receiver: client.text,\n wrapperFunction: spec.chain[0],\n wrapperChain: spec.chain,\n callerSite: { sourceFile: normalizePath(filePath), sourceLine: lineOf(source, call) },\n calleeSite: { sourceFile: spec.sourceFile, sourceLine: spec.sourceLine },\n rawPathExpression: pathAnalysis.rawExpression,\n missingPathIdentifier: pathAnalysis.runtimeIdentifier,\n pathAnalysis,\n odataPathIntent: operationPathExpr\n ? classifyODataPathIntent(operationPathExpr, method)\n : undefined,\n },\n };\n}\n\nfunction importedWrapperClassifier(status: string): string {\n if (status === 'static') return 'imported_wrapper_literal_path';\n if (status === 'ambiguous') return 'imported_wrapper_ambiguous_path';\n return 'imported_wrapper_dynamic_path';\n}\n\nfunction findFunction(source: ts.SourceFile, exportedName: string): { name: string; fn: ts.FunctionLikeDeclaration } | undefined {\n const localName = exportedLocalName(source, exportedName);\n for (const statement of source.statements) {\n if (ts.isFunctionDeclaration(statement) && statement.name?.text === localName) return { name: exportedName, fn: statement };\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && declaration.name.text === localName && declaration.initializer && (ts.isArrowFunction(declaration.initializer) || ts.isFunctionExpression(declaration.initializer))) return { name: exportedName, fn: declaration.initializer };\n }\n }\n return undefined;\n}\n\nfunction exportedLocalName(source: ts.SourceFile, exportedName: string): string {\n for (const statement of source.statements) {\n if (!ts.isExportDeclaration(statement) || !statement.exportClause || !ts.isNamedExports(statement.exportClause)) continue;\n const match = statement.exportClause.elements.find((item) => item.name.text === exportedName);\n if (match) return match.propertyName?.text ?? match.name.text;\n }\n return exportedName;\n}\n\nfunction visitFunctionBody(fn: ts.FunctionLikeDeclaration, visitor: (node: ts.Node) => void): void {\n const visit = (node: ts.Node): void => {\n if (node !== fn && ts.isFunctionLike(node)) return;\n visitor(node);\n ts.forEachChild(node, visit);\n };\n if (fn.body) visit(fn.body);\n}\n\nfunction parameterNames(fn: ts.FunctionLikeDeclaration): string[] {\n return fn.parameters.map((parameter) => ts.isIdentifier(parameter.name) ? parameter.name.text : '');\n}\n\nfunction mappedParameterIndex(expr: ts.Expression | undefined, parameters: string[]): number {\n return expr && ts.isIdentifier(expr) ? parameters.indexOf(expr.text) : -1;\n}\n\nfunction propertyExpression(object: ts.ObjectLiteralExpression, key: string): ts.Expression | undefined {\n for (const property of object.properties) {\n if (ts.isPropertyAssignment(property) && propertyName(property.name) === key) return property.initializer;\n if (ts.isShorthandPropertyAssignment(property) && property.name.text === key) return property.name;\n }\n return undefined;\n}\n\nfunction propertyName(name: ts.PropertyName): string | undefined {\n return ts.isIdentifier(name) || ts.isStringLiteralLike(name) ? name.text : undefined;\n}\n\nfunction literal(expr: ts.Expression | undefined): string | undefined {\n return expr && (ts.isStringLiteralLike(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) ? expr.text : undefined;\n}\n","import ts from 'typescript';\nimport {\n classifyODataPathIntent,\n normalizeODataOperationInvocationPath,\n} from '../linker/odata-path-normalizer.js';\n\nexport type OperationPathStatus = 'static' | 'ambiguous' | 'dynamic' | 'unknown';\n\nexport interface OperationPathAnalysis {\n status: OperationPathStatus;\n rawExpression?: string;\n normalizedOperationPath?: string;\n candidateRawPaths: string[];\n candidateNormalizedOperationPaths: string[];\n placeholderKeys: string[];\n sourceKind: string;\n candidateIdentifier?: string;\n runtimeIdentifier?: string;\n dynamicReassignments: Array<{ expression: string; sourceLine: number }>;\n lexicalScope: {\n declarationLine?: number;\n assignmentLines: number[];\n sourceOrderSafe: boolean;\n };\n}\n\ninterface CandidateState {\n paths: string[];\n placeholders: string[];\n dynamic: Array<{ expression: string; sourceLine: number }>;\n sourceKinds: string[];\n}\n\ninterface Binding {\n declaration: ts.VariableDeclaration | ts.ParameterDeclaration;\n immutable: boolean;\n}\n\nconst maxAliasDepth = 6;\n\nexport function analyzeOperationPath(\n expression: ts.Expression | undefined,\n use: ts.Node,\n method = 'POST',\n): OperationPathAnalysis {\n if (!expression) return emptyAnalysis();\n const state = collectExpressionState(expression, use, 0, new Set());\n const paths = unique(state.paths.map(normalizeRawPath));\n const normalized = unique(paths.flatMap((value) => normalizedCandidate(value, method)));\n const status = pathStatus(paths, state.placeholders, state.dynamic);\n const runtimeIdentifier = state.dynamic.at(-1)?.expression;\n return {\n status,\n rawExpression: expression.getText(expression.getSourceFile()),\n normalizedOperationPath: status === 'static' && normalized.length === 1 ? normalized[0] : undefined,\n candidateRawPaths: paths,\n candidateNormalizedOperationPaths: normalized,\n placeholderKeys: unique([...state.placeholders, ...(runtimeIdentifier ? [runtimeIdentifier] : [])]),\n sourceKind: unique(state.sourceKinds).join('+') || 'unknown',\n candidateIdentifier: ts.isIdentifier(expression) ? expression.text : undefined,\n runtimeIdentifier,\n dynamicReassignments: state.dynamic,\n lexicalScope: lexicalEvidence(expression, use),\n };\n}\n\nexport function operationPathExpression(analysis: OperationPathAnalysis): string | undefined {\n if (analysis.status === 'ambiguous' || analysis.status === 'unknown') return undefined;\n if (analysis.sourceKind.includes('parameter_binding')) return undefined;\n if (analysis.candidateRawPaths.length === 1 && analysis.dynamicReassignments.length === 0)\n return analysis.candidateRawPaths[0];\n if (!analysis.runtimeIdentifier || analysis.sourceKind.includes('binding_not_found'))\n return undefined;\n return isRuntimeIdentifier(analysis.runtimeIdentifier)\n ? `\\${${analysis.runtimeIdentifier}}`\n : undefined;\n}\n\nexport function pathUnresolvedReason(analysis: OperationPathAnalysis): string | undefined {\n if (analysis.status === 'ambiguous') return 'ambiguous_operation_path_candidates';\n if (analysis.status === 'dynamic' && !operationPathExpression(analysis))\n return 'dynamic_operation_path_identifier';\n if (analysis.dynamicReassignments.length > 0) return 'dynamic_operation_path_identifier';\n return undefined;\n}\n\nfunction collectExpressionState(\n expression: ts.Expression,\n use: ts.Node,\n depth: number,\n seen: Set<ts.Node>,\n): CandidateState {\n const unwrapped = unwrap(expression);\n if (ts.isStringLiteral(unwrapped)) return staticState(unwrapped.text, 'string_literal');\n if (ts.isNoSubstitutionTemplateLiteral(unwrapped))\n return staticState(unwrapped.text, 'no_substitution_template');\n if (ts.isTemplateExpression(unwrapped)) return templateState(unwrapped);\n if (ts.isConditionalExpression(unwrapped))\n return mergeStates([\n collectExpressionState(unwrapped.whenTrue, use, depth + 1, seen),\n collectExpressionState(unwrapped.whenFalse, use, depth + 1, seen),\n ], 'conditional_candidates');\n if (ts.isIdentifier(unwrapped))\n return collectIdentifierState(unwrapped, use, depth, seen);\n return dynamicState(unwrapped);\n}\n\nfunction collectIdentifierState(\n identifier: ts.Identifier,\n use: ts.Node,\n depth: number,\n seen: Set<ts.Node>,\n): CandidateState {\n if (depth >= maxAliasDepth)\n return dynamicState(identifier, 'alias_depth_exceeded');\n const binding = resolveBinding(identifier, use);\n if (!binding || seen.has(binding.declaration))\n return dynamicState(identifier, binding ? 'alias_cycle' : 'binding_not_found');\n seen.add(binding.declaration);\n if (ts.isParameter(binding.declaration))\n return dynamicState(identifier, 'parameter_binding');\n const expressions = reachingExpressions(binding.declaration, use);\n if (expressions.length === 0) return dynamicState(identifier, 'initializer_missing');\n const states = expressions.map((item) =>\n collectExpressionState(item.expression, item.node, depth + 1, seen));\n const merged = mergeStates(states, binding.immutable ? 'const_alias' : 'mutable_alias');\n if (merged.dynamic.length === 0) return merged;\n return {\n ...merged,\n dynamic: merged.dynamic.map((item) =>\n item.expression === identifier.text ? item : item),\n };\n}\n\nfunction reachingExpressions(\n declaration: ts.VariableDeclaration,\n use: ts.Node,\n): Array<{ expression: ts.Expression; node: ts.Node }> {\n const rows: Array<{ expression: ts.Expression; node: ts.Node }> = [];\n if (declaration.initializer) rows.push({ expression: declaration.initializer, node: declaration });\n if ((declaration.parent.flags & ts.NodeFlags.Const) !== 0) return rows;\n const source = use.getSourceFile();\n const visit = (node: ts.Node): void => {\n if (node.getStart(source) >= use.getStart(source)) return;\n if (node !== source && ts.isFunctionLike(node) && !contains(node, use)) return;\n if (isAssignmentTo(node, declaration, use))\n rows.push({ expression: node.right, node });\n ts.forEachChild(node, visit);\n };\n visit(source);\n return rows.sort((left, right) =>\n left.node.getStart(source) - right.node.getStart(source));\n}\n\nfunction isAssignmentTo(\n node: ts.Node,\n declaration: ts.VariableDeclaration,\n use: ts.Node,\n): node is ts.BinaryExpression {\n if (!ts.isBinaryExpression(node) || node.operatorToken.kind !== ts.SyntaxKind.EqualsToken)\n return false;\n if (!ts.isIdentifier(node.left) || !ts.isIdentifier(declaration.name)) return false;\n return resolveBinding(node.left, node)?.declaration === declaration && contains(declarationScope(declaration), use);\n}\n\nfunction resolveBinding(identifier: ts.Identifier, use: ts.Node): Binding | undefined {\n const source = use.getSourceFile();\n const matches: Array<ts.VariableDeclaration | ts.ParameterDeclaration> = [];\n const visit = (node: ts.Node): void => {\n if (isNamedDeclaration(node, identifier.text) && isAccessible(node, use))\n matches.push(node);\n ts.forEachChild(node, visit);\n };\n visit(source);\n const declaration = matches.sort((left, right) =>\n right.getStart(source) - left.getStart(source))[0];\n if (!declaration) return undefined;\n const immutable = ts.isVariableDeclaration(declaration)\n && (declaration.parent.flags & ts.NodeFlags.Const) !== 0;\n return { declaration, immutable };\n}\n\nfunction isNamedDeclaration(\n node: ts.Node,\n name: string,\n): node is ts.VariableDeclaration | ts.ParameterDeclaration {\n return (ts.isVariableDeclaration(node) || ts.isParameter(node))\n && ts.isIdentifier(node.name)\n && node.name.text === name;\n}\n\nfunction isAccessible(\n declaration: ts.VariableDeclaration | ts.ParameterDeclaration,\n use: ts.Node,\n): boolean {\n const source = use.getSourceFile();\n if (declaration.name.getStart(source) >= use.getStart(source)) return false;\n const scope = declarationScope(declaration);\n return ts.isSourceFile(scope) || contains(scope, use);\n}\n\nfunction declarationScope(\n declaration: ts.VariableDeclaration | ts.ParameterDeclaration,\n): ts.Node {\n if (ts.isParameter(declaration)) return declaration.parent;\n if (ts.isCatchClause(declaration.parent)) return declaration.parent.block;\n const list = declaration.parent;\n if (isLoopInitializer(list.parent)) return list.parent.statement;\n const blockScoped = (list.flags & (ts.NodeFlags.Const | ts.NodeFlags.Let)) !== 0;\n let current: ts.Node = list.parent;\n if (!blockScoped) {\n while (current.parent && !ts.isFunctionLike(current) && !ts.isSourceFile(current))\n current = current.parent;\n return current;\n }\n while (current.parent && !isLexicalScope(current)) current = current.parent;\n return current;\n}\n\nfunction isLoopInitializer(\n node: ts.Node,\n): node is ts.ForStatement | ts.ForInStatement | ts.ForOfStatement {\n return ts.isForStatement(node) || ts.isForInStatement(node) || ts.isForOfStatement(node);\n}\n\nfunction isLexicalScope(node: ts.Node): boolean {\n return ts.isBlock(node)\n || ts.isSourceFile(node)\n || ts.isModuleBlock(node)\n || ts.isCaseBlock(node)\n || ts.isFunctionLike(node);\n}\n\nfunction templateState(expression: ts.TemplateExpression): CandidateState {\n const value = expression.getText(expression.getSourceFile()).slice(1, -1);\n return {\n paths: [value],\n placeholders: expression.templateSpans.map((span) =>\n span.expression.getText(expression.getSourceFile())),\n dynamic: [],\n sourceKinds: ['template_with_placeholders'],\n };\n}\n\nfunction staticState(path: string, sourceKind: string): CandidateState {\n return { paths: [path], placeholders: [], dynamic: [], sourceKinds: [sourceKind] };\n}\n\nfunction dynamicState(expression: ts.Expression, sourceKind = 'dynamic_expression'): CandidateState {\n return {\n paths: [],\n placeholders: [],\n dynamic: [{\n expression: expression.getText(expression.getSourceFile()),\n sourceLine: sourceLine(expression),\n }],\n sourceKinds: [sourceKind],\n };\n}\n\nfunction mergeStates(states: CandidateState[], sourceKind: string): CandidateState {\n return {\n paths: states.flatMap((state) => state.paths),\n placeholders: states.flatMap((state) => state.placeholders),\n dynamic: states.flatMap((state) => state.dynamic),\n sourceKinds: [sourceKind, ...states.flatMap((state) => state.sourceKinds)],\n };\n}\n\nfunction pathStatus(\n paths: string[],\n placeholders: string[],\n dynamic: CandidateState['dynamic'],\n): OperationPathStatus {\n if (dynamic.length > 0) return 'dynamic';\n if (paths.length > 1) return 'ambiguous';\n if (placeholders.length > 0) return 'dynamic';\n if (paths.length === 1) return 'static';\n return 'unknown';\n}\n\nfunction normalizedCandidate(value: string, method: string): string[] {\n const invocation = normalizeODataOperationInvocationPath(value);\n if (invocation?.wasInvocation) return [invocation.normalizedOperationPath];\n const intent = classifyODataPathIntent(value, method);\n if (intent.kind.startsWith('entity_')) return [];\n if (!value.startsWith('/') || value.slice(1).includes('/') || value.includes('?')) return [];\n return [value];\n}\n\nfunction lexicalEvidence(expression: ts.Expression, use: ts.Node): OperationPathAnalysis['lexicalScope'] {\n if (!ts.isIdentifier(expression))\n return { assignmentLines: [], sourceOrderSafe: expression.getStart() < use.getStart() };\n const binding = resolveBinding(expression, use);\n if (!binding) return { assignmentLines: [], sourceOrderSafe: false };\n const assignmentLines = ts.isVariableDeclaration(binding.declaration)\n ? reachingExpressions(binding.declaration, use)\n .slice(binding.declaration.initializer ? 1 : 0)\n .map((item) => sourceLine(item.node))\n : [];\n return {\n declarationLine: sourceLine(binding.declaration),\n assignmentLines,\n sourceOrderSafe: true,\n };\n}\n\nfunction unwrap(expression: ts.Expression): ts.Expression {\n if (ts.isAwaitExpression(expression) || ts.isParenthesizedExpression(expression))\n return unwrap(expression.expression);\n if (ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression)\n || ts.isTypeAssertionExpression(expression))\n return unwrap(expression.expression);\n return expression;\n}\n\nfunction normalizeRawPath(value: string): string {\n return value.startsWith('/') ? value : `/${value}`;\n}\n\nfunction isRuntimeIdentifier(value: string): boolean {\n return /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*$/.test(value);\n}\n\nfunction contains(parent: ts.Node, child: ts.Node): boolean {\n const source = child.getSourceFile();\n return child.getStart(source) >= parent.getStart(source)\n && child.getEnd() <= parent.getEnd();\n}\n\nfunction sourceLine(node: ts.Node): number {\n const source = node.getSourceFile();\n return source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nfunction emptyAnalysis(): OperationPathAnalysis {\n return {\n status: 'unknown',\n candidateRawPaths: [],\n candidateNormalizedOperationPaths: [],\n placeholderKeys: [],\n sourceKind: 'missing',\n dynamicReassignments: [],\n lexicalScope: { assignmentLines: [], sourceOrderSafe: false },\n };\n}\n","import ts from 'typescript';\n\nconst capQueryBuilderRoots = new Set([\n 'SELECT.from',\n 'SELECT.one.from',\n 'SELECT.one',\n 'SELECT.distinct.from',\n 'SELECT.distinct.one.from',\n 'INSERT.into',\n 'UPSERT.into',\n 'UPDATE.entity',\n 'UPDATE',\n 'DELETE.from',\n]);\nconst promiseValueShadowCache = new WeakMap<ts.SourceFile, boolean>();\n\nexport type DirectQueryExecutionContext =\n | 'await'\n | 'async_return'\n | 'promise_return'\n | 'promise_aggregate';\n\nexport interface DirectQueryBuilderStatement {\n root: ts.CallExpression;\n logicalCall: ts.CallExpression;\n statement: ts.Expression;\n executionContext: DirectQueryExecutionContext;\n}\n\nexport function isCapQueryBuilderRootName(name: string): boolean {\n return capQueryBuilderRoots.has(name);\n}\n\nexport function queryBuilderRoot(\n expression: ts.Expression,\n): ts.CallExpression | undefined {\n const unwrapped = unwrapQueryExpression(expression);\n if (!ts.isCallExpression(unwrapped)) return undefined;\n if (isCapQueryBuilderRootName(expressionName(unwrapped.expression)))\n return unwrapped;\n return ts.isPropertyAccessExpression(unwrapped.expression)\n ? queryBuilderRoot(unwrapped.expression.expression)\n : undefined;\n}\n\nexport function directQueryBuilderStatement(\n node: ts.CallExpression,\n): DirectQueryBuilderStatement | undefined {\n const root = queryBuilderRoot(node);\n if (!root) return undefined;\n const logicalCall = outerFluentQueryCall(root);\n if (logicalCall !== node) return undefined;\n const expression = outerTransparentExpression(logicalCall);\n const awaitExpression = directAwaitExpression(expression);\n if (awaitExpression)\n return { root, logicalCall, statement: awaitExpression, executionContext: 'await' };\n const returnContext = returnExecutionContext(expression);\n if (returnContext)\n return { root, logicalCall, statement: expression, executionContext: returnContext };\n if (isAwaitedPromiseAllElement(expression))\n return { root, logicalCall, statement: expression, executionContext: 'promise_aggregate' };\n return undefined;\n}\n\nfunction expressionName(expression: ts.Expression): string {\n if (ts.isIdentifier(expression)) return expression.text;\n if (ts.isPropertyAccessExpression(expression))\n return `${expressionName(expression.expression)}.${expression.name.text}`;\n return expression.getText();\n}\n\nfunction unwrapQueryExpression(expression: ts.Expression): ts.Expression {\n if (ts.isParenthesizedExpression(expression) || ts.isAwaitExpression(expression)\n || ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)\n || ts.isNonNullExpression(expression) || ts.isSatisfiesExpression(expression))\n return unwrapQueryExpression(expression.expression);\n return expression;\n}\n\nfunction wrapperParent(node: ts.Expression): ts.Expression | undefined {\n const parent = node.parent;\n if ((ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent)\n || ts.isTypeAssertionExpression(parent) || ts.isNonNullExpression(parent)\n || ts.isSatisfiesExpression(parent)) && parent.expression === node)\n return parent;\n return undefined;\n}\n\nfunction fluentCallParent(node: ts.Expression): ts.CallExpression | undefined {\n const property = node.parent;\n if (!ts.isPropertyAccessExpression(property) || property.expression !== node)\n return undefined;\n const call = property.parent;\n return ts.isCallExpression(call) && call.expression === property ? call : undefined;\n}\n\nfunction outerFluentQueryCall(root: ts.CallExpression): ts.CallExpression {\n let current: ts.Expression = root;\n let outer = root;\n while (true) {\n const wrapper = wrapperParent(current);\n if (wrapper) {\n current = wrapper;\n continue;\n }\n const next = fluentCallParent(current);\n if (!next) return outer;\n outer = next;\n current = next;\n }\n}\n\nfunction outerTransparentExpression(expression: ts.Expression): ts.Expression {\n let current = expression;\n while (true) {\n const wrapper = wrapperParent(current);\n if (!wrapper) return current;\n current = wrapper;\n }\n}\n\nfunction directAwaitExpression(\n expression: ts.Expression,\n): ts.AwaitExpression | undefined {\n const parent = expression.parent;\n return ts.isAwaitExpression(parent) && parent.expression === expression\n ? parent\n : undefined;\n}\n\nfunction returnExecutionContext(\n expression: ts.Expression,\n): DirectQueryExecutionContext | undefined {\n const callable = returnedExpressionCallable(expression);\n if (!callable) return undefined;\n if (hasAsyncModifier(callable)) return 'async_return';\n return hasGuaranteedPromiseReturn(callable) ? 'promise_return' : undefined;\n}\n\nfunction returnedExpressionCallable(\n expression: ts.Expression,\n): ts.FunctionLikeDeclaration | undefined {\n const parent = expression.parent;\n if (ts.isArrowFunction(parent) && parent.body === expression) return parent;\n if (!ts.isReturnStatement(parent) || parent.expression !== expression)\n return undefined;\n return nearestCallable(parent);\n}\n\nfunction nearestCallable(node: ts.Node): ts.FunctionLikeDeclaration | undefined {\n let current = node.parent;\n while (current) {\n if (isRuntimeCallable(current)) return current;\n current = current.parent;\n }\n return undefined;\n}\n\nfunction isRuntimeCallable(node: ts.Node): node is ts.FunctionLikeDeclaration {\n return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)\n || ts.isArrowFunction(node) || ts.isMethodDeclaration(node)\n || ts.isConstructorDeclaration(node) || ts.isGetAccessorDeclaration(node)\n || ts.isSetAccessorDeclaration(node);\n}\n\nfunction hasAsyncModifier(node: ts.Node): boolean {\n return !isGeneratorCallable(node) && ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some(\n (modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword,\n ) ?? false);\n}\n\nfunction isGeneratorCallable(node: ts.Node): boolean {\n return (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)\n || ts.isMethodDeclaration(node)) && Boolean(node.asteriskToken);\n}\n\nfunction hasGuaranteedPromiseReturn(\n callable: ts.FunctionLikeDeclaration,\n): boolean {\n const returnType = declaredReturnType(callable);\n return Boolean(returnType && isGuaranteedPromiseType(returnType));\n}\n\nfunction declaredReturnType(\n callable: ts.FunctionLikeDeclaration,\n): ts.TypeNode | undefined {\n if (ts.isFunctionDeclaration(callable) || ts.isFunctionExpression(callable)\n || ts.isArrowFunction(callable) || ts.isMethodDeclaration(callable))\n return callable.type;\n return undefined;\n}\n\nfunction isGuaranteedPromiseType(type: ts.TypeNode): boolean {\n if (ts.isParenthesizedTypeNode(type))\n return isGuaranteedPromiseType(type.type);\n if (ts.isTypeReferenceNode(type))\n return isStandardPromiseTypeName(type.typeName);\n if (ts.isUnionTypeNode(type))\n return type.types.length > 0 && type.types.every(isGuaranteedPromiseType);\n if (ts.isIntersectionTypeNode(type))\n return type.types.some(isGuaranteedPromiseType);\n return false;\n}\n\nfunction isStandardPromiseTypeName(name: ts.EntityName): boolean {\n if (ts.isIdentifier(name))\n return name.text === 'Promise' || name.text === 'PromiseLike';\n return ts.isIdentifier(name.left)\n && (name.left.text === 'globalThis' || name.left.text === 'global')\n && (name.right.text === 'Promise' || name.right.text === 'PromiseLike');\n}\n\nfunction isAwaitedPromiseAllElement(expression: ts.Expression): boolean {\n const array = directArrayParent(expression);\n if (!array) return false;\n const aggregate = aggregateCallForArray(array);\n return Boolean(aggregate && isBuiltInPromiseAll(aggregate)\n && directAwaitExpression(outerTransparentExpression(aggregate)));\n}\n\nfunction directArrayParent(\n expression: ts.Expression,\n): ts.ArrayLiteralExpression | undefined {\n const parent = expression.parent;\n return ts.isArrayLiteralExpression(parent) && parent.elements.some(\n (element) => element === expression,\n ) ? parent : undefined;\n}\n\nfunction aggregateCallForArray(\n array: ts.ArrayLiteralExpression,\n): ts.CallExpression | undefined {\n const argument = outerTransparentExpression(array);\n const parent = argument.parent;\n return ts.isCallExpression(parent) && parent.arguments.length === 1\n && parent.arguments[0] === argument ? parent : undefined;\n}\n\nfunction isBuiltInPromiseAll(call: ts.CallExpression): boolean {\n return ts.isPropertyAccessExpression(call.expression)\n && ts.isIdentifier(call.expression.expression)\n && call.expression.expression.text === 'Promise'\n && call.expression.name.text === 'all'\n && !hasPromiseValueShadow(call.getSourceFile());\n}\n\nfunction hasPromiseValueShadow(source: ts.SourceFile): boolean {\n const cached = promiseValueShadowCache.get(source);\n if (cached !== undefined) return cached;\n let shadowed = false;\n const visit = (node: ts.Node): void => {\n if (shadowed) return;\n if (declaresPromiseValue(node)) {\n shadowed = true;\n return;\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n promiseValueShadowCache.set(source, shadowed);\n return shadowed;\n}\n\nfunction declaresPromiseValue(node: ts.Node): boolean {\n if (ts.isVariableDeclaration(node) || ts.isParameter(node))\n return bindingNameIsPromise(node.name);\n if (ts.isImportClause(node))\n return !node.isTypeOnly && nodeIsPromise(node.name);\n if (ts.isImportSpecifier(node))\n return !node.isTypeOnly && nodeIsPromise(node.name);\n if (ts.isNamespaceImport(node) || ts.isImportEqualsDeclaration(node))\n return nodeIsPromise(node.name);\n if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)\n || ts.isEnumDeclaration(node) || ts.isModuleDeclaration(node))\n return nodeIsPromise(node.name);\n return false;\n}\n\nfunction bindingNameIsPromise(name: ts.BindingName): boolean {\n if (ts.isIdentifier(name)) return name.text === 'Promise';\n if (ts.isObjectBindingPattern(name))\n return name.elements.some((element) => bindingNameIsPromise(element.name));\n return name.elements.some((element) => ts.isBindingElement(element)\n && bindingNameIsPromise(element.name));\n}\n\nfunction nodeIsPromise(name: ts.Node | undefined): boolean {\n return Boolean(name && ts.isIdentifier(name) && name.text === 'Promise');\n}\n","import ts from 'typescript';\nimport { isCapQueryBuilderRootName } from './000-direct-query-execution.js';\n\nexport interface BindingResolution {\n declaration?: ts.VariableDeclaration | ts.ParameterDeclaration;\n initializer?: ts.Expression;\n immutable: boolean;\n evidence: string[];\n}\n\ninterface DestructuredBinding {\n declaration: ts.VariableDeclaration | ts.ParameterDeclaration;\n initializer?: ts.Expression;\n entityName: string;\n}\n\nexport const maxAliasDepth = 5;\nconst cdsModelSpecifier = /^#cds-models(?:\\/|$)/;\nconst modelNamespaceCache = new WeakMap<ts.SourceFile, Set<string>>();\n\nexport function expressionName(expr: ts.Expression): string {\n if (ts.isIdentifier(expr)) return expr.text;\n if (ts.isPropertyAccessExpression(expr))\n return `${expressionName(expr.expression)}.${expr.name.text}`;\n return expr.getText();\n}\n\nexport function variableInitializers(\n source: ts.SourceFile,\n): Map<string, ts.Expression> {\n const initializers = new Map<string, ts.Expression>();\n for (const statement of source.statements) {\n if (!ts.isVariableStatement(statement)\n || (statement.declarationList.flags & ts.NodeFlags.Const) === 0) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && declaration.initializer)\n initializers.set(declaration.name.text, declaration.initializer);\n }\n }\n return initializers;\n}\n\nfunction unwrapQueryExpression(expr: ts.Expression): ts.Expression {\n if (ts.isParenthesizedExpression(expr) || ts.isAwaitExpression(expr)\n || ts.isAsExpression(expr) || ts.isTypeAssertionExpression(expr)\n || ts.isNonNullExpression(expr) || ts.isSatisfiesExpression(expr))\n return unwrapQueryExpression(expr.expression);\n return expr;\n}\n\nfunction isFunctionLikeScope(node: ts.Node): boolean {\n return ts.isFunctionLike(node) || ts.isSourceFile(node);\n}\n\nfunction nodeContains(parent: ts.Node, child: ts.Node): boolean {\n const source = child.getSourceFile();\n return child.getStart(source) >= parent.getStart(source)\n && child.getEnd() <= parent.getEnd();\n}\n\nfunction isLoopInitializerScope(\n declaration: ts.VariableDeclaration,\n scope: ts.Node,\n): boolean {\n const list = declaration.parent;\n return (ts.isForStatement(scope) && scope.initializer === list)\n || ((ts.isForInStatement(scope) || ts.isForOfStatement(scope))\n && scope.initializer === list);\n}\n\nfunction isLexicalScopeBoundary(\n node: ts.Node,\n declaration: ts.VariableDeclaration,\n): boolean {\n return ts.isBlock(node) || ts.isSourceFile(node) || ts.isModuleBlock(node)\n || ts.isCaseBlock(node) || isLoopInitializerScope(declaration, node)\n || isFunctionLikeScope(node);\n}\n\nfunction declarationScope(\n node: ts.VariableDeclaration | ts.ParameterDeclaration,\n): ts.Node {\n if (ts.isParameter(node)) return node.parent;\n if (ts.isCatchClause(node.parent) && node.parent.variableDeclaration === node)\n return node.parent;\n const list = node.parent;\n const blockScoped = (list.flags & (ts.NodeFlags.Const | ts.NodeFlags.Let)) !== 0;\n let current: ts.Node = list.parent;\n if (!blockScoped) {\n while (current.parent && !isFunctionLikeScope(current)) current = current.parent;\n return current;\n }\n while (current.parent && !isLexicalScopeBoundary(current, node))\n current = current.parent;\n return current;\n}\n\nfunction catchBindingScope(\n declaration: ts.VariableDeclaration | ts.ParameterDeclaration,\n): ts.CatchClause | undefined {\n if (ts.isParameter(declaration)) return undefined;\n return ts.isCatchClause(declaration.parent)\n && declaration.parent.variableDeclaration === declaration\n ? declaration.parent\n : undefined;\n}\n\nfunction declarationIsInScope(\n declaration: ts.VariableDeclaration | ts.ParameterDeclaration,\n use: ts.Node,\n): boolean {\n const catchScope = catchBindingScope(declaration);\n if (catchScope) return nodeContains(catchScope.block, use);\n const scope = declarationScope(declaration);\n if (ts.isForStatement(scope) || ts.isForInStatement(scope)\n || ts.isForOfStatement(scope)) return nodeContains(scope.statement, use);\n return ts.isSourceFile(scope) || nodeContains(scope, use);\n}\n\nfunction isAccessibleDeclaration(\n declaration: ts.VariableDeclaration | ts.ParameterDeclaration,\n use: ts.Node,\n): boolean {\n return declaration.name.getStart(use.getSourceFile()) < use.getStart()\n && declarationIsInScope(declaration, use);\n}\n\nexport function resolveBinding(\n identifier: ts.Identifier,\n use: ts.Node,\n): BindingResolution {\n const source = use.getSourceFile();\n let best: ts.VariableDeclaration | ts.ParameterDeclaration | undefined;\n const visit = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)\n && node.name.text === identifier.text && isAccessibleDeclaration(node, use))\n best = node;\n if (ts.isParameter(node) && ts.isIdentifier(node.name)\n && node.name.text === identifier.text && isAccessibleDeclaration(node, use))\n best = node;\n ts.forEachChild(node, visit);\n };\n visit(source);\n if (!best) return { immutable: false, evidence: ['binding_not_found'] };\n const immutable = ts.isVariableDeclaration(best)\n && (best.parent.flags & ts.NodeFlags.Const) !== 0;\n return {\n declaration: best,\n initializer: ts.isVariableDeclaration(best) ? best.initializer : undefined,\n immutable,\n evidence: [immutable\n ? 'lexical_const_binding_before_use'\n : 'lexical_mutable_or_parameter_binding'],\n };\n}\n\nfunction directBindingElement(\n name: ts.BindingName,\n identifier: ts.Identifier,\n): ts.BindingElement | undefined {\n if (ts.isIdentifier(name)) return undefined;\n for (const element of name.elements) {\n if (ts.isOmittedExpression(element) || element.dotDotDotToken\n || element.initializer\n || !ts.isIdentifier(element.name)) continue;\n if (element.name.text === identifier.text) return element;\n }\n return undefined;\n}\n\nfunction bindingNameContains(name: ts.BindingName, target: string): boolean {\n if (ts.isIdentifier(name)) return name.text === target;\n return name.elements.some((element) => ts.isBindingElement(element)\n && bindingNameContains(element.name, target));\n}\n\nfunction bindingScope(node: ts.Node): ts.Node {\n if (ts.isVariableDeclaration(node) || ts.isParameter(node))\n return declarationScope(node);\n if (ts.isFunctionExpression(node) || ts.isClassExpression(node)) return node;\n return node.parent;\n}\n\nfunction bindingIsCloser(candidate: ts.Node, current: ts.Node, use: ts.Node): boolean {\n const source = use.getSourceFile();\n const candidateScope = bindingScope(candidate);\n const currentScope = bindingScope(current);\n const candidateSpan = candidateScope.getEnd() - candidateScope.getStart(source);\n const currentSpan = currentScope.getEnd() - currentScope.getStart(source);\n return candidateSpan < currentSpan\n || (candidateSpan === currentSpan\n && candidate.getStart(source) > current.getStart(source));\n}\n\nfunction nearestScopedVariableDeclaration(\n identifier: ts.Identifier,\n): ts.VariableDeclaration | ts.ParameterDeclaration | undefined {\n let best: ts.VariableDeclaration | ts.ParameterDeclaration | undefined;\n const visit = (node: ts.Node): void => {\n if ((ts.isVariableDeclaration(node) || ts.isParameter(node))\n && bindingNameContains(node.name, identifier.text)\n && declarationIsInScope(node, identifier)\n && (!best || bindingIsCloser(node, best, identifier))) best = node;\n ts.forEachChild(node, visit);\n };\n visit(identifier.getSourceFile());\n return best;\n}\n\nfunction hasScopedVariableDeclaration(identifier: ts.Identifier): boolean {\n return Boolean(nearestScopedVariableDeclaration(identifier));\n}\n\nfunction namedValueDeclarationMatches(\n node: ts.Node,\n name: string,\n): boolean {\n if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)\n || ts.isEnumDeclaration(node)) return node.name?.text === name;\n return ts.isModuleDeclaration(node) && ts.isIdentifier(node.name)\n && node.name.text === name;\n}\n\nfunction declarationContainerContains(node: ts.Node, use: ts.Node): boolean {\n const container = node.parent;\n return ts.isSourceFile(container)\n || ((ts.isBlock(container) || ts.isModuleBlock(container))\n && nodeContains(container, use));\n}\n\nfunction selfNamedValueDeclarationMatches(\n node: ts.Node,\n identifier: ts.Identifier,\n): boolean {\n return (ts.isFunctionExpression(node) || ts.isClassExpression(node))\n && node.name?.text === identifier.text\n && nodeContains(node, identifier);\n}\n\nfunction scopedNonVariableDeclarationMatches(\n node: ts.Node,\n identifier: ts.Identifier,\n): boolean {\n return (namedValueDeclarationMatches(node, identifier.text)\n && declarationContainerContains(node, identifier))\n || selfNamedValueDeclarationMatches(node, identifier);\n}\n\nfunction nearestScopedNonVariableDeclaration(\n identifier: ts.Identifier,\n): ts.Node | undefined {\n let best: ts.Node | undefined;\n const visit = (node: ts.Node): void => {\n if (scopedNonVariableDeclarationMatches(node, identifier)\n && (!best || bindingIsCloser(node, best, identifier))) best = node;\n ts.forEachChild(node, visit);\n };\n visit(identifier.getSourceFile());\n return best;\n}\n\nfunction hasScopedNonVariableDeclaration(identifier: ts.Identifier): boolean {\n return Boolean(nearestScopedNonVariableDeclaration(identifier));\n}\n\nfunction nonVariableBindingWins(\n identifier: ts.Identifier,\n selected: ts.Node | undefined,\n): boolean {\n const declaration = nearestScopedNonVariableDeclaration(identifier);\n return Boolean(declaration\n && (!selected || bindingIsCloser(declaration, selected, identifier)));\n}\n\nfunction importClauseBinds(\n clause: ts.ImportClause | undefined,\n name: string,\n): boolean {\n if (!clause || clause.isTypeOnly) return false;\n if (clause.name?.text === name) return true;\n const bindings = clause.namedBindings;\n if (!bindings) return false;\n if (ts.isNamespaceImport(bindings)) return bindings.name.text === name;\n return bindings.elements.some((element) => !element.isTypeOnly\n && element.name.text === name);\n}\n\nfunction hasValueImportBinding(identifier: ts.Identifier): boolean {\n return identifier.getSourceFile().statements.some((statement) => {\n if (ts.isImportDeclaration(statement))\n return importClauseBinds(statement.importClause, identifier.text);\n return ts.isImportEqualsDeclaration(statement) && !statement.isTypeOnly\n && statement.name.text === identifier.text;\n });\n}\n\nfunction sourcePropertyName(\n element: ts.BindingElement,\n localName: string,\n): string | undefined {\n const property = element.propertyName;\n if (!property) return localName;\n if (ts.isIdentifier(property) || ts.isStringLiteral(property)\n || ts.isNumericLiteral(property)) return property.text;\n return undefined;\n}\n\nfunction resolveDestructuredBinding(\n identifier: ts.Identifier,\n use: ts.Node,\n): DestructuredBinding | undefined {\n const source = use.getSourceFile();\n let best: DestructuredBinding | undefined;\n const visit = (node: ts.Node): void => {\n if ((ts.isVariableDeclaration(node) || ts.isParameter(node))\n && isAccessibleDeclaration(node, use)) {\n const element = directBindingElement(node.name, identifier);\n const entityName = element\n ? sourcePropertyName(element, identifier.text)\n : undefined;\n if (entityName && (!best || node.name.getStart(source)\n > best.declaration.name.getStart(source))) {\n best = {\n declaration: node,\n initializer: node.initializer,\n entityName,\n };\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return best;\n}\n\nfunction isEntitiesBase(expr: ts.Expression): boolean {\n const value = unwrapQueryExpression(expr);\n if (ts.isPropertyAccessExpression(value)) return value.name.text === 'entities';\n return ts.isCallExpression(value)\n && ts.isPropertyAccessExpression(value.expression)\n && value.expression.name.text === 'entities';\n}\n\nfunction hasLexicalValueShadow(\n identifier: ts.Identifier,\n includeImports: boolean,\n): boolean {\n return hasScopedVariableDeclaration(identifier)\n || hasScopedNonVariableDeclaration(identifier)\n || (includeImports && hasValueImportBinding(identifier));\n}\n\nfunction modelRequire(expr: ts.Expression): boolean {\n const value = unwrapQueryExpression(expr);\n if (!ts.isCallExpression(value) || !ts.isIdentifier(value.expression)\n || value.expression.text !== 'require' || value.arguments.length !== 1)\n return false;\n if (hasLexicalValueShadow(value.expression, true)) return false;\n const specifier = value.arguments[0];\n return Boolean(specifier && ts.isStringLiteralLike(specifier)\n && cdsModelSpecifier.test(specifier.text));\n}\n\nfunction modelNamespaceImportName(\n statement: ts.Statement,\n): string | undefined {\n if (!ts.isImportDeclaration(statement)\n || !ts.isStringLiteralLike(statement.moduleSpecifier)\n || !cdsModelSpecifier.test(statement.moduleSpecifier.text)\n || statement.importClause?.isTypeOnly) return undefined;\n const bindings = statement.importClause?.namedBindings;\n return bindings && ts.isNamespaceImport(bindings)\n ? bindings.name.text\n : undefined;\n}\n\nfunction modelImportEqualsName(\n statement: ts.Statement,\n): string | undefined {\n if (!ts.isImportEqualsDeclaration(statement) || statement.isTypeOnly\n || !ts.isExternalModuleReference(statement.moduleReference)) return undefined;\n const specifier = statement.moduleReference.expression;\n return specifier && ts.isStringLiteralLike(specifier)\n && cdsModelSpecifier.test(specifier.text)\n ? statement.name.text\n : undefined;\n}\n\nfunction modelNamespaceNames(source: ts.SourceFile): Set<string> {\n const cached = modelNamespaceCache.get(source);\n if (cached) return cached;\n const names = new Set<string>();\n for (const statement of source.statements) {\n const name = modelNamespaceImportName(statement)\n ?? modelImportEqualsName(statement);\n if (name) names.add(name);\n }\n modelNamespaceCache.set(source, names);\n return names;\n}\n\nfunction destructuredEntitySource(\n initializer: ts.Expression | undefined,\n): boolean {\n if (!initializer) return false;\n if (isEntitiesBase(initializer) || modelRequire(initializer)) return true;\n const value = unwrapQueryExpression(initializer);\n return ts.isIdentifier(value)\n && !hasLexicalValueShadow(value, false)\n && modelNamespaceNames(value.getSourceFile()).has(value.text);\n}\n\nfunction isAssignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment\n && kind <= ts.SyntaxKind.LastAssignment;\n}\n\nfunction identifierIsReadWithinTarget(\n identifier: ts.Identifier,\n parent: ts.Node,\n): boolean {\n if (ts.isPropertyAccessExpression(parent) && parent.name === identifier) return true;\n if (ts.isElementAccessExpression(parent) && parent.argumentExpression\n && nodeContains(parent.argumentExpression, identifier)) return true;\n if (ts.isPropertyAssignment(parent) && nodeContains(parent.name, identifier)) return true;\n return ts.isComputedPropertyName(parent) && nodeContains(parent.expression, identifier);\n}\n\nfunction identifierIsUnaryWrite(identifier: ts.Identifier): boolean {\n const direct = identifier.parent;\n if (!((ts.isPrefixUnaryExpression(direct) || ts.isPostfixUnaryExpression(direct))\n && direct.operand === identifier)) return false;\n return direct.operator === ts.SyntaxKind.PlusPlusToken\n || direct.operator === ts.SyntaxKind.MinusMinusToken;\n}\n\nfunction identifierIsNestedWrite(identifier: ts.Identifier): boolean {\n let current: ts.Node = identifier;\n while (current.parent) {\n const parent = current.parent;\n if (identifierIsReadWithinTarget(identifier, parent)) return false;\n if (ts.isBinaryExpression(parent))\n return isAssignmentOperator(parent.operatorToken.kind)\n && nodeContains(parent.left, identifier);\n if (ts.isForInStatement(parent) || ts.isForOfStatement(parent))\n return nodeContains(parent.initializer, identifier);\n current = parent;\n }\n return false;\n}\n\nfunction identifierIsWrite(identifier: ts.Identifier): boolean {\n return identifierIsUnaryWrite(identifier) || identifierIsNestedWrite(identifier);\n}\n\nfunction destructuredBindingWasWritten(\n binding: DestructuredBinding,\n localName: string,\n use: ts.Node,\n): boolean {\n if (ts.isParameter(binding.declaration)) return true;\n if ((binding.declaration.parent.flags & ts.NodeFlags.Const) !== 0) return false;\n let written = false;\n const declarationEnd = binding.declaration.name.getEnd();\n const useStart = use.getStart();\n const visit = (node: ts.Node): void => {\n if (written) return;\n if (ts.isIdentifier(node) && node.text === localName\n && node.getStart() > declarationEnd && node.getStart() < useStart\n && identifierIsWrite(node)\n && resolveDestructuredBinding(node, node)?.declaration === binding.declaration)\n written = true;\n ts.forEachChild(node, visit);\n };\n visit(use.getSourceFile());\n return written;\n}\n\nfunction destructuredBindingWins(\n destructured: DestructuredBinding,\n simple: BindingResolution,\n use: ts.Node,\n): boolean {\n return !simple.declaration\n || bindingIsCloser(destructured.declaration, simple.declaration, use);\n}\n\nfunction entityFromDestructuredBinding(\n binding: DestructuredBinding,\n identifier: ts.Identifier,\n): string | undefined {\n if (destructuredBindingWasWritten(binding, identifier.text, identifier))\n return undefined;\n return destructuredEntitySource(binding.initializer)\n ? binding.entityName\n : undefined;\n}\n\nfunction entityFromSimpleBinding(\n binding: BindingResolution,\n depth: number,\n seen: Set<ts.Node>,\n): string | undefined {\n if (!binding.declaration || !binding.immutable || !binding.initializer\n || seen.has(binding.declaration)) return undefined;\n seen.add(binding.declaration);\n return entityFromExpression(binding.initializer, depth + 1, seen);\n}\n\nfunction scopedBindingIsCurrent(\n identifier: ts.Identifier,\n declaration: ts.VariableDeclaration | ts.ParameterDeclaration,\n): boolean {\n return nearestScopedVariableDeclaration(identifier) === declaration\n && !nonVariableBindingWins(identifier, declaration);\n}\n\nfunction unboundEntityName(identifier: ts.Identifier): string | undefined {\n return hasScopedVariableDeclaration(identifier)\n || hasScopedNonVariableDeclaration(identifier)\n ? undefined\n : identifier.text;\n}\n\nfunction entityFromIdentifier(\n expr: ts.Identifier,\n depth: number,\n seen: Set<ts.Node>,\n): string | undefined {\n const binding = resolveBinding(expr, expr);\n const destructured = resolveDestructuredBinding(expr, expr);\n if (destructured && destructuredBindingWins(destructured, binding, expr)) {\n return scopedBindingIsCurrent(expr, destructured.declaration)\n ? entityFromDestructuredBinding(destructured, expr)\n : undefined;\n }\n if (!binding.declaration) return unboundEntityName(expr);\n if (!scopedBindingIsCurrent(expr, binding.declaration)) return undefined;\n return entityFromSimpleBinding(binding, depth, seen);\n}\n\nfunction literalEntity(expr: ts.Expression): string | undefined {\n if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr))\n return expr.text;\n if (!ts.isElementAccessExpression(expr) || !expr.argumentExpression)\n return undefined;\n return ts.isStringLiteral(expr.argumentExpression)\n || ts.isNoSubstitutionTemplateLiteral(expr.argumentExpression)\n ? expr.argumentExpression.text\n : undefined;\n}\n\nfunction propertyEntity(expr: ts.Expression): string | undefined {\n if (!ts.isPropertyAccessExpression(expr)) return undefined;\n if (expr.expression.kind === ts.SyntaxKind.ThisKeyword) return undefined;\n return isEntitiesBase(expr.expression) ? expr.name.text : undefined;\n}\n\nfunction entityFromExpression(\n expr: ts.Expression | undefined,\n depth = 0,\n seen = new Set<ts.Node>(),\n): string | undefined {\n if (!expr || depth >= maxAliasDepth) return undefined;\n const value = unwrapQueryExpression(expr);\n const literal = literalEntity(value);\n if (literal !== undefined) return literal;\n if (ts.isIdentifier(value)) return entityFromIdentifier(value, depth, seen);\n return propertyEntity(value);\n}\n\nfunction queryAliasInitializer(\n identifier: ts.Identifier,\n initializers: Map<string, ts.Expression>,\n seen: Set<string>,\n): ts.Expression | undefined {\n const initializer = initializers.get(identifier.text);\n if (!initializer || seen.has(identifier.text)) return undefined;\n const binding = resolveBinding(identifier, identifier);\n if (!binding.declaration || !binding.immutable || binding.initializer !== initializer\n || nearestScopedVariableDeclaration(identifier) !== binding.declaration\n || nonVariableBindingWins(identifier, binding.declaration)) return undefined;\n seen.add(identifier.text);\n return initializer;\n}\n\nfunction queryEntityFromCall(\n call: ts.CallExpression,\n initializers: Map<string, ts.Expression>,\n seenInitializers: Set<string>,\n): string | undefined {\n const name = expressionName(call.expression);\n if (name === 'cds.run')\n return queryEntityFromAst(call.arguments[0], initializers, seenInitializers);\n if (isCapQueryBuilderRootName(name))\n return entityFromExpression(call.arguments[0]);\n const receiver = ts.isPropertyAccessExpression(call.expression)\n ? call.expression.expression\n : undefined;\n return receiver\n ? queryEntityFromAst(receiver, initializers, seenInitializers)\n : undefined;\n}\n\nexport function queryEntityFromAst(\n expr: ts.Expression,\n initializers = new Map<string, ts.Expression>(),\n seenInitializers = new Set<string>(),\n): string | undefined {\n const unwrapped = unwrapQueryExpression(expr);\n if (ts.isIdentifier(unwrapped)) {\n const initializer = queryAliasInitializer(\n unwrapped, initializers, seenInitializers,\n );\n return initializer\n ? queryEntityFromAst(initializer, initializers, seenInitializers)\n : undefined;\n }\n return ts.isCallExpression(unwrapped)\n ? queryEntityFromCall(unwrapped, initializers, seenInitializers)\n : undefined;\n}\n","import { extractPlaceholderKeys, scanPlaceholders } from '../utils/001-placeholders.js';\n\nexport interface RuntimeSubstitution {\n original?: string;\n effective?: string;\n placeholders: string[];\n missing: string[];\n supplied: string[];\n changed: boolean;\n}\n\nexport function applyVariables(\n template: string | undefined,\n vars: Record<string, string>,\n): string | undefined {\n return substituteVariables(template, vars).effective;\n}\n\nexport function extractPlaceholders(template: string | undefined): string[] {\n return extractPlaceholderKeys(template);\n}\n\nexport function matchRuntimeTemplate(\n template: string | undefined,\n concrete: string | undefined,\n): Record<string, string> | undefined {\n if (!template || !concrete) return undefined;\n const keys = extractPlaceholders(template);\n if (keys.length === 0) return template === concrete ? {} : undefined;\n const match = new RegExp(`^${runtimeTemplatePattern(template)}$`).exec(concrete);\n if (!match) return undefined;\n const values: Record<string, string> = {};\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n const value = match[index + 1];\n if (!key || value === undefined) return undefined;\n if (values[key] !== undefined && values[key] !== value) return undefined;\n values[key] = value;\n }\n return values;\n}\n\nexport function substituteVariables(\n template: string | undefined,\n vars: Record<string, string>,\n): RuntimeSubstitution {\n if (!template) return { placeholders: [], missing: [], supplied: [], changed: false };\n const placeholders = [...new Set(extractPlaceholders(template))];\n const supplied = placeholders.filter((key) => Object.hasOwn(vars, key));\n const missing = placeholders.filter((key) => !Object.hasOwn(vars, key));\n let lastIndex = 0;\n let effective = '';\n for (const span of scanPlaceholders(template)) {\n const trimmed = span.key.trim();\n const replacement = Object.hasOwn(vars, trimmed) ? vars[trimmed] ?? '' : `\\${${trimmed}}`;\n effective += template.slice(lastIndex, span.start) + replacement;\n lastIndex = span.end;\n }\n effective += template.slice(lastIndex);\n return {\n original: template,\n effective,\n placeholders,\n missing,\n supplied,\n changed: effective !== template,\n };\n}\n\nfunction runtimeTemplatePattern(template: string): string {\n let pattern = '';\n let lastIndex = 0;\n for (const span of scanPlaceholders(template)) {\n pattern += escapeRegex(template.slice(lastIndex, span.start));\n pattern += '([^/]+?)';\n lastIndex = span.end;\n }\n return `${pattern}${escapeRegex(template.slice(lastIndex))}`;\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","import type { ImplementationHint } from '../types.js';\nimport { projectBounded } from '../utils/000-bounded-projection.js';\n\ninterface Candidate {\n accepted?: boolean;\n methodId?: number;\n sourceFile?: string;\n handlerPackage?: { name?: string; packageName?: string };\n modelPackage?: { name?: string; packageName?: string };\n servicePath?: string;\n operationPath?: string;\n}\n\ninterface EdgeEvidence {\n servicePath?: string;\n operationPath?: string;\n ambiguityReasons?: string[];\n candidateFamilies?: Array<{ packageName?: string }>;\n candidates?: Candidate[];\n modelPackage?: { name?: string; packageName?: string };\n}\n\nexport interface ImplementationSelection {\n methodId?: string;\n blocksAutomatic: boolean;\n evidence: Record<string, unknown>;\n}\n\nexport interface ImplementationHintSuggestionProjection {\n suggestions: Array<Record<string, unknown>>;\n suggestionCount: number;\n shownSuggestionCount: number;\n omittedSuggestionCount: number;\n}\n\nexport function parseImplementationHint(value: string): ImplementationHint {\n const hint: Partial<ImplementationHint> = {};\n for (const part of value.split(',')) {\n const separator = part.indexOf('=');\n if (separator <= 0 || separator === part.length - 1) throw new Error(`Invalid implementation hint field: ${part}`);\n assignHintField(hint, part.slice(0, separator).trim(), part.slice(separator + 1).trim());\n }\n if (!hint.implementationRepo) throw new Error('Scoped implementation hint requires an implementation repo selection');\n return { ...hint, implementationRepo: hint.implementationRepo };\n}\n\nexport function selectImplementation(\n rawEvidence: Record<string, unknown>,\n hints: ImplementationHint[] | undefined,\n legacyRepo: string | undefined,\n canonicalEvidence?: Record<string, unknown>,\n): ImplementationSelection {\n const evidence = asEvidence(canonicalEvidence ?? rawEvidence);\n const scoped = hints ?? [];\n const matchingHints = scoped.filter((hint) => hintMatchesEdge(hint, evidence));\n if (matchingHints.length === 0) {\n if (legacyRepo) return selectCandidate(evidence, legacyHint(legacyRepo), 'implementation_repo_hint');\n const reason = scoped.length > 0 ? 'no_scoped_hint_matched_edge' : 'no_implementation_hint_supplied';\n return { blocksAutomatic: false, evidence: { status: 'not_matched', reason, strategy: 'scoped_implementation_hint' } };\n }\n if (matchingHints.length > 1) {\n const projection = projectBounded(matchingHints, compareHints);\n return {\n blocksAutomatic: true,\n evidence: {\n status: 'tied',\n reason: 'multiple_scoped_hints_matched_edge',\n strategy: 'scoped_implementation_hint',\n matchedHints: projection.items,\n candidateCount: matchingHints.length,\n matchedHintCount: projection.totalCount,\n shownMatchedHintCount: projection.shownCount,\n omittedMatchedHintCount: projection.omittedCount,\n },\n };\n }\n const hint = matchingHints[0];\n return hint ? selectCandidate(evidence, hint, 'scoped_implementation_hint') : { blocksAutomatic: false, evidence: { status: 'not_matched' } };\n}\n\nexport function implementationHintDiagnostic(\n selection: ImplementationSelection,\n suggestionEvidence?: unknown,\n): Record<string, unknown> | undefined {\n if (!selection.blocksAutomatic || selection.methodId) return undefined;\n const suggestions = projectedSuggestions(suggestionEvidence);\n return {\n severity: 'warning',\n code: 'implementation_hint_mismatch',\n message: 'Implementation hint did not select exactly one viable candidate',\n hintStatus: selection.evidence.status,\n candidateCount: selection.evidence.candidateCount,\n implementationHintSuggestions: suggestions.suggestions.length > 0\n ? suggestions.suggestions\n : undefined,\n implementationHintSuggestionCount: suggestions.suggestionCount,\n shownImplementationHintSuggestionCount: suggestions.shownSuggestionCount,\n omittedImplementationHintSuggestionCount: suggestions.omittedSuggestionCount,\n implementationSelection: selection.evidence,\n };\n}\n\nexport function implementationHintSuggestions(rawEvidence: Record<string, unknown>): Array<Record<string, unknown>> {\n return implementationHintSuggestionProjection(rawEvidence).suggestions;\n}\n\nexport function implementationHintSuggestionProjection(\n rawEvidence: Record<string, unknown>,\n): ImplementationHintSuggestionProjection {\n const evidence = asEvidence(rawEvidence);\n const accepted = (evidence.candidates ?? []).filter((candidate) => candidate.accepted);\n if (accepted.length < 2) {\n return {\n suggestions: [],\n suggestionCount: 0,\n shownSuggestionCount: 0,\n omittedSuggestionCount: 0,\n };\n }\n const repos = selectableRepositories(accepted);\n const repositoryProjection = projectBounded(\n repos, (left, right) => left.localeCompare(right),\n );\n const suggestions = accepted\n .flatMap((candidate) => {\n const repo = candidate.handlerPackage?.name;\n if (!repo || !repos.includes(repo)) return [];\n const hint = suggestionHint(evidence, candidate, repo);\n return [{\n servicePath: hint.servicePath,\n operationPath: hint.operationPath,\n ambiguityReason: evidence.ambiguityReasons?.[0],\n candidateFamily: hint.candidateFamily,\n selectableImplementationRepositories: repositoryProjection.items,\n selectableImplementationRepositoryCount: repositoryProjection.totalCount,\n shownSelectableImplementationRepositoryCount:\n repositoryProjection.shownCount,\n omittedSelectableImplementationRepositoryCount:\n repositoryProjection.omittedCount,\n implementationRepo: repo,\n hint,\n cli: `--implementation-hint ${hintString(hint)}`,\n }];\n });\n const projection = projectBounded(suggestions, compareSuggestion);\n return {\n suggestions: projection.items,\n suggestionCount: projection.totalCount,\n shownSuggestionCount: projection.shownCount,\n omittedSuggestionCount: projection.omittedCount,\n };\n}\n\nfunction projectedSuggestions(value: unknown): ImplementationHintSuggestionProjection {\n const evidence = objectRecord(value);\n const values = Array.isArray(value)\n ? recordSuggestions(value)\n : recordSuggestions(evidence.implementationHintSuggestions);\n const projection = projectBounded(values, compareSuggestion);\n const total = Math.max(\n numericValue(evidence.implementationHintSuggestionCount),\n projection.totalCount,\n );\n return {\n suggestions: projection.items,\n suggestionCount: total,\n shownSuggestionCount: projection.shownCount,\n omittedSuggestionCount: Math.max(0, total - projection.shownCount),\n };\n}\n\nfunction compareHints(left: ImplementationHint, right: ImplementationHint): number {\n return hintString(left).localeCompare(hintString(right));\n}\n\nfunction compareSuggestion(\n left: Record<string, unknown>,\n right: Record<string, unknown>,\n): number {\n return String(left.cli ?? '').localeCompare(String(right.cli ?? ''))\n || String(left.implementationRepo ?? '').localeCompare(\n String(right.implementationRepo ?? ''),\n );\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\n}\n\nfunction recordSuggestions(value: unknown): Array<Record<string, unknown>> {\n return Array.isArray(value)\n ? value.filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === 'object' && !Array.isArray(item)))\n : [];\n}\n\nfunction numericValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction selectableRepositories(candidates: Candidate[]): string[] {\n const repos = new Set(candidates.flatMap((candidate) => candidate.handlerPackage?.name ? [candidate.handlerPackage.name] : []));\n return [...repos]\n .filter((repo) => candidates.filter((candidate) => candidateMatchesRepo(candidate, repo)).length === 1)\n .sort();\n}\n\nfunction assignHintField(hint: Partial<ImplementationHint>, key: string, value: string): void {\n if (key === 'service' || key === 'servicePath') hint.servicePath = value;\n else if (key === 'operation' || key === 'operationPath') hint.operationPath = value;\n else if (key === 'package' || key === 'packageName') hint.packageName = value;\n else if (key === 'repository' || key === 'repositoryName') hint.repositoryName = value;\n else if (key === 'family' || key === 'candidateFamily') hint.candidateFamily = value;\n else if (key === 'repo' || key === 'implementationRepo' || key === 'select') hint.implementationRepo = value;\n else throw new Error(`Unknown implementation hint field: ${key}`);\n}\n\nfunction selectCandidate(evidence: EdgeEvidence, hint: ImplementationHint, strategy: string): ImplementationSelection {\n const matches = (evidence.candidates ?? []).filter((candidate) =>\n candidate.accepted && candidateMatchesRepo(candidate, hint.implementationRepo));\n const selected = matches.length === 1 ? matches[0] : undefined;\n if (!selected || selected.methodId === undefined) {\n return {\n blocksAutomatic: true,\n evidence: {\n status: matches.length > 1 ? 'tied' : 'not_matched',\n reason: matches.length > 1 ? 'hint_matched_multiple_candidates' : 'hint_matched_zero_candidates',\n strategy,\n matchedHint: hint,\n selectedRepo: hint.implementationRepo,\n candidateCount: matches.length,\n },\n };\n }\n return {\n methodId: String(selected.methodId),\n blocksAutomatic: false,\n evidence: {\n status: 'selected',\n guided: true,\n strategy,\n matchedHint: hint,\n selectedRepo: hint.implementationRepo,\n selectedMethodId: selected.methodId,\n ambiguityReason: evidence.ambiguityReasons?.[0],\n },\n };\n}\n\nfunction suggestionHint(evidence: EdgeEvidence, candidate: Candidate, repo: string): ImplementationHint {\n const servicePath = evidence.servicePath ?? candidate.servicePath;\n const operationPath = evidence.operationPath ?? candidate.operationPath;\n const family = usefulCandidateFamily(evidence, candidate);\n return {\n ...(servicePath ? { servicePath } : {}),\n ...(operationPath ? { operationPath } : {}),\n ...(evidence.modelPackage?.packageName ? { packageName: evidence.modelPackage.packageName } : {}),\n ...(evidence.modelPackage?.name ? { repositoryName: evidence.modelPackage.name } : {}),\n ...(family ? { candidateFamily: family } : {}),\n implementationRepo: repo,\n };\n}\n\nfunction usefulCandidateFamily(evidence: EdgeEvidence, candidate: Candidate): string | undefined {\n const family = candidate.handlerPackage?.packageName;\n if (!family) return undefined;\n if ((evidence.candidateFamilies ?? []).some((item) => item.packageName === family)) return family;\n const acceptedFamilies = new Set(\n (evidence.candidates ?? [])\n .filter((item) => item.accepted)\n .flatMap((item) => item.handlerPackage?.packageName ? [item.handlerPackage.packageName] : []),\n );\n return acceptedFamilies.size > 1 ? family : undefined;\n}\n\nfunction hintString(hint: ImplementationHint): string {\n const fields = [\n ['service', hint.servicePath],\n ['operation', hint.operationPath],\n ['package', hint.packageName],\n ['repository', hint.repositoryName],\n ['family', hint.candidateFamily],\n ['repo', hint.implementationRepo],\n ];\n return fields.flatMap(([key, value]) => value ? [`${key}=${value}`] : []).join(',');\n}\n\nfunction hintMatchesEdge(hint: ImplementationHint, evidence: EdgeEvidence): boolean {\n const model = evidence.modelPackage ?? evidence.candidates?.[0]?.modelPackage;\n const familyNames = new Set([\n ...(evidence.candidateFamilies ?? []).flatMap((family) => family.packageName ? [family.packageName] : []),\n ...(evidence.candidates ?? []).flatMap((candidate) => candidate.handlerPackage?.packageName ? [candidate.handlerPackage.packageName] : []),\n ]);\n return matches(hint.servicePath, evidence.servicePath ?? evidence.candidates?.[0]?.servicePath)\n && matches(hint.operationPath, evidence.operationPath ?? evidence.candidates?.[0]?.operationPath)\n && matches(hint.packageName, model?.packageName)\n && matches(hint.repositoryName, model?.name)\n && (!hint.candidateFamily || familyNames.has(hint.candidateFamily));\n}\n\nfunction candidateMatchesRepo(candidate: Candidate, value: string): boolean {\n return candidate.handlerPackage?.name === value\n || candidate.handlerPackage?.packageName === value\n || candidate.sourceFile?.startsWith(value) === true;\n}\n\nfunction matches(expected: string | undefined, actual: string | undefined): boolean {\n return expected === undefined || expected === actual;\n}\n\nfunction legacyHint(implementationRepo: string): ImplementationHint {\n return { implementationRepo };\n}\n\nfunction asEvidence(value: Record<string, unknown>): EdgeEvidence {\n return {\n servicePath: stringValue(value.servicePath),\n operationPath: stringValue(value.operationPath),\n ambiguityReasons: stringArray(value.ambiguityReasons),\n candidateFamilies: candidateFamilies(value.candidateFamilies),\n candidates: candidates(value.candidates),\n modelPackage: packageValue(value.modelPackage),\n };\n}\n\nfunction candidates(value: unknown): Candidate[] {\n return recordSuggestions(value).map((candidate) => ({\n accepted: candidate.accepted === true,\n methodId: numericValue(candidate.methodId) || undefined,\n sourceFile: stringValue(candidate.sourceFile),\n handlerPackage: packageValue(candidate.handlerPackage),\n modelPackage: packageValue(candidate.modelPackage),\n servicePath: stringValue(candidate.servicePath),\n operationPath: stringValue(candidate.operationPath),\n }));\n}\n\nfunction candidateFamilies(value: unknown): Array<{ packageName?: string }> {\n return recordSuggestions(value).map((family) => ({\n packageName: stringValue(family.packageName),\n }));\n}\n\nfunction packageValue(value: unknown): { name?: string; packageName?: string } | undefined {\n const candidate = objectRecord(value);\n const name = stringValue(candidate.name);\n const packageName = stringValue(candidate.packageName);\n return name || packageName ? { name, packageName } : undefined;\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n","export interface RemoteQueryTargetInput {\n queryEntity?: unknown;\n servicePath?: string;\n serviceAlias?: unknown;\n serviceAliasExpr?: unknown;\n destination?: string;\n isDynamic?: boolean;\n parserWarning?: unknown;\n}\n\nexport interface RemoteQueryTarget {\n toKind: 'remote_entity' | 'remote_query';\n toId: string;\n label: string;\n evidence: Record<string, unknown>;\n}\n\nexport function buildRemoteQueryTarget(input: RemoteQueryTargetInput): RemoteQueryTarget {\n const entity = typeof input.queryEntity === 'string' && input.queryEntity.trim() ? input.queryEntity.trim() : undefined;\n const servicePath = input.servicePath?.trim();\n const prefix = servicePath ? `${servicePath}:` : '';\n const label = entity ? `Remote entity: ${prefix}${entity}` : 'Remote query: unknown';\n return {\n toKind: entity ? 'remote_entity' : 'remote_query',\n toId: entity ? `${prefix}${entity}` : 'unknown',\n label,\n evidence: {\n remoteQueryTarget: label,\n queryEntity: entity,\n queryTargetKind: entity ? 'remote_entity' : 'remote_query_unknown',\n queryEntityDynamic: entity ? undefined : Boolean(input.isDynamic) || undefined,\n serviceAlias: input.serviceAlias,\n serviceAliasExpr: input.serviceAliasExpr,\n destination: input.destination,\n servicePath,\n parserWarning: entity ? input.parserWarning : input.parserWarning ?? { code: 'query_entity_unknown', message: 'Remote query entity is dynamic or unavailable' },\n },\n };\n}\n","import {\n projectBounded,\n projectBoundedInOrder,\n type BoundedProjection,\n} from '../utils/000-bounded-projection.js';\n\nexport interface SelectedHandlerSource {\n methodId: number;\n className?: string;\n methodName?: string;\n repositoryId?: number;\n repositoryName?: string;\n repositoryPackageName?: string;\n sourceFile?: string;\n sourceLine?: number;\n}\n\nexport interface SelectedHandlerProvenance {\n status: 'selected';\n accepted: true;\n graphTargetId: string;\n methodId: number;\n className?: string;\n methodName?: string;\n repository?: {\n id?: number;\n name?: string;\n packageName?: string;\n };\n sourceFile?: string;\n sourceLine?: number;\n}\n\nexport function selectedHandlerProvenance(\n source: SelectedHandlerSource,\n): SelectedHandlerProvenance {\n return {\n status: 'selected',\n accepted: true,\n graphTargetId: String(source.methodId),\n methodId: source.methodId,\n className: source.className,\n methodName: source.methodName,\n repository: {\n id: source.repositoryId,\n name: source.repositoryName,\n packageName: source.repositoryPackageName,\n },\n sourceFile: source.sourceFile,\n sourceLine: source.sourceLine,\n };\n}\n\nexport function displayImplementationCandidates(\n candidates: Array<Record<string, unknown>>,\n selectedMethodId: number | undefined,\n): Array<Record<string, unknown>> {\n return [...candidates]\n .sort((left, right) => compareDisplayCandidate(\n left, right, selectedMethodId,\n ))\n .map((candidate, index) => ({\n ...candidate,\n discoveryRank: candidate.rank,\n displayRank: index + 1,\n selected: selectedMethodId !== undefined\n && Number(candidate.methodId) === selectedMethodId,\n }));\n}\n\nfunction compareDisplayCandidate(\n left: Record<string, unknown>,\n right: Record<string, unknown>,\n selectedMethodId: number | undefined,\n): number {\n return Number(Number(right.methodId) === selectedMethodId)\n - Number(Number(left.methodId) === selectedMethodId)\n || Number(right.accepted === true) - Number(left.accepted === true)\n || numberValue(left.rank) - numberValue(right.rank)\n || compareTargetCandidates(left, right);\n}\n\nexport function boundedImplementationEvidence(\n evidence: Record<string, unknown>,\n targetCandidateCount: number,\n): Record<string, unknown> {\n const candidates = recordArray(evidence.candidates);\n const candidateProjection = projectBoundedInOrder(candidates);\n const families = recordArray(evidence.candidateFamilies);\n const familyProjection = projectBounded(families, compareFamilies);\n const hints = recordArray(evidence.implementationHintSuggestions);\n const hintProjection = projectBounded(hints, compareHints);\n const hintCount = Math.max(\n numberValue(evidence.implementationHintSuggestionCount),\n hintProjection.totalCount,\n );\n const targets = Math.max(0, targetCandidateCount);\n return {\n ...evidence,\n candidates: candidateProjection.items.map(boundedCandidateEvidence),\n candidateCount: candidateProjection.totalCount,\n shownCandidateCount: candidateProjection.shownCount,\n omittedCandidateCount: candidateProjection.omittedCount,\n candidateFamilies: familyProjection.items.map(boundedFamilyEvidence),\n candidateFamilyCount: familyProjection.totalCount,\n shownCandidateFamilyCount: familyProjection.shownCount,\n omittedCandidateFamilyCount: familyProjection.omittedCount,\n implementationHintSuggestions: hintProjection.items,\n implementationHintSuggestionCount: hintCount,\n shownImplementationHintSuggestionCount: hintProjection.shownCount,\n omittedImplementationHintSuggestionCount: Math.max(0, hintCount - hintProjection.shownCount),\n candidateTargetCount: targets,\n shownCandidateTargetCount: Math.min(targets, candidateProjection.shownCount),\n omittedCandidateTargetCount: Math.max(0, targets - candidateProjection.shownCount),\n };\n}\n\nexport function boundedImplementationTargetIds(\n candidates: Array<Record<string, unknown>>,\n): BoundedProjection<string> {\n const projection = projectBounded(candidates, compareTargetCandidates);\n return {\n totalCount: projection.totalCount,\n shownCount: projection.shownCount,\n omittedCount: projection.omittedCount,\n items: projection.items.map((candidate) => String(candidate.methodId ?? '')),\n };\n}\n\nfunction boundedCandidateEvidence(candidate: Record<string, unknown>): Record<string, unknown> {\n const registrations = recordArray(candidate.registrations);\n const projection = projectBounded(registrations, compareRegistrations);\n return {\n ...candidate,\n registrations: projection.items,\n registrationCount: projection.totalCount,\n shownRegistrationCount: projection.shownCount,\n omittedRegistrationCount: projection.omittedCount,\n };\n}\n\nfunction boundedFamilyEvidence(family: Record<string, unknown>): Record<string, unknown> {\n const repositories = stringArray(family.repositories);\n const projection = projectBounded(repositories, (left, right) => left.localeCompare(right));\n return {\n ...family,\n repositories: projection.items,\n repositoryCount: projection.totalCount,\n shownRepositoryCount: projection.shownCount,\n omittedRepositoryCount: projection.omittedCount,\n };\n}\n\nfunction compareTargetCandidates(left: Record<string, unknown>, right: Record<string, unknown>): number {\n return Number(right.score ?? 0) - Number(left.score ?? 0)\n || String(left.className ?? '').localeCompare(String(right.className ?? ''))\n || Number(left.methodId ?? 0) - Number(right.methodId ?? 0);\n}\n\nfunction compareFamilies(left: Record<string, unknown>, right: Record<string, unknown>): number {\n return String(left.packageName ?? '').localeCompare(String(right.packageName ?? ''))\n || String(left.reason ?? '').localeCompare(String(right.reason ?? ''));\n}\n\nfunction compareHints(left: Record<string, unknown>, right: Record<string, unknown>): number {\n return String(left.cli ?? '').localeCompare(String(right.cli ?? ''))\n || String(left.implementationRepo ?? '').localeCompare(String(right.implementationRepo ?? ''));\n}\n\nfunction compareRegistrations(left: Record<string, unknown>, right: Record<string, unknown>): number {\n return String(left.file ?? '').localeCompare(String(right.file ?? ''))\n || Number(left.line ?? 0) - Number(right.line ?? 0)\n || Number(left.id ?? 0) - Number(right.id ?? 0);\n}\n\nfunction recordArray(value: unknown): Array<Record<string, unknown>> {\n return Array.isArray(value)\n ? value.filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === 'object' && !Array.isArray(item)))\n : [];\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction numberValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n","import type { Db } from '../db/connection.js';\nimport { implementationHintSuggestionProjection } from '../trace/implementation-hints.js';\nimport { normalizeDecoratorOperationSignal, normalizedOperationName } from './operation-decorator-normalizer.js';\nimport {\n boundedImplementationEvidence,\n boundedImplementationTargetIds,\n displayImplementationCandidates,\n selectedHandlerProvenance,\n} from './001-implementation-evidence-projection.js';\n\ninterface ImplementationCandidate extends Record<string, unknown> {\n methodId: number;\n registrations?: Array<Record<string, unknown>>;\n score: number;\n accepted: boolean;\n acceptedReasons: string[];\n rejectedReasons: string[];\n}\n\ninterface ImplementationDecision {\n candidates: ImplementationCandidate[];\n accepted: ImplementationCandidate[];\n selected: ImplementationCandidate[];\n unique?: ImplementationCandidate;\n evidence: Record<string, unknown>;\n evidenceWithHints: Record<string, unknown>;\n}\n\nexport function linkImplementations(\n db: Db,\n workspaceId: number,\n generation: number,\n): { edgeCount: number; resolvedCount: number; ambiguousCount: number; unresolvedCount: number } {\n const operations = workspaceOperations(db, workspaceId);\n let edgeCount = 0;\n let resolvedCount = 0;\n let ambiguousCount = 0;\n let unresolvedCount = 0;\n for (const operation of operations) {\n const decision = implementationDecision(db, workspaceId, operation, true);\n if (decision.candidates.length === 0) continue;\n const status = decision.unique ? 'resolved' : decision.accepted.length > 0\n ? 'ambiguous'\n : 'unresolved';\n insertImplementationEdge(db, workspaceId, generation, operation, decision, status);\n edgeCount += 1;\n if (status === 'resolved') resolvedCount += 1;\n else if (status === 'ambiguous') ambiguousCount += 1;\n else unresolvedCount += 1;\n }\n return { edgeCount, resolvedCount, ambiguousCount, unresolvedCount };\n}\n\nexport function canonicalImplementationEvidence(\n db: Db,\n operationId: string | number,\n): Record<string, unknown> | undefined {\n const operation = operationById(db, operationId);\n const workspaceId = numberValue(operation?.workspaceId);\n if (!operation || workspaceId === undefined) return undefined;\n return implementationDecision(db, workspaceId, operation, false).evidenceWithHints;\n}\n\nfunction workspaceOperations(db: Db, workspaceId: number): Array<Record<string, unknown>> {\n const rows = db.prepare(`SELECT o.id operationId,o.operation_path operationPath,\n o.operation_name operationName,o.provenance provenance,o.base_operation_id baseOperationId,\n s.service_path servicePath,s.repo_id modelRepoId,r.name modelRepo,\n r.package_name modelPackage,r.kind modelKind\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id\n JOIN repositories r ON r.id=s.repo_id WHERE r.workspace_id=?`).all(workspaceId);\n return rows;\n}\n\nfunction operationById(\n db: Db,\n operationId: string | number,\n): Record<string, unknown> | undefined {\n const row = db.prepare(`SELECT o.id operationId,o.operation_path operationPath,\n o.operation_name operationName,o.provenance provenance,o.base_operation_id baseOperationId,\n s.service_path servicePath,s.repo_id modelRepoId,r.name modelRepo,\n r.package_name modelPackage,r.kind modelKind,r.workspace_id workspaceId\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id\n JOIN repositories r ON r.id=s.repo_id WHERE o.id=?`).get(operationId);\n return row;\n}\n\nfunction implementationDecision(\n db: Db,\n workspaceId: number,\n operation: Record<string, unknown>,\n recordDiagnostics: boolean,\n): ImplementationDecision {\n const implementationContext = implementationContextForOperation(db, operation);\n const candidates = rankedImplementationCandidates(\n db, workspaceId, implementationContext, recordDiagnostics,\n );\n const accepted = candidates.filter((candidate) => candidate.accepted);\n const topScore = accepted[0]?.score ?? 0;\n const winners = accepted.filter((candidate) => candidate.score === topScore);\n const duplicateFamilies = duplicatePackageFamilies(accepted);\n const duplicatePackageAmbiguous = duplicateFamilies.length > 0\n && !accepted.some(hasDirectOwnershipEvidence);\n const selected = duplicatePackageAmbiguous ? accepted : winners;\n const unique = !duplicatePackageAmbiguous && winners.length === 1\n ? winners[0]\n : undefined;\n const ambiguityReasons = duplicatePackageAmbiguous\n ? ['duplicate_package_name_candidates']\n : winners.length > 1 ? ['multiple_equal_score_implementation_candidates'] : [];\n const evidence = implementationEvidence(\n operation, implementationContext, candidates, duplicateFamilies, ambiguityReasons,\n unique,\n );\n const hintProjection = implementationHintSuggestionProjection(evidence);\n return {\n candidates,\n accepted,\n selected,\n unique,\n evidence,\n evidenceWithHints: unique\n ? evidence\n : {\n ...evidence,\n implementationHintSuggestions: hintProjection.suggestions,\n implementationHintSuggestionCount: hintProjection.suggestionCount,\n shownImplementationHintSuggestionCount: hintProjection.shownSuggestionCount,\n omittedImplementationHintSuggestionCount: hintProjection.omittedSuggestionCount,\n },\n };\n}\n\nfunction insertImplementationEdge(\n db: Db,\n workspaceId: number,\n generation: number,\n operation: Record<string, unknown>,\n decision: ImplementationDecision,\n status: 'resolved' | 'ambiguous' | 'unresolved',\n): void {\n const targetCandidates = status === 'unresolved'\n ? decision.candidates\n : decision.selected;\n const targetProjection = boundedImplementationTargetIds(targetCandidates);\n const targetIds = targetProjection.items;\n const toId = status === 'resolved'\n ? graphId(decision.unique?.methodId)\n : targetIds.join(',');\n const reason = status === 'unresolved'\n ? 'No implementation candidate passed policy'\n : status === 'ambiguous'\n ? 'Ambiguous registered handler implementation candidates'\n : null;\n db.prepare(`INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,\n to_kind,to_id,confidence,evidence_json,is_dynamic,unresolved_reason,generation)\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`).run(\n workspaceId,\n 'OPERATION_IMPLEMENTED_BY_HANDLER',\n status,\n 'operation',\n graphId(operation.operationId),\n status === 'resolved' ? 'handler_method' : 'handler_method_candidates',\n toId,\n status === 'resolved' ? 0.95 : status === 'ambiguous' ? 0.5 : 0,\n JSON.stringify(boundedImplementationEvidence(\n decision.evidenceWithHints, targetProjection.totalCount,\n )),\n 0,\n reason,\n generation,\n );\n}\n\nfunction implementationEvidence(\n operation: Record<string, unknown>,\n context: Record<string, unknown>,\n candidates: ImplementationCandidate[],\n duplicateFamilies: Array<Record<string, unknown>>,\n ambiguityReasons: string[],\n selected: ImplementationCandidate | undefined,\n): Record<string, unknown> {\n return {\n servicePath: operation.servicePath,\n operationPath: operation.operationPath,\n operationName: operation.operationName,\n modelPackage: {\n id: operation.modelRepoId,\n name: operation.modelRepo,\n packageName: operation.modelPackage,\n },\n implementationSource: context.operationId === operation.operationId\n ? 'direct_or_concrete_override'\n : 'inherited_from_base_operation',\n baseOperationId: operation.baseOperationId,\n implementationOperationId: context.operationId,\n ambiguityReasons,\n candidateFamilies: duplicateFamilies,\n selectedHandler: selected\n ? selectedHandlerProvenance(selectedHandlerSource(selected))\n : undefined,\n candidates: displayImplementationCandidates(\n candidates.map((candidate, index) => candidateEvidence(candidate, index + 1)),\n selected?.methodId,\n ),\n };\n}\n\n\nfunction implementationContextForOperation(\n db: Db,\n operation: Record<string, unknown>,\n): Record<string, unknown> {\n if (operation.provenance !== 'inherited' || !operation.baseOperationId) return operation;\n const base = db.prepare(`SELECT o.id operationId,o.operation_path operationPath,\n o.operation_name operationName,o.provenance provenance,o.base_operation_id baseOperationId,\n s.service_path servicePath,s.repo_id modelRepoId,r.name modelRepo,\n r.package_name modelPackage,r.kind modelKind\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id\n JOIN repositories r ON r.id=s.repo_id WHERE o.id=?`).get(operation.baseOperationId);\n return base ? {\n ...base,\n effectiveOperationId: operation.operationId,\n effectiveServicePath: operation.servicePath,\n effectiveOperationPath: operation.operationPath,\n } : operation;\n}\n\nfunction rankedImplementationCandidates(\n db: Db,\n workspaceId: number,\n operation: Record<string, unknown>,\n recordDiagnostics: boolean,\n): ImplementationCandidate[] {\n const rows = implementationCandidates(db, workspaceId, operation);\n if (recordDiagnostics) recordRegistrationInvariantDiagnostics(\n db, rows.filter((row) => !validRegistrationPair(row)),\n );\n return deduplicateCandidates(rows.filter(validRegistrationPair)\n .map((row) => scoreImplementationCandidate(row, operation)))\n .sort((left, right) => right.score - left.score\n || String(left.className).localeCompare(String(right.className))\n || left.methodId - right.methodId);\n}\n\nfunction validRegistrationPair(row: Record<string, unknown>): boolean {\n if (row.registrationHandlerClassId === null || row.registrationHandlerClassId === undefined)\n return registrationPairingStrategy(row) !== 'unproven';\n return Number(row.registrationHandlerClassId) === Number(row.classId);\n}\n\nfunction registrationPairingStrategy(row: Record<string, unknown>): string {\n if (row.registrationHandlerClassId !== null && row.registrationHandlerClassId !== undefined)\n return 'exact_handler_class_id';\n if (Number(row.applicationRepoId) === Number(row.handlerRepoId))\n return 'same_repository_class_name_fallback';\n const source = stringValue(row.importSource);\n const separator = source?.lastIndexOf('#') ?? -1;\n if (!source || separator <= 0) return 'unproven';\n const moduleName = source.slice(0, separator);\n const importedName = source.slice(separator + 1);\n const matchesClass = importedName === row.className\n || (importedName === 'default' && row.registrationClassName === row.className);\n return moduleName === row.handlerPackage && matchesClass\n ? 'explicit_package_import'\n : 'unproven';\n}\n\nfunction recordRegistrationInvariantDiagnostics(\n db: Db,\n rows: Array<Record<string, unknown>>,\n): void {\n const insert = db.prepare(`INSERT INTO diagnostics(repo_id,severity,code,message,\n source_file,source_line)\n SELECT ?,'error','handler_registration_class_mismatch',\n 'Implementation candidate registration did not match its persisted handler class id',?,?\n WHERE NOT EXISTS (SELECT 1 FROM diagnostics WHERE repo_id=?\n AND code='handler_registration_class_mismatch' AND source_file=? AND source_line=?)`);\n for (const row of rows) insert.run(\n row.applicationRepoId, row.registrationFile, row.registrationLine,\n row.applicationRepoId, row.registrationFile, row.registrationLine,\n );\n}\n\nfunction deduplicateCandidates(rows: ImplementationCandidate[]): ImplementationCandidate[] {\n const merged = new Map<string, ImplementationCandidate>();\n for (const row of rows) {\n const key = [row.methodId, row.classId, row.handlerRepoId].join(':');\n const registration = registrationEvidence(row);\n const existing = merged.get(key);\n if (!existing) {\n merged.set(key, { ...row, registrations: [registration] });\n continue;\n }\n existing.registrations = uniqueRegistrations([\n ...(existing.registrations ?? []), registration,\n ]);\n existing.score = Math.max(existing.score, row.score);\n existing.accepted = existing.accepted || row.accepted;\n existing.acceptedReasons = [...new Set([...existing.acceptedReasons, ...row.acceptedReasons])];\n existing.rejectedReasons = [...new Set([...existing.rejectedReasons, ...row.rejectedReasons])];\n }\n return [...merged.values()];\n}\n\nfunction registrationEvidence(row: Record<string, unknown>): Record<string, unknown> {\n return {\n id: row.registrationId,\n handlerClassId: row.registrationHandlerClassId,\n file: row.registrationFile,\n line: row.registrationLine,\n kind: row.registrationKind,\n importSource: row.importSource,\n pairingStrategy: registrationPairingStrategy(row),\n };\n}\n\nfunction uniqueRegistrations(rows: Array<Record<string, unknown>>): Array<Record<string, unknown>> {\n const seen = new Set<string>();\n return rows.filter((row) => {\n const key = JSON.stringify(row);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction duplicatePackageFamilies(candidates: ImplementationCandidate[]): Array<Record<string, unknown>> {\n const byPackage = new Map<string, ImplementationCandidate[]>();\n for (const candidate of candidates) {\n const packageName = stringValue(candidate.handlerPackage);\n if (packageName) byPackage.set(packageName, [\n ...(byPackage.get(packageName) ?? []), candidate,\n ]);\n }\n return [...byPackage.entries()].filter(([, rows]) =>\n new Set(rows.map((row) => Number(row.handlerRepoId))).size > 1)\n .map(([packageName, rows]) => ({\n reason: 'duplicate_package_name_candidates',\n packageName,\n count: rows.length,\n repositories: rows.map((row) => row.handlerRepo).sort(),\n }));\n}\n\nfunction hasDirectOwnershipEvidence(candidate: ImplementationCandidate): boolean {\n return candidate.acceptedReasons.some((reason) => [\n 'model package equals registration package',\n 'model package equals handler package',\n 'registration package contains exact local service path',\n ].includes(reason));\n}\n\nfunction implementationCandidates(\n db: Db,\n workspaceId: number,\n operation: Record<string, unknown>,\n): Array<Record<string, unknown>> {\n const modelRepoGraphId = graphId(operation.modelRepoId);\n return db.prepare(`SELECT DISTINCT\n hm.id methodId,hm.method_name methodName,hm.decorator_value decoratorValue,\n hm.decorator_raw_expression decoratorRawExpression,\n hm.decorator_resolution_json decoratorResolutionJson,hc.id classId,\n hc.class_name className,hc.source_file sourceFile,hm.source_line sourceLine,\n hr.id registrationId,hr.handler_class_id registrationHandlerClassId,\n hr.class_name registrationClassName,hr.repo_id applicationRepoId,\n hr.registration_file registrationFile,hr.registration_line registrationLine,\n hr.registration_kind registrationKind,hr.import_source importSource,\n handlerRepo.id handlerRepoId,handlerRepo.name handlerRepo,\n handlerRepo.package_name handlerPackage,appRepo.name applicationRepo,\n appRepo.package_name applicationPackage,? modelRepoId,? modelRepo,? modelPackage,\n ? modelKind,? servicePath,? operationPath,? operationName,\n CASE WHEN appRepo.id=? THEN 1 ELSE 0 END modelIsApplicationRepo,\n CASE WHEN handlerRepo.id=? THEN 1 ELSE 0 END modelIsHandlerRepo,\n CASE WHEN appRepo.id=handlerRepo.id THEN 1 ELSE 0 END sameRepoRegistration,\n CASE WHEN EXISTS (SELECT 1 FROM cds_services localService\n WHERE localService.repo_id=appRepo.id AND localService.service_path=?)\n THEN 1 ELSE 0 END localServicePathMatch,\n CASE WHEN EXISTS (SELECT 1 FROM cds_services localService\n WHERE localService.repo_id=appRepo.id) THEN 1 ELSE 0 END applicationHasLocalServices,\n CASE WHEN EXISTS (SELECT 1 FROM handler_registrations localReg\n JOIN handler_classes localClass ON ((localReg.handler_class_id IS NOT NULL\n AND localClass.id=localReg.handler_class_id) OR (localReg.handler_class_id IS NULL\n AND localClass.class_name=localReg.class_name AND localClass.repo_id=localReg.repo_id))\n JOIN handler_methods localMethod ON localMethod.handler_class_id=localClass.id\n WHERE localReg.repo_id=appRepo.id\n AND COALESCE(json_extract(localMethod.decorator_resolution_json,'$.handlerKind'),\n CASE WHEN localMethod.decorator_kind='Event' THEN 'event'\n WHEN localMethod.decorator_kind IN ('Action','Func','On') THEN 'operation'\n ELSE 'unsupported' END)='operation'\n AND COALESCE(json_extract(localMethod.decorator_resolution_json,'$.executable'),\n CASE WHEN localMethod.decorator_kind IN ('Action','Func','On') THEN 1 ELSE 0 END)=1\n AND (localMethod.decorator_value=? OR localMethod.decorator_value=?\n OR localMethod.method_name=? OR localMethod.decorator_raw_expression LIKE ?))\n THEN 1 ELSE 0 END applicationHasLocalRegistrationForOperation,\n CASE WHEN EXISTS (SELECT 1 FROM graph_edges dep\n WHERE dep.edge_type='REPO_IMPORTS_HELPER_PACKAGE' AND dep.status='resolved'\n AND dep.from_kind='repo' AND dep.from_id=CAST(appRepo.id AS TEXT)\n AND dep.to_id=?) THEN 1 ELSE 0 END appDependsOnModel,\n CASE WHEN EXISTS (SELECT 1 FROM graph_edges dep\n WHERE dep.edge_type='REPO_IMPORTS_HELPER_PACKAGE' AND dep.status='resolved'\n AND dep.from_kind='repo' AND dep.from_id=CAST(appRepo.id AS TEXT)\n AND dep.to_id=CAST(handlerRepo.id AS TEXT)) THEN 1 ELSE 0 END appDependsOnHandler,\n CASE WHEN EXISTS (SELECT 1 FROM graph_edges dep\n WHERE dep.edge_type='REPO_IMPORTS_HELPER_PACKAGE' AND dep.status='resolved'\n AND dep.from_kind='repo' AND dep.from_id=CAST(handlerRepo.id AS TEXT)\n AND dep.to_id=?) THEN 1 ELSE 0 END handlerDependsOnModel\n FROM handler_methods hm JOIN handler_classes hc ON hc.id=hm.handler_class_id\n JOIN repositories handlerRepo ON handlerRepo.id=hc.repo_id\n JOIN handler_registrations hr ON ((hr.handler_class_id IS NOT NULL\n AND hr.handler_class_id=hc.id) OR (hr.handler_class_id IS NULL AND\n ((hr.class_name=hc.class_name AND hr.repo_id=hc.repo_id) OR\n (instr(hr.import_source,'#')>1 AND substr(hr.import_source,1,\n instr(hr.import_source,'#')-1)=handlerRepo.package_name AND\n (substr(hr.import_source,instr(hr.import_source,'#')+1)=hc.class_name OR\n (substr(hr.import_source,instr(hr.import_source,'#')+1)='default'\n AND hr.class_name=hc.class_name))))))\n JOIN repositories appRepo ON appRepo.id=hr.repo_id\n WHERE appRepo.workspace_id=?\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.handlerKind'),\n CASE WHEN hm.decorator_kind='Event' THEN 'event'\n WHEN hm.decorator_kind IN ('Action','Func','On') THEN 'operation'\n ELSE 'unsupported' END)='operation'\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.executable'),\n CASE WHEN hm.decorator_kind IN ('Action','Func','On') THEN 1 ELSE 0 END)=1\n AND (hm.decorator_value=? OR hm.decorator_value=? OR hm.method_name=?\n OR hm.decorator_raw_expression LIKE ?)`).all(\n operation.modelRepoId, operation.modelRepo, operation.modelPackage, operation.modelKind,\n operation.servicePath, operation.operationPath, operation.operationName,\n operation.modelRepoId, operation.modelRepoId, operation.servicePath,\n normalizedOperation(String(operation.operationPath ?? '')),\n operation.operationName, operation.operationName,\n `%${upperFirst(normalizedOperation(String(operation.operationPath\n ?? operation.operationName ?? '')))}%`,\n modelRepoGraphId, modelRepoGraphId, workspaceId,\n normalizedOperation(String(operation.operationPath ?? '')),\n operation.operationName, operation.operationName,\n `%${upperFirst(normalizedOperation(String(operation.operationPath\n ?? operation.operationName ?? '')))}%`,\n );\n}\n\nfunction scoreImplementationCandidate(\n row: Record<string, unknown>,\n operation: Record<string, unknown>,\n): ImplementationCandidate {\n const acceptedReasons: string[] = [];\n const rejectedReasons: string[] = [];\n const methodSignal = implementationMethodSignal(row, operation);\n acceptedReasons.push(...methodSignal.acceptedReasons);\n rejectedReasons.push(...methodSignal.rejectedReasons);\n const signals = implementationOwnershipSignals(row, methodSignal.matches);\n acceptedReasons.push(...signals.acceptedReasons);\n rejectedReasons.push(...signals.rejectedReasons);\n const accepted = methodSignal.matches && !methodSignal.contradicted\n && !signals.contradicted && signals.hasOwnership;\n if (!accepted && rejectedReasons.length === 0)\n rejectedReasons.push('candidate did not meet implementation ownership policy');\n return {\n ...row,\n methodId: Number(row.methodId),\n score: signals.score,\n accepted,\n acceptedReasons,\n rejectedReasons,\n };\n}\n\nfunction implementationOwnershipSignals(\n row: Record<string, unknown>,\n methodMatches: boolean,\n): { score: number; hasOwnership: boolean; contradicted: boolean; acceptedReasons: string[]; rejectedReasons: string[] } {\n const acceptedReasons: string[] = [];\n const rejectedReasons: string[] = [];\n const modelIsApplicationRepo = flag(row.modelIsApplicationRepo);\n const modelIsHandlerRepo = flag(row.modelIsHandlerRepo);\n const localServicePathMatch = flag(row.localServicePathMatch);\n const applicationHasLocalServices = flag(row.applicationHasLocalServices);\n const appDependsOnModel = flag(row.appDependsOnModel);\n const appDependsOnHandler = flag(row.appDependsOnHandler);\n const handlerDependsOnModel = flag(row.handlerDependsOnModel);\n const importSource = Boolean(stringValue(row.importSource));\n const sameRepoRegistration = flag(row.sameRepoRegistration);\n const modelOriented = row.modelKind === 'cap-db-model'\n || !flag(row.applicationHasLocalRegistrationForOperation);\n const helperOwned = modelOriented && methodMatches && sameRepoRegistration && importSource\n && !applicationHasLocalServices && !modelIsApplicationRepo && !modelIsHandlerRepo\n && !localServicePathMatch && !appDependsOnModel && !appDependsOnHandler && !handlerDependsOnModel;\n const score = ownershipScore({\n modelIsApplicationRepo, modelIsHandlerRepo, localServicePathMatch,\n appDependsOnModel, appDependsOnHandler, handlerDependsOnModel, helperOwned,\n importSource,\n }, acceptedReasons);\n const hasOwnership = modelIsApplicationRepo || modelIsHandlerRepo;\n const hasCrossPackage = appDependsOnModel\n && (modelIsHandlerRepo || appDependsOnHandler || !importSource);\n const contradicted = applicationHasLocalServices && !localServicePathMatch\n && !appDependsOnModel && !hasOwnership;\n if (applicationHasLocalServices && !localServicePathMatch && !appDependsOnModel\n && !modelIsApplicationRepo)\n rejectedReasons.push(`registration package has local services but none match ${String(row.servicePath ?? '')}`);\n if (!hasOwnership && !localServicePathMatch && !hasCrossPackage && !helperOwned)\n rejectedReasons.push('missing direct ownership, exact local service path, or validated cross-package dependency evidence');\n return {\n score,\n hasOwnership: hasOwnership || localServicePathMatch || hasCrossPackage\n || handlerDependsOnModel || helperOwned,\n contradicted,\n acceptedReasons,\n rejectedReasons,\n };\n}\n\nfunction ownershipScore(\n signals: Record<string, boolean>,\n acceptedReasons: string[],\n): number {\n let score = 0;\n const values: Array<[keyof typeof signals, number, string]> = [\n ['modelIsApplicationRepo', 100, 'model package equals registration package'],\n ['modelIsHandlerRepo', 100, 'model package equals handler package'],\n ['localServicePathMatch', 80, 'registration package contains exact local service path'],\n ['appDependsOnModel', 70, 'registration package depends on model package'],\n ['appDependsOnHandler', 30, 'registration package depends on handler package'],\n ['handlerDependsOnModel', 20, 'handler package depends on model package'],\n ['helperOwned', 60, 'unique registered helper implementation for model-only operation'],\n ['importSource', 10, 'registration imports handler class'],\n ];\n for (const [key, amount, reason] of values) {\n if (!signals[key]) continue;\n score += amount;\n acceptedReasons.push(reason);\n }\n return score;\n}\n\nfunction candidateEvidence(candidate: ImplementationCandidate, rank: number): Record<string, unknown> {\n return {\n rank,\n rankKind: 'discovery_score',\n score: candidate.score,\n accepted: candidate.accepted,\n acceptedReasons: candidate.acceptedReasons,\n rejectedReasons: candidate.rejectedReasons,\n methodId: candidate.methodId,\n classId: candidate.classId,\n className: candidate.className,\n sourceFile: candidate.sourceFile,\n sourceLine: candidate.sourceLine,\n decoratorResolution: objectJson(candidate.decoratorResolutionJson),\n registration: registrationEvidence(candidate),\n registrations: candidate.registrations ?? [],\n registrationPairing: {\n strategy: registrationPairingStrategy(candidate),\n registrationId: candidate.registrationId,\n registrationHandlerClassId: candidate.registrationHandlerClassId,\n candidateHandlerClassId: candidate.classId,\n invariantStatus: validRegistrationPair(candidate) ? 'valid' : 'invalid',\n },\n applicationPackage: {\n id: candidate.applicationRepoId,\n name: candidate.applicationRepo,\n packageName: candidate.applicationPackage,\n },\n handlerPackage: {\n id: candidate.handlerRepoId,\n name: candidate.handlerRepo,\n packageName: candidate.handlerPackage,\n },\n modelPackage: {\n id: candidate.modelRepoId,\n name: candidate.modelRepo,\n packageName: candidate.modelPackage,\n },\n servicePath: candidate.servicePath,\n operationPath: candidate.operationPath,\n operationName: candidate.operationName,\n signals: {\n directOwnership: {\n modelIsApplicationRepo: flag(candidate.modelIsApplicationRepo),\n modelIsHandlerRepo: flag(candidate.modelIsHandlerRepo),\n },\n localServicePathMatch: flag(candidate.localServicePathMatch),\n applicationHasLocalServices: flag(candidate.applicationHasLocalServices),\n applicationHasLocalRegistrationForOperation:\n flag(candidate.applicationHasLocalRegistrationForOperation),\n appDependsOnModel: flag(candidate.appDependsOnModel),\n appDependsOnHandler: flag(candidate.appDependsOnHandler),\n handlerDependsOnModel: flag(candidate.handlerDependsOnModel),\n sameRepoRegistration: flag(candidate.sameRepoRegistration),\n },\n };\n}\n\nfunction selectedHandlerSource(candidate: ImplementationCandidate): {\n methodId: number;\n className?: string;\n methodName?: string;\n repositoryId?: number;\n repositoryName?: string;\n repositoryPackageName?: string;\n sourceFile?: string;\n sourceLine?: number;\n} {\n return {\n methodId: candidate.methodId,\n className: stringValue(candidate.className),\n methodName: stringValue(candidate.methodName),\n repositoryId: numberValue(candidate.handlerRepoId),\n repositoryName: stringValue(candidate.handlerRepo),\n repositoryPackageName: stringValue(candidate.handlerPackage),\n sourceFile: stringValue(candidate.sourceFile),\n sourceLine: numberValue(candidate.sourceLine),\n };\n}\n\nfunction implementationMethodSignal(\n row: Record<string, unknown>,\n operation: Record<string, unknown>,\n): { matches: boolean; contradicted: boolean; acceptedReasons: string[]; rejectedReasons: string[] } {\n const resolution = objectJson(row.decoratorResolutionJson) ?? {};\n if (resolution.handlerKind && resolution.handlerKind !== 'operation')\n return { matches: false, contradicted: true, acceptedReasons: [], rejectedReasons: ['non_operation_handler_kind'] };\n if (resolution.executable === false)\n return { matches: false, contradicted: true, acceptedReasons: [], rejectedReasons: ['handler_method_not_executable'] };\n const operationName = normalizedOperationName(String(\n operation.operationPath ?? operation.operationName ?? '',\n ));\n const decorator = normalizeDecoratorOperationSignal(\n stringValue(row.decoratorValue), stringValue(row.decoratorRawExpression), operationName,\n );\n if (decorator.status === 'resolved' && decorator.operationName === operationName)\n return { matches: true, contradicted: false, acceptedReasons: ['decorator targets operation'], rejectedReasons: [] };\n if (decorator.status === 'resolved')\n return { matches: false, contradicted: true, acceptedReasons: [], rejectedReasons: ['method_name_matches_but_decorator_targets_different_operation'] };\n return String(row.methodName ?? '') === operationName\n ? { matches: true, contradicted: false, acceptedReasons: ['method name fallback matched operation'], rejectedReasons: [] }\n : { matches: false, contradicted: false, acceptedReasons: [], rejectedReasons: ['method name does not match operation'] };\n}\n\nfunction objectJson(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== 'string' || value.length === 0) return undefined;\n try {\n const parsed = JSON.parse(value) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction upperFirst(value: string): string {\n return value ? `${value[0]?.toUpperCase() ?? ''}${value.slice(1)}` : value;\n}\n\nfunction flag(value: unknown): boolean {\n return Boolean(Number(value ?? 0));\n}\n\nfunction graphId(value: unknown): string {\n return String(value ?? '');\n}\n\nfunction normalizedOperation(value: string): string {\n return value.startsWith('/') ? value.slice(1) : value;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n","import type { Db } from '../db/connection.js';\nimport { extractPlaceholderKeys } from '../utils/001-placeholders.js';\nimport { canonicalImplementationEvidence } from './000-implementation-candidates.js';\nexport interface OperationTarget {\n operationId: number;\n repoName: string;\n serviceName: string;\n qualifiedName: string;\n servicePath: string;\n operationPath: string;\n operationName: string;\n sourceFile: string;\n sourceLine: number;\n repoId?: number;\n packageName?: string | null;\n score: number;\n reasons: string[];\n}\nexport interface OperationResolution {\n status: 'resolved' | 'ambiguous' | 'unresolved' | 'dynamic';\n target?: OperationTarget;\n candidates: OperationTarget[];\n reasons: string[];\n}\nfunction rows(\n db: Db,\n operationPath: string,\n workspaceId?: number,\n): OperationTarget[] {\n const names = operationLookupNames(operationPath);\n const result = db\n .prepare(\n `SELECT o.id operationId,r.id repoId,r.name repoName,r.package_name packageName,s.service_name serviceName,s.qualified_name qualifiedName,s.service_path servicePath,o.operation_path operationPath,o.operation_name operationName,o.source_file sourceFile,o.source_line sourceLine,0 score\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id\n WHERE (? IS NULL OR r.workspace_id=?) AND (o.operation_path IN (?,?) OR o.operation_name IN (?,?)) ORDER BY r.name,s.service_path,o.operation_name`,\n )\n .all(\n workspaceId,\n workspaceId,\n names.path,\n names.simplePath,\n names.name,\n names.simpleName,\n ) as Array<Omit<OperationTarget, 'reasons'>>;\n return result.map((row) => ({\n ...row,\n score: Number(row.score ?? 0),\n reasons: [],\n }));\n}\nfunction operationLookupNames(operationPath: string): { path: string; simplePath: string; name: string; simpleName: string } {\n const name = operationPath.replace(/^\\//, '');\n const simpleName = name.split('.').at(-1) ?? name;\n return { path: operationPath, simplePath: `/${simpleName}`, name, simpleName };\n}\nfunction operationMatches(candidate: OperationTarget, operationPath: string | undefined): boolean {\n if (!operationPath) return false;\n const names = operationLookupNames(operationPath);\n return candidate.operationPath === names.path || candidate.operationPath === names.simplePath || candidate.operationName === names.name || candidate.operationName === names.simpleName;\n}\nexport function resolveOperation(\n db: Db,\n signals: {\n servicePath?: string;\n alias?: string;\n destination?: string;\n operationPath?: string;\n serviceName?: string;\n repoId?: number;\n hasExplicitOverride?: boolean;\n isDynamic?: boolean;\n localServiceLookup?: string;\n },\n workspaceId?: number,\n): OperationResolution {\n const missing = [signals.servicePath, signals.alias, signals.destination, signals.operationPath]\n .flatMap(extractPlaceholderKeys);\n if (missing.length > 0)\n return {\n status: 'dynamic',\n candidates: signals.operationPath\n ? rows(db, signals.operationPath, workspaceId).map((candidate) => ({\n ...candidate,\n score: 0.2,\n reasons: ['operation_path_match'],\n }))\n : [],\n reasons: [...new Set(missing)].map((name) => `missing_variable:${name}`),\n };\n if (!signals.operationPath)\n return {\n status: 'unresolved',\n candidates: [],\n reasons: ['missing_operation_path'],\n };\n const allCandidates = rows(db, signals.operationPath, workspaceId).map((c) => ({\n ...c,\n score: 0.2,\n reasons: ['operation_path_match'],\n }));\n let candidates = allCandidates.filter((c) => matchesLocalRepo(db, c.operationId, signals.repoId));\n if (candidates.length === 0 && signals.repoId !== undefined && signals.serviceName) {\n candidates = implementationContextCandidates(db, allCandidates, signals.repoId, signals.serviceName);\n if (candidates.length === 0)\n return {\n status: 'unresolved',\n candidates: allCandidates.filter((c) => serviceMatches(c, signals.serviceName)),\n reasons: allCandidates.some((c) => serviceMatches(c, signals.serviceName)) ? ['local_service_candidate_without_caller_ownership'] : ['no_operation_candidates'],\n };\n }\n if (candidates.length === 0)\n return {\n status: 'unresolved',\n candidates: [],\n reasons: ['no_operation_candidates'],\n };\n const hasStrongSignal = Boolean(\n signals.servicePath ||\n signals.serviceName ||\n signals.alias ||\n signals.destination ||\n signals.hasExplicitOverride,\n );\n for (const c of candidates) {\n if (signals.servicePath && c.servicePath === signals.servicePath) {\n c.score += 0.75;\n c.reasons.push('exact_service_path');\n }\n if (signals.servicePath && c.servicePath !== signals.servicePath) {\n c.score -= 0.1;\n c.reasons.push('service_path_mismatch');\n }\n if (signals.serviceName) {\n const simple = signals.serviceName.split('.').at(-1) ?? signals.serviceName;\n if (c.qualifiedName === signals.serviceName) {\n c.score += 0.8;\n c.reasons.push('exact_local_qualified_service_name');\n } else if (c.serviceName === signals.serviceName || c.serviceName === simple) {\n c.score += 0.75;\n c.reasons.push('exact_local_simple_service_name');\n } else if (c.servicePath === signals.serviceName || c.servicePath === `/${signals.serviceName}` || c.servicePath === `/${simple}`) {\n c.score += 0.7;\n c.reasons.push('exact_local_service_path');\n } else if (c.servicePath.endsWith(`/${simple}`)) {\n c.score += candidates.filter((candidate) => candidate.servicePath.endsWith(`/${simple}`)).length === 1 ? 0.65 : 0.2;\n c.reasons.push('suffix_local_service_path');\n } else c.reasons.push('local_service_name_mismatch');\n }\n if (signals.hasExplicitOverride) {\n c.score += 0.2;\n c.reasons.push(signals.repoId !== undefined ? 'explicit_local_service_call' : 'explicit_dynamic_override');\n }\n if (signals.repoId !== undefined && candidates.length === 1 && signals.serviceName && c.reasons.includes('local_service_name_mismatch') && operationMatches(c, signals.operationPath)) {\n c.score = Math.max(c.score, 0.9);\n c.reasons.push('same_repo_unique_operation_path_with_lookup_mismatch');\n }\n }\n for (const c of candidates) c.score = Math.max(0, Math.min(1, c.score));\n candidates.sort(\n (a, b) => b.score - a.score || a.repoName.localeCompare(b.repoName),\n );\n const best = candidates[0];\n const second = candidates[1];\n if (signals.isDynamic && !signals.hasExplicitOverride && !signals.servicePath)\n return {\n status: 'dynamic',\n candidates,\n reasons: ['dynamic_target_without_override'],\n };\n if (!hasStrongSignal)\n return {\n status: candidates.length > 1 ? 'ambiguous' : 'unresolved',\n candidates,\n reasons: ['operation_path_only_has_no_strong_target_signal'],\n };\n if (\n best &&\n best.score >= 0.9 &&\n (best.servicePath === signals.servicePath || Boolean(signals.serviceName && (!best.reasons.includes('local_service_name_mismatch') || best.reasons.includes('same_repo_unique_operation_path_with_lookup_mismatch')))) &&\n operationMatches(best, signals.operationPath) &&\n (!second || best.score - second.score >= 0.25)\n )\n return {\n status: 'resolved',\n target: best,\n candidates,\n reasons: best.reasons,\n };\n return {\n status: candidates.length > 1 ? 'ambiguous' : 'unresolved',\n candidates,\n reasons: ['candidate_score_below_resolution_threshold'],\n };\n}\nfunction serviceMatches(candidate: OperationTarget, serviceName: string | undefined): boolean {\n if (!serviceName) return false;\n const simple = serviceName.split('.').at(-1) ?? serviceName;\n return candidate.qualifiedName === serviceName || candidate.serviceName === serviceName || candidate.serviceName === simple || candidate.servicePath === serviceName || candidate.servicePath === `/${serviceName}` || candidate.servicePath === `/${simple}` || candidate.servicePath.endsWith(`/${simple}`);\n}\nfunction implementationContextCandidates(db: Db, candidates: OperationTarget[], callerRepoId: number, serviceName: string): OperationTarget[] {\n const matching = candidates.filter((candidate) => serviceMatches(candidate, serviceName));\n const owned = matching.map((candidate) => ownershipReason(db, candidate, callerRepoId)).filter((item): item is { candidate: OperationTarget; reason: string } => Boolean(item));\n if (owned.length === 0) return [];\n const direct = owned.filter((item) => item.reason !== 'caller_depends_on_model_package');\n const chosen = direct.length > 0 ? direct : owned.length === 1 ? owned : [];\n return chosen.map((item) => ({ ...item.candidate, score: 0.95, reasons: [...item.candidate.reasons, 'implementation_context_caller_ownership', item.reason] }));\n}\nfunction ownershipReason(db: Db, candidate: OperationTarget, callerRepoId: number): { candidate: OperationTarget; reason: string } | undefined {\n const edge = db.prepare(\"SELECT status,evidence_json,to_id FROM graph_edges WHERE edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND from_kind='operation' AND from_id=? ORDER BY CASE status WHEN 'resolved' THEN 0 WHEN 'ambiguous' THEN 1 ELSE 2 END LIMIT 1\").get(String(candidate.operationId)) as { status?: string; evidence_json?: string; to_id?: string } | undefined;\n if (edge?.status === 'resolved') {\n const row = db.prepare('SELECT hc.repo_id repoId FROM handler_methods hm JOIN handler_classes hc ON hc.id=hm.handler_class_id WHERE hm.id=?').get(edge.to_id) as { repoId?: number } | undefined;\n if (row?.repoId === callerRepoId) return { candidate, reason: 'resolved_implementation_handler_repo_matches_caller' };\n }\n if (edge?.evidence_json) {\n const stored = parsedRecord(edge.evidence_json);\n const evidence = canonicalImplementationEvidence(db, candidate.operationId) ?? stored;\n const hit = implementationEvidenceCandidates(evidence).find((item) =>\n item.accepted && (item.handlerRepoId === callerRepoId\n || item.applicationRepoId === callerRepoId));\n if (hit) return { candidate, reason: edge.status === 'ambiguous' ? 'ambiguous_implementation_candidate_repo_matches_caller' : 'registration_package_matches_caller' };\n }\n const dep = db.prepare(\"SELECT 1 FROM graph_edges WHERE edge_type='REPO_IMPORTS_HELPER_PACKAGE' AND status='resolved' AND from_kind='repo' AND from_id=? AND to_id=?\").get(String(callerRepoId), String(candidate.repoId));\n if (dep) return { candidate, reason: 'caller_depends_on_model_package' };\n return undefined;\n}\n\nfunction implementationEvidenceCandidates(\n evidence: Record<string, unknown>,\n): Array<{ accepted: boolean; handlerRepoId?: number; applicationRepoId?: number }> {\n const candidates = evidence.candidates;\n if (!Array.isArray(candidates)) return [];\n return candidates.flatMap((candidate) => {\n if (!isRecord(candidate)) return [];\n const row = candidate;\n const handler = recordValue(row.handlerPackage);\n const application = recordValue(row.applicationPackage);\n return [{\n accepted: row.accepted === true,\n handlerRepoId: numberValue(handler.id),\n applicationRepoId: numberValue(application.id),\n }];\n });\n}\n\nfunction recordValue(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\n}\n\nfunction parsedRecord(value: string): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(value);\n return recordValue(parsed);\n } catch {\n return {};\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 numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction matchesLocalRepo(db: Db, operationId: number, repoId: number | undefined): boolean {\n if (repoId === undefined) return true;\n const row = db.prepare('SELECT s.repo_id repoId FROM cds_operations o JOIN cds_services s ON s.id=o.service_id WHERE o.id=?').get(operationId) as { repoId?: number } | undefined;\n return row?.repoId === repoId;\n}\nexport function findOperation(\n db: Db,\n servicePath: string | undefined,\n operationPath: string | undefined,\n workspaceId?: number,\n): OperationTarget | undefined {\n return resolveOperation(db, { servicePath, operationPath }, workspaceId)\n .target;\n}\n","import type { Db } from '../db/connection.js';\nimport { projectBounded } from '../utils/000-bounded-projection.js';\n\ninterface RepoDependencyRow {\n id: number;\n name: string;\n package_name: string | null;\n dependencies_json: string;\n}\nexport interface DependencyLinkSummary {\n edgeCount: number;\n resolvedCount: number;\n ambiguousCount: number;\n}\ninterface CandidateResult {\n candidates: RepoDependencyRow[];\n strategy: 'exact_package_name' | 'normalized_directory';\n}\nfunction normalizeName(value: string): string {\n return value.toLowerCase().replace(/^@[^/]+\\//, '').replace(/[^a-z0-9]+/g, '');\n}\nfunction candidatesForDependency(repos: RepoDependencyRow[], dep: string, sourceId: number): CandidateResult {\n const exact = repos.filter((repo) => repo.id !== sourceId && repo.package_name === dep);\n if (exact.length > 0) return { candidates: exact, strategy: 'exact_package_name' };\n const normalized = normalizeName(dep);\n return { candidates: repos.filter((repo) => repo.id !== sourceId && normalizeName(repo.name) === normalized), strategy: 'normalized_directory' };\n}\nexport function linkHelperPackages(db: Db, workspaceId: number, generation: number): DependencyLinkSummary {\n const repos = db.prepare('SELECT id,name,package_name,dependencies_json FROM repositories WHERE workspace_id=?').all(workspaceId) as unknown as RepoDependencyRow[];\n const summary: DependencyLinkSummary = { edgeCount: 0, resolvedCount: 0, ambiguousCount: 0 };\n for (const repo of repos) {\n const deps = JSON.parse(repo.dependencies_json) as Record<string, string>;\n for (const dep of Object.keys(deps)) {\n const result = candidatesForDependency(repos, dep, repo.id);\n if (result.candidates.length === 0) continue;\n const status = result.candidates.length === 1 ? 'resolved' : 'ambiguous';\n const helper = status === 'resolved' ? result.candidates[0] : undefined;\n const projection = projectBounded(result.candidates, (left, right) =>\n left.name.localeCompare(right.name)\n || String(left.package_name ?? '').localeCompare(String(right.package_name ?? ''))\n || left.id - right.id);\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,unresolved_reason,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)').run(\n workspaceId,\n 'REPO_IMPORTS_HELPER_PACKAGE',\n status,\n 'repo',\n String(repo.id),\n helper ? 'repo' : 'repo_candidates',\n helper ? String(helper.id) : projection.items.map((candidate) => candidate.id).join(','),\n helper ? 1 : 0.5,\n JSON.stringify({\n dependency: dep,\n candidates: projection.items.map((candidate) => ({\n id: candidate.id,\n name: candidate.name,\n packageName: candidate.package_name,\n })),\n candidateCount: projection.totalCount,\n shownCandidateCount: projection.shownCount,\n omittedCandidateCount: projection.omittedCount,\n match: result.strategy,\n }),\n 0,\n helper ? null : 'Ambiguous dependency package candidates',\n generation,\n );\n summary.edgeCount += 1;\n if (helper) summary.resolvedCount += 1;\n else summary.ambiguousCount += 1;\n }\n }\n return summary;\n}\n","import type {\n NormalizedODataOperationPath,\n ODataPathIntent,\n} from './odata-path-normalizer.js';\nimport {\n boundCandidateLikeEvidence,\n projectBounded,\n type BoundedProjection,\n} from '../utils/000-bounded-projection.js';\nimport { extractPlaceholderKeys } from '../utils/001-placeholders.js';\n\nexport interface LinkedOperationResolution {\n target?: {\n repoName?: string;\n servicePath?: string;\n operationPath?: string;\n operationName?: string;\n };\n candidates: unknown[];\n status: string;\n reasons: string[];\n}\n\nexport function linkedCallEvidence(\n call: Record<string, unknown>,\n resolution: LinkedOperationResolution,\n servicePath: string | undefined,\n operationPath: string | undefined,\n destination: string | undefined,\n normalized: NormalizedODataOperationPath | undefined,\n intent: ODataPathIntent | undefined,\n): Record<string, unknown> {\n const candidates = boundedCallCandidates(resolution.candidates);\n return {\n ...callLocationEvidence(call),\n ...selectedBindingEvidence(call),\n ...routingEvidence(call, servicePath, operationPath, destination, normalized, intent),\n ...candidateEvidence(candidates, resolution),\n outboundEvidence: boundCandidateLikeEvidence(objectJson(call.evidence_json) ?? {}),\n analysisCompleteness: call.unresolved_reason ? 'partial' : 'complete',\n parserWarning: call.unresolved_reason\n ? { code: 'parser_warning', message: call.unresolved_reason }\n : undefined,\n };\n}\n\nexport function ambiguousPathCandidates(\n pathAnalysis: Record<string, unknown>,\n): BoundedProjection<string> {\n const values = Array.isArray(pathAnalysis.candidateRawPaths)\n ? pathAnalysis.candidateRawPaths.filter((value): value is string =>\n typeof value === 'string')\n : [];\n return projectBounded(values, (left, right) => left.localeCompare(right));\n}\n\nexport function objectJson(value: unknown): Record<string, unknown> | undefined {\n const parsed = parseJson(value);\n return isRecord(parsed) ? parsed : undefined;\n}\n\nexport function objectValue(value: unknown): Record<string, unknown> | undefined {\n return isRecord(value) ? value : undefined;\n}\n\nfunction callLocationEvidence(call: Record<string, unknown>): Record<string, unknown> {\n return {\n sourceFile: call.source_file,\n sourceLine: call.source_line,\n file: call.source_file,\n line: call.source_line,\n callId: call.id,\n repo: call.repoName,\n };\n}\n\nfunction selectedBindingEvidence(call: Record<string, unknown>): Record<string, unknown> {\n if (!call.selectedBindingId) return {};\n return {\n selectedBindingId: call.selectedBindingId,\n selectedBinding: {\n bindingId: call.selectedBindingId,\n alias: call.alias,\n aliasExpr: call.aliasExpr,\n destinationExpr: call.destinationExpr,\n servicePathExpr: call.servicePathExpr,\n sourceFile: call.bindingSourceFile,\n sourceLine: call.bindingSourceLine,\n helperChain: parseJson(call.helperChainJson),\n },\n };\n}\n\nfunction routingEvidence(\n call: Record<string, unknown>,\n servicePath: string | undefined,\n operationPath: string | undefined,\n destination: string | undefined,\n normalized: NormalizedODataOperationPath | undefined,\n intent: ODataPathIntent | undefined,\n): Record<string, unknown> {\n const routingPlaceholderKeys = placeholderKeys([\n servicePath,\n destination,\n stringValue(call.aliasExpr),\n stringValue(call.alias),\n ]);\n return {\n serviceAlias: call.alias,\n serviceAliasExpr: call.aliasExpr,\n destination,\n servicePath,\n operationPath,\n rawOperationPath: normalized?.wasInvocation\n ? normalized.rawOperationPath\n : intent?.rawPath,\n normalizedOperationPath: normalized?.wasInvocation\n ? normalized.normalizedOperationPath\n : undefined,\n invocationArguments: normalized?.wasInvocation\n ? normalized.invocationArguments\n : undefined,\n invocationArgumentPlaceholderKeys: normalized?.invocationArgumentPlaceholderKeys.length\n ? normalized.invocationArgumentPlaceholderKeys\n : undefined,\n routingPlaceholderKeys: routingPlaceholderKeys.length\n ? routingPlaceholderKeys\n : undefined,\n odataOperationNormalizationReason: normalized?.normalizationReason,\n odataOperationNormalizationRejectedReason: normalized?.normalizationRejectedReason,\n localServiceName: call.local_service_name,\n localServiceLookup: call.local_service_lookup,\n aliasChain: parseJson(call.alias_chain_json),\n transport: call.call_type === 'local_service_call' ? 'local' : undefined,\n helperChain: parseJson(call.helperChainJson),\n odataPathIntent: intent,\n queryStringPresent: intent?.hasQueryString || undefined,\n queryPlaceholderKeys: intent?.placeholderKeys.length\n ? intent.placeholderKeys\n : undefined,\n bindingHasDynamicExpression: Boolean(Number(call.isDynamic ?? 0)) || undefined,\n };\n}\n\nfunction candidateEvidence(\n candidates: ReturnType<typeof boundedCallCandidates>,\n resolution: LinkedOperationResolution,\n): Record<string, unknown> {\n return {\n targetRepo: resolution.target?.repoName,\n targetServicePath: resolution.target?.servicePath,\n targetOperationPath: resolution.target?.operationPath,\n targetOperation: resolution.target?.operationName,\n candidates: candidates.items,\n candidateScores: compactCandidateScores(candidates.items),\n candidateCount: candidates.totalCount,\n shownCandidateCount: candidates.shownCount,\n omittedCandidateCount: candidates.omittedCount,\n candidateScoreCount: candidates.totalCount,\n shownCandidateScoreCount: candidates.shownCount,\n omittedCandidateScoreCount: candidates.omittedCount,\n resolutionStatus: resolution.status,\n resolutionReasons: resolution.reasons,\n };\n}\n\nfunction boundedCallCandidates(\n candidates: unknown[],\n): BoundedProjection<Record<string, unknown>> {\n const rows = candidates.flatMap((candidate): Array<Record<string, unknown>> => {\n const row = objectValue(candidate);\n return row ? [row] : [];\n });\n return projectBounded(rows, compareCallCandidate);\n}\n\nfunction compareCallCandidate(\n left: Record<string, unknown>,\n right: Record<string, unknown>,\n): number {\n return Number(right.score ?? 0) - Number(left.score ?? 0)\n || String(left.repoName ?? '').localeCompare(String(right.repoName ?? ''))\n || String(left.servicePath ?? '').localeCompare(String(right.servicePath ?? ''))\n || String(left.operationPath ?? '').localeCompare(String(right.operationPath ?? ''))\n || Number(left.operationId ?? 0) - Number(right.operationId ?? 0);\n}\n\nfunction compactCandidateScores(\n candidates: Array<Record<string, unknown>>,\n): Array<Record<string, unknown>> {\n return candidates.map((candidate) => ({\n repo: candidate.repoName,\n servicePath: candidate.servicePath,\n operationPath: candidate.operationPath,\n score: candidate.score,\n reasons: Array.isArray(candidate.reasons)\n ? candidate.reasons.filter((reason): reason is string =>\n typeof reason === 'string')\n : ['operation_path_match'],\n }));\n}\n\nfunction placeholderKeys(values: Array<string | undefined>): string[] {\n const keys = values.flatMap(extractPlaceholderKeys);\n return [...new Set(keys)].sort();\n}\n\nfunction parseJson(value: unknown): unknown {\n if (!value) return undefined;\n try {\n const parsed: unknown = JSON.parse(String(value));\n return parsed;\n } catch {\n return undefined;\n }\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n","import type { Db } from '../db/connection.js';\n\nexport interface PackageSymbolLinkSummary {\n resolved: number;\n ambiguous: number;\n unresolved: number;\n}\n\ninterface RepoExports {\n publicName: Map<string, number[]>;\n qualified: Map<string, number[]>;\n fileById: Map<number, string>;\n}\n\ninterface PackageCallRow {\n id: number;\n callerRepoId: number;\n calleeExpression: string;\n importSource: string;\n evidence: Record<string, unknown>;\n}\n\ninterface PackageCallResolution {\n id: number | null;\n status: 'resolved' | 'ambiguous' | 'unresolved';\n reason: string | null;\n strategy: 'package_import_workspace_resolved' | 'package_import_ambiguous' | 'package_import_unresolved';\n candidateCount: number;\n resolvedModulePath?: string;\n}\n\nconst unresolvedRepositoryReason = 'Package import target resolution requires a post-publication workspace pass';\nconst unresolvedSymbolReason = 'Sibling package indexed but no matching exported symbol; the target may be a re-export, barrel, type-only export, or unindexed Receiver.member';\nconst ambiguousSymbolReason = 'Multiple exported sibling-package symbol targets matched exactly';\nconst stripExt = (value: string): string => value.replace(/\\.(ts|tsx|js|jsx|cds)$/, '');\n\nfunction push(map: Map<string, number[]>, key: string, id: number): void {\n const existing = map.get(key);\n if (existing) existing.push(id);\n else map.set(key, [id]);\n}\n\nfunction nullableString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction evidenceObject(value: unknown): Record<string, unknown> {\n if (typeof value !== 'string' || value.length === 0) return {};\n try {\n const parsed = JSON.parse(value) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : {};\n } catch {\n return {};\n }\n}\n\nfunction repoByPackageName(db: Db, workspaceId: number): Map<string, number | null> {\n const result = new Map<string, number | null>();\n const rows = db.prepare(`SELECT id,package_name packageName FROM repositories\n WHERE workspace_id=? AND package_name IS NOT NULL ORDER BY package_name,id`).all(workspaceId);\n for (const row of rows) {\n const packageName = nullableString(row.packageName);\n if (!packageName || typeof row.id !== 'number') continue;\n result.set(packageName, result.has(packageName) ? null : row.id);\n }\n return result;\n}\n\nfunction packagePrefix(importSource: string): string {\n const parts = importSource.split('/');\n if (importSource.startsWith('@')) return parts.length >= 2 ? parts.slice(0, 2).join('/') : importSource;\n return parts[0] ?? importSource;\n}\n\nfunction packageRepoId(repos: Map<string, number | null>, importSource: string): number | null {\n const packageName = repos.has(importSource) ? importSource : packagePrefix(importSource);\n return repos.get(packageName) ?? null;\n}\n\nfunction emptyRepoExports(): RepoExports {\n return { publicName: new Map(), qualified: new Map(), fileById: new Map() };\n}\n\nfunction exportsByRepo(db: Db, workspaceId: number): Map<number, RepoExports> {\n const result = new Map<number, RepoExports>();\n const rows = db.prepare(`SELECT s.id,s.repo_id repoId,s.name,s.exported_name exportedName,\n s.qualified_name qualifiedName,s.source_file sourceFile\n FROM symbols s JOIN repositories r ON r.id=s.repo_id\n WHERE r.workspace_id=? AND s.exported=1 ORDER BY s.repo_id,s.id`).all(workspaceId);\n for (const row of rows) addExportRow(result, row);\n return result;\n}\n\nfunction addExportRow(result: Map<number, RepoExports>, row: Record<string, unknown>): void {\n if (typeof row.id !== 'number' || typeof row.repoId !== 'number') return;\n const exports = result.get(row.repoId) ?? emptyRepoExports();\n result.set(row.repoId, exports);\n const publicName = nullableString(row.exportedName) ?? nullableString(row.name);\n const qualifiedName = nullableString(row.qualifiedName);\n const sourceFile = nullableString(row.sourceFile);\n if (publicName) push(exports.publicName, publicName, row.id);\n if (qualifiedName) push(exports.qualified, qualifiedName, row.id);\n if (sourceFile) exports.fileById.set(row.id, stripExt(sourceFile));\n}\n\nfunction packageCallRows(db: Db, workspaceId: number): PackageCallRow[] {\n const rows = db.prepare(`SELECT sc.id,sc.repo_id callerRepoId,\n sc.callee_expression calleeExpression,sc.import_source importSource,\n sc.evidence_json evidenceJson\n FROM symbol_calls sc JOIN repositories r ON r.id=sc.repo_id\n WHERE r.workspace_id=? AND sc.import_source IS NOT NULL\n AND sc.import_source NOT LIKE './%' AND sc.import_source NOT LIKE '../%'\n AND json_extract(sc.evidence_json,'$.relation')='package_import'\n AND json_extract(sc.evidence_json,'$.candidateStrategy') IN\n ('package_import_unresolved','package_import_workspace_resolved','package_import_ambiguous')\n ORDER BY sc.id`).all(workspaceId);\n return rows.flatMap((row) => packageCallRow(row));\n}\n\nfunction packageCallRow(row: Record<string, unknown>): PackageCallRow[] {\n const calleeExpression = nullableString(row.calleeExpression);\n const importSource = nullableString(row.importSource);\n if (typeof row.id !== 'number' || typeof row.callerRepoId !== 'number'\n || !calleeExpression || !importSource) return [];\n return [{\n id: row.id,\n callerRepoId: row.callerRepoId,\n calleeExpression,\n importSource,\n evidence: evidenceObject(row.evidenceJson),\n }];\n}\n\nfunction candidatesForCall(call: PackageCallRow, exports: RepoExports | undefined): number[] {\n if (!exports) return [];\n const dotCount = [...call.calleeExpression].filter((character) => character === '.').length;\n if (dotCount === 0) {\n const targetName = nullableString(call.evidence.targetName);\n return targetName ? exports.publicName.get(targetName) ?? [] : [];\n }\n return dotCount === 1 ? exports.qualified.get(call.calleeExpression) ?? [] : [];\n}\n\nfunction resolvePackageCall(\n call: PackageCallRow,\n repos: Map<string, number | null>,\n exports: Map<number, RepoExports>,\n): PackageCallResolution {\n const targetRepoId = packageRepoId(repos, call.importSource);\n if (targetRepoId === null || targetRepoId === call.callerRepoId) return unresolvedResolution(unresolvedRepositoryReason);\n const repoExports = exports.get(targetRepoId);\n const candidates = candidatesForCall(call, repoExports);\n const [id] = candidates;\n if (candidates.length === 1 && id !== undefined) {\n return {\n id, status: 'resolved', reason: null, strategy: 'package_import_workspace_resolved',\n candidateCount: 1, resolvedModulePath: repoExports?.fileById.get(id),\n };\n }\n if (candidates.length > 1) {\n return { id: null, status: 'ambiguous', reason: ambiguousSymbolReason, strategy: 'package_import_ambiguous', candidateCount: candidates.length };\n }\n return unresolvedResolution(unresolvedSymbolReason);\n}\n\nfunction unresolvedResolution(reason: string): PackageCallResolution {\n return { id: null, status: 'unresolved', reason, strategy: 'package_import_unresolved', candidateCount: 0 };\n}\n\nfunction resolutionEvidence(call: PackageCallRow, resolution: PackageCallResolution): string {\n const evidence: Record<string, unknown> = {\n ...call.evidence,\n candidateStrategy: resolution.strategy,\n candidateCount: resolution.candidateCount,\n };\n if (resolution.resolvedModulePath) evidence.resolvedModulePath = resolution.resolvedModulePath;\n else delete evidence.resolvedModulePath;\n return JSON.stringify(evidence);\n}\n\nexport function linkPackageImportSymbolCalls(db: Db, workspaceId: number): PackageSymbolLinkSummary {\n const repos = repoByPackageName(db, workspaceId);\n const exports = exportsByRepo(db, workspaceId);\n const update = db.prepare(`UPDATE symbol_calls SET callee_symbol_id=?,status=?,\n unresolved_reason=?,evidence_json=? WHERE id=?`);\n const summary: PackageSymbolLinkSummary = { resolved: 0, ambiguous: 0, unresolved: 0 };\n for (const call of packageCallRows(db, workspaceId)) {\n const resolution = resolvePackageCall(call, repos, exports);\n update.run(resolution.id, resolution.status, resolution.reason, resolutionEvidence(call, resolution), call.id);\n summary[resolution.status] += 1;\n }\n return summary;\n}\n","import type { Db } from '../db/connection.js';\n\nexport interface SubscriptionHandlerLinkSummary {\n edgeCount: number;\n resolvedCount: number;\n ambiguousCount: number;\n unresolvedCount: number;\n missingAssociationCount: number;\n}\n\ninterface SubscriptionRow {\n id: number;\n workspaceId: number;\n repoId: number;\n repoName: string;\n sourceSymbolId?: number | null;\n eventName: string;\n sourceFile: string;\n sourceLine: number;\n startOffset?: number | null;\n endOffset?: number | null;\n confidence: number;\n}\n\ninterface HandlerCallRow {\n id: number;\n callerSymbolId: number;\n calleeSymbolId?: number | null;\n status: string;\n unresolvedReason?: string | null;\n confidence: number;\n sourceLine: number;\n factOrigin?: string | null;\n wrapperFunction?: string | null;\n strategy?: string | null;\n candidateCount?: number | null;\n targetSourceFile?: string | null;\n targetSourceLine?: number | null;\n targetWorkspaceId?: number | null;\n}\n\ninterface HandlerAssociation {\n status: 'resolved' | 'ambiguous' | 'unresolved';\n toKind: 'symbol' | 'symbol_reference' | 'subscription_handler';\n toId: string;\n reasonCode?: string;\n call?: HandlerCallRow;\n matchCount: number;\n missing: boolean;\n factOrigin?: string;\n symbolCallResolutionStatus?: string;\n}\n\nconst symbolCallReasonLimit = 512;\n\nfunction subscriptionRows(db: Db, workspaceId: number): SubscriptionRow[] {\n return db.prepare(`SELECT c.id,r.workspace_id workspaceId,c.repo_id repoId,r.name repoName,\n c.source_symbol_id sourceSymbolId,c.event_name_expr eventName,\n c.source_file sourceFile,c.source_line sourceLine,\n c.call_site_start_offset startOffset,c.call_site_end_offset endOffset,\n c.confidence\n FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id\n WHERE r.workspace_id=? AND c.call_type='async_subscribe'\n ORDER BY r.name COLLATE BINARY,r.id,c.source_file COLLATE BINARY,\n c.call_site_start_offset,c.call_site_end_offset,c.id`).all(\n workspaceId,\n ) as unknown as SubscriptionRow[];\n}\n\nfunction roleSiteRows(db: Db, subscription: SubscriptionRow): HandlerCallRow[] {\n if (typeof subscription.startOffset !== 'number'\n || typeof subscription.endOffset !== 'number') return [];\n return db.prepare(`SELECT sc.id,sc.caller_symbol_id callerSymbolId,\n sc.callee_symbol_id calleeSymbolId,sc.status,\n sc.unresolved_reason unresolvedReason,sc.confidence,sc.source_line sourceLine,\n json_extract(sc.evidence_json,'$.factOrigin') factOrigin,\n json_extract(sc.evidence_json,'$.wrapperFunction') wrapperFunction,\n json_extract(sc.evidence_json,'$.candidateStrategy') strategy,\n json_extract(sc.evidence_json,'$.candidateCount') candidateCount,\n target.source_file targetSourceFile,target.start_line targetSourceLine,\n target_repo.workspace_id targetWorkspaceId\n FROM symbol_calls sc LEFT JOIN symbols target ON target.id=sc.callee_symbol_id\n LEFT JOIN repositories target_repo ON target_repo.id=target.repo_id\n WHERE sc.repo_id=? AND sc.source_file=?\n AND sc.call_site_start_offset=? AND sc.call_site_end_offset=?\n AND sc.call_role='event_subscribe_handler'\n ORDER BY sc.id`).all(\n subscription.repoId,\n subscription.sourceFile,\n subscription.startOffset,\n subscription.endOffset,\n ) as unknown as HandlerCallRow[];\n}\n\nfunction invalidSpan(subscription: SubscriptionRow): boolean {\n return typeof subscription.startOffset !== 'number'\n || typeof subscription.endOffset !== 'number'\n || subscription.startOffset < 0\n || subscription.endOffset <= subscription.startOffset;\n}\n\nfunction associationFor(\n subscription: SubscriptionRow,\n matches: HandlerCallRow[],\n): HandlerAssociation {\n if (invalidSpan(subscription)) return missingAssociation(\n subscription.id, matches.length, 'subscription_call_span_missing',\n );\n if (matches.length === 0) return missingAssociation(\n subscription.id, 0, 'subscription_handler_role_site_missing',\n );\n if (matches.length > 1) return ambiguousRoleSiteAssociation(\n subscription.id, matches,\n );\n const call = matches[0];\n return call\n ? singleCallAssociation(subscription, call)\n : missingAssociation(\n subscription.id, 0, 'subscription_handler_role_site_missing',\n );\n}\n\nfunction ambiguousRoleSiteAssociation(\n subscriptionId: number,\n matches: HandlerCallRow[],\n): HandlerAssociation {\n return {\n status: 'ambiguous', toKind: 'subscription_handler',\n toId: String(subscriptionId), reasonCode: 'multiple_handler_role_site_matches',\n matchCount: matches.length, missing: false,\n factOrigin: agreedOrMixed(matches.map((match) => match.factOrigin)),\n symbolCallResolutionStatus: agreedOrMixed(\n matches.map((match) => match.status),\n ),\n };\n}\n\nfunction singleCallAssociation(\n subscription: SubscriptionRow,\n call: HandlerCallRow,\n): HandlerAssociation {\n const mismatch = associationMismatch(subscription, call);\n if (mismatch) return missingAssociation(subscription.id, 1, mismatch, call);\n return handlerReferenceAssociation(call);\n}\n\nfunction associationMismatch(\n subscription: SubscriptionRow,\n call: HandlerCallRow,\n): string | undefined {\n if (subscription.sourceSymbolId != null\n && call.callerSymbolId !== subscription.sourceSymbolId)\n return 'subscription_handler_caller_mismatch';\n if (call.sourceLine !== subscription.sourceLine)\n return 'subscription_handler_source_line_mismatch';\n if (call.targetWorkspaceId != null\n && call.targetWorkspaceId !== subscription.workspaceId)\n return 'subscription_handler_target_workspace_mismatch';\n return undefined;\n}\n\nfunction handlerReferenceAssociation(call: HandlerCallRow): HandlerAssociation {\n if (call.status === 'resolved' && typeof call.calleeSymbolId === 'number')\n return { status: 'resolved', toKind: 'symbol', toId: String(call.calleeSymbolId), call, matchCount: 1, missing: false };\n if (call.status === 'ambiguous') return {\n status: 'ambiguous', toKind: 'symbol_reference', toId: String(call.id),\n reasonCode: 'subscription_handler_reference_ambiguous', call,\n matchCount: 1, missing: false,\n };\n return {\n status: 'unresolved', toKind: 'symbol_reference', toId: String(call.id),\n reasonCode: call.status === 'resolved'\n ? 'resolved_handler_symbol_missing'\n : 'subscription_handler_reference_unresolved',\n call, matchCount: 1, missing: false,\n };\n}\n\nfunction agreedOrMixed(\n values: Array<string | null | undefined>,\n): string | undefined {\n const distinct = new Set(values.map((value) => value ?? 'missing'));\n if (distinct.size > 1) return 'mixed';\n const value = distinct.values().next().value;\n return value === 'missing' ? undefined : value;\n}\n\nfunction missingAssociation(\n subscriptionId: number,\n matchCount: number,\n reasonCode: string,\n call?: HandlerCallRow,\n): HandlerAssociation {\n return {\n status: 'unresolved', toKind: 'subscription_handler',\n toId: String(subscriptionId), reasonCode, call, matchCount, missing: true,\n };\n}\n\nfunction evidenceFor(\n subscription: SubscriptionRow,\n association: HandlerAssociation,\n): Record<string, unknown> {\n const call: Partial<HandlerCallRow> = association.call ?? {};\n const symbolCallReason = boundedSymbolCallReason(call.unresolvedReason);\n return {\n eventName: subscription.eventName,\n associationBasis: 'exact_subscription_call_span',\n dispatchScope: 'workspace_event_name_only',\n subscribeCallId: subscription.id,\n symbolCallId: call.id,\n roleSiteMatchCount: association.matchCount,\n callRole: association.matchCount > 0 ? 'event_subscribe_handler' : undefined,\n factOrigin: association.factOrigin ?? call.factOrigin,\n repositoryId: subscription.repoId,\n repositoryName: subscription.repoName,\n sourceFile: subscription.sourceFile,\n sourceLine: subscription.sourceLine,\n callSiteStartOffset: subscription.startOffset,\n callSiteEndOffset: subscription.endOffset,\n handlerSymbolId: call.calleeSymbolId,\n handlerSourceFile: call.targetSourceFile,\n handlerSourceLine: call.targetSourceLine,\n wrapperFunction: call.wrapperFunction,\n associationStatus: association.status,\n symbolCallResolutionStatus:\n association.symbolCallResolutionStatus ?? call.status,\n resolutionStatus: association.status,\n resolutionStrategy: call.strategy,\n candidateCount: call.candidateCount,\n reasonCode: association.reasonCode,\n ...symbolCallReason,\n };\n}\n\nfunction boundedSymbolCallReason(\n reason: string | null | undefined,\n): Record<string, unknown> {\n if (!reason) return {};\n const value = reason.slice(0, symbolCallReasonLimit);\n return {\n symbolCallUnresolvedReason: value,\n omittedSymbolCallUnresolvedReasonCharacterCount:\n Math.max(0, reason.length - value.length),\n };\n}\n\nfunction insertAssociationEdge(\n db: Db,\n workspaceId: number,\n generation: number,\n subscription: SubscriptionRow,\n association: HandlerAssociation,\n): void {\n db.prepare(`INSERT INTO graph_edges(\n workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,\n confidence,evidence_json,is_dynamic,unresolved_reason,generation\n ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`).run(\n workspaceId,\n 'EVENT_SUBSCRIPTION_HANDLED_BY',\n association.status,\n 'event',\n subscription.eventName,\n association.toKind,\n association.toId,\n association.call?.confidence ?? subscription.confidence,\n JSON.stringify(evidenceFor(subscription, association)),\n 0,\n association.reasonCode ?? association.call?.unresolvedReason ?? null,\n generation,\n );\n}\n\nexport function linkEventSubscriptionHandlers(\n db: Db,\n workspaceId: number,\n generation: number,\n): SubscriptionHandlerLinkSummary {\n const summary: SubscriptionHandlerLinkSummary = {\n edgeCount: 0,\n resolvedCount: 0,\n ambiguousCount: 0,\n unresolvedCount: 0,\n missingAssociationCount: 0,\n };\n for (const subscription of subscriptionRows(db, workspaceId)) {\n const association = associationFor(\n subscription, roleSiteRows(db, subscription),\n );\n insertAssociationEdge(\n db, workspaceId, generation, subscription, association,\n );\n summary.edgeCount += 1;\n summary.resolvedCount += association.status === 'resolved' ? 1 : 0;\n summary.ambiguousCount += association.status === 'ambiguous' ? 1 : 0;\n summary.unresolvedCount += association.status === 'unresolved' ? 1 : 0;\n summary.missingAssociationCount += association.missing ? 1 : 0;\n }\n return summary;\n}\n","export const schemaTablesSql = `\nCREATE TABLE IF NOT EXISTS workspaces (id INTEGER PRIMARY KEY, root_path TEXT UNIQUE NOT NULL, db_path TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);\nCREATE TABLE IF NOT EXISTS repositories (id INTEGER PRIMARY KEY, workspace_id INTEGER NOT NULL, name TEXT NOT NULL, absolute_path TEXT NOT NULL, relative_path TEXT NOT NULL, package_name TEXT, package_version TEXT, dependencies_json TEXT DEFAULT '{}', kind TEXT NOT NULL, is_git_repo INTEGER NOT NULL, last_indexed_at TEXT, index_status TEXT DEFAULT 'pending', error_count INTEGER DEFAULT 0, fingerprint TEXT, fact_generation INTEGER NOT NULL DEFAULT 0, graph_generation INTEGER NOT NULL DEFAULT 0, graph_stale_reason TEXT, graph_stale_at TEXT, fact_analyzer_version TEXT, UNIQUE(workspace_id, absolute_path), FOREIGN KEY(workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE);\nCREATE TABLE IF NOT EXISTS files (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, relative_path TEXT NOT NULL, extension TEXT NOT NULL, sha256 TEXT NOT NULL, size_bytes INTEGER NOT NULL, last_indexed_at TEXT NOT NULL, UNIQUE(repo_id, relative_path), FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE);\nCREATE TABLE IF NOT EXISTS cds_requires (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, alias TEXT NOT NULL, kind TEXT, model TEXT, destination TEXT, service_path TEXT, request_timeout INTEGER, raw_json TEXT NOT NULL, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE);\nCREATE TABLE IF NOT EXISTS cds_services (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, namespace TEXT, service_name TEXT NOT NULL, qualified_name TEXT NOT NULL, service_path TEXT NOT NULL, is_extend INTEGER NOT NULL, source_file TEXT NOT NULL, source_line INTEGER NOT NULL, extension_local_ref TEXT, extension_imported_symbol TEXT, extension_local_alias TEXT, extension_module_specifier TEXT, extension_import_kind TEXT, extension_base_service_id INTEGER, extension_base_status TEXT, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE, FOREIGN KEY(extension_base_service_id) REFERENCES cds_services(id) ON DELETE SET NULL);\nCREATE TABLE IF NOT EXISTS cds_operations (id INTEGER PRIMARY KEY, service_id INTEGER NOT NULL, operation_type TEXT NOT NULL, operation_name TEXT NOT NULL, operation_path TEXT NOT NULL, params_json TEXT NOT NULL, return_type TEXT, source_file TEXT NOT NULL, source_line INTEGER NOT NULL, provenance TEXT NOT NULL DEFAULT 'direct', base_operation_id INTEGER, FOREIGN KEY(service_id) REFERENCES cds_services(id) ON DELETE CASCADE, FOREIGN KEY(base_operation_id) REFERENCES cds_operations(id) ON DELETE SET NULL);\nCREATE TABLE IF NOT EXISTS symbols (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, file_id INTEGER, kind TEXT NOT NULL, name TEXT NOT NULL, qualified_name TEXT NOT NULL, exported INTEGER NOT NULL, start_line INTEGER NOT NULL, end_line INTEGER NOT NULL, start_offset INTEGER, end_offset INTEGER, source_file TEXT, exported_name TEXT, evidence_json TEXT, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE, FOREIGN KEY(file_id) REFERENCES files(id) ON DELETE CASCADE);\nCREATE TABLE IF NOT EXISTS handler_classes (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, symbol_id INTEGER, class_name TEXT NOT NULL, source_file TEXT NOT NULL, source_line INTEGER NOT NULL, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE, FOREIGN KEY(symbol_id) REFERENCES symbols(id) ON DELETE SET NULL);\nCREATE TABLE IF NOT EXISTS handler_methods (id INTEGER PRIMARY KEY, handler_class_id INTEGER NOT NULL, method_name TEXT NOT NULL, decorator_kind TEXT NOT NULL, decorator_value TEXT, decorator_raw_expression TEXT NOT NULL, decorator_resolution_json TEXT NOT NULL DEFAULT '{}', source_file TEXT NOT NULL, source_line INTEGER NOT NULL, FOREIGN KEY(handler_class_id) REFERENCES handler_classes(id) ON DELETE CASCADE);\nCREATE TABLE IF NOT EXISTS handler_registrations (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, handler_class_id INTEGER, class_name TEXT, import_source TEXT, registration_file TEXT NOT NULL, registration_line INTEGER NOT NULL, registration_kind TEXT NOT NULL, confidence REAL NOT NULL, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE, FOREIGN KEY(handler_class_id) REFERENCES handler_classes(id) ON DELETE SET NULL);\nCREATE TABLE IF NOT EXISTS service_bindings (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, symbol_id INTEGER, variable_name TEXT NOT NULL, alias TEXT, alias_expr TEXT, destination_expr TEXT, service_path_expr TEXT, is_dynamic INTEGER NOT NULL, placeholders_json TEXT NOT NULL, source_file TEXT NOT NULL, source_line INTEGER NOT NULL, helper_chain_json TEXT, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE, FOREIGN KEY(symbol_id) REFERENCES symbols(id) ON DELETE SET NULL);\nCREATE TABLE IF NOT EXISTS outbound_calls (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, source_symbol_id INTEGER, call_type TEXT NOT NULL, service_binding_id INTEGER, method TEXT, operation_path_expr TEXT, query_entity TEXT, event_name_expr TEXT, payload_summary TEXT, source_file TEXT NOT NULL, source_line INTEGER NOT NULL, call_site_start_offset INTEGER, call_site_end_offset INTEGER, confidence REAL NOT NULL, unresolved_reason TEXT, local_service_name TEXT, local_service_lookup TEXT, alias_chain_json TEXT, evidence_json TEXT, external_target_kind TEXT, external_target_id TEXT, external_target_label TEXT, external_target_dynamic INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE, FOREIGN KEY(source_symbol_id) REFERENCES symbols(id) ON DELETE SET NULL, FOREIGN KEY(service_binding_id) REFERENCES service_bindings(id) ON DELETE SET NULL);\nCREATE TABLE IF NOT EXISTS symbol_calls (id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL, caller_symbol_id INTEGER NOT NULL, callee_symbol_id INTEGER, callee_expression TEXT NOT NULL, import_source TEXT, source_file TEXT NOT NULL, source_line INTEGER NOT NULL, call_site_start_offset INTEGER, call_site_end_offset INTEGER, call_role TEXT NOT NULL DEFAULT 'legacy_unknown', status TEXT NOT NULL, confidence REAL NOT NULL, evidence_json TEXT NOT NULL, unresolved_reason TEXT, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE, FOREIGN KEY(caller_symbol_id) REFERENCES symbols(id) ON DELETE CASCADE, FOREIGN KEY(callee_symbol_id) REFERENCES symbols(id) ON DELETE SET NULL);\nCREATE TABLE IF NOT EXISTS graph_edges (id INTEGER PRIMARY KEY, workspace_id INTEGER NOT NULL, edge_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'unresolved', from_kind TEXT NOT NULL, from_id TEXT NOT NULL, to_kind TEXT NOT NULL, to_id TEXT NOT NULL, confidence REAL NOT NULL, evidence_json TEXT NOT NULL, is_dynamic INTEGER NOT NULL, unresolved_reason TEXT, generation INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE);\nCREATE TABLE IF NOT EXISTS index_runs (id INTEGER PRIMARY KEY, workspace_id INTEGER NOT NULL, started_at TEXT NOT NULL, finished_at TEXT, status TEXT NOT NULL, repo_count INTEGER NOT NULL, file_count INTEGER NOT NULL, diagnostic_count INTEGER NOT NULL, error_message TEXT, owner_pid INTEGER, FOREIGN KEY(workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE);\nCREATE TABLE IF NOT EXISTS diagnostics (id INTEGER PRIMARY KEY, repo_id INTEGER, file_id INTEGER, severity TEXT NOT NULL, code TEXT NOT NULL, message TEXT NOT NULL, source_file TEXT, source_line INTEGER, FOREIGN KEY(repo_id) REFERENCES repositories(id) ON DELETE CASCADE, FOREIGN KEY(file_id) REFERENCES files(id) ON DELETE SET NULL);\n`;\n\nexport const schemaIndexesSql = `\nCREATE INDEX IF NOT EXISTS idx_repo_name ON repositories(name);\nCREATE INDEX IF NOT EXISTS idx_service_path ON cds_services(service_path);\nCREATE INDEX IF NOT EXISTS idx_extension_import ON cds_services(extension_module_specifier, extension_imported_symbol, is_extend);\nCREATE INDEX IF NOT EXISTS idx_operation_name ON cds_operations(operation_name, operation_path);\nCREATE INDEX IF NOT EXISTS idx_operation_base ON cds_operations(base_operation_id);\nCREATE INDEX IF NOT EXISTS idx_calls_repo ON outbound_calls(repo_id, call_type);\nCREATE INDEX IF NOT EXISTS idx_symbol_calls_caller ON symbol_calls(repo_id, caller_symbol_id);\nCREATE INDEX IF NOT EXISTS idx_outbound_call_site ON outbound_calls(repo_id, source_file, call_site_start_offset, call_site_end_offset, call_type);\nCREATE INDEX IF NOT EXISTS idx_symbol_call_site_role ON symbol_calls(repo_id, source_file, call_site_start_offset, call_site_end_offset, call_role);\nCREATE VIRTUAL TABLE IF NOT EXISTS search_index USING fts5(kind, name, path, repo);\n`;\n\nexport const schemaSql = `${schemaTablesSql}\\n${schemaIndexesSql}`;\n","import type { Db } from './connection.js';\nimport { schemaIndexesSql, schemaTablesSql } from './schema.js';\nexport const CURRENT_SCHEMA_VERSION = 12;\nconst columns: Record<string, Array<{ name: string; ddl: string }>> = {\n handler_methods: [\n { name: 'decorator_resolution_json', ddl: \"ALTER TABLE handler_methods ADD COLUMN decorator_resolution_json TEXT NOT NULL DEFAULT '{}'\" },\n ],\n service_bindings: [\n { name: 'helper_chain_json', ddl: 'ALTER TABLE service_bindings ADD COLUMN helper_chain_json TEXT' },\n { name: 'alias_expr', ddl: 'ALTER TABLE service_bindings ADD COLUMN alias_expr TEXT' },\n ],\n repositories: [\n { name: 'fingerprint', ddl: 'ALTER TABLE repositories ADD COLUMN fingerprint TEXT' },\n { name: 'fact_generation', ddl: 'ALTER TABLE repositories ADD COLUMN fact_generation INTEGER NOT NULL DEFAULT 0' },\n { name: 'graph_generation', ddl: 'ALTER TABLE repositories ADD COLUMN graph_generation INTEGER NOT NULL DEFAULT 0' },\n { name: 'graph_stale_reason', ddl: 'ALTER TABLE repositories ADD COLUMN graph_stale_reason TEXT' },\n { name: 'graph_stale_at', ddl: 'ALTER TABLE repositories ADD COLUMN graph_stale_at TEXT' },\n { name: 'fact_analyzer_version', ddl: \"ALTER TABLE repositories ADD COLUMN fact_analyzer_version TEXT DEFAULT 'legacy'\" },\n ],\n graph_edges: [\n { name: 'status', ddl: \"ALTER TABLE graph_edges ADD COLUMN status TEXT NOT NULL DEFAULT 'unresolved'\" },\n { name: 'generation', ddl: 'ALTER TABLE graph_edges ADD COLUMN generation INTEGER NOT NULL DEFAULT 0' },\n ],\n handler_registrations: [\n { name: 'class_name', ddl: 'ALTER TABLE handler_registrations ADD COLUMN class_name TEXT' },\n { name: 'import_source', ddl: 'ALTER TABLE handler_registrations ADD COLUMN import_source TEXT' },\n ],\n symbols: [\n { name: 'start_offset', ddl: 'ALTER TABLE symbols ADD COLUMN start_offset INTEGER' },\n { name: 'end_offset', ddl: 'ALTER TABLE symbols ADD COLUMN end_offset INTEGER' },\n { name: 'source_file', ddl: 'ALTER TABLE symbols ADD COLUMN source_file TEXT' },\n { name: 'exported_name', ddl: 'ALTER TABLE symbols ADD COLUMN exported_name TEXT' },\n { name: 'evidence_json', ddl: 'ALTER TABLE symbols ADD COLUMN evidence_json TEXT' },\n ],\n cds_services: [\n { name: 'extension_local_ref', ddl: 'ALTER TABLE cds_services ADD COLUMN extension_local_ref TEXT' },\n { name: 'extension_imported_symbol', ddl: 'ALTER TABLE cds_services ADD COLUMN extension_imported_symbol TEXT' },\n { name: 'extension_local_alias', ddl: 'ALTER TABLE cds_services ADD COLUMN extension_local_alias TEXT' },\n { name: 'extension_module_specifier', ddl: 'ALTER TABLE cds_services ADD COLUMN extension_module_specifier TEXT' },\n { name: 'extension_import_kind', ddl: 'ALTER TABLE cds_services ADD COLUMN extension_import_kind TEXT' },\n { name: 'extension_base_service_id', ddl: 'ALTER TABLE cds_services ADD COLUMN extension_base_service_id INTEGER' },\n { name: 'extension_base_status', ddl: 'ALTER TABLE cds_services ADD COLUMN extension_base_status TEXT' },\n ],\n cds_operations: [\n { name: 'provenance', ddl: \"ALTER TABLE cds_operations ADD COLUMN provenance TEXT NOT NULL DEFAULT 'direct'\" },\n { name: 'base_operation_id', ddl: 'ALTER TABLE cds_operations ADD COLUMN base_operation_id INTEGER' },\n ],\n outbound_calls: [\n { name: 'local_service_name', ddl: 'ALTER TABLE outbound_calls ADD COLUMN local_service_name TEXT' },\n { name: 'local_service_lookup', ddl: 'ALTER TABLE outbound_calls ADD COLUMN local_service_lookup TEXT' },\n { name: 'alias_chain_json', ddl: 'ALTER TABLE outbound_calls ADD COLUMN alias_chain_json TEXT' },\n { name: 'evidence_json', ddl: 'ALTER TABLE outbound_calls ADD COLUMN evidence_json TEXT' },\n { name: 'external_target_kind', ddl: 'ALTER TABLE outbound_calls ADD COLUMN external_target_kind TEXT' },\n { name: 'external_target_id', ddl: 'ALTER TABLE outbound_calls ADD COLUMN external_target_id TEXT' },\n { name: 'external_target_label', ddl: 'ALTER TABLE outbound_calls ADD COLUMN external_target_label TEXT' },\n { name: 'external_target_dynamic', ddl: 'ALTER TABLE outbound_calls ADD COLUMN external_target_dynamic INTEGER NOT NULL DEFAULT 0' },\n { name: 'call_site_start_offset', ddl: 'ALTER TABLE outbound_calls ADD COLUMN call_site_start_offset INTEGER' },\n { name: 'call_site_end_offset', ddl: 'ALTER TABLE outbound_calls ADD COLUMN call_site_end_offset INTEGER' },\n ],\n symbol_calls: [\n { name: 'call_site_start_offset', ddl: 'ALTER TABLE symbol_calls ADD COLUMN call_site_start_offset INTEGER' },\n { name: 'call_site_end_offset', ddl: 'ALTER TABLE symbol_calls ADD COLUMN call_site_end_offset INTEGER' },\n { name: 'call_role', ddl: \"ALTER TABLE symbol_calls ADD COLUMN call_role TEXT NOT NULL DEFAULT 'legacy_unknown'\" },\n ],\n index_runs: [\n { name: 'error_message', ddl: 'ALTER TABLE index_runs ADD COLUMN error_message TEXT' },\n { name: 'owner_pid', ddl: 'ALTER TABLE index_runs ADD COLUMN owner_pid INTEGER' },\n ],\n};\nfunction hasColumn(db: Db, table: string, column: string): boolean {\n return (db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name?: string }>).some((row) => row.name === column);\n}\nfunction userVersion(db: Db): number {\n const row = db.pragma('user_version')[0] as { user_version?: number } | undefined;\n return Number(row?.user_version ?? 0);\n}\nfunction addMissingColumns(db: Db): void {\n for (const [table, tableColumns] of Object.entries(columns)) {\n for (const column of tableColumns) {\n if (!hasColumn(db, table, column.name)) db.prepare(column.ddl).run();\n }\n }\n}\nfunction normalizeLegacyStatus(db: Db): void {\n db.prepare(\"UPDATE graph_edges SET status=CASE WHEN edge_type='REMOTE_CALL_RESOLVES_TO_OPERATION' THEN 'resolved' WHEN edge_type IN ('HANDLER_RUNS_DB_QUERY','HANDLER_CALLS_EXTERNAL_HTTP','HANDLER_EMITS_EVENT','EVENT_CONSUMED_BY_HANDLER') THEN 'terminal' WHEN edge_type='DYNAMIC_EDGE_CANDIDATE' THEN 'dynamic' WHEN status='ambiguous' THEN 'ambiguous' ELSE status END\").run();\n db.prepare(\"UPDATE repositories SET graph_stale_reason='schema_migration_requires_relink', graph_stale_at=COALESCE(graph_stale_at, datetime('now')) WHERE EXISTS (SELECT 1 FROM graph_edges WHERE graph_edges.workspace_id=repositories.workspace_id) AND graph_generation=0\").run();\n}\nfunction markCallSiteMigrationStale(db: Db, priorVersion: number): void {\n if (priorVersion >= 12) return;\n db.prepare(`UPDATE repositories\n SET graph_stale_reason='schema_v12_call_sites_require_reindex',\n graph_stale_at=COALESCE(graph_stale_at,datetime('now'))\n WHERE index_status='indexed' OR last_indexed_at IS NOT NULL`).run();\n}\nexport function migrate(db: Db): void {\n db.transaction(() => {\n const version = userVersion(db);\n if (version > CURRENT_SCHEMA_VERSION) throw new Error(`Unsupported future service-flow schema version ${version}`);\n db.exec(schemaTablesSql);\n addMissingColumns(db);\n db.exec(schemaIndexesSql);\n normalizeLegacyStatus(db);\n markCallSiteMigrationStale(db, version);\n const violations = db.pragma('foreign_key_check');\n if (violations.length > 0) throw new Error('SQLite foreign_key_check failed during migration');\n db.pragma(`user_version = ${CURRENT_SCHEMA_VERSION}`);\n });\n}\nexport function schemaVersion(db: Db): number {\n return userVersion(db);\n}\nexport function foreignKeyViolations(db: Db): Array<Record<string, unknown>> {\n return db.pragma('foreign_key_check');\n}\n","import type { Db } from './connection.js';\nimport { CURRENT_SCHEMA_VERSION, schemaVersion } from './migrations.js';\nimport { ANALYZER_VERSION } from '../version.js';\n\nexport type FactLifecycleCode =\n | 'schema_upgrade_required'\n | 'unsupported_future_schema'\n | 'reindex_required';\n\nexport interface FactLifecycleDiagnostic extends Record<string, unknown> {\n severity: 'error';\n code: FactLifecycleCode;\n message: string;\n remediation: string;\n}\n\nconst remediation = [\n 'service-flow index --workspace /workspace --force',\n 'service-flow link --workspace /workspace --force',\n].join('\\n');\n\nfunction count(db: Db, sql: string, ...params: unknown[]): number {\n const row = db.prepare(sql).get(...params);\n return Number(row?.count ?? 0);\n}\n\nfunction oldAnalyzerCount(db: Db, workspaceId?: number): number {\n return count(db, `SELECT COUNT(*) count FROM repositories\n WHERE (? IS NULL OR workspace_id=?)\n AND (COALESCE(index_status,'pending')<>'indexed'\n OR COALESCE(fact_analyzer_version,'legacy')<>?)`,\n workspaceId, workspaceId, ANALYZER_VERSION);\n}\n\nfunction invalidCurrentFactCount(db: Db, workspaceId?: number): number {\n const outbound = count(db, `SELECT COUNT(*) count\n FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id\n WHERE (? IS NULL OR r.workspace_id=?) AND r.fact_analyzer_version=?\n AND (typeof(c.call_site_start_offset)<>'integer'\n OR typeof(c.call_site_end_offset)<>'integer'\n OR c.call_site_start_offset<0\n OR c.call_site_end_offset<=c.call_site_start_offset)`,\n workspaceId, workspaceId, ANALYZER_VERSION);\n const symbols = count(db, `SELECT COUNT(*) count\n FROM symbol_calls c JOIN repositories r ON r.id=c.repo_id\n WHERE (? IS NULL OR r.workspace_id=?)\n AND (c.call_role='legacy_unknown'\n OR (r.fact_analyzer_version=? AND (\n typeof(c.call_site_start_offset)<>'integer'\n OR typeof(c.call_site_end_offset)<>'integer'\n OR c.call_site_start_offset<0\n OR c.call_site_end_offset<=c.call_site_start_offset\n OR c.call_role NOT IN ('ordinary_call','event_subscribe_handler'))))`,\n workspaceId, workspaceId, ANALYZER_VERSION);\n return outbound + symbols;\n}\n\nexport function factLifecycleDiagnostic(\n db: Db,\n workspaceId?: number,\n): FactLifecycleDiagnostic | undefined {\n return schemaLifecycleDiagnostic(db)\n ?? currentFactLifecycleDiagnostic(db, workspaceId);\n}\n\nexport function schemaLifecycleDiagnostic(\n db: Db,\n): FactLifecycleDiagnostic | undefined {\n const currentSchema = schemaVersion(db);\n if (currentSchema > CURRENT_SCHEMA_VERSION) return {\n severity: 'error',\n code: 'unsupported_future_schema',\n message: `Database schema ${currentSchema} is newer than the supported schema ${CURRENT_SCHEMA_VERSION}; upgrade service-flow before reading this database.`,\n remediation: 'Install a service-flow version that supports this database schema.',\n currentSchemaVersion: currentSchema,\n supportedSchemaVersion: CURRENT_SCHEMA_VERSION,\n };\n if (currentSchema < CURRENT_SCHEMA_VERSION) return {\n severity: 'error',\n code: 'schema_upgrade_required',\n message: `Database schema ${currentSchema} must be upgraded to ${CURRENT_SCHEMA_VERSION} before this command can read current call-site facts.`,\n remediation,\n currentSchemaVersion: currentSchema,\n requiredSchemaVersion: CURRENT_SCHEMA_VERSION,\n };\n return undefined;\n}\n\nexport function currentFactLifecycleDiagnostic(\n db: Db,\n workspaceId?: number,\n): FactLifecycleDiagnostic | undefined {\n const staleRepositories = oldAnalyzerCount(db, workspaceId);\n const invalidFacts = invalidCurrentFactCount(db, workspaceId);\n if (staleRepositories === 0 && invalidFacts === 0) return undefined;\n return {\n severity: 'error',\n code: 'reindex_required',\n message: 'Call-site facts are stale or lack typed roles and exact spans; force index and link before tracing or rebuilding graph edges.',\n remediation,\n staleRepositoryCount: staleRepositories,\n invalidCallFactCount: invalidFacts,\n requiredAnalyzerVersion: ANALYZER_VERSION,\n };\n}\n\nexport function assertWorkspaceLinkable(db: Db, workspaceId: number): void {\n const diagnostic = factLifecycleDiagnostic(db, workspaceId);\n if (!diagnostic) return;\n throw new Error(`${diagnostic.code}: ${diagnostic.message}\\n${diagnostic.remediation}`);\n}\n","import type { Db } from '../db/connection.js';\nimport { applyVariables } from './dynamic-edge-resolver.js';\nimport { classifyODataPathIntent, normalizeODataOperationInvocationPath } from './odata-path-normalizer.js';\nimport { buildRemoteQueryTarget } from './remote-query-target.js';\nimport { resolveOperation } from './service-resolver.js';\nimport { linkHelperPackages } from './helper-package-linker.js';\nimport { externalHttpTarget } from './external-http-target.js';\nimport { linkImplementations as linkCanonicalImplementations } from './000-implementation-candidates.js';\nimport {\n ambiguousPathCandidates,\n linkedCallEvidence,\n objectJson,\n objectValue,\n} from './002-call-evidence.js';\nimport { linkPackageImportSymbolCalls } from './003-package-import-symbol-resolver.js';\nimport { linkEventSubscriptionHandlers } from './004-event-subscription-handler-linker.js';\nimport { assertWorkspaceLinkable } from '../db/001-fact-lifecycle.js';\nexport interface LinkWorkspaceResult {\n edgeCount: number;\n unresolvedCount: number;\n resolvedCount: number;\n remoteResolvedCount: number;\n localResolvedCount: number;\n ambiguousCount: number;\n dynamicCount: number;\n terminalCount: number;\n dependencyResolvedCount: number;\n dependencyAmbiguousCount: number;\n implementationResolvedCount: number;\n implementationAmbiguousCount: number;\n implementationUnresolvedCount: number;\n subscriptionHandlerResolvedCount: number;\n subscriptionHandlerAmbiguousCount: number;\n subscriptionHandlerUnresolvedCount: number;\n subscriptionHandlerMissingAssociationCount: number;\n}\nexport function linkWorkspace(db: Db, workspaceId: number, vars: Record<string, string> = {}): LinkWorkspaceResult {\n return db.transaction(() => {\n assertWorkspaceLinkable(db, workspaceId);\n const generation = nextGraphGeneration(db, workspaceId);\n db.prepare('DELETE FROM graph_edges WHERE workspace_id=?').run(workspaceId);\n const deps = linkHelperPackages(db, workspaceId, generation);\n linkPackageImportSymbolCalls(db, workspaceId);\n const subscriptions = linkEventSubscriptionHandlers(\n db, workspaceId, generation,\n );\n const impl = linkCanonicalImplementations(db, workspaceId, generation);\n const callSummary = linkCalls(db, workspaceId, vars, generation);\n db.prepare(\"UPDATE repositories SET graph_generation=?, graph_stale_reason=NULL, graph_stale_at=NULL WHERE workspace_id=?\").run(generation, workspaceId);\n return { ...callSummary, edgeCount: deps.edgeCount + callSummary.edgeCount + impl.edgeCount + subscriptions.edgeCount, dependencyResolvedCount: deps.resolvedCount, dependencyAmbiguousCount: deps.ambiguousCount, implementationResolvedCount: impl.resolvedCount, implementationAmbiguousCount: impl.ambiguousCount, implementationUnresolvedCount: impl.unresolvedCount, subscriptionHandlerResolvedCount: subscriptions.resolvedCount, subscriptionHandlerAmbiguousCount: subscriptions.ambiguousCount, subscriptionHandlerUnresolvedCount: subscriptions.unresolvedCount, subscriptionHandlerMissingAssociationCount: subscriptions.missingAssociationCount };\n });\n}\nfunction nextGraphGeneration(db: Db, workspaceId: number): number {\n const row = db.prepare('SELECT COALESCE(MAX(graph_generation),0) generation FROM repositories WHERE workspace_id=?').get(workspaceId) as { generation?: number } | undefined;\n return Number(row?.generation ?? 0) + 1;\n}\ntype CallLinkSummary = Omit<LinkWorkspaceResult,\n | 'dependencyResolvedCount'\n | 'dependencyAmbiguousCount'\n | 'implementationResolvedCount'\n | 'implementationAmbiguousCount'\n | 'implementationUnresolvedCount'\n | 'subscriptionHandlerResolvedCount'\n | 'subscriptionHandlerAmbiguousCount'\n | 'subscriptionHandlerUnresolvedCount'\n | 'subscriptionHandlerMissingAssociationCount'>;\n\nfunction linkCalls(db: Db, workspaceId: number, vars: Record<string, string>, generation: number): CallLinkSummary {\n let edgeCount = 0;\n let unresolvedCount = 0;\n let resolvedCount = 0;\n let remoteResolvedCount = 0;\n let localResolvedCount = 0;\n let ambiguousCount = 0;\n let dynamicCount = 0;\n let terminalCount = 0;\n const calls = db.prepare(`SELECT c.*,r.name repoName,b.id selectedBindingId,b.alias,b.alias_expr aliasExpr,b.destination_expr destinationExpr,b.service_path_expr servicePathExpr,b.is_dynamic isDynamic,b.placeholders_json placeholdersJson,b.source_file bindingSourceFile,b.source_line bindingSourceLine,b.helper_chain_json helperChainJson,req.service_path requireServicePath,req.destination requireDestination FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id LEFT JOIN service_bindings b ON b.id=c.service_binding_id LEFT JOIN cds_requires req ON req.repo_id=c.repo_id AND req.alias=b.alias WHERE r.workspace_id=?`).all(workspaceId) as Array<Record<string, unknown>>;\n for (const call of calls) {\n const result = insertCallEdge(db, workspaceId, call, vars, generation);\n edgeCount += 1;\n resolvedCount += result.status === 'resolved' ? 1 : 0;\n remoteResolvedCount += result.status === 'resolved' && result.callType !== 'local_service_call' ? 1 : 0;\n localResolvedCount += result.status === 'resolved' && result.callType === 'local_service_call' ? 1 : 0;\n unresolvedCount += result.status === 'unresolved' ? 1 : 0;\n ambiguousCount += result.status === 'ambiguous' ? 1 : 0;\n dynamicCount += result.status === 'dynamic' ? 1 : 0;\n terminalCount += result.status === 'terminal' ? 1 : 0;\n }\n return { edgeCount, unresolvedCount, resolvedCount, remoteResolvedCount, localResolvedCount, ambiguousCount, dynamicCount, terminalCount };\n}\nfunction insertCallEdge(db: Db, workspaceId: number, call: Record<string, unknown>, vars: Record<string, string>, generation: number): { status: string; callType: string } {\n const callType = String(call.call_type);\n const rawOp = applyVariables(String(call.operation_path_expr ?? ''), vars);\n const intent = classifyODataPathIntent(rawOp, call.method as string | undefined);\n const isEntityQueryIntent = ['entity_query', 'entity_key_read', 'entity_navigation_query'].includes(intent.kind);\n const resolutionRawOp = callType === 'remote_query' && isEntityQueryIntent ? intent.pathWithoutQuery : rawOp;\n const normalized = normalizeODataOperationInvocationPath(resolutionRawOp);\n const op = normalized?.normalizedOperationPath ?? resolutionRawOp;\n const servicePath = applyVariables((call.servicePathExpr as string | undefined) ?? (call.requireServicePath as string | undefined), vars);\n const destination = (call.destinationExpr as string | undefined) ?? (call.requireDestination as string | undefined);\n const isDynamic = Boolean(Number(call.isDynamic ?? 0));\n const isRemoteEntityCall = callType.startsWith('remote_entity_');\n const indexedOperationCandidateCount = operationCandidateCount(db, workspaceId, op, intent.topLevelOperationName);\n const credibleOperationSignal = Boolean(normalized?.wasInvocation) || (Boolean(intent.topLevelOperationNameCandidate) && indexedOperationCandidateCount > 0);\n const strongEntitySignal = ['entity_media', 'entity_delete', 'entity_key_read', 'entity_navigation_query'].includes(intent.kind) || (intent.kind === 'entity_mutation' && (intent.hasEntityKeyPredicate || intent.hasNavigationSuffix));\n const operationLikeRemoteEntity = isRemoteEntityCall && Boolean(op) && credibleOperationSignal && (!strongEntitySignal || indexedOperationCandidateCount > 0);\n const isOperationCall = operationLikeRemoteEntity || ((callType === 'remote_action' || callType === 'local_service_call') || (callType === 'remote_query' && Boolean(op)));\n const resolution = isOperationCall ? resolveOperation(db, { servicePath, operationPath: op, serviceName: call.local_service_name as string | undefined, repoId: callType === 'local_service_call' ? Number(call.repo_id) : undefined, alias: applyVariables((call.aliasExpr as string | undefined) ?? (call.alias as string | undefined), vars), destination: destination ? applyVariables(destination, vars) : undefined, isDynamic, hasExplicitOverride: Object.keys(vars).length > 0 || callType === 'local_service_call' }, workspaceId) : { status: 'unresolved' as const, candidates: [], reasons: [] };\n const evidence: Record<string, unknown> = {\n ...linkedCallEvidence(\n call,\n resolution,\n servicePath,\n op,\n destination ? applyVariables(destination, vars) : undefined,\n normalized,\n intent,\n ),\n indexedOperationCandidateCount,\n parserCallType: callType,\n entityOperationPrecedence: operationPrecedence(\n callType,\n intent,\n indexedOperationCandidateCount,\n Boolean(resolution.target),\n ),\n };\n const pathAnalysis = objectValue(objectJson(call.evidence_json)?.pathAnalysis);\n if (callType === 'remote_action' && pathAnalysis?.status === 'ambiguous') {\n const candidatePaths = ambiguousPathCandidates(pathAnalysis);\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,unresolved_reason,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)').run(\n workspaceId,\n 'UNRESOLVED_EDGE',\n 'ambiguous',\n 'call',\n String(call.id),\n 'operation_candidates',\n candidatePaths.items.join(','),\n Number(call.confidence ?? 0.5),\n JSON.stringify({\n ...evidence,\n ambiguousOperationPathCandidateCount: candidatePaths.totalCount,\n shownAmbiguousOperationPathCandidateCount: candidatePaths.shownCount,\n omittedAmbiguousOperationPathCandidateCount: candidatePaths.omittedCount,\n }),\n 0,\n 'Ambiguous operation path candidates require explicit disambiguation',\n generation,\n );\n return { status: 'ambiguous', callType };\n }\n if (isRemoteEntityCall && (resolution.target || resolution.candidates.length > 0 || resolution.status === 'dynamic')) {\n if (resolution.target) {\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(workspaceId, 'REMOTE_CALL_RESOLVES_TO_OPERATION', 'resolved', 'call', String(call.id), 'operation', String(resolution.target.operationId), resolution.target.score, JSON.stringify({ ...evidence, operationEntityPrecedence: 'indexed_operation_over_parser_entity' }), 0, generation);\n return { status: 'resolved', callType };\n }\n const status = resolution.status === 'dynamic' ? 'dynamic' : resolution.status === 'ambiguous' ? 'ambiguous' : 'unresolved';\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,unresolved_reason,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)').run(workspaceId, status === 'dynamic' ? 'DYNAMIC_EDGE_CANDIDATE' : 'UNRESOLVED_EDGE', status, 'call', String(call.id), 'operation_candidate', op ? `Remote action: ${op}` : 'Remote action: unknown path', Number(call.confidence ?? 0.2), JSON.stringify({ ...evidence, operationEntityPrecedence: resolution.candidates.length > 0 ? 'parser_entity_with_indexed_operation_candidates' : 'parser_entity_operation_candidate_without_indexed_match' }), status === 'dynamic' ? 1 : 0, unresolvedOperationReason(resolution), generation);\n return { status, callType };\n }\n if (isRemoteEntityCall) {\n const target = buildRemoteQueryTarget({ queryEntity: intent.entitySegment ?? call.query_entity, servicePath, serviceAlias: call.alias, serviceAliasExpr: call.aliasExpr, destination: destination ? applyVariables(destination, vars) : undefined, isDynamic, parserWarning: evidence.parserWarning });\n const entityKind = callType;\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(workspaceId, 'HANDLER_ACCESSES_REMOTE_ENTITY', 'terminal', 'call', String(call.id), target.toKind, target.toId, Number(call.confidence ?? 0.5), JSON.stringify({ ...evidence, ...target.evidence, remoteEntityAccess: entityKind }), 0, generation);\n return { status: 'terminal', callType };\n }\n if (callType === 'remote_query' && (isEntityQueryIntent || !op) && !resolution.target) {\n const target = buildRemoteQueryTarget({ queryEntity: call.query_entity, servicePath, serviceAlias: call.alias, serviceAliasExpr: call.aliasExpr, destination: destination ? applyVariables(destination, vars) : undefined, isDynamic, parserWarning: evidence.parserWarning });\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(workspaceId, 'HANDLER_RUNS_REMOTE_QUERY', 'terminal', 'call', String(call.id), target.toKind, target.toId, Number(call.confidence ?? 0.5), JSON.stringify({ ...evidence, ...target.evidence }), 0, generation);\n return { status: 'terminal', callType };\n }\n if (callType === 'local_service_call' && call.unresolved_reason === 'transport_client_method' && !resolution.target && resolution.candidates.length === 0) {\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(workspaceId, 'HANDLER_CALLS_TRANSPORT_METHOD', 'terminal', 'call', String(call.id), 'transport_method', String(op || 'transport_client_method'), Number(call.confidence ?? 0.5), JSON.stringify({ ...evidence, classification: 'transport_client_method' }), 0, generation);\n return { status: 'terminal', callType };\n }\n if (resolution.target) {\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(workspaceId, callType === 'local_service_call' ? 'LOCAL_CALL_RESOLVES_TO_OPERATION' : 'REMOTE_CALL_RESOLVES_TO_OPERATION', 'resolved', 'call', String(call.id), 'operation', String(resolution.target.operationId), resolution.target.score, JSON.stringify(evidence), 0, generation);\n return { status: 'resolved', callType };\n }\n const edgeType = callType === 'local_db_query' ? 'HANDLER_RUNS_DB_QUERY' : callType === 'external_http' ? 'HANDLER_CALLS_EXTERNAL_HTTP' : callType === 'async_emit' ? 'HANDLER_EMITS_EVENT' : callType === 'async_subscribe' ? 'EVENT_CONSUMED_BY_HANDLER' : resolution.status === 'dynamic' ? 'DYNAMIC_EDGE_CANDIDATE' : 'UNRESOLVED_EDGE';\n const status = edgeType === 'DYNAMIC_EDGE_CANDIDATE' ? 'dynamic' : resolution.status === 'ambiguous' ? 'ambiguous' : edgeType === 'UNRESOLVED_EDGE' ? 'unresolved' : 'terminal';\n const unresolvedReason = status === 'terminal' ? null : String(call.unresolved_reason ?? unresolvedOperationReason(resolution));\n const externalTarget = callType === 'external_http' ? externalHttpTarget(call) : undefined;\n const targetKind = callType === 'local_db_query' ? 'db_entity' : callType.startsWith('async_') ? 'event' : callType === 'external_http' ? (externalTarget?.toKind ?? 'external_endpoint') : 'operation_candidate';\n const targetId = callType === 'local_db_query' ? String(call.query_entity ?? 'unknown') : callType === 'remote_action' ? (op ? `Remote action: ${op}` : (call.unresolved_reason === 'dynamic_operation_path_identifier' ? 'Remote action: dynamic path' : 'Remote action: unknown path')) : callType === 'external_http' ? String(externalTarget?.toId ?? 'unknown') : String(call.event_name_expr ?? op ?? 'unknown');\n const graphLevelDynamic = edgeType === 'DYNAMIC_EDGE_CANDIDATE' && resolution.status === 'dynamic';\n const finalEvidence = externalTarget ? { ...evidence, externalTarget } : evidence;\n db.prepare('INSERT INTO graph_edges(workspace_id,edge_type,status,from_kind,from_id,to_kind,to_id,confidence,evidence_json,is_dynamic,unresolved_reason,generation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)').run(workspaceId, edgeType, status, 'call', String(call.id), targetKind, targetId, Number(call.confidence ?? 0.2), JSON.stringify(finalEvidence), graphLevelDynamic ? 1 : 0, unresolvedReason, generation);\n return { status, callType };\n}\nfunction operationCandidateCount(db: Db, workspaceId: number, operationPath: string | undefined, operationName: string | undefined): number {\n if (!operationPath && !operationName) return 0;\n const normalizedName = operationName ?? operationPath?.replace(/^\\//, '').split('.').at(-1);\n const row = db.prepare(`SELECT COUNT(*) count 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_path=? OR o.operation_path=? OR o.operation_name=?)`).get(workspaceId, operationPath, normalizedName ? `/${normalizedName}` : operationPath, normalizedName) as { count?: number } | undefined;\n return Number(row?.count ?? 0);\n}\n\nfunction operationPrecedence(\n callType: string,\n intent: ReturnType<typeof classifyODataPathIntent>,\n indexedOperationCandidateCount: number,\n resolvedOperation: boolean,\n): Record<string, unknown> {\n if (resolvedOperation) {\n return {\n decision: 'operation',\n reason: 'indexed_operation_with_strong_service_context',\n indexedOperationCandidateCount,\n };\n }\n if (callType === 'remote_action' && intent.kind === 'operation_invocation') {\n return {\n decision: 'operation_candidate',\n rejectionReason: indexedOperationCandidateCount > 0\n ? 'indexed_candidates_lack_unique_strong_service_context'\n : 'no_indexed_operation_candidate',\n indexedOperationCandidateCount,\n };\n }\n if (intent.kind.startsWith('entity_')) {\n return {\n decision: 'entity',\n rejectionReason: indexedOperationCandidateCount > 0\n ? 'entity_shape_has_precedence_without_resolved_operation_context'\n : 'entity_shape_has_no_indexed_operation_evidence',\n indexedOperationCandidateCount,\n };\n }\n return {\n decision: 'unresolved',\n rejectionReason: 'path_has_no_safe_entity_or_operation_precedence',\n indexedOperationCandidateCount,\n };\n}\n\nfunction unresolvedOperationReason(resolution: { candidates: unknown[]; status: string; reasons: string[] }): string {\n if (resolution.status === 'dynamic') return `Dynamic target requires runtime variable overrides: ${(resolution.reasons.length ? resolution.reasons : ['missing runtime variables']).join(', ')}`;\n if (resolution.candidates.length === 0) return 'No indexed target operation matched';\n if (resolution.reasons.includes('operation_path_only_has_no_strong_target_signal')) return 'Operation candidates found but no strong service signal is available';\n if (resolution.reasons.includes('candidate_score_below_resolution_threshold')) return 'Operation candidates found but resolution score is below threshold';\n if (resolution.status === 'ambiguous') return 'Ambiguous operation candidates require a strong service signal';\n return 'Operation candidates found but resolution could not select a target';\n}\n","import type { Db } from '../db/connection.js';\nimport type { TraceStart } from '../types.js';\nimport {\n projectBounded,\n type BoundedProjection,\n} from '../utils/000-bounded-projection.js';\n\nexport interface SelectorSourceScope {\n files?: Set<string>;\n symbols?: Set<number>;\n repoId?: number;\n diagnostics?: Array<Record<string, unknown>>;\n}\n\ninterface HandlerSelectorRow {\n handlerClassId?: number | null;\n repoId?: number | null;\n repoName?: string | null;\n className?: string | null;\n sourceFile?: string | null;\n sourceLine?: number | null;\n methodId?: number | null;\n symbolId?: number | null;\n classEvidence?: string | null;\n}\nexport function parseVars(\n values: string[] | undefined\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const value of values ?? []) {\n const [key, ...rest] = value.split('=');\n if (key && rest.length > 0) out[key] = rest.join('=');\n }\n return out;\n}\nexport function startLabel(start: TraceStart): string {\n return [\n start.repo,\n start.servicePath,\n start.operation ?? start.operationPath ?? start.handler\n ]\n .filter(Boolean)\n .join(' ');\n}\n\nexport function selectorRepoNotFoundDiagnostic(\n requested: string,\n): Record<string, unknown> {\n return {\n severity: 'warning',\n code: 'selector_repo_not_found',\n message: `No indexed repository matched selector: ${requested}`,\n selectorKind: 'repo',\n requestedRepository: requested,\n };\n}\n\nexport function selectorRepoAmbiguousDiagnostic(\n requested: string,\n candidates: Array<{ id: number; name: string; packageName?: string }>,\n): Record<string, unknown> {\n const uniqueName = (value: string): boolean => candidates\n .filter((candidate) => candidate.name === value).length === 1;\n const uniquePackage = (value: string): boolean => candidates\n .filter((candidate) => candidate.packageName === value).length === 1;\n const suggestions = candidates.flatMap((candidate) => {\n if (uniqueName(candidate.name)) return [`--repo ${candidate.name}`];\n if (candidate.packageName && uniquePackage(candidate.packageName))\n return [`--repo ${candidate.packageName}`];\n return [];\n });\n const candidateProjection = projectBounded(candidates, (left, right) =>\n left.name.localeCompare(right.name)\n || String(left.packageName ?? '').localeCompare(String(right.packageName ?? ''))\n || left.id - right.id);\n const suggestionProjection = projectBounded(\n [...new Set(suggestions)], (left, right) => left.localeCompare(right),\n );\n return {\n severity: 'warning',\n code: 'selector_repo_ambiguous',\n message: `Repository selector matched multiple indexed repositories: ${requested}`,\n selectorKind: 'repo',\n requestedRepository: requested,\n candidates: candidateProjection.items,\n candidateCount: candidateProjection.totalCount,\n shownCandidateCount: candidateProjection.shownCount,\n omittedCandidateCount: candidateProjection.omittedCount,\n selectorSuggestions: suggestionProjection.items,\n selectorSuggestionCount: suggestionProjection.totalCount,\n shownSelectorSuggestionCount: suggestionProjection.shownCount,\n omittedSelectorSuggestionCount: suggestionProjection.omittedCount,\n remediation: suggestions.length > 0\n ? 'Use one of the unique --repo selectors shown.'\n : 'Repository names and package names must be unique before this selector can be traced safely.',\n };\n}\n\nexport function selectorNotFoundDiagnostic(\n start: TraceStart,\n): Record<string, unknown> {\n const serviceOnly = start.servicePath && !start.operation\n && !start.operationPath && !start.handler;\n return {\n severity: 'warning',\n code: 'trace_start_not_found',\n message: serviceOnly\n ? 'Service-only trace requires --operation or --path and will not broaden to the whole workspace'\n : 'No handler source matched the requested trace start selector',\n selectorKind: start.handler ? 'handler' : start.operation || start.operationPath\n ? 'operation' : start.servicePath ? 'service' : undefined,\n };\n}\n\nexport function sourceScopeForSelector(\n db: Db,\n repoId: number | undefined,\n start: TraceStart,\n workspaceId?: number,\n): SelectorSourceScope | undefined {\n if (start.handler) {\n const classRows = handlerClassRows(db, repoId, start.handler, workspaceId);\n if (classRows.length > 0) return handlerClassScope(classRows, start.handler);\n const methodRows = handlerMethodRows(db, repoId, start.handler, workspaceId);\n if (methodRows.length > 0)\n return handlerMethodScope(methodRows, repoId, start.handler);\n }\n const operation = normalizeOperation(start.operation ?? start.operationPath);\n if (!operation) return undefined;\n const operationRows = operationHandlerRows(\n db, repoId, operation, start.servicePath, workspaceId,\n );\n if (operationRows.length > 0)\n return operationHandlerScope(operationRows, repoId, operation);\n if (!start.servicePath) return undefined;\n const implementationRows = implementationHandlerRows(\n db, repoId, start.servicePath, operation, workspaceId,\n );\n return implementationRows.length > 0\n ? executableScope(implementationRows, repoId)\n : undefined;\n}\n\nfunction handlerClassRows(\n db: Db,\n repoId: number | undefined,\n handler: string,\n workspaceId: number | undefined,\n): HandlerSelectorRow[] {\n return db.prepare(`SELECT hc.id handlerClassId,hc.repo_id repoId,\n r.name repoName,hc.class_name className,\n hc.source_file sourceFile,hc.source_line sourceLine,hm.id methodId,\n sym.id symbolId,COALESCE(classSym.evidence_json,\n (SELECT fallback.evidence_json FROM symbols fallback\n WHERE fallback.repo_id=hc.repo_id AND fallback.kind='class'\n AND fallback.name=hc.class_name AND fallback.source_file=hc.source_file\n ORDER BY fallback.id LIMIT 1)) classEvidence\n FROM handler_classes hc\n JOIN repositories r ON r.id=hc.repo_id\n LEFT JOIN symbols sym ON sym.repo_id=hc.repo_id\n AND sym.source_file=hc.source_file\n AND sym.kind='method'\n AND substr(sym.qualified_name,1,length(hc.class_name)+1)=hc.class_name || '.'\n AND (NOT EXISTS (SELECT 1 FROM handler_methods declared\n WHERE declared.handler_class_id=hc.id\n AND declared.method_name=sym.name)\n OR EXISTS (SELECT 1 FROM handler_methods executable\n WHERE executable.handler_class_id=hc.id\n AND executable.method_name=sym.name\n AND COALESCE(json_extract(executable.decorator_resolution_json,\n '$.executable'),CASE WHEN executable.decorator_kind IN\n ('Action','Func','On','Event') THEN 1 ELSE 0 END)=1))\n LEFT JOIN handler_methods hm ON hm.handler_class_id=hc.id\n AND hm.method_name=sym.name\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.executable'),\n CASE WHEN hm.decorator_kind IN ('Action','Func','On','Event')\n THEN 1 ELSE 0 END)=1\n LEFT JOIN symbols classSym ON classSym.id=hc.symbol_id\n WHERE (? IS NULL OR r.workspace_id=?)\n AND (? IS NULL OR hc.repo_id=?) AND hc.class_name=?\n ORDER BY hc.repo_id,hc.id,hm.id`).all(\n workspaceId, workspaceId, repoId, repoId, handler,\n ) as HandlerSelectorRow[];\n}\n\nfunction handlerMethodRows(\n db: Db,\n repoId: number | undefined,\n handler: string,\n workspaceId: number | undefined,\n): HandlerSelectorRow[] {\n return db.prepare(`SELECT hc.id handlerClassId,hc.repo_id repoId,\n r.name repoName,hc.class_name className,hc.source_file sourceFile,\n hm.source_line sourceLine,hm.id methodId,sym.id symbolId\n FROM handler_methods hm JOIN handler_classes hc ON hc.id=hm.handler_class_id\n JOIN repositories r ON r.id=hc.repo_id\n LEFT JOIN symbols sym ON sym.repo_id=hc.repo_id\n AND sym.source_file=hc.source_file\n AND sym.qualified_name=hc.class_name || '.' || hm.method_name\n AND sym.start_line=hm.source_line\n WHERE (? IS NULL OR r.workspace_id=?)\n AND (? IS NULL OR hc.repo_id=?) AND hm.method_name=?\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.executable'),\n CASE WHEN hm.decorator_kind IN ('Action','Func','On','Event')\n THEN 1 ELSE 0 END)=1\n ORDER BY hc.repo_id,hc.id,hm.id`).all(\n workspaceId, workspaceId, repoId, repoId, handler,\n ) as HandlerSelectorRow[];\n}\n\nfunction operationHandlerRows(\n db: Db,\n repoId: number | undefined,\n operation: string,\n servicePath: string | undefined,\n workspaceId: number | undefined,\n): HandlerSelectorRow[] {\n return db.prepare(`SELECT DISTINCT hc.id handlerClassId,hc.repo_id repoId,\n r.name repoName,hc.class_name className,hc.source_file sourceFile,\n hm.source_line sourceLine,hm.id methodId,sym.id symbolId\n FROM handler_methods hm JOIN handler_classes hc ON hc.id=hm.handler_class_id\n JOIN repositories r ON r.id=hc.repo_id\n LEFT JOIN symbols sym ON sym.repo_id=hc.repo_id\n AND sym.source_file=hc.source_file\n AND sym.qualified_name=hc.class_name || '.' || hm.method_name\n AND sym.start_line=hm.source_line\n WHERE (? IS NULL OR r.workspace_id=?) AND (? IS NULL OR hc.repo_id=?)\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.handlerKind'),\n CASE WHEN hm.decorator_kind='Event' THEN 'event'\n WHEN hm.decorator_kind IN ('Action','Func','On') THEN 'operation'\n ELSE 'unsupported' END)='operation'\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.executable'),\n CASE WHEN hm.decorator_kind IN ('Action','Func','On')\n THEN 1 ELSE 0 END)=1\n AND (hm.decorator_value=? OR hm.method_name=?)\n AND (? IS NULL OR EXISTS (\n SELECT 1 FROM cds_services svc JOIN cds_operations op ON op.service_id=svc.id\n WHERE svc.repo_id=hc.repo_id AND svc.service_path=?\n AND (op.operation_path=? OR op.operation_name=?)))\n ORDER BY hc.repo_id,hc.id,hm.id`).all(\n workspaceId, workspaceId, repoId, repoId,\n operation, operation, servicePath, servicePath,\n operation, operation,\n ) as HandlerSelectorRow[];\n}\n\nfunction operationHandlerScope(\n rows: HandlerSelectorRow[],\n fallbackRepoId: number | undefined,\n requested: string,\n): SelectorSourceScope {\n const candidates = handlerSelectorCandidates(rows, 'method');\n if (candidates.length < 2) return executableScope(rows, fallbackRepoId);\n const classes = new Map<string, Set<string>>();\n for (const candidate of candidates) {\n const key = `${String(candidate.repoName)}:${String(candidate.className)}`;\n classes.set(key, new Set([\n ...(classes.get(key) ?? []),\n String(candidate.handlerClassId),\n ]));\n }\n const suggestions = candidates.flatMap((candidate) => {\n if (typeof candidate.repoName !== 'string'\n || typeof candidate.className !== 'string') return [];\n const key = `${candidate.repoName}:${candidate.className}`;\n return classes.get(key)?.size === 1\n ? [`--repo ${candidate.repoName} --handler ${candidate.className}`]\n : [];\n });\n const projection = boundedSelectorCandidates(candidates);\n const suggestionProjection = boundedSelectorSuggestions(suggestions);\n return { diagnostics: [{\n severity: 'warning',\n code: 'trace_start_ambiguous',\n message: 'Operation selector matched multiple handler-only executable scopes',\n selectorKind: 'operation',\n normalizedSelectorValue: requested,\n resolutionStage: 'handler',\n resolutionStatus: 'ambiguous_handler_operation',\n candidates: projection.items,\n candidateCount: projection.totalCount,\n shownCandidateCount: projection.shownCount,\n omittedCandidateCount: projection.omittedCount,\n selectorSuggestions: suggestionProjection.items,\n selectorSuggestionCount: suggestionProjection.totalCount,\n shownSelectorSuggestionCount: suggestionProjection.shownCount,\n omittedSelectorSuggestionCount: suggestionProjection.omittedCount,\n remediation: 'Select one handler class explicitly; no operation was chosen automatically.',\n }] };\n}\n\nfunction implementationHandlerRows(\n db: Db,\n repoId: number | undefined,\n servicePath: string,\n operation: string,\n workspaceId: number | undefined,\n): HandlerSelectorRow[] {\n return db.prepare(`SELECT DISTINCT hc.repo_id repoId,\n hc.source_file sourceFile,hm.id methodId,sym.id symbolId\n FROM cds_services svc JOIN cds_operations op ON op.service_id=svc.id\n JOIN repositories r ON r.id=svc.repo_id\n JOIN graph_edges edge ON edge.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER'\n AND edge.status='resolved' AND edge.from_kind='operation'\n AND edge.from_id=CAST(op.id AS TEXT)\n JOIN handler_methods hm ON hm.id=CAST(edge.to_id AS INTEGER)\n JOIN handler_classes hc ON hc.id=hm.handler_class_id\n LEFT JOIN symbols sym ON sym.repo_id=hc.repo_id\n AND sym.source_file=hc.source_file\n AND sym.qualified_name=hc.class_name || '.' || hm.method_name\n AND sym.start_line=hm.source_line\n WHERE (? IS NULL OR r.workspace_id=?)\n AND (? IS NULL OR svc.repo_id=?) AND svc.service_path=?\n AND (op.operation_path=? OR op.operation_name=?)\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.handlerKind'),\n CASE WHEN hm.decorator_kind='Event' THEN 'event'\n WHEN hm.decorator_kind IN ('Action','Func','On') THEN 'operation'\n ELSE 'unsupported' END)='operation'\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.executable'),\n CASE WHEN hm.decorator_kind IN ('Action','Func','On')\n THEN 1 ELSE 0 END)=1\n ORDER BY hc.repo_id,hc.id,hm.id`).all(\n workspaceId, workspaceId, repoId, repoId,\n servicePath, operation, operation,\n ) as HandlerSelectorRow[];\n}\n\nfunction handlerClassScope(\n rows: HandlerSelectorRow[],\n requested: string,\n): SelectorSourceScope {\n const ambiguity = handlerSelectorAmbiguity(rows, requested, 'class');\n if (ambiguity) return { diagnostics: [ambiguity] };\n const executable = rows.filter((row) => typeof row.symbolId === 'number');\n const repoId = numericValue(rows[0]?.repoId);\n if (executable.length > 0) {\n const scope = executableScope(executable, repoId);\n const warning = executable.some((row) => typeof row.methodId === 'number')\n ? handlerDecoratorsNotIndexedDiagnostic(rows[0])\n : handlerMethodsNotIndexedDiagnostic(rows[0]);\n return warning ? { ...scope, diagnostics: [warning] } : scope;\n }\n const first = rows[0];\n return {\n repoId,\n diagnostics: [handlerMethodsNotIndexedDiagnostic(first)],\n };\n}\n\nfunction handlerMethodScope(\n rows: HandlerSelectorRow[],\n fallbackRepoId: number | undefined,\n requested: string,\n): SelectorSourceScope {\n const ambiguity = handlerSelectorAmbiguity(rows, requested, 'method');\n return ambiguity\n ? { diagnostics: [ambiguity] }\n : executableScope(rows, fallbackRepoId);\n}\n\nfunction handlerSelectorAmbiguity(\n rows: HandlerSelectorRow[],\n requested: string,\n matchKind: 'class' | 'method',\n): Record<string, unknown> | undefined {\n const candidates = handlerSelectorCandidates(rows, matchKind);\n if (candidates.length < 2) return undefined;\n const repoCounts = new Map<string, number>();\n for (const candidate of candidates) {\n if (typeof candidate.repoName !== 'string') continue;\n repoCounts.set(\n candidate.repoName,\n (repoCounts.get(candidate.repoName) ?? 0) + 1,\n );\n }\n const suggestions = candidates.flatMap((candidate) => {\n const repoName = typeof candidate.repoName === 'string'\n ? candidate.repoName\n : undefined;\n if (repoName && repoCounts.get(repoName) === 1)\n return [`--repo ${repoName} --handler ${requested}`];\n if (matchKind === 'method' && typeof candidate.className === 'string')\n return [`${repoName ? `--repo ${repoName} ` : ''}--handler ${candidate.className}`];\n return [];\n });\n const projection = boundedSelectorCandidates(candidates);\n const suggestionProjection = boundedSelectorSuggestions(suggestions);\n return {\n severity: 'warning',\n code: 'trace_start_ambiguous',\n message: 'Handler selector matched multiple executable scopes and was not selected automatically',\n selectorKind: 'handler',\n requestedHandler: requested,\n resolutionStage: 'handler',\n resolutionStatus: 'ambiguous_handler',\n candidates: projection.items,\n candidateCount: projection.totalCount,\n shownCandidateCount: projection.shownCount,\n omittedCandidateCount: projection.omittedCount,\n selectorSuggestions: suggestionProjection.items,\n selectorSuggestionCount: suggestionProjection.totalCount,\n shownSelectorSuggestionCount: suggestionProjection.shownCount,\n omittedSelectorSuggestionCount: suggestionProjection.omittedCount,\n remediation: suggestions.length > 0\n ? 'Use one of the scoped handler selectors shown.'\n : 'No current CLI selector uniquely identifies these duplicate handler classes.',\n };\n}\n\nfunction handlerSelectorCandidates(\n rows: HandlerSelectorRow[],\n matchKind: 'class' | 'method',\n): Array<Record<string, unknown>> {\n const candidates = new Map<string, Record<string, unknown>>();\n for (const row of rows) {\n const identity = matchKind === 'class'\n ? `class:${String(row.handlerClassId)}`\n : `method:${String(row.repoId)}:${String(row.symbolId ?? row.methodId)}`;\n candidates.set(identity, {\n handlerClassId: row.handlerClassId,\n repoId: row.repoId,\n repoName: row.repoName,\n className: row.className,\n sourceFile: row.sourceFile,\n sourceLine: row.sourceLine,\n matchKind,\n });\n }\n return [...candidates.values()].sort((left, right) =>\n String(left.repoName ?? '').localeCompare(String(right.repoName ?? ''))\n || String(left.className ?? '').localeCompare(String(right.className ?? ''))\n || String(left.sourceFile ?? '').localeCompare(String(right.sourceFile ?? '')));\n}\n\nfunction executableScope(\n rows: HandlerSelectorRow[],\n fallbackRepoId: number | undefined,\n): SelectorSourceScope {\n const files = rows.flatMap((row) => row.sourceFile ? [row.sourceFile] : []);\n const symbols = rows.flatMap((row) => typeof row.symbolId === 'number'\n ? [row.symbolId] : []);\n if (files.length === 0 || symbols.length === 0) return { repoId: fallbackRepoId };\n return {\n files: new Set(files),\n symbols: new Set(symbols),\n repoId: numericValue(rows[0]?.repoId) ?? fallbackRepoId,\n };\n}\n\nfunction handlerMethodsNotIndexedDiagnostic(\n row: HandlerSelectorRow | undefined,\n): Record<string, unknown> {\n return {\n severity: 'warning',\n code: 'handler_methods_not_indexed',\n message: `Handler class ${row?.className ?? 'unknown'} has no indexed executable methods`,\n selectorKind: 'handler',\n className: row?.className,\n sourceFile: row?.sourceFile,\n sourceLine: row?.sourceLine,\n observedDecoratorNames: stringEvidenceArray(\n row?.classEvidence, 'observedDecoratorNames',\n ),\n unsupportedDecoratorNames: stringEvidenceArray(\n row?.classEvidence, 'unsupportedDecoratorNames',\n ),\n remediation: 'Use a supported CAP handler decorator on at least one class method and re-index the workspace.',\n };\n}\n\nfunction handlerDecoratorsNotIndexedDiagnostic(\n row: HandlerSelectorRow | undefined,\n): Record<string, unknown> | undefined {\n const names = stringEvidenceArray(\n row?.classEvidence, 'unsupportedDecoratorNames',\n );\n const methods = arrayEvidence(row?.classEvidence, 'unsupportedMethods');\n if (names.length === 0 && methods.length === 0) return undefined;\n return {\n severity: 'warning',\n code: 'handler_decorators_not_indexed',\n message: `Handler class ${row?.className ?? 'unknown'} contains methods that were not indexed`,\n selectorKind: 'handler',\n className: row?.className,\n sourceFile: row?.sourceFile,\n sourceLine: row?.sourceLine,\n unsupportedDecoratorNames: names,\n unsupportedMethods: methods,\n remediation: 'Use a supported CAP handler decorator shape and re-index the workspace.',\n };\n}\n\nfunction evidenceRecord(\n evidenceJson: string | null | undefined,\n): Record<string, unknown> {\n if (!evidenceJson) return {};\n try {\n const parsed = JSON.parse(evidenceJson) as unknown;\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : {};\n } catch {\n return {};\n }\n}\n\nfunction stringEvidenceArray(\n evidenceJson: string | null | undefined,\n key: string,\n): string[] {\n const value = evidenceRecord(evidenceJson)[key];\n return Array.isArray(value)\n ? [...new Set(value.filter((item): item is string =>\n typeof item === 'string'))].sort()\n : [];\n}\n\nfunction arrayEvidence(\n evidenceJson: string | null | undefined,\n key: string,\n): Array<Record<string, unknown>> {\n const value = evidenceRecord(evidenceJson)[key];\n return Array.isArray(value)\n ? value.filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === 'object' && !Array.isArray(item)))\n : [];\n}\n\nfunction numericValue(value: number | null | undefined): number | undefined {\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction normalizeOperation(value: string | undefined): string | undefined {\n if (!value) return undefined;\n return value.startsWith('/') ? value.slice(1) : value;\n}\nexport function ambiguousStartDiagnostic(\n requested: string,\n candidates: Array<Record<string, unknown>>,\n message: string,\n): Record<string, unknown> {\n const serviceSuggestions = [...new Set(candidates\n .flatMap((row) => typeof row.servicePath === 'string'\n ? [`--service ${row.servicePath}`]\n : []))].sort();\n const projection = boundedSelectorCandidates(candidates);\n const serviceProjection = boundedSelectorSuggestions(serviceSuggestions);\n const selectorProjection = boundedSelectorSuggestions(fullSelectorSuggestions(candidates));\n return {\n severity: 'warning',\n code: 'trace_start_ambiguous',\n message,\n normalizedSelectorValue: requested,\n resolutionStage: 'operation',\n resolutionStatus: 'ambiguous_operation',\n candidates: projection.items,\n candidateCount: projection.totalCount,\n shownCandidateCount: projection.shownCount,\n omittedCandidateCount: projection.omittedCount,\n serviceSuggestions: serviceProjection.items,\n serviceSuggestionCount: serviceProjection.totalCount,\n shownServiceSuggestionCount: serviceProjection.shownCount,\n omittedServiceSuggestionCount: serviceProjection.omittedCount,\n selectorSuggestions: selectorProjection.items,\n selectorSuggestionCount: selectorProjection.totalCount,\n shownSelectorSuggestionCount: selectorProjection.shownCount,\n omittedSelectorSuggestionCount: selectorProjection.omittedCount,\n };\n}\n\nfunction boundedSelectorCandidates(\n candidates: Array<Record<string, unknown>>,\n): BoundedProjection<Record<string, unknown>> {\n return projectBounded(candidates, (left, right) =>\n String(left.repoName ?? '').localeCompare(String(right.repoName ?? ''))\n || String(left.servicePath ?? '').localeCompare(String(right.servicePath ?? ''))\n || String(left.className ?? '').localeCompare(String(right.className ?? ''))\n || String(left.sourceFile ?? '').localeCompare(String(right.sourceFile ?? ''))\n || Number(left.sourceLine ?? 0) - Number(right.sourceLine ?? 0)\n || Number(left.handlerClassId ?? left.operationId ?? 0)\n - Number(right.handlerClassId ?? right.operationId ?? 0));\n}\n\nfunction boundedSelectorSuggestions(\n suggestions: string[],\n): BoundedProjection<string> {\n return projectBounded([...new Set(suggestions)], (left, right) =>\n left.localeCompare(right));\n}\nfunction fullSelectorSuggestions(\n candidates: Array<Record<string, unknown>>,\n): string[] {\n const includeRepo = new Set(candidates.map((row) => row.repoName)).size > 1;\n return [...new Set(candidates.flatMap((row) => {\n if (typeof row.servicePath !== 'string'\n || typeof row.operationPath !== 'string') return [];\n const repoSelector = includeRepo && typeof row.repoName === 'string'\n ? `--repo ${row.repoName} `\n : '';\n return [\n `${repoSelector}--service ${row.servicePath} --path ${row.operationPath}`,\n ];\n }))].sort();\n}\n","import type { Db } from '../db/connection.js';\nimport {\n extractPlaceholders,\n matchRuntimeTemplate,\n} from '../linker/dynamic-edge-resolver.js';\nimport type { OperationTarget } from '../linker/service-resolver.js';\n\nexport function dynamicCandidateTargets(\n db: Db,\n effectiveOperationPath: string | undefined,\n originalOperationPath: string | undefined,\n embedded: unknown,\n workspaceId: number | undefined,\n requireCanonical: boolean,\n): OperationTarget[] {\n const canonical = queryOperationTargets(\n db, effectiveOperationPath, originalOperationPath, workspaceId,\n );\n if (canonical.length > 0 || requireCanonical) return canonical;\n return targetsFromEvidence(embedded);\n}\n\nfunction targetsFromEvidence(value: unknown): OperationTarget[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((item): OperationTarget[] => {\n const row = record(item);\n const operationId = numberValue(row.operationId);\n const repoName = stringValue(row.repoName);\n const servicePath = stringValue(row.servicePath);\n const operationPath = stringValue(row.operationPath);\n const operationName = stringValue(row.operationName) ?? operationPath?.replace(/^\\//, '');\n if (operationId === undefined || !repoName || !servicePath || !operationPath || !operationName)\n return [];\n return [{\n operationId,\n repoId: numberValue(row.repoId),\n repoName,\n packageName: stringValue(row.packageName),\n serviceName: stringValue(row.serviceName) ?? '',\n qualifiedName: stringValue(row.qualifiedName) ?? '',\n servicePath,\n operationPath,\n operationName,\n sourceFile: stringValue(row.sourceFile) ?? '',\n sourceLine: numberValue(row.sourceLine) ?? 0,\n score: numberValue(row.score) ?? 0,\n reasons: stringArray(row.reasons),\n }];\n });\n}\n\nfunction queryOperationTargets(\n db: Db,\n effectiveOperationPath: string | undefined,\n originalOperationPath: string | undefined,\n workspaceId: number | undefined,\n): OperationTarget[] {\n const operationPath = effectiveOperationPath ?? originalOperationPath;\n if (!operationPath) return [];\n if (extractPlaceholders(operationPath).length > 0)\n return templateOperationTargets(db, operationPath, workspaceId);\n return exactOperationTargets(db, operationPath, workspaceId);\n}\n\nfunction exactOperationTargets(\n db: Db,\n operationPath: string,\n workspaceId: number | undefined,\n): OperationTarget[] {\n const simple = operationPath.replace(/^\\//, '').split('.').at(-1) ?? operationPath;\n const rows = recordRows(db.prepare(\n `SELECT o.id operationId,r.id repoId,r.name repoName,r.package_name packageName,\n s.service_name serviceName,s.qualified_name qualifiedName,s.service_path servicePath,\n o.operation_path operationPath,o.operation_name operationName,o.source_file sourceFile,\n o.source_line sourceLine FROM cds_operations o\n JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id\n WHERE (? IS NULL OR r.workspace_id=?)\n AND (o.operation_path IN (?,?) OR o.operation_name=?)\n ORDER BY r.name,s.service_path,o.operation_name,o.id`,\n ).all(workspaceId, workspaceId, operationPath, `/${simple}`, simple));\n return rows.flatMap(targetFromRow);\n}\n\nfunction templateOperationTargets(\n db: Db,\n operationTemplate: string,\n workspaceId: number | undefined,\n): OperationTarget[] {\n const rows = recordRows(db.prepare(\n `SELECT o.id operationId,r.id repoId,r.name repoName,r.package_name packageName,\n s.service_name serviceName,s.qualified_name qualifiedName,s.service_path servicePath,\n o.operation_path operationPath,o.operation_name operationName,o.source_file sourceFile,\n o.source_line sourceLine FROM cds_operations o\n JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id\n WHERE (? IS NULL OR r.workspace_id=?)\n ORDER BY r.name,s.service_path,o.operation_name,o.id`,\n ).all(workspaceId, workspaceId));\n return rows.flatMap((row) => {\n const operationPath = stringValue(row.operationPath);\n return matchRuntimeTemplate(operationTemplate, operationPath)\n ? targetFromRow(row)\n : [];\n });\n}\n\nfunction targetFromRow(row: Record<string, unknown>): OperationTarget[] {\n const operationId = numberValue(row.operationId);\n const repoName = stringValue(row.repoName);\n const servicePath = stringValue(row.servicePath);\n const operationPath = stringValue(row.operationPath);\n const operationName = stringValue(row.operationName);\n if (operationId === undefined || !repoName || !servicePath || !operationPath || !operationName)\n return [];\n return [{\n operationId,\n repoId: numberValue(row.repoId),\n repoName,\n packageName: stringValue(row.packageName),\n serviceName: stringValue(row.serviceName) ?? '',\n qualifiedName: stringValue(row.qualifiedName) ?? '',\n servicePath,\n operationPath,\n operationName,\n sourceFile: stringValue(row.sourceFile) ?? '',\n sourceLine: numberValue(row.sourceLine) ?? 0,\n score: 0.2,\n reasons: ['operation_path_match'],\n }];\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\n}\n\nfunction recordRows(value: unknown): Array<Record<string, unknown>> {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n","import type { Db } from '../db/connection.js';\nimport { scanPlaceholders } from '../utils/001-placeholders.js';\nimport type {\n DynamicTargetCandidate,\n DynamicTemplates,\n DynamicVariableProvenance,\n} from './000-dynamic-target-types.js';\n\ninterface RouteImplementationEvidence {\n routeRepoId?: number;\n handlerRepo?: string;\n operationProvenance?: string;\n baseOperationId?: number;\n edgeStatus?: string;\n}\n\ninterface IdentityProposal {\n operationId: number;\n key: string;\n value: string;\n normalizedIdentity: string;\n provenance: DynamicVariableProvenance;\n}\n\ninterface RepositoryIdentity {\n repoId: number;\n repoName: string;\n packageName?: string;\n}\n\ninterface WorkspaceIdentityMatch {\n ownerKey: string;\n key: string;\n value: string;\n normalizedIdentity: string;\n}\n\nexport interface IdentityDerivation {\n operationId: number;\n key: string;\n value: string;\n provenance: DynamicVariableProvenance;\n}\n\nexport function uniqueIdentityDerivations(\n db: Db,\n candidates: DynamicTargetCandidate[],\n templates: DynamicTemplates,\n): IdentityDerivation[] {\n const identities = workspaceIdentities(db, candidates);\n const proposals = candidates.flatMap((candidate) => {\n const implementation = routeImplementationEvidence(\n db, candidate.candidateOperationId,\n );\n const identity = identities.find((item) => item.repoId === candidate.repoId);\n if (!identity || !implementation || !routeOwnerAgrees(candidate, implementation))\n return [];\n return identityProposals(candidate, identity, templates, implementation);\n });\n const matches = workspaceIdentityMatches(identities, templates);\n const competing = competingIdentityKeys(matches);\n const duplicates = duplicateNormalizedIdentities(identities);\n return proposals\n .filter((proposal) => !competing.has(`${proposal.key}:${proposal.value}`))\n .filter((proposal) => !duplicates.has(proposal.normalizedIdentity))\n .map((proposal) => ({\n operationId: proposal.operationId,\n key: proposal.key,\n value: proposal.value,\n provenance: proposal.provenance,\n }));\n}\n\nfunction identityProposals(\n candidate: DynamicTargetCandidate,\n identity: RepositoryIdentity,\n templates: DynamicTemplates,\n implementation: RouteImplementationEvidence,\n): IdentityProposal[] {\n const routeTemplates = [templates.alias, templates.destination]\n .filter((value): value is string => Boolean(value));\n const identities = [\n { name: identity.packageName, sourceKind: 'package_identity', npmPackage: true },\n { name: identity.repoName, sourceKind: 'repository_identity', npmPackage: false },\n ].filter((item): item is {\n name: string; sourceKind: string; npmPackage: boolean;\n } => Boolean(item.name));\n const proposals = routeTemplates.flatMap((template) =>\n identities.flatMap((identity) =>\n proposalForIdentity(\n candidate, template, identity.name, identity.sourceKind,\n identity.npmPackage, implementation,\n )));\n return deduplicateProposals(proposals);\n}\n\nfunction proposalForIdentity(\n candidate: DynamicTargetCandidate,\n template: string,\n identity: string,\n sourceKind: string,\n npmPackage: boolean,\n implementation: RouteImplementationEvidence,\n): IdentityProposal[] {\n const match = matchIdentityTemplate(template, identity, npmPackage);\n if (!match) return [];\n return [{\n operationId: candidate.candidateOperationId,\n key: match.key,\n value: match.value,\n normalizedIdentity: match.normalizedIdentity,\n provenance: {\n sourceKind,\n value: match.value,\n rule: 'exact_normalized_identity_template_match',\n template,\n matchedName: identity,\n normalizedForm: match.normalizedIdentity,\n sourceRepo: candidate.repoName,\n routeOwner: candidate.repoName,\n candidateOperationId: candidate.candidateOperationId,\n effectiveBaseOperationId: implementation.baseOperationId,\n candidateOperationProvenance: implementation.operationProvenance,\n implementationEdgeStatus: implementation.edgeStatus,\n implementationHandlerRepo: implementation.handlerRepo,\n },\n }];\n}\n\nfunction matchIdentityTemplate(\n template: string,\n identity: string,\n npmPackage: boolean,\n): { key: string; value: string; normalizedIdentity: string } | undefined {\n const matches = scanPlaceholders(template);\n const matchSpan = matches[0];\n if (matches.length !== 1 || !matchSpan?.key) return undefined;\n const placeholder = template.slice(matchSpan.start, matchSpan.end);\n const sentinel = 'dynamic_placeholder_token';\n const normalizedTemplate = normalizeIdentity(template.replace(placeholder, sentinel));\n const [prefix, suffix, extra] = normalizedTemplate.split(sentinel);\n if (!prefix || !suffix || extra !== undefined) return undefined;\n const normalizedIdentity = normalizeIdentity(identity, npmPackage);\n const match = new RegExp(`^${escapeRegex(prefix)}([a-z0-9]+)${escapeRegex(suffix)}$`)\n .exec(normalizedIdentity);\n if (!match?.[1]) return undefined;\n return { key: matchSpan.key.trim(), value: match[1], normalizedIdentity };\n}\n\nfunction competingIdentityKeys(\n proposals: Array<{ key: string; value: string; ownerKey: string }>,\n): Set<string> {\n const owners = new Map<string, Set<string>>();\n for (const proposal of proposals) {\n const key = `${proposal.key}:${proposal.value}`;\n owners.set(key, new Set([...(owners.get(key) ?? []), proposal.ownerKey]));\n }\n return new Set([...owners.entries()]\n .filter(([, repos]) => repos.size > 1)\n .map(([key]) => key));\n}\n\nfunction duplicateNormalizedIdentities(\n identities: RepositoryIdentity[],\n): Set<string> {\n const owners = new Map<string, Set<string>>();\n for (const identity of identities) {\n for (const [name, npmPackage] of [\n [identity.packageName, true],\n [identity.repoName, false],\n ] as const) {\n if (!name) continue;\n const normalized = normalizeIdentity(name, npmPackage);\n owners.set(normalized, new Set([\n ...(owners.get(normalized) ?? []),\n `repository:${identity.repoId}`,\n ]));\n }\n }\n return new Set([...owners.entries()]\n .filter(([, repos]) => repos.size > 1)\n .map(([identity]) => identity));\n}\n\nfunction workspaceIdentityMatches(\n identities: RepositoryIdentity[],\n templates: DynamicTemplates,\n): WorkspaceIdentityMatch[] {\n const routeTemplates = [templates.alias, templates.destination]\n .filter((value): value is string => Boolean(value));\n return identities.flatMap((identity) => {\n const names: Array<{ name?: string; npmPackage: boolean }> = [\n { name: identity.packageName, npmPackage: true },\n { name: identity.repoName, npmPackage: false },\n ];\n return routeTemplates.flatMap((template) =>\n names.flatMap(({ name, npmPackage }) => {\n if (!name) return [];\n const match = matchIdentityTemplate(template, name, npmPackage);\n return match ? [{\n ownerKey: `repository:${identity.repoId}`,\n key: match.key,\n value: match.value,\n normalizedIdentity: match.normalizedIdentity,\n }] : [];\n }));\n });\n}\n\nfunction workspaceIdentities(\n db: Db,\n candidates: DynamicTargetCandidate[],\n): RepositoryIdentity[] {\n const repoIds = [...new Set(candidates.flatMap((candidate) =>\n candidate.repoId === undefined ? [] : [candidate.repoId]))].sort((a, b) => a - b);\n if (repoIds.length === 0) return [];\n const placeholders = repoIds.map(() => '?').join(',');\n const rows = db.prepare(`SELECT id repoId,name repoName,package_name packageName\n FROM repositories WHERE workspace_id IN (\n SELECT DISTINCT workspace_id FROM repositories WHERE id IN (${placeholders})\n ) ORDER BY workspace_id,name,absolute_path,id`).all(...repoIds);\n return rows.flatMap((row): RepositoryIdentity[] => {\n const repoId = numberValue(row.repoId);\n const repoName = stringValue(row.repoName);\n return repoId === undefined || !repoName ? [] : [{\n repoId,\n repoName,\n packageName: stringValue(row.packageName),\n }];\n });\n}\n\nfunction deduplicateProposals(rows: IdentityProposal[]): IdentityProposal[] {\n const sorted = [...rows].sort((left, right) =>\n left.operationId - right.operationId\n || left.key.localeCompare(right.key)\n || left.value.localeCompare(right.value)\n || left.provenance.sourceKind.localeCompare(right.provenance.sourceKind));\n const seen = new Set<string>();\n return sorted.filter((row) => {\n const key = [row.operationId, row.key, row.value, row.normalizedIdentity].join(':');\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction routeOwnerAgrees(\n candidate: DynamicTargetCandidate,\n implementation: RouteImplementationEvidence | undefined,\n): boolean {\n return candidate.repoId !== undefined\n && implementation?.routeRepoId === candidate.repoId\n && implementation.edgeStatus === 'resolved'\n && candidate.viable\n && candidate.reasons.includes('service_path_template_match');\n}\n\nfunction routeImplementationEvidence(\n db: Db,\n operationId: number,\n): RouteImplementationEvidence | undefined {\n const rows = db.prepare(\n `SELECT s.repo_id routeRepoId,o.provenance operationProvenance,\n o.base_operation_id baseOperationId,e.status edgeStatus,\n r.name handlerRepo\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id\n JOIN graph_edges e ON e.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER'\n AND e.from_kind='operation' AND e.from_id=CAST(o.id AS TEXT)\n JOIN handler_methods hm ON hm.id=CAST(e.to_id AS INTEGER)\n JOIN handler_classes hc ON hc.id=hm.handler_class_id\n JOIN repositories r ON r.id=hc.repo_id\n WHERE e.edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND e.status='resolved'\n AND o.id=?\n ORDER BY e.id,hm.id`,\n ).all(String(operationId));\n if (rows.length !== 1) return undefined;\n const row = rows[0];\n if (!row) return undefined;\n return {\n routeRepoId: numberValue(row.routeRepoId),\n handlerRepo: stringValue(row.handlerRepo),\n operationProvenance: stringValue(row.operationProvenance),\n baseOperationId: numberValue(row.baseOperationId),\n edgeStatus: stringValue(row.edgeStatus),\n };\n}\n\nfunction normalizeIdentity(value: string, npmPackage = false): string {\n const unscoped = npmPackage && /^@[^/]+\\/[^/]+$/.test(value)\n ? value.slice(value.indexOf('/') + 1)\n : value;\n return unscoped\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|(?<!_)_+$/g, '');\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","import type { Db } from '../db/connection.js';\nimport {\n projectBounded,\n type BoundedProjection,\n} from '../utils/000-bounded-projection.js';\nimport type { DynamicVariableProvenance } from './000-dynamic-target-types.js';\n\nexport interface DynamicReferenceRow {\n bindingId?: number;\n alias?: string;\n aliasExpr?: string;\n destination?: string;\n servicePath?: string;\n sourceKind: 'service_binding' | 'cds_require';\n selection: 'selected_binding' | 'selected_binding_require' | 'fallback';\n repoName: string;\n sourceFile?: string;\n sourceLine?: number;\n helperChain?: unknown;\n}\n\nexport interface DynamicRoutingContext {\n outboundCallId?: number;\n callerRepoId?: number;\n callerRepo?: string;\n selectedBindingId?: number;\n bindingResolutionStatus: string;\n selectedBinding?: DynamicReferenceRow;\n bindingAlternatives: Array<Record<string, unknown>>;\n bindingAlternativeCount: number;\n shownBindingAlternativeCount: number;\n omittedBindingAlternativeCount: number;\n references: DynamicReferenceRow[];\n fallbackUsed: boolean;\n}\n\ninterface SelectedDynamicReference extends DynamicReferenceRow {\n outboundCallId: number;\n callerRepoId: number;\n}\n\nexport function dynamicRoutingContext(\n db: Db,\n workspaceId: number | undefined,\n evidence: Record<string, unknown>,\n): DynamicRoutingContext {\n const selected = selectedBinding(db, workspaceId, evidence);\n const persisted = persistedBindingResolution(evidence);\n const alternatives = boundedAlternatives(\n persisted.candidates,\n persisted.candidateCount,\n );\n if (selected) {\n const requires = exactRequireReferences(db, workspaceId, selected);\n return {\n ...contextBase(selected, persisted.status, alternatives),\n selectedBinding: selected,\n references: [selected, ...requires],\n fallbackUsed: false,\n };\n }\n const callerRepoId = numberValue(evidence.repoId);\n const callerRepo = stringValue(evidence.repo);\n return {\n outboundCallId: numberValue(evidence.outboundCallId ?? evidence.callId),\n callerRepoId,\n callerRepo,\n bindingResolutionStatus: persisted.status,\n bindingAlternatives: alternatives.items,\n bindingAlternativeCount: alternatives.totalCount,\n shownBindingAlternativeCount: alternatives.shownCount,\n omittedBindingAlternativeCount: alternatives.omittedCount,\n references: fallbackReferences(db, workspaceId, callerRepoId, callerRepo),\n fallbackUsed: true,\n };\n}\n\nexport function dynamicReferenceProvenance(\n reference: DynamicReferenceRow,\n kind: 'alias' | 'destination',\n template: string,\n value: string,\n): DynamicVariableProvenance {\n const sourceKind = reference.selection === 'selected_binding'\n ? `selected_binding.${kind}`\n : reference.selection === 'selected_binding_require'\n ? `selected_binding_require.${kind}`\n : `${reference.sourceKind}.${kind}`;\n return {\n sourceKind,\n value,\n rule: 'exact_indexed_reference_template_match',\n template,\n sourceRepo: reference.repoName,\n sourceFile: reference.sourceFile,\n sourceLine: reference.sourceLine,\n selection: reference.selection,\n bindingId: reference.bindingId,\n };\n}\n\nfunction contextBase(\n selected: SelectedDynamicReference,\n status: string,\n alternatives: ReturnType<typeof boundedAlternatives>,\n): Omit<DynamicRoutingContext, 'selectedBinding' | 'references' | 'fallbackUsed'> {\n return {\n outboundCallId: selected.outboundCallId,\n callerRepoId: selected.callerRepoId,\n callerRepo: selected.repoName,\n selectedBindingId: selected.bindingId,\n bindingResolutionStatus: status,\n bindingAlternatives: alternatives.items,\n bindingAlternativeCount: alternatives.totalCount,\n shownBindingAlternativeCount: alternatives.shownCount,\n omittedBindingAlternativeCount: alternatives.omittedCount,\n };\n}\n\nfunction selectedBinding(\n db: Db,\n workspaceId: number | undefined,\n evidence: Record<string, unknown>,\n): SelectedDynamicReference | undefined {\n const callId = numberValue(evidence.outboundCallId ?? evidence.callId);\n if (callId === undefined) return undefined;\n const row = db.prepare(`SELECT c.id outboundCallId,c.repo_id callerRepoId,r.name repoName,\n b.id bindingId,b.alias,b.alias_expr aliasExpr,b.destination_expr destination,\n b.service_path_expr servicePath,b.source_file sourceFile,b.source_line sourceLine,\n b.helper_chain_json helperChainJson\n FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id\n JOIN service_bindings b ON b.id=c.service_binding_id AND b.repo_id=c.repo_id\n WHERE c.id=? AND (? IS NULL OR r.workspace_id=?)`).get(\n callId, workspaceId, workspaceId,\n );\n return selectedReferenceFromRow(row);\n}\n\nfunction selectedReferenceFromRow(\n row: Record<string, unknown> | undefined,\n): SelectedDynamicReference | undefined {\n const outboundCallId = numberValue(row?.outboundCallId);\n const callerRepoId = numberValue(row?.callerRepoId);\n const reference = referenceFromRow(\n row, 'service_binding', 'selected_binding',\n )[0];\n return reference && outboundCallId !== undefined && callerRepoId !== undefined\n ? { ...reference, outboundCallId, callerRepoId }\n : undefined;\n}\n\nfunction exactRequireReferences(\n db: Db,\n workspaceId: number | undefined,\n selected: SelectedDynamicReference,\n): DynamicReferenceRow[] {\n if (!(selected.aliasExpr ?? selected.alias)) return [];\n const rows = db.prepare(`SELECT req.alias,req.destination,req.service_path servicePath,\n r.name repoName,'package.json' sourceFile,1 sourceLine\n FROM cds_requires req JOIN repositories r ON r.id=req.repo_id\n WHERE req.repo_id=? AND (? IS NULL OR r.workspace_id=?)\n ORDER BY req.alias,req.id`).all(\n selected.callerRepoId, workspaceId, workspaceId,\n );\n return rows.flatMap((row) => referenceFromRow(\n row, 'cds_require', 'selected_binding_require', selected.bindingId,\n ));\n}\n\nfunction fallbackReferences(\n db: Db,\n workspaceId: number | undefined,\n callerRepoId: number | undefined,\n callerRepo: string | undefined,\n): DynamicReferenceRow[] {\n if (callerRepoId === undefined && callerRepo === undefined) return [];\n const rows = db.prepare(`SELECT b.id bindingId,COALESCE(b.alias,b.alias_expr) alias,\n b.alias_expr aliasExpr,b.destination_expr destination,b.service_path_expr servicePath,\n 'service_binding' sourceKind,r.name repoName,b.source_file sourceFile,\n b.source_line sourceLine,b.helper_chain_json helperChainJson,0 sourcePriority\n FROM service_bindings b JOIN repositories r ON r.id=b.repo_id\n WHERE (? IS NULL OR r.workspace_id=?)\n AND ((? IS NOT NULL AND r.id=?) OR (? IS NULL AND r.name=?))\n UNION ALL\n SELECT NULL,req.alias,req.alias,req.destination,req.service_path,\n 'cds_require',r.name,'package.json',1,NULL,1\n FROM cds_requires req JOIN repositories r ON r.id=req.repo_id\n WHERE (? IS NULL OR r.workspace_id=?)\n AND ((? IS NOT NULL AND r.id=?) OR (? IS NULL AND r.name=?))\n ORDER BY sourcePriority,repoName,sourceFile,sourceLine`).all(\n workspaceId, workspaceId, callerRepoId, callerRepoId, callerRepoId, callerRepo,\n workspaceId, workspaceId, callerRepoId, callerRepoId, callerRepoId, callerRepo,\n );\n return rows.flatMap((row) => {\n const sourceKind = row.sourceKind;\n return sourceKind === 'service_binding' || sourceKind === 'cds_require'\n ? referenceFromRow(row, sourceKind, 'fallback')\n : [];\n });\n}\n\nfunction referenceFromRow(\n row: Record<string, unknown> | undefined,\n sourceKind: DynamicReferenceRow['sourceKind'],\n selection: DynamicReferenceRow['selection'],\n bindingId = numberValue(row?.bindingId),\n): DynamicReferenceRow[] {\n const repoName = stringValue(row?.repoName);\n if (!repoName) return [];\n return [{\n bindingId,\n alias: stringValue(row?.alias),\n aliasExpr: stringValue(row?.aliasExpr),\n destination: stringValue(row?.destination),\n servicePath: stringValue(row?.servicePath),\n sourceKind,\n selection,\n repoName,\n sourceFile: stringValue(row?.sourceFile),\n sourceLine: numberValue(row?.sourceLine),\n helperChain: parsedJson(row?.helperChainJson),\n }];\n}\n\nfunction persistedBindingResolution(evidence: Record<string, unknown>): {\n status: string;\n candidates: Array<Record<string, unknown>>;\n candidateCount: number;\n} {\n const outbound = record(evidence.outboundEvidence);\n const resolution = record(outbound.serviceBindingResolution);\n return {\n status: stringValue(resolution.status) ?? 'unknown',\n candidates: recordArray(resolution.candidates),\n candidateCount: numberValue(resolution.candidateCount) ?? 0,\n };\n}\n\nfunction boundedAlternatives(\n rows: Array<Record<string, unknown>>,\n reportedCount: number,\n): BoundedProjection<Record<string, unknown>> {\n const projection = projectBounded(rows, (left, right) =>\n Number(left.bindingId ?? 0) - Number(right.bindingId ?? 0)\n || String(left.sourceFile ?? '').localeCompare(String(right.sourceFile ?? ''))\n || Number(left.sourceLine ?? 0) - Number(right.sourceLine ?? 0));\n const totalCount = Math.max(reportedCount, projection.totalCount);\n return {\n ...projection,\n totalCount,\n omittedCount: Math.max(0, totalCount - projection.shownCount),\n };\n}\n\nfunction parsedJson(value: unknown): unknown {\n if (typeof value !== 'string' || value.length === 0) return undefined;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return undefined;\n }\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : {};\n}\n\nfunction recordArray(value: unknown): Array<Record<string, unknown>> {\n return Array.isArray(value)\n ? value.filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === 'object' && !Array.isArray(item)))\n : [];\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n","import type { Db } from '../db/connection.js';\nimport {\n applyVariables,\n extractPlaceholders,\n matchRuntimeTemplate,\n} from '../linker/dynamic-edge-resolver.js';\nimport { normalizeODataOperationInvocationPath } from '../linker/odata-path-normalizer.js';\nimport type { OperationTarget } from '../linker/service-resolver.js';\nimport type { DynamicMode } from '../types.js';\nimport { dynamicCandidateTargets } from './004-dynamic-candidate-sources.js';\nimport { projectBounded } from '../utils/000-bounded-projection.js';\nimport { uniqueIdentityDerivations } from './001-dynamic-identity.js';\nimport {\n dynamicReferenceProvenance,\n dynamicRoutingContext,\n type DynamicReferenceRow,\n type DynamicRoutingContext,\n} from './003-dynamic-references.js';\nimport type {\n DynamicTargetAnalysis,\n DynamicTargetCandidate,\n DynamicTemplates,\n DynamicVariableProvenance,\n} from './000-dynamic-target-types.js';\nexport type {\n DynamicTargetAnalysis,\n DynamicTargetCandidate,\n} from './000-dynamic-target-types.js';\ntype Templates = DynamicTemplates;\ntype VariableProvenance = DynamicVariableProvenance;\ninterface AnalysisInputs {\n original: Templates;\n effective: Templates;\n required: string[];\n requiredSources: Record<string, string[]>;\n supplied: Record<string, string>;\n order: string[];\n callerRepo?: string;\n callerRepoId?: number;\n routing: DynamicRoutingContext;\n}\n\nexport function analyzeDynamicTargetCandidates(\n db: Db,\n evidence: Record<string, unknown>,\n workspaceId: number | undefined,\n mode: DynamicMode,\n maxCandidates: number,\n): DynamicTargetAnalysis | undefined {\n const inputs = analysisInputs(db, evidence, workspaceId);\n if (inputs.required.length === 0) return undefined;\n const targets = dynamicCandidateTargets(\n db,\n inputs.effective.operationPath,\n inputs.original.operationPath,\n evidence.candidates,\n workspaceId,\n inputs.routing.outboundCallId !== undefined,\n );\n const candidates = buildCandidates(db, targets, inputs.routing.references, inputs);\n applyUniqueIdentityEvidence(db, candidates, inputs);\n finalizeCandidates(candidates, inputs.order);\n const ranked = stableRank(candidates);\n const inference = inferenceDecision(ranked);\n applyModeState(ranked, mode, inference);\n const viable = ranked.filter((candidate) => candidate.viable);\n const rejected = ranked.filter((candidate) => candidate.rejected);\n const shown = viable.slice(0, maxCandidates)\n .map((candidate) => boundedCandidate(candidate, maxCandidates));\n const shownRejected = rejected.slice(0, maxCandidates)\n .map((candidate) => boundedCandidate(candidate, maxCandidates));\n const suggestionProjection = suggestedVarSets(viable, inputs.order, maxCandidates);\n return {\n mode,\n maxCandidates,\n candidateCount: ranked.length,\n viableCandidateCount: viable.length,\n rejectedCandidateCount: rejected.length,\n shownCandidateCount: shown.length,\n omittedCandidateCount: Math.max(0, viable.length - shown.length),\n shownRejectedCandidateCount: shownRejected.length,\n omittedRejectedCandidateCount: Math.max(0, rejected.length - shownRejected.length),\n missingVariables: inputs.required.filter((key) => inputs.supplied[key] === undefined),\n requiredVariables: inputs.required,\n suppliedVariables: inputs.supplied,\n appliedSuppliedVariables: requiredSuppliedVariables(inputs),\n substitutedSignals: inputs.effective,\n candidates: shown,\n shownCandidates: shown,\n rejectedCandidates: shownRejected,\n suggestedVarSets: suggestionProjection.items,\n suggestedVarSetCount: suggestionProjection.totalCount,\n shownSuggestedVarSetCount: suggestionProjection.shownCount,\n omittedSuggestedVarSetCount: suggestionProjection.omittedCount,\n inference,\n routingContext: routingEvidence(inputs.routing),\n };\n}\n\nfunction analysisInputs(\n db: Db,\n evidence: Record<string, unknown>,\n workspaceId: number | undefined,\n): AnalysisInputs {\n const routing = dynamicRoutingContext(db, workspaceId, evidence);\n const supplied = stringRecord(evidence.suppliedRuntimeVariables);\n const original = templatesFromEvidence(evidence, routing);\n const effective = effectiveTemplates(original, supplied);\n const requiredSources = placeholderSources(original);\n const required = Object.keys(requiredSources);\n return {\n original,\n effective,\n required,\n requiredSources,\n supplied,\n order: variableOrder(original, required),\n callerRepo: routing.callerRepo ?? stringValue(evidence.repo),\n callerRepoId: routing.callerRepoId ?? numberValue(evidence.repoId),\n routing,\n };\n}\n\nfunction buildCandidates(\n db: Db,\n targets: OperationTarget[],\n references: DynamicReferenceRow[],\n inputs: AnalysisInputs,\n): DynamicTargetCandidate[] {\n return targets.map((target) => {\n const state = emptyCandidate(target, inputs);\n applyDirectSignal(state, inputs, 'operationPath', target.operationPath, 0.25);\n applyDirectSignal(state, inputs, 'servicePath', target.servicePath, 0.35);\n const matchingReferences = references.filter((reference) =>\n referenceMatchesCandidate(reference, target.servicePath)\n && referenceMatchesSelectedAlias(reference, inputs.routing.selectedBinding));\n const referencesForSignals = fallbackReferencesForCandidate(\n state, matchingReferences, inputs.routing.fallbackUsed,\n );\n applyReferenceSignal(state, inputs, referencesForSignals, 'alias');\n applyReferenceSignal(state, inputs, referencesForSignals, 'destination');\n if (hasResolvedImplementation(db, target.operationId))\n addScore(state, 0.1, 'implementation_edge_resolved');\n return state;\n });\n}\n\nfunction fallbackReferencesForCandidate(\n state: DynamicTargetCandidate,\n references: DynamicReferenceRow[],\n fallbackUsed: boolean,\n): DynamicReferenceRow[] {\n if (!fallbackUsed) return references;\n const unique = uniqueFallbackReferences(references);\n if (unique.length <= 1) return unique;\n addReason(state, 'fallback_reference_ambiguous');\n addInferenceBlock(state, 'fallback_reference_ambiguous');\n return [];\n}\n\nfunction uniqueFallbackReferences(\n references: DynamicReferenceRow[],\n): DynamicReferenceRow[] {\n const seen = new Set<string>();\n return references.filter((reference) => {\n const signature = [\n reference.sourceKind,\n reference.alias,\n reference.destination,\n reference.servicePath,\n ].join('\\0');\n if (seen.has(signature)) return false;\n seen.add(signature);\n return true;\n });\n}\n\nfunction emptyCandidate(\n target: OperationTarget,\n inputs: AnalysisInputs,\n): DynamicTargetCandidate {\n return {\n candidateOperationId: target.operationId,\n repoId: target.repoId,\n repoName: target.repoName,\n packageName: target.packageName ?? undefined,\n serviceName: target.serviceName,\n qualifiedName: target.qualifiedName,\n servicePath: target.servicePath,\n operationPath: target.operationPath,\n operationName: target.operationName,\n sourceFile: target.sourceFile,\n sourceLine: target.sourceLine,\n originalTemplates: inputs.original,\n effectiveValues: inputs.effective,\n requiredVariables: inputs.required,\n requiredVariableSources: inputs.requiredSources,\n suppliedVariables: inputs.supplied,\n completeVariables: { ...inputs.supplied },\n derivedVariables: {},\n derivedVariableSources: {},\n derivationProvenance: {},\n missingVariables: [],\n conflicts: [],\n score: Math.max(0.2, Number(target.score ?? 0)),\n explicitSignalStrength: 0,\n reasons: nonEmptyStrings(target.reasons, ['operation_path_match']),\n rejectedReasons: [],\n inferenceBlockReasons: [],\n viable: true,\n rejected: false,\n selected: false,\n exploratory: false,\n };\n}\n\nfunction applyDirectSignal(\n state: DynamicTargetCandidate,\n inputs: AnalysisInputs,\n kind: 'servicePath' | 'operationPath',\n concrete: string,\n score: number,\n): void {\n const effective = inputs.effective[kind];\n const original = inputs.original[kind];\n if (effective && !matchRuntimeTemplate(effective, concrete)) {\n reject(state, `${signalCode(kind)}_contradicts_runtime_substitution`);\n return;\n }\n if (!effective) return;\n const suppliedKeys = extractPlaceholders(original)\n .filter((key) => inputs.supplied[key] !== undefined);\n state.explicitSignalStrength += suppliedKeys.length;\n const matched = matchRuntimeTemplate(original, concrete) ?? {};\n const fromSelectedBinding = kind === 'servicePath'\n && inputs.routing.selectedBinding !== undefined;\n for (const [key, value] of Object.entries(matched)) {\n addDerivation(state, key, value, {\n sourceKind: fromSelectedBinding\n ? `selected_binding.${signalCode(kind)}_template`\n : `${signalCode(kind)}_template`,\n value,\n rule: fromSelectedBinding\n ? 'exact_selected_binding_template_match'\n : 'exact_template_match',\n template: original,\n sourceRepo: fromSelectedBinding ? inputs.routing.selectedBinding?.repoName : undefined,\n sourceFile: fromSelectedBinding ? inputs.routing.selectedBinding?.sourceFile : undefined,\n sourceLine: fromSelectedBinding ? inputs.routing.selectedBinding?.sourceLine : undefined,\n selection: fromSelectedBinding ? 'selected_binding' : 'call_evidence',\n });\n }\n addScore(state, score, `${signalCode(kind)}_template_match`);\n}\n\nfunction applyReferenceSignal(\n state: DynamicTargetCandidate,\n inputs: AnalysisInputs,\n references: DynamicReferenceRow[],\n kind: 'alias' | 'destination',\n): void {\n const original = inputs.original[kind];\n const effective = inputs.effective[kind];\n if (!original || extractPlaceholders(original).length === 0) return;\n const values = references.flatMap((reference) => {\n const concrete = kind === 'alias' ? reference.alias : reference.destination;\n return isConcrete(concrete) ? [{ reference, concrete }] : [];\n });\n if (effective && extractPlaceholders(effective).length === 0\n && values.length > 0 && !values.some(({ concrete }) => concrete === effective)) {\n reject(state, `${kind}_contradicts_runtime_substitution`);\n }\n let matchedSignal = false;\n for (const { reference, concrete } of values) {\n const matched = matchRuntimeTemplate(original, concrete);\n if (!matched) continue;\n matchedSignal = true;\n for (const [key, value] of Object.entries(matched)) {\n addDerivation(\n state, key, value,\n dynamicReferenceProvenance(reference, kind, original, value),\n );\n }\n }\n if (matchedSignal) {\n state.explicitSignalStrength += extractPlaceholders(original)\n .filter((key) => inputs.supplied[key] !== undefined).length;\n addScore(state, 0.2, `${kind}_template_match`);\n }\n}\n\nfunction applyUniqueIdentityEvidence(\n db: Db,\n candidates: DynamicTargetCandidate[],\n inputs: AnalysisInputs,\n): void {\n for (const derivation of uniqueIdentityDerivations(db, candidates, inputs.original)) {\n const candidate = candidates.find((item) =>\n item.candidateOperationId === derivation.operationId);\n if (!candidate) continue;\n addDerivation(candidate, derivation.key, derivation.value, derivation.provenance);\n addScore(candidate, 0.2, 'exact_identity_template_match');\n }\n}\n\nfunction addDerivation(\n state: DynamicTargetCandidate,\n key: string,\n value: string,\n provenance: VariableProvenance,\n): void {\n const priorProvenance = state.derivationProvenance[key] ?? [];\n state.derivationProvenance[key] = uniqueProvenance([...priorProvenance, provenance]);\n const supplied = state.suppliedVariables[key];\n if (supplied !== undefined && supplied !== value) {\n addConflict(state, key, [supplied, value], 'explicit_value_conflicts_with_derived_value');\n return;\n }\n const prior = state.derivedVariables[key];\n if (prior !== undefined && prior !== value) {\n addConflict(state, key, [prior, value], 'conflicting_strong_derivations');\n return;\n }\n if (supplied === undefined) state.derivedVariables[key] = value;\n state.completeVariables[key] = supplied ?? value;\n state.derivedVariableSources[key] ??= provenance;\n}\n\nfunction addConflict(\n state: DynamicTargetCandidate,\n key: string,\n values: string[],\n reason: string,\n): void {\n const sources = (state.derivationProvenance[key] ?? [])\n .map((item) => item.sourceKind).sort();\n state.conflicts.push({ key, values: [...new Set(values)].sort(), reason, sources });\n reject(state, reason);\n}\n\nfunction uniqueProvenance(rows: VariableProvenance[]): VariableProvenance[] {\n const sorted = [...rows].sort((left, right) =>\n left.sourceKind.localeCompare(right.sourceKind)\n || String(left.matchedName ?? '').localeCompare(String(right.matchedName ?? ''))\n || left.value.localeCompare(right.value));\n const seen = new Set<string>();\n return sorted.filter((row) => {\n const key = JSON.stringify(row);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction finalizeCandidates(candidates: DynamicTargetCandidate[], order: string[]): void {\n for (const candidate of candidates) {\n candidate.missingVariables = order.filter((key) =>\n candidate.completeVariables[key] === undefined);\n candidate.viable = candidate.rejectedReasons.length === 0;\n candidate.rejected = !candidate.viable;\n if (candidate.missingVariables.length === 0 && candidate.viable)\n addScore(candidate, 0.15, 'all_runtime_variables_derived');\n else if (candidate.missingVariables.length > 0)\n addReason(candidate, 'missing_required_runtime_variable');\n candidate.score = Math.max(0, Math.min(1, candidate.score));\n candidate.cli = candidate.missingVariables.length === 0 && candidate.viable\n ? cliFor(candidate.completeVariables, order)\n : undefined;\n }\n}\n\nfunction stableRank(candidates: DynamicTargetCandidate[]): DynamicTargetCandidate[] {\n return [...candidates].sort((left, right) =>\n Number(right.viable) - Number(left.viable)\n || right.score - left.score\n || right.explicitSignalStrength - left.explicitSignalStrength\n || left.repoName.localeCompare(right.repoName)\n || String(left.packageName ?? '').localeCompare(String(right.packageName ?? ''))\n || left.servicePath.localeCompare(right.servicePath)\n || left.operationPath.localeCompare(right.operationPath)\n || left.operationName.localeCompare(right.operationName)\n || left.candidateOperationId - right.candidateOperationId);\n}\n\nfunction inferenceDecision(candidates: DynamicTargetCandidate[]): Record<string, unknown> {\n const viable = candidates.filter((candidate) => candidate.viable);\n const first = viable[0];\n const second = viable[1];\n if (!first || first.missingVariables.length > 0)\n return { status: 'unresolved', reason: 'missing_required_runtime_variable' };\n if (first.inferenceBlockReasons.length > 0)\n return { status: 'unresolved', reason: first.inferenceBlockReasons[0] };\n if (first.score < 0.85)\n return { status: 'unresolved', reason: 'candidate_score_below_inference_threshold' };\n const scoreGap = second\n ? Number((first.score - second.score).toFixed(12))\n : undefined;\n if (second && scoreGap !== undefined && scoreGap <= 0.05) {\n const reason = scoreGap === 0\n ? 'candidate_tied_with_equal_score'\n : 'candidate_within_inference_margin';\n for (const candidate of viable.filter((item) => first.score - item.score <= 0.05))\n addInferenceBlock(candidate, reason);\n return { status: 'ambiguous', reason, scoreGap, requiredMargin: 0.05 };\n }\n return {\n status: 'resolved',\n candidateOperationId: first.candidateOperationId,\n inferredVariables: first.completeVariables,\n score: first.score,\n reasons: first.reasons,\n };\n}\n\nfunction boundedCandidate(\n candidate: DynamicTargetCandidate,\n limit: number,\n): DynamicTargetCandidate {\n const provenanceProjections = Object.fromEntries(\n Object.entries(candidate.derivationProvenance)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, rows]) => [key, projectBounded(rows, compareProvenance, limit)]),\n );\n const derivationProvenance = Object.fromEntries(Object.entries(provenanceProjections)\n .map(([key, projection]) => [key, projection.items]));\n const derivationProvenanceCounts = Object.fromEntries(Object.entries(provenanceProjections)\n .map(([key, projection]) => [key, {\n provenanceCount: projection.totalCount,\n shownProvenanceCount: projection.shownCount,\n omittedProvenanceCount: projection.omittedCount,\n }]));\n const conflicts = projectBounded(candidate.conflicts, compareConflict, limit);\n return {\n ...candidate,\n derivationProvenance,\n derivationProvenanceCounts,\n conflicts: conflicts.items.map(boundedConflict),\n conflictCount: conflicts.totalCount,\n shownConflictCount: conflicts.shownCount,\n omittedConflictCount: conflicts.omittedCount,\n };\n}\n\nfunction compareProvenance(\n left: DynamicVariableProvenance,\n right: DynamicVariableProvenance,\n): number {\n return left.sourceKind.localeCompare(right.sourceKind)\n || String(left.matchedName ?? '').localeCompare(String(right.matchedName ?? ''))\n || left.value.localeCompare(right.value);\n}\n\nfunction compareConflict(\n left: DynamicTargetCandidate['conflicts'][number],\n right: DynamicTargetCandidate['conflicts'][number],\n): number {\n return left.key.localeCompare(right.key)\n || left.reason.localeCompare(right.reason)\n || left.values.join('\\0').localeCompare(right.values.join('\\0'));\n}\n\nfunction boundedConflict(\n conflict: DynamicTargetCandidate['conflicts'][number],\n): DynamicTargetCandidate['conflicts'][number] & Record<string, unknown> {\n const sources = projectBounded(conflict.sources, (left, right) =>\n left.localeCompare(right));\n return {\n ...conflict,\n sources: sources.items,\n sourceCount: sources.totalCount,\n shownSourceCount: sources.shownCount,\n omittedSourceCount: sources.omittedCount,\n };\n}\n\nfunction applyModeState(\n candidates: DynamicTargetCandidate[],\n mode: DynamicMode,\n inference: Record<string, unknown>,\n): void {\n const selectedId = mode === 'infer' && inference.status === 'resolved'\n ? numberValue(inference.candidateOperationId)\n : undefined;\n for (const candidate of candidates) {\n candidate.selected = selectedId === candidate.candidateOperationId;\n candidate.exploratory = mode === 'candidates' && candidate.viable;\n }\n}\n\nfunction suggestedVarSets(\n candidates: DynamicTargetCandidate[],\n order: string[],\n limit: number,\n): ReturnType<typeof projectBounded<{ variables: Record<string, string>; cli: string }>> {\n const seen = new Set<string>();\n const rows: Array<{ variables: Record<string, string>; cli: string }> = [];\n for (const candidate of candidates) {\n if (!candidate.cli || candidate.missingVariables.length > 0) continue;\n if (seen.has(candidate.cli)) continue;\n seen.add(candidate.cli);\n rows.push({ variables: orderedVariables(candidate.completeVariables, order), cli: candidate.cli });\n }\n return projectBounded(rows, (left, right) => left.cli.localeCompare(right.cli), limit);\n}\n\nfunction hasResolvedImplementation(db: Db, operationId: number): boolean {\n return Boolean(db.prepare(\n \"SELECT 1 FROM graph_edges WHERE edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND status='resolved' AND from_kind='operation' AND from_id=? LIMIT 1\",\n ).get(String(operationId)));\n}\nfunction templatesFromEvidence(\n evidence: Record<string, unknown>,\n routing: DynamicRoutingContext,\n): Templates {\n const selected = routing.selectedBinding;\n return {\n servicePath: selected?.servicePath ?? substitutionSignal(evidence, 'servicePath', 'original'),\n operationPath: substitutionSignal(evidence, 'operationPath', 'original'),\n alias: selected?.aliasExpr ?? selected?.alias ?? substitutionSignal(evidence,\n evidence.serviceAliasExpr !== undefined ? 'serviceAliasExpr' : 'serviceAlias', 'original'),\n destination: selected?.destination ?? substitutionSignal(evidence, 'destination', 'original'),\n };\n}\nfunction effectiveTemplates(\n templates: Templates,\n supplied: Record<string, string>,\n): Templates {\n const operationPath = applyVariables(templates.operationPath, supplied);\n return {\n servicePath: applyVariables(templates.servicePath, supplied),\n operationPath: normalizeODataOperationInvocationPath(operationPath)?.normalizedOperationPath\n ?? operationPath,\n alias: applyVariables(templates.alias, supplied),\n destination: applyVariables(templates.destination, supplied),\n };\n}\n\nfunction substitutionSignal(\n evidence: Record<string, unknown>,\n key: string,\n phase: 'original' | 'effective',\n): string | undefined {\n const substitution = record(record(evidence.runtimeSubstitutions)[key]);\n return stringValue(substitution[phase]) ?? stringValue(evidence[key]);\n}\n\nfunction placeholderSources(templates: Templates): Record<string, string[]> {\n const sources: Record<string, string[]> = {};\n for (const [kind, template] of Object.entries(templates)) {\n if (typeof template !== 'string') continue;\n for (const key of extractPlaceholders(template))\n sources[key] = [...new Set([...(sources[key] ?? []), `${kind}:${template}`])].sort();\n }\n return Object.fromEntries(Object.entries(sources).sort(([left], [right]) =>\n left.localeCompare(right)));\n}\n\nfunction variableOrder(templates: Templates, required: string[]): string[] {\n const ordered = [\n templates.servicePath,\n templates.operationPath,\n templates.alias,\n templates.destination,\n ].flatMap((value) => extractPlaceholders(value));\n return [...new Set([...ordered, ...required])];\n}\n\nfunction referenceMatchesCandidate(\n reference: DynamicReferenceRow,\n servicePath: string,\n): boolean {\n return matchRuntimeTemplate(reference.servicePath, servicePath) !== undefined;\n}\n\nfunction referenceMatchesSelectedAlias(\n reference: DynamicReferenceRow,\n selected: DynamicRoutingContext['selectedBinding'],\n): boolean {\n if (reference.selection !== 'selected_binding_require') return true;\n const template = selected?.aliasExpr ?? selected?.alias;\n return matchRuntimeTemplate(template, reference.alias) !== undefined;\n}\n\nfunction cliFor(variables: Record<string, string>, order: string[]): string {\n return order.filter((key) => variables[key] !== undefined)\n .map((key) => `--var ${shellArgument(`${key}=${variables[key]}`)}`).join(' ');\n}\n\nfunction shellArgument(value: string): string {\n return /^[A-Za-z0-9_./:=+-]+$/.test(value)\n ? value\n : `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction orderedVariables(\n variables: Record<string, string>,\n order: string[],\n): Record<string, string> {\n return Object.fromEntries(order.flatMap((key) =>\n variables[key] === undefined ? [] : [[key, variables[key]]]));\n}\n\nfunction addScore(state: DynamicTargetCandidate, amount: number, reason: string): void {\n state.score += amount;\n addReason(state, reason);\n}\n\nfunction addReason(state: DynamicTargetCandidate, reason: string): void {\n if (!state.reasons.includes(reason)) state.reasons.push(reason);\n}\n\nfunction reject(state: DynamicTargetCandidate, reason: string): void {\n rejectReasonOnly(state, reason);\n state.viable = false;\n state.rejected = true;\n}\n\nfunction rejectReasonOnly(state: DynamicTargetCandidate, reason: string): void {\n if (!state.rejectedReasons.includes(reason)) state.rejectedReasons.push(reason);\n}\n\nfunction addInferenceBlock(state: DynamicTargetCandidate, reason: string): void {\n addReason(state, reason);\n if (!state.inferenceBlockReasons.includes(reason))\n state.inferenceBlockReasons.push(reason);\n}\n\nfunction requiredSuppliedVariables(inputs: AnalysisInputs): Record<string, string> {\n return Object.fromEntries(inputs.required.flatMap((key) =>\n inputs.supplied[key] === undefined ? [] : [[key, inputs.supplied[key]]]));\n}\n\nfunction routingEvidence(routing: DynamicRoutingContext): Record<string, unknown> {\n const binding = routing.selectedBinding;\n return {\n outboundCallId: routing.outboundCallId,\n callerRepoId: routing.callerRepoId,\n callerRepo: routing.callerRepo,\n selectedBindingId: routing.selectedBindingId,\n bindingResolutionStatus: routing.bindingResolutionStatus,\n selectedBinding: binding ? {\n bindingId: binding.bindingId,\n alias: binding.alias,\n aliasExpr: binding.aliasExpr,\n destination: binding.destination,\n destinationExpr: binding.destination,\n servicePath: binding.servicePath,\n servicePathExpr: binding.servicePath,\n sourceFile: binding.sourceFile,\n sourceLine: binding.sourceLine,\n helperChain: binding.helperChain,\n } : undefined,\n bindingAlternativeCount: routing.bindingAlternativeCount,\n shownBindingAlternativeCount: routing.shownBindingAlternativeCount,\n omittedBindingAlternativeCount: routing.omittedBindingAlternativeCount,\n bindingAlternatives: routing.bindingAlternatives,\n fallbackUsed: routing.fallbackUsed,\n };\n}\n\nfunction signalCode(kind: 'servicePath' | 'operationPath'): string {\n return kind === 'servicePath' ? 'service_path' : 'operation_path';\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : {};\n}\n\nfunction stringRecord(value: unknown): Record<string, string> {\n const entries = Object.entries(record(value))\n .filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n .sort(([left], [right]) => left.localeCompare(right));\n return Object.fromEntries(entries);\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction nonEmptyStrings(value: unknown, fallback: string[]): string[] {\n const values = stringArray(value).filter((item) => item.length > 0);\n return values.length > 0 ? values : fallback;\n}\n\nfunction isConcrete(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0\n && extractPlaceholders(value).length === 0;\n}\n","import { projectBounded } from '../utils/000-bounded-projection.js';\n\nexport function boundedContextCandidates(values: unknown[]): {\n candidates: Array<Record<string, unknown>>;\n candidateCount: number;\n shownCandidateCount: number;\n omittedCandidateCount: number;\n} {\n const candidates = values.flatMap((value): Array<Record<string, unknown>> => {\n return isRecord(value) ? [value] : [];\n });\n const projection = projectBounded(candidates, (left, right) =>\n Number(right.score ?? 0) - Number(left.score ?? 0)\n || String(left.repoName ?? '').localeCompare(String(right.repoName ?? ''))\n || String(left.servicePath ?? '').localeCompare(String(right.servicePath ?? ''))\n || String(left.sourceFile ?? '').localeCompare(String(right.sourceFile ?? ''))\n || Number(left.sourceLine ?? 0) - Number(right.sourceLine ?? 0)\n || Number(left.bindingId ?? left.operationId ?? 0)\n - Number(right.bindingId ?? right.operationId ?? 0));\n return {\n candidates: projection.items,\n candidateCount: projection.totalCount,\n shownCandidateCount: projection.shownCount,\n omittedCandidateCount: projection.omittedCount,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n","import type { Db } from '../db/connection.js';\nimport { normalizeODataOperationInvocationPath } from '../linker/odata-path-normalizer.js';\nimport { resolveOperation, type OperationResolution } from '../linker/service-resolver.js';\nimport { boundedContextCandidates } from './006-contextual-projection.js';\n\nexport interface ContextBinding {\n bindingId?: number;\n alias?: string;\n aliasExpr?: string;\n destinationExpr?: string;\n servicePathExpr?: string;\n requireServicePath?: string;\n requireDestination?: string;\n effectiveServicePath?: string;\n effectiveDestination?: string;\n sourceFile?: string;\n sourceLine?: number;\n source: string;\n callerArgument?: string;\n callerProperty?: string;\n calleeParameter?: string;\n calleeObjectProperty?: string;\n calleeLocalDestructuredIdentifier?: string;\n parameterPropertyAliasKind?: unknown;\n parameterPropertyAliasLine?: unknown;\n calleeReceiver: string;\n callerSite?: { sourceFile?: string; sourceLine?: number };\n calleeSite?: { sourceFile?: string; sourceLine?: number };\n resolutionStatus?: 'selected' | 'ambiguous';\n bindingCandidates?: Array<Record<string, unknown>>;\n}\n\ninterface ContextualCall {\n id: number;\n call_type: string;\n operation_path_expr?: unknown;\n}\n\ninterface PersistedGraphRow {\n status?: string;\n}\n\nexport interface ContextualGraphRow {\n id: number;\n edge_type: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n confidence: number;\n evidence_json: string;\n status: 'resolved';\n}\n\nexport type ContextualResolutionCategory =\n | 'none'\n | 'dynamic_missing'\n | 'ambiguous_binding'\n | 'ambiguous_operation'\n | 'no_matching_operation'\n | 'other_blocker';\n\nexport interface ContextualRuntimeState {\n category: ContextualResolutionCategory;\n message?: string;\n missingVariables?: string[];\n resolutionStatus?: string;\n phase?: 'before_runtime_substitution';\n}\n\nexport interface ContextualRuntimeResolution {\n row?: ContextualGraphRow;\n evidence?: Record<string, unknown>;\n state: ContextualRuntimeState;\n}\n\nexport function dynamicMissingReason(keys: readonly string[]): string {\n const missing = normalizedKeys(keys);\n return missing.length > 0\n ? `Dynamic target is missing runtime variables: ${missing.join(', ')}`\n : 'Dynamic target still requires runtime variables';\n}\n\nexport function isStructuralContextualBlocker(\n state: ContextualRuntimeState | undefined,\n): boolean {\n return state?.category === 'ambiguous_binding'\n || state?.category === 'ambiguous_operation'\n || state?.category === 'no_matching_operation'\n || state?.category === 'other_blocker';\n}\n\nexport function contextualRuntimeResolution(\n db: Db,\n call: ContextualCall,\n binding: ContextBinding | undefined,\n workspaceId: number | undefined,\n persistedRows: PersistedGraphRow[] = [],\n): ContextualRuntimeResolution {\n if (!binding || call.call_type !== 'remote_action'\n || call.operation_path_expr === undefined || call.operation_path_expr === null)\n return { state: { category: 'none' } };\n if (binding.resolutionStatus === 'ambiguous')\n return ambiguousBindingResolution(binding);\n return selectedBindingResolution(db, call, binding, workspaceId, persistedRows);\n}\n\nfunction ambiguousBindingResolution(\n binding: ContextBinding,\n): ContextualRuntimeResolution {\n const candidates = boundedContextCandidates(binding.bindingCandidates ?? []);\n const state: ContextualRuntimeState = {\n category: 'ambiguous_binding',\n message: 'Ambiguous contextual service binding candidates',\n resolutionStatus: 'ambiguous',\n };\n return {\n evidence: {\n contextualServiceBindingAttempted: true,\n contextualBinding: {\n source: binding.source,\n status: 'tied',\n candidates: candidates.candidates,\n candidateCount: candidates.candidateCount,\n shownCandidateCount: candidates.shownCandidateCount,\n omittedCandidateCount: candidates.omittedCandidateCount,\n },\n contextualResolutionStatus: 'ambiguous',\n contextualCandidateCount: candidates.candidateCount,\n contextualPreSubstitutionState: historicalState(state),\n },\n state,\n };\n}\n\nfunction selectedBindingResolution(\n db: Db,\n call: ContextualCall,\n binding: ContextBinding,\n workspaceId: number | undefined,\n persistedRows: PersistedGraphRow[],\n): ContextualRuntimeResolution {\n const normalized = normalizeODataOperationInvocationPath(\n String(call.operation_path_expr),\n );\n const operationPath = normalized?.normalizedOperationPath\n ?? withLeadingSlash(String(call.operation_path_expr));\n const servicePath = binding.effectiveServicePath\n ?? binding.servicePathExpr ?? binding.requireServicePath;\n const destination = binding.effectiveDestination\n ?? binding.destinationExpr ?? binding.requireDestination;\n const resolution = resolveOperation(db, {\n servicePath,\n operationPath,\n alias: binding.aliasExpr ?? binding.alias,\n destination,\n hasExplicitOverride: true,\n isDynamic: false,\n }, workspaceId);\n const state = stateForResolution(resolution);\n const evidence = contextualEvidence(\n binding, normalized, operationPath, servicePath, destination, resolution, state,\n );\n if (!resolution.target) return { evidence, state };\n const resolvedEvidence = {\n ...evidence,\n contextualServiceBindingSelected: true,\n targetRepo: resolution.target.repoName,\n targetServicePath: resolution.target.servicePath,\n targetOperationPath: resolution.target.operationPath,\n targetOperation: resolution.target.operationName,\n };\n if (persistedRows.some((row) => row.status === 'resolved'))\n return { evidence: { ...resolvedEvidence, contextualPreservedPersistedResolvedEdge: true }, state };\n return {\n row: {\n id: -call.id,\n edge_type: 'REMOTE_CALL_RESOLVES_TO_OPERATION',\n from_id: String(call.id),\n to_kind: 'operation',\n to_id: String(resolution.target.operationId),\n confidence: resolution.target.score,\n evidence_json: JSON.stringify(resolvedEvidence),\n status: 'resolved',\n },\n evidence: resolvedEvidence,\n state,\n };\n}\n\nfunction contextualEvidence(\n binding: ContextBinding,\n normalized: ReturnType<typeof normalizeODataOperationInvocationPath>,\n operationPath: string,\n servicePath: string | undefined,\n destination: string | undefined,\n resolution: OperationResolution,\n state: ContextualRuntimeState,\n): Record<string, unknown> {\n const candidates = boundedContextCandidates(resolution.candidates);\n return {\n contextualServiceBindingAttempted: true,\n contextualBinding: bindingEvidence(binding),\n operationPath,\n rawOperationPath: normalized?.rawOperationPath,\n normalizedOperationPath: normalized?.wasInvocation\n ? normalized.normalizedOperationPath : undefined,\n invocationArgumentPlaceholderKeys: normalized?.invocationArgumentPlaceholderKeys.length\n ? normalized.invocationArgumentPlaceholderKeys : undefined,\n servicePath,\n serviceAlias: binding.alias,\n serviceAliasExpr: binding.aliasExpr,\n destination,\n requireServicePath: binding.requireServicePath,\n requireDestination: binding.requireDestination,\n effectiveServicePath: binding.effectiveServicePath,\n effectiveDestination: binding.effectiveDestination,\n contextualResolutionStatus: resolution.status,\n contextualCandidateCount: candidates.candidateCount,\n shownContextualCandidateCount: candidates.shownCandidateCount,\n omittedContextualCandidateCount: candidates.omittedCandidateCount,\n candidates: candidates.candidates,\n contextualResolutionReasons: resolution.reasons,\n resolutionReasons: resolution.reasons,\n contextualPreSubstitutionState: historicalState(state),\n };\n}\n\nfunction bindingEvidence(binding: ContextBinding): Record<string, unknown> {\n return {\n source: binding.source,\n callerArgument: binding.callerArgument,\n callerProperty: binding.callerProperty,\n calleeParameter: binding.calleeParameter,\n calleeReceiver: binding.calleeReceiver,\n callerSite: binding.callerSite,\n calleeSite: binding.calleeSite,\n bindingSourceFile: binding.sourceFile,\n bindingSourceLine: binding.sourceLine,\n alias: binding.alias,\n aliasExpr: binding.aliasExpr,\n requireServicePath: binding.requireServicePath,\n requireDestination: binding.requireDestination,\n effectiveServicePath: binding.effectiveServicePath,\n effectiveDestination: binding.effectiveDestination,\n };\n}\n\nfunction stateForResolution(\n resolution: OperationResolution,\n): ContextualRuntimeState {\n if (resolution.status === 'resolved') return { category: 'none' };\n if (resolution.status === 'dynamic') {\n const missingVariables = missingVariableKeys(resolution.reasons);\n return {\n category: 'dynamic_missing',\n message: dynamicMissingReason(missingVariables),\n missingVariables,\n resolutionStatus: resolution.status,\n };\n }\n if (resolution.status === 'ambiguous') return {\n category: 'ambiguous_operation',\n message: 'Ambiguous contextual operation candidates',\n resolutionStatus: resolution.status,\n };\n return {\n category: resolution.status === 'unresolved'\n ? 'no_matching_operation' : 'other_blocker',\n message: resolution.status === 'unresolved'\n ? 'No contextual operation candidate matched'\n : 'Contextual operation resolution is blocked',\n resolutionStatus: resolution.status,\n };\n}\n\nfunction historicalState(\n state: ContextualRuntimeState,\n): ContextualRuntimeState {\n return { ...state, phase: 'before_runtime_substitution' };\n}\n\nfunction missingVariableKeys(reasons: string[]): string[] {\n return normalizedKeys(reasons.flatMap((reason) =>\n reason.startsWith('missing_variable:')\n ? [reason.slice('missing_variable:'.length)] : []));\n}\n\nfunction normalizedKeys(keys: readonly string[]): string[] {\n return [...new Set(keys.filter((key) => key.length > 0))].sort();\n}\n\nfunction withLeadingSlash(value: string): string {\n return value.startsWith('/') ? value : `/${value}`;\n}\n","import type { Db } from '../db/connection.js';\nimport { extractPlaceholders, substituteVariables, type RuntimeSubstitution } from '../linker/dynamic-edge-resolver.js';\nimport { normalizeODataOperationInvocationPath } from '../linker/odata-path-normalizer.js';\nimport { resolveOperation, type OperationTarget } from '../linker/service-resolver.js';\nimport type { DynamicMode } from '../types.js';\nimport { analyzeDynamicTargetCandidates, type DynamicTargetAnalysis, type DynamicTargetCandidate } from './dynamic-targets.js';\nimport { boundCandidateLikeEvidence } from '../utils/000-bounded-projection.js';\nimport {\n dynamicMissingReason,\n isStructuralContextualBlocker,\n type ContextualRuntimeState,\n} from './008-contextual-runtime-state.js';\n\nexport interface TraceGraphRow extends Record<string, unknown> {\n id: number;\n edge_type: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n confidence: number;\n evidence_json: string;\n unresolved_reason?: string;\n status?: string;\n}\n\ninterface Candidate {\n servicePath?: string;\n operationPath?: string;\n repoName?: string;\n operationName?: string;\n score?: number;\n}\ninterface RuntimeDiagnosticTotals {\n missing: Set<string>;\n candidateCount: number;\n viableCandidateCount: number;\n rejectedCandidateCount: number;\n maxCandidates: number;\n candidateSuggestions: Record<string, unknown>[];\n rejectedCandidates: Record<string, unknown>[];\n suggestedVarSets: Record<string, unknown>[];\n}\ninterface RuntimeResolutionResult {\n row: TraceGraphRow;\n evidence: Record<string, unknown>;\n target?: OperationTarget;\n unresolvedReason?: string;\n}\n\nexport function baseTraceEvidence(\n row: TraceGraphRow,\n call: Record<string, unknown>,\n persistedEvidence: Record<string, unknown>,\n contextualEvidence: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const evidence = { ...persistedEvidence, ...(contextualEvidence ?? {}) };\n return {\n ...evidence,\n graphEdgeId: row.id,\n persistedGraphEdgeId: row.id > 0 ? row.id : undefined,\n outboundCallId: call.id,\n callSite: { sourceFile: call.source_file, sourceLine: call.source_line },\n callType: call.call_type,\n repoId: call.repo_id,\n sourceFile: call.source_file,\n sourceLine: call.source_line,\n file: call.source_file,\n line: call.source_line,\n persistedTarget: { kind: row.to_kind, id: row.to_id },\n contextualResolutionParticipated: Boolean(contextualEvidence?.contextualServiceBindingAttempted),\n persistedResolution: persistedResolution(row),\n };\n}\n\nexport function runtimeResolution(\n db: Db,\n row: TraceGraphRow,\n evidence: Record<string, unknown>,\n options: { vars?: Record<string, string>; dynamicMode?: DynamicMode; maxDynamicCandidates?: number },\n workspaceId: number | undefined,\n contextualState?: ContextualRuntimeState,\n): RuntimeResolutionResult {\n const dynamicMode = options.dynamicMode ?? 'strict';\n const candidateCap = positiveCandidateCap(options.maxDynamicCandidates);\n const boundedEvidence = boundCandidateLikeEvidence(evidence, candidateCap);\n if (!isDynamicRemoteOperationEdge(row, evidence))\n return unchangedRuntimeResolution(\n row,\n boundDynamicEvidence(boundedEvidence, candidateCap),\n contextualState,\n );\n const substituted = evidenceWithRuntimeVariables(boundedEvidence, options.vars);\n const analysis = analyzeDynamicTargetCandidates(\n db, substituted, workspaceId, dynamicMode, candidateCap,\n );\n const enriched = boundDynamicEvidence(\n analysis ? evidenceWithDynamicAnalysis(substituted, analysis) : substituted,\n candidateCap,\n );\n const appliedRuntimeValues = hasApplicableRuntimeVariables(evidence, options.vars);\n const analyzed = analyzedRuntimeResolution(\n row, enriched, analysis, dynamicMode, appliedRuntimeValues, contextualState,\n );\n if (analyzed) return analyzed;\n if (!appliedRuntimeValues) {\n const unresolvedReason = contextualReason(contextualState) ?? row.unresolved_reason;\n const withSections = withEffectiveResolution(\n enriched, row, unresolvedReason, undefined, contextualState,\n );\n return { row, evidence: withSections, unresolvedReason };\n }\n return resolveSuppliedRuntimeOperation(db, row, enriched, workspaceId, contextualState);\n}\n\nfunction analyzedRuntimeResolution(\n row: TraceGraphRow,\n evidence: Record<string, unknown>,\n analysis: DynamicTargetAnalysis | undefined,\n dynamicMode: DynamicMode,\n appliedRuntimeValues: boolean,\n contextualState: ContextualRuntimeState | undefined,\n): RuntimeResolutionResult | undefined {\n if (analysis && analysis.viableCandidateCount === 0\n && Object.keys(analysis.appliedSuppliedVariables).length > 0)\n return noCandidateRuntimeResolution(row, evidence, contextualState);\n const inferred = dynamicMode === 'infer' ? inferredTarget(analysis) : undefined;\n if (inferred && !isStructuralContextualBlocker(contextualState))\n return resolvedRuntimeResolution(row, evidence, inferred, inferred.reasons);\n if (analysis && analysis.missingVariables.length > 0 && appliedRuntimeValues) {\n const unresolvedReason = dynamicMissingReason(analysis.missingVariables);\n return {\n row,\n evidence: withEffectiveResolution(\n evidence, row, unresolvedReason, undefined, contextualState,\n ),\n unresolvedReason,\n };\n }\n return isStructuralContextualBlocker(contextualState)\n ? unchangedRuntimeResolution(row, evidence, contextualState)\n : undefined;\n}\n\nfunction resolveSuppliedRuntimeOperation(\n db: Db,\n row: TraceGraphRow,\n evidence: Record<string, unknown>,\n workspaceId: number | undefined,\n contextualState: ContextualRuntimeState | undefined,\n): RuntimeResolutionResult {\n const resolution = resolveRuntimeOperation(db, evidence, workspaceId);\n if (resolution.target)\n return resolvedRuntimeResolution(\n row, evidence, resolution.target, resolution.reasons,\n );\n const unresolvedReason = runtimeUnresolvedReason(resolution);\n return {\n row,\n evidence: withEffectiveResolution(\n evidence, row, unresolvedReason, resolution, contextualState,\n ),\n unresolvedReason,\n };\n}\n\nfunction unchangedRuntimeResolution(\n row: TraceGraphRow,\n evidence: Record<string, unknown>,\n contextualState: ContextualRuntimeState | undefined,\n): RuntimeResolutionResult {\n const unresolvedReason = contextualReason(contextualState) ?? row.unresolved_reason;\n return {\n row,\n evidence: withEffectiveResolution(\n evidence, row, unresolvedReason, undefined, contextualState,\n ),\n unresolvedReason,\n };\n}\n\nfunction noCandidateRuntimeResolution(\n row: TraceGraphRow,\n evidence: Record<string, unknown>,\n contextualState: ContextualRuntimeState | undefined,\n): RuntimeResolutionResult {\n const unresolvedReason = 'No candidate remained after runtime substitution';\n return {\n row,\n evidence: withEffectiveResolution(\n evidence, row, unresolvedReason, undefined, contextualState,\n ),\n unresolvedReason,\n };\n}\n\nfunction resolvedRuntimeResolution(\n row: TraceGraphRow,\n evidence: Record<string, unknown>,\n target: OperationTarget,\n reasons: string[],\n): RuntimeResolutionResult {\n const resolvedRow = {\n ...row,\n status: 'resolved',\n to_kind: 'operation',\n to_id: String(target.operationId),\n unresolved_reason: undefined,\n confidence: Math.max(0, Math.min(1, target.score)),\n };\n const resolution = {\n status: 'resolved' as const,\n target,\n candidates: [],\n reasons,\n };\n return {\n row: resolvedRow,\n evidence: withEffectiveResolution(evidence, resolvedRow, undefined, resolution),\n target,\n };\n}\n\nexport function runtimeVariableDiagnostic(edges: Array<{ evidence: Record<string, unknown> }>): Record<string, unknown> | undefined {\n const totals = runtimeDiagnosticTotals(edges);\n const missingVariables = [...totals.missing].sort();\n if (missingVariables.length === 0) return undefined;\n const shownSuggestions = totals.candidateSuggestions.slice(0, totals.maxCandidates);\n const shownRejected = totals.rejectedCandidates.slice(0, totals.maxCandidates);\n const shownCandidateCount = shownSuggestions.length;\n return {\n severity: 'warning',\n code: 'trace_runtime_variables_missing',\n message: `Runtime variables are required to resolve dynamic trace targets: ${missingVariables.join(', ')}`,\n missingVariables,\n suggestions: missingVariables.map((key) => `--var ${key}=<value>`),\n candidateCount: totals.candidateCount,\n viableCandidateCount: totals.viableCandidateCount,\n rejectedCandidateCount: totals.rejectedCandidateCount,\n shownCandidateCount,\n omittedCandidateCount: Math.max(0, totals.viableCandidateCount - shownCandidateCount),\n maxDynamicCandidates: totals.maxCandidates,\n shownRejectedCandidateCount: shownRejected.length,\n omittedRejectedCandidateCount: Math.max(0, totals.rejectedCandidateCount - shownRejected.length),\n candidateSuggestions: shownSuggestions,\n rejectedCandidates: shownRejected,\n suggestedVarSets: uniqueCliRows(totals.suggestedVarSets).slice(0, totals.maxCandidates),\n copyableExamples: copyableExamples(totals.suggestedVarSets, totals.candidateCount, totals.maxCandidates),\n };\n}\n\nfunction runtimeDiagnosticTotals(\n edges: Array<{ evidence: Record<string, unknown> }>): RuntimeDiagnosticTotals {\n const missing = new Set<string>();\n let candidateCount = 0;\n let viableCandidateCount = 0;\n let rejectedCandidateCount = 0;\n let maxCandidates = 5;\n const candidateSuggestions: Record<string, unknown>[] = [];\n const rejectedCandidates: Record<string, unknown>[] = [];\n const suggestedVarSets: Record<string, unknown>[] = [];\n for (const edge of edges) {\n const effective = parseObject(edge.evidence.effectiveResolution);\n if (!['dynamic', 'unresolved', 'ambiguous'].includes(String(effective.status ?? '')))\n continue;\n const substitutions = edge.evidence.runtimeSubstitutions;\n if (!substitutions || typeof substitutions !== 'object' || Array.isArray(substitutions)) continue;\n for (const value of Object.values(substitutions as Record<string, RuntimeSubstitution>))\n for (const key of value.missing ?? []) missing.add(key);\n const exploration = parseObject(edge.evidence.dynamicTargetExploration);\n maxCandidates = positiveCandidateCap(numeric(exploration.maxCandidates) || maxCandidates);\n candidateCount += numeric(exploration.candidateCount);\n viableCandidateCount += numeric(exploration.viableCandidateCount);\n rejectedCandidateCount += numeric(exploration.rejectedCandidateCount);\n appendBounded(\n candidateSuggestions,\n recordArray(edge.evidence.dynamicTargetCandidateSuggestions),\n maxCandidates,\n );\n appendBounded(\n rejectedCandidates,\n recordArray(exploration.rejectedCandidates),\n maxCandidates,\n );\n appendBounded(\n suggestedVarSets,\n recordArray(exploration.suggestedVarSets),\n maxCandidates,\n );\n }\n return {\n missing,\n candidateCount,\n viableCandidateCount,\n rejectedCandidateCount,\n maxCandidates,\n candidateSuggestions,\n rejectedCandidates,\n suggestedVarSets,\n };\n}\n\nexport function runtimeNoCandidateDiagnostics(\n edges: Array<{ evidence: Record<string, unknown> }>,\n): Array<Record<string, unknown>> {\n const seen = new Set<string>();\n return edges.flatMap((edge) => {\n const exploration = parseObject(edge.evidence.dynamicTargetExploration);\n const suppliedVariables = parseObject(exploration.suppliedVariables);\n const appliedSuppliedVariables = parseObject(\n exploration.appliedSuppliedVariables,\n );\n if (numeric(exploration.viableCandidateCount) !== 0\n || Object.keys(appliedSuppliedVariables).length === 0) return [];\n const callSite = parseObject(edge.evidence.callSite);\n const key = JSON.stringify([callSite, suppliedVariables]);\n if (seen.has(key)) return [];\n seen.add(key);\n const maxCandidates = positiveCandidateCap(numeric(exploration.maxCandidates));\n return [{\n severity: 'warning',\n code: 'no_candidate_after_runtime_substitution',\n message: 'No dynamic target candidate remained after applying runtime variables',\n suppliedVariables,\n appliedSuppliedVariables,\n substitutedSignals: parseObject(exploration.substitutedSignals),\n candidateCount: numeric(exploration.candidateCount),\n viableCandidateCount: 0,\n rejectedCandidateCount: numeric(exploration.rejectedCandidateCount),\n shownCandidateCount: numeric(exploration.shownCandidateCount),\n omittedCandidateCount: numeric(exploration.omittedCandidateCount),\n shownRejectedCandidateCount: numeric(\n exploration.shownRejectedCandidateCount,\n ),\n omittedRejectedCandidateCount: numeric(\n exploration.omittedRejectedCandidateCount,\n ),\n rejectedCandidates: recordArray(exploration.rejectedCandidates).slice(0, maxCandidates),\n callSite,\n }];\n });\n}\n\nexport function edgeTarget(row: TraceGraphRow, evidence: Record<string, unknown>): string {\n const effective = parseObject(evidence.effectiveResolution);\n const targetServicePath = stringValue(effective.targetServicePath ?? evidence.targetServicePath);\n const targetOperationPath = stringValue(effective.targetOperationPath ?? evidence.targetOperationPath);\n if (targetServicePath && targetOperationPath) return `${targetServicePath}${targetOperationPath}`;\n const runtimeCandidate = evidence.runtimeResolvedCandidate as Candidate | undefined;\n if (runtimeCandidate?.servicePath && runtimeCandidate.operationPath) return `${runtimeCandidate.servicePath}${runtimeCandidate.operationPath}`;\n const servicePath = stringValue(evidence.servicePath);\n const operationPath = stringValue(evidence.operationPath);\n const targetOperation = stringValue(evidence.targetOperation);\n const targetRepo = stringValue(evidence.targetRepo) ?? '';\n if (row.edge_type === 'HANDLER_RUNS_DB_QUERY') return `Entity: ${row.to_id || 'unknown'}`;\n if (row.edge_type === 'HANDLER_RUNS_REMOTE_QUERY') return stringValue(evidence.remoteQueryTarget) ?? `Remote query: ${row.to_id || 'unknown'}`;\n if (row.edge_type === 'HANDLER_CALLS_EXTERNAL_HTTP') {\n const target = parseObject(evidence.externalTarget);\n return stringValue(target.label) ?? `External endpoint: ${row.to_id || 'unknown'}`;\n }\n if (servicePath && operationPath) return `${servicePath}${operationPath}`;\n return targetOperation ? `${targetRepo}:${targetOperation}` : row.to_id;\n}\n\nfunction persistedResolution(row: TraceGraphRow): Record<string, unknown> {\n return {\n status: row.status,\n targetKind: row.to_kind,\n targetId: row.to_id,\n edgeId: row.id > 0 ? row.id : undefined,\n confidence: row.confidence,\n unresolvedReason: row.unresolved_reason,\n edgeType: row.edge_type,\n };\n}\n\nfunction effectiveResolution(\n row: TraceGraphRow,\n evidence: Record<string, unknown>,\n unresolvedReason: string | undefined,\n resolution?: ReturnType<typeof resolveRuntimeOperation>,\n contextualState?: ContextualRuntimeState,\n): Record<string, unknown> {\n const target = resolution?.target;\n return {\n status: target ? 'resolved' : row.status,\n targetKind: target ? 'operation' : row.to_kind,\n targetId: target ? String(target.operationId) : row.to_id,\n targetRepo: target?.repoName ?? evidence.targetRepo,\n targetServicePath: target?.servicePath ?? evidence.targetServicePath,\n targetOperationPath: target?.operationPath ?? evidence.targetOperationPath,\n targetOperation: target?.operationName ?? evidence.targetOperation,\n confidence: target?.score ?? row.confidence,\n reasons: resolution?.reasons ?? evidence.resolutionReasons,\n unresolvedReason,\n edgeType: target ? 'REMOTE_CALL_RESOLVES_TO_OPERATION' : row.edge_type,\n contextualBlocker: isStructuralContextualBlocker(contextualState)\n ? contextualState : undefined,\n };\n}\n\nfunction withEffectiveResolution(\n evidence: Record<string, unknown>,\n row: TraceGraphRow,\n unresolvedReason: string | undefined,\n resolution?: ReturnType<typeof resolveRuntimeOperation>,\n contextualState?: ContextualRuntimeState,\n): Record<string, unknown> {\n const current = effectiveResolution(\n row, evidence, unresolvedReason, resolution, contextualState,\n );\n const rest = { ...evidence };\n delete rest.runtimeResolvedCandidate;\n return {\n ...rest,\n effectiveResolution: current,\n linker: {\n status: current.status,\n confidence: current.confidence,\n reason: unresolvedReason,\n edgeType: current.edgeType,\n contextualBlocker: current.contextualBlocker,\n },\n };\n}\n\nfunction contextualReason(\n state: ContextualRuntimeState | undefined,\n): string | undefined {\n return state?.category === 'none' ? undefined : state?.message;\n}\n\nfunction resolveRuntimeOperation(db: Db, evidence: Record<string, unknown>, workspaceId: number | undefined): ReturnType<typeof resolveOperation> {\n const servicePath = stringValue(evidence.servicePath);\n const rawOperationPath = stringValue(evidence.operationPath);\n const normalized = normalizeODataOperationInvocationPath(rawOperationPath);\n const operationPath = normalized?.wasInvocation\n ? normalized.normalizedOperationPath\n : stringValue(evidence.normalizedOperationPath) ?? rawOperationPath;\n const alias = stringValue(evidence.serviceAliasExpr ?? evidence.serviceAlias);\n const destination = stringValue(evidence.destination);\n return resolveOperation(db, { servicePath, operationPath, alias, destination, hasExplicitOverride: true, isDynamic: true }, workspaceId);\n}\n\nfunction evidenceWithRuntimeVariables(evidence: Record<string, unknown>, vars: Record<string, string> | undefined): Record<string, unknown> {\n const substitutions = runtimeSubstitutions(evidence, vars ?? {});\n const suppliedRuntimeVariables = Object.fromEntries(\n Object.entries(vars ?? {}).sort(([left], [right]) => left.localeCompare(right)),\n );\n const next: Record<string, unknown> = {\n ...evidence,\n runtimeSubstitutions: substitutions,\n suppliedRuntimeVariables,\n };\n for (const [key, value] of Object.entries(substitutions)) if (value.effective) next[key] = value.effective;\n const missing = Object.values(substitutions).flatMap((value) => value.missing);\n if (missing.length > 0) next.missingRuntimeVariables = [...new Set(missing)].sort();\n if (Object.keys(suppliedRuntimeVariables).length > 0) next.runtimeVariablesApplied = true;\n return next;\n}\n\nfunction evidenceWithDynamicAnalysis(\n evidence: Record<string, unknown>,\n analysis: DynamicTargetAnalysis,\n): Record<string, unknown> {\n const persistedCandidates = recordArray(evidence.candidates);\n const persistedScores = recordArray(evidence.candidateScores);\n const persistedCandidateCount = numeric(evidence.persistedCandidateCount)\n || numeric(evidence.candidateCount)\n || persistedCandidates.length;\n const persistedScoreCount = numeric(evidence.candidateScoreCount)\n || persistedScores.length;\n return {\n ...evidence,\n candidates: persistedCandidates.slice(0, analysis.maxCandidates),\n candidateScores: persistedScores.slice(0, analysis.maxCandidates),\n persistedCandidateCount,\n persistedCandidateOmittedCount: Math.max(\n 0,\n persistedCandidateCount - Math.min(persistedCandidates.length, analysis.maxCandidates),\n ),\n persistedCandidateScoreCount: persistedScoreCount,\n persistedCandidateScoreOmittedCount: Math.max(\n 0, persistedScoreCount - Math.min(persistedScores.length, analysis.maxCandidates),\n ),\n dynamicTargetExploration: {\n mode: analysis.mode,\n maxCandidates: analysis.maxCandidates,\n missingVariables: analysis.missingVariables,\n requiredVariables: analysis.requiredVariables,\n suppliedVariables: analysis.suppliedVariables,\n appliedSuppliedVariables: analysis.appliedSuppliedVariables,\n substitutedSignals: analysis.substitutedSignals,\n candidateCount: analysis.candidateCount,\n viableCandidateCount: analysis.viableCandidateCount,\n rejectedCandidateCount: analysis.rejectedCandidateCount,\n shownCandidateCount: analysis.shownCandidateCount,\n omittedCandidateCount: analysis.omittedCandidateCount,\n shownRejectedCandidateCount: analysis.shownRejectedCandidateCount,\n omittedRejectedCandidateCount: analysis.omittedRejectedCandidateCount,\n rejectedCandidates: analysis.rejectedCandidates,\n suggestedVarSets: analysis.suggestedVarSets,\n suggestedVarSetCount: analysis.suggestedVarSetCount,\n shownSuggestedVarSetCount: analysis.shownSuggestedVarSetCount,\n omittedSuggestedVarSetCount: analysis.omittedSuggestedVarSetCount,\n routingContext: analysis.routingContext,\n },\n dynamicTargetCandidates: analysis.candidates,\n dynamicTargetCandidateSuggestions: analysis.shownCandidates,\n dynamicTargetCandidateSuggestionCount: analysis.viableCandidateCount,\n shownDynamicTargetCandidateSuggestionCount: analysis.shownCandidateCount,\n omittedDynamicTargetCandidateSuggestionCount: analysis.omittedCandidateCount,\n rejectedCandidates: analysis.rejectedCandidates,\n dynamicTargetInference: analysis.inference,\n };\n}\n\nconst boundedDynamicListKeys = new Set([\n 'candidates',\n 'candidateScores',\n 'dynamicTargetCandidates',\n 'dynamicTargetCandidateSuggestions',\n 'candidateSuggestions',\n 'suggestedVarSets',\n 'rejectedCandidates',\n 'rejectedCandidateSuggestions',\n 'copyableExamples',\n 'conflicts',\n 'bindingAlternatives',\n]);\n\nfunction boundDynamicEvidence(\n evidence: Record<string, unknown>,\n limit: number,\n): Record<string, unknown> {\n const candidateCount = numeric(evidence.persistedCandidateCount)\n || numeric(evidence.candidateCount)\n || (Array.isArray(evidence.candidates) ? evidence.candidates.length : 0);\n const projected = boundDynamicValue(evidence, limit);\n const next = parseObject(projected);\n if (candidateCount === 0) return next;\n return {\n ...next,\n persistedCandidateCount: candidateCount,\n persistedCandidateOmittedCount: Math.max(0, candidateCount - limit),\n };\n}\n\nfunction boundDynamicValue(\n value: unknown,\n limit: number,\n key?: string,\n parentKey?: string,\n): unknown {\n if (Array.isArray(value)) {\n const bounded = Boolean(key && (boundedDynamicListKeys.has(key)\n || parentKey === 'derivationProvenance'\n || parentKey === 'conflicts' && key === 'sources'));\n const input = bounded ? value.slice(0, limit) : value;\n const projected = input.map((item) =>\n boundDynamicValue(item, limit, undefined, key ?? parentKey));\n return projected;\n }\n if (!value || typeof value !== 'object') return value;\n return Object.fromEntries(Object.entries(value).map(([childKey, child]) => [\n childKey,\n boundDynamicValue(child, limit, childKey, key ?? parentKey),\n ]));\n}\n\nfunction runtimeSubstitutions(evidence: Record<string, unknown>, vars: Record<string, string>): Record<string, RuntimeSubstitution> {\n const substitutions: Record<string, RuntimeSubstitution> = {};\n for (const key of ['servicePath', 'operationPath', 'serviceAliasExpr', 'serviceAlias', 'destination']) {\n const substitution = substituteVariables(substitutionValue(evidence, key), vars);\n if (substitution.placeholders.length > 0) substitutions[key] = substitution;\n }\n return substitutions;\n}\n\nfunction substitutionValue(\n evidence: Record<string, unknown>,\n key: string,\n): string | undefined {\n const value = stringValue(evidence[key]);\n if (key !== 'operationPath') return value;\n const normalized = normalizeODataOperationInvocationPath(value);\n return normalized?.wasInvocation ? normalized.normalizedOperationPath : value;\n}\n\nfunction isDynamicRemoteOperationEdge(\n row: TraceGraphRow,\n evidence: Record<string, unknown>,\n): boolean {\n if (evidence.callType !== 'remote_action') return false;\n if (!['dynamic', 'ambiguous', 'unresolved'].includes(String(row.status ?? ''))) return false;\n return ['DYNAMIC_EDGE_CANDIDATE', 'UNRESOLVED_EDGE', 'REMOTE_CALL_RESOLVES_TO_OPERATION']\n .includes(row.edge_type);\n}\n\nfunction hasApplicableRuntimeVariables(\n evidence: Record<string, unknown>,\n vars: Record<string, string> | undefined,\n): boolean {\n if (!vars || Object.keys(vars).length === 0) return false;\n return ['servicePath', 'operationPath', 'serviceAliasExpr', 'serviceAlias', 'destination'].some((key) => hasRuntimeVariable(evidence[key], vars));\n}\n\nfunction inferredTarget(analysis: DynamicTargetAnalysis | undefined): OperationTarget | undefined {\n if (analysis?.inference.status !== 'resolved') return undefined;\n const id = Number(analysis.inference.candidateOperationId);\n const candidate = analysis.candidates.find((item) => item.candidateOperationId === id);\n if (!candidate) return undefined;\n return targetFromCandidate(candidate);\n}\n\nfunction targetFromCandidate(candidate: DynamicTargetCandidate): OperationTarget {\n return {\n operationId: candidate.candidateOperationId,\n repoName: candidate.repoName,\n serviceName: '',\n qualifiedName: '',\n servicePath: candidate.servicePath,\n operationPath: candidate.operationPath,\n operationName: candidate.operationName,\n repoId: candidate.repoId,\n packageName: candidate.packageName,\n score: candidate.score,\n reasons: candidate.reasons,\n sourceFile: candidate.sourceFile,\n sourceLine: candidate.sourceLine,\n };\n}\n\nfunction hasRuntimeVariable(value: unknown, vars: Record<string, string>): boolean {\n return typeof value === 'string' && extractPlaceholders(value).some((key) => Object.hasOwn(vars, key));\n}\n\nfunction runtimeUnresolvedReason(resolution: ReturnType<typeof resolveRuntimeOperation>): string {\n if (resolution.status === 'dynamic') return `Dynamic target is missing runtime variables: ${resolution.reasons.join(', ')}`;\n if (resolution.status === 'ambiguous') return 'Ambiguous runtime operation candidates';\n return 'No runtime operation candidate matched substituted service and operation path';\n}\n\nfunction parseObject(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numeric(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction recordArray(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value)\n ? value.filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === 'object' && !Array.isArray(item)))\n : [];\n}\n\nfunction appendBounded<T>(target: T[], values: T[], limit: number): void {\n const remaining = Math.max(0, limit - target.length);\n if (remaining > 0) target.push(...values.slice(0, remaining));\n}\n\nfunction uniqueCliRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {\n const seen = new Set<string>();\n return rows.filter((row) => {\n const cli = typeof row.cli === 'string' ? row.cli : JSON.stringify(row);\n if (seen.has(cli)) return false;\n seen.add(cli);\n return true;\n });\n}\n\nfunction copyableExamples(\n suggestedVarSets: Record<string, unknown>[],\n candidateCount: number,\n limit: number,\n): string[] {\n const variableExamples = uniqueCliRows(suggestedVarSets).flatMap((row) =>\n typeof row.cli === 'string' ? [row.cli] : []);\n const exploration = candidateCount > 0\n ? ['--dynamic-mode candidates --max-dynamic-candidates 20']\n : [];\n return [...variableExamples, ...exploration].slice(0, limit);\n}\n\nfunction positiveCandidateCap(value: number | undefined): number {\n return Number.isFinite(value) && Number(value) > 0 ? Math.floor(Number(value)) : 5;\n}\n","import type { TraceEdge } from '../types.js';\n\ninterface DynamicBranchCall {\n repoName: string;\n source_file: string;\n source_line: number;\n}\n\nexport interface DynamicCandidateBranch {\n edge: TraceEdge;\n operationId?: number;\n repositoryId?: number;\n servicePath?: string;\n operationPath?: string;\n}\n\nexport function dynamicCandidateBranches(\n depth: number,\n call: DynamicBranchCall,\n evidence: Record<string, unknown>,\n): DynamicCandidateBranch[] {\n const exploration = objectRecord(evidence.dynamicTargetExploration);\n return recordArray(evidence.dynamicTargetCandidateSuggestions).map((candidate) => ({\n edge: {\n step: depth,\n type: 'dynamic_candidate_branch',\n from: `${call.repoName}:${call.source_file}:${call.source_line}`,\n to: `${String(candidate.servicePath ?? '')}${String(candidate.operationPath ?? '')}`,\n evidence: {\n ...candidate,\n exploratory: true,\n dynamicMode: String(exploration.mode ?? 'candidates'),\n selected: false,\n omittedCandidateCount: numericValue(exploration.omittedCandidateCount),\n },\n confidence: numericValue(candidate.score),\n unresolvedReason: 'Exploratory dynamic target candidate; provide runtime variables to select it',\n },\n operationId: optionalNumber(candidate.candidateOperationId),\n repositoryId: optionalNumber(candidate.repoId),\n servicePath: optionalString(candidate.servicePath),\n operationPath: optionalString(candidate.operationPath),\n }));\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};\n}\n\nfunction recordArray(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value)\n ? value.filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === 'object' && !Array.isArray(item)))\n : [];\n}\n\nfunction numericValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction optionalNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n","import type { Db } from '../db/connection.js';\n\nexport function loadTraceDiagnostics(\n db: Db,\n repoId: number | undefined,\n includeWorkspaceDiagnostics: boolean,\n workspaceId?: number,\n): Array<Record<string, unknown>> {\n if (repoId === undefined && !includeWorkspaceDiagnostics) return [];\n return db.prepare(`SELECT d.repo_id repoId,d.severity,d.code,d.message,\n d.source_file sourceFile,d.source_line sourceLine\n FROM diagnostics d LEFT JOIN repositories r ON r.id=d.repo_id\n WHERE (? IS NULL OR d.repo_id=?)\n AND (? IS NULL OR d.repo_id IS NULL OR r.workspace_id=?)\n ORDER BY severity,code,COALESCE(source_file,''),\n COALESCE(source_line,0),d.id`).all(\n repoId, repoId, workspaceId, workspaceId,\n ) as Array<\n Record<string, unknown>\n >;\n}\n\nexport function prependTraceDiagnostic(\n diagnostics: Array<Record<string, unknown>>,\n diagnostic: Record<string, unknown>,\n): void {\n const duplicate = diagnostics.findIndex((item) =>\n sameDiagnosticLocation(item, diagnostic));\n if (duplicate >= 0) diagnostics.splice(duplicate, 1);\n diagnostics.unshift(diagnostic);\n}\n\nfunction sameDiagnosticLocation(\n left: Record<string, unknown>,\n right: Record<string, unknown>,\n): boolean {\n if (left.code !== right.code) return false;\n const leftFile = stringValue(left.sourceFile);\n const rightFile = stringValue(right.sourceFile);\n if (leftFile || rightFile)\n return leftFile === rightFile\n && numericValue(left.sourceLine) === numericValue(right.sourceLine);\n return String(left.message ?? '') === String(right.message ?? '');\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numericValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value)\n ? value\n : undefined;\n}\n","import type { Db } from '../db/connection.js';\nimport { canonicalImplementationEvidence } from '../linker/000-implementation-candidates.js';\nimport type { ImplementationHint } from '../types.js';\nimport { projectBounded } from '../utils/000-bounded-projection.js';\nimport {\n selectImplementation,\n type ImplementationSelection,\n} from './implementation-hints.js';\n\nexport interface ImplementationGraphEdge {\n status?: string;\n evidence_json?: string;\n}\n\nexport interface ImplementationSelectionOptions {\n implementationRepo?: string;\n implementationHints?: ImplementationHint[];\n}\n\nexport function hintedImplementationSelection(\n db: Db,\n edge: ImplementationGraphEdge | undefined,\n operationId: string,\n options: ImplementationSelectionOptions,\n): ImplementationSelection {\n if (!edge || edge.status !== 'ambiguous')\n return { blocksAutomatic: false, evidence: { status: 'not_applicable' } };\n return selectImplementation(\n parsedEvidence(edge.evidence_json), options.implementationHints,\n options.implementationRepo, canonicalImplementationEvidence(db, operationId),\n );\n}\n\nexport function contextualImplementationSelection(\n db: Db,\n edge: ImplementationGraphEdge | undefined,\n operationId: string,\n callerRepoId: number | undefined,\n remoteEvidence: Record<string, unknown>,\n options: ImplementationSelectionOptions,\n): ImplementationSelection {\n const hinted = hintedImplementationSelection(db, edge, operationId, options);\n if (hinted.methodId || hinted.blocksAutomatic || !edge\n || edge.status !== 'ambiguous' || callerRepoId === undefined) return hinted;\n const candidates = implementationCandidates(\n canonicalImplementationEvidence(db, operationId) ?? parsedEvidence(edge.evidence_json),\n );\n const scores = candidates.filter((candidate) => candidate.accepted)\n .map((candidate) => contextualScore(candidate, callerRepoId, remoteEvidence))\n .sort(compareScore);\n if (scores.length === 0)\n return { blocksAutomatic: false, evidence: { status: 'not_applicable', candidateScores: [] } };\n const [first, second] = scores;\n if (first?.methodId !== undefined && first.score > 0\n && (!second || first.score > second.score))\n return selectedContext(first, scores);\n return tiedContext(hinted, scores);\n}\n\nfunction selectedContext(\n first: ContextScore,\n scores: ContextScore[],\n): ImplementationSelection {\n const projection = projectBounded(scores, compareScore);\n return {\n methodId: String(first.methodId),\n blocksAutomatic: false,\n evidence: {\n status: 'selected',\n selectedMethodId: first.methodId,\n candidateScores: projection.items,\n candidateScoreCount: projection.totalCount,\n shownCandidateScoreCount: projection.shownCount,\n omittedCandidateScoreCount: projection.omittedCount,\n },\n };\n}\n\nfunction tiedContext(\n hinted: ImplementationSelection,\n scores: ContextScore[],\n): ImplementationSelection {\n if (hinted.evidence.reason === 'no_scoped_hint_matched_edge') return hinted;\n const projection = projectBounded(scores, compareScore);\n return {\n blocksAutomatic: false,\n evidence: {\n status: 'tied',\n tieReason: scores.length > 1\n ? 'duplicate_helper_implementation_candidates'\n : 'no_unique_materially_stronger_candidate',\n candidateScores: projection.items,\n candidateScoreCount: projection.totalCount,\n shownCandidateScoreCount: projection.shownCount,\n omittedCandidateScoreCount: projection.omittedCount,\n },\n };\n}\n\ninterface ImplementationCandidate {\n accepted: boolean;\n methodId?: number;\n score: number;\n handlerPackage: Record<string, unknown>;\n applicationPackage: Record<string, unknown>;\n}\n\ninterface ContextScore {\n methodId?: number;\n score: number;\n reasons: string[];\n handlerPackage: Record<string, unknown>;\n applicationPackage: Record<string, unknown>;\n}\n\nfunction implementationCandidates(evidence: Record<string, unknown>): ImplementationCandidate[] {\n const rows = Array.isArray(evidence.candidates) ? evidence.candidates : [];\n return rows.flatMap((value) => {\n const row = record(value);\n return Object.keys(row).length === 0 ? [] : [{\n accepted: row.accepted === true,\n methodId: numberValue(row.methodId),\n score: numberValue(row.score) ?? 0,\n handlerPackage: record(row.handlerPackage),\n applicationPackage: record(row.applicationPackage),\n }];\n });\n}\n\nfunction contextualScore(\n candidate: ImplementationCandidate,\n callerRepoId: number,\n remoteEvidence: Record<string, unknown>,\n): ContextScore {\n const reasons: string[] = [];\n let score = candidate.score;\n if (numberValue(candidate.handlerPackage.id) === callerRepoId) {\n score += 10;\n reasons.push('handler_package_matches_caller_repository');\n }\n if (numberValue(candidate.applicationPackage.id) === callerRepoId) {\n score += 10;\n reasons.push('registration_package_matches_caller_repository');\n }\n if (hasRemoteContext(remoteEvidence)) {\n score += 1;\n reasons.push('remote_call_context_available');\n }\n return {\n methodId: candidate.methodId,\n score,\n reasons,\n handlerPackage: candidate.handlerPackage,\n applicationPackage: candidate.applicationPackage,\n };\n}\n\nfunction hasRemoteContext(evidence: Record<string, unknown>): boolean {\n return typeof evidence.effectiveServicePath === 'string'\n || typeof evidence.effectiveDestination === 'string'\n || typeof evidence.effectiveAlias === 'string';\n}\n\nfunction compareScore(left: ContextScore, right: ContextScore): number {\n return right.score - left.score\n || Number(left.methodId ?? 0) - Number(right.methodId ?? 0);\n}\n\nfunction parsedEvidence(value: string | undefined): Record<string, unknown> {\n try {\n return record(JSON.parse(String(value ?? '{}')) as unknown);\n } catch {\n return {};\n }\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\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 | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n","interface ImplementationStartEdge {\n id: number;\n status?: string;\n}\n\nexport function implementationStartDiagnostic(\n edge: ImplementationStartEdge,\n evidence: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n severity: 'warning',\n code: edge.status === 'ambiguous'\n ? 'trace_start_ambiguous'\n : 'trace_start_implementation_unresolved',\n message: `Indexed operation matched but implementation edge is ${String(\n edge.status ?? 'unresolved',\n )}`,\n resolutionStage: 'implementation',\n resolutionStatus: edge.status === 'ambiguous'\n ? 'ambiguous_implementation'\n : 'rejected_implementation',\n implementationEdgeId: edge.id,\n implementationStatus: edge.status,\n implementationAmbiguityReasons: evidence.ambiguityReasons,\n implementationRejectionReasons: implementationRejectionReasons(evidence),\n implementationHintSuggestions: evidence.implementationHintSuggestions,\n implementationHintSuggestionCount: evidence.implementationHintSuggestionCount,\n shownImplementationHintSuggestionCount:\n evidence.shownImplementationHintSuggestionCount,\n omittedImplementationHintSuggestionCount:\n evidence.omittedImplementationHintSuggestionCount,\n candidates: evidence.candidates,\n candidateCount: evidence.candidateCount,\n shownCandidateCount: evidence.shownCandidateCount,\n omittedCandidateCount: evidence.omittedCandidateCount,\n };\n}\n\nfunction implementationRejectionReasons(\n evidence: Record<string, unknown>,\n): string[] {\n const candidates = recordArray(evidence.candidates);\n const reasons = candidates.flatMap((candidate) => stringArray(candidate.rejectedReasons));\n return [...new Set(reasons)].sort();\n}\n\nfunction recordArray(value: unknown): Array<Record<string, unknown>> {\n return Array.isArray(value)\n ? value.filter(isRecord)\n : [];\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n","import type { Db } from '../db/connection.js';\nimport {\n selectedHandlerProvenance,\n type SelectedHandlerProvenance,\n type SelectedHandlerSource,\n} from '../linker/001-implementation-evidence-projection.js';\n\nexport interface HandlerMethodNode extends Record<string, unknown> {\n id: string;\n kind: 'handler_method';\n label: string;\n methodId: number;\n methodName: string;\n className: string;\n sourceFile: string;\n sourceLine: number;\n repoId: number;\n repoName: string;\n packageName?: string;\n}\n\nexport interface SelectedHandlerEvidence {\n handler?: HandlerMethodNode;\n evidence: Record<string, unknown>;\n diagnostic?: Record<string, unknown>;\n unresolvedReason?: string;\n}\n\nexport function handlerMethodNode(\n db: Db,\n methodId: string,\n): HandlerMethodNode | undefined {\n const row = db.prepare(`SELECT hm.id methodId,hm.method_name methodName,\n hm.source_line sourceLine,hc.class_name className,hc.source_file sourceFile,\n r.name repoName,r.id repoId,r.package_name packageName\n FROM handler_methods hm JOIN handler_classes hc ON hc.id=hm.handler_class_id\n JOIN repositories r ON r.id=hc.repo_id WHERE hm.id=?`).get(methodId) as\n | Record<string, unknown>\n | undefined;\n return handlerNodeFromRow(row);\n}\n\nexport function withSelectedHandlerProvenance(\n evidence: Record<string, unknown>,\n targetId: string,\n handler: HandlerMethodNode | undefined,\n): SelectedHandlerEvidence {\n if (!handler) return unavailableHandlerEvidence(evidence, targetId);\n const selected = selectedHandlerProvenance(handlerSource(handler));\n const stored = record(evidence.selectedHandler);\n const mismatchedFields = storedSelectedHandlerMismatches(\n stored, selected, targetId,\n );\n if (mismatchedFields.length === 0)\n return { handler, evidence: { ...evidence, selectedHandler: selected } };\n return {\n handler,\n evidence: {\n ...evidence,\n selectedHandler: selected,\n selectedHandlerProvenanceAudit: {\n status: 'mismatch',\n graphTargetId: targetId,\n mismatchedFields,\n persistedSelectedHandler: stored,\n },\n },\n diagnostic: {\n severity: 'warning',\n code: 'selected_handler_provenance_mismatch',\n message: 'Persisted selected handler provenance did not match the resolved graph target',\n graphTargetId: targetId,\n mismatchedFields,\n sourceFile: handler.sourceFile,\n sourceLine: handler.sourceLine,\n },\n };\n}\n\nfunction unavailableHandlerEvidence(\n evidence: Record<string, unknown>,\n targetId: string,\n): SelectedHandlerEvidence {\n return {\n evidence: {\n ...evidence,\n selectedHandlerProvenanceAudit: {\n status: 'unavailable',\n graphTargetId: targetId,\n reason: 'handler_target_not_indexed',\n },\n },\n diagnostic: {\n severity: 'warning',\n code: 'selected_handler_target_not_found',\n message: 'Resolved implementation target is not an indexed handler method',\n graphTargetId: targetId,\n },\n unresolvedReason: 'Resolved implementation target is not an indexed handler method',\n };\n}\n\nfunction handlerNodeFromRow(\n row: Record<string, unknown> | undefined,\n): HandlerMethodNode | undefined {\n const methodId = numberValue(row?.methodId);\n const methodName = stringValue(row?.methodName);\n const className = stringValue(row?.className);\n const sourceFile = stringValue(row?.sourceFile);\n const sourceLine = numberValue(row?.sourceLine);\n const repoId = numberValue(row?.repoId);\n const repoName = stringValue(row?.repoName);\n if (methodId === undefined || !methodName || !className || !sourceFile\n || sourceLine === undefined || repoId === undefined || !repoName)\n return undefined;\n return {\n id: `handler_method:${methodId}`,\n kind: 'handler_method',\n label: `${repoName}:${className}.${methodName}`,\n methodId,\n methodName,\n className,\n sourceFile,\n sourceLine,\n repoId,\n repoName,\n packageName: stringValue(row?.packageName),\n };\n}\n\nfunction handlerSource(node: HandlerMethodNode): SelectedHandlerSource {\n return {\n methodId: node.methodId,\n methodName: node.methodName,\n className: node.className,\n repositoryId: node.repoId,\n repositoryName: node.repoName,\n repositoryPackageName: node.packageName,\n sourceFile: node.sourceFile,\n sourceLine: node.sourceLine,\n };\n}\n\nfunction storedSelectedHandlerMismatches(\n stored: Record<string, unknown>,\n selected: SelectedHandlerProvenance,\n targetId: string,\n): string[] {\n if (Object.keys(stored).length === 0) return [];\n const expectedRepository = record(stored.repository);\n const selectedRepository = selected.repository ?? {};\n return [\n mismatch('graphTargetId', stored.graphTargetId, targetId),\n mismatch('methodId', stored.methodId, selected.methodId),\n mismatch('className', stored.className, selected.className),\n mismatch('methodName', stored.methodName, selected.methodName),\n mismatch('sourceFile', stored.sourceFile, selected.sourceFile),\n mismatch('sourceLine', stored.sourceLine, selected.sourceLine),\n mismatch('repository.id', expectedRepository.id, selectedRepository.id),\n mismatch('repository.name', expectedRepository.name, selectedRepository.name),\n mismatch('repository.packageName', expectedRepository.packageName,\n selectedRepository.packageName),\n ].flatMap((field) => field ? [field] : []);\n}\n\nfunction mismatch(\n field: string,\n stored: unknown,\n actual: unknown,\n): string | undefined {\n return stored === undefined || stored === actual ? undefined : field;\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : {};\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n","import { createHash } from 'node:crypto';\nimport type { Db } from '../db/connection.js';\nimport type { ContextBinding } from './008-contextual-runtime-state.js';\n\nexport interface TraversalScopeIdentity {\n workspaceId?: number;\n repoId?: number;\n files?: ReadonlySet<string>;\n symbolIds?: ReadonlySet<number>;\n context?: ReadonlyMap<string, ContextBinding>;\n}\n\nexport interface TraversalScopeState {\n structuralKey: string;\n evaluationKey: string;\n ancestry: ReadonlySet<string>;\n}\n\nexport type TraversalScheduleKind = 'scheduled' | 'converged' | 'cycle';\n\nexport interface TraversalScheduleDecision {\n kind: TraversalScheduleKind;\n state: TraversalScopeState;\n alreadyExpanded: boolean;\n}\n\nexport function compareBinary(left: string, right: string): number {\n const leftPoints = [...left];\n const rightPoints = [...right];\n const length = Math.min(leftPoints.length, rightPoints.length);\n for (let index = 0; index < length; index += 1) {\n const leftPoint = leftPoints[index]?.codePointAt(0) ?? 0;\n const rightPoint = rightPoints[index]?.codePointAt(0) ?? 0;\n if (leftPoint !== rightPoint) return leftPoint < rightPoint ? -1 : 1;\n }\n return leftPoints.length - rightPoints.length;\n}\n\nexport function resolveTraversalWorkspaceId(\n db: Db,\n requestedWorkspaceId: number | undefined,\n repoId: number | undefined,\n): number | undefined {\n if (requestedWorkspaceId !== undefined) return requestedWorkspaceId;\n if (repoId !== undefined) {\n const row = db.prepare(\n 'SELECT workspace_id workspaceId FROM repositories WHERE id=?',\n ).get(repoId) as { workspaceId?: number } | undefined;\n return typeof row?.workspaceId === 'number' ? row.workspaceId : undefined;\n }\n const rows = db.prepare(`SELECT DISTINCT w.id workspaceId FROM workspaces w\n JOIN repositories r ON r.workspace_id=w.id ORDER BY w.id LIMIT 2`).all() as\n Array<{ workspaceId?: number }>;\n return rows.length === 1 && typeof rows[0]?.workspaceId === 'number'\n ? rows[0].workspaceId : undefined;\n}\n\nexport function structuralScopeKey(\n workspaceId: number | undefined,\n repoId: number | undefined,\n files: ReadonlySet<string> | undefined,\n symbolIds: ReadonlySet<number> | undefined,\n): string {\n return JSON.stringify([\n workspaceId ?? null,\n repoId ?? null,\n files ? [...files].sort(compareBinary) : null,\n symbolIds ? [...symbolIds].sort((left, right) => left - right) : null,\n ]);\n}\n\nexport function canonicalContextFingerprint(\n context: ReadonlyMap<string, ContextBinding> | undefined,\n): string {\n const entries = [...(context ?? new Map<string, ContextBinding>()).entries()]\n .map(([name, binding]) => `${JSON.stringify(name)}:${canonicalValue(binding)}`)\n .sort(compareBinary);\n return createHash('sha256').update(`[${entries.join(',')}]`).digest('hex');\n}\n\nexport function evaluationScopeKey(\n structuralKey: string,\n context: ReadonlyMap<string, ContextBinding> | undefined,\n): string {\n return JSON.stringify([structuralKey, canonicalContextFingerprint(context)]);\n}\n\nexport class TraversalScopeScheduler {\n readonly #scheduled = new Set<string>();\n readonly #expanded = new Set<string>();\n readonly #structuralByEvaluation = new Map<string, string>();\n readonly #childrenByEvaluation = new Map<string, Set<string>>();\n\n schedule(\n identity: TraversalScopeIdentity,\n parent?: TraversalScopeState,\n ): TraversalScheduleDecision {\n const state = scopeState(identity, parent);\n this.#rememberState(state);\n if (parent) this.#rememberState(parent);\n const cycle = parent\n ? parent.ancestry.has(state.structuralKey)\n || this.#reachesStructural(state.evaluationKey, parent.structuralKey)\n : false;\n if (parent) this.#recordEdge(parent.evaluationKey, state.evaluationKey);\n if (cycle)\n return { kind: 'cycle', state, alreadyExpanded: this.#expanded.has(state.evaluationKey) };\n if (this.#scheduled.has(state.evaluationKey))\n return { kind: 'converged', state, alreadyExpanded: this.#expanded.has(state.evaluationKey) };\n this.#scheduled.add(state.evaluationKey);\n return { kind: 'scheduled', state, alreadyExpanded: false };\n }\n\n markExpanded(state: TraversalScopeState): boolean {\n if (this.#expanded.has(state.evaluationKey)) return false;\n this.#expanded.add(state.evaluationKey);\n return true;\n }\n\n #rememberState(state: TraversalScopeState): void {\n this.#structuralByEvaluation.set(state.evaluationKey, state.structuralKey);\n }\n\n #recordEdge(parent: string, child: string): void {\n const children = this.#childrenByEvaluation.get(parent) ?? new Set<string>();\n children.add(child);\n this.#childrenByEvaluation.set(parent, children);\n }\n\n #reachesStructural(start: string, targetStructuralKey: string): boolean {\n const pending = [start];\n const seen = new Set<string>();\n let cursor = 0;\n while (cursor < pending.length) {\n const current = pending[cursor];\n cursor += 1;\n if (seen.has(current)) continue;\n seen.add(current);\n if (this.#structuralByEvaluation.get(current) === targetStructuralKey)\n return true;\n pending.push(...(this.#childrenByEvaluation.get(current) ?? []));\n }\n return false;\n }\n}\n\nfunction scopeState(\n identity: TraversalScopeIdentity,\n parent: TraversalScopeState | undefined,\n): TraversalScopeState {\n const structuralKey = structuralScopeKey(\n identity.workspaceId, identity.repoId, identity.files, identity.symbolIds,\n );\n const ancestry = new Set(parent?.ancestry ?? []);\n ancestry.add(structuralKey);\n return {\n structuralKey,\n evaluationKey: evaluationScopeKey(structuralKey, identity.context),\n ancestry,\n };\n}\n\nfunction canonicalValue(value: unknown): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `string:${JSON.stringify(value)}`;\n if (typeof value === 'boolean') return `boolean:${String(value)}`;\n if (typeof value === 'number') return canonicalNumber(value);\n if (typeof value === 'bigint') return `bigint:${String(value)}`;\n if (Array.isArray(value))\n return `array:[${value.map(canonicalValue).join(',')}]`;\n if (!isRecord(value)) return `unsupported:${typeof value}`;\n const entries = Object.entries(value).sort(([left], [right]) => compareBinary(left, right));\n return `object:{${entries.map(([key, child]) =>\n `${JSON.stringify(key)}:${canonicalValue(child)}`).join(',')}}`;\n}\n\nfunction canonicalNumber(value: number): string {\n if (Number.isNaN(value)) return 'number:NaN';\n if (value === Number.POSITIVE_INFINITY) return 'number:Infinity';\n if (value === Number.NEGATIVE_INFINITY) return 'number:-Infinity';\n if (Object.is(value, -0)) return 'number:-0';\n return `number:${String(value)}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n","import type { Db } from '../db/connection.js';\nimport {\n type TraversalScopeScheduler,\n type TraversalScopeState,\n} from './010-traversal-scope.js';\n\nexport type EventSubscriberTransitionStatus =\n | 'resolved'\n | 'ambiguous'\n | 'unresolved';\n\nexport interface EventSubscriberSymbolTarget {\n symbolId: number;\n kind: string;\n qualifiedName: string;\n repoId: number;\n repoName: string;\n packageName?: string;\n sourceFile: string;\n sourceLine: number;\n endLine: number;\n startOffset?: number;\n endOffset?: number;\n}\n\nexport interface EventSubscriberTransition {\n graphEdgeId: number;\n graphGeneration: number;\n eventName: string;\n status: EventSubscriberTransitionStatus;\n targetKind: 'symbol' | 'symbol_reference' | 'subscription_handler';\n targetId: string;\n confidence: number;\n unresolvedReason?: string;\n reasonCode?: string;\n subscribeCallId?: number;\n symbolCallId?: number;\n roleSiteMatchCount: number;\n callRole?: string;\n factOrigin?: string;\n associationBasis?: string;\n dispatchScope?: string;\n subscriptionRepoId?: number;\n subscriptionRepoName?: string;\n sourceFile?: string;\n sourceLine?: number;\n callSiteStartOffset?: number;\n callSiteEndOffset?: number;\n wrapperFunction?: string;\n resolutionStrategy?: string;\n associationStatus?: string;\n symbolCallResolutionStatus?: string;\n candidateCount: number;\n symbolCallUnresolvedReason?: string;\n omittedSymbolCallUnresolvedReasonCharacterCount?: number;\n handler?: EventSubscriberSymbolTarget;\n}\n\nexport interface EventSubscriberTransitionQuery {\n workspaceId: number;\n graphGeneration: number;\n eventName: string;\n}\n\nexport type EventBodyExpansion =\n | 'scheduled'\n | 'already_scheduled'\n | 'already_expanded'\n | 'cycle_blocked'\n | 'depth_limited'\n | 'not_resolved';\n\nexport interface PlannedEventSubscriberTransition {\n transition: EventSubscriberTransition;\n node: Record<string, unknown>;\n evidence: Record<string, unknown>;\n bodyExpansion: EventBodyExpansion;\n state?: TraversalScopeState;\n}\n\nexport function planEventSubscriberTransitions(\n db: Db,\n query: EventSubscriberTransitionQuery,\n scheduler: TraversalScopeScheduler,\n parent: TraversalScopeState,\n depth: number,\n maxDepth: number,\n): PlannedEventSubscriberTransition[] {\n return loadEventSubscriberTransitions(db, query).map((transition) => {\n const handler = transition.handler;\n if (!handler) return plannedTransition(transition, 'not_resolved');\n if (depth >= maxDepth)\n return plannedTransition(transition, 'depth_limited');\n const state = scheduler.schedule({\n workspaceId: query.workspaceId,\n repoId: handler.repoId,\n files: new Set([handler.sourceFile]),\n symbolIds: new Set([handler.symbolId]),\n context: new Map(),\n }, parent);\n const bodyExpansion: EventBodyExpansion = state.kind === 'scheduled'\n ? 'scheduled'\n : state.kind === 'cycle' ? 'cycle_blocked'\n : state.alreadyExpanded ? 'already_expanded' : 'already_scheduled';\n return plannedTransition(transition, bodyExpansion, state.state);\n });\n}\n\nfunction plannedTransition(\n transition: EventSubscriberTransition,\n bodyExpansion: EventBodyExpansion,\n state?: TraversalScopeState,\n): PlannedEventSubscriberTransition {\n return {\n transition,\n node: eventSubscriberNode(transition),\n evidence: eventTransitionEvidence(transition, bodyExpansion),\n bodyExpansion,\n state,\n };\n}\n\nexport function eventSubscriberNode(\n transition: EventSubscriberTransition,\n): Record<string, unknown> {\n const handler = transition.handler;\n if (!handler) return {\n id: `event_subscription:${transition.graphEdgeId}`,\n kind: transition.targetKind,\n label: `${transition.targetKind}:${transition.targetId}`,\n graphEdgeId: transition.graphEdgeId,\n };\n const fileName = handler.sourceFile.split('/').at(-1) ?? handler.sourceFile;\n return {\n id: `symbol:${handler.symbolId}`,\n kind: 'symbol',\n label: `${fileName}:${handler.qualifiedName}`,\n symbolId: handler.symbolId,\n symbolName: handler.qualifiedName,\n qualifiedName: handler.qualifiedName,\n sourceFile: handler.sourceFile,\n startLine: handler.sourceLine,\n endLine: handler.endLine,\n repoName: handler.repoName,\n repoId: handler.repoId,\n };\n}\n\nexport function eventTransitionEvidence(\n transition: EventSubscriberTransition,\n bodyExpansion: EventBodyExpansion,\n): Record<string, unknown> {\n return {\n graphEdgeId: transition.graphEdgeId,\n graphGeneration: transition.graphGeneration,\n subscribeCallId: transition.subscribeCallId,\n symbolCallId: transition.symbolCallId,\n eventName: transition.eventName,\n matchStrategy: 'workspace_exact_event_name',\n dispatchCertainty: 'static_name_only',\n associationBasis: transition.associationBasis,\n dispatchScope: transition.dispatchScope,\n roleSiteMatchCount: transition.roleSiteMatchCount,\n callRole: transition.callRole,\n factOrigin: transition.factOrigin,\n repositoryId: transition.subscriptionRepoId,\n repositoryName: transition.subscriptionRepoName,\n sourceFile: transition.sourceFile,\n sourceLine: transition.sourceLine,\n callSiteStartOffset: transition.callSiteStartOffset,\n callSiteEndOffset: transition.callSiteEndOffset,\n wrapperFunction: transition.wrapperFunction,\n handlerSymbolId: transition.handler?.symbolId,\n handlerSourceFile: transition.handler?.sourceFile,\n handlerSourceLine: transition.handler?.sourceLine,\n associationStatus: transition.associationStatus ?? transition.status,\n symbolCallResolutionStatus: transition.symbolCallResolutionStatus,\n resolutionStatus: transition.status,\n resolutionStrategy: transition.resolutionStrategy,\n candidateCount: transition.candidateCount,\n symbolCallUnresolvedReason: transition.symbolCallUnresolvedReason,\n omittedSymbolCallUnresolvedReasonCharacterCount:\n transition.omittedSymbolCallUnresolvedReasonCharacterCount,\n reasonCode: transition.reasonCode,\n bodyExpansion,\n cycle: bodyExpansion === 'cycle_blocked' || undefined,\n cycleReason: bodyExpansion === 'cycle_blocked'\n ? 'structural_ancestry_cycle' : undefined,\n };\n}\n\nexport function loadEventSubscriberTransitions(\n db: Db,\n query: EventSubscriberTransitionQuery,\n): EventSubscriberTransition[] {\n const rows = db.prepare(`SELECT ge.id graphEdgeId,ge.generation graphGeneration,\n ge.from_id eventName,ge.status,ge.to_kind targetKind,ge.to_id targetId,\n ge.confidence,ge.unresolved_reason unresolvedReason,ge.evidence_json evidenceJson,\n subscribe.id subscribeCallId,subscribe.repo_id subscriptionRepoId,\n subscribe.source_file sourceFile,subscribe.source_line sourceLine,\n subscribe.call_site_start_offset callSiteStartOffset,\n subscribe.call_site_end_offset callSiteEndOffset,\n subscription_repo.name subscriptionRepoName,\n handler.id handlerSymbolId,handler.kind handlerKind,\n handler.qualified_name handlerQualifiedName,handler.source_file handlerSourceFile,\n handler.start_line handlerSourceLine,handler.end_line handlerEndLine,\n handler.start_offset handlerStartOffset,handler.end_offset handlerEndOffset,\n handler_repo.id handlerRepoId,handler_repo.name handlerRepoName,\n handler_repo.package_name handlerPackageName\n FROM graph_edges ge\n LEFT JOIN outbound_calls subscribe\n ON subscribe.id=CAST(json_extract(ge.evidence_json,'$.subscribeCallId') AS INTEGER)\n LEFT JOIN repositories subscription_repo\n ON subscription_repo.id=subscribe.repo_id\n AND subscription_repo.workspace_id=ge.workspace_id\n LEFT JOIN symbols handler\n ON ge.to_kind='symbol' AND handler.id=CAST(ge.to_id AS INTEGER)\n LEFT JOIN repositories handler_repo\n ON handler_repo.id=handler.repo_id AND handler_repo.workspace_id=ge.workspace_id\n WHERE ge.workspace_id=? AND ge.generation=?\n AND ge.edge_type='EVENT_SUBSCRIPTION_HANDLED_BY' AND ge.from_kind='event'\n AND ge.from_id COLLATE BINARY=? COLLATE BINARY\n ORDER BY COALESCE(subscription_repo.name,'') COLLATE BINARY,\n COALESCE(subscription_repo.id,0),COALESCE(subscribe.source_file,'') COLLATE BINARY,\n subscribe.call_site_start_offset,subscribe.call_site_end_offset,ge.id`).all(\n query.workspaceId, query.graphGeneration, query.eventName,\n );\n return rows.flatMap((row) => {\n const transition = transitionFromRow(row);\n return transition ? [transition] : [];\n });\n}\n\nfunction transitionFromRow(\n row: Record<string, unknown>,\n): EventSubscriberTransition | undefined {\n const graphEdgeId = numberValue(row.graphEdgeId);\n const graphGeneration = numberValue(row.graphGeneration);\n const eventName = stringValue(row.eventName);\n const targetId = stringValue(row.targetId);\n if (graphEdgeId === undefined || graphGeneration === undefined\n || eventName === undefined || targetId === undefined) return undefined;\n const evidence = parseEvidence(row.evidenceJson);\n const handler = symbolTarget(row);\n const status = transitionStatus(stringValue(row.status), handler);\n const reasonCode = status === 'resolved'\n ? undefined\n : stringValue(evidence.reasonCode) ?? missingTargetReason(row, handler);\n return {\n graphEdgeId, graphGeneration, eventName, status,\n targetKind: targetKind(row.targetKind), targetId,\n confidence: numberValue(row.confidence) ?? 0,\n unresolvedReason: status === 'resolved'\n ? undefined : stringValue(row.unresolvedReason) ?? reasonCode,\n reasonCode,\n ...associationEvidence(row, evidence),\n handler,\n };\n}\n\nfunction associationEvidence(\n row: Record<string, unknown>,\n evidence: Record<string, unknown>,\n): Omit<EventSubscriberTransition,\n 'graphEdgeId' | 'graphGeneration' | 'eventName' | 'status' | 'targetKind'\n | 'targetId' | 'confidence' | 'unresolvedReason' | 'reasonCode' | 'handler'> {\n const symbolCallUnresolvedReason = stringValue(\n evidence.symbolCallUnresolvedReason,\n );\n return {\n subscribeCallId: numberValue(row.subscribeCallId),\n symbolCallId: numberValue(evidence.symbolCallId),\n roleSiteMatchCount: nonNegativeCount(evidence.roleSiteMatchCount),\n callRole: stringValue(evidence.callRole),\n factOrigin: stringValue(evidence.factOrigin),\n associationBasis: stringValue(evidence.associationBasis),\n dispatchScope: stringValue(evidence.dispatchScope),\n subscriptionRepoId: numberValue(row.subscriptionRepoId),\n subscriptionRepoName: stringValue(row.subscriptionRepoName),\n sourceFile: stringValue(row.sourceFile),\n sourceLine: numberValue(row.sourceLine),\n callSiteStartOffset: numberValue(row.callSiteStartOffset),\n callSiteEndOffset: numberValue(row.callSiteEndOffset),\n wrapperFunction: stringValue(evidence.wrapperFunction),\n resolutionStrategy: stringValue(evidence.resolutionStrategy),\n associationStatus: stringValue(evidence.associationStatus),\n symbolCallResolutionStatus: stringValue(evidence.symbolCallResolutionStatus),\n candidateCount: nonNegativeCount(evidence.candidateCount),\n symbolCallUnresolvedReason,\n omittedSymbolCallUnresolvedReasonCharacterCount: symbolCallUnresolvedReason\n ? nonNegativeCount(evidence.omittedSymbolCallUnresolvedReasonCharacterCount)\n : undefined,\n };\n}\n\nfunction symbolTarget(\n row: Record<string, unknown>,\n): EventSubscriberSymbolTarget | undefined {\n const symbolId = numberValue(row.handlerSymbolId);\n const repoId = numberValue(row.handlerRepoId);\n const repoName = stringValue(row.handlerRepoName);\n const sourceFile = stringValue(row.handlerSourceFile);\n const sourceLine = numberValue(row.handlerSourceLine);\n const endLine = numberValue(row.handlerEndLine);\n const kind = stringValue(row.handlerKind);\n const qualifiedName = stringValue(row.handlerQualifiedName);\n if (symbolId === undefined || repoId === undefined || !repoName || !sourceFile\n || sourceLine === undefined || endLine === undefined || !kind || !qualifiedName)\n return undefined;\n return {\n symbolId, repoId, repoName, sourceFile, sourceLine, endLine, kind, qualifiedName,\n packageName: stringValue(row.handlerPackageName),\n startOffset: numberValue(row.handlerStartOffset),\n endOffset: numberValue(row.handlerEndOffset),\n };\n}\n\nfunction transitionStatus(\n value: string | undefined,\n handler: EventSubscriberSymbolTarget | undefined,\n): EventSubscriberTransitionStatus {\n if (value === 'resolved' && handler) return 'resolved';\n return value === 'ambiguous' ? 'ambiguous' : 'unresolved';\n}\n\nfunction missingTargetReason(\n row: Record<string, unknown>,\n handler: EventSubscriberSymbolTarget | undefined,\n): string | undefined {\n return stringValue(row.status) === 'resolved' && !handler\n ? 'subscription_handler_target_missing'\n : undefined;\n}\n\nfunction targetKind(\n value: unknown,\n): EventSubscriberTransition['targetKind'] {\n return value === 'symbol' || value === 'symbol_reference'\n || value === 'subscription_handler' ? value : 'subscription_handler';\n}\n\nfunction parseEvidence(value: unknown): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(String(value ?? '{}'));\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction nonNegativeCount(value: unknown): number {\n const count = numberValue(value);\n return count === undefined ? 0 : Math.max(0, Math.floor(count));\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n","import type { Db } from '../db/connection.js';\n\nexport interface TraceGraphEdgeRow extends Record<string, unknown> {\n id: number;\n edge_type: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n confidence: number;\n evidence_json: string;\n unresolved_reason?: string;\n status?: string;\n}\n\nexport function graphForCalls(\n db: Db,\n callIds: number[],\n): Map<number, TraceGraphEdgeRow[]> {\n const map = new Map<number, TraceGraphEdgeRow[]>();\n if (callIds.length === 0) return map;\n const rows = db.prepare(`SELECT * FROM graph_edges\n WHERE from_kind='call'\n AND from_id IN (${callIds.map(() => '?').join(',')})\n ORDER BY id`).all(\n ...callIds.map(String),\n ) as TraceGraphEdgeRow[];\n for (const row of rows) {\n const id = Number(row.from_id);\n map.set(id, [...(map.get(id) ?? []), row]);\n }\n return map;\n}\n\nexport function symbolNode(\n db: Db,\n symbolId: number,\n): Record<string, unknown> | undefined {\n const row = db.prepare(`SELECT s.id symbolId,s.name symbolName,\n s.qualified_name qualifiedName,s.source_file sourceFile,\n s.start_line startLine,s.end_line endLine,r.name repoName,r.id repoId\n FROM symbols s JOIN repositories r ON r.id=s.repo_id\n WHERE s.id=?`).get(symbolId) as Record<string, unknown> | undefined;\n if (!row) return undefined;\n const sourceFile = String(row.sourceFile ?? '');\n const fileName = sourceFile.split('/').at(-1) ?? sourceFile;\n return {\n id: `symbol:${symbolId}`,\n kind: 'symbol',\n label: `${fileName}:${String(row.qualifiedName ?? row.symbolName)}`,\n ...row,\n };\n}\n\nexport function operationNode(\n db: Db,\n operationId: string,\n): Record<string, unknown> | undefined {\n const row = db.prepare(`SELECT o.id operationId,o.operation_name operationName,\n o.operation_type operationType,o.operation_path operationPath,\n o.source_file sourceFile,o.source_line sourceLine,s.id serviceId,\n s.service_name serviceName,s.qualified_name qualifiedName,\n s.service_path servicePath,r.id repoId,r.name repoName\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id\n JOIN repositories r ON r.id=s.repo_id WHERE o.id=?`).get(\n operationId,\n ) as Record<string, unknown> | undefined;\n if (!row) return undefined;\n return {\n id: `operation:${operationId}`,\n kind: 'operation',\n label: `${String(row.repoName)}:${String(row.servicePath)}${String(row.operationPath)}`,\n ...row,\n };\n}\n","import type { Db } from '../db/connection.js';\nimport { currentFactLifecycleDiagnostic } from '../db/001-fact-lifecycle.js';\nimport type { ContextBinding } from './008-contextual-runtime-state.js';\nimport {\n resolveTraversalWorkspaceId,\n type TraversalScopeScheduler,\n type TraversalScopeState,\n} from './010-traversal-scope.js';\n\nexport interface TraceQueueScope {\n repoId?: number;\n files?: Set<string>;\n symbolIds?: Set<number>;\n depth: number;\n context: Map<string, ContextBinding>;\n state: TraversalScopeState;\n unownedOnly?: boolean;\n rootObservationOnly?: boolean;\n}\n\nexport interface PendingTraceRootScope {\n repoId: number;\n files: Set<string>;\n symbolIds: Set<number>;\n unownedOnly: boolean;\n rootObservationOnly: boolean;\n}\n\ninterface RootCallRow {\n id: number;\n repoId: number;\n repoName: string;\n workspaceId: number;\n graphGeneration: number;\n sourceSymbolId?: number | null;\n sourceFile: string;\n callType: string;\n eventName?: string | null;\n}\n\nexport interface TraceRootPlan {\n workspaceId?: number;\n queue: TraceQueueScope[];\n pendingRoots: PendingTraceRootScope[];\n diagnostic?: Record<string, unknown>;\n}\n\nexport function createTraceRootPlan(\n db: Db,\n scheduler: TraversalScopeScheduler,\n scope: {\n repoId?: number;\n files?: Set<string>;\n symbolIds?: Set<number>;\n selectorMatched: boolean;\n },\n requestedWorkspaceId: number | undefined,\n includeAsync: boolean,\n): TraceRootPlan {\n const workspaceId = resolveTraversalWorkspaceId(\n db, requestedWorkspaceId, scope.repoId,\n );\n if (workspaceId !== undefined) {\n const lifecycle = currentFactLifecycleDiagnostic(db, workspaceId);\n if (lifecycle) return {\n workspaceId, queue: [], pendingRoots: [], diagnostic: lifecycle,\n };\n }\n if (!scope.selectorMatched)\n return { workspaceId, queue: [], pendingRoots: [] };\n if (workspaceId === undefined) return {\n workspaceId, queue: [], pendingRoots: [],\n diagnostic: workspaceAmbiguityDiagnostic(db),\n };\n const pendingRoots = includeAsync\n ? rootScopes(db, workspaceId, scope) : undefined;\n if (pendingRoots)\n return { workspaceId, queue: [], pendingRoots };\n return {\n workspaceId,\n queue: initialQueue(scheduler, workspaceId, scope),\n pendingRoots: [],\n };\n}\n\nexport function nextPendingRoot(\n pendingRoots: PendingTraceRootScope[],\n scheduler: TraversalScopeScheduler,\n workspaceId: number,\n): TraceQueueScope | undefined {\n while (pendingRoots.length > 0) {\n const root = pendingRoots.shift();\n if (!root) return undefined;\n const context = new Map<string, ContextBinding>();\n const scheduled = scheduler.schedule({\n workspaceId, repoId: root.repoId, files: root.files,\n symbolIds: root.symbolIds, context,\n });\n if (scheduled.kind !== 'scheduled') continue;\n return { ...root, depth: 1, context, state: scheduled.state };\n }\n return undefined;\n}\n\nexport function claimPendingRoot(\n pendingRoots: PendingTraceRootScope[],\n target: {\n repoId?: number;\n files: ReadonlySet<string>;\n symbolIds: ReadonlySet<number>;\n },\n): boolean {\n const index = pendingRoots.findIndex((root) =>\n target.repoId === root.repoId\n && !root.unownedOnly\n && setsEqual(root.files, target.files)\n && setsEqual(root.symbolIds, target.symbolIds));\n if (index < 0) return false;\n pendingRoots.splice(index, 1);\n return true;\n}\n\nexport function enqueueCausalScope(\n queue: TraceQueueScope[],\n pendingRoots: PendingTraceRootScope[],\n scope: TraceQueueScope,\n): void {\n if (scope.context.size === 0 && scope.files && scope.symbolIds)\n claimPendingRoot(pendingRoots, {\n repoId: scope.repoId, files: scope.files, symbolIds: scope.symbolIds,\n });\n queue.push(scope);\n}\n\nfunction initialQueue(\n scheduler: TraversalScopeScheduler,\n workspaceId: number,\n scope: { repoId?: number; files?: Set<string>; symbolIds?: Set<number> },\n): TraceQueueScope[] {\n const context = new Map<string, ContextBinding>();\n const scheduled = scheduler.schedule({\n workspaceId, repoId: scope.repoId, files: scope.files,\n symbolIds: scope.symbolIds, context,\n });\n return scheduled.kind === 'scheduled' ? [{\n repoId: scope.repoId, files: scope.files, symbolIds: scope.symbolIds,\n depth: 1, context, state: scheduled.state,\n }] : [];\n}\n\nfunction rootScopes(\n db: Db,\n workspaceId: number,\n scope: { repoId?: number; files?: Set<string>; symbolIds?: Set<number> },\n): PendingTraceRootScope[] | undefined {\n if (scope.symbolIds && scope.symbolIds.size === 1) return undefined;\n const calls = scopedRootCalls(db, workspaceId, scope);\n if (!hasExactDispatch(db, calls)) return undefined;\n if (scope.symbolIds && scope.symbolIds.size > 1)\n return selectedSymbolRoots(db, workspaceId, scope.symbolIds);\n return callOwnerRoots(calls);\n}\n\nfunction scopedRootCalls(\n db: Db,\n workspaceId: number,\n scope: { repoId?: number; files?: Set<string>; symbolIds?: Set<number> },\n): RootCallRow[] {\n return rootCalls(db, workspaceId, scope.repoId, scope.files)\n .filter((call) => !scope.symbolIds\n || (typeof call.sourceSymbolId === 'number'\n && scope.symbolIds.has(call.sourceSymbolId)));\n}\n\nfunction callOwnerRoots(\n calls: RootCallRow[],\n): PendingTraceRootScope[] | undefined {\n const roots = new Map<string, PendingTraceRootScope>();\n for (const call of calls) {\n const [key, root] = callOwnerRoot(call);\n if (roots.has(key)) continue;\n roots.set(key, root);\n }\n return roots.size > 0 ? [...roots.values()] : undefined;\n}\n\nfunction callOwnerRoot(\n call: RootCallRow,\n): [string, PendingTraceRootScope] {\n const symbolId = call.sourceSymbolId;\n const owned = typeof symbolId === 'number';\n const key = owned\n ? `symbol:${symbolId}` : `unowned:${call.repoId}:${call.sourceFile}`;\n return [key, {\n repoId: call.repoId,\n files: new Set([call.sourceFile]),\n symbolIds: owned ? new Set([symbolId]) : new Set(),\n unownedOnly: !owned,\n rootObservationOnly: true,\n }];\n}\n\nfunction selectedSymbolRoots(\n db: Db,\n workspaceId: number,\n symbolIds: Set<number>,\n): PendingTraceRootScope[] {\n const ids = [...symbolIds];\n const rows = db.prepare(`SELECT s.id,s.repo_id repoId,s.source_file sourceFile\n FROM symbols s JOIN repositories r ON r.id=s.repo_id\n WHERE r.workspace_id=? AND s.id IN (${ids.map(() => '?').join(',')})\n ORDER BY r.name COLLATE BINARY,r.id,s.source_file COLLATE BINARY,\n s.start_offset,s.end_offset,s.id`).all(workspaceId, ...ids);\n return rows.flatMap((row) => typeof row.id === 'number'\n && typeof row.repoId === 'number' && typeof row.sourceFile === 'string'\n ? [{ repoId: row.repoId, files: new Set([row.sourceFile]),\n symbolIds: new Set([row.id]), unownedOnly: false,\n rootObservationOnly: false }]\n : []);\n}\n\nfunction setsEqual<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): boolean {\n if (left.size !== right.size) return false;\n return [...left].every((value) => right.has(value));\n}\n\nfunction rootCalls(\n db: Db,\n workspaceId: number,\n repoId: number | undefined,\n files: Set<string> | undefined,\n): RootCallRow[] {\n const rows = db.prepare(`SELECT c.id,c.repo_id repoId,r.name repoName,\n r.workspace_id workspaceId,r.graph_generation graphGeneration,\n c.source_symbol_id sourceSymbolId,c.source_file sourceFile,\n c.call_type callType,c.event_name_expr eventName\n FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id\n WHERE r.workspace_id=? AND (? IS NULL OR c.repo_id=?)\n ORDER BY r.name COLLATE BINARY,r.id,c.source_file COLLATE BINARY,\n c.call_site_start_offset,c.call_site_end_offset,c.source_line,c.id`).all(\n workspaceId, repoId, repoId,\n ) as unknown as RootCallRow[];\n return files ? rows.filter((row) => files.has(row.sourceFile)) : rows;\n}\n\nfunction hasExactDispatch(db: Db, calls: RootCallRow[]): boolean {\n const match = db.prepare(`SELECT 1 matched FROM graph_edges emitted\n WHERE emitted.workspace_id=? AND emitted.generation=?\n AND emitted.edge_type='HANDLER_EMITS_EVENT'\n AND emitted.from_kind='call' AND emitted.from_id=?\n AND EXISTS (SELECT 1 FROM graph_edges subscriber\n WHERE subscriber.workspace_id=emitted.workspace_id\n AND subscriber.generation=emitted.generation\n AND subscriber.edge_type='EVENT_SUBSCRIPTION_HANDLED_BY'\n AND subscriber.from_kind='event'\n AND subscriber.from_id COLLATE BINARY=? COLLATE BINARY)\n LIMIT 1`);\n return calls.some((call) => call.callType === 'async_emit'\n && typeof call.eventName === 'string'\n && Boolean(match.get(call.workspaceId, call.graphGeneration,\n String(call.id), call.eventName)));\n}\n\nfunction workspaceAmbiguityDiagnostic(db: Db): Record<string, unknown> {\n const total = Number(db.prepare(`SELECT COUNT(DISTINCT w.id) count\n FROM workspaces w JOIN repositories r ON r.workspace_id=w.id`).get()?.count ?? 0);\n const workspaceIds = db.prepare(`SELECT DISTINCT w.id FROM workspaces w\n JOIN repositories r ON r.workspace_id=w.id ORDER BY w.id LIMIT 5`).all()\n .flatMap((row) => typeof row.id === 'number' ? [row.id] : []);\n return {\n severity: 'error', code: 'trace_workspace_ambiguous',\n message: total > 1\n ? 'Trace spans multiple indexed workspaces; provide a workspace identity.'\n : 'No indexed workspace could be selected for this trace.',\n workspaceCount: total, workspaceIds,\n omittedWorkspaceCount: Math.max(0, total - workspaceIds.length),\n remediation: 'Pass TraceOptions.workspaceId or select a repository in one workspace.',\n };\n}\n","import type { Db } from '../db/connection.js';\nimport { extractPlaceholders } from '../linker/dynamic-edge-resolver.js';\nimport { boundCandidateLikeEvidence } from '../utils/000-bounded-projection.js';\nimport type { ContextBinding } from './008-contextual-runtime-state.js';\n\nexport interface TraceContextCall extends Record<string, unknown> {\n service_binding_id?: number;\n evidence_json?: string;\n}\n\ntype BindingRow = Omit<ContextBinding,\n 'bindingId' | 'source' | 'calleeReceiver'> & {\n id?: number;\n symbolId?: number | null;\n variableName?: string;\n};\n\nexport function parseTraceEvidence(value: unknown): Record<string, unknown> {\n try {\n const parsed = JSON.parse(String(value || '{}')) as unknown;\n return isRecord(parsed) ? boundCandidateLikeEvidence(parsed) : {};\n } catch {\n return {};\n }\n}\n\nexport function receiverFromTraceEvidence(value: unknown): string | undefined {\n const evidence = parseTraceEvidence(value);\n return typeof evidence.receiver === 'string' ? evidence.receiver : undefined;\n}\n\nexport function knownBindingsForCalls(\n db: Db,\n calls: TraceContextCall[],\n): Map<string, ContextBinding> {\n const map = new Map<string, ContextBinding>();\n for (const call of calls) addCallBinding(db, map, call);\n return map;\n}\n\nexport function knownBindingsForScope(\n db: Db,\n repoId: number | undefined,\n symbolIds: Set<number> | undefined,\n files: Set<string> | undefined,\n): Map<string, ContextBinding> {\n const map = new Map<string, ContextBinding>();\n if (repoId === undefined) return map;\n const rows = db.prepare(`SELECT b.id,b.symbol_id symbolId,\n b.variable_name variableName,b.alias,b.alias_expr aliasExpr,\n b.destination_expr destinationExpr,b.service_path_expr servicePathExpr,\n b.source_file sourceFile,b.source_line sourceLine,\n req.service_path requireServicePath,req.destination requireDestination\n FROM service_bindings b LEFT JOIN cds_requires req\n ON req.repo_id=b.repo_id AND req.alias=b.alias\n WHERE b.repo_id=?\n ORDER BY b.source_file COLLATE BINARY,b.source_line,b.id`).all(\n repoId,\n ) as BindingRow[];\n for (const row of rows) addScopeBinding(map, row, symbolIds, files);\n return map;\n}\n\nexport function contextForSymbolCall(\n db: Db,\n symbolCall: Record<string, unknown>,\n callerBindings: Map<string, ContextBinding>,\n): Map<string, ContextBinding> {\n const next = new Map<string, ContextBinding>();\n if (callerBindings.size === 0) return next;\n const context = symbolCallContext(db, symbolCall);\n context.args.forEach((argument, index) => addArgumentBindings(\n next, callerBindings, context, argument, index,\n ));\n return next;\n}\n\nfunction addCallBinding(\n db: Db,\n map: Map<string, ContextBinding>,\n call: TraceContextCall,\n): void {\n const receiver = receiverFromTraceEvidence(call.evidence_json);\n const bindingId = Number(call.service_binding_id ?? 0);\n if (!receiver || !bindingId) return;\n const row = db.prepare(`SELECT b.id,b.alias,b.alias_expr aliasExpr,\n b.destination_expr destinationExpr,b.service_path_expr servicePathExpr,\n b.source_file sourceFile,b.source_line sourceLine,\n req.service_path requireServicePath,req.destination requireDestination\n FROM service_bindings b LEFT JOIN cds_requires req\n ON req.repo_id=b.repo_id AND req.alias=b.alias WHERE b.id=?`).get(\n bindingId,\n ) as ContextBinding | undefined;\n if (row) map.set(receiver, enrichBinding({\n ...row, bindingId, source: 'local_service_binding', calleeReceiver: receiver,\n }));\n}\n\nfunction addScopeBinding(\n map: Map<string, ContextBinding>,\n row: BindingRow,\n symbolIds: Set<number> | undefined,\n files: Set<string> | undefined,\n): void {\n if (!row.variableName) return;\n if (files && !files.has(String(row.sourceFile))) return;\n if (symbolIds?.size && row.symbolId != null\n && !symbolIds.has(Number(row.symbolId))) return;\n const candidate = enrichBinding({\n ...row, bindingId: Number(row.id), source: 'local_service_binding',\n calleeReceiver: row.variableName, resolutionStatus: 'selected',\n });\n const existing = map.get(row.variableName);\n if (!existing) {\n map.set(row.variableName, candidate);\n return;\n }\n map.set(row.variableName, ambiguousBinding(existing, candidate));\n}\n\nfunction ambiguousBinding(\n existing: ContextBinding,\n candidate: ContextBinding,\n): ContextBinding {\n const bindingCandidates = uniqueBindingCandidates([\n ...(existing.bindingCandidates ?? [bindingEvidence(existing)]),\n bindingEvidence(candidate),\n ]);\n return {\n ...candidate, bindingId: undefined,\n source: 'ambiguous_local_service_bindings', resolutionStatus: 'ambiguous',\n bindingCandidates,\n };\n}\n\ninterface SymbolCallContext {\n args: Array<Record<string, unknown>>;\n params: string[];\n parameterBindings: Array<Record<string, unknown>>;\n parameterPropertyAliases: Array<Record<string, unknown>>;\n provenance: Record<string, unknown>;\n}\n\nfunction symbolCallContext(\n db: Db,\n symbolCall: Record<string, unknown>,\n): SymbolCallContext {\n const callEvidence = parseTraceEvidence(symbolCall.evidence_json);\n const callee = db.prepare(`SELECT evidence_json evidenceJson,\n source_file sourceFile,start_line startLine FROM symbols WHERE id=?`).get(\n symbolCall.callee_symbol_id,\n ) as { evidenceJson?: string; sourceFile?: string; startLine?: number } | undefined;\n const evidence = parseTraceEvidence(callee?.evidenceJson);\n return {\n args: recordArray(callEvidence.callArguments),\n params: stringArray(evidence.parameters),\n parameterBindings: recordArray(evidence.parameterBindings),\n parameterPropertyAliases: recordArray(evidence.parameterPropertyAliases),\n provenance: {\n callerSite: { sourceFile: String(symbolCall.source_file ?? ''),\n sourceLine: Number(symbolCall.source_line ?? 0) },\n calleeSite: { sourceFile: callee?.sourceFile, sourceLine: callee?.startLine },\n },\n };\n}\n\nfunction addArgumentBindings(\n next: Map<string, ContextBinding>,\n caller: Map<string, ContextBinding>,\n context: SymbolCallContext,\n argument: Record<string, unknown>,\n index: number,\n): void {\n const parameterBinding = context.parameterBindings.find(\n (binding) => binding.index === index,\n );\n const parameter = parameterBinding?.kind === 'identifier'\n && typeof parameterBinding.name === 'string'\n ? parameterBinding.name : context.params[index];\n addIdentifierBinding(next, caller, context.provenance, argument, parameter);\n addObjectBindings(next, caller, context, argument, parameterBinding, parameter, index);\n addArrayBindings(next, caller, context.provenance, argument, parameterBinding, index);\n}\n\nfunction addIdentifierBinding(\n next: Map<string, ContextBinding>,\n caller: Map<string, ContextBinding>,\n provenance: Record<string, unknown>,\n argument: Record<string, unknown>,\n parameter: string | undefined,\n): void {\n if (argument.kind !== 'identifier' || typeof argument.name !== 'string'\n || !parameter) return;\n const binding = caller.get(argument.name);\n if (binding) next.set(parameter, { ...binding, ...provenance,\n source: 'local_symbol_argument', callerArgument: argument.name,\n calleeParameter: parameter, calleeReceiver: parameter });\n}\n\nfunction addObjectBindings(\n next: Map<string, ContextBinding>,\n caller: Map<string, ContextBinding>,\n context: SymbolCallContext,\n argument: Record<string, unknown>,\n parameterBinding: Record<string, unknown> | undefined,\n parameter: string | undefined,\n index: number,\n): void {\n if (argument.kind !== 'object_literal' || !Array.isArray(argument.properties)) return;\n for (const property of recordArray(argument.properties)) addObjectPropertyBinding(\n next, caller, context, property, parameterBinding, parameter, index,\n );\n}\n\nfunction addObjectPropertyBinding(\n next: Map<string, ContextBinding>,\n caller: Map<string, ContextBinding>,\n context: SymbolCallContext,\n property: Record<string, unknown>,\n parameterBinding: Record<string, unknown> | undefined,\n parameter: string | undefined,\n index: number,\n): void {\n if (typeof property.property !== 'string' || typeof property.argument !== 'string') return;\n const binding = caller.get(property.argument);\n if (!binding) return;\n const local = objectPatternLocal(parameterBinding, property.property);\n if (local) {\n next.set(local, objectBinding(binding, context.provenance,\n property.property, property.argument, String(index), local,\n 'local_symbol_destructured_object_argument'));\n return;\n }\n if (!parameter) return;\n const receiver = `${parameter}.${property.property}`;\n next.set(receiver, objectBinding(binding, context.provenance,\n property.property, property.argument, parameter, receiver,\n 'local_symbol_object_argument'));\n addObjectAliases(next, binding, context, property, parameter, receiver);\n}\n\nfunction addObjectAliases(\n next: Map<string, ContextBinding>,\n binding: ContextBinding,\n context: SymbolCallContext,\n property: Record<string, unknown>,\n parameter: string,\n receiver: string,\n): void {\n for (const alias of context.parameterPropertyAliases) {\n if (alias.parameter !== parameter || alias.property !== property.property\n || typeof alias.local !== 'string') continue;\n next.set(alias.local, {\n ...objectBinding(binding, context.provenance,\n String(property.property), String(property.argument), parameter,\n alias.local, 'local_symbol_object_parameter_destructure'),\n calleeObjectProperty: receiver,\n calleeLocalDestructuredIdentifier: alias.local,\n parameterPropertyAliasKind: alias.kind,\n parameterPropertyAliasLine: alias.line,\n });\n }\n}\n\nfunction addArrayBindings(\n next: Map<string, ContextBinding>,\n caller: Map<string, ContextBinding>,\n provenance: Record<string, unknown>,\n argument: Record<string, unknown>,\n parameterBinding: Record<string, unknown> | undefined,\n index: number,\n): void {\n const arrays = arrayPattern(argument, parameterBinding);\n if (!arrays) return;\n for (const element of arrays.elements)\n addArrayElement(next, caller, provenance, element, arrays.targets, index);\n}\n\nfunction arrayPattern(\n argument: Record<string, unknown>,\n binding: Record<string, unknown> | undefined,\n): { elements: Array<Record<string, unknown>>;\n targets: Array<Record<string, unknown>> } | undefined {\n if (argument.kind !== 'array_literal') return undefined;\n if (!Array.isArray(argument.elements)) return undefined;\n if (binding?.kind !== 'array_pattern') return undefined;\n if (!Array.isArray(binding.elements)) return undefined;\n return { elements: recordArray(argument.elements),\n targets: recordArray(binding.elements) };\n}\n\nfunction addArrayElement(\n next: Map<string, ContextBinding>,\n caller: Map<string, ContextBinding>,\n provenance: Record<string, unknown>,\n element: Record<string, unknown>,\n targets: Array<Record<string, unknown>>,\n index: number,\n): void {\n if (element.kind !== 'identifier' || typeof element.name !== 'string') return;\n const target = targets.find((item) => item.index === element.index);\n if (typeof target?.local !== 'string') return;\n const binding = caller.get(element.name);\n if (binding) next.set(target.local, { ...binding, ...provenance,\n source: 'local_symbol_destructured_array_argument',\n callerArgument: element.name, calleeParameter: String(index),\n calleeReceiver: target.local });\n}\n\nfunction objectPatternLocal(\n binding: Record<string, unknown> | undefined,\n property: string,\n): string | undefined {\n if (binding?.kind !== 'object_pattern' || !Array.isArray(binding.properties)) return undefined;\n const match = recordArray(binding.properties).find(\n (item) => item.property === property && typeof item.local === 'string',\n );\n return typeof match?.local === 'string' ? match.local : undefined;\n}\n\nfunction objectBinding(\n binding: ContextBinding,\n provenance: Record<string, unknown>,\n callerProperty: string,\n callerArgument: string,\n parameter: string,\n receiver: string,\n source: string,\n): ContextBinding {\n return { ...binding, ...provenance, source,\n callerProperty, callerArgument,\n calleeParameter: parameter, calleeReceiver: receiver };\n}\n\nfunction enrichBinding(row: ContextBinding): ContextBinding {\n const servicePath = row.servicePathExpr && !hasPlaceholder(row.servicePathExpr)\n ? row.servicePathExpr : !row.servicePathExpr ? row.requireServicePath : undefined;\n const destination = row.destinationExpr && !hasPlaceholder(row.destinationExpr)\n ? row.destinationExpr : !row.destinationExpr ? row.requireDestination : undefined;\n return { ...row, effectiveServicePath: servicePath,\n effectiveDestination: destination };\n}\n\nfunction hasPlaceholder(value: string | undefined): boolean {\n return extractPlaceholders(value).length > 0;\n}\n\nfunction bindingEvidence(binding: ContextBinding): Record<string, unknown> {\n return { bindingId: binding.bindingId, sourceFile: binding.sourceFile,\n sourceLine: binding.sourceLine, alias: binding.alias,\n aliasExpr: binding.aliasExpr, destinationExpr: binding.destinationExpr,\n servicePathExpr: binding.servicePathExpr };\n}\n\nfunction uniqueBindingCandidates(\n candidates: Array<Record<string, unknown>>,\n): Array<Record<string, unknown>> {\n const seen = new Set<string>();\n return candidates.filter((candidate) => {\n const key = JSON.stringify(candidate);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction recordArray(value: unknown): Array<Record<string, unknown>> {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string') : [];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n","import type { TraceEdge } from '../types.js';\nimport type {\n CompactDecisionInput,\n CompactEdgeObservation,\n CompactReferenceInput,\n CompactSemanticEndpoint,\n CompactSourceSite,\n CompactStatus,\n CompactTraceObserver,\n} from './014-compact-contract.js';\n\nexport interface TraceEdgeSemantics {\n source: CompactSemanticEndpoint;\n target: CompactSemanticEndpoint;\n status: CompactStatus;\n decision?: CompactDecisionInput;\n refs?: CompactReferenceInput;\n site?: CompactSourceSite;\n}\n\nexport interface SemanticCallRow extends Record<string, unknown> {\n id: number;\n repo_id: number;\n repoName: string;\n source_file: string;\n source_line: number;\n source_symbol_id?: number;\n}\n\nexport interface SemanticTargetRow extends Record<string, unknown> {\n to_kind: string;\n to_id: string;\n status?: string;\n}\n\nconst nonResolvedGraphStatuses: Readonly<Record<string, CompactStatus>> = {\n ambiguous: 'ambiguous', dynamic: 'dynamic', terminal: 'terminal',\n};\n\nexport class TraceEdgeRecorder {\n constructor(\n private readonly edges: TraceEdge[],\n private readonly observer?: CompactTraceObserver,\n ) {}\n\n record(edge: TraceEdge, semantics: TraceEdgeSemantics): number {\n const ordinal = this.edges.length;\n this.edges.push(edge);\n this.observer?.record(observation(ordinal, edge, semantics));\n return ordinal;\n }\n\n unavailable(\n side: 'source' | 'target',\n endpointKind: string,\n ): CompactSemanticEndpoint {\n return { kind: 'unavailable', side, endpointKind,\n detailedEdgeIndex: this.edges.length };\n }\n}\n\nexport function semanticCallSource(\n call: SemanticCallRow,\n workspaceId: number,\n): CompactSemanticEndpoint {\n const symbolId = positiveNumber(call.source_symbol_id);\n if (symbolId !== undefined) return { kind: 'symbol', symbolId };\n return {\n kind: 'call_site', workspaceId, repositoryId: call.repo_id,\n repositoryName: call.repoName, sourceFile: call.source_file,\n sourceLine: call.source_line,\n startOffset: finiteNumber(call.call_site_start_offset),\n endOffset: finiteNumber(call.call_site_end_offset), callId: call.id,\n };\n}\n\nexport function semanticOperation(\n value: unknown,\n unavailable: () => CompactSemanticEndpoint,\n): CompactSemanticEndpoint {\n const operationId = positiveNumber(value);\n return operationId === undefined ? unavailable()\n : { kind: 'operation', operationId };\n}\n\nexport function semanticSymbol(\n value: unknown,\n unavailable: () => CompactSemanticEndpoint,\n): CompactSemanticEndpoint {\n const symbolId = positiveNumber(value);\n return symbolId === undefined ? unavailable() : { kind: 'symbol', symbolId };\n}\n\nexport function semanticHandler(\n methodIdValue: unknown,\n symbolIdValue: unknown,\n unavailable: () => CompactSemanticEndpoint,\n): CompactSemanticEndpoint {\n const symbolId = positiveNumber(symbolIdValue);\n if (symbolId !== undefined) return { kind: 'symbol', symbolId };\n const handlerMethodId = positiveNumber(methodIdValue);\n return handlerMethodId === undefined ? unavailable()\n : { kind: 'handler_method', handlerMethodId };\n}\n\nexport function semanticGraphTarget(\n row: SemanticTargetRow,\n call: Record<string, unknown>,\n workspaceId: number,\n unavailable: () => CompactSemanticEndpoint,\n): CompactSemanticEndpoint {\n if (row.to_kind === 'event') return {\n kind: 'event', workspaceId,\n eventName: typeof call.event_name_expr === 'string'\n ? call.event_name_expr : row.to_id,\n };\n const id = positiveNumber(row.to_id);\n if (row.to_kind === 'operation')\n return id === undefined ? unavailable() : { kind: 'operation', operationId: id };\n if (row.to_kind === 'symbol')\n return id === undefined ? unavailable() : { kind: 'symbol', symbolId: id };\n if (row.to_kind === 'handler_method') return id === undefined\n ? unavailable() : { kind: 'handler_method', handlerMethodId: id };\n return { kind: 'target', workspaceId,\n repositoryId: positiveNumber(call.repo_id), targetKind: row.to_kind,\n targetId: row.to_id };\n}\n\nexport function semanticScopeTarget(\n workspaceId: number,\n repositoryId: number | undefined,\n sourceFiles: ReadonlySet<string> | undefined,\n symbolIds: ReadonlySet<number> | undefined,\n structuralKey: string,\n): CompactSemanticEndpoint {\n return {\n kind: 'scope', workspaceId, repositoryId,\n sourceFiles: [...(sourceFiles ?? [])],\n symbolIds: [...(symbolIds ?? [])], structuralKey,\n };\n}\n\nexport function compactGraphStatus(\n row: SemanticTargetRow,\n evidence: Record<string, unknown>,\n unresolvedReason: string | undefined,\n dynamicMode: string | undefined,\n): CompactStatus {\n const effective = recordValue(evidence.effectiveResolution);\n const status = stringValue(effective.status) ?? row.status ?? 'unresolved';\n if (status !== 'resolved')\n return nonResolvedGraphStatuses[status] ?? 'unresolved';\n if (unresolvedReason) return 'unresolved';\n const inference = recordValue(evidence.dynamicTargetInference);\n if (isDynamicInference(dynamicMode, inference)) return 'dynamic';\n return traversableTargetKind(row.to_kind) ? 'resolved' : 'terminal';\n}\n\nfunction isDynamicInference(\n mode: string | undefined,\n evidence: Record<string, unknown>,\n): boolean {\n return mode === 'infer' && evidence.status === 'resolved';\n}\n\nfunction traversableTargetKind(kind: string): boolean {\n return ['operation', 'symbol', 'handler_method'].includes(kind);\n}\n\nexport function compactResolutionStatus(\n status: unknown,\n unresolvedReason?: string,\n): CompactStatus {\n if (status === 'ambiguous') return 'ambiguous';\n if (status === 'dynamic') return 'dynamic';\n return status === 'resolved' && !unresolvedReason ? 'resolved' : 'unresolved';\n}\n\nexport function compactEventStatus(\n status: unknown,\n bodyExpansion: unknown,\n): CompactStatus {\n if (bodyExpansion === 'cycle_blocked') return 'cycle';\n if (status === 'ambiguous') return 'ambiguous';\n return status === 'resolved' ? 'inferred' : 'unresolved';\n}\n\nexport function compactDecisionFromEvidence(\n evidence: Record<string, unknown>,\n overrides: CompactDecisionInput = {},\n): CompactDecisionInput {\n const effective = recordValue(evidence.effectiveResolution);\n const persisted = recordValue(evidence.persistedResolution);\n const dynamic = recordValue(evidence.dynamicTargetExploration);\n const implementation = recordValue(evidence.implementationSelection);\n const missing = stringArray(dynamic.missingVariables\n ?? evidence.missingRuntimeVariables);\n const authoritativeMissingCount = finiteNumber(\n dynamic.missingVariableCount ?? evidence.missingVariableCount,\n );\n return {\n effectiveResolutionStatus: stringValue(effective.status),\n effectiveTarget: targetSummary(effective),\n persistedResolutionStatus: stringValue(persisted.status),\n persistedTarget: targetSummary(persisted),\n missingVariableNames: missing.length > 0 ? missing : undefined,\n missingVariableCount: authoritativeMissingCount\n ?? (missing.length > 0 ? missing.length : undefined),\n dynamicMode: dynamicMode(dynamic.mode),\n candidateCount: firstNumber(\n dynamic.candidateCount,\n implementation.candidateCount,\n implementation.candidateScoreCount,\n evidence.candidateCount,\n evidence.persistedCandidateCount,\n ),\n viableCandidateCount: finiteNumber(dynamic.viableCandidateCount),\n rejectedCandidateCount: finiteNumber(dynamic.rejectedCandidateCount),\n omittedCandidateCount: finiteNumber(dynamic.omittedCandidateCount),\n implementationStrategy: stringValue(implementation.strategy),\n implementationGuided: booleanValue(implementation.guided),\n implementationContextual: booleanValue(\n evidence.contextualImplementationSelected),\n reasonCode: stringValue(evidence.reasonCode ?? evidence.cycleReason),\n eventMatchStrategy: stringValue(evidence.matchStrategy),\n dispatchCertainty: stringValue(evidence.dispatchCertainty),\n associationStatus: stringValue(evidence.associationStatus),\n associationBasis: stringValue(evidence.associationBasis),\n eventScope: stringValue(evidence.dispatchScope),\n callRole: stringValue(evidence.callRole),\n factOrigin: stringValue(evidence.factOrigin),\n roleSiteMatchCount: finiteNumber(evidence.roleSiteMatchCount),\n bodyExpansion: stringValue(evidence.bodyExpansion),\n ...overrides,\n };\n}\n\nexport function compactRefs(\n values: Record<string, unknown>,\n): CompactReferenceInput {\n return {\n graphEdgeIds: reference(values.graphEdgeId),\n outboundCallIds: reference(values.outboundCallId),\n subscribeCallIds: reference(values.subscribeCallId),\n symbolCallIds: reference(values.symbolCallId),\n operationIds: reference(values.operationId),\n symbolIds: reference(values.symbolId),\n handlerMethodIds: reference(values.handlerMethodId),\n };\n}\n\nexport function compactSite(\n values: Record<string, unknown>,\n): CompactSourceSite {\n return {\n repository: stringValue(values.repository ?? values.repoName),\n sourceFile: stringValue(values.sourceFile ?? values.source_file),\n sourceLine: finiteNumber(values.sourceLine ?? values.source_line),\n startOffset: finiteNumber(values.startOffset ?? values.call_site_start_offset),\n endOffset: finiteNumber(values.endOffset ?? values.call_site_end_offset),\n };\n}\n\nfunction observation(\n ordinal: number,\n edge: TraceEdge,\n semantics: TraceEdgeSemantics,\n): CompactEdgeObservation {\n return {\n ordinal, step: edge.step, type: edge.type,\n source: semantics.source, target: semantics.target,\n status: semantics.status, confidence: edge.confidence,\n decision: semantics.decision, refs: semantics.refs, site: semantics.site,\n };\n}\n\nfunction targetSummary(\n value: Record<string, unknown>,\n): { kind: string; id: string } | undefined {\n const kind = stringValue(value.targetKind);\n const id = stringValue(value.targetId);\n return kind && id ? { kind, id } : undefined;\n}\n\nfunction reference(value: unknown): Array<number | string> | undefined {\n if (typeof value === 'string' && value.length > 0) {\n const numeric = Number(value);\n if (Number.isSafeInteger(numeric)) return numeric > 0 ? [numeric] : undefined;\n return [value];\n }\n const number = finiteNumber(value);\n return number === undefined || number <= 0 ? undefined : [number];\n}\n\nfunction dynamicMode(value: unknown): 'strict' | 'candidates' | 'infer' | undefined {\n return value === 'strict' || value === 'candidates' || value === 'infer'\n ? value : undefined;\n}\n\nfunction recordValue(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown> : {};\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string') : [];\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value !== 'string' || value.trim() === '') return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction positiveNumber(value: unknown): number | undefined {\n const number = finiteNumber(value);\n return number !== undefined && number > 0 ? number : undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction firstNumber(...values: unknown[]): number | undefined {\n for (const value of values) {\n const numeric = finiteNumber(value);\n if (numeric !== undefined) return numeric;\n }\n return undefined;\n}\n","import type { TraceEdge } from '../types.js';\nimport type { CompactSemanticEndpoint, CompactStatus } from './014-compact-contract.js';\nimport {\n compactDecisionFromEvidence,\n compactEventStatus,\n compactGraphStatus,\n compactRefs,\n compactResolutionStatus,\n compactSite,\n semanticCallSource,\n semanticGraphTarget,\n semanticHandler,\n semanticOperation,\n semanticScopeTarget,\n semanticSymbol,\n type SemanticCallRow,\n type SemanticTargetRow,\n type TraceEdgeRecorder,\n} from './015-trace-edge-recorder.js';\nimport type { PlannedEventSubscriberTransition } from './011-event-subscriber-traversal.js';\nimport type { DynamicCandidateBranch } from './dynamic-branches.js';\n\ninterface ImplementationObservation {\n operationId: unknown;\n handlerMethodId?: unknown;\n handlerSymbolId?: unknown;\n graphEdgeId?: unknown;\n persistedStatus?: string;\n persistedTargetKind?: string;\n persistedTargetId?: string;\n effectiveStatus: string;\n strategy: string;\n guided?: boolean;\n contextual?: boolean;\n unresolvedReason?: string;\n evidence: Record<string, unknown>;\n site: Record<string, unknown>;\n}\n\ninterface LocalCallObservation {\n symbolCall: Record<string, unknown>;\n evidence: Record<string, unknown>;\n unresolvedReason?: string;\n}\n\ninterface ScopeObservation {\n workspaceId?: number;\n repositoryId?: number;\n sourceFiles?: ReadonlySet<string>;\n symbolIds?: ReadonlySet<number>;\n structuralKey: string;\n}\n\ninterface OutboundObservation {\n call: SemanticCallRow;\n row: SemanticTargetRow;\n evidence: Record<string, unknown>;\n workspaceId: number;\n dynamicMode?: string;\n unresolvedReason?: string;\n}\n\nexport function recordImplementationObservation(\n recorder: TraceEdgeRecorder,\n edge: TraceEdge,\n input: ImplementationObservation,\n): void {\n const target = semanticHandler(input.handlerMethodId, input.handlerSymbolId,\n () => recorder.unavailable('target', 'selected_handler'));\n recorder.record(edge, {\n source: semanticOperation(input.operationId,\n () => recorder.unavailable('source', 'operation')),\n target,\n status: compactResolutionStatus(input.effectiveStatus, input.unresolvedReason),\n decision: compactDecisionFromEvidence(input.evidence, {\n effectiveResolutionStatus: input.unresolvedReason\n ? 'unresolved' : input.effectiveStatus,\n effectiveTarget: decisionTarget(target),\n persistedResolutionStatus: input.persistedStatus,\n persistedTarget: input.persistedTargetKind && input.persistedTargetId\n ? { kind: input.persistedTargetKind, id: input.persistedTargetId }\n : undefined,\n implementationStrategy: input.strategy,\n implementationGuided: input.guided,\n implementationContextual: input.contextual,\n reasonCode: input.unresolvedReason\n ? 'selected_handler_unavailable' : undefined,\n }),\n refs: compactRefs({ graphEdgeId: input.graphEdgeId,\n operationId: input.operationId,\n handlerMethodId: input.handlerMethodId,\n symbolId: input.handlerSymbolId }),\n site: compactSite(input.site),\n });\n}\n\nexport function recordLocalCallObservation(\n recorder: TraceEdgeRecorder,\n edge: TraceEdge,\n input: LocalCallObservation,\n): CompactSemanticEndpoint {\n const source = semanticSymbol(input.symbolCall.caller_symbol_id,\n () => recorder.unavailable('source', 'caller_symbol'));\n const target = semanticSymbol(input.symbolCall.callee_symbol_id,\n () => recorder.unavailable('target', 'callee_symbol'));\n recorder.record(edge, {\n source, target,\n status: compactResolutionStatus(\n input.symbolCall.status, input.unresolvedReason,\n ),\n decision: compactDecisionFromEvidence(input.evidence, {\n effectiveResolutionStatus: String(input.symbolCall.status),\n reasonCode: input.unresolvedReason ? 'symbol_call_unresolved' : undefined,\n }),\n refs: { symbolCallIds: idArray(input.symbolCall.id),\n symbolIds: idArray(input.symbolCall.caller_symbol_id,\n input.symbolCall.callee_symbol_id) },\n site: compactSite(input.symbolCall),\n });\n return target;\n}\n\nexport function recordCycleObservation(\n recorder: TraceEdgeRecorder,\n edge: TraceEdge,\n source: CompactSemanticEndpoint,\n scope: ScopeObservation,\n refs: Record<string, unknown>,\n site: Record<string, unknown>,\n): void {\n recorder.record(edge, {\n source,\n target: scope.workspaceId === undefined\n ? recorder.unavailable('target', 'cycle_scope')\n : semanticScopeTarget(scope.workspaceId, scope.repositoryId,\n scope.sourceFiles, scope.symbolIds, scope.structuralKey),\n status: 'cycle',\n decision: compactDecisionFromEvidence(edge.evidence, {\n reasonCode: 'structural_ancestry_cycle',\n }),\n refs: compactRefs(refs),\n site: compactSite(site),\n });\n}\n\nexport function recordOutboundObservation(\n recorder: TraceEdgeRecorder,\n edge: TraceEdge,\n input: OutboundObservation,\n): { source: CompactSemanticEndpoint; target: CompactSemanticEndpoint } {\n const source = semanticCallSource(input.call, input.workspaceId);\n const target = semanticGraphTarget(\n input.row, input.call, input.workspaceId,\n () => recorder.unavailable('target', input.row.to_kind),\n );\n recorder.record(edge, {\n source, target,\n status: compactGraphStatus(input.row, input.evidence,\n input.unresolvedReason, input.dynamicMode),\n decision: compactDecisionFromEvidence(input.evidence, {\n reasonCode: input.unresolvedReason\n ? safeReasonCode(input.evidence.reasonCode, 'outbound_target_unresolved')\n : undefined,\n }),\n refs: compactRefs({\n graphEdgeId: positiveId(input.evidence.persistedGraphEdgeId),\n outboundCallId: input.call.id,\n operationId: input.row.to_kind === 'operation' ? input.row.to_id : undefined,\n symbolId: input.call.source_symbol_id,\n }),\n site: compactSite(input.call),\n });\n return { source, target };\n}\n\nexport function recordEventBridgeObservation(\n recorder: TraceEdgeRecorder,\n edge: TraceEdge,\n plan: PlannedEventSubscriberTransition,\n workspaceId: number,\n subscriptionCount: number,\n): CompactSemanticEndpoint {\n const handler = plan.transition.handler;\n const target: CompactSemanticEndpoint = handler\n ? { kind: 'symbol', symbolId: handler.symbolId }\n : { kind: 'target', workspaceId,\n repositoryId: plan.transition.subscriptionRepoId,\n targetKind: plan.transition.targetKind,\n targetId: plan.transition.targetId };\n recorder.record(edge, {\n source: { kind: 'event', workspaceId,\n eventName: plan.transition.eventName },\n target,\n status: compactEventStatus(plan.transition.status, plan.bodyExpansion),\n decision: compactDecisionFromEvidence(plan.evidence, {\n eventSubscriptionCount: subscriptionCount,\n reasonCode: plan.transition.reasonCode,\n }),\n refs: eventReferences(plan),\n site: eventSite(plan),\n });\n return target;\n}\n\nexport function recordEventCycleObservation(\n recorder: TraceEdgeRecorder,\n edge: TraceEdge,\n plan: PlannedEventSubscriberTransition,\n source: CompactSemanticEndpoint,\n workspaceId: number,\n): void {\n const handler = plan.transition.handler;\n if (!plan.state) return;\n recorder.record(edge, {\n source,\n target: semanticScopeTarget(workspaceId, handler?.repoId,\n handler ? new Set([handler.sourceFile]) : undefined,\n handler ? new Set([handler.symbolId]) : undefined,\n plan.state.structuralKey),\n status: 'cycle',\n decision: compactDecisionFromEvidence(edge.evidence, {\n reasonCode: 'structural_ancestry_cycle',\n dispatchCertainty: 'static_name_only',\n }),\n refs: eventReferences(plan),\n site: eventSite(plan),\n });\n}\n\nexport function recordDynamicBranchObservation(\n recorder: TraceEdgeRecorder,\n branch: DynamicCandidateBranch,\n call: SemanticCallRow,\n source: CompactSemanticEndpoint,\n evidence: Record<string, unknown>,\n workspaceId: number,\n): void {\n const target = dynamicBranchTarget(recorder, branch, workspaceId);\n recorder.record(branch.edge, {\n source, target, status: 'dynamic',\n decision: compactDecisionFromEvidence(evidence, {\n dynamicMode: 'candidates',\n effectiveTarget: branch.operationId === undefined\n ? undefined : { kind: 'operation', id: String(branch.operationId) },\n remediationCode: 'provide_runtime_variables',\n }),\n refs: compactRefs({ graphEdgeId: positiveId(evidence.persistedGraphEdgeId),\n outboundCallId: call.id, operationId: branch.operationId,\n symbolId: call.source_symbol_id }),\n site: compactSite(call),\n });\n}\n\nfunction dynamicBranchTarget(\n recorder: TraceEdgeRecorder,\n branch: DynamicCandidateBranch,\n workspaceId: number,\n): CompactSemanticEndpoint {\n if (branch.operationId !== undefined)\n return { kind: 'operation', operationId: branch.operationId };\n if (branch.servicePath && branch.operationPath) return {\n kind: 'target', workspaceId,\n repositoryId: branch.repositoryId,\n targetKind: 'dynamic_operation_candidate',\n targetId: JSON.stringify([branch.servicePath, branch.operationPath]),\n };\n return recorder.unavailable('target', 'dynamic_operation_candidate');\n}\n\nexport function graphObservationStatus(\n row: SemanticTargetRow,\n evidence: Record<string, unknown>,\n unresolvedReason: string | undefined,\n dynamicMode: string | undefined,\n): CompactStatus {\n return compactGraphStatus(row, evidence, unresolvedReason, dynamicMode);\n}\n\nfunction eventReferences(\n plan: PlannedEventSubscriberTransition,\n): ReturnType<typeof compactRefs> {\n return compactRefs({ graphEdgeId: plan.transition.graphEdgeId,\n subscribeCallId: plan.transition.subscribeCallId,\n symbolCallId: plan.transition.symbolCallId,\n symbolId: plan.transition.handler?.symbolId });\n}\n\nfunction eventSite(\n plan: PlannedEventSubscriberTransition,\n): ReturnType<typeof compactSite> {\n return compactSite({ repository: plan.transition.subscriptionRepoName,\n sourceFile: plan.transition.sourceFile,\n sourceLine: plan.transition.sourceLine,\n startOffset: plan.transition.callSiteStartOffset,\n endOffset: plan.transition.callSiteEndOffset });\n}\n\nfunction safeReasonCode(value: unknown, fallback: string): string {\n return typeof value === 'string' && /^[a-z][a-z0-9_.-]{0,79}$/.test(value)\n ? value : fallback;\n}\n\nfunction positiveId(value: unknown): number | string | undefined {\n if (typeof value === 'number') return Number.isFinite(value) && value > 0\n ? value : undefined;\n if (typeof value !== 'string' || value.length === 0) return undefined;\n const numeric = Number(value);\n if (Number.isSafeInteger(numeric)) return numeric > 0 ? numeric : undefined;\n return value;\n}\n\nfunction idArray(...values: unknown[]): Array<number | string> | undefined {\n const ids = values.flatMap((value) => {\n const id = positiveId(value);\n return id === undefined ? [] : [id];\n });\n return ids.length > 0 ? ids : undefined;\n}\n\nfunction decisionTarget(\n endpoint: CompactSemanticEndpoint,\n): { kind: string; id: string } | undefined {\n if (endpoint.kind === 'symbol')\n return { kind: 'symbol', id: String(endpoint.symbolId) };\n if (endpoint.kind === 'handler_method')\n return { kind: 'handler_method', id: String(endpoint.handlerMethodId) };\n return undefined;\n}\n","import type { Db } from '../db/connection.js';\nimport { reposByName } from '../db/repositories.js';\nimport type { ImplementationHint, TraceEdge, TraceOptions, TraceResult, TraceStart } from '../types.js';\nimport { baseTraceEvidence, edgeTarget, runtimeNoCandidateDiagnostics, runtimeResolution, runtimeVariableDiagnostic, type TraceGraphRow } from './evidence.js';\nimport { dynamicCandidateBranches } from './dynamic-branches.js';\nimport {\n loadTraceDiagnostics,\n prependTraceDiagnostic,\n} from './002-trace-diagnostics.js';\nimport { implementationHintDiagnostic } from './implementation-hints.js';\nimport {\n contextualImplementationSelection,\n hintedImplementationSelection,\n} from './005-implementation-selection.js';\nimport { implementationStartDiagnostic } from './007-implementation-start-diagnostic.js';\nimport {\n contextualRuntimeResolution,\n type ContextBinding,\n} from './008-contextual-runtime-state.js';\nimport {\n handlerMethodNode,\n withSelectedHandlerProvenance,\n type SelectedHandlerEvidence,\n} from './009-selected-handler-provenance.js';\nimport { schemaLifecycleDiagnostic } from '../db/001-fact-lifecycle.js';\nimport { TraversalScopeScheduler } from './010-traversal-scope.js';\nimport { planEventSubscriberTransitions } from './011-event-subscriber-traversal.js';\nimport {\n graphForCalls,\n operationNode,\n symbolNode,\n type TraceGraphEdgeRow as GraphRow,\n} from './012-trace-graph-lookups.js';\nimport {\n createTraceRootPlan,\n enqueueCausalScope,\n nextPendingRoot,\n} from './013-trace-root-scopes.js';\nimport {\n contextForSymbolCall,\n knownBindingsForCalls,\n knownBindingsForScope,\n parseTraceEvidence as parseEvidence,\n receiverFromTraceEvidence as receiverFromEvidence,\n} from './017-trace-context.js';\nimport type { CompactTraceObserver } from './014-compact-contract.js';\nimport { TraceEdgeRecorder } from './015-trace-edge-recorder.js';\nimport {\n recordCycleObservation,\n recordDynamicBranchObservation,\n recordEventBridgeObservation,\n recordEventCycleObservation,\n recordImplementationObservation,\n recordLocalCallObservation,\n recordOutboundObservation,\n} from './019-trace-edge-semantics.js';\nimport {\n ambiguousStartDiagnostic,\n selectorNotFoundDiagnostic,\n selectorRepoAmbiguousDiagnostic,\n selectorRepoNotFoundDiagnostic,\n sourceScopeForSelector,\n} from './selectors.js';\ninterface RepoRef {\n id: number;\n name: string;\n packageName?: string;\n}\ninterface StartScope {\n repo?: RepoRef;\n executionRepoId?: number;\n sourceFiles?: Set<string>;\n symbolIds?: Set<number>;\n selectorMatched: boolean;\n startOperationId?: string;\n startDiagnostics?: Array<Record<string, unknown>>;\n}\ninterface CallRow extends Record<string, unknown> {\n id: number;\n repo_id: number;\n repoName: string;\n source_file: string;\n source_line: number;\n call_type: string;\n confidence: number;\n source_symbol_id?: number;\n workspaceId: number;\n graphGeneration: number;\n}\ninterface ImplementationHintOptions {\n implementationRepo?: string;\n implementationHints?: ImplementationHint[];\n}\nconst compactObserverKey = Symbol('service-flow.compact-trace-observer');\ntype ObservedTraceOptions = TraceOptions & {\n [compactObserverKey]?: CompactTraceObserver;\n};\nfunction compactObserver(options: TraceOptions): CompactTraceObserver | undefined {\n const observed: ObservedTraceOptions = options;\n return observed[compactObserverKey];\n}\nfunction normalizeOperation(value: string | undefined): string | undefined {\n if (!value) return undefined;\n return value.startsWith('/') ? value.slice(1) : value;\n}\nfunction positiveDepth(value: number): number {\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 25;\n}\nfunction operationStartScope(db: Db, repoId: number | undefined, start: TraceStart, hintOptions: ImplementationHintOptions, workspaceId?: number): { files?: Set<string>; symbols?: Set<number>; repoId?: number; operationId?: string; diagnostics?: Array<Record<string, unknown>> } | undefined {\n const requested = normalizeOperation(start.operationPath ?? start.operation);\n if (!requested) return undefined;\n const rows = db.prepare(`SELECT o.id operationId,o.operation_name operationName,o.operation_path operationPath,o.source_file sourceFile,o.source_line sourceLine,s.service_path servicePath,r.id repoId,r.name repoName\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id JOIN repositories r ON r.id=s.repo_id\n WHERE (? IS NULL OR r.workspace_id=?) AND (? IS NULL OR r.id=?)\n AND (? IS NULL OR s.service_path=?) AND (o.operation_name=? OR o.operation_path=? OR o.operation_path=?)\n ORDER BY r.name,s.service_path,o.operation_name,o.id`).all(workspaceId, workspaceId, repoId, repoId, start.servicePath, start.servicePath, requested, requested, requested.startsWith('/') ? requested : `/${requested}`) as Array<Record<string, unknown>>;\n if (rows.length === 0) return undefined;\n const repoCount = new Set(rows.map((row) => String(row.repoName))).size;\n const serviceCount = new Set(rows.map((row) => `${String(row.repoName)}:${String(row.servicePath)}`)).size;\n if (!repoId && repoCount > 1)\n return { diagnostics: [ambiguousStartDiagnostic(requested, rows, 'Operation trace start matched multiple repositories; add --repo to disambiguate')] };\n if (!start.servicePath && serviceCount > 1)\n return { diagnostics: [ambiguousStartDiagnostic(requested, rows, 'Operation trace start matched multiple services; add --service to disambiguate')] };\n if (rows.length !== 1)\n return { diagnostics: [ambiguousStartDiagnostic(requested, rows, 'Operation trace start matched multiple indexed operations')] };\n const operationId = String(rows[0]?.operationId);\n const impl = implementationScope(db, operationId);\n if (impl.edge?.status === 'resolved' && impl.files.size > 0) return { files: impl.files, symbols: impl.symbolId ? new Set([impl.symbolId]) : undefined, repoId: impl.repoId, operationId, diagnostics: [] };\n const hinted = hintedImplementationSelection(\n db, impl.edge, operationId, hintOptions,\n );\n if (hinted.methodId) {\n const hintedScope = handlerScope(db, hinted.methodId);\n if (hintedScope?.files.size) return { files: hintedScope.files, symbols: hintedScope.symbolId ? new Set([hintedScope.symbolId]) : undefined, repoId: hintedScope.repoId, operationId, diagnostics: [] };\n }\n if (impl.edge) {\n const evidence = parseEvidence(impl.edge.evidence_json);\n const hintDiagnostic = implementationHintDiagnostic(hinted, evidence);\n const diagnostics = [implementationStartDiagnostic(impl.edge, evidence)];\n return { operationId, diagnostics: hintDiagnostic ? [hintDiagnostic, ...diagnostics] : diagnostics };\n }\n return { operationId, diagnostics: [{ severity: 'warning', code: 'trace_start_implementation_unresolved', message: 'Indexed operation matched but no implementation candidate exists', resolutionStage: 'implementation', resolutionStatus: 'operation_without_implementation' }] };\n}\nfunction sourceFilesForStart(\n db: Db,\n repoId: number | undefined,\n start: TraceStart,\n workspaceId: number | undefined,\n): ReturnType<typeof sourceScopeForSelector> {\n return sourceScopeForSelector(db, repoId, start, workspaceId);\n}\nfunction startScope(db: Db, start: TraceStart, hintOptions: ImplementationHintOptions, workspaceId?: number): StartScope {\n const repos: RepoRef[] = start.repo\n ? reposByName(db, start.repo, workspaceId).map((row) => ({\n id: row.id,\n name: row.name,\n packageName: row.package_name ?? undefined,\n }))\n : [];\n if (start.repo && repos.length === 0) return {\n selectorMatched: false,\n startDiagnostics: [selectorRepoNotFoundDiagnostic(start.repo)],\n };\n if (start.repo && repos.length > 1) return {\n selectorMatched: false,\n startDiagnostics: [selectorRepoAmbiguousDiagnostic(start.repo, repos)],\n };\n const repo = repos[0];\n const operationScope = operationStartScope(\n db, repo?.id, start, hintOptions, workspaceId,\n );\n const terminalOperationScope = operationScope && !operationScope.files && (operationScope.diagnostics ?? []).some((d) => d.resolutionStage === 'operation' || d.resolutionStage === 'implementation');\n const sourceScope = operationScope?.files || terminalOperationScope ? operationScope : sourceFilesForStart(db, repo?.id, start, workspaceId);\n const terminalSelectorScope = Boolean(sourceScope?.diagnostics?.length && !sourceScope.files);\n const sourceFiles = sourceScope?.files;\n const hasSelector = Boolean(\n start.handler ?? start.operation ?? start.operationPath ?? start.servicePath,\n );\n if (start.servicePath && !start.operation && !start.operationPath && !start.handler)\n return { repo, selectorMatched: false };\n return {\n repo,\n executionRepoId: sourceScope?.repoId ?? repo?.id,\n sourceFiles,\n symbolIds: sourceScope?.symbols,\n selectorMatched: !terminalOperationScope && !terminalSelectorScope\n && (!hasSelector || sourceFiles !== undefined),\n startOperationId: operationScope?.operationId,\n startDiagnostics: operationScope?.diagnostics?.length\n ? operationScope.diagnostics\n : sourceScope?.diagnostics,\n };\n}\nfunction handlerFilesForOperation(db: Db, operationId: string): Set<string> {\n const op = db\n .prepare(\n `SELECT o.operation_name operationName,o.operation_path operationPath,s.repo_id repoId\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id WHERE o.id=?`,\n )\n .get(operationId) as\n | { operationName?: string; operationPath?: string; repoId?: number }\n | undefined;\n if (!op) return new Set();\n const operation = normalizeOperation(op.operationPath ?? op.operationName);\n const rows = db\n .prepare(\n `SELECT DISTINCT hc.source_file sourceFile,sym.id symbolId FROM handler_classes hc\n JOIN handler_methods hm ON hm.handler_class_id=hc.id\n LEFT JOIN symbols sym ON sym.repo_id=hc.repo_id\n AND sym.source_file=hc.source_file\n AND sym.qualified_name=hc.class_name || '.' || hm.method_name\n AND sym.start_line=hm.source_line\n WHERE hc.repo_id=?\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.handlerKind'),\n CASE WHEN hm.decorator_kind='Event' THEN 'event'\n WHEN hm.decorator_kind IN ('Action','Func','On') THEN 'operation'\n ELSE 'unsupported' END)='operation'\n AND COALESCE(json_extract(hm.decorator_resolution_json,'$.executable'),\n CASE WHEN hm.decorator_kind IN ('Action','Func','On')\n THEN 1 ELSE 0 END)=1\n AND (hm.decorator_value=? OR hm.method_name=? OR hm.decorator_value=?)`,\n )\n .all(op.repoId, operation, operation, op.operationName) as Array<{\n sourceFile?: string;\n }>;\n return new Set(rows.map((row) => row.sourceFile).filter(Boolean) as string[]);\n}\nfunction implementationEdge(db: Db, operationId: string): GraphRow | undefined {\n return db.prepare(\"SELECT * FROM graph_edges WHERE edge_type='OPERATION_IMPLEMENTED_BY_HANDLER' AND from_kind='operation' AND from_id=? ORDER BY CASE status WHEN 'resolved' THEN 0 WHEN 'ambiguous' THEN 1 ELSE 2 END,id LIMIT 1\").get(operationId) as GraphRow | undefined;\n}\nfunction implementationScope(db: Db, operationId: string): { repoId?: number; files: Set<string>; symbolId?: number; edge?: GraphRow } {\n const edge = implementationEdge(db, operationId);\n if (!edge || edge.status !== 'resolved') return { files: new Set(), edge };\n const row = db.prepare(\"SELECT hc.repo_id repoId,hc.source_file sourceFile,s.id symbolId FROM handler_methods hm JOIN handler_classes hc ON hc.id=hm.handler_class_id LEFT JOIN symbols s ON s.repo_id=hc.repo_id AND s.source_file=hc.source_file AND s.qualified_name=hc.class_name || '.' || hm.method_name AND s.start_line=hm.source_line WHERE hm.id=?\").get(edge.to_id) as { repoId?: number; sourceFile?: string; symbolId?: number } | undefined;\n if (!row || typeof row.symbolId !== 'number')\n return { repoId: row?.repoId, files: new Set(), edge };\n return { repoId: row?.repoId, files: new Set(row?.sourceFile ? [row.sourceFile] : []), symbolId: row?.symbolId, edge };\n}\nfunction handlerScope(db: Db, methodId: string): { repoId?: number; files: Set<string>; symbolId?: number } | undefined {\n const row = db.prepare(\"SELECT hc.repo_id repoId,hc.source_file sourceFile,s.id symbolId FROM handler_methods hm JOIN handler_classes hc ON hc.id=hm.handler_class_id LEFT JOIN symbols s ON s.repo_id=hc.repo_id AND s.source_file=hc.source_file AND s.qualified_name=hc.class_name || '.' || hm.method_name AND s.start_line=hm.source_line WHERE hm.id=?\").get(methodId) as { repoId?: number; sourceFile?: string; symbolId?: number } | undefined;\n if (!row || typeof row.symbolId !== 'number') return undefined;\n return { repoId: row.repoId, files: new Set(row.sourceFile ? [row.sourceFile] : []), symbolId: row.symbolId };\n}\nfunction traceEdgeType(call: CallRow, row: GraphRow): string {\n if (row.to_kind === 'operation' && row.edge_type === 'REMOTE_CALL_RESOLVES_TO_OPERATION') return 'remote_action';\n if (row.to_kind === 'operation' && row.edge_type === 'LOCAL_CALL_RESOLVES_TO_OPERATION') return 'local_service_call';\n return String(call.call_type);\n}\nfunction includeCall(\n type: string,\n options: {\n includeExternal?: boolean;\n includeDb?: boolean;\n includeAsync?: boolean;\n },\n): boolean {\n if (!options.includeDb && type === 'local_db_query') return false;\n if (!options.includeExternal && type === 'external_http') return false;\n if (!options.includeAsync && type.startsWith('async_')) return false;\n return true;\n}\nexport function trace(\n db: Db,\n start: TraceStart,\n options: TraceOptions,\n): TraceResult {\n const observer = compactObserver(options);\n const schemaLifecycle = schemaLifecycleDiagnostic(db);\n if (schemaLifecycle)\n return { start, nodes: [], edges: [], diagnostics: [schemaLifecycle] };\n const hintOptions = { implementationRepo: options.implementationRepo, implementationHints: options.implementationHints };\n const scope = startScope(db, start, hintOptions, options.workspaceId);\n const hasSelector = Boolean(start.repo || start.handler || start.operation\n || start.operationPath || start.servicePath);\n const diagnosticRepoId = scope.executionRepoId ?? scope.repo?.id;\n const scheduler = new TraversalScopeScheduler();\n const roots = createTraceRootPlan(db, scheduler, {\n repoId: diagnosticRepoId, files: scope.sourceFiles,\n symbolIds: scope.symbolIds, selectorMatched: scope.selectorMatched,\n }, options.workspaceId, Boolean(options.includeAsync));\n observer?.setWorkspaceId?.(roots.workspaceId);\n if (roots.diagnostic)\n return { start, nodes: [], edges: [], diagnostics: [roots.diagnostic] };\n const { workspaceId, queue, pendingRoots } = roots;\n const diagnostics = loadTraceDiagnostics(\n db,\n diagnosticRepoId,\n !hasSelector,\n workspaceId,\n );\n const stale = diagnosticRepoId !== undefined || !hasSelector\n ? db.prepare('SELECT name,graph_stale_reason reason FROM repositories WHERE graph_stale_reason IS NOT NULL AND (? IS NULL OR id=?) AND (? IS NULL OR workspace_id=?) ORDER BY name,id').all(diagnosticRepoId, diagnosticRepoId, workspaceId, workspaceId) as Array<{ name?: string; reason?: string }>\n : [];\n for (const row of stale)\n prependTraceDiagnostic(diagnostics, { severity: 'warning', code: 'graph_stale', message: `Graph is stale for ${row.name ?? 'repository'}: ${row.reason ?? 'facts_changed'}. Run service-flow link.` });\n for (const diagnostic of scope.startDiagnostics ?? [])\n prependTraceDiagnostic(diagnostics, diagnostic);\n if (!scope.selectorMatched && !(scope.startDiagnostics?.length))\n prependTraceDiagnostic(diagnostics, selectorNotFoundDiagnostic(start));\n const maxDepth = positiveDepth(options.depth);\n const edges: TraceEdge[] = [];\n const recorder = new TraceEdgeRecorder(edges, observer);\n const nodes = new Map<string, Record<string, unknown>>();\n if (scope.startOperationId && scope.selectorMatched) {\n const op = operationNode(db, scope.startOperationId);\n const impl = implementationScope(db, scope.startOperationId);\n if (op) nodes.set(String(op.id), op);\n const startSelection = hintedImplementationSelection(\n db, impl.edge, scope.startOperationId, hintOptions,\n );\n if (impl.edge && (impl.edge.status === 'resolved' || startSelection.methodId)) {\n const selectedMethodId = impl.edge.status === 'resolved' ? impl.edge.to_id : startSelection.methodId;\n const implEvidence = {\n ...parseEvidence(impl.edge.evidence_json),\n startResolution: {\n strategy: 'indexed_operation_graph',\n matchedOperationId: scope.startOperationId,\n implementationEdgeId: impl.edge.id,\n implementationStatus: impl.edge.status,\n selectedHandlerMethodId: selectedMethodId,\n },\n implementationSelection: startSelection.methodId\n ? startSelection.evidence : undefined,\n };\n const selected: SelectedHandlerEvidence = selectedMethodId\n ? withSelectedHandlerProvenance(\n implEvidence, selectedMethodId, handlerMethodNode(db, selectedMethodId),\n )\n : { evidence: implEvidence };\n if (selected.diagnostic) prependTraceDiagnostic(diagnostics, selected.diagnostic);\n if (selected.handler) nodes.set(String(selected.handler.id), selected.handler);\n const unresolvedReason = selected.unresolvedReason\n ?? (impl.edge.status === 'resolved' || startSelection.methodId\n ? undefined : String(impl.edge.unresolved_reason ?? impl.edge.status));\n const selectedScope = selectedMethodId\n ? handlerScope(db, selectedMethodId) : undefined;\n const edge: TraceEdge = { step: 1, type: 'operation_implemented_by_handler', from: op?.label ? String(op.label) : `operation:${scope.startOperationId}`, to: selected.handler?.label ? String(selected.handler.label) : `${impl.edge.to_kind}:${impl.edge.to_id}`, evidence: selected.evidence, confidence: Number(impl.edge.confidence ?? 0), unresolvedReason };\n recordImplementationObservation(recorder, edge, {\n operationId: scope.startOperationId,\n handlerMethodId: selectedMethodId,\n handlerSymbolId: selectedScope?.symbolId,\n graphEdgeId: impl.edge.id,\n persistedStatus: impl.edge.status,\n persistedTargetKind: impl.edge.to_kind,\n persistedTargetId: impl.edge.to_id,\n effectiveStatus: startSelection.methodId\n ? 'resolved' : String(impl.edge.status ?? 'unresolved'),\n strategy: String(startSelection.evidence.strategy\n ?? 'indexed_operation_graph'),\n guided: startSelection.evidence.guided === true,\n unresolvedReason, evidence: selected.evidence, site: op ?? {},\n });\n }\n }\n while (queue.length > 0 || pendingRoots.length > 0) {\n if ((queue[0]?.depth ?? Number.POSITIVE_INFINITY) > 1\n && workspaceId !== undefined) {\n const root = nextPendingRoot(pendingRoots, scheduler, workspaceId);\n if (root) queue.unshift(root);\n }\n const current = queue.shift();\n if (!current || current.depth > maxDepth) continue;\n if (!scheduler.markExpanded(current.state)) continue;\n const calls = db\n .prepare(\n `SELECT c.*,r.name repoName,r.workspace_id workspaceId,\n r.graph_generation graphGeneration\n FROM outbound_calls c JOIN repositories r ON r.id=c.repo_id\n WHERE (? IS NULL OR c.repo_id=?) AND (? IS NULL OR r.workspace_id=?)\n ORDER BY c.source_file COLLATE BINARY,c.call_site_start_offset,\n c.call_site_end_offset,c.source_line,c.id`,\n )\n .all(current.repoId, current.repoId, workspaceId, workspaceId) as CallRow[];\n const filtered = calls.filter(\n (c) =>\n (current.unownedOnly ? c.source_symbol_id == null\n : !current.symbolIds || current.symbolIds.has(Number(c.source_symbol_id)))\n && (!current.files || current.files.has(String(c.source_file))) &&\n includeCall(String(c.call_type), options),\n );\n const callerBindings = new Map<string, ContextBinding>([...current.context, ...knownBindingsForScope(db, current.repoId, current.symbolIds, current.files), ...knownBindingsForCalls(db, filtered)]);\n\n if (!current.rootObservationOnly && current.symbolIds\n && current.symbolIds.size > 0 && current.depth < maxDepth) {\n const symbolRows = db.prepare(`SELECT sc.*,s.repo_id calleeRepoId,\n s.source_file calleeFile FROM symbol_calls sc\n LEFT JOIN symbols s ON s.id=sc.callee_symbol_id\n WHERE sc.call_role='ordinary_call'\n AND sc.caller_symbol_id IN (${[...current.symbolIds].map(() => '?').join(',')})\n ORDER BY sc.source_file COLLATE BINARY,sc.call_site_start_offset,\n sc.call_site_end_offset,sc.source_line,sc.id`).all(\n ...current.symbolIds,\n ) as Array<Record<string, unknown>>;\n for (const symbolCall of symbolRows) {\n if (!symbolCall.callee_symbol_id) continue;\n const nextSymbols = new Set([Number(symbolCall.callee_symbol_id)]);\n const nextFiles = new Set([String(symbolCall.calleeFile)]);\n const nextRepoId = Number(symbolCall.calleeRepoId);\n const nextContext = contextForSymbolCall(db, symbolCall, callerBindings);\n const scheduling = scheduler.schedule({\n workspaceId,\n repoId: nextRepoId,\n files: nextFiles,\n symbolIds: nextSymbols,\n context: nextContext,\n }, current.state);\n const calleeNode = symbolNode(db, Number(symbolCall.callee_symbol_id));\n if (calleeNode) nodes.set(String(calleeNode.id), calleeNode);\n const evidence = { ...parseEvidence(symbolCall.evidence_json), sourceFile: symbolCall.source_file, sourceLine: symbolCall.source_line, calleeSymbolId: symbolCall.callee_symbol_id, calleeSymbolName: calleeNode?.symbolName, calleeSymbolFile: calleeNode?.sourceFile, resolutionStatus: symbolCall.status };\n const unresolvedReason = String(symbolCall.status) === 'resolved'\n ? undefined : symbolCall.unresolved_reason\n ? String(symbolCall.unresolved_reason) : undefined;\n const edge: TraceEdge = { step: current.depth, type: 'local_symbol_call', from: String(symbolCall.callee_expression), to: calleeNode?.label ? String(calleeNode.label) : `symbol:${String(symbolCall.callee_symbol_id)}`, evidence, confidence: Number(symbolCall.confidence ?? 0.8), unresolvedReason };\n const target = recordLocalCallObservation(recorder, edge, {\n symbolCall, evidence, unresolvedReason,\n });\n if (scheduling.kind === 'cycle') {\n const cycleEvidence = { cycle: true,\n cycleReason: 'structural_ancestry_cycle',\n symbolCallId: symbolCall.id };\n const cycleEdge: TraceEdge = { step: current.depth, type: 'cycle', from: String(symbolCall.callee_expression), to: scheduling.state.structuralKey, evidence: cycleEvidence, confidence: 1, unresolvedReason: 'Cycle detected in structural ancestry; downstream symbol was not expanded' };\n recordCycleObservation(recorder, cycleEdge, target, {\n workspaceId, repositoryId: nextRepoId, sourceFiles: nextFiles,\n symbolIds: nextSymbols,\n structuralKey: scheduling.state.structuralKey,\n }, { symbolCallId: symbolCall.id,\n symbolId: symbolCall.callee_symbol_id }, symbolCall);\n }\n if (scheduling.kind === 'scheduled') enqueueCausalScope(\n queue, pendingRoots, { repoId: nextRepoId, files: nextFiles,\n symbolIds: nextSymbols, depth: current.depth + 1,\n context: nextContext, state: scheduling.state });\n }\n }\n const graph = graphForCalls(\n db,\n filtered.map((c) => Number(c.id)),\n );\n for (const call of filtered) {\n const callNode = `call:${call.id}`;\n nodes.set(callNode, {\n id: callNode,\n kind: 'outbound_call',\n repo: call.repoName,\n file: call.source_file,\n line: call.source_line,\n callType: call.call_type,\n });\n const persistedRowsForCall = graph.get(Number(call.id)) ?? [];\n const contextual = contextualRuntimeResolution(db, call, callerBindings.get(receiverFromEvidence(call.evidence_json) ?? ''), call.workspaceId, persistedRowsForCall);\n const graphRows = contextual.row ? [contextual.row] : persistedRowsForCall;\n for (const row of graphRows) {\n const persistedEvidence = parseEvidence(row.evidence_json);\n const rawEvidence = baseTraceEvidence(row as TraceGraphRow, call, persistedEvidence, contextual.evidence);\n const effective = runtimeResolution(db, row as TraceGraphRow, rawEvidence, {\n vars: options.vars,\n dynamicMode: options.dynamicMode ?? 'strict',\n maxDynamicCandidates: options.maxDynamicCandidates,\n }, call.workspaceId, contextual.state);\n const evidence = effective.evidence;\n const effectiveRow = effective.row;\n const targetNode = `${effectiveRow.to_kind}:${effectiveRow.to_id}`;\n const opNode = effectiveRow.to_kind === 'operation' ? operationNode(db, effectiveRow.to_id) : undefined;\n nodes.set(targetNode, opNode ?? {\n id: targetNode,\n kind: effectiveRow.to_kind,\n label: effectiveRow.to_kind === 'db_entity' ? `Entity: ${effectiveRow.to_id || 'unknown'}` : effectiveRow.to_id,\n });\n const to = edgeTarget(effectiveRow, evidence);\n const edge: TraceEdge = {\n step: current.depth,\n type: traceEdgeType(call, effectiveRow),\n from: `${call.repoName}:${call.source_file}:${call.source_line}`,\n to,\n evidence,\n confidence: Number(effectiveRow.confidence ?? call.confidence),\n unresolvedReason: effective.unresolvedReason,\n };\n const semanticWorkspaceId = workspaceId ?? call.workspaceId;\n const semantic = recordOutboundObservation(recorder, edge, {\n call, row: effectiveRow, evidence,\n workspaceId: semanticWorkspaceId,\n dynamicMode: options.dynamicMode,\n unresolvedReason: effective.unresolvedReason,\n });\n if (options.includeAsync && call.call_type === 'async_emit'\n && effectiveRow.edge_type === 'HANDLER_EMITS_EVENT'\n && typeof call.event_name_expr === 'string') {\n const plans = planEventSubscriberTransitions(db, {\n workspaceId: workspaceId ?? call.workspaceId,\n graphGeneration: call.graphGeneration,\n eventName: call.event_name_expr,\n }, scheduler, current.state, current.depth, maxDepth);\n for (const plan of plans) {\n const nodeId = String(plan.node.id);\n const targetLabel = String(plan.node.label ?? nodeId);\n nodes.set(nodeId, plan.node);\n const bridgeEdge: TraceEdge = {\n step: current.depth,\n type: 'event_name_matches_subscription_handler',\n from: plan.transition.eventName,\n to: targetLabel,\n evidence: plan.evidence,\n confidence: plan.transition.confidence,\n unresolvedReason: plan.transition.unresolvedReason,\n };\n const handler = plan.transition.handler;\n const bridgeTarget = recordEventBridgeObservation(\n recorder, bridgeEdge, plan, semanticWorkspaceId, plans.length,\n );\n if (plan.bodyExpansion === 'cycle_blocked' && plan.state) {\n const cycleEvidence = { cycle: true,\n cycleReason: 'structural_ancestry_cycle',\n graphEdgeId: plan.transition.graphEdgeId };\n const cycleEdge: TraceEdge = { step: current.depth, type: 'cycle', from: targetLabel, to: plan.state.structuralKey, evidence: cycleEvidence, confidence: 1, unresolvedReason: 'Cycle detected across an event subscriber boundary; downstream symbol was not expanded' };\n recordEventCycleObservation(recorder, cycleEdge, plan,\n bridgeTarget, semanticWorkspaceId);\n }\n if (plan.bodyExpansion === 'scheduled' && plan.state && handler) {\n const files = new Set([handler.sourceFile]);\n const symbolIds = new Set([handler.symbolId]);\n enqueueCausalScope(queue, pendingRoots, {\n repoId: handler.repoId, files, symbolIds,\n depth: current.depth + 1, context: new Map(), state: plan.state,\n });\n }\n }\n }\n if ((options.dynamicMode ?? 'strict') === 'candidates'\n && effectiveRow.status !== 'resolved') {\n for (const branch of dynamicCandidateBranches(\n current.depth, call, evidence,\n )) {\n recordDynamicBranchObservation(\n recorder, branch, call, semantic.source, evidence,\n semanticWorkspaceId,\n );\n }\n }\n if (effectiveRow.to_kind === 'operation') {\n const implementation = implementationScope(db, effectiveRow.to_id);\n const contextSelection = contextualImplementationSelection(\n db, implementation.edge, effectiveRow.to_id, current.repoId, evidence,\n hintOptions,\n );\n const contextMethodId = contextSelection.methodId;\n let selectedHandlerAvailable = true;\n if (implementation.edge) {\n const implEvidence = parseEvidence(implementation.edge.evidence_json);\n const hintDiagnostic = implementationHintDiagnostic(contextSelection, implEvidence);\n if (hintDiagnostic) prependTraceDiagnostic(diagnostics, hintDiagnostic);\n const selectedMethodId = implementation.edge.status === 'resolved'\n ? implementation.edge.to_id : contextMethodId;\n const selectionEvidence = contextMethodId\n ? {\n ...implEvidence,\n contextualImplementationSelected:\n contextSelection.evidence.strategy !== 'implementation_repo_hint',\n contextualImplementation: contextSelection.evidence,\n implementationSelection: contextSelection.evidence,\n }\n : {\n ...implEvidence,\n contextualImplementation: contextSelection.evidence,\n implementationSelection: contextSelection.evidence,\n };\n const selected: SelectedHandlerEvidence = selectedMethodId\n ? withSelectedHandlerProvenance(\n selectionEvidence,\n selectedMethodId,\n handlerMethodNode(db, selectedMethodId),\n )\n : { evidence: selectionEvidence };\n selectedHandlerAvailable = !selected.unresolvedReason;\n if (selected.diagnostic) prependTraceDiagnostic(diagnostics, selected.diagnostic);\n const implTo = selected.handler?.label\n ? String(selected.handler.label)\n : `${implementation.edge.to_kind}:${implementation.edge.to_id}`;\n if (selected.handler) nodes.set(String(selected.handler.id), selected.handler);\n const unresolvedReason = selected.unresolvedReason\n ?? (implementation.edge.status === 'resolved' || contextMethodId\n ? undefined\n : String(implementation.edge.unresolved_reason\n ?? implementation.edge.status));\n const implementationTraceEdge: TraceEdge = {\n step: current.depth,\n type: 'operation_implemented_by_handler',\n from: to,\n to: implTo,\n evidence: selected.evidence,\n confidence: Number(implementation.edge.confidence ?? 0),\n unresolvedReason,\n };\n const selectedScope = selectedMethodId\n ? handlerScope(db, selectedMethodId) : undefined;\n recordImplementationObservation(recorder, implementationTraceEdge, {\n operationId: effectiveRow.to_id,\n handlerMethodId: selectedMethodId,\n handlerSymbolId: selectedScope?.symbolId,\n graphEdgeId: implementation.edge.id,\n persistedStatus: implementation.edge.status,\n persistedTargetKind: implementation.edge.to_kind,\n persistedTargetId: implementation.edge.to_id,\n effectiveStatus: contextMethodId\n ? 'resolved' : String(implementation.edge.status),\n strategy: String(contextSelection.evidence.strategy\n ?? (contextMethodId ? 'contextual_implementation_selection'\n : 'indexed_operation_graph')),\n guided: contextSelection.evidence.guided === true,\n contextual: Boolean(contextMethodId\n && contextSelection.evidence.strategy\n !== 'implementation_repo_hint'),\n unresolvedReason, evidence: selected.evidence, site: call,\n });\n }\n if (current.depth >= maxDepth) continue;\n const contextScope = contextMethodId ? handlerScope(db, contextMethodId) : undefined;\n const files = contextScope?.files ?? (implementation.files.size > 0 ? implementation.files : handlerFilesForOperation(db, effectiveRow.to_id));\n const symbolIds = contextScope?.symbolId ? new Set([contextScope.symbolId]) : implementation.symbolId ? new Set([implementation.symbolId]) : undefined;\n if (selectedHandlerAvailable\n && (implementation.edge?.status === 'resolved' || contextScope)\n && files.size > 0) {\n const targetRepoId = contextScope?.repoId ?? implementation.repoId ?? (db\n .prepare(\n 'SELECT s.repo_id repoId FROM cds_operations o JOIN cds_services s ON s.id=o.service_id WHERE o.id=?',\n )\n .get(effectiveRow.to_id)?.repoId as number | undefined);\n const nextContext = new Map<string, ContextBinding>();\n const scheduling = scheduler.schedule({\n workspaceId: workspaceId ?? call.workspaceId,\n repoId: targetRepoId,\n files,\n symbolIds,\n context: nextContext,\n }, current.state);\n if (scheduling.kind === 'cycle') {\n const cycleEvidence = { ...evidence, cycle: true,\n cycleReason: 'structural_ancestry_cycle' };\n const cycleEdge: TraceEdge = {\n step: current.depth,\n type: 'cycle',\n from: to,\n to: scheduling.state.structuralKey,\n evidence: cycleEvidence,\n confidence: 1,\n unresolvedReason:\n 'Cycle detected in structural ancestry; downstream scope was not expanded',\n };\n recordCycleObservation(recorder, cycleEdge, semantic.target, {\n workspaceId: semanticWorkspaceId, repositoryId: targetRepoId,\n sourceFiles: files, symbolIds,\n structuralKey: scheduling.state.structuralKey,\n }, { graphEdgeId: evidence.persistedGraphEdgeId,\n outboundCallId: call.id,\n operationId: effectiveRow.to_id }, call);\n }\n if (scheduling.kind === 'scheduled') enqueueCausalScope(\n queue, pendingRoots, { repoId: targetRepoId, files, symbolIds,\n depth: current.depth + 1, context: nextContext,\n state: scheduling.state });\n }\n }\n }\n }\n }\n const runtimeDiagnostic = runtimeVariableDiagnostic(edges);\n if (runtimeDiagnostic) prependTraceDiagnostic(diagnostics, runtimeDiagnostic);\n for (const diagnostic of runtimeNoCandidateDiagnostics(edges))\n prependTraceDiagnostic(diagnostics, diagnostic);\n return { start, nodes: [...nodes.values()], edges, diagnostics };\n}\n\nexport function traceWithObserver(\n db: Db,\n start: TraceStart,\n options: TraceOptions,\n observer: CompactTraceObserver,\n): TraceResult {\n const observed: ObservedTraceOptions = {\n ...options,\n [compactObserverKey]: observer,\n };\n return trace(db, start, observed);\n}\n","import type { Db } from '../db/connection.js';\nimport type {\n DynamicMode,\n TraceOptions,\n TraceResult,\n TraceStart,\n} from '../types.js';\n\nexport type CompactStatus =\n | 'resolved'\n | 'terminal'\n | 'inferred'\n | 'dynamic'\n | 'ambiguous'\n | 'unresolved'\n | 'cycle';\n\nexport type CompactEndpointSide = 'source' | 'target';\n\nexport type CompactSemanticEndpoint =\n | { kind: 'operation'; operationId: number }\n | { kind: 'symbol'; symbolId: number }\n | { kind: 'handler_method'; handlerMethodId: number }\n | { kind: 'event'; workspaceId: number; eventName: string }\n | {\n kind: 'target';\n workspaceId: number;\n repositoryId?: number;\n targetKind: string;\n targetId: string;\n }\n | {\n kind: 'call_site';\n workspaceId: number;\n repositoryId: number;\n repositoryName: string;\n sourceFile: string;\n sourceLine: number;\n startOffset?: number;\n endOffset?: number;\n callId: number;\n }\n | {\n kind: 'scope';\n workspaceId: number;\n repositoryId?: number;\n sourceFiles: string[];\n symbolIds: number[];\n structuralKey: string;\n }\n | {\n kind: 'unavailable';\n side: CompactEndpointSide;\n endpointKind: string;\n detailedEdgeIndex: number;\n site?: CompactSourceSite;\n };\n\nexport type CompactRemediationCode =\n | 'provide_runtime_variables'\n | 'select_implementation'\n | 'reindex_and_link'\n | 'inspect_detailed_edge';\n\nexport interface CompactDecisionTargetInput {\n kind: string;\n id: string;\n}\n\nexport interface CompactDecisionInput {\n effectiveResolutionStatus?: string;\n effectiveTarget?: CompactDecisionTargetInput;\n persistedResolutionStatus?: string;\n persistedTarget?: CompactDecisionTargetInput;\n missingVariableNames?: string[];\n missingVariableCount?: number;\n dynamicMode?: DynamicMode;\n candidateCount?: number;\n viableCandidateCount?: number;\n rejectedCandidateCount?: number;\n omittedCandidateCount?: number;\n implementationStrategy?: string;\n implementationGuided?: boolean;\n implementationContextual?: boolean;\n reasonCode?: string;\n eventMatchStrategy?: string;\n dispatchCertainty?: string;\n eventSubscriptionCount?: number;\n associationStatus?: string;\n associationBasis?: string;\n eventScope?: string;\n callRole?: string;\n factOrigin?: string;\n roleSiteMatchCount?: number;\n bodyExpansion?: string;\n remediationCode?: CompactRemediationCode;\n remediationHintCount?: number;\n}\n\nexport interface CompactReferenceInput {\n graphEdgeIds?: Array<number | string>;\n outboundCallIds?: Array<number | string>;\n subscribeCallIds?: Array<number | string>;\n symbolCallIds?: Array<number | string>;\n operationIds?: Array<number | string>;\n symbolIds?: Array<number | string>;\n handlerMethodIds?: Array<number | string>;\n}\n\nexport interface CompactSourceSite {\n repository?: string;\n sourceFile?: string;\n sourceLine?: number;\n startOffset?: number;\n endOffset?: number;\n}\n\nexport interface CompactEdgeObservation {\n ordinal: number;\n step: number;\n type: string;\n source: CompactSemanticEndpoint;\n target: CompactSemanticEndpoint;\n status: CompactStatus;\n confidence: number;\n decision?: CompactDecisionInput;\n refs?: CompactReferenceInput;\n site?: CompactSourceSite;\n}\n\nexport interface CompactTraceObserver {\n record(observation: CompactEdgeObservation): void;\n setWorkspaceId?(workspaceId: number | undefined): void;\n}\n\nexport class CompactObservationCollector implements CompactTraceObserver {\n readonly observations: CompactEdgeObservation[] = [];\n workspaceId?: number;\n\n record(observation: CompactEdgeObservation): void {\n this.observations.push(observation);\n }\n\n setWorkspaceId(workspaceId: number | undefined): void {\n this.workspaceId = workspaceId;\n }\n}\n\nexport interface CompactSourceContext {\n schemaVersion: number;\n analyzerVersion: string;\n graphGeneration: number;\n}\n\nexport interface CompactProjectionInput {\n db: Db;\n start: TraceStart;\n options: TraceOptions;\n source: CompactSourceContext;\n trace: TraceResult;\n observations: CompactEdgeObservation[];\n}\n\nexport interface CompactHintV1 {\n servicePath: string | null;\n operationPath: string | null;\n packageName: string | null;\n repositoryName: string | null;\n candidateFamily: string | null;\n implementationRepo: string | null;\n}\n\nexport interface CompactStartV1 {\n repo: string | null;\n servicePath: string | null;\n operation: string | null;\n operationPath: string | null;\n handler: string | null;\n}\n\nexport interface CompactQueryV1 {\n depth: number;\n includeAsync: boolean;\n includeDb: boolean;\n includeExternal: boolean;\n dynamicMode: DynamicMode;\n maxDynamicCandidates: number;\n suppliedVariableNames: string[];\n runtimeValuesOmitted: true;\n implementationRepo: string | null;\n implementationHints: CompactHintV1[];\n}\n\nexport interface CompactReferenceGroupV1 {\n values: Array<number | string>;\n total: number;\n shown: number;\n omitted: number;\n}\n\nexport interface CompactReferencesV1 {\n graphEdgeIds?: CompactReferenceGroupV1;\n outboundCallIds?: CompactReferenceGroupV1;\n subscribeCallIds?: CompactReferenceGroupV1;\n symbolCallIds?: CompactReferenceGroupV1;\n operationIds?: CompactReferenceGroupV1;\n symbolIds?: CompactReferenceGroupV1;\n handlerMethodIds?: CompactReferenceGroupV1;\n}\n\nexport interface CompactDecisionV1 {\n effectiveResolutionStatus?: string;\n effectiveTarget?: string;\n persistedResolutionStatus?: string;\n persistedTarget?: string;\n missingVariableNames?: string[];\n missingVariableCount?: number;\n shownMissingVariableCount?: number;\n omittedMissingVariableCount?: number;\n dynamicMode?: DynamicMode;\n candidateCount?: number;\n viableCandidateCount?: number;\n rejectedCandidateCount?: number;\n omittedCandidateCount?: number;\n implementationStrategy?: string;\n implementationGuided?: boolean;\n implementationContextual?: boolean;\n eventMatchStrategy?: string;\n dispatchCertainty?: string;\n eventSubscriptionCount?: number;\n associationStatus?: string;\n associationBasis?: string;\n eventScope?: string;\n callRole?: string;\n factOrigin?: string;\n roleSiteMatchCount?: number;\n bodyExpansion?: string;\n reasonCode?: string;\n remediationHint?: string;\n omittedRemediationHintCount?: number;\n}\n\nexport interface CompactEdgeDetailsV1 {\n decision: CompactDecisionV1;\n refs: CompactReferencesV1;\n}\n\nexport interface CompactDiagnosticDetailsV1 {\n reasonCode?: string;\n missingVariableNames?: string[];\n missingVariableCount?: number;\n shownMissingVariableCount?: number;\n omittedMissingVariableCount?: number;\n candidateCount?: number;\n viableCandidateCount?: number;\n rejectedCandidateCount?: number;\n remediationHint?: string;\n omittedHintCount?: number;\n}\n\nexport interface CompactProjectedDiagnostic {\n index: number;\n severity: 'error' | 'warning' | 'info';\n code: string;\n message: string;\n file?: string;\n line?: number;\n details?: CompactDiagnosticDetailsV1;\n}\n\nexport type CompactNodeRowV1 = [\n id: string,\n kind: string,\n label: string,\n repo: number | null,\n file: number | null,\n line: number | null,\n];\n\nexport type CompactEdgeRowV1 = [\n id: string,\n traceOrdinals: number[],\n step: number,\n type: string,\n from: string,\n to: string,\n status: CompactStatus,\n confidence: number,\n count: number,\n details: CompactEdgeDetailsV1 | null,\n];\n\nexport type CompactDiagnosticRowV1 = [\n fullDiagnosticIndex: number,\n severity: 'error' | 'warning' | 'info',\n code: string,\n message: string,\n file: number | null,\n line: number | null,\n details: CompactDiagnosticDetailsV1 | null,\n];\n\nexport interface CompactStatusCountsV1 {\n resolved: number;\n terminal: number;\n inferred: number;\n dynamic: number;\n ambiguous: number;\n unresolved: number;\n cycle: number;\n}\n\nexport interface CompactGraphV1 {\n schema: 'service-flow/compact-graph@1';\n start: CompactStartV1;\n query: CompactQueryV1;\n source: CompactSourceContext;\n summary: {\n completeness: 'complete' | 'partial' | 'blocked';\n fullTraceNodes: number;\n fullTraceEdges: number;\n fullTraceDiagnostics: number;\n nodes: number;\n edges: number;\n collapsedEdges: number;\n statusCounts: CompactStatusCountsV1;\n projection: {\n evidence: 'summary-only';\n syntheticEndpoints: number;\n omittedUnreferencedFullNodes: number;\n };\n };\n repos: string[];\n files: string[];\n nodeColumns: ['id', 'kind', 'label', 'repo', 'file', 'line'];\n nodes: CompactNodeRowV1[];\n edgeColumns: [\n 'id', 'traceOrdinals', 'step', 'type', 'from', 'to',\n 'status', 'confidence', 'count', 'details',\n ];\n edges: CompactEdgeRowV1[];\n diagnosticColumns: [\n 'fullDiagnosticIndex', 'severity', 'code', 'message',\n 'file', 'line', 'details',\n ];\n diagnostics: CompactDiagnosticRowV1[];\n}\n","import { redactText } from '../utils/redaction.js';\nimport type {\n ImplementationHint,\n TraceOptions,\n TraceStart,\n} from '../types.js';\nimport { compareBinary } from './010-traversal-scope.js';\nimport type {\n CompactDecisionInput,\n CompactDecisionV1,\n CompactDiagnosticDetailsV1,\n CompactDiagnosticRowV1,\n CompactEdgeObservation,\n CompactHintV1,\n CompactProjectedDiagnostic,\n CompactQueryV1,\n CompactStartV1,\n CompactStatusCountsV1,\n} from './014-compact-contract.js';\n\nconst compactNameLimit = 8;\nconst compactDiagnosticMessages: Readonly<Record<string, string>> = {\n schema_upgrade_required: 'The database schema must be upgraded before tracing.',\n reindex_required: 'Current analyzer facts are required before tracing.',\n trace_workspace_ambiguous: 'The trace workspace is ambiguous.',\n trace_runtime_variables_missing: 'Runtime variable names are required to resolve a branch.',\n implementation_hint_mismatch: 'The implementation hint did not select one implementation.',\n selected_handler_provenance_mismatch: 'Selected handler provenance did not match its graph target.',\n selected_handler_target_not_found: 'The selected handler target is not indexed.',\n trace_start_implementation_unresolved: 'The trace start implementation is unresolved.',\n};\n\nexport function projectCompactDecision(\n input: CompactDecisionInput | undefined,\n): CompactDecisionV1 {\n if (!input) return {};\n const out = resolutionDecision(input);\n addNameDecision(out, input);\n addDynamicDecision(out, input);\n addImplementationDecision(out, input);\n addEventDecision(out, input);\n const reasonCode = compactSafeCode(input.reasonCode);\n if (reasonCode) out.reasonCode = reasonCode;\n addRemediationDecision(out, input);\n return out;\n}\n\nfunction resolutionDecision(input: CompactDecisionInput): CompactDecisionV1 {\n const out: CompactDecisionV1 = {};\n const status = compactSafeCode(input.effectiveResolutionStatus);\n if (status) out.effectiveResolutionStatus = status;\n if (!persistedResolutionDiffers(input)) return out;\n const persistedStatus = compactSafeCode(input.persistedResolutionStatus);\n if (persistedStatus) out.persistedResolutionStatus = persistedStatus;\n return out;\n}\n\nfunction addNameDecision(out: CompactDecisionV1, input: CompactDecisionInput): void {\n const allNames = safeVariableNames(input.missingVariableNames);\n const names = allNames.slice(0, compactNameLimit);\n const total = Math.max(compactCount(input.missingVariableCount), allNames.length);\n if (names.length > 0) out.missingVariableNames = names;\n if (total === 0) return;\n out.missingVariableCount = total;\n out.shownMissingVariableCount = names.length;\n out.omittedMissingVariableCount = Math.max(0, total - names.length);\n}\n\nfunction addDynamicDecision(out: CompactDecisionV1, input: CompactDecisionInput): void {\n if (input.dynamicMode) out.dynamicMode = input.dynamicMode;\n if (input.candidateCount !== undefined) out.candidateCount = compactCount(input.candidateCount);\n if (input.viableCandidateCount !== undefined)\n out.viableCandidateCount = compactCount(input.viableCandidateCount);\n if (input.rejectedCandidateCount !== undefined)\n out.rejectedCandidateCount = compactCount(input.rejectedCandidateCount);\n if (input.omittedCandidateCount !== undefined)\n out.omittedCandidateCount = compactCount(input.omittedCandidateCount);\n}\n\nfunction addImplementationDecision(\n out: CompactDecisionV1,\n input: CompactDecisionInput,\n): void {\n const strategy = compactSafeCode(input.implementationStrategy);\n if (strategy) out.implementationStrategy = strategy;\n if (input.implementationGuided !== undefined)\n out.implementationGuided = input.implementationGuided;\n if (input.implementationContextual !== undefined)\n out.implementationContextual = input.implementationContextual;\n}\n\nfunction addEventDecision(out: CompactDecisionV1, input: CompactDecisionInput): void {\n addEventCodes(out, input);\n if (input.eventSubscriptionCount !== undefined)\n out.eventSubscriptionCount = compactCount(input.eventSubscriptionCount);\n if (input.roleSiteMatchCount !== undefined)\n out.roleSiteMatchCount = compactCount(input.roleSiteMatchCount);\n}\n\nfunction addEventCodes(out: CompactDecisionV1, input: CompactDecisionInput): void {\n const values: Array<[keyof CompactDecisionV1, string | undefined]> = [\n ['eventMatchStrategy', compactSafeCode(input.eventMatchStrategy)],\n ['dispatchCertainty', compactSafeCode(input.dispatchCertainty)],\n ['associationStatus', compactSafeCode(input.associationStatus)],\n ['associationBasis', compactSafeCode(input.associationBasis)],\n ['eventScope', compactSafeCode(input.eventScope)],\n ['callRole', compactSafeCode(input.callRole)],\n ['factOrigin', compactSafeCode(input.factOrigin)],\n ['bodyExpansion', compactSafeCode(input.bodyExpansion)],\n ];\n for (const [key, value] of values) {\n if (value) Object.assign(out, { [key]: value });\n }\n}\n\nfunction addRemediationDecision(\n out: CompactDecisionV1,\n input: CompactDecisionInput,\n): void {\n const hint = input.remediationCode\n ? compactRemediationHint(input.remediationCode) : undefined;\n if (!hint) return;\n out.remediationHint = hint;\n const total = Math.max(1, compactCount(input.remediationHintCount));\n out.omittedRemediationHintCount = Math.max(0, total - 1);\n}\n\nexport function projectCompactDiagnostics(\n values: Array<Record<string, unknown>>,\n): CompactProjectedDiagnostic[] {\n return values.map((value, index) => compactDiagnostic(value, index))\n .sort(compareCompactDiagnostic);\n}\n\nexport function projectCompactStart(start: TraceStart): CompactStartV1 {\n return {\n repo: start.repo ?? null,\n servicePath: start.servicePath ?? null,\n operation: start.operation ?? null,\n operationPath: start.operationPath ?? null,\n handler: start.handler ?? null,\n };\n}\n\nexport function projectCompactQuery(options: TraceOptions): CompactQueryV1 {\n const hints = (options.implementationHints ?? []).map(projectCompactHint)\n .sort((left, right) => compareBinary(\n JSON.stringify(left), JSON.stringify(right),\n ));\n return {\n depth: compactPositiveInteger(options.depth) ?? 25,\n includeAsync: Boolean(options.includeAsync),\n includeDb: Boolean(options.includeDb),\n includeExternal: Boolean(options.includeExternal),\n dynamicMode: options.dynamicMode ?? 'strict',\n maxDynamicCandidates: compactPositiveInteger(options.maxDynamicCandidates) ?? 5,\n suppliedVariableNames: compactSortedUnique(Object.keys(options.vars ?? {})),\n runtimeValuesOmitted: true,\n implementationRepo: options.implementationRepo ?? null,\n implementationHints: hints,\n };\n}\n\nfunction projectCompactHint(hint: ImplementationHint): CompactHintV1 {\n return {\n servicePath: hint.servicePath ?? null,\n operationPath: hint.operationPath ?? null,\n packageName: hint.packageName ?? null,\n repositoryName: hint.repositoryName ?? null,\n candidateFamily: hint.candidateFamily ?? null,\n implementationRepo: hint.implementationRepo ?? null,\n };\n}\n\nexport function compactStatusCounts(\n values: CompactEdgeObservation[],\n): CompactStatusCountsV1 {\n const counts: CompactStatusCountsV1 = {\n resolved: 0, terminal: 0, inferred: 0, dynamic: 0,\n ambiguous: 0, unresolved: 0, cycle: 0,\n };\n for (const value of values) counts[value.status] += 1;\n return counts;\n}\n\nexport function compactCompleteness(\n counts: CompactStatusCountsV1,\n diagnostics: CompactDiagnosticRowV1[],\n): 'complete' | 'partial' | 'blocked' {\n const total = compactStatusTotal(counts);\n if (total === 0 && diagnostics.some(compactBlockingDiagnostic)) return 'blocked';\n if (counts.dynamic + counts.ambiguous + counts.unresolved > 0) return 'partial';\n if (diagnostics.some((item) => item[1] === 'error' || item[1] === 'warning'))\n return 'partial';\n return 'complete';\n}\n\nexport function compactStatusTotal(counts: CompactStatusCountsV1): number {\n return counts.resolved + counts.terminal + counts.inferred + counts.dynamic\n + counts.ambiguous + counts.unresolved + counts.cycle;\n}\n\nexport function removeEquivalentCompactPersistedDecision(\n decision: CompactDecisionV1,\n): void {\n if (decision.persistedResolutionStatus !== decision.effectiveResolutionStatus) return;\n if (!decision.persistedTarget || decision.persistedTarget !== decision.effectiveTarget) return;\n delete decision.persistedResolutionStatus;\n delete decision.persistedTarget;\n}\n\nfunction compactBlockingDiagnostic(item: CompactDiagnosticRowV1): boolean {\n if (item[1] === 'error') return true;\n return item[2] === 'schema_upgrade_required'\n || item[2] === 'reindex_required'\n || item[2] === 'trace_workspace_ambiguous'\n || item[2].startsWith('selector_')\n || item[2].startsWith('trace_start_');\n}\n\nfunction compactDiagnostic(\n value: Record<string, unknown>,\n index: number,\n): CompactProjectedDiagnostic {\n const code = compactSafeCode(value.code) ?? 'unknown_diagnostic';\n const details = compactDiagnosticDetails(value, code);\n return {\n index,\n severity: compactDiagnosticSeverity(value.severity),\n code,\n message: compactDiagnosticMessages[code] ?? `See detailed diagnostic at index ${index}.`,\n file: compactSafeSourceFile(value.sourceFile) ?? compactSafeSourceFile(value.file),\n line: compactPositiveInteger(value.sourceLine) ?? compactPositiveInteger(value.line),\n details: Object.keys(details).length > 0 ? details : undefined,\n };\n}\n\nfunction compactDiagnosticDetails(\n value: Record<string, unknown>,\n code: string,\n): CompactDiagnosticDetailsV1 {\n const out: CompactDiagnosticDetailsV1 = {};\n const reasonCode = compactSafeCode(value.reasonCode);\n if (reasonCode) out.reasonCode = reasonCode;\n addDiagnosticNames(out, value);\n addDiagnosticCounts(out, value);\n const hint = compactDiagnosticRemediation(code);\n if (hint) {\n out.remediationHint = hint;\n out.omittedHintCount = Math.max(\n 0, compactDiagnosticHintCount(value, code, out) - 1,\n );\n }\n return out;\n}\n\nfunction addDiagnosticNames(\n out: CompactDiagnosticDetailsV1,\n value: Record<string, unknown>,\n): void {\n const allNames = safeVariableNames(compactStringArray(value.missingVariables));\n const names = allNames.slice(0, compactNameLimit);\n const total = Math.max(allNames.length, compactCount(value.missingVariableCount));\n if (names.length > 0) out.missingVariableNames = names;\n if (total === 0) return;\n out.missingVariableCount = total;\n out.shownMissingVariableCount = names.length;\n out.omittedMissingVariableCount = Math.max(0, total - names.length);\n}\n\nfunction addDiagnosticCounts(\n out: CompactDiagnosticDetailsV1,\n value: Record<string, unknown>,\n): void {\n if (value.candidateCount !== undefined)\n out.candidateCount = compactCount(value.candidateCount);\n if (value.viableCandidateCount !== undefined)\n out.viableCandidateCount = compactCount(value.viableCandidateCount);\n if (value.rejectedCandidateCount !== undefined)\n out.rejectedCandidateCount = compactCount(value.rejectedCandidateCount);\n}\n\nfunction compareCompactDiagnostic(\n left: CompactProjectedDiagnostic,\n right: CompactProjectedDiagnostic,\n): number {\n const ranks = { error: 0, warning: 1, info: 2 } as const;\n return ranks[left.severity] - ranks[right.severity]\n || compareBinary(left.code, right.code)\n || compareBinary(left.file ?? '', right.file ?? '')\n || (left.line ?? Number.MAX_SAFE_INTEGER) - (right.line ?? Number.MAX_SAFE_INTEGER)\n || compareBinary(left.message, right.message)\n || left.index - right.index;\n}\n\nfunction persistedResolutionDiffers(input: CompactDecisionInput): boolean {\n return input.persistedResolutionStatus !== undefined\n && (input.persistedResolutionStatus !== input.effectiveResolutionStatus\n || JSON.stringify(input.persistedTarget) !== JSON.stringify(input.effectiveTarget));\n}\n\nfunction compactDiagnosticSeverity(value: unknown): 'error' | 'warning' | 'info' {\n return value === 'error' || value === 'warning' ? value : 'info';\n}\n\nfunction compactDiagnosticRemediation(code: string): string | undefined {\n if (code === 'schema_upgrade_required' || code === 'reindex_required')\n return compactRemediationHint('reindex_and_link');\n if (code === 'trace_runtime_variables_missing')\n return compactRemediationHint('provide_runtime_variables');\n if (code === 'implementation_hint_mismatch')\n return compactRemediationHint('select_implementation');\n return undefined;\n}\n\nfunction compactDiagnosticHintCount(\n value: Record<string, unknown>,\n code: string,\n details: CompactDiagnosticDetailsV1,\n): number {\n const missing = code === 'trace_runtime_variables_missing'\n ? details.missingVariableCount ?? 0 : 0;\n return Math.max(1, missing, compactArrayLength(value.suggestions),\n compactArrayLength(value.implementationHintSuggestions),\n compactArrayLength(value.copyableExamples), compactCount(value.suggestionCount),\n compactCount(value.implementationHintSuggestionCount),\n compactCount(value.copyableExampleCount));\n}\n\nfunction compactRemediationHint(code: string): string | undefined {\n if (code === 'provide_runtime_variables') return 'Provide the missing variable names listed in details.';\n if (code === 'select_implementation') return 'Select one implementation with a scoped implementation hint.';\n if (code === 'reindex_and_link') return 'Force reindex, then force relink the workspace.';\n if (code === 'inspect_detailed_edge') return 'Inspect the correlated detailed trace edge.';\n return undefined;\n}\n\nexport function compactSafeCode(value: unknown): string | undefined {\n return typeof value === 'string' && /^[a-z][a-z0-9_.-]{0,79}$/.test(value)\n ? value : undefined;\n}\n\nexport function projectCompactDecisionTarget(\n kindValue: string,\n id: string,\n): string | undefined {\n const kind = compactSafeCode(kindValue);\n if (!kind || id.length === 0 || id.length > 240 || /[\\r\\n]/.test(id)) return undefined;\n if (/^[a-z]+:\\/\\//i.test(id)\n || /\\b(?:bearer|token|secret|password|credential|authorization)\\b/i.test(id))\n return undefined;\n const redacted = redactText(id);\n return redacted === id ? `${kind}:${redacted}` : undefined;\n}\n\nfunction compactSafeSourceFile(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 && value.length <= 512\n && !/^[a-z]+:\\/\\//i.test(value) && !/[\\r\\n]/.test(value) ? value : undefined;\n}\n\nfunction safeVariableNames(values: string[] | undefined): string[] {\n return compactSortedUnique((values ?? [])\n .filter((value) => /^[A-Za-z_$][\\w$]*$/.test(value)));\n}\n\nfunction compactCount(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value)\n ? Math.max(0, Math.floor(value)) : 0;\n}\n\nfunction compactPositiveInteger(value: unknown): number | undefined {\n const normalized = compactCount(value);\n return normalized > 0 ? normalized : undefined;\n}\n\nfunction compactStringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string') : [];\n}\n\nfunction compactArrayLength(value: unknown): number {\n return Array.isArray(value) ? value.length : 0;\n}\n\nfunction compactSortedUnique(values: string[]): string[] {\n return [...new Set(values)].sort(compareBinary);\n}\n","import type { Db } from '../db/connection.js';\nimport { redactText } from '../utils/redaction.js';\nimport { compareBinary as binaryCompare } from './010-traversal-scope.js';\nimport {\n type CompactDecisionTargetInput,\n type CompactProjectedDiagnostic,\n type CompactDecisionV1,\n type CompactDiagnosticRowV1,\n type CompactEdgeDetailsV1,\n type CompactEdgeObservation,\n type CompactEdgeRowV1,\n type CompactGraphV1,\n type CompactProjectionInput,\n type CompactReferenceGroupV1,\n type CompactReferenceInput,\n type CompactReferencesV1,\n type CompactSemanticEndpoint,\n type CompactSourceSite,\n type CompactStatus,\n} from './014-compact-contract.js';\nimport {\n compactCompleteness, compactSafeCode, compactStatusCounts, compactStatusTotal,\n projectCompactDecision, projectCompactDecisionTarget, projectCompactDiagnostics,\n projectCompactQuery, projectCompactStart,\n removeEquivalentCompactPersistedDecision,\n} from './020-compact-field-projection.js';\n\nconst REFERENCE_LIMIT = 5;\n\ninterface ResolvedNode {\n key: string;\n kind: string;\n label: string;\n repo?: string;\n file?: string;\n line?: number;\n synthetic: boolean;\n decisionTarget?: string;\n}\n\ninterface ResolvedObservation {\n input: CompactEdgeObservation;\n source: ResolvedNode;\n target: ResolvedNode;\n decision: CompactDecisionV1;\n}\n\ninterface EdgeAggregate {\n source: ResolvedNode;\n target: ResolvedNode;\n step: number;\n type: string;\n status: CompactStatus;\n confidence: number;\n decision: CompactDecisionV1;\n ordinals: number[];\n refs: CompactReferenceInput[];\n site?: CompactSourceSite;\n}\n\nexport function projectCompactGraph(input: CompactProjectionInput): CompactGraphV1 {\n validateObservationOrdinals(input.observations, input.trace.edges.length);\n const resolved = input.observations.map((item) => resolveObservation(input.db, item));\n const diagnostics = projectCompactDiagnostics(input.trace.diagnostics);\n const aggregates = aggregateObservations(resolved);\n const nodes = canonicalNodes(resolved);\n const repos = sortedUnique(nodes.flatMap((node) => node.repo ? [node.repo] : []));\n const files = sortedUnique([\n ...nodes.flatMap((node) => node.file ? [node.file] : []),\n ...diagnostics.flatMap((item) => item.file ? [item.file] : []),\n ]);\n const nodeRows = compactNodeRows(nodes, repos, files);\n const edgeRows = compactEdgeRows(aggregates, nodes);\n const diagnosticRows = compactDiagnosticRows(diagnostics, files);\n const result = compactResult(input, nodes, nodeRows, edgeRows, diagnosticRows, repos, files);\n validateCompactResult(result);\n return result;\n}\n\nfunction resolveObservation(db: Db, input: CompactEdgeObservation): ResolvedObservation {\n const target = resolveEndpoint(db, input.target, input.ordinal, 'target', input.site);\n return {\n input,\n source: resolveEndpoint(db, input.source, input.ordinal, 'source', input.site),\n target,\n decision: observationDecision(db, input, target),\n };\n}\n\nfunction observationDecision(\n db: Db,\n input: CompactEdgeObservation,\n target: ResolvedNode,\n): CompactDecisionV1 {\n const decision = projectCompactDecision(input.decision);\n if (decision.effectiveResolutionStatus && target.decisionTarget)\n decision.effectiveTarget = target.decisionTarget;\n if (decision.persistedResolutionStatus && input.decision?.persistedTarget) {\n const persisted = persistedDecisionTarget(db, input.decision.persistedTarget);\n if (persisted) decision.persistedTarget = persisted;\n }\n removeEquivalentCompactPersistedDecision(decision);\n return decision;\n}\n\nfunction persistedDecisionTarget(\n db: Db,\n target: CompactDecisionTargetInput,\n): string | undefined {\n const numeric = numericId(target.id);\n if (target.kind === 'operation' && numeric !== undefined)\n return operationNode(db, numeric)?.decisionTarget;\n if (target.kind === 'symbol' && numeric !== undefined)\n return symbolNode(db, numeric)?.decisionTarget;\n if (target.kind === 'handler_method' && numeric !== undefined)\n return handlerNode(db, numeric)?.decisionTarget;\n return projectCompactDecisionTarget(target.kind, target.id);\n}\n\nfunction resolveEndpoint(\n db: Db,\n endpoint: CompactSemanticEndpoint,\n ordinal: number,\n side: 'source' | 'target',\n site: CompactSourceSite | undefined,\n): ResolvedNode {\n if (endpoint.kind === 'operation')\n return resolvedOrUnavailable(operationNode(db, endpoint.operationId), side,\n 'operation', ordinal, site);\n if (endpoint.kind === 'symbol')\n return resolvedOrUnavailable(symbolNode(db, endpoint.symbolId), side,\n 'symbol', ordinal, site);\n if (endpoint.kind === 'handler_method')\n return resolvedOrUnavailable(handlerNode(db, endpoint.handlerMethodId), side,\n 'handler_method', ordinal, site);\n if (endpoint.kind === 'event') return eventNode(endpoint.workspaceId, endpoint.eventName);\n if (endpoint.kind === 'target') return targetNode(db, endpoint, ordinal, side, site);\n if (endpoint.kind === 'call_site') return callSiteNode(db, endpoint);\n if (endpoint.kind === 'scope') return scopeNode(db, endpoint);\n return unavailableNode(endpoint.side, endpoint.endpointKind,\n endpoint.detailedEdgeIndex, endpoint.site ?? site);\n}\n\nfunction resolvedOrUnavailable(\n node: ResolvedNode | undefined,\n side: 'source' | 'target',\n kind: string,\n ordinal: number,\n site?: CompactSourceSite,\n): ResolvedNode {\n return node ?? unavailableNode(side, kind, ordinal, site);\n}\n\nfunction operationNode(db: Db, operationId: number): ResolvedNode | undefined {\n const row = db.prepare(`SELECT o.id,o.operation_name operationName,\n o.operation_path operationPath,o.source_file sourceFile,o.source_line sourceLine,\n s.service_path servicePath,r.workspace_id workspaceId,r.relative_path relativePath,\n r.name repoName\n FROM cds_operations o JOIN cds_services s ON s.id=o.service_id\n JOIN repositories r ON r.id=s.repo_id WHERE o.id=?`).get(operationId);\n if (!row) return undefined;\n const operationPath = stringValue(row.operationPath);\n const servicePath = stringValue(row.servicePath);\n const repo = repositoryLabel(row);\n const workspaceId = numberValue(row.workspaceId);\n if (!operationPath) return undefined;\n if (!servicePath) return undefined;\n if (!repo) return undefined;\n if (workspaceId === undefined) return undefined;\n const operationName = stringValue(row.operationName);\n return {\n key: canonicalKey('operation', workspaceId, repo, servicePath, operationPath),\n kind: 'operation',\n label: `${servicePath}:${operationName || operationPath}`,\n repo,\n file: stringValue(row.sourceFile),\n line: numberValue(row.sourceLine),\n synthetic: false,\n decisionTarget: projectCompactDecisionTarget('operation',\n `${repo}:${servicePath}:${operationPath}`),\n };\n}\n\nfunction symbolNode(db: Db, symbolId: number): ResolvedNode | undefined {\n const row = db.prepare(`SELECT s.id,s.kind,s.qualified_name qualifiedName,\n s.source_file sourceFile,s.start_line startLine,s.start_offset startOffset,\n s.end_offset endOffset,r.workspace_id workspaceId,r.relative_path relativePath,\n r.name repoName FROM symbols s JOIN repositories r ON r.id=s.repo_id\n WHERE s.id=?`).get(symbolId);\n return symbolNodeFromRow(row);\n}\n\nfunction symbolNodeFromRow(row: Record<string, unknown> | undefined): ResolvedNode | undefined {\n if (!row) return undefined;\n const name = stringValue(row.qualifiedName);\n const repo = repositoryLabel(row);\n const file = stringValue(row.sourceFile);\n const workspaceId = numberValue(row.workspaceId);\n if (!name) return undefined;\n if (!repo) return undefined;\n if (!file) return undefined;\n if (workspaceId === undefined) return undefined;\n const startOffset = numberValue(row.startOffset);\n const endOffset = numberValue(row.endOffset);\n return {\n key: canonicalKey('symbol', workspaceId, repo, file,\n startOffset, endOffset, name),\n kind: 'symbol', label: name, repo, file,\n line: numberValue(row.startLine), synthetic: false,\n decisionTarget: projectCompactDecisionTarget('symbol',\n `${repo}:${file}:${startOffset ?? ''}:${endOffset ?? ''}:${name}`),\n };\n}\n\nfunction handlerNode(db: Db, handlerMethodId: number): ResolvedNode | undefined {\n const symbol = db.prepare(`SELECT s.kind,s.qualified_name qualifiedName,\n s.source_file sourceFile,s.start_line startLine,s.start_offset startOffset,\n s.end_offset endOffset,r.workspace_id workspaceId,r.relative_path relativePath,\n r.name repoName\n FROM handler_methods hm JOIN handler_classes hc ON hc.id=hm.handler_class_id\n JOIN repositories r ON r.id=hc.repo_id LEFT JOIN symbols s\n ON s.repo_id=hc.repo_id AND s.source_file=hc.source_file\n AND s.qualified_name=hc.class_name || '.' || hm.method_name\n AND s.start_line=hm.source_line WHERE hm.id=?\n ORDER BY s.id LIMIT 1`).get(handlerMethodId);\n const resolved = symbolNodeFromRow(symbol);\n return resolved ?? standaloneHandlerNode(db, handlerMethodId);\n}\n\nfunction standaloneHandlerNode(db: Db, handlerMethodId: number): ResolvedNode | undefined {\n const row = db.prepare(`SELECT hm.method_name methodName,hm.source_file sourceFile,\n hm.source_line sourceLine,hc.class_name className,r.workspace_id workspaceId,\n r.relative_path relativePath,r.name repoName FROM handler_methods hm\n JOIN handler_classes hc ON hc.id=hm.handler_class_id\n JOIN repositories r ON r.id=hc.repo_id WHERE hm.id=?`).get(handlerMethodId);\n if (!row) return undefined;\n const methodName = stringValue(row.methodName);\n const className = stringValue(row.className);\n const repo = repositoryLabel(row);\n const file = stringValue(row.sourceFile);\n const workspaceId = numberValue(row.workspaceId);\n if (!methodName) return undefined;\n if (!className) return undefined;\n if (!repo) return undefined;\n if (!file) return undefined;\n if (workspaceId === undefined) return undefined;\n const sourceLine = numberValue(row.sourceLine);\n return {\n key: canonicalKey('handler_method', workspaceId, repo, file,\n sourceLine, className, methodName),\n kind: 'handler_method', label: `${className}.${methodName}`, repo, file,\n line: sourceLine, synthetic: false,\n decisionTarget: projectCompactDecisionTarget('handler_method',\n `${repo}:${file}:${sourceLine ?? ''}:${className}.${methodName}`),\n };\n}\n\nfunction eventNode(workspaceId: number, eventName: string): ResolvedNode {\n return {\n key: canonicalKey('event', workspaceId, eventName),\n kind: 'event', label: eventName, synthetic: false,\n decisionTarget: projectCompactDecisionTarget('event', eventName),\n };\n}\n\nfunction targetNode(\n db: Db,\n endpoint: Extract<CompactSemanticEndpoint, { kind: 'target' }>,\n ordinal: number,\n side: 'source' | 'target',\n site: CompactSourceSite | undefined,\n): ResolvedNode {\n const linked = linkedTargetNode(db, endpoint.targetKind, endpoint.targetId);\n if (linked !== undefined)\n return linked ?? unavailableNode(side, endpoint.targetKind, ordinal, site);\n const repo = endpoint.repositoryId === undefined\n ? undefined : repositoryById(db, endpoint.repositoryId);\n return {\n key: canonicalKey('target', endpoint.workspaceId, repo,\n endpoint.targetKind, endpoint.targetId),\n kind: compactTargetKind(endpoint.targetKind),\n label: endpoint.targetId || endpoint.targetKind,\n repo,\n synthetic: false,\n decisionTarget: projectCompactDecisionTarget(endpoint.targetKind, endpoint.targetId),\n };\n}\n\nfunction linkedTargetNode(\n db: Db,\n kind: string,\n id: string,\n): ResolvedNode | null | undefined {\n const numeric = numericId(id);\n if (kind === 'operation') {\n if (numeric === undefined) return null;\n return operationNode(db, numeric) ?? null;\n }\n if (kind === 'symbol') {\n if (numeric === undefined) return null;\n return symbolNode(db, numeric) ?? null;\n }\n if (kind === 'handler_method') {\n if (numeric === undefined) return null;\n return handlerNode(db, numeric) ?? null;\n }\n return undefined;\n}\n\nfunction callSiteNode(\n db: Db,\n endpoint: Extract<CompactSemanticEndpoint, { kind: 'call_site' }>,\n): ResolvedNode {\n const repo = repositoryById(db, endpoint.repositoryId) ?? endpoint.repositoryName;\n const span = endpoint.startOffset === undefined || endpoint.endOffset === undefined\n ? ['line', endpoint.sourceLine] : [endpoint.startOffset, endpoint.endOffset];\n return {\n key: canonicalKey('call_site', endpoint.workspaceId, repo,\n endpoint.sourceFile, ...span, endpoint.callId),\n kind: 'call_site',\n label: `${repo}:${endpoint.sourceFile}:${endpoint.sourceLine}`,\n repo, file: endpoint.sourceFile, line: endpoint.sourceLine, synthetic: false,\n decisionTarget: projectCompactDecisionTarget('call_site',\n `${repo}:${endpoint.sourceFile}:${span.join(':')}`),\n };\n}\n\nfunction scopeNode(\n db: Db,\n endpoint: Extract<CompactSemanticEndpoint, { kind: 'scope' }>,\n): ResolvedNode {\n const repo = endpoint.repositoryId === undefined\n ? undefined : repositoryById(db, endpoint.repositoryId);\n const files = sortedUnique(endpoint.sourceFiles);\n const symbols = sortedUnique(endpoint.symbolIds.flatMap((id) => {\n const key = symbolNode(db, id)?.key;\n return key ? [key] : [];\n }));\n const identity = canonicalKey('scope', endpoint.workspaceId, repo, files, symbols);\n return {\n key: symbols.length > 0 || files.length > 0 ? identity\n : canonicalKey('scope', endpoint.workspaceId, repo, endpoint.structuralKey),\n kind: 'scope',\n label: repo ? `scope:${repo}` : 'scope:workspace',\n repo, file: files.length === 1 ? files[0] : undefined,\n synthetic: false,\n decisionTarget: projectCompactDecisionTarget('scope', identity),\n };\n}\n\nfunction unavailableNode(\n side: 'source' | 'target',\n endpointKind: string,\n ordinal: number,\n site?: CompactSourceSite,\n): ResolvedNode {\n return {\n key: canonicalKey('unavailable', side, endpointKind,\n site?.repository, site?.sourceFile, site?.startOffset,\n site?.endOffset, site?.sourceLine, ordinal),\n kind: 'synthetic',\n label: `${side}:${compactSafeCode(endpointKind) ?? 'unavailable'}`,\n repo: site?.repository,\n file: site?.sourceFile,\n line: site?.sourceLine,\n synthetic: true,\n };\n}\n\nfunction aggregateObservations(items: ResolvedObservation[]): EdgeAggregate[] {\n const groups = new Map<string, EdgeAggregate>();\n for (const item of items) {\n const key = aggregationKey(item);\n const current = groups.get(key);\n if (current) appendAggregate(current, item);\n else groups.set(key, createAggregate(item));\n }\n return [...groups.values()].map(finalizeAggregate);\n}\n\nfunction aggregationKey(item: ResolvedObservation): string {\n return JSON.stringify([\n item.input.step, item.input.type, item.source.key, item.target.key,\n item.input.status, normalizedConfidence(item.input.confidence), item.decision,\n ]);\n}\n\nfunction createAggregate(item: ResolvedObservation): EdgeAggregate {\n return {\n source: item.source, target: item.target, step: item.input.step,\n type: item.input.type, status: item.input.status,\n confidence: normalizedConfidence(item.input.confidence),\n decision: item.decision, ordinals: [item.input.ordinal],\n refs: item.input.refs ? [item.input.refs] : [], site: item.input.site,\n };\n}\n\nfunction appendAggregate(group: EdgeAggregate, item: ResolvedObservation): void {\n group.ordinals.push(item.input.ordinal);\n if (item.input.refs) group.refs.push(item.input.refs);\n if (compareSite(item.input.site, group.site) < 0) group.site = item.input.site;\n}\n\nfunction finalizeAggregate(group: EdgeAggregate): EdgeAggregate {\n group.ordinals.sort((left, right) => left - right);\n return group;\n}\n\nfunction canonicalNodes(items: ResolvedObservation[]): ResolvedNode[] {\n const nodes = new Map<string, ResolvedNode>();\n for (const node of items.flatMap((item) => [item.source, item.target])) {\n const existing = nodes.get(node.key);\n if (!existing || compareNodeBody(node, existing) < 0) nodes.set(node.key, node);\n }\n return [...nodes.values()].sort((left, right) => binaryCompare(left.key, right.key));\n}\n\nfunction compactNodeRows(\n nodes: ResolvedNode[],\n repos: string[],\n files: string[],\n): CompactGraphV1['nodes'] {\n const repoIndexes = indexMap(repos);\n const fileIndexes = indexMap(files);\n return nodes.map((node, index) => [\n `n${index}`, node.kind, redactText(node.label),\n node.repo === undefined ? null : repoIndexes.get(node.repo) ?? null,\n node.file === undefined ? null : fileIndexes.get(node.file) ?? null,\n node.line ?? null,\n ]);\n}\n\nfunction compactEdgeRows(\n groups: EdgeAggregate[],\n nodes: ResolvedNode[],\n): CompactGraphV1['edges'] {\n const nodeIndexes = new Map(nodes.map((node, index) => [node.key, index]));\n const sorted = [...groups].sort((left, right) => compareAggregate(left, right, nodeIndexes));\n return sorted.map((group, index) => edgeRow(group, index, nodeIndexes));\n}\n\nfunction edgeRow(\n group: EdgeAggregate,\n index: number,\n nodeIndexes: Map<string, number>,\n): CompactEdgeRowV1 {\n const source = nodeIndexes.get(group.source.key);\n const target = nodeIndexes.get(group.target.key);\n if (source === undefined || target === undefined) throw compactError('edge_node_missing');\n return [\n `e${index}`, group.ordinals, group.step, group.type, `n${source}`, `n${target}`,\n group.status, group.confidence, group.ordinals.length, edgeDetails(group),\n ];\n}\n\nfunction edgeDetails(group: EdgeAggregate): CompactEdgeDetailsV1 | null {\n const refs = projectReferences(group.refs);\n if (Object.keys(group.decision).length === 0 && Object.keys(refs).length === 0) return null;\n return { decision: group.decision, refs };\n}\n\nfunction projectReferences(values: CompactReferenceInput[]): CompactReferencesV1 {\n const out: CompactReferencesV1 = {};\n setReference(out, 'graphEdgeIds', values.flatMap((item) => item.graphEdgeIds ?? []));\n setReference(out, 'outboundCallIds', values.flatMap((item) => item.outboundCallIds ?? []));\n setReference(out, 'subscribeCallIds', values.flatMap((item) => item.subscribeCallIds ?? []));\n setReference(out, 'symbolCallIds', values.flatMap((item) => item.symbolCallIds ?? []));\n setReference(out, 'operationIds', values.flatMap((item) => item.operationIds ?? []));\n setReference(out, 'symbolIds', values.flatMap((item) => item.symbolIds ?? []));\n setReference(out, 'handlerMethodIds', values.flatMap((item) => item.handlerMethodIds ?? []));\n return out;\n}\n\nfunction setReference(\n out: CompactReferencesV1,\n key: keyof CompactReferencesV1,\n values: Array<number | string>,\n): void {\n const unique = uniqueReferences(values);\n if (unique.length === 0) return;\n const shown = unique.slice(0, REFERENCE_LIMIT);\n out[key] = {\n values: shown, total: unique.length, shown: shown.length,\n omitted: unique.length - shown.length,\n } satisfies CompactReferenceGroupV1;\n}\n\nfunction compactDiagnosticRows(\n diagnostics: CompactProjectedDiagnostic[],\n files: string[],\n): CompactDiagnosticRowV1[] {\n const fileIndexes = indexMap(files);\n return diagnostics.map((item) => [\n item.index, item.severity, item.code, item.message,\n item.file === undefined ? null : fileIndexes.get(item.file) ?? null,\n item.line ?? null, item.details ?? null,\n ]);\n}\n\nfunction compactResult(\n input: CompactProjectionInput,\n resolvedNodes: ResolvedNode[],\n nodes: CompactGraphV1['nodes'],\n edges: CompactGraphV1['edges'],\n diagnostics: CompactGraphV1['diagnostics'],\n repos: string[],\n files: string[],\n): CompactGraphV1 {\n const statusCounts = compactStatusCounts(input.observations);\n return {\n schema: 'service-flow/compact-graph@1',\n start: projectCompactStart(input.start),\n query: projectCompactQuery(input.options),\n source: input.source,\n summary: {\n completeness: compactCompleteness(statusCounts, diagnostics),\n fullTraceNodes: input.trace.nodes.length,\n fullTraceEdges: input.trace.edges.length,\n fullTraceDiagnostics: input.trace.diagnostics.length,\n nodes: nodes.length, edges: edges.length,\n collapsedEdges: input.trace.edges.length - edges.length,\n statusCounts,\n projection: {\n evidence: 'summary-only',\n syntheticEndpoints: resolvedNodes.filter((node) => node.synthetic).length,\n omittedUnreferencedFullNodes: omittedDetailedNodeCount(input),\n },\n },\n repos, files,\n nodeColumns: ['id', 'kind', 'label', 'repo', 'file', 'line'],\n nodes,\n edgeColumns: ['id', 'traceOrdinals', 'step', 'type', 'from', 'to',\n 'status', 'confidence', 'count', 'details'],\n edges,\n diagnosticColumns: ['fullDiagnosticIndex', 'severity', 'code', 'message',\n 'file', 'line', 'details'],\n diagnostics,\n };\n}\n\nfunction omittedDetailedNodeCount(input: CompactProjectionInput): number {\n const referenced = new Set(input.observations.flatMap((item) => [\n ...detailedNodeIds(item.source), ...detailedNodeIds(item.target),\n ]));\n return input.trace.nodes.filter((node) => {\n const id = typeof node.id === 'string' ? node.id : undefined;\n return id === undefined || !referenced.has(id);\n }).length;\n}\n\nfunction detailedNodeIds(endpoint: CompactSemanticEndpoint): string[] {\n if (endpoint.kind === 'operation') return [`operation:${endpoint.operationId}`];\n if (endpoint.kind === 'symbol') return [`symbol:${endpoint.symbolId}`];\n if (endpoint.kind === 'handler_method')\n return [`handler_method:${endpoint.handlerMethodId}`];\n if (endpoint.kind === 'event') return [`event:${endpoint.eventName}`];\n if (endpoint.kind === 'target') return [`${endpoint.targetKind}:${endpoint.targetId}`];\n if (endpoint.kind === 'call_site') return [`call:${endpoint.callId}`];\n if (endpoint.kind === 'scope')\n return endpoint.symbolIds.map((symbolId) => `symbol:${symbolId}`);\n return [];\n}\n\nfunction validateObservationOrdinals(\n observations: CompactEdgeObservation[],\n fullEdgeCount: number,\n): void {\n const ordinals = observations.map((item) => item.ordinal).sort((left, right) => left - right);\n if (ordinals.length !== fullEdgeCount) throw compactError('observation_count_mismatch');\n if (ordinals.some((value, index) => value !== index))\n throw compactError('trace_ordinal_partition_invalid');\n}\n\nfunction validateCompactResult(result: CompactGraphV1): void {\n if (result.summary.nodes !== result.nodes.length) throw compactError('node_count_mismatch');\n if (result.summary.edges !== result.edges.length) throw compactError('edge_count_mismatch');\n const statusTotal = compactStatusTotal(result.summary.statusCounts);\n if (statusTotal !== result.summary.fullTraceEdges) throw compactError('status_count_mismatch');\n const edgeTotal = result.edges.reduce((sum, edge) => sum + edge[8], 0);\n if (edgeTotal !== result.summary.fullTraceEdges) throw compactError('edge_member_count_mismatch');\n if (result.edges.some((edge) => edge.length !== 10 || edge[8] !== edge[1].length))\n throw compactError('edge_tuple_invalid');\n if (result.nodes.some((node) => node.length !== 6)) throw compactError('node_tuple_invalid');\n if (result.diagnostics.some((item) => item.length !== 7)) throw compactError('diagnostic_tuple_invalid');\n validateResultOrdinals(result);\n}\n\nfunction validateResultOrdinals(result: CompactGraphV1): void {\n const ordinals = result.edges.flatMap((edge) => edge[1]).sort((left, right) => left - right);\n if (ordinals.some((value, index) => value !== index)\n || ordinals.length !== result.summary.fullTraceEdges)\n throw compactError('output_trace_ordinal_partition_invalid');\n if (result.summary.collapsedEdges !== result.summary.fullTraceEdges - result.summary.edges)\n throw compactError('collapsed_edge_count_mismatch');\n}\n\nfunction compareAggregate(\n left: EdgeAggregate,\n right: EdgeAggregate,\n nodeIndexes: Map<string, number>,\n): number {\n return left.step - right.step\n || indexFor(nodeIndexes, left.source.key) - indexFor(nodeIndexes, right.source.key)\n || indexFor(nodeIndexes, left.target.key) - indexFor(nodeIndexes, right.target.key)\n || binaryCompare(left.type, right.type)\n || binaryCompare(left.status, right.status)\n || compareSite(left.site, right.site)\n || (left.ordinals[0] ?? 0) - (right.ordinals[0] ?? 0);\n}\n\nfunction compareSite(left: CompactSourceSite | undefined, right: CompactSourceSite | undefined): number {\n return binaryCompare(siteSortKey(left), siteSortKey(right));\n}\n\nfunction siteSortKey(site: CompactSourceSite | undefined): string {\n return JSON.stringify([\n site?.repository ?? '', site?.sourceFile ?? '',\n sortableNumber(site?.startOffset), sortableNumber(site?.endOffset),\n sortableNumber(site?.sourceLine),\n ]);\n}\n\nfunction sortableNumber(value: number | undefined): string {\n return value === undefined ? 'z' : `n${String(value).padStart(16, '0')}`;\n}\n\nfunction compareNodeBody(left: ResolvedNode, right: ResolvedNode): number {\n return binaryCompare(JSON.stringify([\n left.kind, left.label, left.repo, left.file, left.line,\n ]), JSON.stringify([\n right.kind, right.label, right.repo, right.file, right.line,\n ]));\n}\n\nfunction compactTargetKind(kind: string): string {\n if (kind === 'db_entity') return 'database_entity';\n if (kind === 'operation_candidate') return 'dynamic_target';\n if (kind === 'symbol_reference' || kind === 'subscription_handler')\n return 'unresolved_target';\n return compactSafeCode(kind) ?? 'target';\n}\n\nfunction repositoryById(db: Db, repositoryId: number): string | undefined {\n const row = db.prepare('SELECT relative_path relativePath,name repoName FROM repositories WHERE id=?')\n .get(repositoryId);\n return repositoryLabel(row);\n}\n\nfunction repositoryLabel(row: Record<string, unknown> | undefined): string | undefined {\n return stringValue(row?.relativePath) ?? stringValue(row?.repoName);\n}\n\nfunction normalizedConfidence(value: number): number {\n return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;\n}\n\nfunction numericId(value: string): number | undefined {\n return /^\\d+$/.test(value) ? Number(value) : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction uniqueReferences(values: Array<number | string>): Array<number | string> {\n const unique = new Map(values.map((value) => [`${typeof value}:${String(value)}`, value]));\n return [...unique.values()].sort((left, right) => {\n if (typeof left === 'number' && typeof right === 'number') return left - right;\n return binaryCompare(`${typeof left}:${String(left)}`, `${typeof right}:${String(right)}`);\n });\n}\n\nfunction sortedUnique(values: string[]): string[] {\n return [...new Set(values)].sort(binaryCompare);\n}\n\nfunction canonicalKey(...parts: unknown[]): string {\n return JSON.stringify(parts);\n}\n\nfunction indexMap(values: string[]): Map<string, number> {\n return new Map(values.map((value, index) => [value, index]));\n}\n\nfunction indexFor(values: Map<string, number>, key: string): number {\n const value = values.get(key);\n if (value === undefined) throw compactError('canonical_node_index_missing');\n return value;\n}\n\nfunction compactError(code: string): Error {\n return new Error(`compact_graph_invariant:${code}`);\n}\n","import type { Db } from '../db/connection.js';\nimport { CURRENT_SCHEMA_VERSION } from '../db/migrations.js';\nimport type { CompactGraphV1, CompactSourceContext } from './014-compact-contract.js';\nimport { CompactObservationCollector } from './014-compact-contract.js';\nimport { projectCompactGraph } from './016-compact-projector.js';\nimport { traceWithObserver } from './trace-engine.js';\nimport type { TraceOptions, TraceResult, TraceStart } from '../types.js';\n\nexport interface CompactTraceExecution {\n trace: TraceResult;\n compact: CompactGraphV1;\n}\n\nexport function compactTrace(\n db: Db,\n start: TraceStart,\n options: TraceOptions,\n): CompactGraphV1 {\n return traceAndCompact(db, start, options).compact;\n}\n\nexport function traceAndCompact(\n db: Db,\n start: TraceStart,\n options: TraceOptions,\n): CompactTraceExecution {\n const collector = new CompactObservationCollector();\n const trace = traceWithObserver(db, start, options, collector);\n const source = compactSourceContext(db, options, collector.workspaceId);\n const compact = projectCompactGraph({\n db, start, options, source, trace,\n observations: collector.observations,\n });\n return { trace, compact };\n}\n\nexport function compactSourceContext(\n db: Db,\n options: TraceOptions,\n traversalWorkspaceId?: number,\n): CompactSourceContext {\n return {\n schemaVersion: schemaVersion(db),\n analyzerVersion: sourceAnalyzerVersion(\n db, traversalWorkspaceId ?? options.workspaceId,\n ),\n graphGeneration: graphGeneration(\n db, traversalWorkspaceId ?? options.workspaceId,\n ),\n };\n}\n\nfunction sourceAnalyzerVersion(\n db: Db,\n workspaceId: number | undefined,\n): string {\n const rows = db.prepare(`SELECT DISTINCT\n COALESCE(fact_analyzer_version,'legacy_unknown') analyzerVersion\n FROM repositories WHERE (? IS NULL OR workspace_id=?)\n ORDER BY analyzerVersion COLLATE BINARY LIMIT 2`).all(\n workspaceId, workspaceId,\n );\n if (rows.length === 0) return 'none';\n if (rows.length > 1) return 'mixed';\n return stringValue(rows[0]?.analyzerVersion) ?? 'legacy_unknown';\n}\n\nfunction graphGeneration(db: Db, workspaceId: number | undefined): number {\n if (workspaceId === undefined) return 0;\n const rows = db.prepare(`SELECT DISTINCT graph_generation generation\n FROM repositories WHERE workspace_id=?\n ORDER BY graph_generation LIMIT 2`).all(workspaceId);\n return rows.length === 1 ? numberValue(rows[0]?.generation) ?? 0 : 0;\n}\n\nfunction schemaVersion(db: Db): number {\n const row = db.pragma('user_version')[0];\n return numberValue(row?.user_version) ?? CURRENT_SCHEMA_VERSION;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n"],"mappings":";;;AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,eAAiB;AAAA,IACf,QAAU;AAAA,IACV,UAAY;AAAA,EACd;AAAA,EACA,KAAO;AAAA,IACL,gBAAgB;AAAA,EAClB;AAAA,EACA,MAAQ;AAAA,EACR,OAAS;AAAA,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAA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AAA,EAC1B,CAAC;AACD,SAAO,EAAE,OAAAA,QAAO,QAAQ;AAC1B;AAEO,SAAS,qBACd,IACA,SACA,sBACsB;AACtB,SAAO;AAAA,IACL,eAAeC,eAAc,EAAE;AAAA,IAC/B,iBAAiB;AAAA,MACf;AAAA,MAAI,wBAAwB,QAAQ;AAAA,IACtC;AAAA,IACA,iBAAiB;AAAA,MACf;AAAA,MAAI,wBAAwB,QAAQ;AAAA,IACtC;AAAA,EACF;AACF;AAEA,SAAS,sBACP,IACA,aACQ;AACR,QAAMC,QAAO,GAAG,QAAQ;AAAA;AAAA;AAAA,oDAG0B,EAAE;AAAA,IAClD;AAAA,IAAa;AAAA,EACf;AACA,MAAIA,MAAK,WAAW,EAAG,QAAO;AAC9B,MAAIA,MAAK,SAAS,EAAG,QAAO;AAC5B,SAAOC,cAAYD,MAAK,CAAC,GAAG,eAAe,KAAK;AAClD;AAEA,SAAS,gBAAgB,IAAQ,aAAyC;AACxE,MAAI,gBAAgB,OAAW,QAAO;AACtC,QAAMA,QAAO,GAAG,QAAQ;AAAA;AAAA,sCAEY,EAAE,IAAI,WAAW;AACrD,SAAOA,MAAK,WAAW,IAAIE,cAAYF,MAAK,CAAC,GAAG,UAAU,KAAK,IAAI;AACrE;AAEA,SAASD,eAAc,IAAgB;AACrC,QAAM,MAAM,GAAG,OAAO,cAAc,EAAE,CAAC;AACvC,SAAOG,cAAY,KAAK,YAAY,KAAK;AAC3C;AAEA,SAASA,cAAY,OAAoC;AACvD,SAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAASD,cAAY,OAAoC;AACvD,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;","names":["rows","candidates","rows","path","path","fs","path","fs","path","path","fs","fs","path","ts","literal","normalizedCandidate","fs","path","fs","path","ts","resolved","objectValue","fs","path","fs","path","ts","lineOf","ts","path","fs","path","ts","fs","path","ts","lineOf","stringValue","ts","fs","path","ts","propertyName","path","lineOf","rows","resolved","matches","visit","fs","path","ts","path","candidates","path","placeholderKeys","path","ts","ts","unique","ts","rows","matches","path","placeholders","ts","path","methodName","lineOf","propertyName","ts","ts","maxAliasDepth","expressionName","ts","unwrapQueryExpression","declarationScope","resolveBinding","literal","lineOf","expressionName","ts","placeholders","maxAliasDepth","resolveBinding","resolved","candidates","methodName","firstArg","fs","path","placeholders","hint","numericValue","candidates","matches","stringValue","candidates","compareHints","stringArray","numberValue","rows","candidates","unique","stringValue","upperFirst","candidates","isRecord","numberValue","candidates","candidateEvidence","objectJson","isRecord","stringValue","rows","stripExt","nullableString","rows","candidates","matches","mismatch","value","objectJson","status","targetKind","candidates","rows","numericValue","numberValue","stringValue","stringArray","rows","isRecord","candidates","matches","identity","escapeRegex","placeholders","rows","numberValue","stringValue","numberValue","stringValue","reference","rows","record","recordArray","candidates","routingEvidence","stringValue","numberValue","reference","unique","rows","record","stringArray","candidates","isRecord","candidates","bindingEvidence","contextualEvidence","dynamicMode","suggestedVarSets","recordArray","stringValue","rows","objectRecord","recordArray","numericValue","stringValue","numericValue","candidates","implementationCandidates","rows","record","numberValue","isRecord","candidates","recordArray","stringArray","isRecord","record","numberValue","methodName","stringValue","sourceLine","createHash","rows","isRecord","rows","numberValue","graphGeneration","stringValue","sourceLine","isRecord","count","rows","rows","isRecord","rows","bindingCandidates","bindingEvidence","recordArray","stringArray","candidates","dynamicMode","recordValue","stringValue","stringArray","numeric","numeric","normalizeOperation","rows","targetNode","observation","resolved","numeric","operationNode","symbolNode","stringValue","numberValue","methodName","sourceLine","unique","trace","schemaVersion","rows","stringValue","numberValue"]}
|