@vibgrate/cli 2026.819.2 → 2026.824.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-ZJRWCMR6.js → agent-6SJVWFPV.js} +12 -12
  2. package/dist/{agent-ZJRWCMR6.js.map → agent-6SJVWFPV.js.map} +1 -1
  3. package/dist/{approvals-YTUXBZWQ.js → approvals-5UBLBNJF.js} +5 -5
  4. package/dist/{approvals-YTUXBZWQ.js.map → approvals-5UBLBNJF.js.map} +1 -1
  5. package/dist/{attach-WOA25VNH.js → attach-PSGCCJMA.js} +3 -3
  6. package/dist/{attach-WOA25VNH.js.map → attach-PSGCCJMA.js.map} +1 -1
  7. package/dist/baseline-HPXACNFU.js +9 -0
  8. package/dist/{baseline-TVRRUZGA.js.map → baseline-HPXACNFU.js.map} +1 -1
  9. package/dist/{chunk-24HKTTFV.js → chunk-2IY24TTR.js} +3 -3
  10. package/dist/{chunk-24HKTTFV.js.map → chunk-2IY24TTR.js.map} +1 -1
  11. package/dist/{chunk-7BSUPHX6.js → chunk-3PNAQUZM.js} +3 -3
  12. package/dist/{chunk-7BSUPHX6.js.map → chunk-3PNAQUZM.js.map} +1 -1
  13. package/dist/{chunk-W6ASIMG5.js → chunk-4PDWV4AE.js} +10 -12
  14. package/dist/chunk-4PDWV4AE.js.map +1 -0
  15. package/dist/{chunk-2ZBLZ2S3.js → chunk-5QO2GFAE.js} +27 -23
  16. package/dist/chunk-5QO2GFAE.js.map +1 -0
  17. package/dist/{chunk-GBXOAO5V.js → chunk-5UG4UHKU.js} +40 -10
  18. package/dist/chunk-5UG4UHKU.js.map +1 -0
  19. package/dist/chunk-AGOKTI77.js +6 -0
  20. package/dist/{chunk-ZUZHYAJK.js.map → chunk-AGOKTI77.js.map} +1 -1
  21. package/dist/{chunk-C2EZIAA3.js → chunk-B5GOCQFB.js} +9 -9
  22. package/dist/{chunk-C2EZIAA3.js.map → chunk-B5GOCQFB.js.map} +1 -1
  23. package/dist/{chunk-MMJFHEZ4.js → chunk-CJ2R3LVX.js} +4 -4
  24. package/dist/{chunk-MMJFHEZ4.js.map → chunk-CJ2R3LVX.js.map} +1 -1
  25. package/dist/{chunk-2C4QT5D7.js → chunk-III7S75O.js} +53 -463
  26. package/dist/chunk-III7S75O.js.map +1 -0
  27. package/dist/{chunk-IMI2VHHZ.js → chunk-IKB5U3AH.js} +3 -3
  28. package/dist/{chunk-IMI2VHHZ.js.map → chunk-IKB5U3AH.js.map} +1 -1
  29. package/dist/{chunk-AP3JN33O.js → chunk-JL66EPZ4.js} +221 -10
  30. package/dist/chunk-JL66EPZ4.js.map +1 -0
  31. package/dist/{chunk-QE6F62FR.js → chunk-KBLKNR3V.js} +3 -3
  32. package/dist/{chunk-QE6F62FR.js.map → chunk-KBLKNR3V.js.map} +1 -1
  33. package/dist/{chunk-JPOYXG7Z.js → chunk-KRE7SXSA.js} +12 -13
  34. package/dist/chunk-KRE7SXSA.js.map +1 -0
  35. package/dist/{chunk-XW2XQM3C.js → chunk-LA4CETXN.js} +3 -3
  36. package/dist/{chunk-XW2XQM3C.js.map → chunk-LA4CETXN.js.map} +1 -1
  37. package/dist/{chunk-OGFOJG4H.js → chunk-LMHKIQA5.js} +3 -3
  38. package/dist/{chunk-OGFOJG4H.js.map → chunk-LMHKIQA5.js.map} +1 -1
  39. package/dist/{chunk-FCMWHSQ6.js → chunk-M5QSBXA6.js} +17 -4
  40. package/dist/chunk-M5QSBXA6.js.map +1 -0
  41. package/dist/{chunk-R5TQBIR6.js → chunk-QLNJ3VWO.js} +3 -3
  42. package/dist/{chunk-R5TQBIR6.js.map → chunk-QLNJ3VWO.js.map} +1 -1
  43. package/dist/{chunk-XLQ4YHS3.js → chunk-QP3P4V4I.js} +10 -8
  44. package/dist/chunk-QP3P4V4I.js.map +1 -0
  45. package/dist/{chunk-BQ6NTRRK.js → chunk-RAEHWCN6.js} +6 -6
  46. package/dist/{chunk-BQ6NTRRK.js.map → chunk-RAEHWCN6.js.map} +1 -1
  47. package/dist/{chunk-USPMMVNH.js → chunk-SGIFJIII.js} +3 -3
  48. package/dist/{chunk-USPMMVNH.js.map → chunk-SGIFJIII.js.map} +1 -1
  49. package/dist/{chunk-CBL3VY7J.js → chunk-TWWVTKA7.js} +35 -14
  50. package/dist/chunk-TWWVTKA7.js.map +1 -0
  51. package/dist/chunk-USW5WHUG.js +605 -0
  52. package/dist/chunk-USW5WHUG.js.map +1 -0
  53. package/dist/{chunk-NKKOGJ63.js → chunk-UUNEUEPQ.js} +71 -9
  54. package/dist/chunk-UUNEUEPQ.js.map +1 -0
  55. package/dist/{chunk-WPLOEFZU.js → chunk-WATYIYWP.js} +3 -3
  56. package/dist/{chunk-WPLOEFZU.js.map → chunk-WATYIYWP.js.map} +1 -1
  57. package/dist/{chunk-PJRPSYFQ.js → chunk-XHIWQGRE.js} +5 -5
  58. package/dist/{chunk-PJRPSYFQ.js.map → chunk-XHIWQGRE.js.map} +1 -1
  59. package/dist/{chunk-AQZYDFEK.js → chunk-YJ23GGAJ.js} +3 -3
  60. package/dist/{chunk-AQZYDFEK.js.map → chunk-YJ23GGAJ.js.map} +1 -1
  61. package/dist/cli.js +379 -544
  62. package/dist/cli.js.map +1 -1
  63. package/dist/{daemon-YKOEP3XA.js → daemon-AEL5N4SJ.js} +9 -9
  64. package/dist/{daemon-YKOEP3XA.js.map → daemon-AEL5N4SJ.js.map} +1 -1
  65. package/dist/embed-worker-main.js +3 -3
  66. package/dist/{ensure-map-BLRJDO2Y.js → ensure-map-YL5NR6UH.js} +15 -15
  67. package/dist/{ensure-map-BLRJDO2Y.js.map → ensure-map-YL5NR6UH.js.map} +1 -1
  68. package/dist/{graph-backend-NTYONTWW.js → graph-backend-LEPXFPXQ.js} +7 -7
  69. package/dist/{graph-backend-NTYONTWW.js.map → graph-backend-LEPXFPXQ.js.map} +1 -1
  70. package/dist/index.d.ts +72 -130
  71. package/dist/index.js +15 -15
  72. package/dist/{interactive-B3WTC7LB.js → interactive-YJ37ZWTA.js} +27 -26
  73. package/dist/interactive-YJ37ZWTA.js.map +1 -0
  74. package/dist/load-LT6R73IZ.js +11 -0
  75. package/dist/{load-AJROS77R.js.map → load-LT6R73IZ.js.map} +1 -1
  76. package/dist/parse-worker.js +3 -2
  77. package/dist/parse-worker.js.map +1 -1
  78. package/dist/{run-outcome-SBBSTSH3.js → run-outcome-YQBPYNEY.js} +5 -5
  79. package/dist/{run-outcome-SBBSTSH3.js.map → run-outcome-YQBPYNEY.js.map} +1 -1
  80. package/dist/{runtime-session-JYYKQVDX.js → runtime-session-JSH5UL7Z.js} +9 -9
  81. package/dist/{runtime-session-JYYKQVDX.js.map → runtime-session-JSH5UL7Z.js.map} +1 -1
  82. package/dist/{session-2ZMHZ2O6.js → session-3FLVZRMM.js} +8 -8
  83. package/dist/{session-2ZMHZ2O6.js.map → session-3FLVZRMM.js.map} +1 -1
  84. package/dist/{stream-json-ZWGB4C47.js → stream-json-VJ2O52CR.js} +12 -12
  85. package/dist/{stream-json-ZWGB4C47.js.map → stream-json-VJ2O52CR.js.map} +1 -1
  86. package/dist/version-VUTM46C5.js +4 -0
  87. package/dist/{version-5QIEUXU6.js.map → version-VUTM46C5.js.map} +1 -1
  88. package/dist/{vg-mcp-bridge-4FETMJ6M.js → vg-mcp-bridge-UUMEOJSO.js} +9 -9
  89. package/dist/{vg-mcp-bridge-4FETMJ6M.js.map → vg-mcp-bridge-UUMEOJSO.js.map} +1 -1
  90. package/dist/{vgd-R524P5BJ.js → vgd-XFT574U6.js} +8 -8
  91. package/dist/vgd-XFT574U6.js.map +1 -0
  92. package/package.json +2 -1
  93. package/dist/baseline-TVRRUZGA.js +0 -9
  94. package/dist/chunk-2C4QT5D7.js.map +0 -1
  95. package/dist/chunk-2ZBLZ2S3.js.map +0 -1
  96. package/dist/chunk-AP3JN33O.js.map +0 -1
  97. package/dist/chunk-CA4YQBA7.js +0 -699
  98. package/dist/chunk-CA4YQBA7.js.map +0 -1
  99. package/dist/chunk-CBL3VY7J.js.map +0 -1
  100. package/dist/chunk-FCMWHSQ6.js.map +0 -1
  101. package/dist/chunk-GBXOAO5V.js.map +0 -1
  102. package/dist/chunk-JPOYXG7Z.js.map +0 -1
  103. package/dist/chunk-NKKOGJ63.js.map +0 -1
  104. package/dist/chunk-W6ASIMG5.js.map +0 -1
  105. package/dist/chunk-XLQ4YHS3.js.map +0 -1
  106. package/dist/chunk-ZUZHYAJK.js +0 -6
  107. package/dist/interactive-B3WTC7LB.js.map +0 -1
  108. package/dist/load-AJROS77R.js +0 -11
  109. package/dist/version-5QIEUXU6.js +0 -4
  110. package/dist/vgd-R524P5BJ.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/engine/relations.ts","../src/engine/user-ask.ts","../src/engine/query.ts","../src/engine/impact.ts"],"names":["push","l","v","affinity","text","round"],"mappings":";;;;AAGO,IAAM,aAAN,MAAiB;AAAA,EAKtB,YAAqB,KAAA,EAAgB;AAAhB,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AACnB,IAAA,KAAA,MAAW,CAAA,IAAK,MAAM,KAAA,EAAO,IAAA,CAAK,SAAS,GAAA,CAAI,CAAA,CAAE,IAAI,CAAC,CAAA;AACtD,IAAA,KAAA,MAAW,CAAA,IAAK,MAAM,KAAA,EAAO;AAC3B,MAAA,IAAA,CAAK,IAAA,CAAK,OAAA,EAAS,CAAA,CAAE,GAAA,EAAK,CAAC,CAAA;AAC3B,MAAA,IAAA,CAAK,IAAA,CAAK,MAAA,EAAQ,CAAA,CAAE,GAAA,EAAK,CAAC,CAAA;AAAA,IAC5B;AAAA,EACF;AAAA,EANqB,KAAA;AAAA,EAJZ,QAAA,uBAAe,GAAA,EAAuB;AAAA,EACvC,OAAA,uBAAc,GAAA,EAAyB;AAAA,EACvC,MAAA,uBAAa,GAAA,EAAyB;AAAA,EAU9C,GAAA,CAAI,IAAY,IAAA,EAA8B;AAC5C,IAAA,MAAM,MAAM,IAAA,CAAK,OAAA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,EAAY;AAAA,SACb,CAAA;AACD,QAAA,YAAA,CAAa,KAAK,EAAE,EAAA,EAAI,WAAA,EAAa,IAAA,EAAM,OAAO,CAAA;AAAA,MACpD;AAAA,IACF;AACA,IAAA,QAAA,GAAW,YAAA;AACX,IAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AAAA,EAC7B;AAEA,EAAA,MAAM,QAAQ,CAAC,GAAG,QAAA,CAAS,MAAA,EAAQ,CAAA,CAAE,IAAA;AAAA,IACnC,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,QAAQ,CAAA,CAAE,KAAA,IAAS,CAAA,CAAE,UAAA,GAAa,EAAE,UAAA,IAAc,CAAA,CAAE,IAAA,CAAK,aAAA,CAAc,EAAE,IAAI;AAAA,GAC3F;AAEA,EAAA,OAAO;AAAA,IACL,MAAM,EAAE,EAAA,EAAI,QAAQ,IAAA,EAAM,IAAA,EAAM,iBAAiB,MAAA,EAAO;AAAA,IACxD,KAAA,EAAO,QAAA;AAAA,IACP,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,MAAM,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,KAAA,KAAU,CAAC,CAAA,CAAE,MAAA;AAAA,IAC3C,UAAA,EAAY,MAAM,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,KAAA,GAAQ,CAAC,CAAA,CAAE,MAAA;AAAA,IAC7C,iBAAA,EAAmBA,OAAM,iBAAiB;AAAA,GAC5C;AACF;AAEA,SAASA,OAAM,CAAA,EAAmB;AAChC,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,CAAA,GAAI,GAAG,CAAA,GAAI,GAAA;AAC/B","file":"chunk-CA4YQBA7.js","sourcesContent":["import type { EdgeKind, GraphEdge, GraphNode, VgGraph } from '../schema.js';\n\n/** Indexes over a graph for O(1) neighbor lookups (built once per command). */\nexport class GraphIndex {\n readonly nodeById = new Map<string, GraphNode>();\n private outById = new Map<string, GraphEdge[]>();\n private inById = new Map<string, GraphEdge[]>();\n\n constructor(readonly graph: VgGraph) {\n for (const n of graph.nodes) this.nodeById.set(n.id, n);\n for (const e of graph.edges) {\n push(this.outById, e.src, e);\n push(this.inById, e.dst, e);\n }\n }\n\n out(id: string, kind?: EdgeKind): GraphEdge[] {\n const all = this.outById.get(id) ?? [];\n return kind ? all.filter((e) => e.kind === kind) : all;\n }\n\n in(id: string, kind?: EdgeKind): GraphEdge[] {\n const all = this.inById.get(id) ?? [];\n return kind ? all.filter((e) => e.kind === kind) : all;\n }\n\n node(id: string): GraphNode | undefined {\n return this.nodeById.get(id);\n }\n\n /**\n * Resolved nodes called by `id` — invocations (`call`) plus structural\n * dependency references (`references`, e.g. a constructor-injected field's\n * type), since both represent real usage a caller/impact question cares\n * about. `references` is otherwise only emitted by the precise SCIP/tsc\n * rungs and (for Java DI wiring) the heuristic rung — never a guess.\n */\n callees(id: string): { edge: GraphEdge; node: GraphNode }[] {\n return this.resolveTargets(this.out(id).filter(isUsageEdge), 'dst');\n }\n\n /** Resolved nodes that call or structurally reference `id`. */\n callers(id: string): { edge: GraphEdge; node: GraphNode }[] {\n return this.resolveTargets(this.in(id).filter(isUsageEdge), 'src');\n }\n\n private resolveTargets(edges: GraphEdge[], end: 'src' | 'dst') {\n const out: { edge: GraphEdge; node: GraphNode }[] = [];\n for (const e of edges) {\n const node = this.nodeById.get(e[end]);\n if (node) out.push({ edge: e, node });\n }\n return out;\n }\n}\n\nconst USAGE_KINDS: ReadonlySet<EdgeKind> = new Set(['call', 'references']);\nfunction isUsageEdge(e: GraphEdge): boolean {\n return USAGE_KINDS.has(e.kind);\n}\n\nfunction push(map: Map<string, GraphEdge[]>, key: string, value: GraphEdge): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\n/**\n * Memoized `GraphIndex`, keyed on the graph object's identity.\n *\n * The index (node-by-id + in/out adjacency) is a pure function of the graph's\n * content, and every read path rebuilds it from scratch — an O(nodes + edges)\n * pass that, on a large map, costs hundreds of milliseconds *per query*. Under\n * `vg serve` the same parsed graph object is reused across many tool calls\n * (`GraphSource` caches it by file mtime and only replaces the reference when\n * `graph.json` actually changes), so rebuilding the index on every call is pure\n * waste. Keying a `WeakMap` on that object identity builds the index once and\n * reuses it until the file is rebuilt — at which point `GraphSource` hands back a\n * *new* object, this map misses, and the stale index is collected with the old\n * graph. Correct and stale-safe by construction: a different graph is a\n * different object, so there is no cross-graph reuse and nothing to invalidate.\n *\n * `GraphIndex` is read-only (no method mutates its maps), so sharing one\n * instance across callers is safe.\n */\nconst INDEX_CACHE = new WeakMap<VgGraph, GraphIndex>();\n\nexport function indexFor(graph: VgGraph): GraphIndex {\n let idx = INDEX_CACHE.get(graph);\n if (!idx) {\n idx = new GraphIndex(graph);\n INDEX_CACHE.set(graph, idx);\n }\n return idx;\n}\n","/**\n * Split the user's ask from host-injected attachment metadata.\n *\n * The VS Code panel (`codeAttachments.ts`) and other hosts append a markdown\n * block after a `---` fence:\n *\n * ## User attachments (always include in your reasoning for this turn)\n * ### Attached image: `image.png`\n * … saved at: `.vibgrate/code-attachments/…`\n *\n * Those backticks are for the model. If the full instruction is fed into\n * {@link extractLiteralNeedles} / seed ranking, attachment basenames and paths\n * become **literal-locate hard constraints** (\"0 hits → finish, do not invent\n * an edit\") and the agent aborts a real coding task. Field report: version-badge\n * health UI with a screenshot — agent searched for `image.png` and stopped.\n *\n * Retrieval, needle pinning, locate-only detection, and relevance analysis must\n * use {@link userAskFromInstruction}. The full instruction (with attachments)\n * still belongs in the Task / user message so the model can see the appendix.\n */\n\n/** Heading written by hosts when packing panel attachments into the instruction. */\nexport const USER_ATTACHMENTS_HEADING_PREFIX = '## User attachments';\n\n/**\n * Return only the user-authored portion of an instruction, dropping a trailing\n * host \"User attachments\" appendix when present. Unchanged when no appendix.\n */\nexport function userAskFromInstruction(instruction: string): string {\n if (!instruction) return instruction;\n\n // Canonical host shape: blank line, --- fence, then the attachments heading.\n const fenced = /\\n---\\s*\\n## User attachments\\b[^\\n]*\\n?/;\n const m = fenced.exec(instruction);\n if (m && m.index != null) {\n return instruction.slice(0, m.index).trimEnd();\n }\n\n // Defensive: heading without the fence (older hosts / hand-edited prompts).\n const bare = instruction.search(/(?:^|\\n)## User attachments\\b/);\n if (bare > 0) {\n return instruction.slice(0, bare).trimEnd();\n }\n if (bare === 0) {\n // Instruction is only the appendix — no user ask left.\n return '';\n }\n\n return instruction;\n}\n","import { indexFor, type GraphIndex } from './relations.js';\nimport { cosine, type Embedder } from './embeddings.js';\nimport { WEAK_TERMS, expandConcepts, bigramConsumedTokens } from './concepts.js';\nimport type { RelevanceAnalysis } from './relevance-provider.js';\nimport type { GraphNode, VgGraph } from '../schema.js';\nimport { userAskFromInstruction } from './user-ask.js';\n\n/**\n * Deterministic retrieval for `vg ask` (VG-CLI-SPEC §3.2).\n *\n * Builds a structured, fact-annotated, budget-bounded context block for a\n * question — designed to drop straight into an assistant's context. The default\n * is deterministic lexical+structural retrieval: identifier/term matching with\n * morphological prefix-fuzzing, term-role weighting (process verbs like \"add\"\n * only corroborate, never seed — see engine/concepts.ts), static concept\n * expansion (\"payments\" → stripe/billing/…, \"direct debit\" → sepa/bacs/mandate),\n * and a multi-term coverage bonus, ranked with importance as a mild tiebreaker.\n * `--semantic`/`--deep` adds\n * a hybrid local-embedding pass (`queryGraphSemantic`) that surfaces conceptually\n * related code even when no word is shared — still no API key.\n */\n\nexport interface QueryOptions {\n budget?: number; // approx token budget for the context block (default 2000)\n limit?: number; // max seed matches to expand (default 12)\n /** Optional pre-computed relevance analysis (engine/relevance-provider.ts).\n * Injected by async callers so this module stays pure and sync; when\n * absent, ranking is exactly the built-in lexicon path. */\n relevance?: RelevanceAnalysis | null;\n /** Optional per-node topic tags (engine/relevance-enrich.ts). Combined with\n * `relevance.topics` into a bounded affinity bonus: a node structurally\n * tagged with a topic the question is about ranks above an equal textual\n * match outside it. Never seeds alone — it multiplies existing evidence. */\n topicTags?: Map<string, readonly string[]> | null;\n /** Previous conversational ask (multi-turn `vg code`). Its content terms —\n * never its process verbs — join ranking at a damped weight (CARRY_WEIGHT)\n * so a follow-up like \"can we use direct debits?\" keeps the prior turn's\n * topic (\"where is stripe used?\") instead of ranking the repo on the\n * follow-up's words alone. Absent → behaviour is unchanged. */\n priorQuestion?: string | null;\n}\n\nexport interface QueryMatch {\n node: GraphNode;\n score: number;\n why: string;\n}\n\nexport interface QueryResult {\n question: string;\n matches: QueryMatch[];\n context: string;\n tokensEstimate: number;\n}\n\nconst STOPWORDS = new Set([\n 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'to', 'of', 'in', 'on', 'for', 'and', 'or',\n 'where', 'what', 'which', 'how', 'do', 'does', 'did', 'i', 'we', 'it', 'this', 'that', 'with',\n 'when', 'who', 'why', 'can', 'should', 'my', 'our', 'you', 'your', 'from', 'by', 'at', 'as',\n // Discovery-question scaffolding: words a caller uses to FRAME the ask\n // (\"find the code responsible for X\", \"I need to modify X, where do I\n // start?\", \"explain how X works in this codebase\") rather than to name the\n // target. Left in, these compete on equal footing with the real identifier\n // terms and can outrank it outright — e.g. \"find the code responsible for\n // deleteAsync\" let \"find\" alone drag in every FindByIdAsync/FindAll method\n // in the repo, none of them the target (VG-LOCATE-FAILURE-ANALYSIS.md).\n 'find', 'code', 'responsible', 'need', 'modify', 'me',\n 'implementation', 'explain', 'works', 'codebase', 'contains', 'file',\n // String/URL occurrence scaffolding: \"does not exist\", \"find occurrences of …\"\n // must not light up DoesNot*/NonExisting*/commandExists via weak substrings\n // (field report: https://…/signup does not exist find occurrences).\n 'not', 'no', 'exist', 'exists', 'existing', 'occurrence', 'occurrences',\n 'occurence', 'occurences', 'every', 'place', 'places', 'string', 'literal',\n 'text', 'search', 'locate', 'look', 'looking', 'show', 'list', 'all',\n]);\n\n/**\n * Strip sentence punctuation from a URL match without breaking real query\n * strings (`?key=value`). A lone trailing `?` / `!` is English punctuation\n * (\"where is https://…/signup?\") — leaving it in the needle makes the literal\n * sweep miss the bare path in source.\n */\nfunction cleanUrlNeedle(raw: string): string {\n let s = raw.trim();\n // Trailing ) ] } > , ; : ! . from markdown links / sentence ends.\n s = s.replace(/[.,;:!)\\]}>]+$/g, '');\n // Lone trailing `?` → drop. Keep `?key=…` (content after `?`).\n if (s.endsWith('?')) {\n const qi = s.lastIndexOf('?');\n if (qi === s.length - 1) s = s.slice(0, -1);\n }\n return s;\n}\n\n/**\n * Extract string/URL needles a caller is asking to *locate as text*, not as\n * bag-of-words symbol terms. URLs and quoted phrases are exact-match material\n * for the literal sweep (`search_symbols` / `search_code`); feeding their path\n * segments into lexical symbol ranking produces confidently wrong seeds\n * (dash → dashboard package, exist → NonExisting, …).\n */\nexport function extractLiteralNeedles(question: string): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const push = (raw: string, kind: 'url' | 'quote') => {\n let s = raw.trim();\n s = kind === 'url' ? cleanUrlNeedle(s) : s.replace(/[.,;:!)\\]}>?]+$/g, '');\n if (s.length < 2 || seen.has(s)) return;\n seen.add(s);\n out.push(s);\n };\n for (const m of question.matchAll(/https?:\\/\\/[^\\s\"'`<>]+/gi)) push(m[0]!, 'url');\n for (const m of question.matchAll(/([\"'`])((?:(?!\\1)[^\\\\]|\\\\.){2,})\\1/g)) {\n push(m[2]!.replace(/\\\\(.)/g, '$1'), 'quote');\n }\n return out;\n}\n\n/** Question text with URL/quoted needles removed so residual tokens can name symbols. */\nexport function stripLiteralNeedles(question: string): string {\n let s = question;\n // Strip raw URL spans first (may still carry a trailing `?` from the ask).\n for (const m of question.matchAll(/https?:\\/\\/[^\\s\"'`<>]+/gi)) {\n s = s.split(m[0]!).join(' ');\n }\n for (const lit of extractLiteralNeedles(question)) {\n s = s.split(lit).join(' ');\n }\n // Also strip bare quote pairs left behind.\n s = s.replace(/([\"'`])\\s*\\1/g, ' ');\n return s.replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Residual ask used for graph symbol ranking when the question embeds a\n * URL/quote. Empty when only framing words remain (\"where is …?\") so we do\n * not light up unrelated symbols like `applyPlan.where`.\n */\nexport function residualForSymbolSearch(question: string): string {\n const literals = extractLiteralNeedles(question);\n if (literals.length === 0) return question.trim();\n const stripped = stripLiteralNeedles(question);\n return tokenize(stripped).length === 0 ? '' : stripped;\n}\n\n/**\n * True when the instruction is a string/URL occurrence locate (not an edit).\n * Used to skip PatchIR grammar and answer from the literal sweep without\n * dumping constrained-decoding JSON into the VG Code panel.\n */\nexport function isLocateOnlyInstruction(instruction: string): boolean {\n // Drop host-injected \"User attachments\" appendix (backticked image paths)\n // before classify — same rule as buildCodeContext. Avoids treating a screenshot\n // filename as a locate-only occurrence search.\n const q = userAskFromInstruction(instruction).trim();\n if (!q) return false;\n const needles = extractLiteralNeedles(q);\n const hasLocateFrame =\n /\\b(where\\s+is|where\\s+are|find\\s+(all\\s+|every\\s+)?occurrence|find\\s+occurrences|does\\s+not\\s+exist|locate|search\\s+for)\\b/i.test(\n q,\n ) ||\n (needles.length > 0 && /^https?:\\/\\//i.test(q));\n // Strong edit verbs cancel locate-only (ignore \"does not exist\" as non-edit).\n const withoutExist = q.replace(/\\bdoes\\s+not\\s+exist\\b/gi, ' ');\n if (\n /\\b(fix|edit|change|replace|implement|refactor|rename|patch|create\\s+file|delete\\s+file|add\\s+a\\b|remove\\s+the\\b)\\b/i.test(\n withoutExist,\n )\n ) {\n return false;\n }\n if (needles.some((n) => /^https?:\\/\\//i.test(n))) return true;\n return hasLocateFrame && needles.length > 0;\n}\n\nexport function queryGraph(graph: VgGraph, question: string, options: QueryOptions = {}): QueryResult {\n const budget = options.budget ?? 2000;\n const limit = options.limit ?? 12;\n // When the ask embeds a URL or quoted string, score symbols only on the\n // residual framing text. Empty residual → empty matches (honest miss) rather\n // than path-token false positives that poison Task Capsules.\n const literals = extractLiteralNeedles(question);\n const forTokens = literals.length > 0 ? stripLiteralNeedles(question) : question;\n const prep = prepareTerms(forTokens, options.relevance, priorResidual(options.priorQuestion));\n const weightOf = termWeights(graph, prep.terms.map((t) => t.term));\n const index = indexFor(graph);\n\n const scored: QueryMatch[] = [];\n // Two honest-miss paths: literal-only locate (no identifier terms after\n // stripping needles) and weak-only asks (\"add a new feature\") whose every\n // term is a process verb — seeding those from `add*`/`create*` surface\n // matches is exactly the capsule-poisoning failure (field report 2026-07).\n if (prep.hasContent) {\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n const { score, why } = scoreNode(node, prep.terms, weightOf);\n if (score > 0) {\n const affinity = topicAffinity(node.id, options.relevance, options.topicTags);\n scored.push({\n node,\n score: round(score * affinity.boost * (1 + IMPORTANCE_WEIGHT * node.importance)),\n why: why + affinity.label,\n });\n }\n }\n scored.sort((a, b) => b.score - a.score || a.node.qualifiedName.localeCompare(b.node.qualifiedName));\n }\n\n const seeds = scored.slice(0, limit);\n const { context, tokensEstimate } = buildContext(graph, index, question, seeds, budget, literals);\n\n return { question, matches: seeds, context, tokensEstimate };\n}\n\nexport interface SemanticQueryOptions extends QueryOptions {\n /** Local embedder. Optional only when {@link semanticRanked} supplies the pass. */\n embedder?: Embedder;\n /** Precomputed node vectors (from getNodeEmbeddings); falls back to lexical for nodes without one. */\n nodeVectors?: Map<string, number[]>;\n /**\n * A semantic pass someone else already ran — vgd ranking the question\n * against its resident slot index. Supplied instead of `embedder` +\n * `nodeVectors` so the caller pays neither a model load nor a vector scan,\n * and no vectors cross the socket.\n *\n * Only the ORDER of this list is consumed (RRF fuses rankings, not scores),\n * so a truncated top-K is not an approximation: a candidate ranked past a\n * few hundred cannot reach a 12-row answer.\n */\n semanticRanked?: Array<{ id: string; score: number }>;\n}\n\n/**\n * Reciprocal Rank Fusion constant (the standard k=60). Fusing RANKINGS\n * instead of blending raw scores removes the need to calibrate two\n * incomparable scales (tiered lexical evidence vs cosine similarity): a node's\n * fused score is Σ 1/(k + rankᵢ) over the lists it appears in, so agreement\n * between signals dominates and a single signal's outlier magnitude cannot.\n */\nconst RRF_K = 60;\n\n/** 1-based ranks for a scored id list (desc score, qualifiedName tiebreak). */\nfunction ranksOf(scores: Map<string, number>, nameOf: (id: string) => string): Map<string, number> {\n const ids = [...scores.entries()]\n .filter(([, s]) => s > 0)\n .sort((a, b) => b[1] - a[1] || nameOf(a[0]).localeCompare(nameOf(b[0])))\n .map(([id]) => id);\n return new Map(ids.map((id, i) => [id, i + 1]));\n}\n\n/**\n * Hybrid lexical + local-embedding retrieval, combined with Reciprocal Rank\n * Fusion (Phase 3.2 — replaces the former 50/50 score blend), so a question\n * like \"where do we handle auth failures?\" can surface `verify_token` even\n * with no shared identifier. Topic affinity and importance stay multiplicative\n * tiebreakers on the fused score. Deterministic given the same model + cached\n * vectors; embeddings live in a binary sidecar next to the map, never in `graph.json`.\n */\nexport async function queryGraphSemantic(\n graph: VgGraph,\n question: string,\n options: SemanticQueryOptions,\n): Promise<QueryResult> {\n const budget = options.budget ?? 2000;\n const limit = options.limit ?? 12;\n const literals = extractLiteralNeedles(question);\n const forTokens = literals.length > 0 ? stripLiteralNeedles(question) : question;\n const prep = prepareTerms(forTokens, options.relevance, priorResidual(options.priorQuestion));\n const terms = prep.terms.map((t) => t.term);\n const weightOf = termWeights(graph, terms);\n const index = indexFor(graph);\n // Embed the residual ask (without URL/quote noise) so semantic neighbours\n // aren't dragged toward package names that share host path segments. Skipped\n // entirely when the ranking arrives pre-computed (vgd already embedded it).\n const queryVec = options.semanticRanked\n ? null\n : await options.embedder?.embedQuery(forTokens || question);\n\n // Raw lexical scores (pre-importance) — RRF consumes only their ORDER.\n // Weak-only asks get no lexical evidence (same suppression as queryGraph);\n // the semantic cosine below may still surface conceptual neighbours for them.\n const lexRaw = new Map<string, number>();\n const whyById = new Map<string, string>();\n if (prep.hasContent) {\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n const { score, why } = scoreNode(node, prep.terms, weightOf);\n lexRaw.set(node.id, score);\n whyById.set(node.id, why);\n }\n }\n\n const scored: QueryMatch[] = [];\n // Literal-only asks: skip the semantic loop entirely — embeddings over\n // \"does not exist find occurrences\" still surface unrelated hubs.\n if (terms.length > 0 || literals.length === 0) {\n // Independent per-signal rankings, then RRF.\n const semRaw = new Map<string, number>();\n const nodeById = new Map<string, GraphNode>();\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n nodeById.set(node.id, node);\n if (options.semanticRanked || !queryVec) continue;\n const vec = options.nodeVectors?.get(node.id);\n const sem = vec && terms.length > 0 ? Math.max(0, cosine(queryVec, vec)) : 0;\n if (sem > 0) semRaw.set(node.id, sem);\n }\n if (options.semanticRanked && terms.length > 0) {\n // Ignore ids the ranking knows about but this graph no longer has: the\n // daemon's index can be one publish behind a locally refreshed map.\n for (const { id, score } of options.semanticRanked) {\n if (score > 0 && nodeById.has(id)) semRaw.set(id, score);\n }\n }\n const nameOf = (id: string) => nodeById.get(id)?.qualifiedName ?? id;\n const lexRanks = ranksOf(lexRaw, nameOf);\n const semRanks = ranksOf(semRaw, nameOf);\n for (const [id, node] of nodeById) {\n const lr = lexRanks.get(id);\n const sr = semRanks.get(id);\n if (lr === undefined && sr === undefined) continue;\n const fused = (lr !== undefined ? 1 / (RRF_K + lr) : 0) + (sr !== undefined ? 1 / (RRF_K + sr) : 0);\n const sem = semRaw.get(id) ?? 0;\n const lexWhy = whyById.get(id);\n const affinity = topicAffinity(id, options.relevance, options.topicTags);\n const why = (lexWhy || (sem > 0.3 ? `semantic match (${sem.toFixed(2)})` : 'weak match')) + affinity.label;\n scored.push({ node, score: round(fused * affinity.boost * (1 + IMPORTANCE_WEIGHT * node.importance)), why });\n }\n scored.sort((a, b) => b.score - a.score || a.node.qualifiedName.localeCompare(b.node.qualifiedName));\n }\n\n const seeds = scored.slice(0, limit);\n const { context, tokensEstimate } = buildContext(graph, index, question, seeds, budget, literals);\n return { question, matches: seeds, context, tokensEstimate };\n}\n\n/**\n * Split on anything that isn't a Unicode letter/number (`\\p{L}\\p{N}`, not the\n * ASCII-only `[a-z0-9]`) so identifiers in non-Latin scripts (Japanese,\n * Cyrillic, ...) survive tokenization instead of vanishing entirely — the\n * ASCII-only split treated every character of e.g. `名前` as a separator,\n * producing zero terms and a guaranteed empty result for any question about\n * it (VG-LOCATE-FAILURE-ANALYSIS.md). Length floor is 1, not 2: a single\n * non-stopword letter/digit is still the whole identifier when that's genuinely\n * the symbol's name (adversarial fixtures deliberately use bare `f`/`x`/`h`\n * names to stress this) — STOPWORDS already screens out short function words.\n */\nfunction tokenize(q: string): string[] {\n return [\n ...new Set(\n q\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter((t) => t.length >= 1 && !STOPWORDS.has(t)),\n ),\n ];\n}\n\n/** Ordered, lowercased token stream WITH stopwords — bigram concepts (\"sign in\",\n * \"direct debit\") need adjacency over the raw word order. */\nfunction tokenizeOrdered(q: string): string[] {\n return q\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter((t) => t.length >= 1);\n}\n\n/**\n * A query term with its role resolved. Roles decide how much evidence a match\n * carries (see scoreNode):\n * - content — names the topic; full weight, counts toward coverage\n * - weak — process verb (\"add\", \"create\", \"via\"); down-weighted, can only\n * corroborate a content match, never carry a seed alone\n * - expansion — concept vocabulary from the lexicon (\"payments\"→\"stripe\");\n * reduced weight, counts as content evidence, provenance in `why`\n */\ninterface QueryTerm {\n term: string;\n weak: boolean;\n /** Source token/bigram when this term came from concept expansion. */\n from?: string;\n /** Provider-supplied confidence (0..1) when this term came from the optional\n * relevance provider; replaces the flat EXPANSION_WEIGHT for that term. */\n providerWeight?: number;\n /** True when this term was carried over from the previous conversational\n * turn (QueryOptions.priorQuestion); scores at CARRY_WEIGHT. */\n carried?: boolean;\n}\n\ninterface PreparedTerms {\n terms: QueryTerm[];\n /** True when at least one content or expansion term exists — the bar a\n * question must clear before ANY node may seed. */\n hasContent: boolean;\n}\n\n/** Weak process verbs corroborate at a fraction of a content term's weight. */\nconst WEAK_TERM_WEIGHT = 0.25;\n/** Concept expansions score below a literal question term of the same rarity. */\nconst EXPANSION_WEIGHT = 0.7;\n/** Per extra distinct content term matched, the multiplicative coverage bonus.\n * Multi-topic evidence (\"direct\" + \"debit\" + \"payments\") must beat any\n * single-term surface hit (\"add\") by construction, not by luck. */\nconst COVERAGE_BONUS = 0.35;\n/** Terms carried from the previous conversational turn score at half weight:\n * enough to keep a follow-up anchored to the conversation's topic (and to\n * rescue weak-only follow-ups like \"can we use it?\"), never enough for stale\n * context to outrank a clearly-named new topic in the current ask. */\nconst CARRY_WEIGHT = 0.5;\n\n/** Resolve term roles + concept expansions for the residual ask text. */\nfunction prepareTerms(forTokens: string, relevance?: RelevanceAnalysis | null, prior?: string | null): PreparedTerms {\n const base = tokenize(forTokens);\n const ordered = tokenizeOrdered(forTokens);\n const baseSet = new Set(base);\n // A token consumed by a fired bigram concept (\"direct\" in \"direct debits\")\n // is demoted to the weak role: the bigram's expansions carry the topic, and\n // the constituent alone is a distractor magnet (directGet, redirectUrl, …).\n const consumed = bigramConsumedTokens(ordered);\n const terms: QueryTerm[] = base.map((t) => ({ term: t, weak: WEAK_TERMS.has(t) || consumed.has(t) }));\n const have = new Set(base);\n for (const e of expandConcepts(ordered)) {\n if (baseSet.has(e.term)) continue;\n terms.push({ term: e.term, weak: false, from: e.from });\n have.add(e.term);\n }\n // Provider expansions (already sanitized by engine/relevance-provider.ts)\n // join as expansion-role terms with their own confidence weight. The\n // built-in lexicon wins ties: a term it already produced is not re-added,\n // so provider presence never changes the score of a lexicon-covered term.\n for (const e of relevance?.expansions ?? []) {\n if (have.has(e.term)) continue;\n terms.push({ term: e.term, weak: false, from: e.from, providerWeight: e.weight });\n have.add(e.term);\n }\n // Conversation carry-over: the previous turn's CONTENT terms (plus their\n // lexicon expansions) join at CARRY_WEIGHT. Weak process verbs from the\n // prior turn are dropped outright — carrying \"add\"/\"use\" forward would\n // re-open the grab-bag failure this module exists to prevent. A term the\n // current ask already produced is never re-added, so the current turn\n // always wins ties and single-turn behaviour is byte-identical.\n if (prior?.trim()) {\n const priorOrdered = tokenizeOrdered(prior);\n const priorConsumed = bigramConsumedTokens(priorOrdered);\n for (const t of tokenize(prior)) {\n if (have.has(t) || WEAK_TERMS.has(t) || priorConsumed.has(t)) continue;\n terms.push({ term: t, weak: false, carried: true });\n have.add(t);\n }\n for (const e of expandConcepts(priorOrdered)) {\n if (have.has(e.term)) continue;\n terms.push({ term: e.term, weak: false, from: e.from, carried: true });\n have.add(e.term);\n }\n }\n const hasContent = terms.some((t) => !t.weak);\n return { terms, hasContent };\n}\n\n/** Residual text of the previous ask, with URL/quoted needles stripped so a\n * pasted link in turn N-1 cannot poison turn N's carried vocabulary. */\nfunction priorResidual(prior: string | null | undefined): string | null {\n const raw = prior?.trim();\n if (!raw) return null;\n return extractLiteralNeedles(raw).length > 0 ? stripLiteralNeedles(raw) : raw;\n}\n\n/**\n * Plain-language concept map for one ask: how its words were interpreted —\n * fired concept/bigram expansions, relevance-kernel topics and vocabulary,\n * and terms carried from the previous conversational turn. Rendered into the\n * Task Capsule so a model (especially a small local one) can read the\n * inference chain (\"direct debits\" → debit/mandate/…; topic payments →\n * stripe/billing/…) as sentences instead of reverse-engineering the `a→b`\n * slugs in per-seed match provenance. Deterministic and bounded; empty when\n * nothing fired (honest-empty asks stay empty).\n */\nexport function conceptMapLines(\n question: string,\n relevance?: RelevanceAnalysis | null,\n priorQuestion?: string | null,\n): string[] {\n const cap = (xs: string[]) => [...new Set(xs)].slice(0, 8).join(', ');\n const literals = extractLiteralNeedles(question);\n const residual = literals.length > 0 ? stripLiteralNeedles(question) : question;\n const lines: string[] = [];\n\n // Lexicon / bigram expansions, grouped by the ask term that fired them.\n const byFrom = new Map<string, string[]>();\n for (const e of expandConcepts(tokenizeOrdered(residual))) {\n const list = byFrom.get(e.from) ?? [];\n list.push(e.term);\n byFrom.set(e.from, list);\n }\n for (const [from, terms] of byFrom) {\n lines.push(`- \"${from}\" in the ask implies these codebase identifiers: ${cap(terms)}.`);\n }\n\n // ---------------------------------------------------------------------\n // What the ask is about, deepest first.\n //\n // Order is the message. A reader (or a model) wants the most specific thing\n // first — \"cname\" — then the product that makes it concrete — \"cloudflare\" —\n // then the containing levels, widening out to \"infrastructure\". Files come\n // after that, because they are where to look once you know what you are\n // looking for. Corrections come last: they explain how the ask was read,\n // which only matters once the reading itself is on the page.\n // ---------------------------------------------------------------------\n const matches = relevance?.taxonomy ?? [];\n if (matches.length) {\n // Every matched level, deduped, deepest first. Ties keep provider order,\n // which is evidence-ranked.\n const seenPath = new Set<string>();\n const levels: Array<{ path: string; id: string; depth: number; terms: string[] }> = [];\n for (const m of matches) {\n for (const l of m.levels) {\n if (seenPath.has(l.path)) continue;\n seenPath.add(l.path);\n levels.push({ path: l.path, id: l.id, depth: l.path.split('/').length, terms: l.terms });\n }\n }\n const deepest = Math.max(...levels.map((l) => l.depth));\n const describe = (l: { id: string; terms: string[] }, lead: string) =>\n l.terms.length\n ? `${lead} ${l.id}; code for it typically uses: ${cap(l.terms)}.`\n : `${lead} ${l.id}.`;\n\n for (const l of levels.filter((l) => l.depth === deepest)) {\n lines.push(describe(l, '- The ask is specifically about'));\n }\n\n // The product named sits directly under the most specific topic — it is\n // what turns that topic into this codebase's version of it. When the\n // product IS the most specific topic, the line above already said so, and\n // only the typed form is worth adding.\n const deepestIds = new Set(levels.filter((l) => l.depth === deepest).map((l) => l.id));\n for (const v of (relevance?.vendors ?? []).filter((v) => v.score > 0).slice(0, 3)) {\n if (deepestIds.has(v.name)) {\n if (v.from !== v.name) lines.push(`- That product was typed \"${v.from}\".`);\n continue;\n }\n lines.push(\n v.from === v.name\n ? `- It names the product \"${v.name}\".`\n : `- It names the product \"${v.name}\" (typed \"${v.from}\").`,\n );\n }\n\n // Then widen, one level at a time — skipping any level the vendor line\n // already named, so a Cloudflare ask does not say \"cloudflare\" twice.\n const named = new Set((relevance?.vendors ?? []).map((v) => v.name));\n for (let d = deepest - 1; d >= 1; d--) {\n for (const l of levels.filter((l) => l.depth === d && !named.has(l.id))) {\n lines.push(describe(l, '- More broadly, this is'));\n }\n }\n } else if (relevance?.topics?.length) {\n // Provider without a taxonomy (or an older one): flat topics, as before.\n const topicVocab = new Map<string, string[]>();\n for (const e of relevance.expansions ?? []) {\n const list = topicVocab.get(e.from) ?? [];\n list.push(e.term);\n topicVocab.set(e.from, list);\n }\n for (const t of relevance.topics.slice(0, 3)) {\n const vocab = topicVocab.get(t.id);\n lines.push(\n vocab?.length\n ? `- The ask is about the \"${t.id}\" domain; code for it typically uses: ${cap(vocab)}.`\n : `- The ask is about the \"${t.id}\" domain.`,\n );\n }\n }\n\n // What governs the work, named at the revision the provider tracks. This is\n // the difference between \"this is accessibility work\" and \"this is\n // accessibility work, and WCAG 2.2 is what it has to satisfy\".\n const standards = relevance?.standards ?? [];\n if (standards.length) {\n const specs = standards.filter((st) => st.kind !== 'regulation');\n const rules = standards.filter((st) => st.kind === 'regulation');\n const render = (list: typeof standards) =>\n list\n .slice(0, 3)\n .map((st) => (st.publisher ? `${st.name} (${st.publisher})` : st.name))\n .join('; ');\n // A spec and a legal duty are not the same obligation, so they are not\n // pooled into one sentence.\n if (specs.length) lines.push(`- Standards that govern this area: ${render(specs)}.`);\n if (rules.length) lines.push(`- Regulations that apply here: ${render(rules)}.`);\n }\n\n // The site's own category slugs for everything above, so a reader (or a\n // lookup) can cross-reference content by the same key.\n const categories = relevance?.categories ?? [];\n if (categories.length) {\n lines.push(`- Related categories: ${cap(categories)}.`);\n }\n\n // Where that work usually lives — the concrete lead, after the abstract one.\n const fileHints = relevance?.files ?? [];\n if (fileHints.length) {\n lines.push(`- Files for this kind of work are usually named or extended: ${cap(fileHints)}.`);\n }\n\n // How the ask was read, if it was read as something other than typed.\n for (const c of (relevance?.corrections ?? []).slice(0, 3)) {\n lines.push(`- Read \"${c.from}\" in the ask as \"${c.to}\".`);\n }\n\n // Conversation carry-over provenance.\n const priorText = priorResidual(priorQuestion);\n if (priorText) {\n const current = new Set(tokenize(residual));\n const consumed = bigramConsumedTokens(tokenizeOrdered(priorText));\n const carried = tokenize(priorText).filter((t) => !current.has(t) && !WEAK_TERMS.has(t) && !consumed.has(t));\n if (carried.length) {\n lines.push(`- This is a follow-up; topic words carried from the previous ask: ${cap(carried)}.`);\n }\n }\n\n if (lines.length) {\n lines.push(\n '- Seed notation below: `a→b` = ask term \"a\" implied identifier \"b\"; `~t` = word-form match; `↩t` = carried from the previous ask.',\n );\n }\n return lines;\n}\n\nfunction scoreNode(node: GraphNode, terms: QueryTerm[], weightOf: (t: string) => number = () => 1): { score: number; why: string } {\n let score = 0;\n let contentHits = 0;\n const hits: string[] = [];\n const name = node.name.toLowerCase();\n const qn = node.qualifiedName.toLowerCase();\n const file = node.file.toLowerCase();\n // Directory segments of the file path: a term naming a whole directory\n // (\"payments\" → src/payments/…) is domain evidence, stronger than an\n // incidental substring somewhere in the path.\n const dirSegments = new Set(file.split('/').slice(0, -1));\n // Split the ORIGINAL name on camelCase / snake_case, then lowercase the parts\n // (splitting must see the capitals, so it happens before lowercasing).\n const nameParts = identifierParts(node.name);\n for (const { term: t, weak, from, providerWeight, carried } of terms) {\n // Each term's contribution is weighted by its specificity (IDF over symbol\n // names): a match on a distinctive term (\"toComparable\", \"layoutFor\") counts\n // for more than a match on a term shared by hundreds of symbols (\"code\",\n // \"get\", \"run\"). Without this, an incidental exact-name hit on a common word\n // in a natural-language question outranked the conceptually-correct symbol,\n // and importance weighting amplified the wrong hit (VG-NAVIGATION trace).\n // Role multipliers stack on top: process verbs corroborate at a fraction,\n // concept expansions score below a literal term of the same rarity.\n // Expansion role multiplier: provider expansions carry their own 0..1\n // confidence (capped at the lexicon's EXPANSION_WEIGHT so an installed\n // provider can widen vocabulary but never outrank the reviewed lexicon's\n // evidence class); lexicon expansions keep the flat EXPANSION_WEIGHT.\n const expansionW = providerWeight !== undefined ? Math.min(providerWeight, EXPANSION_WEIGHT) : from ? EXPANSION_WEIGHT : 1;\n const w = weightOf(t) * (weak ? WEAK_TERM_WEIGHT : 1) * expansionW * (carried ? CARRY_WEIGHT : 1);\n const label = (carried ? '↩' : '') + (from ? `${from}→${t}` : t);\n let contribution = 0;\n if (name === t) {\n contribution = 10 * w;\n hits.push(label);\n } else if (nameParts.has(t)) {\n contribution = 6 * w;\n hits.push(label);\n } else if (name.includes(t)) {\n contribution = 4 * w;\n hits.push(label);\n } else if (qn.includes(t)) {\n contribution = 3 * w;\n hits.push(label);\n } else if (fuzzyPartMatch(t, nameParts)) {\n // Morphological / subword match: \"authentication\" ↔ \"authenticate\"\n // (shared prefix), so lexical ask survives word-form differences without\n // a model. The semantic path handles non-shared-root synonyms.\n contribution = 2 * w;\n hits.push((carried ? '↩' : '') + (from ? `~${from}→${t}` : `~${t}`));\n } else if (dirSegments.has(t)) {\n contribution = 2 * w;\n hits.push(label);\n } else if (file.includes(t)) {\n contribution = 1 * w;\n hits.push(label);\n }\n if (contribution > 0) {\n score += contribution;\n if (!weak) contentHits += 1;\n }\n }\n // A node whose only evidence is weak process verbs is noise by definition —\n // the `add`-grab-bag capsule failure. Suppress it outright: weak terms\n // corroborate content matches, they never carry a seed.\n if (contentHits === 0) return { score: 0, why: '' };\n // Reward multi-term topic coverage multiplicatively so converging evidence\n // (\"direct\" + \"debit\" + payments-expansion) dominates single-term hits.\n score *= 1 + COVERAGE_BONUS * Math.min(contentHits - 1, 4);\n return { score, why: hits.length ? `matched: ${hits.join(', ')}` : '' };\n}\n\n/**\n * Importance is a mild tiebreaker, not a doubling. The old `1 + importance`\n * let a hub (importance→1) double its score and outrank a stronger textual\n * match on the actual target; at 0.4 a top hub adds at most 40%, enough to\n * break genuine ties without overriding term evidence.\n */\nconst IMPORTANCE_WEIGHT = 0.4;\n\n/**\n * Topic-affinity bonus cap: a node whose enrichment tags intersect the\n * question's inferred topics gains at most this fraction on top of its\n * textual evidence. Sized between IMPORTANCE_WEIGHT (0.4) and nothing:\n * strong enough to break domain ties (\"direct debits\" → the payments file\n * over an equal-scoring name hit elsewhere), never strong enough to outrank\n * a clearly better textual match — and it multiplies an existing non-zero\n * score, so it can never conjure a seed by itself.\n */\nconst TOPIC_AFFINITY_WEIGHT = 0.3;\n\n/** Affinity multiplier + provenance for one node under the current analysis. */\n/**\n * Shared root-first path depth between two taxonomy paths.\n * \"infrastructure/networking/dns/cname\" vs \"infrastructure/networking/dns\" → 3.\n */\nfunction sharedDepth(a: string, b: string): number {\n const as = a.split('/');\n const bs = b.split('/');\n let n = 0;\n while (n < as.length && n < bs.length && as[n] === bs[n]) n++;\n return n;\n}\n\n/**\n * How strongly a node's taxonomy tags match what the ask is about.\n *\n * Tags and query matches are both PATHS, so agreement is measured by how far\n * down the tree they agree, not merely whether they share a label. A DNS ask\n * and a file tagged `infrastructure/networking/dns` agree three levels deep\n * and get most of the bonus; the same ask and a file tagged\n * `infrastructure/containers` agree only at the root and get a fraction of it.\n * That is the whole reason tags carry paths.\n *\n * Falls back to flat topic-id matching when the provider predates the\n * taxonomy (or a stale sidecar still holds flat tags), so an older install\n * ranks exactly as it did before.\n */\nfunction topicAffinity(\n nodeId: string,\n relevance: RelevanceAnalysis | null | undefined,\n topicTags: Map<string, readonly string[]> | null | undefined,\n): { boost: number; label: string } {\n if (!topicTags) return { boost: 1, label: '' };\n const tags = topicTags.get(nodeId);\n if (!tags?.length) return { boost: 1, label: '' };\n\n const paths = relevance?.taxonomy ?? [];\n if (paths.length && tags.some((t) => t.includes('/'))) {\n let best = 0;\n let label = '';\n for (const match of paths) {\n const askDepth = match.path.split('/').length;\n for (const tag of tags) {\n const shared = sharedDepth(match.path, tag);\n if (shared === 0) continue;\n // Specificity of agreement × confidence in the match.\n const affinity = (shared / askDepth) * match.score;\n if (affinity > best) {\n best = affinity;\n label = shared === askDepth ? match.path : match.path.split('/').slice(0, shared).join('/');\n }\n }\n }\n if (best <= 0) return { boost: 1, label: '' };\n return { boost: 1 + TOPIC_AFFINITY_WEIGHT * Math.min(best, 1), label: `, topic:${label}` };\n }\n\n if (!relevance?.topics?.length) return { boost: 1, label: '' };\n let affinity = 0;\n const matched: string[] = [];\n for (const t of relevance.topics) {\n if (tags.includes(t.id)) {\n affinity += t.score;\n matched.push(t.id);\n }\n }\n if (affinity <= 0) return { boost: 1, label: '' };\n return { boost: 1 + TOPIC_AFFINITY_WEIGHT * Math.min(affinity, 1), label: `, topic:${matched.sort().join('+')}` };\n}\n\n/**\n * Per-term specificity weights (IDF) for one question, computed over the graph's\n * symbol-name vocabulary: `ln((N+1)/(df+1)) + 1`, clamped to a sane band. A term\n * that appears in one symbol name is highly discriminating; one that appears in\n * hundreds (\"get\", \"code\", \"run\", \"handler\") is near-noise. Clamped so a term\n * matching nothing (huge idf, but it scores 0 anyway) or everything can't\n * distort the scale. Cost is one O(nodes) pass, dwarfed by the scoring loop.\n */\nfunction termWeights(graph: VgGraph, terms: string[]): (t: string) => number {\n if (terms.length === 0) return () => 1;\n const df = new Map<string, number>();\n let n = 0;\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n n++;\n const name = node.name.toLowerCase();\n const parts = identifierParts(node.name);\n for (const t of terms) {\n if (parts.has(t) || name.includes(t)) df.set(t, (df.get(t) ?? 0) + 1);\n }\n }\n const w = new Map<string, number>();\n for (const t of terms) {\n const idf = Math.log((n + 1) / ((df.get(t) ?? 0) + 1)) + 1;\n // Ceiling of 8 (vs a natural df≈40 idf ≈ 5.4) keeps genuinely rare terms\n // dominant while a term matching nothing/only a file path can't distort.\n w.set(t, Math.max(0.5, Math.min(8, idf)));\n }\n return (t: string) => w.get(t) ?? 1;\n}\n\n/**\n * camelCase / snake_case / kebab split of an identifier → lowercased parts.\n * The separator alternative is Unicode-letter-aware (`\\p{L}\\p{N}`, not\n * ASCII-only `a-zA-Z0-9`) so non-Latin identifiers split on punctuation\n * without losing every character to it; the camelCase boundary lookaround\n * stays ASCII-only since upper/lowercase casing is itself an ASCII-script\n * concept — scripts without case simply never trigger it and fall through to\n * the separator split.\n */\nexport function identifierParts(name: string): Set<string> {\n return new Set(\n name\n .split(/[^\\p{L}\\p{N}]+|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/u)\n .filter(Boolean)\n .map((s) => s.toLowerCase()),\n );\n}\n\n/** A term fuzzily matches a part if they share a long-enough prefix (same root). */\nfunction fuzzyPartMatch(term: string, parts: Set<string>): boolean {\n for (const part of parts) {\n const shared = sharedPrefixLen(term, part);\n if (shared >= 5 && shared >= 0.6 * Math.min(term.length, part.length)) return true;\n }\n return false;\n}\n\nfunction sharedPrefixLen(a: string, b: string): number {\n const n = Math.min(a.length, b.length);\n let i = 0;\n while (i < n && a[i] === b[i]) i++;\n return i;\n}\n\nfunction buildContext(\n graph: VgGraph,\n index: GraphIndex,\n question: string,\n seeds: QueryMatch[],\n budget: number,\n literals: string[] = [],\n): { context: string; tokensEstimate: number } {\n const lines: string[] = [];\n lines.push(`# Context for: ${question}`);\n lines.push('');\n if (literals.length) {\n lines.push('## Literal string(s) to locate (exact text, not symbol names)');\n for (const lit of literals) lines.push(`- \\`${lit}\\``);\n lines.push(\n '_Use a quoted phrase / URL search (`search_symbols` or `search_code` with the exact needle) for occurrences. Graph symbols below (if any) are residual identifier hints only._',\n );\n lines.push('');\n }\n if (seeds.length === 0) {\n lines.push(\n literals.length\n ? '_No graph symbols matched residual terms — this is expected for a pure string/URL occurrence search. Run a literal sweep on the needle(s) above._'\n : '_No matching symbols found in the map. Try different terms, or `vg hubs` for the most important code._',\n );\n const text = lines.join('\\n');\n return { context: text, tokensEstimate: estimateTokens(text) };\n }\n\n for (const { node, why } of seeds) {\n const block: string[] = [];\n block.push(`## ${node.qualifiedName} (${node.kind}, ${node.file}:${node.span.start})`);\n if (node.signature) block.push('`' + node.signature + '`');\n const callees = index.callees(node.id).map((x) => x.node.qualifiedName);\n const callers = index.callers(node.id).map((x) => x.node.qualifiedName);\n if (callees.length) block.push(`calls: ${unique(callees).slice(0, 8).join(', ')}`);\n if (callers.length) block.push(`called by: ${unique(callers).slice(0, 8).join(', ')}`);\n block.push(`importance ${node.importance.toFixed(3)} · area #${node.area}${node.isHub ? ' · hub' : ''} · ${why}`);\n block.push('');\n\n const candidate = lines.concat(block).join('\\n');\n if (estimateTokens(candidate) > budget && lines.length > 2) break;\n lines.push(...block);\n }\n\n const text = lines.join('\\n');\n return { context: text, tokensEstimate: estimateTokens(text) };\n}\n\nfunction unique(xs: string[]): string[] {\n return [...new Set(xs)];\n}\n\nfunction estimateTokens(text: string): number {\n // ~4 chars per token, the standard rough estimate.\n return Math.ceil(text.length / 4);\n}\n\nfunction round(x: number): number {\n return Math.round(x * 1e6) / 1e6;\n}\n","import { indexFor } from './relations.js';\nimport type { EdgeKind, VgGraph } from '../schema.js';\n\n/**\n * Deterministic reverse-reachability impact analysis (VG-CLI-SPEC §3.5).\n *\n * \"What breaks if `<node>` changes\" = everything that (transitively) depends on\n * it: its callers, importers, and subtypes. We BFS *backwards* along dependency\n * edges, bounded by depth, with a confidence that decays with distance (direct =\n * high; transitive lower; ambiguous/dynamic edges already carry lower edge\n * confidence which we fold in). Test-impact selection (`--tests`) lands in\n * Phase 2; this is the structural blast radius.\n */\n\nconst DEPEND_EDGES = new Set<EdgeKind>(['call', 'import', 'extends', 'implements', 'references']);\n\nexport interface ImpactItem {\n id: string;\n name: string;\n kind: string;\n file: string;\n line: number;\n depth: number;\n confidence: number;\n}\n\nexport interface ImpactResult {\n root: { id: string; name: string };\n depth: number;\n affected: ImpactItem[];\n direct: number;\n transitive: number;\n /** Lowest edge confidence encountered (e.g. a dynamic-dispatch edge). */\n minEdgeConfidence: number;\n}\n\nexport function impactOf(graph: VgGraph, rootId: string, opts: { depth?: number } = {}): ImpactResult {\n const maxDepth = Math.max(1, opts.depth ?? 4);\n const index = indexFor(graph);\n const root = index.node(rootId);\n\n const affected = new Map<string, ImpactItem>();\n let minEdgeConfidence = 1;\n\n // BFS over incoming dependency edges (dependents of the frontier).\n let frontier: { id: string; conf: number }[] = [{ id: rootId, conf: 1 }];\n for (let depth = 1; depth <= maxDepth; depth++) {\n const nextFrontier: { id: string; conf: number }[] = [];\n for (const { id, conf } of frontier) {\n for (const e of index.in(id)) {\n if (!DEPEND_EDGES.has(e.kind)) continue;\n minEdgeConfidence = Math.min(minEdgeConfidence, e.confidence);\n const dependentId = e.src;\n if (dependentId === rootId || affected.has(dependentId)) continue;\n const node = index.node(dependentId);\n if (!node) continue;\n const conf2 = round(conf * e.confidence * 0.9); // decay with distance\n affected.set(dependentId, {\n id: node.id,\n name: node.qualifiedName,\n kind: node.kind,\n file: node.file,\n line: node.span.start,\n depth,\n confidence: conf2,\n });\n nextFrontier.push({ id: dependentId, conf: conf2 });\n }\n }\n frontier = nextFrontier;\n if (frontier.length === 0) break;\n }\n\n const items = [...affected.values()].sort(\n (a, b) => a.depth - b.depth || b.confidence - a.confidence || a.name.localeCompare(b.name),\n );\n\n return {\n root: { id: rootId, name: root?.qualifiedName ?? rootId },\n depth: maxDepth,\n affected: items,\n direct: items.filter((i) => i.depth === 1).length,\n transitive: items.filter((i) => i.depth > 1).length,\n minEdgeConfidence: round(minEdgeConfidence),\n };\n}\n\nfunction round(x: number): number {\n return Math.round(x * 1e6) / 1e6;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/engine/savings.ts","../src/code/context.ts","../src/code/capsule.ts"],"names":["estimateTokens","normalize"],"mappings":";;;;;;AAmBA,IAAM,MAAA,GAAS,eAAA;AAER,IAAM,eAAA,GAAkB;AAQxB,IAAM,gCAAgB,IAAI,GAAA,CAAI,CAAC,aAAA,EAAe,UAAA,EAAY,gBAAgB,CAAC;AAoB3E,IAAM,gBAAA,GAAqD;AAAA,EAChE,GAAA,EAAK,aAAA;AAAA,EACL,IAAA,EAAM,UAAA;AAAA,EACN,MAAA,EAAQ,WAAA;AAAA,EACR,IAAA,EAAM,WAAA;AAAA,EACN,IAAA,EAAM,WAAA;AAAA,EACN,KAAA,EAAO,YAAA;AAAA,EACP,IAAA,EAAM;AACR;AASO,SAAS,eAAe,IAAA,EAAyC;AACtE,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,EAAU,OAAO,SAAA;AACrC,EAAA,MA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MAAA;AAAA,IACN,EAAA,EAAI,QAAA;AAAA,IACJ,EAAA,EAAI,IAAA;AAAA,IACJ,IAAA,EAAM;AAAA,GACR;AACA,EAAA,OAAO,GAAA,CAAI,GAAG,CAAA,IAAK,EAAA;AACrB;AAEA,SAASC,WAAU,IAAA,EAAsB;AACvC,EAAA,OAAO,KAAK,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,SAAS,EAAE,CAAA;AACrD;AAEA,SAASD,gBAAe,IAAA,EAAsB;AAC5C,EAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,CAAC,CAAA;AAClC","file":"chunk-CBL3VY7J.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { cacheDir } from './cache.js';\n\n/**\n * Usage-savings tracking (VG-DEVELOPMENT-PLAN §5) — local, privacy-safe, and\n * **opt-in**. We record *counts only* — never code, never the question text —\n * comparing the context tokens vg returned against a grep/read baseline estimate.\n * `vg savings` reports it with the assumptions shown; figures are labelled\n * estimates, never a hero number.\n *\n * Each entry also carries which path served the call (`source`: an MCP tool call\n * vs a `vg <subcommand>` CLI invocation) and, when known, a coarse `client` label\n * (the AI on the other end). That powers the command-vs-MCP split and the\n * per-client breakdown in `vg savings`, and is the basis for the opt-in\n * `vg serve --share-stats` upload (see ./stats-share.ts). Nothing here leaves the\n * machine unless the operator explicitly enables sharing.\n */\n\nconst LEDGER = 'savings.jsonl';\n// A conservative, documented estimate: tokens an agent reads per file it opens.\nexport const PER_FILE_TOKENS = 400;\n\n/** The tools whose grep/read token baseline the savings summary is computed from.\n * search_symbols belongs here: it is the direct grep replacement (the server\n * instructions steer agents to it INSTEAD of grep), yet it used to contribute\n * zero to the estimate — on search-heavy sessions most of the real saving went\n * uncounted. Its baseline is the same measure as query_graph's: the distinct\n * files its matches point at, at PER_FILE_TOKENS each. */\nexport const SAVINGS_TOOLS = new Set(['query_graph', 'get_node', 'search_symbols']);\n\n/**\n * How a navigation call reached the map:\n * - `mcp` — a tool call over the local `vg serve` MCP server;\n * - `cli` — a `vg <subcommand>` invocation that identified itself with `--client`.\n * Both are recorded into one ledger under a shared tool vocabulary (CLI\n * subcommands are normalised to their MCP tool names via CLI_TOOL_ALIASES), so\n * `(tool, source)` is the command-vs-MCP split and the token math stays unified.\n * Absent on ledger lines written before sources existed → read as `mcp` (the\n * only path that recorded then).\n */\nexport type Source = 'mcp' | 'cli';\n\n/**\n * Canonical tool name a CLI navigation subcommand maps to — the same vocabulary\n * the MCP tools use, so a `vg ask --client=claude` and an MCP `query_graph` call\n * land on one row distinguished only by `source`. A subcommand with no MCP twin\n * (e.g. `tree`) keeps its own name.\n */\nexport const CLI_TOOL_ALIASES: Readonly<Record<string, string>> = {\n ask: 'query_graph',\n show: 'get_node',\n impact: 'impact_of',\n path: 'find_path',\n hubs: 'list_hubs',\n areas: 'list_areas',\n tree: 'tree',\n};\n\n/**\n * Normalise a free-form client name (from `--client` or the MCP `initialize`\n * handshake) to a short, bounded, non-PII token: lowercase, `[a-z0-9._-]` only,\n * ≤ 40 chars. Never carries arbitrary user input into the ledger or an upload —\n * it is a coarse client label (e.g. `claude`, `cursor`, `cline`), not identity.\n * Returns `'unknown'` when nothing usable is provided.\n */\nexport function sanitizeClient(name: string | undefined | null): string {\n if (typeof name !== 'string') return 'unknown';\n const cleaned = name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40);\n return cleaned || 'unknown';\n}\n\n/**\n * Outcome of a recorded navigation call:\n * - `complete` — returned results, with nothing capped or paginated;\n * - `partial` — returned results, but more were available/truncated;\n * - `miss` — returned no result (no match, not-found, not-connected).\n */\nexport type Outcome = 'complete' | 'partial' | 'miss';\n\nexport interface SavingEntry {\n ts: number; // epoch ms (runtime ledger state, not part of any artifact)\n tool: string;\n // Optional for back-compat with ledger lines written before outcomes existed;\n // an absent value is read as `complete` (those lines only recorded hits).\n outcome?: Outcome;\n vgTokens: number;\n baselineTokens: number;\n // Optional for back-compat: absent `source` reads as `mcp`. `client` is a\n // sanitized coarse label (see sanitizeClient) or absent when unidentified.\n source?: Source;\n client?: string;\n // The model that made the call, for per-model savings auditing. `provider` is\n // a coarse provider label (e.g. `anthropic`, `ollama`), `model` the sanitized\n // model slug. VG Code sets both so `vg savings` can break usage down per model.\n // Absent on lines from callers that don't identify a model.\n provider?: string;\n model?: string;\n // Wall time of the call, ms. Optional: absent on lines written before timing\n // existed (and on CLI-sourced lines) — absent means \"not measured\", never 0.\n ms?: number;\n}\n\n/**\n * Normalise a model slug to a bounded, non-PII token — like {@link sanitizeClient}\n * but keeping the `/` and `:` that model ids use (`anthropic/claude-3.5-sonnet`,\n * `qwen2.5-coder:7b`). Returns undefined when nothing usable is given.\n */\nexport function sanitizeModelId(name: string | undefined | null): string | undefined {\n if (typeof name !== 'string') return undefined;\n const cleaned = name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._:/-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60);\n return cleaned || undefined;\n}\n\n/**\n * Record a CLI navigation call (`vg <subcommand> --client=<ai>`) into the same\n * local ledger the MCP path uses. Only ever called when the caller passed\n * `--client` — i.e. an AI host explicitly identified itself — so a human's bare\n * `vg ask` still records nothing. Counts only; never the question or code.\n */\nexport function recordCliCall(\n root: string,\n entry: { tool: string; client?: string; provider?: string; model?: string; outcome: Outcome; vgTokens?: number; baselineFiles?: number },\n now: number,\n): void {\n recordSaving(\n root,\n {\n tool: entry.tool,\n source: 'cli',\n client: sanitizeClient(entry.client),\n provider: entry.provider ? sanitizeClient(entry.provider) : undefined,\n model: sanitizeModelId(entry.model),\n outcome: entry.outcome,\n vgTokens: entry.vgTokens ?? 0,\n baselineTokens: (entry.baselineFiles ?? 0) * PER_FILE_TOKENS,\n },\n now,\n );\n}\n\n/**\n * Absolute path of the local usage ledger for this repo. Exported so the serve\n * status display can tail it live (mcp/ledger-tail.ts) — the file itself stays\n * local-only (GUARDRAILS §3.4; upload is the separate opt-in stats-share path).\n */\nexport function savingsLedgerPath(root: string): string {\n return path.join(cacheDir(root), LEDGER);\n}\n\nfunction ledgerPath(root: string): string {\n return savingsLedgerPath(root);\n}\n\n/** Whether a savings ledger exists for this repo (i.e. `vg serve --savings` has recorded). */\nexport function savingsRecorded(root: string): boolean {\n return fs.existsSync(ledgerPath(root));\n}\n\n/**\n * Delete the recorded usage data for this repo: the ledger itself plus the\n * stats-share state that indexes into it (a byte offset into the ledger and the\n * random per-install id) — a stale offset against a fresh ledger would silently\n * skip new entries, and clearing \"my data\" should also reset the id. Everything\n * removed lives under `.vibgrate/cache/`; nothing else is touched. Returns\n * whether a ledger existed.\n */\nexport function clearSavings(root: string): boolean {\n const file = ledgerPath(root);\n const existed = fs.existsSync(file);\n fs.rmSync(file, { force: true });\n fs.rmSync(path.join(cacheDir(root), 'stats-share.json'), { force: true });\n return existed;\n}\n\nexport function recordSaving(root: string, entry: Omit<SavingEntry, 'ts'>, now: number): void {\n try {\n fs.mkdirSync(cacheDir(root), { recursive: true });\n const line = JSON.stringify({ ts: now, ...entry });\n fs.appendFileSync(ledgerPath(root), line + '\\n');\n } catch {\n /* never let telemetry break a tool call */\n }\n}\n\nexport interface SavingsReport {\n enabled: boolean;\n days: number;\n queries: number;\n vgTokens: number;\n baselineTokens: number;\n ratio: number;\n estCostVg: number;\n estCostBaseline: number;\n saved: number;\n rateLabel: string;\n}\n\n// Published-style input rate ($/1M tokens), shipped with the CLI. Labelled\n// estimate; the user can pass their own model rate.\nconst DEFAULT_RATE_PER_M = 3.0; // e.g. a mid-tier model input rate\nconst DEFAULT_RATE_LABEL = 'input @ $3/1M';\n\nexport function readSavings(root: string, days: number, now: number, ratePerM = DEFAULT_RATE_PER_M): SavingsReport {\n const file = ledgerPath(root);\n const cutoff = now - days * 24 * 60 * 60 * 1000;\n let queries = 0;\n let vgTokens = 0;\n let baselineTokens = 0;\n if (fs.existsSync(file)) {\n for (const line of fs.readFileSync(file, 'utf8').split('\\n')) {\n if (!line.trim()) continue;\n try {\n const e = JSON.parse(line) as SavingEntry;\n if (e.ts < cutoff) continue;\n // The token-savings figures compare only the tools with a meaningful\n // grep/read baseline; the full per-command breakdown lives in readUsage.\n if (!SAVINGS_TOOLS.has(e.tool)) continue;\n queries++;\n vgTokens += e.vgTokens;\n baselineTokens += e.baselineTokens;\n } catch {\n /* skip corrupt line */\n }\n }\n }\n const estCostVg = (vgTokens / 1e6) * ratePerM;\n const estCostBaseline = (baselineTokens / 1e6) * ratePerM;\n return {\n enabled: savingsRecorded(root),\n days,\n queries,\n vgTokens,\n baselineTokens,\n ratio: vgTokens > 0 ? Math.round((baselineTokens / vgTokens) * 100) / 100 : 0,\n estCostVg: round2(estCostVg),\n estCostBaseline: round2(estCostBaseline),\n saved: round2(estCostBaseline - estCostVg),\n rateLabel: DEFAULT_RATE_LABEL,\n };\n}\n\nfunction round2(x: number): number {\n return Math.round(x * 100) / 100;\n}\n\n/** Token + cost savings attributed to one model (VG Code per-model auditing). */\nexport interface ModelSaving {\n /** `provider/model`, the ledger's per-model key. */\n key: string;\n provider: string;\n model: string;\n queries: number;\n vgTokens: number;\n baselineTokens: number;\n saved: number;\n}\n\n/**\n * Per-model breakdown of the token-savings figures — the basis of \"full savings\n * auditing per model\". Only entries that carry a `model` and are savings-baseline\n * tools contribute, so it lines up with the headline `readSavings` totals.\n * Sorted by dollars saved (desc), then key.\n */\nexport function readModelSavings(root: string, days: number, now: number, ratePerM = DEFAULT_RATE_PER_M): ModelSaving[] {\n const file = ledgerPath(root);\n const cutoff = now - days * 24 * 60 * 60 * 1000;\n const byModel = new Map<string, { provider: string; model: string; queries: number; vg: number; base: number }>();\n if (fs.existsSync(file)) {\n for (const line of fs.readFileSync(file, 'utf8').split('\\n')) {\n if (!line.trim()) continue;\n try {\n const e = JSON.parse(line) as SavingEntry;\n if (e.ts < cutoff || !e.model || !SAVINGS_TOOLS.has(e.tool)) continue;\n const provider = e.provider ?? 'unknown';\n const key = `${provider}/${e.model}`;\n const row = byModel.get(key) ?? { provider, model: e.model, queries: 0, vg: 0, base: 0 };\n row.queries++;\n row.vg += e.vgTokens;\n row.base += e.baselineTokens;\n byModel.set(key, row);\n } catch {\n /* skip corrupt line */\n }\n }\n }\n return [...byModel.entries()]\n .map(([key, r]) => ({\n key,\n provider: r.provider,\n model: r.model,\n queries: r.queries,\n vgTokens: r.vg,\n baselineTokens: r.base,\n saved: round2(((r.base - r.vg) / 1e6) * ratePerM),\n }))\n .sort((a, b) => b.saved - a.saved || a.key.localeCompare(b.key));\n}\n\n/** Per-command usage stats over the ledger window (all recorded tools). */\nexport interface CommandStat {\n tool: string;\n calls: number;\n complete: number;\n partial: number;\n miss: number;\n /** (complete + partial) / calls, as a whole-number percentage. */\n successPct: number;\n /** Mean wall time over the calls that recorded one; null when none did. */\n avgMs: number | null;\n}\n\n/** Calls attributed to one dimension value (a source, or a client). */\nexport interface DimensionStat {\n key: string;\n calls: number;\n complete: number;\n partial: number;\n miss: number;\n successPct: number;\n}\n\nexport interface UsageReport {\n enabled: boolean;\n days: number;\n /** One row per tool used, ordered by call count (desc), then name. */\n commands: CommandStat[];\n /** The command-vs-MCP split: calls grouped by `source` (`cli` / `mcp`). */\n sources: DimensionStat[];\n /** Which AI is calling: calls grouped by coarse `client` label. */\n clients: DimensionStat[];\n /** Column sums across all commands. */\n totals: { calls: number; complete: number; partial: number; miss: number };\n /** The mean of the per-command success percentages (each command weighted equally). */\n avgSuccessPct: number;\n}\n\ninterface OutcomeCounts {\n complete: number;\n partial: number;\n miss: number;\n}\n\n/** Turn a name→outcome-count map into sorted DimensionStat rows. */\nfunction toDimensionStats(byKey: Map<string, OutcomeCounts>): DimensionStat[] {\n return [...byKey.entries()]\n .map(([key, r]) => {\n const calls = r.complete + r.partial + r.miss;\n return {\n key,\n calls,\n complete: r.complete,\n partial: r.partial,\n miss: r.miss,\n successPct: calls ? Math.round(((r.complete + r.partial) / calls) * 100) : 0,\n };\n })\n .sort((a, b) => b.calls - a.calls || a.key.localeCompare(b.key));\n}\n\n/**\n * Per-command breakdown of recorded navigation calls: how often each tool was\n * used and how those calls resolved (complete / partial / miss), plus column\n * totals and the average success rate. Complements the token-savings summary —\n * this counts *every* recorded tool, not just the grep-baseline ones.\n */\nexport function readUsage(root: string, days: number, now: number): UsageReport {\n const file = ledgerPath(root);\n const cutoff = now - days * 24 * 60 * 60 * 1000;\n const byTool = new Map<string, OutcomeCounts>();\n const bySource = new Map<string, OutcomeCounts>();\n const byClient = new Map<string, OutcomeCounts>();\n // Per-tool timing over the entries that recorded a duration (older ledger\n // lines and CLI-sourced calls carry none — \"not measured\", never zero).\n const msByTool = new Map<string, { sum: number; n: number }>();\n const bump = (m: Map<string, OutcomeCounts>, key: string, outcome: Outcome): void => {\n const row = m.get(key) ?? { complete: 0, partial: 0, miss: 0 };\n row[outcome]++;\n m.set(key, row);\n };\n if (fs.existsSync(file)) {\n for (const line of fs.readFileSync(file, 'utf8').split('\\n')) {\n if (!line.trim()) continue;\n try {\n const e = JSON.parse(line) as SavingEntry;\n if (e.ts < cutoff) continue;\n const outcome: Outcome = e.outcome ?? 'complete';\n // Back-compat: lines written before these dims existed are MCP calls\n // from an unidentified client.\n bump(byTool, e.tool, outcome);\n bump(bySource, e.source ?? 'mcp', outcome);\n bump(byClient, e.client ?? 'unknown', outcome);\n if (typeof e.ms === 'number' && e.ms >= 0) {\n const timing = msByTool.get(e.tool) ?? { sum: 0, n: 0 };\n timing.sum += e.ms;\n timing.n++;\n msByTool.set(e.tool, timing);\n }\n } catch {\n /* skip corrupt line */\n }\n }\n }\n const commands: CommandStat[] = toDimensionStats(byTool).map((d) => {\n const timing = msByTool.get(d.key);\n return {\n tool: d.key,\n calls: d.calls,\n complete: d.complete,\n partial: d.partial,\n miss: d.miss,\n successPct: d.successPct,\n avgMs: timing && timing.n > 0 ? Math.round(timing.sum / timing.n) : null,\n };\n });\n const totals = commands.reduce(\n (t, c) => ({\n calls: t.calls + c.calls,\n complete: t.complete + c.complete,\n partial: t.partial + c.partial,\n miss: t.miss + c.miss,\n }),\n { calls: 0, complete: 0, partial: 0, miss: 0 },\n );\n const avgSuccessPct = commands.length\n ? Math.round(commands.reduce((s, c) => s + c.successPct, 0) / commands.length)\n : 0;\n return {\n enabled: savingsRecorded(root),\n days,\n commands,\n sources: toDimensionStats(bySource),\n clients: toDimensionStats(byClient),\n totals,\n avgSuccessPct,\n };\n}\n","/**\n * Graph-grounded context assembly for `vg code` (VG-CLI-CODE §3).\n *\n * A generic coding agent starts blind and reconstructs structure by grepping and\n * reading whole files — which is exactly what blows the context window and\n * degrades the model. This module instead uses the deterministic code graph to\n * hand the planner a *small, high-signal, budget-bounded* context: the symbols\n * most relevant to the instruction, their immediate relations, the blast radius\n * of changing them, and any declared facts (hard constraints) that must not be\n * dropped by later compaction. Deterministic given a graph + instruction, so it\n * is fully offline-testable and benchmarkable.\n */\n\nimport { conceptMapLines, extractLiteralNeedles, queryGraph } from '../engine/query.js';\nimport type { RelevanceAnalysis } from '../engine/relevance-provider.js';\nimport { indexFor } from '../engine/relations.js';\nimport { impactOf } from '../engine/impact.js';\nimport type { CodeContext } from './types.js';\nimport type { GraphNode, VgGraph } from '../schema.js';\nimport { userAskFromInstruction } from '../engine/user-ask.js';\n\nexport interface BuildContextOptions {\n /** Approx token budget for the rendered block (default 3000). */\n budget?: number;\n /** How many retrieval seeds to expand (default 8). */\n seeds?: number;\n /** Impact BFS depth for the blast radius (default 2). */\n impactDepth?: number;\n /** Restrict the edit surface to these files (from `--file`), if given. */\n files?: string[];\n /** Optional pre-computed relevance analysis (engine/relevance-provider.ts),\n * loaded by the async caller; widens seed vocabulary deterministically. */\n relevance?: RelevanceAnalysis | null;\n /** Optional per-node topic tags (engine/relevance-enrich.ts). */\n topicTags?: Map<string, readonly string[]> | null;\n /** The previous conversational ask (multi-turn `vg code`). Its content\n * terms join seed ranking at a damped weight so follow-ups (\"do we\n * support direct debits?\" after \"where is stripe used?\") stay anchored to\n * the conversation's topic. Absent → single-turn behaviour, unchanged. */\n priorInstruction?: string | null;\n}\n\n/**\n * Build the context block for a coding instruction. The ordering is\n * cache-stable by design (see router.ts): the invariant, repo-derived material\n * (facts, symbols, relations) comes first and the volatile instruction is\n * echoed last, so a provider's prompt cache can reuse the stable prefix across\n * turns.\n */\nexport function buildCodeContext(graph: VgGraph, instruction: string, options: BuildContextOptions = {}): CodeContext {\n const budget = options.budget ?? 3000;\n const seedLimit = options.seeds ?? 8;\n const impactDepth = options.impactDepth ?? 2;\n const index = indexFor(graph);\n\n // Hosts (VS Code panel) append a \"User attachments\" block with backticked\n // filenames/paths. Ranking and literal-locate pins must use only the user's\n // ask — otherwise `image.png` becomes a hard constraint that aborts the task.\n // The full instruction (with attachments) still goes in the Task section.\n const ask = userAskFromInstruction(instruction);\n const priorAsk = options.priorInstruction\n ? userAskFromInstruction(options.priorInstruction)\n : options.priorInstruction;\n\n // Retrieval seeds: reuse the deterministic lexical/structural retrieval that\n // backs `vg ask`. When `--file` narrows the surface, keep only seeds in those\n // files (but still let impact reach outside them, so the review is honest).\n // URL / quoted-string needles are stripped inside queryGraph so path tokens\n // cannot poison seeds (dash→dashboard, exist→NonExisting, …).\n const q = queryGraph(graph, ask, {\n budget: Math.floor(budget * 0.6),\n limit: seedLimit * 2,\n relevance: options.relevance,\n topicTags: options.topicTags,\n priorQuestion: priorAsk,\n });\n let seeds = q.matches.map((m) => ({ node: m.node, why: m.why }));\n if (options.files && options.files.length) {\n const set = new Set(options.files.map(normalize));\n const inScope = seeds.filter((s) => set.has(normalize(s.node.file)));\n // If nothing matched inside the named files, keep the best global seeds but\n // still steer target files to what the caller asked for.\n if (inScope.length) seeds = inScope;\n }\n seeds = seeds.slice(0, seedLimit);\n\n // Blast radius: who depends on the seeds. This is the impact-aware review\n // signal — an edit to a hub is riskier and the context says so.\n const impacted = new Map<string, { node: GraphNode; via: string }>();\n for (const s of seeds) {\n const impact = impactOf(graph, s.node.id, { depth: impactDepth });\n for (const item of impact.affected.slice(0, 6)) {\n const node = index.node(item.id);\n if (node && !impacted.has(node.id)) impacted.set(node.id, { node, via: s.node.qualifiedName });\n }\n }\n\n // Target files: the seed files (or the explicit --file set), stable order.\n const targetFiles = options.files?.length\n ? [...new Set(options.files.map(normalize))].sort()\n : [...new Set(seeds.map((s) => s.node.file))].sort();\n\n // Pinned facts: declared invariants/contracts that touch the seeds. These are\n // hard constraints; they are surfaced explicitly and never summarized away.\n const seedIds = new Set(seeds.map((s) => s.node.id));\n const pinnedFacts = [\n ...literalNeedleFacts(ask),\n ...pinnedFactsFor(graph, seedIds),\n ];\n\n const conceptMap = conceptMapLines(ask, options.relevance, priorAsk);\n const rendered = render(instruction, seeds, [...impacted.values()], targetFiles, pinnedFacts, conceptMap, index, budget);\n return {\n instruction,\n seeds,\n targetFiles,\n impacted: [...impacted.values()],\n pinnedFacts,\n conceptMap,\n rendered,\n tokensEstimate: estimateTokens(rendered),\n };\n}\n\n/** Pin URL / quoted needles so the agent does not treat path tokens as symbols. */\nfunction literalNeedleFacts(ask: string): string[] {\n const needles = extractLiteralNeedles(ask);\n if (!needles.length) return [];\n return needles.map(\n (n) =>\n `literal-locate: search the workspace for the exact string \\`${n}\\` (use search_code with the quoted needle). This is not a graph symbol name. If there are zero hits, report that honestly and finish — do not invent an edit.`,\n );\n}\n\nfunction pinnedFactsFor(graph: VgGraph, seedIds: Set<string>): string[] {\n if (!graph.facts?.length) return [];\n const out: string[] = [];\n for (const f of graph.facts) {\n if (f.kind === 'characterization') continue; // keep hard constraints only\n if (!f.subjectIds.some((id) => seedIds.has(id))) continue;\n const subjects = f.subjectIds\n .map((id) => graph.nodes.find((n) => n.id === id)?.qualifiedName ?? id)\n .join(', ');\n out.push(`${f.kind}: ${subjects} — ${JSON.stringify(f.predicate)}`);\n }\n return out.sort().slice(0, 12);\n}\n\nfunction render(\n instruction: string,\n seeds: { node: GraphNode; why: string }[],\n impacted: { node: GraphNode; via: string }[],\n targetFiles: string[],\n pinnedFacts: string[],\n conceptMap: string[],\n index: ReturnType<typeof indexFor>,\n budget: number,\n): string {\n const lines: string[] = [];\n lines.push('# Repository context (from the deterministic code graph)');\n lines.push('');\n\n if (pinnedFacts.length) {\n lines.push('## Hard constraints (do not violate)');\n for (const f of pinnedFacts) lines.push(`- ${f}`);\n lines.push('');\n }\n\n if (conceptMap.length) {\n lines.push('## How the ask was interpreted');\n for (const l of conceptMap) lines.push(l);\n lines.push('');\n }\n\n lines.push('## Relevant symbols');\n for (const { node, why } of seeds) {\n const block: string[] = [];\n block.push(`### ${node.qualifiedName} (${node.kind}, ${node.file}:${node.span.start}-${node.span.end})`);\n if (node.signature) block.push('`' + node.signature + '`');\n const callees = uniqueNames(index.callees(node.id).map((x) => x.node.qualifiedName)).slice(0, 6);\n const callers = uniqueNames(index.callers(node.id).map((x) => x.node.qualifiedName)).slice(0, 6);\n if (callees.length) block.push(`calls: ${callees.join(', ')}`);\n if (callers.length) block.push(`called by: ${callers.join(', ')}`);\n block.push(`importance ${node.importance.toFixed(3)}${node.isHub ? ' · hub (high blast radius)' : ''} · ${why}`);\n block.push('');\n const candidate = lines.concat(block).join('\\n');\n if (estimateTokens(candidate) > budget && lines.length > 3) break;\n lines.push(...block);\n }\n\n if (impacted.length) {\n lines.push('## Blast radius (would be affected by a change here)');\n for (const { node, via } of impacted.slice(0, 10)) {\n lines.push(`- ${node.qualifiedName} (${node.file}:${node.span.start}) — depends on ${via}`);\n }\n lines.push('');\n }\n\n lines.push('## Files in scope for this edit');\n for (const f of targetFiles) lines.push(`- ${f}`);\n lines.push('');\n\n lines.push('## Task');\n lines.push(instruction);\n return lines.join('\\n');\n}\n\nfunction uniqueNames(xs: string[]): string[] {\n return [...new Set(xs)];\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n","/**\n * Source-bearing Task Capsule compiler (Fusion Runtime Phase 0).\n *\n * Today's {@link buildCodeContext} pays for graph metadata, then the model still\n * calls `read_file` — double payment. This module compiles a Task Capsule that\n * includes exact source ranges (from Tree-sitter spans already on graph nodes)\n * so the first inference can solve without navigation tool calls (ZNS@1 path).\n *\n * Deterministic given (graph, instruction, file contents, options). Injectable\n * `readFile` keeps unit tests offline and pure.\n *\n * Schema: docs/fusion/task-capsule-v0.schema.json\n */\n\nimport { queryGraph } from '../engine/query.js';\nimport { indexFor } from '../engine/relations.js';\nimport { impactOf } from '../engine/impact.js';\nimport { hashString } from '../engine/hash.js';\nimport type { GraphNode, VgGraph } from '../schema.js';\nimport type { CodeContext } from './types.js';\nimport { buildCodeContext, type BuildContextOptions } from './context.js';\n\nexport const TASK_CAPSULE_SCHEMA_VERSION = 'task-capsule/0' as const;\n/** Frozen ranking policy id — bump when the heuristic changes (benchmark gate). */\n/** Bumped 2026.07.1: strip URL/quoted needles from seed ranking (no path-token false positives). */\n/** Bumped 2026.08.1: term roles (weak process verbs never seed alone), concept/bigram\n * expansion (payments→stripe, \"direct debit\"→sepa/bacs/mandate), multi-term coverage\n * bonus, directory-segment evidence — gated by the ask-quality corpus (bench/ask-corpus.mjs). */\n/** Bumped 2026.08.2: optional relevance-provider seam — sanitized provider expansions\n * join term preparation (own 0..1 weight capped at EXPANSION_WEIGHT; weak-provenance\n * dropped); provider version recorded as `relevanceVersion` provenance. Absent\n * provider = 2026.08.1 behaviour exactly — gated by the same corpus, dual-mode. */\n/** Bumped 2026.08.3: multi-turn field report (\"do we support direct debits?\" after a\n * stripe ask seeded direct* distractors). (a) Tokens consumed by a fired bigram\n * concept are demoted to the weak role — \"direct\" corroborates, never seeds.\n * (b) Conversation carry-over: the previous ask's content terms join ranking at\n * CARRY_WEIGHT when the caller passes `priorInstruction`. (c) A plain-language\n * \"how the ask was interpreted\" concept map is rendered for small local models.\n * No prior instruction + no bigram ask = 2026.08.2 behaviour exactly. */\nexport const CAPSULE_RANKING_VERSION = 'capsule-rank@2026.08.3' as const;\nexport const CAPSULE_COMPILER_ID = 'vg-task-capsule/0' as const;\n\nexport interface BuildCapsuleOptions extends BuildContextOptions {\n /**\n * Read file contents relative to the repository root. Required for source\n * slices; when omitted, the capsule still builds metadata + empty slices\n * (useful for schema/shape tests).\n */\n readFile?: (relativePath: string) => string | null;\n /** Extra lines of context around each symbol span (default 1). */\n padding?: number;\n /** Max source slices after merge (default 12). */\n maxSlices?: number;\n repositoryId?: string | null;\n /** Optional provenance from the Model Execution Profile / security ladder. */\n provenance?: CapsuleProvenanceExtras;\n /**\n * Extra pinned facts (e.g. high-confidence federation bridge edges) appended\n * after graph-derived facts. Secret-free, short strings only.\n */\n extraPinnedFacts?: string[];\n}\n\nexport interface CapsuleSymbolRef {\n id: string;\n qualifiedName: string;\n kind: string;\n file: string;\n span: { start: number; end: number };\n signature?: string | null;\n why: string;\n importance: number;\n}\n\nexport interface SourceSlice {\n file: string;\n start: number;\n end: number;\n content: string;\n contentHash: string;\n symbolIds: string[];\n}\n\nexport interface CapsuleRelationship {\n kind: 'calls' | 'called-by' | 'impacts' | 'contains' | 'other';\n from: string;\n to: string;\n}\n\nexport interface VerificationPlan {\n syntaxFiles: string[];\n suggestedTests: string[];\n notes: string[];\n}\n\nexport interface TaskCapsule {\n schemaVersion: typeof TASK_CAPSULE_SCHEMA_VERSION;\n instruction: string;\n primary: CapsuleSymbolRef[];\n supporting: CapsuleSymbolRef[];\n sourceSlices: SourceSlice[];\n relationships: CapsuleRelationship[];\n pinnedFacts: string[];\n /** Plain-language interpretation of the ask (concept expansions, relevance\n * topics, carried prior-turn terms) — see engine/query.ts conceptMapLines. */\n conceptMap: string[];\n targetFiles: string[];\n verificationPlan: VerificationPlan;\n rendered: string;\n tokensEstimate: number;\n provenance: {\n compiler: string;\n rankingVersion: string;\n graphCorpusHash: string | null;\n repositoryId: string | null;\n /** Model Execution Profile id when resolved (Fusion Phase 4/7). */\n modelProfileId?: string | null;\n /** Security tier for shell during this task. */\n securityTier?: string | null;\n /** Frozen policy / ranking patch id if any. */\n policyVersion?: string | null;\n /** Version of the optional relevance provider that widened seed\n * vocabulary for this capsule, or null when none was active. */\n relevanceVersion?: string | null;\n };\n}\n\nexport interface CapsuleProvenanceExtras {\n modelProfileId?: string | null;\n securityTier?: string | null;\n policyVersion?: string | null;\n}\n\n/** Host-safe capsule summary for VS Code / stream-json capsule transparency. */\nexport interface CapsuleSummary {\n schemaVersion: string;\n instruction: string;\n primary: Array<{ qualifiedName: string; file: string; kind: string }>;\n supporting: Array<{ qualifiedName: string; file: string; kind: string }>;\n sourceSliceCount: number;\n sourceFiles: string[];\n tokensEstimate: number;\n rankingVersion: string;\n /** Truncated rendered capsule for display (not the full prompt dump). */\n preview: string;\n}\n\n/** Host-safe capsule summary (capsule transparency UI / stream-json). */\nexport function summarizeCapsule(capsule: TaskCapsule): CapsuleSummary {\n const sourceFiles = [...new Set(capsule.sourceSlices.map((s) => s.file))].sort();\n const preview = capsule.rendered.length > 4000 ? `${capsule.rendered.slice(0, 4000)}\\n… (truncated)` : capsule.rendered;\n return {\n schemaVersion: capsule.schemaVersion,\n instruction: capsule.instruction,\n primary: capsule.primary.map((p) => ({ qualifiedName: p.qualifiedName, file: p.file, kind: p.kind })),\n supporting: capsule.supporting.map((p) => ({ qualifiedName: p.qualifiedName, file: p.file, kind: p.kind })),\n sourceSliceCount: capsule.sourceSlices.length,\n sourceFiles,\n tokensEstimate: capsule.tokensEstimate,\n rankingVersion: capsule.provenance.rankingVersion,\n preview,\n };\n}\n\n/**\n * Compile a source-bearing Task Capsule. Reuses the same seed / impact /\n * fact-pinning path as {@link buildCodeContext}, then attaches exact source\n * slices and a verification sketch.\n */\nexport function buildTaskCapsule(graph: VgGraph, instruction: string, options: BuildCapsuleOptions = {}): TaskCapsule {\n const base = buildCodeContext(graph, instruction, options);\n const padding = options.padding ?? 1;\n const maxSlices = options.maxSlices ?? 12;\n const budget = options.budget ?? 3000;\n const index = indexFor(graph);\n\n const primary = base.seeds.map((s) => toRef(s.node, s.why));\n const primaryIds = new Set(primary.map((p) => p.id));\n\n const supporting: CapsuleSymbolRef[] = [];\n for (const { node, via } of base.impacted) {\n if (primaryIds.has(node.id)) continue;\n supporting.push(toRef(node, `depends on ${via}`));\n }\n\n const relationships = collectRelationships(base, index);\n const sourceSlices = options.readFile\n ? buildSourceSlices(\n [...base.seeds.map((s) => s.node), ...base.impacted.map((i) => i.node)],\n options.readFile,\n padding,\n maxSlices,\n )\n : [];\n\n const extraFacts = (options.extraPinnedFacts ?? []).filter((f) => typeof f === 'string' && f.trim());\n const pinnedFacts = [...base.pinnedFacts, ...extraFacts];\n const verificationPlan = buildVerificationPlan(graph, base);\n const rendered = renderCapsule(instruction, primary, supporting, sourceSlices, pinnedFacts, base.conceptMap, base.targetFiles, verificationPlan, relationships, budget);\n\n return {\n schemaVersion: TASK_CAPSULE_SCHEMA_VERSION,\n instruction,\n primary,\n supporting,\n sourceSlices,\n relationships,\n pinnedFacts,\n conceptMap: base.conceptMap,\n targetFiles: base.targetFiles,\n verificationPlan,\n rendered,\n tokensEstimate: estimateTokens(rendered),\n provenance: {\n compiler: CAPSULE_COMPILER_ID,\n rankingVersion: CAPSULE_RANKING_VERSION,\n graphCorpusHash: graph.provenance?.corpusHash ?? null,\n repositoryId: options.repositoryId ?? null,\n modelProfileId: options.provenance?.modelProfileId ?? null,\n securityTier: options.provenance?.securityTier ?? null,\n policyVersion: options.provenance?.policyVersion ?? null,\n relevanceVersion: options.relevance?.version ?? null,\n },\n };\n}\n\n/**\n * Project a capsule into the legacy {@link CodeContext} shape so the existing\n * agent prompt path can consume it without a full rewrite (A/B flag).\n */\nexport function capsuleToCodeContext(capsule: TaskCapsule): CodeContext {\n return {\n instruction: capsule.instruction,\n seeds: capsule.primary.map((p) => ({\n node: {\n id: p.id,\n qualifiedName: p.qualifiedName,\n kind: p.kind,\n file: p.file,\n span: p.span,\n signature: p.signature ?? undefined,\n importance: p.importance,\n } as GraphNode,\n why: p.why,\n })),\n targetFiles: capsule.targetFiles,\n conceptMap: capsule.conceptMap,\n impacted: capsule.supporting.map((s) => ({\n node: {\n id: s.id,\n qualifiedName: s.qualifiedName,\n kind: s.kind,\n file: s.file,\n span: s.span,\n signature: s.signature ?? undefined,\n importance: s.importance,\n } as GraphNode,\n via: s.why.replace(/^depends on /, ''),\n })),\n pinnedFacts: capsule.pinnedFacts,\n rendered: capsule.rendered,\n tokensEstimate: capsule.tokensEstimate,\n };\n}\n\nfunction toRef(node: GraphNode, why: string): CapsuleSymbolRef {\n return {\n id: node.id,\n qualifiedName: node.qualifiedName,\n kind: node.kind,\n file: normalize(node.file),\n span: { start: node.span.start, end: node.span.end },\n signature: node.signature ?? null,\n why,\n importance: node.importance,\n };\n}\n\nfunction collectRelationships(\n base: CodeContext,\n index: ReturnType<typeof indexFor>,\n): CapsuleRelationship[] {\n const out: CapsuleRelationship[] = [];\n const seen = new Set<string>();\n const push = (kind: CapsuleRelationship['kind'], from: string, to: string) => {\n const key = `${kind}|${from}|${to}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({ kind, from, to });\n };\n\n for (const { node } of base.seeds) {\n for (const c of index.callees(node.id).slice(0, 6)) {\n push('calls', node.qualifiedName, c.node.qualifiedName);\n }\n for (const c of index.callers(node.id).slice(0, 6)) {\n push('called-by', node.qualifiedName, c.node.qualifiedName);\n }\n }\n for (const { node, via } of base.impacted.slice(0, 10)) {\n push('impacts', via, node.qualifiedName);\n }\n\n // Stable order for determinism.\n return out.sort((a, b) => a.kind.localeCompare(b.kind) || a.from.localeCompare(b.from) || a.to.localeCompare(b.to));\n}\n\nfunction buildSourceSlices(\n nodes: GraphNode[],\n readFile: (relativePath: string) => string | null,\n padding: number,\n maxSlices: number,\n): SourceSlice[] {\n // Prefer concrete symbols over file/module containers for source evidence.\n const eligible = nodes.filter((n) => !['file', 'module', 'package'].includes(n.kind));\n const byFile = new Map<string, GraphNode[]>();\n for (const n of eligible) {\n const file = normalize(n.file);\n const list = byFile.get(file) ?? [];\n list.push(n);\n byFile.set(file, list);\n }\n\n type Range = { file: string; start: number; end: number; symbolIds: string[]; score: number };\n const ranges: Range[] = [];\n\n for (const [file, fileNodes] of [...byFile.entries()].sort(([a], [b]) => a.localeCompare(b))) {\n const sorted = [...fileNodes].sort((a, b) => a.span.start - b.span.start || b.importance - a.importance);\n let current: Range | null = null;\n for (const n of sorted) {\n const start = Math.max(1, n.span.start - padding);\n const end = n.span.end + padding;\n const score = n.importance + (n.isHub ? 0.25 : 0);\n if (current && current.file === file && start <= current.end + 2) {\n current.end = Math.max(current.end, end);\n current.symbolIds.push(n.id);\n current.score = Math.max(current.score, score);\n } else {\n if (current) ranges.push(current);\n current = { file, start, end, symbolIds: [n.id], score };\n }\n }\n if (current) ranges.push(current);\n }\n\n ranges.sort((a, b) => b.score - a.score || a.file.localeCompare(b.file) || a.start - b.start);\n\n const slices: SourceSlice[] = [];\n for (const range of ranges) {\n if (slices.length >= maxSlices) break;\n const raw = readFile(range.file);\n if (raw === null) continue;\n const lines = raw.split('\\n');\n const start = Math.min(range.start, lines.length);\n const end = Math.min(range.end, lines.length);\n if (start < 1 || end < start) continue;\n const content = lines.slice(start - 1, end).join('\\n');\n slices.push({\n file: range.file,\n start,\n end,\n content,\n contentHash: hashString(content),\n symbolIds: [...new Set(range.symbolIds)].sort(),\n });\n }\n\n // Stable final order: file then start line (score only used for selection).\n return slices.sort((a, b) => a.file.localeCompare(b.file) || a.start - b.start);\n}\n\nfunction buildVerificationPlan(graph: VgGraph, base: CodeContext): VerificationPlan {\n const syntaxFiles = [...base.targetFiles].sort();\n const seedIds = new Set(base.seeds.map((s) => s.node.id));\n const suggestedTests: string[] = [];\n\n for (const n of graph.nodes) {\n if (n.kind !== 'test') continue;\n // Prefer tests that share a file with seeds or whose name mentions a seed.\n const sameFile = base.seeds.some((s) => normalize(s.node.file) === normalize(n.file));\n const nameHit = base.seeds.some((s) => n.qualifiedName.toLowerCase().includes(s.node.name.toLowerCase()));\n if (sameFile || nameHit || seedIds.has(n.id)) {\n suggestedTests.push(n.qualifiedName);\n }\n }\n suggestedTests.sort();\n\n const notes: string[] = [];\n if (!suggestedTests.length) {\n notes.push('No graph-linked tests found for seed symbols; run the nearest project test command after apply.');\n }\n if (base.impacted.some((i) => i.node.isHub || i.node.importance >= 0.7)) {\n notes.push('High-importance dependents in blast radius — prefer targeted tests before a full build.');\n }\n\n return {\n syntaxFiles,\n suggestedTests: suggestedTests.slice(0, 12),\n notes,\n };\n}\n\nfunction renderCapsule(\n instruction: string,\n primary: CapsuleSymbolRef[],\n supporting: CapsuleSymbolRef[],\n slices: SourceSlice[],\n pinnedFacts: string[],\n conceptMap: string[],\n targetFiles: string[],\n verification: VerificationPlan,\n relationships: CapsuleRelationship[],\n budget: number,\n): string {\n const lines: string[] = [];\n lines.push('# Task capsule (source-bearing, from the deterministic code graph)');\n lines.push('');\n lines.push('Use the exact source evidence below. Search or read outside it only if this capsule is insufficient.');\n lines.push('');\n\n if (pinnedFacts.length) {\n lines.push('## Hard constraints (do not violate)');\n for (const f of pinnedFacts) lines.push(`- ${f}`);\n lines.push('');\n }\n\n // Rendered before the symbol list on purpose: a small local model reads the\n // interpretation first, so the `a→b` provenance slugs on each seed line are\n // decodable instead of noise.\n if (conceptMap.length) {\n lines.push('## How the ask was interpreted');\n for (const l of conceptMap) lines.push(l);\n lines.push('');\n }\n\n lines.push('## Primary symbols');\n for (const s of primary) {\n lines.push(`- ${s.qualifiedName} (${s.kind}, ${s.file}:${s.span.start}-${s.span.end})${s.signature ? ` — \\`${s.signature}\\`` : ''} — ${s.why}`);\n }\n lines.push('');\n\n if (supporting.length) {\n lines.push('## Supporting / blast radius');\n for (const s of supporting.slice(0, 10)) {\n lines.push(`- ${s.qualifiedName} (${s.file}:${s.span.start}) — ${s.why}`);\n }\n lines.push('');\n }\n\n if (relationships.length) {\n lines.push('## Relationships');\n for (const r of relationships.slice(0, 24)) {\n lines.push(`- ${r.kind}: ${r.from} → ${r.to}`);\n }\n lines.push('');\n }\n\n lines.push('## Exact source evidence');\n if (!slices.length) {\n lines.push('_No source slices available (file reader missing or spans unreadable)._');\n lines.push('');\n } else {\n let included = 0;\n for (const slice of slices) {\n const block = [\n `### ${slice.file}:${slice.start}-${slice.end}`,\n `\\`\\`\\`${langFor(slice.file)}`,\n slice.content,\n '```',\n '',\n ];\n const candidate = [...lines, ...block, '## Task', instruction].join('\\n');\n if (estimateTokens(candidate) > budget && included > 0) break;\n lines.push(...block);\n included += 1;\n }\n }\n\n lines.push('## Files in scope');\n for (const f of targetFiles) lines.push(`- ${f}`);\n lines.push('');\n\n lines.push('## Verification plan');\n for (const f of verification.syntaxFiles) lines.push(`- syntax: ${f}`);\n for (const t of verification.suggestedTests) lines.push(`- test: ${t}`);\n for (const n of verification.notes) lines.push(`- note: ${n}`);\n lines.push('');\n\n lines.push('## Task');\n lines.push(instruction);\n return lines.join('\\n');\n}\n\nfunction langFor(file: string): string {\n const ext = file.split('.').pop()?.toLowerCase() ?? '';\n const map: Record<string, string> = {\n ts: 'ts',\n tsx: 'tsx',\n js: 'js',\n jsx: 'jsx',\n mjs: 'js',\n cjs: 'js',\n py: 'python',\n rs: 'rust',\n go: 'go',\n java: 'java',\n cs: 'csharp',\n md: 'md',\n json: 'json',\n };\n return map[ext] ?? '';\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n// Re-export query touch so tree-shaking keeps the dependency explicit for tests.\nexport const __testing = { queryGraph, impactOf };\n"]}