@vibgrate/cli 2026.801.1 → 2026.803.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/agent-JTA4YWMQ.js +24 -0
  2. package/dist/{agent-4DAECASW.js.map → agent-JTA4YWMQ.js.map} +1 -1
  3. package/dist/baseline-2V7PKA7Q.js +9 -0
  4. package/dist/{baseline-4BDH4F2W.js.map → baseline-2V7PKA7Q.js.map} +1 -1
  5. package/dist/{chunk-76TDXGGF.js → chunk-3Q3ZXJZP.js} +218 -51
  6. package/dist/chunk-3Q3ZXJZP.js.map +1 -0
  7. package/dist/{chunk-G7W4MFPZ.js → chunk-4ACXDVON.js} +4 -4
  8. package/dist/{chunk-G7W4MFPZ.js.map → chunk-4ACXDVON.js.map} +1 -1
  9. package/dist/{chunk-E6H2F2XF.js → chunk-6DFV4WCQ.js} +3 -3
  10. package/dist/{chunk-E6H2F2XF.js.map → chunk-6DFV4WCQ.js.map} +1 -1
  11. package/dist/{chunk-FF5ZQ6KI.js → chunk-6JP7HGIF.js} +4 -4
  12. package/dist/{chunk-FF5ZQ6KI.js.map → chunk-6JP7HGIF.js.map} +1 -1
  13. package/dist/chunk-7KNFG44U.js +6 -0
  14. package/dist/{chunk-TGDHOAXX.js.map → chunk-7KNFG44U.js.map} +1 -1
  15. package/dist/{chunk-T6DRYOMT.js → chunk-CPLG4GFB.js} +4 -4
  16. package/dist/{chunk-T6DRYOMT.js.map → chunk-CPLG4GFB.js.map} +1 -1
  17. package/dist/{chunk-SDG242R4.js → chunk-HC44772H.js} +132 -365
  18. package/dist/chunk-HC44772H.js.map +1 -0
  19. package/dist/{chunk-MPP4S4OE.js → chunk-K6Q6HTFD.js} +32 -11
  20. package/dist/chunk-K6Q6HTFD.js.map +1 -0
  21. package/dist/{chunk-7G5S5KZN.js → chunk-KUZLILN3.js} +16 -3
  22. package/dist/chunk-KUZLILN3.js.map +1 -0
  23. package/dist/{chunk-XEJJGDGX.js → chunk-KYX2YCXT.js} +134 -9
  24. package/dist/chunk-KYX2YCXT.js.map +1 -0
  25. package/dist/{chunk-V2QK3IUY.js → chunk-L5PUNO3T.js} +4 -4
  26. package/dist/{chunk-V2QK3IUY.js.map → chunk-L5PUNO3T.js.map} +1 -1
  27. package/dist/{chunk-7PVCHLR2.js → chunk-M452MRWI.js} +109 -10
  28. package/dist/chunk-M452MRWI.js.map +1 -0
  29. package/dist/{chunk-WIDZ5IE7.js → chunk-M7773OUN.js} +14 -7
  30. package/dist/chunk-M7773OUN.js.map +1 -0
  31. package/dist/{chunk-XRN7DQGR.js → chunk-NJFQCDGA.js} +3 -3
  32. package/dist/{chunk-XRN7DQGR.js.map → chunk-NJFQCDGA.js.map} +1 -1
  33. package/dist/{chunk-BNEHDLVZ.js → chunk-NSWEJPLV.js} +129 -20
  34. package/dist/chunk-NSWEJPLV.js.map +1 -0
  35. package/dist/{chunk-JLWI2JGA.js → chunk-NUZM7UOR.js} +117 -6
  36. package/dist/chunk-NUZM7UOR.js.map +1 -0
  37. package/dist/{chunk-B3OMGYZZ.js → chunk-PXM3VZYR.js} +4 -4
  38. package/dist/{chunk-B3OMGYZZ.js.map → chunk-PXM3VZYR.js.map} +1 -1
  39. package/dist/chunk-QMME6TB4.js +457 -0
  40. package/dist/chunk-QMME6TB4.js.map +1 -0
  41. package/dist/{chunk-G25STLE7.js → chunk-SJFBXCII.js} +30 -3
  42. package/dist/chunk-SJFBXCII.js.map +1 -0
  43. package/dist/{chunk-A43I2AJ4.js → chunk-TM5XQY3L.js} +3 -3
  44. package/dist/{chunk-A43I2AJ4.js.map → chunk-TM5XQY3L.js.map} +1 -1
  45. package/dist/{chunk-KL65SSR7.js → chunk-TNADGCOX.js} +323 -152
  46. package/dist/chunk-TNADGCOX.js.map +1 -0
  47. package/dist/{chunk-V3X3DBZL.js → chunk-UXR7FBE3.js} +6 -6
  48. package/dist/{chunk-V3X3DBZL.js.map → chunk-UXR7FBE3.js.map} +1 -1
  49. package/dist/{chunk-IPICO2RV.js → chunk-VIWZ4QT7.js} +14 -3
  50. package/dist/chunk-VIWZ4QT7.js.map +1 -0
  51. package/dist/{chunk-IRCYOTRG.js → chunk-WGPS3NZQ.js} +240 -13
  52. package/dist/chunk-WGPS3NZQ.js.map +1 -0
  53. package/dist/{chunk-I6RBAIS3.js → chunk-XK5LKOBF.js} +4 -4
  54. package/dist/{chunk-I6RBAIS3.js.map → chunk-XK5LKOBF.js.map} +1 -1
  55. package/dist/cli.js +796 -359
  56. package/dist/cli.js.map +1 -1
  57. package/dist/ensure-map-TAVYMPEG.js +29 -0
  58. package/dist/{ensure-map-SMWHKOUY.js.map → ensure-map-TAVYMPEG.js.map} +1 -1
  59. package/dist/{graph-backend-I4I72J4W.js → graph-backend-WF4LGBGD.js} +5 -5
  60. package/dist/{graph-backend-I4I72J4W.js.map → graph-backend-WF4LGBGD.js.map} +1 -1
  61. package/dist/index.d.ts +143 -7
  62. package/dist/index.js +17 -16
  63. package/dist/index.js.map +1 -1
  64. package/dist/{interactive-TMQR6TXM.js → interactive-6PN237LX.js} +49 -32
  65. package/dist/interactive-6PN237LX.js.map +1 -0
  66. package/dist/load-T2FOJUPI.js +10 -0
  67. package/dist/{load-E3OTM7BS.js.map → load-T2FOJUPI.js.map} +1 -1
  68. package/dist/model-manager-GJ2YSTSK.js +1 -1
  69. package/dist/{run-outcome-QWLNBASF.js → run-outcome-AMIKAASL.js} +6 -6
  70. package/dist/{run-outcome-QWLNBASF.js.map → run-outcome-AMIKAASL.js.map} +1 -1
  71. package/dist/runtime-session-QAVOPSSH.js +20 -0
  72. package/dist/{runtime-session-UQ7UVAPL.js.map → runtime-session-QAVOPSSH.js.map} +1 -1
  73. package/dist/session-SCHQQTHN.js +15 -0
  74. package/dist/{session-MG6BJVAG.js.map → session-SCHQQTHN.js.map} +1 -1
  75. package/dist/session-store-F7NX7SZN.js +4 -0
  76. package/dist/{session-store-SQECEXUU.js.map → session-store-F7NX7SZN.js.map} +1 -1
  77. package/dist/{stream-json-GM44SP7L.js → stream-json-A6K2MONY.js} +48 -16
  78. package/dist/stream-json-A6K2MONY.js.map +1 -0
  79. package/dist/{vg-mcp-bridge-3WFC7LGE.js → vg-mcp-bridge-3TSFOL4V.js} +13 -11
  80. package/dist/vg-mcp-bridge-3TSFOL4V.js.map +1 -0
  81. package/dist/{vgd-ZUSBEVUL.js → vgd-B67JCNJP.js} +9 -9
  82. package/dist/vgd-B67JCNJP.js.map +1 -0
  83. package/package.json +1 -1
  84. package/dist/agent-4DAECASW.js +0 -22
  85. package/dist/baseline-4BDH4F2W.js +0 -9
  86. package/dist/chunk-76TDXGGF.js.map +0 -1
  87. package/dist/chunk-7G5S5KZN.js.map +0 -1
  88. package/dist/chunk-7PVCHLR2.js.map +0 -1
  89. package/dist/chunk-BNEHDLVZ.js.map +0 -1
  90. package/dist/chunk-G25STLE7.js.map +0 -1
  91. package/dist/chunk-IPICO2RV.js.map +0 -1
  92. package/dist/chunk-IRCYOTRG.js.map +0 -1
  93. package/dist/chunk-JLWI2JGA.js.map +0 -1
  94. package/dist/chunk-KL65SSR7.js.map +0 -1
  95. package/dist/chunk-MPP4S4OE.js.map +0 -1
  96. package/dist/chunk-SDG242R4.js.map +0 -1
  97. package/dist/chunk-TGDHOAXX.js +0 -6
  98. package/dist/chunk-WIDZ5IE7.js.map +0 -1
  99. package/dist/chunk-XEJJGDGX.js.map +0 -1
  100. package/dist/chunk-ZKNB4YH4.js +0 -102
  101. package/dist/chunk-ZKNB4YH4.js.map +0 -1
  102. package/dist/ensure-map-SMWHKOUY.js +0 -28
  103. package/dist/interactive-TMQR6TXM.js.map +0 -1
  104. package/dist/load-E3OTM7BS.js +0 -10
  105. package/dist/runtime-session-UQ7UVAPL.js +0 -20
  106. package/dist/session-MG6BJVAG.js +0 -13
  107. package/dist/session-store-SQECEXUU.js +0 -4
  108. package/dist/stream-json-GM44SP7L.js.map +0 -1
  109. package/dist/vg-mcp-bridge-3WFC7LGE.js.map +0 -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AAW,OAAA,EAAS,CAAA,EAAE;AAAA,IACvG;AAAA,GACF;AACA,EAAA,OAAO,IAAA,CAAK,SAAA,CAAU,GAAA,EAAK,IAAA,EAAM,CAAC,CAAA,GAAI,IAAA;AACxC;AAEA,SAAS,KAAK,GAAA,EAA4B;AACxC,EAAA,MAAM,YAAY,GAAA,CAAI,IAAA,IAAQ,EAAC,EAAG,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,IAC5C,MAAA,EAAQ,CAAA,gBAAA,EAAmB,WAAA,CAAY,CAAA,CAAE,IAAI,CAAC,CAAA,CAAA;AAAA,IAC9C,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,WAAA,EAAa,CAAA,CAAE,SAAA,IAAa,CAAA,CAAE,QAAA;AAAA,IAC9B,gBAAA,EAAkB;AAAA,GACpB,CAAE,CAAA;AACF,EAAA,MAAM,GAAA,GAAM;AAAA,IACV,WAAA,EAAa,UAAA;AAAA,IACb,WAAA,EAAa,SAAA;AAAA,IACb,MAAA,EAAQ,kBAAA;AAAA,IACR,IAAA,EAAM,SAAA;AAAA,IACN,YAAA,EAAc,EAAE,OAAA,EAAS,GAAA,CAAI,WAAA,EAAa,QAAA,EAAU,CAAC,CAAA,SAAA,EAAY,GAAA,CAAI,KAAA,CAAM,UAAA,CAAW,OAAO,EAAE,CAAA,EAAE;AAAA,IACjG;AAAA,GACF;AACA,EAAA,OAAO,IAAA,CAAK,SAAA,CAAU,GAAA,EAAK,IAAA,EAAM,CAAC,CAAA,GAAI,IAAA;AACxC","file":"chunk-BNEHDLVZ.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { parseGraph } from '../engine/serialize.js';\nimport { mapFileStat } from '../engine/snapshot.js';\nimport { loadGraphPreferIndex } from '../engine/index-db.js';\nimport { refreshIfStale } from '../engine/refresh.js';\nimport { TOOLS, warmEmbedderInBackground } from './tools.js';\nimport { renderToolResult } from './response.js';\nimport { recordSaving, sanitizeClient, PER_FILE_TOKENS, SAVINGS_TOOLS, type Outcome } from '../engine/savings.js';\nimport type { SessionStats } from './serve-stats.js';\nimport { countTokens } from '../engine/tokens.js';\nimport { VERSION } from '../version.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * The local `vg serve` MCP server. Self-contained and offline. Freshness is\n * two-layered, with no filesystem watcher (freshness only matters at the\n * moment of a query, so we check on read instead of watching):\n *\n * 1. **Hot reload** — `graph.json` is re-read whenever its mtime changes, so a\n * rebuild from ANY source (a foreground `vg`, another serve process, CI)\n * is picked up on the next tool call.\n * 2. **Auto-refresh** (default on) — each tool call runs a debounced, stat-only\n * freshness probe against the last build's snapshot; if the working tree\n * drifted, an incremental rebuild runs in-process (cross-process locked,\n * single-flight). The call waits only a **micro-budget** so a warm probe can\n * land without stalling MCP tools — otherwise it answers from the current\n * map while the rebuild finishes for a later call (hot-reload picks it up).\n *\n * Every tool remains read-only and auto-approvable; the refresh only rewrites\n * vg's own artifacts under `.vibgrate/`, never user code.\n */\n\n/** Min gap between freshness probes — bounds stat-walk cost under bursty tool calls. */\nconst PROBE_INTERVAL_MS = 2000;\n/** Ceiling for the self-tuned probe interval on very large repos. */\nconst MAX_PROBE_INTERVAL_MS = 30_000;\n/** Probe/rebuild may consume at most ~1/PROBE_DUTY_FACTOR of serve wall-time (20 → ≤5%). */\nconst PROBE_DUTY_FACTOR = 20;\n/**\n * How long a tool call waits for an in-flight refresh before answering from\n * the current map. Kept deliberately small: MCP tool latency is sub-10ms on\n * warm maps, and a multi-second budget (the previous 5s ceiling matched\n * `git rev-parse`'s spawn timeout) turned every sequential tool call during a\n * large-repo rebuild into a multi-second stall — measured as TypeScript p50\n * ~5.2s on the release benchmark for the `vg-cli-public` corpus entry.\n * Warm probes still finish inside this window; heavy rebuilds never should.\n */\nexport const REFRESH_BUDGET_MS = 100;\n/** After a refresh failure (e.g. read-only checkout), don't retry for this long. */\nconst FAILURE_COOLDOWN_MS = 60_000;\n\nexport type RefreshImpl = typeof refreshIfStale;\n\nexport interface GraphSourceTuning {\n probeIntervalMs?: number;\n refreshBudgetMs?: number;\n /**\n * Workspace root for freshness probes. Prefer passing this explicitly —\n * deriving it from `graphPath` via `dirname` twice only works for the legacy\n * `root/.vibgrate/graph.json` layout, not the global branch-keyed store.\n */\n root?: string;\n /** Tests only: inject a slow/fake refresh to assert the micro-budget. */\n refreshImpl?: RefreshImpl;\n}\n\nexport interface ServeOptions {\n /** Record local, counts-only usage savings (opt-in). */\n savings?: boolean;\n /**\n * Periodically upload the counts-only ledger to Vibgrate (opt-in; off by\n * default). Implies recording. The upload itself is driven by the serve\n * command (see commands/serve.ts + engine/stats-share.ts); here it just also\n * turns recording on so there's something to send.\n */\n shareStats?: boolean;\n /** Air-gapped mode (no model downloads). */\n local?: boolean;\n /** Collapse repeat heavy relation lists within a session (opt-in). */\n dedup?: boolean;\n /** Auto-refresh the map when the working tree drifts (default true). */\n refresh?: boolean;\n /**\n * Workspace root (project directory). When set, freshness probes and tools\n * use this instead of inferring root from the graph path.\n */\n root?: string;\n /**\n * In-memory session stats behind the live `vg serve` status display. Always\n * safe to pass: nothing recorded here is persisted or uploaded — it dies with\n * the process (the opt-in ledger above is a separate concern).\n */\n stats?: SessionStats;\n}\n\nexport class GraphSource {\n private cachedMtimeMs = -1;\n private cached: VgGraph | null = null;\n /** Project root used for freshness probes and rebuilds. */\n readonly root: string;\n private lastProbeAt = 0;\n private failedUntil = 0;\n private inflight: Promise<void> | null = null;\n /** Self-tuned: grows with measured probe/rebuild cost so huge repos aren't penalized. */\n private probeIntervalMs = PROBE_INTERVAL_MS;\n private readonly refreshImpl: RefreshImpl;\n\n constructor(\n readonly graphPath: string,\n private readonly refresh = false,\n /** Timing / root overrides (production passes `root`; tests may pass more). */\n private readonly tuning: GraphSourceTuning = {},\n ) {\n // Prefer an explicit root. Fallback assumes legacy `root/.vibgrate/graph.json`\n // (dirname twice); wrong for the global store — callers should pass `root`.\n this.root = tuning.root ?? path.dirname(path.dirname(graphPath));\n this.refreshImpl = tuning.refreshImpl ?? refreshIfStale;\n }\n\n /** Current graph: auto-refreshed if the tree drifted, reloaded if the file changed. */\n async get(): Promise<VgGraph> {\n if (this.refresh) await this.maybeRefresh();\n // JSON when present, else the standalone snapshot (global-store mode);\n // throws if neither exists → surfaced as tool error.\n const stat = mapFileStat(this.graphPath);\n if (stat.mtimeMs !== this.cachedMtimeMs || !this.cached) {\n // Prefer SQLite reconstruct when corpusHash matches (scale past JSON parse).\n const preferred = loadGraphPreferIndex(this.root, this.graphPath);\n this.cached = preferred\n ? preferred.graph\n : parseGraph(fs.readFileSync(this.graphPath, 'utf8'));\n this.cachedMtimeMs = stat.mtimeMs;\n }\n return this.cached;\n }\n\n /**\n * Debounced, single-flight refresh. Never throws — a refresh problem must\n * degrade to \"answer from the current map\", not break the tool call.\n */\n private async maybeRefresh(): Promise<void> {\n const now = Date.now();\n if (!this.inflight) {\n const interval = this.tuning.probeIntervalMs ?? this.probeIntervalMs;\n if (now < this.failedUntil || now - this.lastProbeAt < interval) return;\n this.lastProbeAt = now;\n this.inflight = this.refreshImpl(this.root, { graphPath: this.graphPath })\n .then((r) => {\n if (r.status === 'error') this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n // Self-tune off the full wall cost of *every* outcome — including a\n // multi-second incremental rebuild. Previously only probe-only\n // outcomes (fresh/no-snapshot/locked) backed off, so a 20s rebuild\n // of a large repo re-armed after the 2s floor and every sequential\n // tool call blocked on the refresh budget for the whole suite.\n const cost =\n r.status === 'refreshed' && typeof r.ms === 'number' ? Math.max(r.ms, Date.now() - now) : Date.now() - now;\n this.probeIntervalMs = Math.min(\n MAX_PROBE_INTERVAL_MS,\n Math.max(PROBE_INTERVAL_MS, cost * PROBE_DUTY_FACTOR),\n );\n })\n .catch(() => {\n this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n })\n .finally(() => {\n this.inflight = null;\n });\n }\n await Promise.race([this.inflight, sleep(this.tuning.refreshBudgetMs ?? REFRESH_BUDGET_MS)]);\n }\n}\n\nexport function createServer(source: GraphSource, opts: ServeOptions = {}): Server {\n const { savings = false, shareStats = false, local = false, dedup = false, stats } = opts;\n // Recording feeds both the local `vg savings` report and the opt-in upload, so\n // enabling either turns it on. Absent both, `vg serve` records nothing.\n const record = savings || shareStats;\n // Prefer GraphSource's explicit root (set by serve from the project cwd).\n const root = opts.root ?? source.root;\n // Per-session memory of node ids whose full detail was already returned — the\n // basis for opt-in cross-call dedup (`--dedup`). Scoped to this server\n // instance so it never leaks across sessions. Node ids are content-addressed\n // (blake3 of content), so an edited node gets a new id and is never falsely\n // treated as already-seen — dedup is stale-safe by construction.\n const seen = new Set<string>();\n const server = new Server(\n { name: 'vg', version: VERSION },\n {\n capabilities: { tools: {} },\n // Routing guidance once at the server level (hosts that surface\n // `instructions` get it at zero per-step schema cost): the flashlight\n // vs the map.\n instructions:\n 'vg is a code map. Use search_symbols to find a known name or literal string fast — ' +\n 'a multi-word/quoted phrase runs a complete literal sweep and reports totalTextMatches, ' +\n 'so reach for it instead of grep even for plain-string \"find every occurrence\" lookups. ' +\n 'Use orient/query_graph for meaning: symptoms, relationships, and what-breaks-if. ' +\n 'Responses are concise by default; pass response_format:\"detailed\" only when a node proves load-bearing. ' +\n // Stop-discipline: the failure mode on a focused task is over-navigation\n // — one more query, one more get_node — which re-bills the whole context\n // every step. One good navigation call usually locates the code.\n 'Navigate as little as possible: one good search/query usually locates the code. ' +\n 'As soon as you have the file and line, read that file and make the edit — ' +\n 'do not call further graph tools unless the edit fails or the match was wrong. ' +\n // Library docs: position against web search (version-correct beats\n // SEO results), and give a stopping rule so a thin doc doesn't turn\n // into an open-ended search loop.\n 'For how-do-I-use-this-library questions call resolve_library once, then library_docs ' +\n 'with the returned targetId and a focused query: the docs are official and matched to ' +\n 'the version THIS project has installed (drift-annotated) — prefer them over web search ' +\n 'or training-data recall when they conflict. Skip them for language built-ins or APIs ' +\n 'already shown in context. If two library_docs calls have not surfaced the section you ' +\n 'need, read the package source under node_modules instead of searching again.',\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: TOOLS.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n annotations: { readOnlyHint: true, openWorldHint: false },\n })),\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const tool = TOOLS.find((t) => t.name === request.params.name);\n if (!tool) {\n return errorResult(`unknown tool \"${request.params.name}\"`);\n }\n let graph: VgGraph;\n try {\n graph = await source.get();\n } catch {\n return errorResult(\n 'no code map found. Run `vg` in the project to build .vibgrate/graph.json, then retry.',\n );\n }\n const startedAt = Date.now();\n try {\n const args = (request.params.arguments ?? {}) as Record<string, unknown>;\n const result = await tool.handler(graph, args, { root, local, dedup, seen });\n const ms = Date.now() - startedAt;\n // Live, in-memory session stats for the serve status display — always on\n // when a serve process passed them (nothing leaves the process).\n stats?.record({ ...measureCall(tool.name, result), client: sanitizeClient(detectClient(server)), ms });\n // Opt-in, counts-only usage ledger: one entry per navigation call, with its\n // outcome, the grep-baseline token counts, and — so `vg savings` can show\n // the command-vs-MCP split and which AI is calling — the source (`mcp`) and\n // the client detected from the initialize handshake.\n if (record) recordUsage(root, tool.name, result, detectClient(server), ms);\n // Compact → clamp to the token ceiling → compact-serialise. See ./response.ts.\n return renderToolResult(result);\n } catch (err) {\n // A failed call still counts in the live display — as a miss, so the\n // operator sees trouble instead of a silently frozen dashboard.\n stats?.record({\n tool: tool.name,\n client: sanitizeClient(detectClient(server)),\n outcome: 'miss',\n ms: Date.now() - startedAt,\n vgTokens: 0,\n baselineTokens: 0,\n });\n return errorResult(`tool \"${tool.name}\" failed: ${(err as Error).message}`);\n }\n });\n\n return server;\n}\n\nexport async function serveStdio(graphPath: string, opts: ServeOptions = {}): Promise<void> {\n const source = new GraphSource(graphPath, opts.refresh !== false, { root: opts.root });\n const server = createServer(source, opts);\n // Start the semantic-model warm-up as soon as the server boots, so the first\n // orient/query_graph doesn't pay a cold download. Non-blocking: navigation\n // answers lexically until the model is ready, then upgrades to semantic.\n warmEmbedderInBackground(opts.local);\n await server.connect(new StdioServerTransport());\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.(); // never keep the server process alive just for the budget timer\n });\n}\n\n/**\n * Append a counts-only usage entry for a navigation call: which tool, how it\n * resolved (complete/partial/miss), and — for the grep-baseline tools — the\n * tokens vg spent vs the grep/read baseline it replaced.\n *\n * `vgTokens` is the size of the payload vg ACTUALLY returned — the rendered text\n * block the model receives and re-pays on every subsequent turn — measured with\n * the same token counter the budget uses. It is deliberately NOT read from a\n * `tokensEstimate` field: only query_graph's rarely-used *detailed* mode ever\n * set that (get_node never did), so the old code recorded nothing under normal\n * concise usage and `vg savings` always reported \"recording is off\".\n */\nexport function recordUsage(root: string, tool: string, result: unknown, client?: string, ms?: number): void {\n recordSaving(\n root,\n { ...measureCall(tool, result), source: 'mcp', client: sanitizeClient(client), ...(ms !== undefined ? { ms } : {}) },\n Date.now(),\n );\n}\n\n/**\n * Measure one tool call for the ledger and the live session stats: its outcome\n * plus — for the grep-baseline tools only — the context tokens vg returned and\n * the baseline they replaced (other tools report zeros, meaning \"no baseline\").\n */\nfunction measureCall(tool: string, result: unknown): { tool: string; outcome: Outcome; vgTokens: number; baselineTokens: number } {\n const outcome = classifyOutcome(result);\n let vgTokens = 0;\n let baselineTokens = 0;\n if (SAVINGS_TOOLS.has(tool) && result && typeof result === 'object') {\n vgTokens = countTokens(renderedText(renderToolResult(result)));\n // Grep/read baseline: ~PER_FILE_TOKENS per distinct file the answer points\n // at — the files a grep/read agent would have had to open to learn the same\n // thing. query_graph surfaces them as `matches[].file`; get_node as its own\n // `file` plus the files of the callers/callees it returned in one call.\n baselineTokens = referencedFiles(result).size * PER_FILE_TOKENS;\n }\n return { tool, outcome, vgTokens, baselineTokens };\n}\n\n/**\n * The coarse client label from the MCP `initialize` handshake, if the host sent\n * `clientInfo`. Read defensively — `getClientVersion()` exists on the SDK Server\n * once initialized, but we never want telemetry bookkeeping to throw. Returns\n * undefined when unknown (then sanitized to `'unknown'`).\n */\nfunction detectClient(server: Server): string | undefined {\n try {\n const info = (server as { getClientVersion?: () => { name?: string } | undefined }).getClientVersion?.();\n return typeof info?.name === 'string' ? info.name : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Bucket a tool result into complete / partial / miss. A `miss` is an answer\n * that found nothing (no match, not-found, not-connected, or an empty listing);\n * a `partial` found results but capped or paginated some of them; everything\n * else is `complete`. Note that a legitimately empty `affected`/`covers` (e.g.\n * \"nothing depends on this\") is a successful answer, not a miss — only the\n * primary discovery signals below mark a miss.\n */\nfunction classifyOutcome(result: unknown): Outcome {\n if (Array.isArray(result)) return result.length === 0 ? 'miss' : 'complete';\n if (!result || typeof result !== 'object') return 'miss';\n const r = result as Record<string, unknown>;\n if (typeof r.error === 'string' && r.error) return 'miss'; // not_found / ambiguous / unresolved\n if (r.connected === false) return 'miss'; // find_path\n if (Array.isArray(r.matches) && r.matches.length === 0) return 'miss'; // query_graph / search_symbols\n return isPartial(r) ? 'partial' : 'complete';\n}\n\n/** True when a hit left results on the table: paginated, or a capped relation list. */\nfunction isPartial(r: Record<string, unknown>): boolean {\n if (r.moreAvailable === true) return true;\n if (r._truncated && typeof r._truncated === 'object') return true;\n // A `<name>Total` greater than the length of its sibling `<name>` array means\n // the array was capped (e.g. get_node's callsTotal vs the shown calls).\n for (const [key, value] of Object.entries(r)) {\n if (typeof value !== 'number' || !key.endsWith('Total')) continue;\n const base = key.slice(0, -'Total'.length);\n const shown = Array.isArray(r[base]) ? (r[base] as unknown[]).length : 0;\n if (value > shown) return true;\n }\n return false;\n}\n\n/** The text block of a rendered tool result — what the model is billed for. */\nfunction renderedText(rendered: CallToolResult): string {\n const block = rendered.content?.find((b) => b.type === 'text');\n return block && 'text' in block && typeof block.text === 'string' ? block.text : '';\n}\n\n/** Distinct files a navigation result points at (its grep/read baseline set). */\nfunction referencedFiles(result: unknown): Set<string> {\n const r = result as { file?: unknown; matches?: unknown; calls?: unknown; calledBy?: unknown };\n const files = new Set<string>();\n if (typeof r.file === 'string' && r.file) files.add(r.file);\n for (const m of asArray(r.matches)) {\n const f = (m as { file?: unknown }).file;\n if (typeof f === 'string' && f) files.add(f);\n }\n // get_node's calls/calledBy are qualified names of the form `path:symbol`; the\n // path prefix is the file a grep/read agent would open to inspect that edge.\n for (const name of [...asArray(r.calls), ...asArray(r.calledBy)]) {\n if (typeof name !== 'string') continue;\n const i = name.indexOf(':');\n if (i > 0) files.add(name.slice(0, i));\n }\n return files;\n}\n\nfunction asArray(v: unknown): unknown[] {\n return Array.isArray(v) ? v : [];\n}\n\nfunction errorResult(message: string) {\n return { content: [{ type: 'text', text: message }], isError: true };\n}\n","import { serializeGraph, slimGraphForExport } from './serialize.js';\nimport { renderReport } from './report.js';\nimport { renderHtml } from './html.js';\nimport type { DepRecord } from './drift.js';\nimport type { LocalModel } from './models.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Above this node count, JSON export defaults to compact (no pretty-print). */\nexport const COMPACT_JSON_NODES = 5_000;\n\n/**\n * Deterministic exporters (VG-CLI-SPEC §4.2). One `vg export <file>` verb, format\n * inferred from the extension. Live graph-DB push is deliberately out (a file\n * import covers the same need offline). CycloneDX/SPDX power the SBOM/AI-BOM seam\n * (VG-LOCAL-MODELS §9.4).\n */\n\nexport type ExportFormat =\n | 'json'\n | 'ndjson'\n | 'graphml'\n | 'dot'\n | 'cypher'\n | 'sql'\n | 'md'\n | 'html'\n | 'cyclonedx'\n | 'spdx';\n\nexport function formatForExt(ext: string): ExportFormat | null {\n switch (ext.toLowerCase()) {\n case '.json':\n return 'json';\n case '.ndjson':\n return 'ndjson';\n case '.graphml':\n return 'graphml';\n case '.dot':\n case '.gv':\n return 'dot';\n case '.cypher':\n return 'cypher';\n case '.sql':\n return 'sql';\n case '.md':\n return 'md';\n case '.html':\n return 'html';\n default:\n return null;\n }\n}\n\nexport interface ExportContext {\n graph: VgGraph;\n deps?: DepRecord[];\n models?: LocalModel[];\n generatedAt: string;\n /** Force compact JSON (no indent). Default: auto when nodes > COMPACT_JSON_NODES. */\n compact?: boolean;\n /** Drop area members + grounding for smaller artifacts. */\n slim?: boolean;\n}\n\nexport function exportGraph(format: ExportFormat, ctx: ExportContext): string {\n const graph = ctx.slim ? slimGraphForExport(ctx.graph) : ctx.graph;\n const compact =\n ctx.compact === true ||\n (ctx.compact !== false && format === 'json' && graph.meta.counts.nodes > COMPACT_JSON_NODES);\n\n switch (format) {\n case 'json':\n return serializeGraph(graph, { compact });\n case 'md':\n return renderReport(graph);\n case 'html':\n return renderHtml(graph);\n case 'ndjson':\n return ndjson(graph);\n case 'graphml':\n return graphml(graph);\n case 'dot':\n return dot(graph);\n case 'cypher':\n return cypher(graph);\n case 'sql':\n return sql({ ...ctx, graph });\n case 'cyclonedx':\n return cyclonedx({ ...ctx, graph });\n case 'spdx':\n return spdx({ ...ctx, graph });\n }\n}\n\nfunction ndjson(graph: VgGraph): string {\n // Facts stream if present, else the node stream — one JSON object per line.\n const rows = graph.facts && graph.facts.length ? graph.facts : graph.nodes;\n return rows.map((r) => JSON.stringify(r)).join('\\n') + '\\n';\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}\n\nfunction graphml(graph: VgGraph): string {\n const lines: string[] = [];\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n lines.push('<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\">');\n lines.push(' <key id=\"name\" for=\"node\" attr.name=\"name\" attr.type=\"string\"/>');\n lines.push(' <key id=\"kind\" for=\"node\" attr.name=\"kind\" attr.type=\"string\"/>');\n lines.push(' <key id=\"file\" for=\"node\" attr.name=\"file\" attr.type=\"string\"/>');\n lines.push(' <key id=\"ekind\" for=\"edge\" attr.name=\"kind\" attr.type=\"string\"/>');\n lines.push(' <graph edgedefault=\"directed\">');\n for (const n of graph.nodes) {\n lines.push(` <node id=\"${esc(n.id)}\"><data key=\"name\">${esc(n.qualifiedName)}</data><data key=\"kind\">${esc(n.kind)}</data><data key=\"file\">${esc(n.file)}</data></node>`);\n }\n for (const e of graph.edges) {\n lines.push(` <edge source=\"${esc(e.src)}\" target=\"${esc(e.dst)}\"><data key=\"ekind\">${esc(e.kind)}</data></edge>`);\n }\n lines.push(' </graph>');\n lines.push('</graphml>');\n return lines.join('\\n') + '\\n';\n}\n\nfunction dot(graph: VgGraph): string {\n const lines: string[] = ['digraph vg {'];\n for (const n of graph.nodes) lines.push(` \"${n.id}\" [label=\"${dotEsc(n.qualifiedName)}\"];`);\n for (const e of graph.edges) lines.push(` \"${e.src}\" -> \"${e.dst}\" [label=\"${e.kind}\"];`);\n lines.push('}');\n return lines.join('\\n') + '\\n';\n}\nfunction dotEsc(s: string): string {\n return s.replace(/\"/g, '\\\\\"');\n}\n\nfunction cypher(graph: VgGraph): string {\n const lines: string[] = [];\n for (const n of graph.nodes) {\n lines.push(\n `CREATE (:\\`${cypherLabel(n.kind)}\\` {id:${q(n.id)}, name:${q(n.qualifiedName)}, file:${q(n.file)}});`,\n );\n }\n for (const e of graph.edges) {\n lines.push(\n `MATCH (a {id:${q(e.src)}}),(b {id:${q(e.dst)}}) CREATE (a)-[:\\`${cypherLabel(e.kind)}\\`]->(b);`,\n );\n }\n return lines.join('\\n') + '\\n';\n}\nfunction cypherLabel(s: string): string {\n return s.replace(/[^A-Za-z0-9_]/g, '_');\n}\nfunction q(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Portable SQL fact-DB (VG-CLI-SPEC §4.2, agent-consumption). Emits deterministic\n * DDL + INSERT text — NOT a native driver — that loads identically into BOTH\n * sqlite3 and duckdb (`sqlite3 map.db < map.sql` / `duckdb map.db < map.sql`).\n * Text keeps the CLI dependency-free, offline, and byte-diffable; an identical\n * graph yields identical bytes. An agent can then run e.g.\n * SELECT src, dst FROM edges WHERE epistemic = 'observed' AND confidence >= 0.9;\n * Determinism: single transaction, `CREATE TABLE IF NOT EXISTS`, rows emitted in\n * the graph's own (already-sorted) array order, single quotes doubled, NULL for\n * absent optionals, booleans as 0/1, and no timestamp but the graph's generatedAt.\n */\nfunction sql(ctx: ExportContext): string {\n const graph = ctx.graph;\n const lines: string[] = [];\n lines.push('BEGIN;');\n\n // meta — provenance / toolchain fingerprint (key/value; agent can read the corpus hash).\n lines.push('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);');\n const meta: [string, string | null][] = [\n ['schemaVersion', graph.schemaVersion],\n ['generatedAt', ctx.generatedAt],\n ['corpusHash', graph.provenance.corpusHash],\n ['tool', graph.provenance.tool],\n ['toolVersion', graph.provenance.version],\n ['resolver', graph.provenance.resolver.join(',')],\n ['fingerprint', graph.provenance.toolchain?.fingerprint ?? null],\n ];\n for (const [k, v] of meta) lines.push(`INSERT INTO meta VALUES (${sqlStr(k)}, ${sqlStr(v)});`);\n\n // nodes\n lines.push(\n 'CREATE TABLE IF NOT EXISTS nodes (id TEXT PRIMARY KEY, kind TEXT, name TEXT, qualified_name TEXT, file TEXT, span_start INTEGER, span_end INTEGER, lang TEXT, visibility TEXT, signature TEXT, importance REAL, area INTEGER, is_hub INTEGER, tested INTEGER, coverage REAL);',\n );\n for (const n of graph.nodes) {\n lines.push(\n `INSERT INTO nodes VALUES (${sqlStr(n.id)}, ${sqlStr(n.kind)}, ${sqlStr(n.name)}, ${sqlStr(n.qualifiedName)}, ${sqlStr(n.file)}, ${sqlNum(n.span.start)}, ${sqlNum(n.span.end)}, ${sqlStr(n.lang)}, ${sqlStr(n.visibility)}, ${sqlStr(n.signature)}, ${sqlNum(n.importance)}, ${sqlNum(n.area)}, ${sqlBool(n.isHub)}, ${sqlBool(n.tested)}, ${sqlNum(n.coverage)});`,\n );\n }\n\n // edges — the epistemic column is the point: SELECT ... WHERE epistemic='observed'.\n lines.push(\n 'CREATE TABLE IF NOT EXISTS edges (id TEXT PRIMARY KEY, kind TEXT, src TEXT, dst TEXT, resolution TEXT, confidence REAL, epistemic TEXT, surprise REAL, \"count\" INTEGER);',\n );\n for (const e of graph.edges) {\n lines.push(\n `INSERT INTO edges VALUES (${sqlStr(e.id)}, ${sqlStr(e.kind)}, ${sqlStr(e.src)}, ${sqlStr(e.dst)}, ${sqlStr(e.resolution)}, ${sqlNum(e.confidence)}, ${sqlStr(e.epistemic)}, ${sqlNum(e.surprise)}, ${sqlNum(e.count)});`,\n );\n }\n\n // areas (+ members)\n lines.push('CREATE TABLE IF NOT EXISTS areas (id INTEGER PRIMARY KEY, label TEXT, size INTEGER, cohesion REAL, external_edges INTEGER);');\n lines.push('CREATE TABLE IF NOT EXISTS area_members (area_id INTEGER, node_id TEXT);');\n for (const a of graph.areas) {\n lines.push(`INSERT INTO areas VALUES (${sqlNum(a.id)}, ${sqlStr(a.label)}, ${sqlNum(a.size)}, ${sqlNum(a.cohesion)}, ${sqlNum(a.externalEdges)});`);\n for (const m of a.members) lines.push(`INSERT INTO area_members VALUES (${sqlNum(a.id)}, ${sqlStr(m)});`);\n }\n\n // facts (+ subjects, evidence) when the graph carried them.\n if (graph.facts && graph.facts.length) {\n lines.push('CREATE TABLE IF NOT EXISTS facts (id TEXT PRIMARY KEY, kind TEXT, predicate_json TEXT, derived_by TEXT, confidence TEXT);');\n lines.push('CREATE TABLE IF NOT EXISTS fact_subjects (fact_id TEXT, node_id TEXT);');\n lines.push('CREATE TABLE IF NOT EXISTS fact_evidence (fact_id TEXT, file TEXT, span_start INTEGER, span_end INTEGER);');\n for (const f of graph.facts) {\n lines.push(`INSERT INTO facts VALUES (${sqlStr(f.id)}, ${sqlStr(f.kind)}, ${sqlStr(JSON.stringify(f.predicate))}, ${sqlStr(f.derivedBy)}, ${sqlStr(f.confidence)});`);\n for (const s of f.subjectIds) lines.push(`INSERT INTO fact_subjects VALUES (${sqlStr(f.id)}, ${sqlStr(s)});`);\n for (const ev of f.evidence) lines.push(`INSERT INTO fact_evidence VALUES (${sqlStr(f.id)}, ${sqlStr(ev.file)}, ${sqlNum(ev.span.start)}, ${sqlNum(ev.span.end)});`);\n }\n }\n\n lines.push('COMMIT;');\n return lines.join('\\n') + '\\n';\n}\n\n/** SQL string literal (single quotes doubled) or NULL for absent values. */\nfunction sqlStr(v: string | null | undefined): string {\n if (v == null) return 'NULL';\n return `'${v.replace(/'/g, \"''\")}'`;\n}\n/** Numeric literal or NULL for absent values. */\nfunction sqlNum(v: number | null | undefined): string {\n return v == null || !Number.isFinite(v) ? 'NULL' : String(v);\n}\n/** Boolean as 0/1, NULL when unknown (e.g. an unanalyzable node's `tested`). */\nfunction sqlBool(v: boolean | null | undefined): string {\n return v == null ? 'NULL' : v ? '1' : '0';\n}\n\nfunction cyclonedx(ctx: ExportContext): string {\n // CycloneDX 1.6 JSON — dependencies as library components + local models as\n // machine-learning-model components (AI-BOM). Deterministic ordering; no\n // timestamps beyond the pinned generatedAt.\n const components: unknown[] = [];\n for (const d of ctx.deps ?? []) {\n components.push({\n type: 'library',\n name: d.name,\n version: d.installed ?? d.declared,\n purl: d.ecosystem === 'npm' ? `pkg:npm/${d.name}@${d.installed ?? ''}` : undefined,\n });\n }\n for (const m of ctx.models ?? []) {\n components.push({ type: 'machine-learning-model', name: m.name, properties: [{ name: 'vg:runtime', value: m.runtime }] });\n }\n const bom = {\n bomFormat: 'CycloneDX',\n specVersion: '1.6',\n metadata: { timestamp: ctx.generatedAt, tools: [{ name: 'vg', version: ctx.graph.provenance.version }] },\n components,\n };\n return JSON.stringify(bom, null, 2) + '\\n';\n}\n\nfunction spdx(ctx: ExportContext): string {\n const packages = (ctx.deps ?? []).map((d) => ({\n SPDXID: `SPDXRef-Package-${cypherLabel(d.name)}`,\n name: d.name,\n versionInfo: d.installed ?? d.declared,\n downloadLocation: 'NOASSERTION',\n }));\n const doc = {\n spdxVersion: 'SPDX-2.3',\n dataLicense: 'CC0-1.0',\n SPDXID: 'SPDXRef-DOCUMENT',\n name: 'vg-sbom',\n creationInfo: { created: ctx.generatedAt, creators: [`Tool: vg-${ctx.graph.provenance.version}`] },\n packages,\n };\n return JSON.stringify(doc, null, 2) + '\\n';\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/code/prompt.ts","../src/code/apply.ts","../src/code/diff.ts","../src/code/providers.ts"],"names":["i","j"],"mappings":";;;AAoBO,IAAM,kBAAA,GAAqB;AAAA,EAChC,6EAAA;AAAA,EACA,wFAAA;AAAA,EACA,qEAAA;AAAA,EACA,EAAA;AAAA,EACA,mEAAA;AAAA,EACA,EAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,+BAAA;AAAA,EACA,SAAA;AAAA,EACA,qBAAA;AAAA,EACA,iBAAA;AAAA,EACA,EAAA;AAAA,EACA,qFAAA;AAAA,EACA,wBAAA;AAAA,EACA,uBAAA;AAAA,EACA,kBAAA;AAAA,EACA,YAAA;AAAA,EACA,6CAAA;AAAA,EACA,EAAA;AAAA,EACA;AACF,CAAA,CAAE,KAAK,IAAI,CAAA;AAWJ,SAAS,cAAc,OAAA,EAAqC;AACjE,EAAA,OAAO;AAAA,IACL,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,kBAAA,EAAmB;AAAA,IAC9C,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,QAAQ,QAAA,EAAS;AAAA,IAC1C,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA,iCAAA,EAAoC,OAAA,CAAQ,WAAW,CAAA,CAAA;AAAG,GACrF;AACF;AAOO,IAAM,mBAAA,GAAsB;AAAA,EACjC,wHAAA;AAAA,EACA,wKAAA;AAAA,EACA,yGAAA;AAAA,EACA,wDAAA;AAAA,EACA,EAAA;AAAA,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BACjC,WAAW,IAAA,CAAK,SAAA;AAAA,gBAChB,SAAS,IAAA,CAAK,OAAA;AAAA,gBACd,gBAAgB,IAAA,CAAK,cAAA;AAAA,gBACrB,gBAAgB,IAAA,CAAK,cAAA;AAAA,gBACrB,0BAAA,EAA4B,CAAC,CAAC,IAAA,CAAK,cAAA;AAAA,gBACnC,iBAAiB,IAAA,CAAK,eAAA;AAAA,gBACtB,gBAAgB,IAAA,CAAK;AAAA;AACvB,aACF;AACA,YAAA,OAAO,EAAE,MAAM,GAAA,CAAI,IAAA,EAAM,OAAO,IAAA,CAAK,KAAA,EAAO,QAAA,EAAU,IAAA,CAAK,EAAA,EAAG;AAAA,UAChE;AAAA,QACF;AAAA,MACF,CAAA,CAAA,MAAQ;AAAA,MAER;AACA,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qCAAA,EAAwC,IAAA,CAAK,SAAS,WAAM,aAAA,CAAe,CAAA,CAAY,OAAO,CAAC,CAAA,CAAE,CAAA;AAAA,IACnH;AAAA,EACF;AACF","file":"chunk-G25STLE7.js","sourcesContent":["/**\n * Prompt assembly with cache-stable ordering (VG-CLI-CODE §5.1).\n *\n * The fast coding tools lean hard on prompt caching — cached tokens are roughly\n * an order of magnitude cheaper and skip re-encoding, so hit-rate is a\n * first-class speed lever. A cache only helps if the *prefix* is byte-stable\n * across turns, which makes prompt ordering a scheduling constraint, not a\n * cosmetic choice: put the invariant material (the instruction contract + the\n * repo-derived context) first and the volatile turn-specific ask last. This\n * module is the single place that ordering is enforced, so every provider\n * inherits it.\n */\n\nimport type { ChatMessage, CodeContext } from './types.js';\n\n/**\n * The system contract for the planner. Intentionally fixed (no interpolation)\n * so it is a perfectly stable cache prefix. It pins the edit *format* the\n * deterministic applier expects — the model's only job is to emit these blocks.\n */\nexport const CODE_SYSTEM_PROMPT = [\n 'You are a precise code-editing assistant operating inside the Vibgrate CLI.',\n 'You are given repository context derived from a deterministic code graph, then a task.',\n 'Propose the smallest correct change. Do not restate unchanged code.',\n '',\n 'Reply ONLY with edit blocks in this exact format, one per change:',\n '',\n '<path/to/file>',\n '<<<<<<< SEARCH',\n '<exact current lines to find>',\n '=======',\n '<replacement lines>',\n '>>>>>>> REPLACE',\n '',\n 'The SEARCH text must match the current file (whitespace differences are tolerated).',\n 'To add a new file use:',\n 'CREATE <path/to/file>',\n '<full file body>',\n 'END CREATE',\n 'To remove a file use: DELETE <path/to/file>',\n '',\n 'Respect every hard constraint in the context. Keep edits minimal and self-consistent.',\n].join('\\n');\n\n/**\n * Build the chat messages for a planning turn, in cache-stable order:\n * 1. system contract (fixed)\n * 2. repository context (stable for the repo/turn — the big, reusable prefix)\n * 3. the task instruction (volatile — always last)\n *\n * Keeping the volatile instruction in its own trailing user turn maximizes the\n * reusable prefix when the same repo is edited across multiple asks.\n */\nexport function buildMessages(context: CodeContext): ChatMessage[] {\n return [\n { role: 'system', content: CODE_SYSTEM_PROMPT },\n { role: 'user', content: context.rendered },\n { role: 'user', content: `Now produce the edit blocks for: ${context.instruction}` },\n ];\n}\n\n/**\n * The system contract for the agentic loop (tool-calling). Fixed text → stable\n * cache prefix. Full coding agent (Claude Code / Codex / Cline / OpenHands class):\n * free tool use, Markdown answers, edits only via tools — never a forced edit IR.\n */\nexport const AGENT_SYSTEM_PROMPT = [\n 'You are VG Code — a full coding agent in a real repository (parity with Claude Code / Codex / Cline / OpenHands).',\n 'You handle every intent: questions, locate/search, design discussion, and multi-file edits. The host never forces an edit format on your turn — you choose tools.',\n 'Most requests change application source. Prefer editing code under packages/src, not package manifests,',\n 'unless the user asks for dependency or packaging work.',\n '',\n 'You receive a Task Capsule (ranked symbols + source slices) as first-turn evidence. Use it;',\n 'it does not replace tools when you need more context.',\n '',\n 'Tools: search_code (graph + literal string/URL sweep — like workspace Find), read_file, list_files, graph_impact,',\n 'library_docs, edit_file, create_file, delete_file, apply_patch, run_command, inspect_task,',\n 'inspect_change, verify_change, ask_user, finish, abort.',\n '',\n 'You also always have the local Vibgrate AI Context MCP tools (namespaced',\n 'mcp__vibgrate__*): search_symbols, query_graph, orient, get_node, impact_of,',\n 'library_docs, check_drift, and the rest of `vg serve`. Prefer them for deep',\n 'graph navigation, docs, and drift. Project MCP servers may add more mcp__* tools.',\n '',\n '## How to work',\n '- Search or read before you edit. Never invent file contents.',\n '- Smallest correct change; check graph_impact / mcp__vibgrate__impact_of before touching shared hubs.',\n '- edit_file SEARCH must match current file (whitespace-flexible). Prefer apply_patch for multi-file edits.',\n '- Run tests or build when useful; use verify_change after multi-file work.',\n '- Mutating tools and shell need user approval — adapt if declined.',\n '',\n '## Answers and task space',\n '- Call finish with a Markdown summary: what you did or found, key `file:line` refs, next steps.',\n '- Q&A / locate / explain: use search_code (pass the exact needle, e.g. stripe or \"stripe\"), then finish with Markdown.',\n '- Do not invent PatchIR, dummy edits, or raw JSON as the user-facing answer. Edits only via edit_file / apply_patch tools.',\n '',\n '## When stuck',\n '- If intent, scope, or trade-off is ambiguous, call ask_user with one clear question (optional options).',\n '- Prefer ask_user over abort when the user can unblock you. Do not guess product requirements.',\n '- abort only when the request is impossible after clarification or lookup.',\n '',\n 'Never dump raw JSON schemas, PatchIR templates, or tool wire formats as the user-facing answer.',\n].join('\\n');\n\n/** Build the opening messages for an agent run: system contract + graph-grounded context + task. */\nexport function buildAgentMessages(context: CodeContext): ChatMessage[] {\n return [\n { role: 'system', content: AGENT_SYSTEM_PROMPT },\n { role: 'user', content: context.rendered },\n { role: 'user', content: `Task: ${context.instruction}` },\n ];\n}\n","/**\n * The deterministic fast-apply merge engine (VG-CLI-CODE §4).\n *\n * Speed in the fast coding tools comes from letting the planner emit a *terse*\n * edit instead of rewriting a whole file; correctness comes from applying that\n * edit **deterministically and scoped**, never by letting the model free-hand\n * the merge. This module is that deterministic floor: it parses the\n * search/replace edit form and applies it with three escalating match\n * strategies — exact, whitespace-flexible, then graph-span-scoped — so an\n * ambiguous SEARCH is resolved to the symbol the planner actually named rather\n * than the first textual hit. No model is required to apply an edit; a hosted\n * fast-apply model is only ever an *acceleration* over this same contract.\n *\n * Everything here is pure and deterministic: identical (content, edit) always\n * yields the identical outcome, which is what makes it unit- and\n * benchmark-testable offline.\n */\n\nimport type { CodeEdit, EditOutcome } from './types.js';\n\n/** A symbol span the graph knows about, used to disambiguate a SEARCH match. */\nexport interface SymbolSpan {\n /** Qualified name, matched against `anchorSymbol`. */\n qualifiedName: string;\n file: string;\n /** 1-based inclusive line range. */\n start: number;\n end: number;\n}\n\n/**\n * Parse a model's reply into structured edits. The accepted form is the\n * widely-supported search/replace block (robust to surrounding prose and code\n * fences), plus explicit whole-file create/delete markers:\n *\n * ```\n * path/to/file.ts\n * <<<<<<< SEARCH\n * old code\n * =======\n * new code\n * >>>>>>> REPLACE\n * ```\n *\n * `CREATE path/to/new.ts` … `END CREATE` wraps a new file's whole body;\n * `DELETE path/to/gone.ts` removes a file. Parsing is forgiving of blank lines\n * and fences but strict about the block markers, so a malformed block surfaces\n * as an `invalid` outcome at apply time rather than silently corrupting a file.\n */\nexport function parseEdits(text: string): CodeEdit[] {\n const edits: CodeEdit[] = [];\n const lines = text.split('\\n');\n let i = 0;\n let pendingFile = '';\n\n const isFence = (s: string): boolean => /^\\s*```/.test(s);\n\n while (i < lines.length) {\n const line = lines[i];\n\n // Whole-file create: `CREATE <path>` … `END CREATE`.\n const create = /^\\s*CREATE\\s+(\\S.*?)\\s*$/.exec(line);\n if (create) {\n const file = create[1];\n const body: string[] = [];\n i++;\n while (i < lines.length && !/^\\s*END CREATE\\s*$/.test(lines[i])) {\n if (!isFence(lines[i])) body.push(lines[i]);\n i++;\n }\n i++; // consume END CREATE\n edits.push({ op: 'create', file, content: body.join('\\n') });\n pendingFile = '';\n continue;\n }\n\n // Whole-file delete: `DELETE <path>`.\n const del = /^\\s*DELETE\\s+(\\S.*?)\\s*$/.exec(line);\n if (del) {\n edits.push({ op: 'delete', file: del[1] });\n i++;\n pendingFile = '';\n continue;\n }\n\n // Search/replace block. The file path is the most recent non-fence,\n // non-blank line before the SEARCH marker (or an inline `path` on it).\n if (/^\\s*<{5,}\\s*SEARCH/.test(line)) {\n const file = pendingFile;\n const search: string[] = [];\n const replace: string[] = [];\n i++;\n while (i < lines.length && !/^\\s*={5,}\\s*$/.test(lines[i])) {\n search.push(lines[i]);\n i++;\n }\n i++; // consume =======\n while (i < lines.length && !/^\\s*>{5,}\\s*REPLACE/.test(lines[i])) {\n replace.push(lines[i]);\n i++;\n }\n i++; // consume >>>>>>> REPLACE\n edits.push({\n op: 'replace',\n file,\n search: search.join('\\n'),\n replace: replace.join('\\n'),\n anchorSymbol: undefined,\n });\n continue;\n }\n\n // Track the most recent file-path candidate: a lone token that looks like a\n // path (has a slash or a file extension) and isn't a fence/marker.\n const trimmed = line.trim();\n if (trimmed && !isFence(line) && looksLikePath(trimmed)) pendingFile = trimmed.replace(/[:`]+$/, '');\n i++;\n }\n\n return edits;\n}\n\nfunction looksLikePath(s: string): boolean {\n if (/\\s/.test(s.replace(/:$/, ''))) return false; // paths don't contain spaces\n return /\\//.test(s) || /\\.[A-Za-z0-9]{1,8}:?$/.test(s);\n}\n\n/**\n * Apply a single edit to a file's current content (or `null` when the file does\n * not exist). Pure: returns the new content and an outcome; never touches disk.\n * The `spans` are the graph's symbol spans for this file — when a SEARCH is\n * textually ambiguous, a match inside the `anchorSymbol` span wins, which is how\n * the graph makes a terse edit land where the planner meant it to.\n */\nexport function applyEdit(\n content: string | null,\n edit: CodeEdit,\n spans: SymbolSpan[] = [],\n): { content: string | null; outcome: EditOutcome } {\n if (edit.op === 'create') {\n if (content !== null && content !== edit.content) {\n return { content, outcome: { edit, status: 'conflict', reason: `${edit.file} already exists — refusing to overwrite it with a create; use a replace edit instead` } };\n }\n return { content: edit.content, outcome: { edit, status: content === edit.content ? 'no-op' : 'applied', matchedBy: 'exact' } };\n }\n\n if (edit.op === 'delete') {\n if (content === null) return { content: null, outcome: { edit, status: 'no-op', reason: `${edit.file} does not exist — nothing to delete` } };\n return { content: null, outcome: { edit, status: 'applied', matchedBy: 'exact' } };\n }\n\n // op === 'replace'\n if (content === null) {\n return { content: null, outcome: { edit, status: 'not-found', reason: `${edit.file} does not exist — a replace needs an existing file (did you mean CREATE ${edit.file}?)` } };\n }\n if (edit.search === '') {\n // Empty SEARCH means \"prepend\" only when the file is empty; otherwise it is\n // ambiguous and we refuse rather than guess a location.\n if (content === '') return { content: edit.replace, outcome: { edit, status: 'applied', matchedBy: 'exact' } };\n return { content, outcome: { edit, status: 'invalid', reason: 'empty SEARCH on a non-empty file is ambiguous — quote the exact lines to replace' } };\n }\n if (edit.search === edit.replace) {\n return { content, outcome: { edit, status: 'no-op', reason: 'SEARCH and REPLACE are identical — no change' } };\n }\n\n const located = locate(content, edit.search, edit.anchorSymbol, spans, edit.file);\n if (located.kind === 'none') {\n return { content, outcome: { edit, status: 'not-found', reason: `the SEARCH text was not found in ${edit.file} — it must match the current file exactly (whitespace-flexible)` } };\n }\n if (located.kind === 'ambiguous') {\n return {\n content,\n outcome: {\n edit,\n status: 'ambiguous',\n reason: `the SEARCH text matches ${located.count} places in ${edit.file} — add more surrounding lines, or name the symbol so the graph can disambiguate`,\n },\n };\n }\n const next = content.slice(0, located.from) + edit.replace + content.slice(located.to);\n return { content: next, outcome: { edit, status: 'applied', matchedBy: located.matchedBy } };\n}\n\n/**\n * Apply a set of edits across a set of files. `read(file)` returns current\n * content or `null`. Edits are applied in the order given, threading each\n * file's evolving content so two edits to the same file compose. Returns, per\n * file, its before/after content and the per-edit outcomes — the dry-run\n * product the session turns into diffs. Deterministic given a deterministic\n * `read`.\n */\nexport function applyEdits(\n edits: CodeEdit[],\n read: (file: string) => string | null,\n spansByFile: (file: string) => SymbolSpan[] = () => [],\n): Map<string, { before: string | null; after: string | null; outcomes: EditOutcome[] }> {\n const state = new Map<string, { before: string | null; after: string | null; outcomes: EditOutcome[] }>();\n for (const edit of edits) {\n let entry = state.get(edit.file);\n if (!entry) {\n const before = read(edit.file);\n entry = { before, after: before, outcomes: [] };\n state.set(edit.file, entry);\n }\n const { content, outcome } = applyEdit(entry.after, edit, spansByFile(edit.file));\n entry.after = content;\n entry.outcomes.push(outcome);\n }\n return state;\n}\n\ntype Located =\n | { kind: 'unique'; from: number; to: number; matchedBy: 'exact' | 'whitespace' | 'graph-span' }\n | { kind: 'ambiguous'; count: number }\n | { kind: 'none' };\n\n/**\n * Find the SEARCH text in the content. Escalates: (1) exact substring; (2)\n * whitespace-flexible (indentation/trailing-space differences tolerated); and\n * when either is ambiguous, (3) narrow to the `anchorSymbol`'s graph span so the\n * intended occurrence wins. Line-oriented so offsets map back to real edits.\n */\nfunction locate(content: string, search: string, anchor: string | undefined, spans: SymbolSpan[], file: string): Located {\n const exact = allIndexes(content, search);\n if (exact.length === 1) return { kind: 'unique', from: exact[0], to: exact[0] + search.length, matchedBy: 'exact' };\n if (exact.length > 1) {\n const scoped = scopeToAnchor(content, exact.map((from) => ({ from, to: from + search.length })), anchor, spans, file);\n if (scoped) return { ...scoped, matchedBy: 'graph-span' };\n return { kind: 'ambiguous', count: exact.length };\n }\n\n // Whitespace-flexible: compare with runs of whitespace collapsed and each\n // line trimmed, then map the match back to real character offsets.\n const flex = flexIndexes(content, search);\n if (flex.length === 1) return { kind: 'unique', from: flex[0].from, to: flex[0].to, matchedBy: 'whitespace' };\n if (flex.length > 1) {\n const scoped = scopeToAnchor(content, flex, anchor, spans, file);\n if (scoped) return { ...scoped, matchedBy: 'graph-span' };\n return { kind: 'ambiguous', count: flex.length };\n }\n return { kind: 'none' };\n}\n\n/** Every start index of `needle` in `hay` (non-overlapping left-to-right). */\nfunction allIndexes(hay: string, needle: string): number[] {\n const out: number[] = [];\n if (needle === '') return out;\n let from = 0;\n for (;;) {\n const idx = hay.indexOf(needle, from);\n if (idx === -1) break;\n out.push(idx);\n from = idx + needle.length;\n }\n return out;\n}\n\n/**\n * Whitespace-flexible match: align the search's trimmed non-empty lines against\n * the content's lines, tolerating indentation and trailing-whitespace drift\n * (the single most common reason an otherwise-correct terse edit fails to\n * apply). Returns real character offset ranges for each full-block match.\n */\nfunction flexIndexes(content: string, search: string): { from: number; to: number }[] {\n const cLines = content.split('\\n');\n const sLines = search.split('\\n');\n // Trim a possible leading/trailing blank line from the search block.\n while (sLines.length && sLines[0].trim() === '') sLines.shift();\n while (sLines.length && sLines[sLines.length - 1].trim() === '') sLines.pop();\n if (sLines.length === 0) return [];\n const sNorm = sLines.map((l) => l.trim());\n\n // Precompute char offset of the start of each content line.\n const lineStart: number[] = [];\n let acc = 0;\n for (const l of cLines) {\n lineStart.push(acc);\n acc += l.length + 1; // +1 for the '\\n'\n }\n\n const out: { from: number; to: number }[] = [];\n for (let i = 0; i + sNorm.length <= cLines.length; i++) {\n let ok = true;\n for (let j = 0; j < sNorm.length; j++) {\n if (cLines[i + j].trim() !== sNorm[j]) {\n ok = false;\n break;\n }\n }\n if (!ok) continue;\n const from = lineStart[i];\n const lastLine = i + sNorm.length - 1;\n const to = lineStart[lastLine] + cLines[lastLine].length; // end of the last matched line (exclusive of '\\n')\n out.push({ from, to });\n }\n return out;\n}\n\n/** If exactly one candidate falls inside the anchor symbol's span, pick it. */\nfunction scopeToAnchor(\n content: string,\n candidates: { from: number; to: number }[],\n anchor: string | undefined,\n spans: SymbolSpan[],\n file: string,\n): { kind: 'unique'; from: number; to: number } | null {\n if (!anchor) return null;\n const span = spans.find((s) => s.file === file && s.qualifiedName === anchor);\n if (!span) return null;\n const lineOf = lineIndexer(content);\n const inside = candidates.filter((c) => {\n const line = lineOf(c.from); // 1-based\n return line >= span.start && line <= span.end;\n });\n if (inside.length === 1) return { kind: 'unique', from: inside[0].from, to: inside[0].to };\n return null;\n}\n\n/** Returns a function mapping a char offset → 1-based line number. */\nfunction lineIndexer(content: string): (offset: number) => number {\n const starts: number[] = [0];\n for (let i = 0; i < content.length; i++) if (content[i] === '\\n') starts.push(i + 1);\n return (offset: number) => {\n // binary search for the greatest line start <= offset\n let lo = 0;\n let hi = starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (starts[mid] <= offset) lo = mid;\n else hi = mid - 1;\n }\n return lo + 1;\n };\n}\n","/**\n * Deterministic unified diff (VG-CLI-CODE §4.3).\n *\n * A `vg code` dry-run shows the human/agent exactly what would change *before*\n * anything is written — the \"inspect the proposal\" half of the governance\n * lifecycle. This is a small, dependency-free Myers-style line diff producing\n * standard unified-diff hunks. Identical (before, after) always renders the\n * identical text, so the dry-run output is stable and diff-able in tests and\n * benchmarks.\n */\n\n/** Render a unified diff for one file. Returns '' when there is no change. */\nexport function unifiedDiff(before: string | null, after: string | null, file: string, context = 3): string {\n if (before === after) return '';\n if (before === null) return newFileDiff(after ?? '', file);\n if (after === null) return deletedFileDiff(before, file);\n\n const a = splitLines(before);\n const b = splitLines(after);\n const ops = diffLines(a, b);\n const hunks = groupHunks(ops, context);\n if (hunks.length === 0) return '';\n\n const out: string[] = [`--- a/${file}`, `+++ b/${file}`];\n for (const h of hunks) {\n out.push(`@@ -${h.aStart},${h.aLen} +${h.bStart},${h.bLen} @@`);\n for (const line of h.lines) out.push(line);\n }\n return out.join('\\n');\n}\n\nfunction newFileDiff(after: string, file: string): string {\n const lines = splitLines(after);\n const out = [`--- /dev/null`, `+++ b/${file}`, `@@ -0,0 +1,${lines.length} @@`];\n for (const l of lines) out.push(`+${l}`);\n return out.join('\\n');\n}\n\nfunction deletedFileDiff(before: string, file: string): string {\n const lines = splitLines(before);\n const out = [`--- a/${file}`, `+++ /dev/null`, `@@ -1,${lines.length} +0,0 @@`];\n for (const l of lines) out.push(`-${l}`);\n return out.join('\\n');\n}\n\nfunction splitLines(s: string): string[] {\n if (s === '') return [];\n const lines = s.split('\\n');\n // A trailing newline yields a final '' element — drop it so line counts match.\n if (lines.length && lines[lines.length - 1] === '') lines.pop();\n return lines;\n}\n\ntype Op = { tag: 'eq' | 'del' | 'add'; line: string };\n\n/**\n * Line diff via LCS (dynamic programming). O(n·m) space is fine for source\n * files; the deterministic backtrace (favouring deletions before additions on\n * ties) keeps output stable.\n */\nfunction diffLines(a: string[], b: string[]): Op[] {\n const n = a.length;\n const m = b.length;\n const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);\n }\n }\n const ops: Op[] = [];\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (a[i] === b[j]) {\n ops.push({ tag: 'eq', line: a[i] });\n i++;\n j++;\n } else if (dp[i + 1][j] >= dp[i][j + 1]) {\n ops.push({ tag: 'del', line: a[i] });\n i++;\n } else {\n ops.push({ tag: 'add', line: b[j] });\n j++;\n }\n }\n while (i < n) ops.push({ tag: 'del', line: a[i++] });\n while (j < m) ops.push({ tag: 'add', line: b[j++] });\n return ops;\n}\n\ninterface Hunk {\n aStart: number;\n aLen: number;\n bStart: number;\n bLen: number;\n lines: string[];\n}\n\n/** Group the op stream into unified-diff hunks with `context` equal lines around changes. */\nfunction groupHunks(ops: Op[], context: number): Hunk[] {\n // Index of each op that is a change (del/add).\n const changeIdx = ops.map((o, i) => (o.tag === 'eq' ? -1 : i)).filter((i) => i >= 0);\n if (changeIdx.length === 0) return [];\n\n // Merge change indices into windows that share context.\n const windows: [number, number][] = [];\n let start = Math.max(0, changeIdx[0] - context);\n let end = Math.min(ops.length - 1, changeIdx[0] + context);\n for (let k = 1; k < changeIdx.length; k++) {\n const cs = Math.max(0, changeIdx[k] - context);\n const ce = Math.min(ops.length - 1, changeIdx[k] + context);\n if (cs <= end + 1) {\n end = ce;\n } else {\n windows.push([start, end]);\n start = cs;\n end = ce;\n }\n }\n windows.push([start, end]);\n\n const hunks: Hunk[] = [];\n // Running 1-based line numbers into a and b.\n let aLine = 1;\n let bLine = 1;\n let idx = 0;\n for (const [ws, we] of windows) {\n // advance line counters up to window start\n while (idx < ws) {\n const o = ops[idx];\n if (o.tag !== 'add') aLine++;\n if (o.tag !== 'del') bLine++;\n idx++;\n }\n const hunk: Hunk = { aStart: aLine, aLen: 0, bStart: bLine, bLen: 0, lines: [] };\n for (let k = ws; k <= we; k++) {\n const o = ops[k];\n if (o.tag === 'eq') {\n hunk.lines.push(` ${o.line}`);\n hunk.aLen++;\n hunk.bLen++;\n aLine++;\n bLine++;\n } else if (o.tag === 'del') {\n hunk.lines.push(`-${o.line}`);\n hunk.aLen++;\n aLine++;\n } else {\n hunk.lines.push(`+${o.line}`);\n hunk.bLen++;\n bLine++;\n }\n idx = k + 1;\n }\n // A hunk that starts at line 1 with zero length should report start 0.\n if (hunk.aLen === 0) hunk.aStart = Math.max(0, hunk.aStart - 1);\n if (hunk.bLen === 0) hunk.bStart = Math.max(0, hunk.bStart - 1);\n hunks.push(hunk);\n }\n return hunks;\n}\n\n/** A compact one-line changeset summary: `+adds -dels across N file(s)`. */\nexport function summarizeDiffs(diffs: { file: string; diff: string }[]): string {\n let adds = 0;\n let dels = 0;\n let touched = 0;\n for (const { diff } of diffs) {\n if (!diff) continue;\n touched++;\n for (const line of diff.split('\\n')) {\n if (line.startsWith('+') && !line.startsWith('+++')) adds++;\n else if (line.startsWith('-') && !line.startsWith('---')) dels++;\n }\n }\n return `+${adds} -${dels} across ${touched} file(s)`;\n}\n","/**\n * Model backends for `vg code` (VG-CLI-CODE §5).\n *\n * Every backend implements the same {@link Provider} contract, so the router and\n * session are provider-agnostic. Three families:\n * - **local HTTP** — Ollama and LM Studio, reached over `fetch` on localhost;\n * no package, no key, no egress. Selected under `--local`.\n * - **hosted HTTP** — any OpenAI-compatible endpoint (OpenRouter, LiteLLM,\n * Together, a self-hosted gateway, …). One shape covers the \"best in breed\n * router\" story: an ordered model list with automatic fallback lives in the\n * router, not here. Keys come from the environment only and are never logged.\n * - **local inference** — a llama.cpp binding loaded on demand via\n * {@link ensurePackage}; this is the one path that may install a package on\n * first use, and only with consent. Model weights are never auto-downloaded.\n *\n * A deterministic {@link MockProvider} backs the tests, the offline benchmark,\n * and the `--mock` flag, so the whole loop runs end-to-end with no network.\n */\n\nimport { ensurePackage, ensureUnavailableMessage } from './ensure.js';\nimport type { ChatMessage, ChatOptions, Provider, ProviderResult, ToolCall, ToolSpec } from './types.js';\n\n/* ------------------------------------------------------------------ *\\\n * Tool-calling wire helpers (shared by the HTTP providers)\n\\* ------------------------------------------------------------------ */\n\n/** Map our ChatMessage union to OpenAI-compatible wire messages (tool calls included). */\nfunction openAiMessages(messages: ChatMessage[]): unknown[] {\n return messages.map((m) => {\n if (m.role === 'tool') return { role: 'tool', tool_call_id: m.toolCallId, name: m.name, content: m.content };\n if (m.role === 'assistant' && m.toolCalls?.length) {\n return {\n role: 'assistant',\n content: m.content || null,\n tool_calls: m.toolCalls.map((t) => ({ id: t.id, type: 'function', function: { name: t.name, arguments: JSON.stringify(t.arguments) } })),\n };\n }\n return { role: m.role, content: m.content };\n });\n}\n\n/** OpenAI-compatible `tools` array from our specs. */\nfunction openAiTools(tools: ToolSpec[] | undefined): unknown[] | undefined {\n if (!tools?.length) return undefined;\n return tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }));\n}\n\n/** Parse OpenAI-shaped tool_calls, tolerating a malformed arguments string. */\nfunction parseToolCalls(raw: unknown, synthesizePrefix = 'call'): ToolCall[] {\n const calls = raw as { id?: string; function?: { name?: string; arguments?: unknown } }[] | undefined;\n if (!Array.isArray(calls)) return [];\n return calls.map((c, i) => ({\n id: typeof c.id === 'string' && c.id ? c.id : `${synthesizePrefix}_${i}`,\n name: c.function?.name ?? 'unknown',\n arguments: coerceArgs(c.function?.arguments),\n }));\n}\n\nfunction coerceArgs(raw: unknown): Record<string, unknown> {\n if (raw && typeof raw === 'object') return raw as Record<string, unknown>;\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/** Redact anything that looks like a credential before it can reach a log/error. */\nexport function redactSecrets(s: string): string {\n return s\n .replace(/\\b(sk|xoxb|ghp|gho|glpat|AKIA)[-_][A-Za-z0-9-_]{6,}/g, '$1-***redacted***')\n .replace(/Bearer\\s+[A-Za-z0-9._-]{8,}/gi, 'Bearer ***redacted***');\n}\n\n/** Common HTTP-completion error shaping: actionable, internals-free (GUARDRAILS §1.3). */\nfunction httpError(label: string, status: number, hint: string): Error {\n return new Error(`${label} returned HTTP ${status} — ${hint}`);\n}\n\n/** Yield newline-delimited lines from a streamed response body. */\nasync function* streamLines(res: Response): AsyncGenerator<string> {\n const reader = res.body?.getReader();\n if (!reader) return;\n const decoder = new TextDecoder();\n let buf = '';\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n let idx: number;\n while ((idx = buf.indexOf('\\n')) >= 0) {\n const line = buf.slice(0, idx).trim();\n buf = buf.slice(idx + 1);\n if (line) yield line;\n }\n }\n if (buf.trim()) yield buf.trim();\n}\n\n/** Accumulate an OpenAI-compatible SSE stream into text + tool calls + usage. */\nexport function accumulateOpenAiDelta(\n acc: { text: string; tools: Map<number, { id?: string; name?: string; args: string }>; usage: { promptTokens?: number; completionTokens?: number } },\n chunk: unknown,\n onToken?: (t: string) => void,\n): void {\n const c = chunk as { choices?: { delta?: { content?: string; tool_calls?: { index?: number; id?: string; function?: { name?: string; arguments?: string } }[] } }[]; usage?: { prompt_tokens?: number; completion_tokens?: number } };\n const delta = c.choices?.[0]?.delta;\n if (delta?.content) {\n acc.text += delta.content;\n onToken?.(delta.content);\n }\n for (const tc of delta?.tool_calls ?? []) {\n const idx = tc.index ?? 0;\n const e = acc.tools.get(idx) ?? { args: '' };\n if (tc.id) e.id = tc.id;\n if (tc.function?.name) e.name = tc.function.name;\n if (tc.function?.arguments) e.args += tc.function.arguments;\n acc.tools.set(idx, e);\n }\n if (c.usage) {\n acc.usage.promptTokens = c.usage.prompt_tokens;\n acc.usage.completionTokens = c.usage.completion_tokens;\n }\n}\n\n/** Turn accumulated OpenAI tool-call fragments into ToolCalls. */\nfunction finalizeTools(tools: Map<number, { id?: string; name?: string; args: string }>): ToolCall[] {\n return [...tools.entries()]\n .sort((a, b) => a[0] - b[0])\n .map(([i, e]) => ({ id: e.id ?? `call_${i}`, name: e.name ?? 'unknown', arguments: coerceArgs(e.args) }));\n}\n\nasync function postJson(url: string, body: unknown, headers: Record<string, string>, timeoutMs: number): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Deterministic mock (tests / offline / --mock)\n\\* ------------------------------------------------------------------ */\n\n/**\n * A provider that returns a fixed, scripted reply — the deterministic floor that\n * lets the entire `vg code` loop run offline. Used by tests, the benchmark, and\n * the `--mock` flag (which reads the scripted edit blocks from a file).\n */\nexport class MockProvider implements Provider {\n readonly id = 'mock';\n readonly label = 'Mock (deterministic)';\n readonly local = true;\n constructor(\n readonly model: string,\n private readonly reply: string,\n ) {}\n async chat(_messages?: ChatMessage[], _opts?: ChatOptions): Promise<ProviderResult> {\n return { text: this.reply, model: this.model, provider: this.id };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Ollama (local, no key)\n\\* ------------------------------------------------------------------ */\n\nexport class OllamaProvider implements Provider {\n readonly id = 'ollama';\n readonly label = 'Ollama (local)';\n readonly local = true;\n constructor(\n readonly model: string,\n private readonly host = process.env.OLLAMA_HOST || 'http://127.0.0.1:11434',\n ) {}\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const streaming = !!(opts.stream && opts.onToken);\n let res: Response;\n try {\n res = await postJson(\n `${this.host.replace(/\\/$/, '')}/api/chat`,\n { model: this.model, messages: openAiMessages(messages), stream: streaming, tools: openAiTools(opts.tools), options: { temperature: opts.temperature ?? 0 } },\n {},\n opts.timeoutMs ?? 120_000,\n );\n } catch {\n throw new Error(`couldn't reach Ollama at ${this.host} — is \\`ollama serve\\` running? (start it, or pass --provider to use a different backend)`);\n }\n if (!res.ok) throw httpError('Ollama', res.status, res.status === 404 ? `model \"${this.model}\" isn't pulled — run \\`ollama pull ${this.model}\\` or pick another with --model` : 'check `ollama serve` and the model name');\n\n if (streaming) {\n let text = '';\n let toolCallsRaw: unknown;\n const usage: { promptTokens?: number; completionTokens?: number } = {};\n for await (const line of streamLines(res)) {\n try {\n const obj = JSON.parse(line) as { message?: { content?: string; tool_calls?: unknown }; prompt_eval_count?: number; eval_count?: number };\n const delta = obj.message?.content;\n if (delta) {\n text += delta;\n opts.onToken?.(delta);\n }\n if (obj.message?.tool_calls) toolCallsRaw = obj.message.tool_calls;\n if (typeof obj.prompt_eval_count === 'number') usage.promptTokens = obj.prompt_eval_count;\n if (typeof obj.eval_count === 'number') usage.completionTokens = obj.eval_count;\n } catch {\n /* skip a malformed line */\n }\n }\n return { text, model: this.model, provider: this.id, toolCalls: parseToolCalls(toolCallsRaw), usage };\n }\n\n const data = (await res.json()) as { message?: { content?: string; tool_calls?: unknown }; prompt_eval_count?: number; eval_count?: number };\n return {\n text: data.message?.content ?? '',\n model: this.model,\n provider: this.id,\n toolCalls: parseToolCalls(data.message?.tool_calls),\n usage: { promptTokens: data.prompt_eval_count, completionTokens: data.eval_count },\n };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * OpenAI-compatible (LM Studio, OpenRouter, LiteLLM, …)\n\\* ------------------------------------------------------------------ */\n\nexport interface OpenAiCompatibleConfig {\n /** Base URL, e.g. `https://openrouter.ai/api/v1` or `http://127.0.0.1:1234/v1`. */\n baseUrl: string;\n /** Env var name holding the API key (never the key itself). Absent for local. */\n apiKeyEnv?: string;\n /** Whether this endpoint is on-device (LM Studio) vs hosted. */\n local: boolean;\n /** Display label. */\n label: string;\n id: string;\n}\n\nexport class OpenAiCompatibleProvider implements Provider {\n readonly id: string;\n readonly label: string;\n readonly local: boolean;\n constructor(\n readonly model: string,\n private readonly config: OpenAiCompatibleConfig,\n ) {\n this.id = config.id;\n this.label = config.label;\n this.local = config.local;\n }\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const headers: Record<string, string> = {};\n if (this.config.apiKeyEnv) {\n const key = process.env[this.config.apiKeyEnv];\n if (!key) {\n throw new Error(`${this.label} needs an API key in ${this.config.apiKeyEnv} — set it in your environment (never pass keys as flags), or use --local for an on-device backend.`);\n }\n headers.authorization = `Bearer ${key}`;\n }\n const streaming = !!(opts.stream && opts.onToken);\n const url = `${this.config.baseUrl.replace(/\\/$/, '')}/chat/completions`;\n const body = {\n model: this.model,\n messages: openAiMessages(messages),\n tools: openAiTools(opts.tools),\n temperature: opts.temperature ?? 0,\n max_tokens: opts.maxTokens,\n stream: streaming,\n ...(streaming ? { stream_options: { include_usage: true } } : {}),\n };\n let res: Response;\n try {\n res = await postJson(url, body, headers, opts.timeoutMs ?? 120_000);\n } catch {\n throw new Error(`couldn't reach ${this.label} at ${this.config.baseUrl} — check the endpoint is up (or use --local).`);\n }\n if (!res.ok) {\n const hint = res.status === 401 || res.status === 403 ? `the key in ${this.config.apiKeyEnv ?? '(none)'} was rejected — check it has access to \"${this.model}\"` : `check the model id \"${this.model}\" and the endpoint`;\n throw httpError(this.label, res.status, hint);\n }\n\n if (streaming) {\n const acc = { text: '', tools: new Map<number, { id?: string; name?: string; args: string }>(), usage: {} as { promptTokens?: number; completionTokens?: number } };\n for await (const line of streamLines(res)) {\n if (!line.startsWith('data:')) continue;\n const payload = line.slice(5).trim();\n if (payload === '[DONE]') break;\n try {\n accumulateOpenAiDelta(acc, JSON.parse(payload), opts.onToken);\n } catch {\n /* skip a malformed chunk */\n }\n }\n const tools = finalizeTools(acc.tools);\n return { text: acc.text, model: this.model, provider: this.id, toolCalls: tools.length ? tools : undefined, usage: acc.usage };\n }\n const data = (await res.json()) as { choices?: { message?: { content?: string; tool_calls?: unknown } }[]; usage?: { prompt_tokens?: number; completion_tokens?: number } };\n const message = data.choices?.[0]?.message;\n return {\n text: message?.content ?? '',\n model: this.model,\n provider: this.id,\n toolCalls: parseToolCalls(message?.tool_calls),\n usage: { promptTokens: data.usage?.prompt_tokens, completionTokens: data.usage?.completion_tokens },\n };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Scripted provider (agent-loop tests / offline demos)\n\\* ------------------------------------------------------------------ */\n\n/**\n * Returns a queued sequence of {@link ProviderResult}s — one per turn — so the\n * agentic loop can be driven deterministically offline: script the tool calls\n * the \"model\" makes (read → search → edit → run → finish) and assert what the\n * agent did. Ignores the incoming messages by design.\n */\nexport class ScriptedProvider implements Provider {\n readonly id = 'scripted';\n readonly label = 'Scripted (deterministic)';\n readonly local = true;\n private turn = 0;\n constructor(\n readonly model: string,\n private readonly steps: Array<{ text?: string; toolCalls?: ToolCall[] }>,\n ) {}\n // Match Provider.chat so tests can wrap/spy with the full signature.\n async chat(_messages?: ChatMessage[], _opts?: ChatOptions): Promise<ProviderResult> {\n const step = this.steps[Math.min(this.turn, this.steps.length - 1)];\n this.turn++;\n return { text: step.text ?? '', model: this.model, provider: this.id, toolCalls: step.toolCalls };\n }\n}\n\n/** The catalogue of known OpenAI-compatible endpoints, keyed by short id. */\nexport const OPENAI_COMPATIBLE: Record<string, Omit<OpenAiCompatibleConfig, 'label' | 'id'> & { label: string }> = {\n /**\n * Vibgrate Relay — the first-party hosted router. OpenAI-compatible, so it\n * needs no bespoke client. Reached with a Vibgrate token rather than a\n * provider key; the base URL is overridable for staging and self-hosting.\n */\n 'vibgrate-relay': {\n baseUrl: process.env.VIBGRATE_RELAY_URL || 'https://api.vibgrate.com/relay/v1',\n apiKeyEnv: 'VIBGRATE_RELAY_TOKEN',\n local: false,\n label: 'Vibgrate Relay',\n },\n openrouter: { baseUrl: 'https://openrouter.ai/api/v1', apiKeyEnv: 'OPENROUTER_API_KEY', local: false, label: 'OpenRouter' },\n litellm: { baseUrl: process.env.LITELLM_BASE_URL || 'http://127.0.0.1:4000', apiKeyEnv: 'LITELLM_API_KEY', local: false, label: 'LiteLLM' },\n openai: { baseUrl: 'https://api.openai.com/v1', apiKeyEnv: 'OPENAI_API_KEY', local: false, label: 'OpenAI' },\n together: { baseUrl: 'https://api.together.xyz/v1', apiKeyEnv: 'TOGETHER_API_KEY', local: false, label: 'Together' },\n lmstudio: { baseUrl: process.env.LMSTUDIO_BASE_URL || 'http://127.0.0.1:1234/v1', local: true, label: 'LM Studio (local)' },\n /**\n * Microsoft Foundry Local — OpenAI-compatible local endpoint (Windows NPU/GPU).\n * Default port matches current Foundry Local docs; override with FOUNDRY_LOCAL_BASE_URL.\n */\n 'foundry-local': {\n baseUrl: process.env.FOUNDRY_LOCAL_BASE_URL || 'http://127.0.0.1:5272/v1',\n local: true,\n label: 'Foundry Local',\n },\n};\n\n/* ------------------------------------------------------------------ *\\\n * Local llama.cpp (installs a package on first use, with consent)\n\\* ------------------------------------------------------------------ */\n\n/**\n * A fully-local inference backend backed by the dual-mode llm-host (ADR-005)\n * and `node-llama-cpp`. Install runtime deps via `vg models install` (or pass\n * consent so ensurePackage can run once). Model *weights* are never fetched\n * automatically: `modelPath` must point at a gguf the user already has.\n */\nexport class LocalLlamaProvider implements Provider {\n readonly id = 'llama-cpp';\n /** Surfaced as the Vibgrate model manager (embedded llama.cpp). */\n readonly label = 'Vibgrate (local)';\n readonly local = true;\n /** Process-wide warm binding + path (best-in-breed: no reload per turn). */\n private static warmBinding: unknown | null = null;\n private static warmHost: import('../runtime/llm-host/embedded.js').EmbeddedLlmHost | null = null;\n private static warmPath: string | null = null;\n\n constructor(\n readonly model: string,\n private readonly modelPath: string,\n private readonly ensure: typeof ensurePackage = ensurePackage,\n private readonly consent = false,\n /** Override isolation (default: env / embedded). */\n private readonly isolation: 'embedded' | 'process' = 'embedded',\n private readonly processEndpoint?: string,\n ) {}\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const {\n createLlmHost,\n EmbeddedLlmHost,\n resolveInferenceIsolation,\n acquireHostSession,\n generateOnSession,\n evictIdleSessions,\n } = await import('../runtime/llm-host/index.js');\n const isolation = resolveInferenceIsolation(this.isolation);\n try {\n const chatMessages = messages.map((m) => ({\n role: (m.role === 'tool' ? 'user' : m.role) as 'system' | 'user' | 'assistant',\n content: m.content,\n }));\n const genOpts = {\n temperature: opts.temperature ?? 0,\n maxTokens: opts.maxTokens,\n grammar: opts.grammar,\n requireGrammar: opts.requireGrammar,\n identifierTrie: opts.identifierTrie,\n annotateUnknownIdentifiers: !!opts.identifierTrie,\n draftCandidates: opts.draftCandidates,\n promptSegments: opts.promptSegments,\n };\n\n if (isolation === 'process') {\n const host = createLlmHost({ isolation: 'process', endpoint: this.processEndpoint });\n await host.load(this.modelPath);\n const out = await host.generate(chatMessages, genOpts);\n return { text: out.text, model: this.model, provider: this.id };\n }\n\n // Warm path: reuse binding + session across turns.\n if (!LocalLlamaProvider.warmBinding) {\n const res = await this.ensure('node-llama-cpp@^3', { consent: this.consent, onUnavailable: () => {} });\n if (!res.module) {\n throw new Error(ensureUnavailableMessage(res.reason ?? 'no-consent', 'node-llama-cpp', res.detail));\n }\n LocalLlamaProvider.warmBinding = res.module;\n }\n evictIdleSessions(2);\n\n // Prefer direct session API for metrics-rich generate.\n const session = await acquireHostSession(LocalLlamaProvider.warmBinding, this.modelPath);\n const report = await generateOnSession(session, chatMessages, genOpts);\n // Real-ish usage for the panel meter. Never report draftAcceptedChars as\n // tokens — that is a char count of a speculative draft, not model usage\n // (it produced footers like \"56 tokens\" for multi-paragraph answers).\n const promptTokens = report.kvPlan?.totalTokens;\n const completionTokens = report.text ? Math.max(1, Math.ceil(report.text.length / 4)) : undefined;\n return {\n text: report.text,\n model: this.model,\n provider: this.id,\n usage: {\n ...(typeof promptTokens === 'number' && promptTokens > 0 ? { promptTokens } : {}),\n ...(completionTokens != null ? { completionTokens } : {}),\n },\n };\n } catch (e) {\n // Fall back to EmbeddedLlmHost once if session path fails.\n try {\n if (LocalLlamaProvider.warmBinding) {\n if (\n !LocalLlamaProvider.warmHost ||\n LocalLlamaProvider.warmPath !== this.modelPath\n ) {\n const host = createLlmHost({\n isolation: 'embedded',\n binding: LocalLlamaProvider.warmBinding,\n preferGrammar: !!opts.grammar,\n });\n if (host instanceof EmbeddedLlmHost) {\n LocalLlamaProvider.warmHost = host;\n LocalLlamaProvider.warmPath = this.modelPath;\n await host.load(this.modelPath);\n }\n }\n if (LocalLlamaProvider.warmHost) {\n const out = await LocalLlamaProvider.warmHost.generate(\n messages.map((m) => ({\n role: (m.role === 'tool' ? 'user' : m.role) as 'system' | 'user' | 'assistant',\n content: m.content,\n })),\n {\n temperature: opts.temperature ?? 0,\n maxTokens: opts.maxTokens,\n grammar: opts.grammar,\n requireGrammar: opts.requireGrammar,\n identifierTrie: opts.identifierTrie,\n annotateUnknownIdentifiers: !!opts.identifierTrie,\n draftCandidates: opts.draftCandidates,\n promptSegments: opts.promptSegments,\n },\n );\n return { text: out.text, model: this.model, provider: this.id };\n }\n }\n } catch {\n /* rethrow outer */\n }\n throw new Error(`local llama.cpp inference failed for ${this.modelPath} — ${redactSecrets((e as Error).message)}`);\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/engine/module-resolver.ts","../src/engine/ids.ts","../src/engine/tests.ts","../src/engine/resolve.ts"],"names":["resolve","path2","mod","sep"],"mappings":";;;;AAuBA,IAAM,SAAA,GAAY,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAQ,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAQ,SAAA,EAAW,QAAQ,CAAA;AAC5G,IAAM,SAAA,GAAY;AAAA,EAChB,KAAA;AAAA,EAAO,MAAA;AAAA,EAAQ,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,KAAA;AAAA,EAAO,OAAA;AAAA,EAAS,KAAA;AAAA,EAC7C,MAAA;AAAA,EAAQ,KAAA;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A,QAAA,CAAS,KAAA,GAAA,CAAS,QAAA,CAAS,KAAA,IAAS,CAAA,IAAK,CAAA;AAEzC,MAAA,IAAI,UAAA,GAAa,QAAA,CAAS,UAAA,EAAY,QAAA,CAAS,UAAA,GAAa,UAAA;AAC5D,MAAA;AAAA,IACF;AACA,IAAA,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,EAAA,EAAI,EAAE,EAAA,EAAI,IAAA,EAAM,GAAA,EAAK,GAAA,EAAK,UAAA,EAAY,UAAA,EAAY,KAAA,EAAO,CAAA,EAAG,CAAA;AAAA,EAC3E;AAAA,EAEA,OAAA,GAAuB;AACrB,IAAA,OAAO,CAAC,GAAG,IAAA,CAAK,GAAA,CAAI,MAAA,EAAQ,CAAA,CAAE,IAAA;AAAA,MAC5B,CAAC,CAAA,EAAG,CAAA,KACF,EAAE,IAAA,CAAK,aAAA,CAAc,EAAE,IAAI,CAAA,IAAK,EAAE,GAAA,CAAI,aAAA,CAAc,EAAE,GAAG,CAAA,IAAK,EAAE,GAAA,CAAI,aAAA,CAAc,EAAE,GAAG;AAAA,KAC3F;AAAA,EACF;AACF,CAAA","file":"chunk-IPICO2RV.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Module resolution for import edges. Resolves an import specifier (relative,\n * `tsconfig` path alias, or workspace-package name) to a repo-relative file —\n * the fix for alias-heavy TS monorepos (Nx/Turborepo) where every cross-package\n * import looked \"external\" and tanked call resolution.\n *\n * Deterministic: it reads the repo's tsconfig(s) and workspace manifests once at\n * construction, then `resolve()` is pure over those in-memory maps. Still the\n * heuristic rung — precise SCIP/stack-graphs slot above it later — but now\n * scope-aware of the project's own module map.\n */\n\nexport interface ModuleResolver {\n /** Resolve `source` imported from `fromRel`; returns a repo-rel path or null (external). */\n resolve(fromRel: string, source: string): string | null;\n}\n\n// Container SFC formats (.vue/.svelte/.astro) resolve as part of the JS/TS\n// group: their script region is JS/TS, they import ts/js modules, and ts/js\n// files import them back (`import Foo from './Foo.vue'`).\nconst JS_TS_EXT = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.svelte', '.astro'];\nconst OTHER_EXT = [\n '.py', '.pyi', '.go', '.rs', '.rb', '.java', '.cs',\n '.php', '.kt', '.kts', '.swift', '.scala', '.sc', '.dart', '.lua',\n '.ex', '.exs', '.sh', '.bash', '.zig', '.c', '.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx', '.h',\n '.m', '.mm', '.ml', '.mli', '.res', '.sol',\n];\n\n// Which target extensions a dotted import from a given file may resolve to.\n// Keeps Python imports matching Python files, Java matching Java, etc. — a\n// dotted module path must not cross languages.\nconst EXT_GROUPS: Record<string, string[]> = {\n '.py': ['.py', '.pyi'],\n '.pyi': ['.py', '.pyi'],\n '.java': ['.java'],\n '.cs': ['.cs'],\n '.go': ['.go'],\n '.rs': ['.rs'],\n '.rb': ['.rb'],\n};\nfor (const e of JS_TS_EXT) EXT_GROUPS[e] = JS_TS_EXT;\nconst CPP_EXT = ['.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx', '.h'];\nObject.assign(EXT_GROUPS, {\n '.php': ['.php'],\n '.kt': ['.kt', '.kts'],\n '.kts': ['.kt', '.kts'],\n '.swift': ['.swift'],\n '.scala': ['.scala', '.sc'],\n '.sc': ['.scala', '.sc'],\n '.dart': ['.dart'],\n '.lua': ['.lua'],\n '.ex': ['.ex', '.exs'],\n '.exs': ['.ex', '.exs'],\n '.sh': ['.sh', '.bash'],\n '.bash': ['.sh', '.bash'],\n '.zig': ['.zig'],\n '.c': ['.c', '.h'],\n '.cpp': CPP_EXT,\n '.cc': CPP_EXT,\n '.cxx': CPP_EXT,\n '.hpp': CPP_EXT,\n '.hh': CPP_EXT,\n '.hxx': CPP_EXT,\n '.h': [...CPP_EXT, '.c'],\n // ObjC #imports headers; ObjC++ additionally reaches C++ headers.\n '.m': ['.h', '.m', '.mm'],\n '.mm': ['.h', '.m', '.mm', ...CPP_EXT],\n '.ml': ['.ml', '.mli'],\n '.mli': ['.ml', '.mli'],\n '.res': ['.res'],\n '.sol': ['.sol'],\n // Template containers: ERB fragments are Ruby; HTML/EJS script is JS.\n '.erb': ['.rb', '.erb'],\n '.html': JS_TS_EXT,\n '.htm': JS_TS_EXT,\n '.ejs': JS_TS_EXT,\n});\n\nexport function buildModuleResolver(root: string, relSet: Set<string>): ModuleResolver {\n const probe = makeProbe(relSet);\n const suffixIndex = buildSuffixIndex(relSet);\n const tsPaths = loadTsconfigPaths(root); // {baseUrlRel, paths}\n const workspaces = loadWorkspacePackages(root); // name -> dirRel\n\n function resolveAlias(source: string): string | null {\n if (!tsPaths) return null;\n for (const [pattern, targets] of tsPaths.paths) {\n const m = matchPattern(pattern, source);\n if (m === null) continue;\n for (const target of targets) {\n const sub = target.replace('*', m);\n const rel = posixJoin(tsPaths.baseUrlRel, sub);\n const hit = probe(rel);\n if (hit) return hit;\n }\n }\n return null;\n }\n\n function resolveWorkspace(source: string): string | null {\n if (!workspaces.size) return null;\n // longest package-name match (so @org/a/b prefers @org/a/b over @org/a)\n let best: { dirRel: string; rest: string } | null = null;\n for (const [name, dirRel] of workspaces) {\n if (source === name || source.startsWith(`${name}/`)) {\n const rest = source === name ? '' : source.slice(name.length + 1);\n if (!best || name.length > best.dirRel.length) best = { dirRel, rest };\n }\n }\n if (!best) return null;\n const base = best.rest ? posixJoin(best.dirRel, best.rest) : best.dirRel;\n return probe(base) ?? probe(posixJoin(base, 'src/index')) ?? probe(posixJoin(base, 'index'));\n }\n\n return {\n resolve(fromRel, source) {\n // PHP namespaces (`App\\\\Models\\\\User`) — treat as a dotted module path so\n // the PSR-4-style suffix machinery can match `src/Models/User.php`.\n if (source.includes('\\\\')) source = source.split('\\\\').join('.');\n // JS/TS relative (`./x`, `../x`) — join against the importer's directory.\n if (source.startsWith('./') || source.startsWith('../')) {\n return probe(posixJoin(path.posix.dirname(fromRel), source));\n }\n // Bare relative FILE references: `require 'helpers.php'` (PHP),\n // `import 'util.dart'`, `@import(\"util.zig\")`, `#include \"util.h\"` — an\n // extension-bearing name resolves against the importer's directory first.\n if (/\\.[A-Za-z0-9]+$/.test(source) && !source.startsWith('<')) {\n const hit = probe(posixJoin(path.posix.dirname(fromRel), source));\n if (hit) return hit;\n }\n // Python-style relative (`.models`, `..core.utils`, `.`) — leading dots are\n // package levels, not a filename. One dot = the file's package (its dir),\n // each extra dot goes up one package.\n if (source.startsWith('.')) {\n return resolvePyRelative(probe, fromRel, source);\n }\n return (\n resolveAlias(source) ??\n resolveWorkspace(source) ??\n resolveSuffix(suffixIndex, fromRel, source) ??\n resolveDotted(probe, source)\n );\n },\n };\n}\n\n// --- suffix-based module resolution (Python/Java packages, src-layout) ---\n\ninterface SuffixEntry {\n rel: string;\n key: string; // path without extension (or directory, for __init__/index)\n ext: string;\n}\n\n/**\n * Index every file by the LAST segment of its module key, so a dotted import can\n * be matched against the *tail* of a repo path. This is what makes real Python\n * and Java layouts resolve: `from src.feature_pipeline.services.x import Y` in a\n * monorepo where the file actually lives at\n * `feature-pipeline/src/feature_pipeline/services/x.py` (per-subproject `src/`\n * roots, PYTHONPATH-style), or `import com.example.Foo` →\n * `.../src/main/java/com/example/Foo.java`. A repo-root/`src/` prefix probe\n * (the old behaviour) resolved none of these, so cross-file edges were ~0.\n */\nfunction buildSuffixIndex(relSet: Set<string>): Map<string, SuffixEntry[]> {\n const byLast = new Map<string, SuffixEntry[]>();\n for (const rel of relSet) {\n const dot = rel.lastIndexOf('.');\n if (dot < 0) continue;\n const ext = rel.slice(dot);\n if (!EXT_GROUPS[ext]) continue;\n let key = rel.slice(0, dot);\n const base = key.slice(key.lastIndexOf('/') + 1);\n if (base === '__init__' || base === 'index') {\n key = key.slice(0, Math.max(0, key.length - base.length - 1)); // → directory key\n }\n if (!key) continue;\n const last = key.slice(key.lastIndexOf('/') + 1);\n const list = byLast.get(last);\n if (list) list.push({ rel, key, ext });\n else byLast.set(last, [{ rel, key, ext }]);\n }\n return byLast;\n}\n\n/**\n * Resolve a dotted module path (Python/Java) by matching it against the tail of\n * a repo file's path, restricted to the importer's language group. On multiple\n * matches, pick the file sharing the longest path prefix with the importer\n * (same subproject), then the shortest path, then lexicographically — fully\n * deterministic.\n */\nfunction resolveSuffix(\n index: Map<string, SuffixEntry[]>,\n fromRel: string,\n source: string,\n): string | null {\n if (!/^[A-Za-z_][\\w.]*$/.test(source) || !source.includes('.')) return null;\n const fromDot = fromRel.lastIndexOf('.');\n const fromExt = fromDot >= 0 ? fromRel.slice(fromDot) : '';\n const allowed = EXT_GROUPS[fromExt];\n if (!allowed) return null; // unknown importer language — don't risk a cross-language match\n const q = source.replace(/\\./g, '/');\n const last = q.slice(q.lastIndexOf('/') + 1);\n const cands = index.get(last);\n if (!cands) return null;\n const matches = cands.filter(\n (c) => allowed.includes(c.ext) && (c.key === q || c.key.endsWith('/' + q)),\n );\n if (matches.length === 0) return null;\n if (matches.length === 1) return matches[0].rel;\n return pickClosest(matches, fromRel).rel;\n}\n\nfunction pickClosest(matches: SuffixEntry[], fromRel: string): SuffixEntry {\n const fromSegs = fromRel.split('/');\n const score = (rel: string): number => {\n const segs = rel.split('/');\n let i = 0;\n while (i < segs.length && i < fromSegs.length && segs[i] === fromSegs[i]) i++;\n return i;\n };\n return [...matches].sort((a, b) => {\n const d = score(b.rel) - score(a.rel);\n if (d) return d;\n if (a.rel.length !== b.rel.length) return a.rel.length - b.rel.length;\n return a.rel < b.rel ? -1 : 1;\n })[0];\n}\n\n/**\n * Dotted-module resolution (Python/Java style): `app.core.security` →\n * `app/core/security(.py|/__init__.py)`. Tries a repo-root and `src/` layout.\n * Safe across languages — it only returns a hit when a real repo file matches,\n * so JS packages that contain a dot (e.g. `socket.io`) fall through to external.\n */\nfunction resolveDotted(probe: (base: string) => string | null, source: string): string | null {\n if (!/^[A-Za-z_][\\w.]*$/.test(source) || !source.includes('.')) return null;\n const slashed = source.replace(/\\./g, '/');\n return probe(slashed) ?? probe(posixJoin('src', slashed));\n}\n\n/**\n * Resolve a Python-style relative import. `source` is leading dots plus an\n * optional dotted module (`.models`, `..core.utils`, or just `.`). The number of\n * dots is the package level: one dot = the importer's own package (directory),\n * each additional dot ascends one package. A bare `from . import x` resolves to\n * the package itself (its `__init__.py`); the dotted-module form targets the\n * submodule file.\n */\nfunction resolvePyRelative(\n probe: (base: string) => string | null,\n fromRel: string,\n source: string,\n): string | null {\n let dots = 0;\n while (source[dots] === '.') dots++;\n const rest = source.slice(dots); // dotted submodule path, possibly empty\n let dir = path.posix.dirname(fromRel);\n for (let i = 1; i < dots; i++) dir = path.posix.dirname(dir);\n const sub = rest.replace(/\\./g, '/');\n return probe(sub ? posixJoin(dir, sub) : dir);\n}\n\n/** A resolver that only handles relative imports (no fs) — for tests/embedding. */\nexport function relativeResolver(relSet: Set<string>): ModuleResolver {\n const probe = makeProbe(relSet);\n return {\n resolve(fromRel, source) {\n if (source.startsWith('.')) return probe(posixJoin(path.posix.dirname(fromRel), source));\n return resolveDotted(probe, source);\n },\n };\n}\n\n// --- probing ---\n\nfunction makeProbe(relSet: Set<string>): (base: string) => string | null {\n return (base: string) => {\n const norm = normalizeRel(base);\n if (!norm) return null;\n if (relSet.has(norm)) return norm;\n for (const ext of JS_TS_EXT) if (relSet.has(norm + ext)) return norm + ext;\n for (const ext of JS_TS_EXT) if (relSet.has(`${norm}/index${ext}`)) return `${norm}/index${ext}`;\n for (const ext of OTHER_EXT) if (relSet.has(norm + ext)) return norm + ext;\n if (relSet.has(`${norm}/__init__.py`)) return `${norm}/__init__.py`;\n return null;\n };\n}\n\nfunction normalizeRel(p: string): string {\n const norm = path.posix.normalize(p);\n const stripped = norm.startsWith('./') ? norm.slice(2) : norm;\n return stripped.startsWith('..') ? '' : stripped;\n}\n\nfunction posixJoin(a: string, b: string): string {\n return path.posix.normalize(path.posix.join(a, b));\n}\n\n/** Match a tsconfig paths pattern (`@app/*`) against a specifier; returns the `*` capture or '' on exact, null on no match. */\nfunction matchPattern(pattern: string, source: string): string | null {\n const star = pattern.indexOf('*');\n if (star === -1) return source === pattern ? '' : null;\n const prefix = pattern.slice(0, star);\n const suffix = pattern.slice(star + 1);\n if (!source.startsWith(prefix) || !source.endsWith(suffix)) return null;\n if (source.length < prefix.length + suffix.length) return null;\n return source.slice(prefix.length, source.length - suffix.length);\n}\n\n// --- tsconfig ---\n\ninterface TsPaths {\n baseUrlRel: string; // relative to root\n paths: [string, string[]][];\n}\n\nfunction loadTsconfigPaths(root: string): TsPaths | null {\n // Prefer tsconfig.base.json (Nx) then tsconfig.json; follow `extends`.\n for (const name of ['tsconfig.base.json', 'tsconfig.json']) {\n const file = path.join(root, name);\n if (fs.existsSync(file)) {\n const merged = readTsconfigChain(root, file, new Set());\n if (merged && merged.paths.length) return merged;\n }\n }\n return null;\n}\n\nfunction readTsconfigChain(root: string, file: string, seen: Set<string>): TsPaths | null {\n if (seen.has(file) || seen.size > 6) return null;\n seen.add(file);\n let cfg: { extends?: string; compilerOptions?: { baseUrl?: string; paths?: Record<string, string[]> } };\n try {\n cfg = parseJsonc(fs.readFileSync(file, 'utf8'));\n } catch {\n return null;\n }\n const dir = path.dirname(file);\n let base: TsPaths = { baseUrlRel: '', paths: [] };\n if (cfg.extends && cfg.extends.startsWith('.')) {\n const extPath = path.resolve(dir, cfg.extends.endsWith('.json') ? cfg.extends : `${cfg.extends}.json`);\n if (fs.existsSync(extPath)) {\n const inherited = readTsconfigChain(root, extPath, seen);\n if (inherited) base = inherited;\n }\n }\n const co = cfg.compilerOptions ?? {};\n // baseUrl is relative to THIS config's dir; express it relative to the repo root.\n const baseUrlRel =\n co.baseUrl !== undefined\n ? path.relative(root, path.resolve(dir, co.baseUrl)).split(path.sep).join('/')\n : base.baseUrlRel;\n const paths: [string, string[]][] = [...base.paths];\n if (co.paths) for (const [k, v] of Object.entries(co.paths)) paths.push([k, v]);\n return { baseUrlRel, paths };\n}\n\n// --- workspaces ---\n\nfunction loadWorkspacePackages(root: string): Map<string, string> {\n const map = new Map<string, string>();\n const globs: string[] = [];\n\n const rootPkg = path.join(root, 'package.json');\n if (fs.existsSync(rootPkg)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(rootPkg, 'utf8')) as { workspaces?: string[] | { packages?: string[] } };\n const ws = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages;\n if (ws) globs.push(...ws);\n } catch {\n /* ignore */\n }\n }\n const pnpmWs = path.join(root, 'pnpm-workspace.yaml');\n if (fs.existsSync(pnpmWs)) {\n for (const line of fs.readFileSync(pnpmWs, 'utf8').split('\\n')) {\n const m = /^\\s*-\\s*['\"]?([^'\"\\n]+)['\"]?\\s*$/.exec(line);\n if (m) globs.push(m[1].trim());\n }\n }\n\n for (const dir of expandWorkspaceGlobs(root, globs)) {\n const pj = path.join(dir, 'package.json');\n try {\n const name = (JSON.parse(fs.readFileSync(pj, 'utf8')) as { name?: string }).name;\n if (name) map.set(name, path.relative(root, dir).split(path.sep).join('/'));\n } catch {\n /* ignore */\n }\n }\n return map;\n}\n\n/** Resolve simple workspace globs (`packages/*`, `apps/*`, `libs/**`) to dirs containing package.json. */\nfunction expandWorkspaceGlobs(root: string, globs: string[]): string[] {\n const out = new Set<string>();\n for (const glob of globs) {\n const clean = glob.replace(/\\/\\*\\*$/, '').replace(/\\/\\*$/, '');\n const baseDir = path.join(root, clean);\n const recurse = glob.endsWith('**');\n if (glob === clean) {\n // No wildcard — a direct package dir.\n if (fs.existsSync(path.join(baseDir, 'package.json'))) out.add(baseDir);\n continue;\n }\n collectPackageDirs(baseDir, recurse ? 4 : 1, out);\n }\n return [...out];\n}\n\nfunction collectPackageDirs(dir: string, depth: number, out: Set<string>): void {\n if (depth < 0) return;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n if (!e.isDirectory() || e.name === 'node_modules' || e.name.startsWith('.')) continue;\n const child = path.join(dir, e.name);\n if (fs.existsSync(path.join(child, 'package.json'))) out.add(child);\n else collectPackageDirs(child, depth - 1, out);\n }\n}\n\n// --- tolerant JSONC ---\n\nexport function parseJsonc<T = unknown>(text: string): T {\n return JSON.parse(stripJsonc(text)) as T;\n}\n\nfunction stripJsonc(text: string): string {\n let out = '';\n let inStr = false;\n let strCh = '';\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n const next = text[i + 1];\n if (inStr) {\n out += ch;\n if (ch === '\\\\') {\n out += next ?? '';\n i++;\n } else if (ch === strCh) {\n inStr = false;\n }\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inStr = true;\n strCh = ch;\n out += ch;\n continue;\n }\n if (ch === '/' && next === '/') {\n while (i < text.length && text[i] !== '\\n') i++;\n out += '\\n';\n continue;\n }\n if (ch === '/' && next === '*') {\n i += 2;\n while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++;\n i++;\n continue;\n }\n out += ch;\n }\n // drop trailing commas before } or ]\n return out.replace(/,(\\s*[}\\]])/g, '$1');\n}\n","import { canonicalize, shortId } from './hash.js';\nimport type { EdgeKind, NodeKind } from '../schema.js';\n\n/**\n * Content-addressed ids. The id of a node is a function only of its *identity*\n * (kind, qualified name, file, signature) — never its line span, which can move\n * without changing the node. So adding a blank line above a function leaves its\n * id (and every edge touching it) byte-identical.\n */\n\nexport interface NodeIdParts {\n kind: NodeKind;\n qualifiedName: string;\n file: string;\n signature?: string;\n}\n\nexport function nodeId(parts: NodeIdParts): string {\n return shortId(\n canonicalize({\n t: 'node',\n kind: parts.kind,\n qn: parts.qualifiedName,\n file: parts.file,\n sig: parts.signature ?? '',\n }),\n );\n}\n\nexport function edgeId(kind: EdgeKind, src: string, dst: string): string {\n return shortId(canonicalize({ t: 'edge', kind, src, dst }));\n}\n","import { edgeId } from './ids.js';\nimport type { GraphEdge, GraphNode } from '../schema.js';\n\n/**\n * Test-awareness (VG-ENGINE-TEARDOWN §3.6).\n *\n * Deterministic, two signals:\n * 1. **Static linkage** — calls from a test file into product code become `test`\n * edges (test file → covered node), so we can answer \"which tests exercise\n * this\" from structure alone, no runner needed.\n * 2. **Coverage** (coverage.ts) — runtime-grounded line coverage applied as\n * `coverage` on nodes (stronger than static linkage when present).\n *\n * A node's `tested` flag is true when it has any incoming test/coverage signal;\n * false for analyzable code with none; null for non-analyzable kinds.\n */\n\nexport function isTestFile(rel: string): boolean {\n const lower = rel.toLowerCase();\n const base = rel.split('/').pop() ?? rel; // original case (for CamelCase rules)\n const lbase = base.toLowerCase();\n // Directory-based conventions (case-insensitive).\n if (/(^|\\/)(__tests__|__test__)\\//.test(lower)) return true;\n if (/(^|\\/)(tests?|spec|specs)\\//.test(lower)) return true;\n if (/(^|\\/)src\\/test\\//.test(lower)) return true;\n // Filename-based conventions across languages.\n if (/\\.(test|spec)\\.[cm]?[jt]sx?$/.test(lbase)) return true; // JS/TS\n if (/^test_.*\\.py$/.test(lbase) || /_test\\.py$/.test(lbase)) return true; // Python\n if (/_test\\.go$/.test(lbase)) return true; // Go\n if (/[A-Za-z0-9](Test|Tests|IT)\\.java$/.test(base)) return true; // *Test.java (CamelCase)\n if (/_spec\\.rb$/.test(lbase) || /_test\\.rb$/.test(lbase)) return true; // Ruby\n if (/[A-Za-z0-9](Test|Tests)\\.cs$/.test(base)) return true; // *Test.cs (CamelCase)\n if (/[A-Za-z0-9](Test|Tests)\\.swift$/.test(base)) return true; // XCTest *Tests.swift (CamelCase)\n return false;\n}\n\nexport interface TestAwarenessResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n testFiles: string[]; // rel paths\n testEdgeCount: number;\n}\n\n/**\n * Apply static test linkage. Adds `test` edges from each test file node to the\n * product-code nodes its functions call, and sets `tested` on analyzable nodes.\n */\nexport function applyStaticTestLinkage(nodes: GraphNode[], edges: GraphEdge[]): TestAwarenessResult {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const testFiles = new Set<string>();\n for (const n of nodes) if (n.kind === 'file' && isTestFile(n.file)) testFiles.add(n.file);\n\n // File node id per rel (to source test edges from the file).\n const fileNodeIdByRel = new Map<string, string>();\n for (const n of nodes) if (n.kind === 'file') fileNodeIdByRel.set(n.file, n.id);\n\n const covered = new Set<string>(); // node ids with a test signal\n const newEdges = new Map<string, GraphEdge>();\n\n for (const e of edges) {\n if (e.kind !== 'call') continue;\n const src = byId.get(e.src);\n const dst = byId.get(e.dst);\n if (!src || !dst) continue;\n // A call originating in a test file into non-test product code → test edge.\n if (testFiles.has(src.file) && !testFiles.has(dst.file) && dst.kind !== 'external') {\n const testFileId = fileNodeIdByRel.get(src.file);\n if (!testFileId) continue;\n const id = edgeId('test', testFileId, dst.id);\n if (!newEdges.has(id)) {\n newEdges.set(id, {\n id,\n kind: 'test',\n src: testFileId,\n dst: dst.id,\n resolution: e.resolution,\n confidence: e.confidence,\n });\n }\n covered.add(dst.id);\n }\n }\n\n const outNodes = nodes.map((n) => ({ ...n, tested: testedFlag(n, covered.has(n.id), testFiles) }));\n const outEdges = [...edges, ...newEdges.values()].sort(\n (a, b) => a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n\n return {\n nodes: outNodes,\n edges: outEdges,\n testFiles: [...testFiles].sort(),\n testEdgeCount: newEdges.size,\n };\n}\n\n/** Analyzable code units get true/false; everything else stays null. */\nfunction testedFlag(node: GraphNode, covered: boolean, testFiles: Set<string>): boolean | null {\n if (node.kind === 'external' || node.kind === 'file' || node.kind === 'package' || node.kind === 'module') {\n return null;\n }\n if (testFiles.has(node.file)) return null; // the test code itself isn't \"tested\"\n if (node.kind === 'function' || node.kind === 'method') return covered;\n // Classes/interfaces/etc.: covered if any signal, else leave null (not a unit).\n return covered ? true : node.tested ?? null;\n}\n","import * as path from 'node:path';\nimport { nodeId, edgeId } from './ids.js';\nimport { relativeResolver, type ModuleResolver } from './module-resolver.js';\nimport { isTestFile } from './tests.js';\nimport type { FileParse } from './types.js';\nimport type { EdgeKind, GraphEdge, GraphNode, NodeKind, ResolverKind } from '../schema.js';\n\n/**\n * Resolution: turn per-file symbol/edge tables into a connected graph of nodes\n * and typed, id'd edges.\n *\n * The Phase-0 resolver is the deterministic **heuristic** rung of the ladder\n * (VG-ENGINE-TEARDOWN §3.2). It is already well beyond a\n * single-candidate label match: it is scope-aware (same-file first), import-aware\n * (callees reachable through imported files next), and arity/visibility-honest\n * (records its confidence and resolution rung per edge rather than silently\n * dropping ambiguity). SCIP/stack-graphs rungs slot in above it later, recorded\n * via `edge.resolution`.\n */\n\n/**\n * A reference the heuristic resolver could not connect to a definition — the raw\n * material for `vg unknowns`. `from` is the node id of the enclosing definition\n * (or file) where the reference occurs; `name` is the callee/type it names. We\n * keep the source-relative path so a later precise rung that covers this file can\n * suppress the unknown (the compiler is authoritative there).\n */\nexport interface UnresolvedRef {\n from: string;\n name: string;\n kind: 'call' | 'extends' | 'implements';\n count: number;\n fromRel: string;\n}\n\nexport interface ResolveResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n /** References the heuristic rung could not resolve (deduped, sorted). */\n unresolved: UnresolvedRef[];\n /** Diagnostic counts, surfaced by `vg status`. */\n stats: {\n callsResolved: number;\n callsUnresolved: number;\n importsResolvedToFile: number;\n importsExternal: number;\n resolvers: ResolverKind[];\n };\n}\n\ninterface DefNodeRef {\n id: string;\n name: string;\n qualifiedName: string;\n rel: string;\n lang: string;\n kind: NodeKind;\n startByte: number; // for enclosing-scope lookup (not persisted)\n endByte: number;\n}\n\n// A partial node we fill analysis fields onto later (centrality/area/etc.).\ntype BaseNode = Omit<\n GraphNode,\n 'importance' | 'centrality' | 'area' | 'isHub' | 'tested' | 'coverage' | 'changeCoupling'\n>;\n\nexport function resolve(parses: FileParse[], resolver?: ModuleResolver): ResolveResult {\n const baseNodes = new Map<string, BaseNode>();\n const relSet = new Set(parses.map((p) => p.rel));\n // Default to relative-only resolution; build.ts passes a full resolver that\n // also follows tsconfig path aliases and workspace-package names.\n const mod = resolver ?? relativeResolver(relSet);\n\n // Index of definitions for resolution.\n const defsByName = new Map<string, DefNodeRef[]>(); // short name → defs\n const defsByFile = new Map<string, DefNodeRef[]>(); // rel → defs\n const fileNodeIdByRel = new Map<string, string>();\n\n // --- 1. file + definition nodes ---\n for (const p of parses) {\n const fileId = nodeId({ kind: 'file', qualifiedName: p.rel, file: p.rel });\n fileNodeIdByRel.set(p.rel, fileId);\n addNode(baseNodes, {\n id: fileId,\n kind: 'file',\n name: path.posix.basename(p.rel),\n qualifiedName: p.rel,\n file: p.rel,\n span: { start: 1, end: 1 },\n lang: p.lang,\n });\n\n for (const d of p.defs) {\n const id = nodeId({\n kind: d.kind,\n qualifiedName: d.qualifiedName,\n file: p.rel,\n signature: d.signature,\n });\n addNode(baseNodes, {\n id,\n kind: d.kind,\n name: d.name,\n qualifiedName: d.qualifiedName,\n file: p.rel,\n span: { start: d.startLine, end: d.endLine },\n lang: p.lang,\n signature: d.signature,\n doc: d.doc,\n });\n const ref: DefNodeRef = {\n id,\n name: d.name,\n qualifiedName: d.qualifiedName,\n rel: p.rel,\n lang: p.lang,\n kind: d.kind,\n startByte: d.startByte,\n endByte: d.endByte,\n };\n push(defsByName, d.name, ref);\n push(defsByFile, p.rel, ref);\n }\n }\n\n // --- namespace reachability (C#-style: a namespace is decoupled from the\n // directory, so cross-directory refs resolve through `using`, not co-location).\n // filesByNamespace: which files declare types in a namespace. nsReachableByRel:\n // for each file, the files reachable through a namespace it declares (same\n // namespace, split across files/dirs) or `using`-imports.\n const filesByNamespace = new Map<string, Set<string>>();\n for (const p of parses) for (const ns of p.namespaces ?? []) addToSet(filesByNamespace, ns, p.rel);\n const relsByLang = new Map<string, string[]>();\n for (const p of parses) push(relsByLang, p.lang, p.rel);\n // EXPLICIT namespace reachability (a shared namespace, or a `using`/`import`\n // of the target's namespace). Strong enough to justify a unique-name match —\n // the developer named the scope.\n const nsReachableByRel = new Map<string, Set<string>>();\n // IMPLICIT whole-module reachability (Swift: every file in the module sees the\n // others with no import). Too broad to justify a unique-name match — used ONLY\n // to let the heritage-anchored interface/implementation disambiguation see the\n // conforming type. Otherwise a lone same-named symbol anywhere in the repo\n // would wrongly resolve (the precision guard covers exactly this).\n const moduleReachableByRel = new Map<string, Set<string>>();\n for (const p of parses) {\n if (MODULE_SCOPED_LANGS.has(p.lang)) {\n const mod = new Set<string>();\n for (const rel of relsByLang.get(p.lang) ?? []) if (rel !== p.rel) mod.add(rel);\n moduleReachableByRel.set(p.rel, mod);\n }\n const reach = new Set<string>();\n const namespaces = new Set<string>(p.namespaces ?? []);\n for (const imp of p.imports) {\n namespaces.add(imp.source); // C# `using X.Y` names the namespace directly\n // Java/Kotlin/Scala `import a.b.Foo` names a CLASS, so the package (its\n // dotted parent) is what becomes reachable. Only matched candidates that\n // are ACTUALLY declared namespaces survive, so this never invents scope.\n if (IMPORT_NAMES_A_TYPE.has(p.lang)) {\n const sep = Math.max(imp.source.lastIndexOf('.'), imp.source.lastIndexOf('\\\\'));\n if (sep > 0) namespaces.add(imp.source.slice(0, sep));\n }\n }\n for (const ns of namespaces) for (const rel of filesByNamespace.get(ns) ?? []) if (rel !== p.rel) reach.add(rel);\n nsReachableByRel.set(p.rel, reach);\n }\n\n // --- interface/implementation index: type name → the super types it declares\n // (`class Foo : IFoo` → Foo⇒{IFoo}). Anchors DI call disambiguation on a real\n // heritage declaration, so `_svc.M()` (ambiguous between an interface method\n // and its implementation) resolves to the concrete implementation instead of\n // being dropped — the exact reason DI-wired services looked like orphans.\n const superTypesByType = new Map<string, Set<string>>();\n for (const p of parses) {\n const localDefs = defsByFile.get(p.rel) ?? [];\n for (const h of p.heritage) {\n const encl = enclosingDefRef(localDefs, h.byte);\n if (encl && (encl.kind === 'class' || encl.kind === 'interface')) addToSet(superTypesByType, encl.name, h.superName);\n }\n }\n\n const edges = new EdgeSet();\n const unresolved = new Map<string, UnresolvedRef>();\n const stats: ResolveResult['stats'] = {\n callsResolved: 0,\n callsUnresolved: 0,\n importsResolvedToFile: 0,\n importsExternal: 0,\n resolvers: ['heuristic'],\n };\n\n // --- 2. contains edges (file → top-level def, def → nested def) ---\n for (const p of parses) {\n const fileId = fileNodeIdByRel.get(p.rel)!;\n const localByQn = new Map<string, string>();\n for (const ref of defsByFile.get(p.rel) ?? []) localByQn.set(ref.qualifiedName, ref.id);\n for (const d of p.defs) {\n const id = localByQn.get(d.qualifiedName)!;\n const parentQn = parentQualifiedName(d.qualifiedName);\n const parentId = parentQn ? localByQn.get(parentQn) : undefined;\n edges.add('contains', parentId ?? fileId, id, 'heuristic', 1.0);\n }\n }\n\n // --- 3. import edges (file → file | external) ---\n const importedFilesByRel = new Map<string, Set<string>>();\n for (const p of parses) {\n const fileId = fileNodeIdByRel.get(p.rel)!;\n const importedRels = new Set<string>();\n for (const imp of p.imports) {\n const targetRel = mod.resolve(p.rel, imp.source);\n if (targetRel && targetRel !== p.rel) {\n importedRels.add(targetRel);\n edges.add('import', fileId, fileNodeIdByRel.get(targetRel)!, 'heuristic', 0.9);\n stats.importsResolvedToFile++;\n } else {\n const extId = ensureExternalNode(baseNodes, imp.source);\n edges.add('import', fileId, extId, 'heuristic', 1.0);\n stats.importsExternal++;\n }\n }\n importedFilesByRel.set(p.rel, importedRels);\n }\n\n // --- 4. call edges (heuristic resolution ladder) ---\n for (const p of parses) {\n const fileId = fileNodeIdByRel.get(p.rel)!;\n const localDefs = defsByFile.get(p.rel) ?? [];\n const imported = importedFilesByRel.get(p.rel) ?? new Set<string>();\n const testCaller = isTestFile(p.rel);\n const nsReach = nsReachableByRel.get(p.rel) ?? new Set<string>();\n const modReach = moduleReachableByRel.get(p.rel) ?? new Set<string>();\n for (const call of p.calls) {\n const srcId = enclosingDefId(localDefs, call.byte) ?? fileId;\n const resolved = resolveCall(call, p.rel, p.lang, imported, defsByName, srcId, testCaller, nsReach, superTypesByType, modReach);\n if (resolved) {\n edges.add('call', srcId, resolved.id, 'heuristic', resolved.confidence);\n stats.callsResolved++;\n } else {\n stats.callsUnresolved++;\n bumpUnresolved(unresolved, srcId, call.callee, 'call', p.rel);\n }\n }\n }\n\n // --- 4b. type-reference edges (constructor/field DI wiring, not a call) ---\n // A constructor parameter or field's declared type is a structural\n // dependency even when it's never invoked directly (Spring-style injection).\n // Most misses here are JDK/stdlib types (String, List, …) with no local\n // definition — expected and not actionable, so unlike calls/heritage these\n // don't get tracked as `unresolved` (it would swamp `vg unknowns`).\n for (const p of parses) {\n const fileId = fileNodeIdByRel.get(p.rel)!;\n const localDefs = defsByFile.get(p.rel) ?? [];\n const imported = importedFilesByRel.get(p.rel) ?? new Set<string>();\n const testCaller = isTestFile(p.rel);\n const nsReach = nsReachableByRel.get(p.rel) ?? new Set<string>();\n const modReach = moduleReachableByRel.get(p.rel) ?? new Set<string>();\n for (const ref of p.typeRefs) {\n const srcId = enclosingDefId(localDefs, ref.byte) ?? fileId;\n const target = resolveType(ref.name, p.rel, p.lang, imported, defsByName, testCaller, nsReach, modReach);\n if (target) edges.add('references', srcId, target.id, 'heuristic', 0.7);\n }\n }\n\n // --- 5. heritage edges (extends / implements) ---\n for (const p of parses) {\n const localDefs = defsByFile.get(p.rel) ?? [];\n const imported = importedFilesByRel.get(p.rel) ?? new Set<string>();\n const testCaller = isTestFile(p.rel);\n for (const h of p.heritage) {\n const srcId = enclosingDefId(localDefs, h.byte);\n if (!srcId) continue;\n const nsReach = nsReachableByRel.get(p.rel) ?? new Set<string>();\n const modReach = moduleReachableByRel.get(p.rel) ?? new Set<string>();\n const target = resolveType(h.superName, p.rel, p.lang, imported, defsByName, testCaller, nsReach, modReach);\n if (target) edges.add(h.kind as EdgeKind, srcId, target.id, 'heuristic', 0.85);\n else bumpUnresolved(unresolved, srcId, h.superName, h.kind as 'extends' | 'implements', p.rel);\n }\n }\n\n // Finalise: assemble GraphNodes (analysis fields filled later by analyze()).\n // `tested` is null in Phase 0 (not yet analyzed); test-awareness lands in\n // Phase 2 and will set true/false for analyzable nodes.\n const nodes: GraphNode[] = [...baseNodes.values()].map((n) => ({\n ...n,\n importance: 0,\n centrality: { degree: 0, pagerank: 0, betweenness: 0, eigenvector: 0 },\n area: 0,\n isHub: false,\n tested: null,\n }));\n\n const unresolvedList = [...unresolved.values()].sort(\n (a, b) =>\n a.from.localeCompare(b.from) || a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name),\n );\n\n return { nodes, edges: edges.toArray(), unresolved: unresolvedList, stats };\n}\n\n// --- helpers ---\n\n/** Accumulate an unresolved reference, deduped by (from, kind, name) with a count. */\nfunction bumpUnresolved(\n map: Map<string, UnresolvedRef>,\n from: string,\n name: string,\n kind: UnresolvedRef['kind'],\n fromRel: string,\n): void {\n const key = `${from}${kind}${name}`;\n const existing = map.get(key);\n if (existing) existing.count++;\n else map.set(key, { from, name, kind, count: 1, fromRel });\n}\n\nfunction addNode(map: Map<string, BaseNode>, n: BaseNode): void {\n if (!map.has(n.id)) map.set(n.id, n);\n}\n\nfunction ensureExternalNode(map: Map<string, BaseNode>, source: string): string {\n const id = nodeId({ kind: 'external', qualifiedName: source, file: '' });\n if (!map.has(id)) {\n map.set(id, {\n id,\n kind: 'external',\n name: source,\n qualifiedName: source,\n file: '',\n span: { start: 1, end: 1 },\n lang: 'external',\n });\n }\n return id;\n}\n\nfunction push<T>(map: Map<string, T[]>, key: string, value: T): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\nfunction parentQualifiedName(qn: string): string | null {\n const idx = qn.lastIndexOf('.');\n return idx > 0 ? qn.slice(0, idx) : null;\n}\n\nfunction enclosingDefRef(defs: DefNodeRef[], byte: number): DefNodeRef | undefined {\n let best: DefNodeRef | undefined;\n for (const d of defs) {\n if (d.startByte <= byte && d.endByte >= byte) {\n if (!best || d.endByte - d.startByte < best.endByte - best.startByte) best = d;\n }\n }\n return best;\n}\n\nfunction enclosingDefId(defs: DefNodeRef[], byte: number): string | undefined {\n return enclosingDefRef(defs, byte)?.id;\n}\n\nfunction addToSet(map: Map<string, Set<string>>, key: string, value: string): void {\n const s = map.get(key);\n if (s) s.add(value);\n else map.set(key, new Set([value]));\n}\n\n/** The declaring type of a method, from its dotted qualified name (`Foo.bar` → `Foo`). */\nfunction parentTypeName(qualifiedName: string): string | null {\n const i = qualifiedName.lastIndexOf('.');\n return i > 0 ? qualifiedName.slice(0, i) : null;\n}\n\n/**\n * Disambiguate an interface/implementation family among same-named candidate\n * methods, anchored on real heritage (`class Impl : IFace`):\n * - exactly one implementation → resolve to it (the concrete runtime target,\n * so impact_of/tests_for/find_path on the service work);\n * - several implementations of one interface → resolve to the interface method\n * (the stable contract) rather than fan out to every impl or pick arbitrarily;\n * - not an interface/impl family → null (stay honestly ambiguous).\n * Returns the chosen def, or null when the pool is not a single such family.\n */\nfunction disambiguateInterfaceImpl(\n pool: DefNodeRef[],\n superTypesByType: Map<string, Set<string>>,\n): DefNodeRef | null {\n const withParent = pool\n .map((c) => ({ c, parent: parentTypeName(c.qualifiedName) }))\n .filter((x): x is { c: DefNodeRef; parent: string } => x.parent !== null);\n if (withParent.length < 2) return null;\n const parents = new Set(withParent.map((x) => x.parent));\n // An impl candidate: its parent type declares (implements/extends) another\n // candidate's parent type.\n const impls = withParent.filter((x) =>\n [...parents].some((other) => other !== x.parent && superTypesByType.get(x.parent)?.has(other)),\n );\n if (impls.length === 0) return null;\n // The interface(s) those impls satisfy (a candidate whose parent is a super of an impl's parent).\n const interfaceParents = new Set<string>();\n for (const impl of impls) for (const s of superTypesByType.get(impl.parent) ?? []) interfaceParents.add(s);\n const interfaces = withParent.filter((x) => interfaceParents.has(x.parent));\n const uniqueImplIds = new Set(impls.map((x) => x.c.id));\n if (uniqueImplIds.size === 1) return impls[0].c;\n const uniqueIfaceIds = new Set(interfaces.map((x) => x.c.id));\n if (uniqueIfaceIds.size === 1) return interfaces[0].c;\n return null;\n}\n\n/**\n * Languages where definitions in the same directory share a visibility scope\n * (package / namespace) and reference each other WITHOUT an import — so a\n * same-directory match is justified resolution, not a guess:\n * - Go: a package IS a directory; all files in it see each other's identifiers.\n * - Java: same-package classes (package == directory by convention).\n * - C#: file-scoped/co-located namespaces commonly align with the directory.\n * - Kotlin/Scala: Java-style package visibility (package == directory by convention).\n * - Swift: module-wide visibility; files in one target see each other un-imported.\n * TS/JS, Python, Ruby, PHP, Dart, Lua, Elixir, Shell, Zig, C and C++ require an\n * explicit import/include for cross-file refs, so they get NO directory rung —\n * a same-name def elsewhere is not reachable.\n */\nconst PACKAGE_SCOPED_LANGS = new Set(['go', 'java', 'cs', 'kotlin', 'scala', 'swift']);\n\n/** Languages whose `import` names a TYPE (not a namespace), so the reachable\n * namespace is the import's parent (`import a.b.Foo` → package `a.b`, PHP\n * `use A\\B\\Foo` → namespace `A\\B`). Separator is `.` except PHP's `\\`. */\nconst IMPORT_NAMES_A_TYPE = new Set(['java', 'kotlin', 'scala', 'php']);\n\n/** Languages with whole-module visibility — every file in the module sees the\n * others' top-level symbols with no import (Swift). Treated as one module. */\nconst MODULE_SCOPED_LANGS = new Set(['swift']);\n\nfunction dirOf(rel: string): string {\n const i = rel.lastIndexOf('/');\n return i >= 0 ? rel.slice(0, i) : '';\n}\n\n/**\n * The heuristic call resolution ladder. A call resolves only when the target is\n * *reachable*: same-file scope, an imported file, or — for package-scoped\n * languages — the same package directory. There is deliberately NO \"single\n * global definition with this name\" fallback: that rung produced the dominant\n * class of false positives (every `fetch()` linking to a lone repo method named\n * `fetch`, every `parse()` to an unrelated `Parser.parse`). Honest\n * non-resolution (null) beats a wrong edge that corrupts centrality, areas and\n * impact; the SCIP/tsc rungs recover the precise edge where a user needs it.\n */\nfunction resolveCall(\n call: { callee: string; qualified?: boolean },\n fromRel: string,\n fromLang: string,\n importedRels: Set<string>,\n defsByName: Map<string, DefNodeRef[]>,\n enclosingId?: string,\n fromIsTestFile = false,\n nsReachableRels: Set<string> = new Set(),\n superTypesByType: Map<string, Set<string>> = new Map(),\n moduleReachableRels: Set<string> = new Set(),\n): { id: string; confidence: number } | null {\n const candidates = defsByName.get(call.callee);\n if (!candidates || candidates.length === 0) return null;\n\n const callable = candidates.filter((c) => c.kind === 'function' || c.kind === 'method');\n const pool = callable.length ? callable : candidates;\n\n // 1. Same-file scope (the strongest signal). A *qualified* call (`crud.foo()`)\n // must not match the enclosing def itself: the parser drops the receiver, so a\n // handler `foo` that delegates to `module.foo(...)` would otherwise resolve to\n // *itself* — on FastAPI/Django-style codebases that false self-loop was the\n // dominant edge (100% of resolved calls in one corpus repo). A bare `foo()`\n // inside `foo` is still honest recursion and is kept.\n let sameFile = pool.filter((c) => c.rel === fromRel);\n if (call.qualified && enclosingId) sameFile = sameFile.filter((c) => c.id !== enclosingId);\n if (sameFile.length === 1) return { id: sameFile[0].id, confidence: 0.85 };\n if (sameFile.length > 1) {\n // Overloads/redefinitions in one file — pick deterministically, low confidence.\n const pick = [...sameFile].sort((a, b) => a.id.localeCompare(b.id))[0];\n return { id: pick.id, confidence: 0.4 };\n }\n\n // 2. Reachable-candidate resolution, in two tiers of trust.\n //\n // STRICT reachability (imported file, same package directory, or an\n // explicitly named namespace) is strong enough to resolve a UNIQUE match —\n // the developer named the scope. Unified into one pool BEFORE deciding, so\n // a DI call reaches the concrete implementation even when only the interface\n // was directly imported (interface via `import`, impl via its package) —\n // the ordering that previously stopped at the interface method.\n const dir = dirOf(fromRel);\n const notSelf = (c: DefNodeRef): boolean => !(call.qualified && enclosingId && c.id === enclosingId);\n const strict = pool.filter(\n (c) =>\n notSelf(c) &&\n (importedRels.has(c.rel) ||\n (PACKAGE_SCOPED_LANGS.has(fromLang) && c.lang === fromLang && dirOf(c.rel) === dir) ||\n nsReachableRels.has(c.rel)),\n );\n if (strict.length === 1) return { id: strict[0].id, confidence: 0.75 };\n\n // The DISAMBIGUATION pool additionally admits whole-module reachability\n // (Swift) — too broad for a unique-name match, but fine for the\n // heritage-anchored interface/implementation family, which requires a real\n // `implements`/`extends` declaration and so cannot fire on an unrelated\n // same-named symbol. Resolve a DI family to the concrete implementation.\n const broad = pool.filter((c) => notSelf(c) && (moduleReachableRels.has(c.rel) || strict.includes(c)));\n if (broad.length > 1) {\n const dedup = disambiguateInterfaceImpl(broad, superTypesByType);\n if (dedup) return { id: dedup.id, confidence: 0.6 };\n }\n // Ambiguous within STRICT scope with no interface/impl resolution → do not\n // guess (the \"lone global match\" false-positive class stays out).\n if (strict.length > 1) return null;\n\n // 4. Swift-only test-file fallback. Xcode test targets commonly live in a\n // sibling `Tests/` tree, not the product code's directory, so rung 3's\n // same-directory check never reaches them even though the whole module is\n // visible unimported — the dominant cause of `tests_for` undercounting a\n // class that a test directly constructs (including via a local helper).\n // Gated on the *caller* being test code (this only adds test-linkage/call\n // visibility, never a product-to-product edge) and an unambiguous\n // repo-wide name match, so it can't reintroduce the \"lone global match\"\n // false-positive class rung 4 elsewhere refuses to guess.\n if (fromLang === 'swift' && fromIsTestFile && pool.length === 1) {\n return { id: pool[0].id, confidence: 0.5 };\n }\n\n // 5. No reachability justification → do not guess (precision over recall).\n return null;\n}\n\n/** Heritage/type-reference resolution — same reachability rule as calls. */\nfunction resolveType(\n name: string,\n fromRel: string,\n fromLang: string,\n importedRels: Set<string>,\n defsByName: Map<string, DefNodeRef[]>,\n fromIsTestFile = false,\n nsReachableRels: Set<string> = new Set(),\n moduleReachableRels: Set<string> = new Set(),\n): { id: string } | null {\n const candidates = (defsByName.get(name) ?? []).filter(\n (c) => c.kind === 'class' || c.kind === 'interface',\n );\n if (candidates.length === 0) return null;\n\n const sameFile = candidates.filter((c) => c.rel === fromRel);\n if (sameFile.length === 1) return { id: sameFile[0].id };\n\n const imported = candidates.filter((c) => importedRels.has(c.rel));\n if (imported.length === 1) return { id: imported[0].id };\n if (imported.length > 1) return null;\n\n if (PACKAGE_SCOPED_LANGS.has(fromLang)) {\n const dir = dirOf(fromRel);\n const samePkg = candidates.filter((c) => c.lang === fromLang && dirOf(c.rel) === dir);\n if (samePkg.length === 1) return { id: samePkg[0].id };\n }\n\n // Namespace / whole-module reachable type: the type's file declares a\n // namespace this file `using`/`import`s or shares (C#/JVM), or is in the same\n // module (Swift). An explicit type annotation naming a unique reachable type\n // is unambiguous — this is not a call, so the lone-name-call precision guard\n // does not apply. A type name matching two reachable types stays unresolved.\n if (nsReachableRels.size || moduleReachableRels.size) {\n const reach = candidates.filter((c) => nsReachableRels.has(c.rel) || moduleReachableRels.has(c.rel));\n if (reach.length === 1) return { id: reach[0].id };\n }\n\n // Swift-only test-file fallback — see the matching rung in resolveCall.\n if (fromLang === 'swift' && fromIsTestFile && candidates.length === 1) {\n return { id: candidates[0].id };\n }\n return null; // no global single-match fallback (false-positive source)\n}\n\n/** Accumulates edges, deduping on (kind, src, dst) and counting multiplicity. */\nclass EdgeSet {\n private map = new Map<string, GraphEdge>();\n\n add(kind: EdgeKind, src: string, dst: string, resolution: ResolverKind, confidence: number): void {\n const id = edgeId(kind, src, dst);\n const existing = this.map.get(id);\n if (existing) {\n existing.count = (existing.count ?? 1) + 1;\n // Keep the highest confidence seen for this logical edge.\n if (confidence > existing.confidence) existing.confidence = confidence;\n return;\n }\n this.map.set(id, { id, kind, src, dst, resolution, confidence, count: 1 });\n }\n\n toArray(): GraphEdge[] {\n return [...this.map.values()].sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n }\n}\n"]}