@vibgrate/cli 2026.825.2 → 2026.829.1

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 (129) hide show
  1. package/DOCS.md +204 -9
  2. package/README.md +2 -0
  3. package/dist/{agent-DHQYEHVW.js → agent-5GW7C7EB.js} +14 -14
  4. package/dist/{agent-DHQYEHVW.js.map → agent-5GW7C7EB.js.map} +1 -1
  5. package/dist/{approvals-KBM72NU2.js → approvals-ISJFILVK.js} +5 -5
  6. package/dist/{approvals-KBM72NU2.js.map → approvals-ISJFILVK.js.map} +1 -1
  7. package/dist/{attach-O74NL4M5.js → attach-JUSALQ75.js} +3 -3
  8. package/dist/{attach-O74NL4M5.js.map → attach-JUSALQ75.js.map} +1 -1
  9. package/dist/baseline-YL2IZZ4Y.js +9 -0
  10. package/dist/{baseline-4X6MQBDA.js.map → baseline-YL2IZZ4Y.js.map} +1 -1
  11. package/dist/{chunk-JAEHLTVX.js → chunk-5RW5PIBH.js} +3 -3
  12. package/dist/{chunk-JAEHLTVX.js.map → chunk-5RW5PIBH.js.map} +1 -1
  13. package/dist/{chunk-TT2J2TB6.js → chunk-65YN3BG3.js} +1207 -40
  14. package/dist/chunk-65YN3BG3.js.map +1 -0
  15. package/dist/{chunk-VMPKOMHG.js → chunk-B5VCPIKT.js} +7 -6
  16. package/dist/chunk-B5VCPIKT.js.map +1 -0
  17. package/dist/{chunk-FQHWPOTS.js → chunk-BA6YBVNT.js} +3 -3
  18. package/dist/{chunk-FQHWPOTS.js.map → chunk-BA6YBVNT.js.map} +1 -1
  19. package/dist/{chunk-3E7QT4NE.js → chunk-BODXEZEY.js} +9 -9
  20. package/dist/{chunk-3E7QT4NE.js.map → chunk-BODXEZEY.js.map} +1 -1
  21. package/dist/{chunk-BICZR6UJ.js → chunk-D3SV3JWB.js} +3 -3
  22. package/dist/{chunk-BICZR6UJ.js.map → chunk-D3SV3JWB.js.map} +1 -1
  23. package/dist/chunk-EGMBHPXV.js +127 -0
  24. package/dist/chunk-EGMBHPXV.js.map +1 -0
  25. package/dist/{chunk-DIZ5KI5Q.js → chunk-FHSEK64W.js} +7 -7
  26. package/dist/{chunk-DIZ5KI5Q.js.map → chunk-FHSEK64W.js.map} +1 -1
  27. package/dist/{chunk-E3XVIFSH.js → chunk-FKCN653F.js} +3 -3
  28. package/dist/{chunk-E3XVIFSH.js.map → chunk-FKCN653F.js.map} +1 -1
  29. package/dist/{chunk-OIUVWCKM.js → chunk-FPIMNVLI.js} +12 -4
  30. package/dist/chunk-FPIMNVLI.js.map +1 -0
  31. package/dist/{chunk-NS4DL3QR.js → chunk-HHMWE52J.js} +10 -135
  32. package/dist/chunk-HHMWE52J.js.map +1 -0
  33. package/dist/{chunk-5UG4UHKU.js → chunk-HUJZO4K5.js} +281 -106
  34. package/dist/chunk-HUJZO4K5.js.map +1 -0
  35. package/dist/{chunk-HFQIYM6E.js → chunk-JWQ2JCQS.js} +4 -4
  36. package/dist/{chunk-HFQIYM6E.js.map → chunk-JWQ2JCQS.js.map} +1 -1
  37. package/dist/{chunk-27TS2AUJ.js → chunk-K7QR7U3V.js} +12 -11
  38. package/dist/chunk-K7QR7U3V.js.map +1 -0
  39. package/dist/{chunk-IJVWKZRS.js → chunk-KCKG3EEJ.js} +3 -3
  40. package/dist/{chunk-IJVWKZRS.js.map → chunk-KCKG3EEJ.js.map} +1 -1
  41. package/dist/{chunk-GWSJYDK7.js → chunk-MMIIVRQC.js} +7 -7
  42. package/dist/chunk-MMIIVRQC.js.map +1 -0
  43. package/dist/chunk-N6R4XPLX.js +27 -0
  44. package/dist/chunk-N6R4XPLX.js.map +1 -0
  45. package/dist/{chunk-GR7SFCQJ.js → chunk-NQQT75AN.js} +77 -27
  46. package/dist/chunk-NQQT75AN.js.map +1 -0
  47. package/dist/{chunk-6MIJLO5B.js → chunk-NSC7ZK62.js} +3 -3
  48. package/dist/{chunk-6MIJLO5B.js.map → chunk-NSC7ZK62.js.map} +1 -1
  49. package/dist/{chunk-SYMJSRYF.js → chunk-OAYSRM7J.js} +12 -14
  50. package/dist/chunk-OAYSRM7J.js.map +1 -0
  51. package/dist/{chunk-L7GCJNDT.js → chunk-QMROD7MI.js} +15 -8
  52. package/dist/chunk-QMROD7MI.js.map +1 -0
  53. package/dist/{chunk-SHD5TCZ5.js → chunk-R2FX4USU.js} +7 -7
  54. package/dist/chunk-R2FX4USU.js.map +1 -0
  55. package/dist/{chunk-7M4E7UGX.js → chunk-RL7JYG3D.js} +3 -3
  56. package/dist/{chunk-7M4E7UGX.js.map → chunk-RL7JYG3D.js.map} +1 -1
  57. package/dist/{chunk-QLNJ3VWO.js → chunk-RRSUNTZI.js} +3 -3
  58. package/dist/{chunk-QLNJ3VWO.js.map → chunk-RRSUNTZI.js.map} +1 -1
  59. package/dist/{chunk-NZES47ST.js → chunk-TWFPHXPN.js} +3 -3
  60. package/dist/{chunk-NZES47ST.js.map → chunk-TWFPHXPN.js.map} +1 -1
  61. package/dist/chunk-UGRUG2FA.js +6 -0
  62. package/dist/{chunk-G3ACLBMG.js.map → chunk-UGRUG2FA.js.map} +1 -1
  63. package/dist/{chunk-KYM55VZX.js → chunk-VOEEYCR3.js} +6 -6
  64. package/dist/{chunk-KYM55VZX.js.map → chunk-VOEEYCR3.js.map} +1 -1
  65. package/dist/{chunk-SIXWWQ6S.js → chunk-WBDRBP22.js} +4 -4
  66. package/dist/{chunk-SIXWWQ6S.js.map → chunk-WBDRBP22.js.map} +1 -1
  67. package/dist/{chunk-K3SXWOTT.js → chunk-YL332BU2.js} +20 -15
  68. package/dist/chunk-YL332BU2.js.map +1 -0
  69. package/dist/{chunk-2NUS5BOR.js → chunk-ZQY5TWCB.js} +3 -3
  70. package/dist/{chunk-2NUS5BOR.js.map → chunk-ZQY5TWCB.js.map} +1 -1
  71. package/dist/cli.d.ts +16 -1
  72. package/dist/cli.js +2362 -342
  73. package/dist/cli.js.map +1 -1
  74. package/dist/{daemon-RZS5FPIW.js → daemon-NRIIDMX2.js} +10 -10
  75. package/dist/{daemon-RZS5FPIW.js.map → daemon-NRIIDMX2.js.map} +1 -1
  76. package/dist/embed-worker-main.js +3 -3
  77. package/dist/{ensure-map-DL2S774J.js → ensure-map-VAIYCCEJ.js} +17 -16
  78. package/dist/{ensure-map-DL2S774J.js.map → ensure-map-VAIYCCEJ.js.map} +1 -1
  79. package/dist/explain-EXPJTCB5.js +126 -0
  80. package/dist/explain-EXPJTCB5.js.map +1 -0
  81. package/dist/{graph-backend-JXARVT3R.js → graph-backend-V5A2H5ZB.js} +7 -7
  82. package/dist/{graph-backend-JXARVT3R.js.map → graph-backend-V5A2H5ZB.js.map} +1 -1
  83. package/dist/index.d.ts +217 -13
  84. package/dist/index.js +17 -16
  85. package/dist/index.js.map +1 -1
  86. package/dist/{interactive-2XRBRFRB.js → interactive-VQM2CTE2.js} +37 -32
  87. package/dist/interactive-VQM2CTE2.js.map +1 -0
  88. package/dist/load-UAVA732M.js +11 -0
  89. package/dist/{load-7C5VETRD.js.map → load-UAVA732M.js.map} +1 -1
  90. package/dist/parse-worker.js +2 -2
  91. package/dist/{rules-ASYEUNB5.js → rules-TLRGB5L4.js} +12 -4
  92. package/dist/rules-TLRGB5L4.js.map +1 -0
  93. package/dist/{run-outcome-TMB5TJNA.js → run-outcome-EATWIKLR.js} +5 -5
  94. package/dist/{run-outcome-TMB5TJNA.js.map → run-outcome-EATWIKLR.js.map} +1 -1
  95. package/dist/{runtime-session-Y23NVY7R.js → runtime-session-Y2BRBXUW.js} +9 -9
  96. package/dist/{runtime-session-Y23NVY7R.js.map → runtime-session-Y2BRBXUW.js.map} +1 -1
  97. package/dist/{session-KXT2ZTPE.js → session-N2FTYIHQ.js} +9 -9
  98. package/dist/{session-KXT2ZTPE.js.map → session-N2FTYIHQ.js.map} +1 -1
  99. package/dist/{stream-json-NW6AOE47.js → stream-json-GCZAHORX.js} +14 -14
  100. package/dist/{stream-json-NW6AOE47.js.map → stream-json-GCZAHORX.js.map} +1 -1
  101. package/dist/version-XNZ4GLMQ.js +4 -0
  102. package/dist/{version-7ABYXWOZ.js.map → version-XNZ4GLMQ.js.map} +1 -1
  103. package/dist/{vg-mcp-bridge-LXBHKEFR.js → vg-mcp-bridge-VDZWFEO2.js} +22 -11
  104. package/dist/vg-mcp-bridge-VDZWFEO2.js.map +1 -0
  105. package/dist/{vgd-RW7HCEIP.js → vgd-3A2TRNP5.js} +8 -8
  106. package/dist/vgd-3A2TRNP5.js.map +1 -0
  107. package/package.json +2 -2
  108. package/dist/baseline-4X6MQBDA.js +0 -9
  109. package/dist/chunk-27TS2AUJ.js.map +0 -1
  110. package/dist/chunk-5UG4UHKU.js.map +0 -1
  111. package/dist/chunk-G3ACLBMG.js +0 -6
  112. package/dist/chunk-GR7SFCQJ.js.map +0 -1
  113. package/dist/chunk-GWSJYDK7.js.map +0 -1
  114. package/dist/chunk-K3SXWOTT.js.map +0 -1
  115. package/dist/chunk-L7GCJNDT.js.map +0 -1
  116. package/dist/chunk-NS4DL3QR.js.map +0 -1
  117. package/dist/chunk-OIUVWCKM.js.map +0 -1
  118. package/dist/chunk-SHD5TCZ5.js.map +0 -1
  119. package/dist/chunk-SYMJSRYF.js.map +0 -1
  120. package/dist/chunk-TT2J2TB6.js.map +0 -1
  121. package/dist/chunk-VMPKOMHG.js.map +0 -1
  122. package/dist/chunk-YENM3HT7.js +0 -23
  123. package/dist/chunk-YENM3HT7.js.map +0 -1
  124. package/dist/interactive-2XRBRFRB.js.map +0 -1
  125. package/dist/load-7C5VETRD.js +0 -11
  126. package/dist/rules-ASYEUNB5.js.map +0 -1
  127. package/dist/version-7ABYXWOZ.js +0 -4
  128. package/dist/vg-mcp-bridge-LXBHKEFR.js.map +0 -1
  129. package/dist/vgd-RW7HCEIP.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { indexFor, userAskFromInstruction, queryGraph, impactOf, extractLiteralNeedles } from './chunk-K3SXWOTT.js';
1
+ import { indexFor, userAskFromInstruction, queryGraph, impactOf, extractLiteralNeedles } from './chunk-YL332BU2.js';
2
2
  import { cacheDir } from './chunk-MVPRPSXU.js';
3
3
  import { hashString } from './chunk-JFGYT6BI.js';
4
4
  import * as fs from 'fs';
@@ -249,7 +249,7 @@ function buildCodeContext(graph, instruction, options = {}) {
249
249
  ...pinnedFactsFor(graph, seedIds)
250
250
  ];
251
251
  const conceptMap = options.ranked?.conceptMap ?? [];
252
- const rendered = render(instruction, seeds, [...impacted.values()], targetFiles, pinnedFacts, conceptMap, index, budget);
252
+ const rendered = render(seeds, [...impacted.values()], targetFiles, pinnedFacts, conceptMap, index, budget);
253
253
  return {
254
254
  instruction,
255
255
  seeds,
@@ -279,7 +279,8 @@ function pinnedFactsFor(graph, seedIds) {
279
279
  }
280
280
  return out.sort().slice(0, 12);
281
281
  }
282
- function render(instruction, seeds, impacted, targetFiles, pinnedFacts, conceptMap, index, budget) {
282
+ var CONCEPT_MAP_MAX_LINES = 6;
283
+ function render(seeds, impacted, targetFiles, pinnedFacts, conceptMap, index, budget) {
283
284
  const lines = [];
284
285
  lines.push("# Repository context (from the deterministic code graph)");
285
286
  lines.push("");
@@ -290,7 +291,7 @@ function render(instruction, seeds, impacted, targetFiles, pinnedFacts, conceptM
290
291
  }
291
292
  if (conceptMap.length) {
292
293
  lines.push("## How the ask was interpreted");
293
- for (const l of conceptMap) lines.push(l);
294
+ for (const l of conceptMap.slice(0, CONCEPT_MAP_MAX_LINES)) lines.push(l);
294
295
  lines.push("");
295
296
  }
296
297
  lines.push("## Relevant symbols");
@@ -318,8 +319,6 @@ function render(instruction, seeds, impacted, targetFiles, pinnedFacts, conceptM
318
319
  lines.push("## Files in scope for this edit");
319
320
  for (const f of targetFiles) lines.push(`- ${f}`);
320
321
  lines.push("");
321
- lines.push("## Task");
322
- lines.push(instruction);
323
322
  return lines.join("\n");
324
323
  }
325
324
  function uniqueNames(xs) {
@@ -399,7 +398,7 @@ function buildTaskCapsule(graph, instruction, options = {}) {
399
398
  const extraFacts = (options.extraPinnedFacts ?? []).filter((f) => typeof f === "string" && f.trim());
400
399
  const pinnedFacts = [...base.pinnedFacts, ...extraFacts];
401
400
  const verificationPlan = buildVerificationPlan(graph, base);
402
- const rendered = renderCapsule(instruction, primary, supporting, sourceSlices, pinnedFacts, base.conceptMap, base.targetFiles, verificationPlan, relationships, budget);
401
+ const rendered = renderCapsule(primary, supporting, sourceSlices, pinnedFacts, base.conceptMap, base.targetFiles, verificationPlan, relationships, budget);
403
402
  return {
404
403
  schemaVersion: TASK_CAPSULE_SCHEMA_VERSION,
405
404
  instruction,
@@ -569,7 +568,8 @@ function buildVerificationPlan(graph, base) {
569
568
  notes
570
569
  };
571
570
  }
572
- function renderCapsule(instruction, primary, supporting, slices, pinnedFacts, conceptMap, targetFiles, verification, relationships, budget) {
571
+ var CONCEPT_MAP_MAX_LINES2 = 6;
572
+ function renderCapsule(primary, supporting, slices, pinnedFacts, conceptMap, targetFiles, verification, relationships, budget) {
573
573
  const lines = [];
574
574
  lines.push("# Context capsule (source-bearing, from the deterministic code graph)");
575
575
  lines.push("");
@@ -582,7 +582,7 @@ function renderCapsule(instruction, primary, supporting, slices, pinnedFacts, co
582
582
  }
583
583
  if (conceptMap.length) {
584
584
  lines.push("## How the ask was interpreted");
585
- for (const l of conceptMap) lines.push(l);
585
+ for (const l of conceptMap.slice(0, CONCEPT_MAP_MAX_LINES2)) lines.push(l);
586
586
  lines.push("");
587
587
  }
588
588
  lines.push("## Primary symbols");
@@ -618,7 +618,7 @@ function renderCapsule(instruction, primary, supporting, slices, pinnedFacts, co
618
618
  "```",
619
619
  ""
620
620
  ];
621
- const candidate = [...lines, ...block, "## Task", instruction].join("\n");
621
+ const candidate = [...lines, ...block].join("\n");
622
622
  if (estimateTokens2(candidate) > budget && included > 0) break;
623
623
  lines.push(...block);
624
624
  included += 1;
@@ -632,8 +632,6 @@ function renderCapsule(instruction, primary, supporting, slices, pinnedFacts, co
632
632
  for (const t of verification.suggestedTests) lines.push(`- test: ${t}`);
633
633
  for (const n of verification.notes) lines.push(`- note: ${n}`);
634
634
  lines.push("");
635
- lines.push("## Task");
636
- lines.push(instruction);
637
635
  return lines.join("\n");
638
636
  }
639
637
  function langFor(file) {
@@ -663,5 +661,5 @@ function estimateTokens2(text) {
663
661
  }
664
662
 
665
663
  export { CAPSULE_COMPILER_ID, CAPSULE_RANKING_VERSION, CLI_TOOL_ALIASES, PER_FILE_TOKENS, SAVINGS_TOOLS, TASK_CAPSULE_SCHEMA_VERSION, buildCodeContext, buildTaskCapsule, capsuleToCodeContext, capsuleTransparencyLines, clearSavings, readModelSavings, readSavings, readUsage, recordCliCall, recordSaving, sanitizeClient, savingsLedgerPath, savingsRecorded, summarizeCapsule };
666
- //# sourceMappingURL=chunk-SYMJSRYF.js.map
667
- //# sourceMappingURL=chunk-SYMJSRYF.js.map
664
+ //# sourceMappingURL=chunk-OAYSRM7J.js.map
665
+ //# sourceMappingURL=chunk-OAYSRM7J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/engine/savings.ts","../src/code/context.ts","../src/code/capsule.ts"],"names":["estimateTokens","normalize","CONCEPT_MAP_MAX_LINES"],"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,MAAM,UAAU,IAAA,CACb,IAAA,EAAK,CACL,WAAA,GACA,OAAA,CAA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A,IACL,EAAA,EAAI,QAAA;AAAA,IACJ,EAAA,EAAI,MAAA;AAAA,IACJ,EAAA,EAAI,IAAA;AAAA,IACJ,IAAA,EAAM,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-OAYSRM7J.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 { extractLiteralNeedles, queryGraph } from '../engine/query.js';\nimport type { SanitizedRank } 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 /** Sanitized module ranking (engine/relevance-provider.ts rankQuestion),\n * computed by the async caller over the user's ask — carries the seed\n * ordering AND the plain-language concept map. Absent → the mechanical\n * fallback ranks and the concept map is empty. */\n ranked?: SanitizedRank | 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\n // Retrieval seeds: the module ranking when the async caller supplied one\n // (options.ranked — the relevance engine), the mechanical fallback\n // otherwise. 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 const q = queryGraph(graph, ask, {\n budget: Math.floor(budget * 0.6),\n limit: seedLimit * 2,\n ranked: options.ranked,\n });\n // Keep every candidate here: `--file` narrows below, and capping first would\n // discard in-scope symbols ranked outside the top `seedLimit`. The cap runs\n // after the filter (as it always has), so the count is unchanged.\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 // The plain-language interpretation is authored by the relevance module\n // (and sanitized at the seam); the mechanical fallback has none to offer.\n const conceptMap = options.ranked?.conceptMap ?? [];\n const rendered = render(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\n/**\n * How many \"How the ask was interpreted\" lines the rendered block carries.\n *\n * The relevance module returns up to 24 (sanitizeRank's cap) and a verbose ask\n * genuinely produces that many — measured 8.4 lines on a normal ask against\n * 22.1 on a verbose one. Those lines share a fixed budget with the source\n * slices, so an uncapped concept map lets a long ask evict the very evidence\n * the capsule exists to carry. Six is the same cap the transparency surfaces\n * use, so a reader and the model see the ask read the same way.\n */\nconst CONCEPT_MAP_MAX_LINES = 6;\n\n/**\n * Render the context block. Like the capsule, this does NOT echo the\n * instruction: buildAgentMessages sends it as its own trailing turn, so\n * echoing it here billed it twice per step and let a long ask crowd out the\n * symbol blocks below.\n */\nfunction render(\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.slice(0, CONCEPT_MAP_MAX_LINES)) 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 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 Context 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 Context 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, multi-term coverage bonus, directory-segment evidence. */\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. */\n/** Bumped 2026.08.4: relevance relocation — the ranking engine (lexicon, term\n * roles, IDF, tiers, typo repair, morphology, diversification, concept map)\n * moved into the auto-provisioned relevance module behind the seam's\n * rankSymbols API; the host keeps mechanical name matching as the\n * module-less fallback. Seed content with the module active matches\n * 2026.08.3 + the coding-prompt-corpus improvements; the recorded\n * relevanceVersion says which engine ranked this capsule. */\nexport const CAPSULE_RANKING_VERSION = 'capsule-rank@2026.08.4' 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; why: string }>;\n supporting: Array<{ qualifiedName: string; file: string; kind: string; why: string }>;\n sourceSliceCount: number;\n sourceFiles: string[];\n tokensEstimate: number;\n rankingVersion: string;\n /**\n * How the ask was interpreted, ready to show a human: the capsule's concept\n * map with the model-facing seed-notation legend dropped and the leading\n * \"- \" bullet stripped. Empty when no relevance engine widened the ask.\n */\n interpretation: string[];\n /** Truncated rendered capsule for display (not the full prompt dump). */\n preview: string;\n}\n\n/**\n * The concept map, projected for a human surface. The rendered capsule ends its\n * concept map with a notation legend that exists so a small local model can\n * decode the `a→b` slugs on each seed line; a terminal or panel reader has the\n * `why` strings spelled out next to the symbol, so the legend is noise there.\n */\nfunction interpretationFor(conceptMap: string[]): string[] {\n return conceptMap\n .filter((line) => !/^\\s*-?\\s*Seed notation\\b/i.test(line))\n .map((line) => line.replace(/^\\s*-\\s+/, '').trim())\n .filter(Boolean);\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, why: p.why })),\n supporting: capsule.supporting.map((p) => ({ qualifiedName: p.qualifiedName, file: p.file, kind: p.kind, why: p.why })),\n sourceSliceCount: capsule.sourceSlices.length,\n sourceFiles,\n tokensEstimate: capsule.tokensEstimate,\n rankingVersion: capsule.provenance.rankingVersion,\n interpretation: interpretationFor(capsule.conceptMap),\n preview,\n };\n}\n\n/**\n * Interpretation lines shown before the seeds. Matches the VS Code panel's cap\n * so the two surfaces explain an ask the same way. Three was too few in\n * practice: the concept map orders broad taxonomy lines ahead of the specific\n * ones, so a typo repair (\"read \\\"chekout\\\" as \\\"checkout\\\"\") — the line a\n * reader who typed the typo most needs — fell past the cut.\n */\nconst TRANSPARENCY_INTERPRETATION_LINES = 6;\n/** Seeds shown with their match provenance. */\nconst TRANSPARENCY_SEED_LINES = 3;\n\n/**\n * The capsule transparency block for a text surface: how the ask was read, and\n * which symbols that reached, with the reason each one matched.\n *\n * Returns indented, ready-to-print lines (the caller applies dimming). Both\n * sections are capped — a coding session prints one of these per turn, and the\n * complete block already travels inside the capsule itself. Empty when there is\n * nothing to explain (no relevance engine active and no seeds).\n */\nexport function capsuleTransparencyLines(summary: CapsuleSummary): string[] {\n const lines: string[] = [];\n\n const interpretation = summary.interpretation ?? [];\n for (const line of interpretation.slice(0, TRANSPARENCY_INTERPRETATION_LINES)) {\n lines.push(` read: ${line}`);\n }\n const hiddenInterpretation = interpretation.length - TRANSPARENCY_INTERPRETATION_LINES;\n if (hiddenInterpretation > 0) lines.push(` read: … ${hiddenInterpretation} more`);\n\n const seeds = (summary.primary ?? []).filter((p) => p.qualifiedName);\n for (const seed of seeds.slice(0, TRANSPARENCY_SEED_LINES)) {\n // An external/module node carries no file of its own — no dangling separator.\n const where = seed.file ? ` · ${seed.file}` : '';\n const why = seed.why ? ` — ${seed.why}` : '';\n lines.push(` seed: ${seed.qualifiedName}${where}${why}`);\n }\n const hiddenSeeds = seeds.length - TRANSPARENCY_SEED_LINES;\n if (hiddenSeeds > 0) lines.push(` seed: … ${hiddenSeeds} more`);\n\n return lines;\n}\n\n/**\n * Compile a source-bearing Context 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(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.ranked?.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\n/**\n * How many \"How the ask was interpreted\" lines the rendered block carries.\n *\n * The relevance module returns up to 24 (sanitizeRank's cap) and a verbose ask\n * genuinely produces that many — measured 8.4 lines on a normal ask against\n * 22.1 on a verbose one. Those lines share a fixed budget with the source\n * slices, so an uncapped concept map lets a long ask evict the very evidence\n * the capsule exists to carry. Six is the same cap the transparency surfaces\n * use, so a reader and the model see the ask read the same way.\n */\nconst CONCEPT_MAP_MAX_LINES = 6;\n\n/**\n * Render the capsule body. The instruction is deliberately NOT echoed here:\n * every consumer (buildAgentMessages, the bench capsule arms) already sends the\n * ask as its own trailing turn, so echoing it a second time billed a long ask\n * twice on every step of a run — and, because the echo counted against this\n * budget, a verbose ask evicted the source slices that make the capsule worth\n * compiling at all. Measured at 42% capsule growth for 25%->16% evidence share\n * (docs/graph/VG-ASK-LENGTH-CAPSULE-ANALYSIS.md 3.4/3.5).\n */\nfunction renderCapsule(\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('# Context 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.slice(0, CONCEPT_MAP_MAX_LINES)) 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].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 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"]}
@@ -1,4 +1,4 @@
1
- import { userAskFromInstruction, queryGraph } from './chunk-K3SXWOTT.js';
1
+ import { userAskFromInstruction, queryGraph } from './chunk-YL332BU2.js';
2
2
 
3
3
  // src/code/capsule-mode.ts
4
4
  var WHOLE_REPO_MAX_SOURCE_TOKENS = 1500;
@@ -25,14 +25,23 @@ function askNamesSymbol(graph, instruction) {
25
25
  const q = queryGraph(graph, ask, { budget: 400, limit: 8 });
26
26
  return q.matches.some((m) => m.score >= 6);
27
27
  }
28
+ var MIN_RANK_CONFIDENCE = 1;
29
+ function rankConfidenceOf(ranked) {
30
+ if (!ranked) return null;
31
+ if (ranked.hasContent === false) return 0;
32
+ const scores = (ranked.seeds ?? []).map((s) => Number(s?.score)).filter((n) => Number.isFinite(n) && n > 0);
33
+ if (!scores.length) return null;
34
+ return Math.max(...scores);
35
+ }
28
36
  function capsuleMode(input) {
29
37
  const mass = Math.max(0, input.sourceTokens);
30
38
  if (mass <= WHOLE_REPO_MAX_SOURCE_TOKENS) return "whole-repo";
39
+ if (input.rankConfidence === 0) return "off";
31
40
  if (mass > COMPILE_MIN_SOURCE_TOKENS) return "compile";
32
41
  if (input.askNamesSymbol) return "off";
33
42
  return "off";
34
43
  }
35
- function buildWholeRepoPacket(instruction, files, budget = WHOLE_REPO_MAX_SOURCE_TOKENS) {
44
+ function buildWholeRepoPacket(files, budget = WHOLE_REPO_MAX_SOURCE_TOKENS) {
36
45
  const sorted = [...files].map((f) => ({ path: normalize(f.path), content: f.content })).filter((f) => f.path && f.content.length > 0).sort((a, b) => a.path.localeCompare(b.path));
37
46
  const sourceTokens = sourceTokenMass(sorted.map((f) => f.content));
38
47
  const lines = [
@@ -44,13 +53,11 @@ function buildWholeRepoPacket(instruction, files, budget = WHOLE_REPO_MAX_SOURCE
44
53
  const included = [];
45
54
  for (const f of sorted) {
46
55
  const block = [`### \`${f.path}\``, `\`\`\`${langFor(f.path)}`, f.content.replace(/\n$/, ""), "```", ""];
47
- const candidate = [...lines, ...block, "## Task", instruction].join("\n");
56
+ const candidate = [...lines, ...block].join("\n");
48
57
  if (included.length > 0 && estimateSourceTokens(candidate) > budget) break;
49
58
  lines.push(...block);
50
59
  included.push(f.path);
51
60
  }
52
- lines.push("## Task");
53
- lines.push(instruction);
54
61
  const rendered = lines.join("\n");
55
62
  return {
56
63
  rendered,
@@ -85,6 +92,6 @@ function langFor(file) {
85
92
  return map[ext] ?? "";
86
93
  }
87
94
 
88
- export { COMPILE_MIN_SOURCE_TOKENS, WHOLE_REPO_MAX_SOURCE_TOKENS, askNamesSymbol, buildWholeRepoPacket, capsuleMode, mappedFilePaths, sourceTokenMass };
89
- //# sourceMappingURL=chunk-L7GCJNDT.js.map
90
- //# sourceMappingURL=chunk-L7GCJNDT.js.map
95
+ export { COMPILE_MIN_SOURCE_TOKENS, MIN_RANK_CONFIDENCE, WHOLE_REPO_MAX_SOURCE_TOKENS, askNamesSymbol, buildWholeRepoPacket, capsuleMode, mappedFilePaths, rankConfidenceOf, sourceTokenMass };
96
+ //# sourceMappingURL=chunk-QMROD7MI.js.map
97
+ //# sourceMappingURL=chunk-QMROD7MI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/code/capsule-mode.ts"],"names":[],"mappings":";;;AAeO,IAAM,4BAAA,GAA+B;AAErC,IAAM,yBAAA,GAA4B;AAElC,SAAS,qBAAqB,IAAA,EAAsB;AACzD,EAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,CAAC,CAAA;AAClC;AAGO,SAAS,gBAAgB,KAAA,EAA0B;AACxD,EAAA,MAAM,KAAA,uBAAY,GAAA,EAAY;AAC9B,EAAA,KAAA,MAAW,CAAA,IAAK,MAAM,KAAA,EAAO;AAC3B,IAAA,MAAM,CAAA,GAAI,SAAA,CAAU,CAAA,CAAE,IAAI,CAAA;AAC1B,IAAA,IAAI,CAAC,CAAA,IAAK,cAAA,CAAe,CAAC,CAAA,EAAG;AAC7B,IAAA,KAAA,CAAM,IAAI,CAAC,CAAA;AAAA,EACb;AACA,EAAA,OAAO,CAAC,GAAG,KAAK,CAAA,CAAE,IAAA,EAAK;AACzB;AAEO,SAAS,gBAAgB,QAAA,EAAoC;AAClE,EAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,EAAA,KAAA,MAAW,CAAA,IAAK,QAAA,EAAU,KAAA,IAAS,CAAA,CAAE,MAAA;AACrC,EAAA,O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MROD7MI.js","sourcesContent":["/**\n * Whether to send a ranked Context Capsule, paste the mapped tree, or send\n * neither. Independent of Model Execution Profiles (those describe how a\n * local model is run). Mass × greppability, not file count.\n *\n * See docs/graph/VG-CAPSULE-SMALL-REPO-DISABLE.md.\n */\n\nimport { queryGraph } from '../engine/query.js';\nimport { userAskFromInstruction } from '../engine/user-ask.js';\nimport type { VgGraph } from '../schema.js';\n\nexport type CapsuleMode = 'off' | 'whole-repo' | 'compile';\n\n/** Trees this small are cheaper to paste (or grep) than to rank. */\nexport const WHOLE_REPO_MAX_SOURCE_TOKENS = 1_500;\n/** Above this, discovery has a real bill — always compile. */\nexport const COMPILE_MIN_SOURCE_TOKENS = 8_000;\n\nexport function estimateSourceTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/** Unique mapped paths from the graph, stable order. */\nexport function mappedFilePaths(graph: VgGraph): string[] {\n const files = new Set<string>();\n for (const n of graph.nodes) {\n const f = normalize(n.file);\n if (!f || skipMappedPath(f)) continue;\n files.add(f);\n }\n return [...files].sort();\n}\n\nexport function sourceTokenMass(contents: Iterable<string>): number {\n let bytes = 0;\n for (const c of contents) bytes += c.length;\n return Math.ceil(bytes / 4);\n}\n\n/**\n * True when the mechanical fallback would pin an identifier the ask actually\n * names (F0/F1). Does not use the relevance module.\n */\nexport function askNamesSymbol(graph: VgGraph, instruction: string): boolean {\n const ask = userAskFromInstruction(instruction);\n const q = queryGraph(graph, ask, { budget: 400, limit: 8 });\n // Score 6 = camel-part; 10 = exact name. Substring hits (3) are not \"named\".\n return q.matches.some((m) => m.score >= 6);\n}\n\n/**\n * @deprecated Not a shipped threshold — a compatibility shim. An earlier\n * revision used 150 as an absolute ranking-score gate; it suppressed 3 of 114\n * real measurements, all terse one-line symptom asks, two of which retrieve\n * their target. Stand-down is now `rankConfidence === 0` only. Exported at 1\n * so a harness comparing `confidence < MIN_RANK_CONFIDENCE` keeps compiling\n * and matches the shipped rule (only honest-empty is suppressed).\n */\nexport const MIN_RANK_CONFIDENCE = 1;\n\n/**\n * Top ranking score from a module ranking, or null when there is nothing\n * comparable to threshold — no module answered, or it returned no scored seed.\n *\n * **Zero means the module's honest-empty verdict** (`hasContent === false`):\n * the ask named nothing this repo knows. Null means \"no signal at all\" and\n * never suppresses. A weak but nonzero score is a real, if faint, match and\n * compiles — a terse \"invoice total is wrong\" scoring 113 is the most common\n * field shape there is, and silencing it is `vg code` feeling dumber.\n */\nexport function rankConfidenceOf(ranked: { hasContent?: boolean; seeds?: Array<{ score?: number }> } | null | undefined): number | null {\n if (!ranked) return null;\n if (ranked.hasContent === false) return 0;\n const scores = (ranked.seeds ?? []).map((s) => Number(s?.score)).filter((n) => Number.isFinite(n) && n > 0);\n if (!scores.length) return null;\n return Math.max(...scores);\n}\n\nexport function capsuleMode(input: {\n sourceTokens: number;\n askNamesSymbol: boolean;\n /** Top module ranking score; 0 is the honest-empty verdict, null no signal. */\n rankConfidence?: number | null;\n}): CapsuleMode {\n const mass = Math.max(0, input.sourceTokens);\n if (mass <= WHOLE_REPO_MAX_SOURCE_TOKENS) return 'whole-repo';\n // Stand down ONLY on the module's honest-empty verdict. A score threshold\n // was measured and dropped: at any level that catches a log dump (129.9) it\n // also silences real terse symptom asks (113.6, 117.8, 133.3), two of which\n // retrieve their target. See docs/graph/VG-ASK-LENGTH-CAPSULE-FOLLOWUP.md.\n if (input.rankConfidence === 0) return 'off';\n if (mass > COMPILE_MIN_SOURCE_TOKENS) return 'compile';\n // Modest mass: greppable asks lose to grep (measured). Symptom-only in this\n // band is unmeasured — fail closed to off.\n if (input.askNamesSymbol) return 'off';\n return 'off';\n}\n\nexport interface WholeRepoFile {\n path: string;\n content: string;\n}\n\nexport interface WholeRepoPacket {\n rendered: string;\n tokensEstimate: number;\n files: string[];\n sourceTokens: number;\n}\n\n/**\n * First-turn packet = the mapped files, not a ranked dump. Files are sorted\n * by path. `budget` caps the paste (default {@link WHOLE_REPO_MAX_SOURCE_TOKENS});\n * at least one file is always included when any exist.\n *\n * The instruction is NOT echoed into the packet — the caller sends the ask as\n * its own trailing turn, so echoing it here billed it twice per step.\n */\nexport function buildWholeRepoPacket(\n files: WholeRepoFile[],\n budget: number = WHOLE_REPO_MAX_SOURCE_TOKENS,\n): WholeRepoPacket {\n const sorted = [...files]\n .map((f) => ({ path: normalize(f.path), content: f.content }))\n .filter((f) => f.path && f.content.length > 0)\n .sort((a, b) => a.path.localeCompare(b.path));\n const sourceTokens = sourceTokenMass(sorted.map((f) => f.content));\n\n const lines: string[] = [\n '# Repository source (entire mapped tree)',\n '',\n 'The files below are the repository. Use them; search or read outside only if they are insufficient.',\n '',\n ];\n const included: string[] = [];\n for (const f of sorted) {\n const block = [`### \\`${f.path}\\``, `\\`\\`\\`${langFor(f.path)}`, f.content.replace(/\\n$/, ''), '```', ''];\n const candidate = [...lines, ...block].join('\\n');\n if (included.length > 0 && estimateSourceTokens(candidate) > budget) break;\n lines.push(...block);\n included.push(f.path);\n }\n const rendered = lines.join('\\n');\n return {\n rendered,\n tokensEstimate: estimateSourceTokens(rendered),\n files: included,\n sourceTokens,\n };\n}\n\nfunction skipMappedPath(file: string): boolean {\n return (\n file.startsWith('node_modules/') ||\n file.includes('/node_modules/') ||\n file.startsWith('.git/') ||\n file.startsWith('.vibgrate/')\n );\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\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"]}
@@ -44,14 +44,14 @@ var AGENT_SYSTEM_PROMPT = [
44
44
  "library_docs, edit_file, create_file, delete_file, apply_patch, run_command, set_progress, inspect_task,",
45
45
  "inspect_change, verify_change, ask_user, finish, abort.",
46
46
  "",
47
- "You also always have the local Vibgrate AI Context MCP tools (namespaced",
48
- "mcp__vibgrate__*): search_symbols, query_graph, orient, get_node, impact_of,",
49
- "library_docs, check_drift, and the rest of `vg serve`. Prefer them for deep",
50
- "graph navigation, docs, and drift. Project MCP servers may add more mcp__* tools.",
47
+ "Call only a tool name listed in this turn. Never invent a name.",
48
+ "Project files may mention MCP names (search_symbols, query_graph, orient, get_node, impact_of).",
49
+ "Those jobs are search_code and graph_impact here. If a tool is listed as mcp__vibgrate__\u2026, use that full name.",
50
+ "Project MCP servers may add more mcp__* tools \u2014 still call them only by the listed name.",
51
51
  "",
52
52
  "## How to work",
53
53
  "- Search or read before you edit. Never invent file contents.",
54
- "- Smallest correct change; check graph_impact / mcp__vibgrate__impact_of before touching shared hubs.",
54
+ "- Smallest correct change; check graph_impact before touching shared hubs.",
55
55
  "- edit_file SEARCH must match current file (whitespace-flexible). Prefer apply_patch for multi-file edits.",
56
56
  "- Run tests or build when useful; use verify_change after multi-file work.",
57
57
  "- For multi-step tasks, call set_progress early with a short plan; mark items done as you complete them.",
@@ -1005,5 +1005,5 @@ var LocalLlamaProvider = class _LocalLlamaProvider {
1005
1005
  };
1006
1006
 
1007
1007
  export { LocalLlamaProvider, MockProvider, OPENAI_COMPATIBLE, OllamaProvider, OpenAiCompatibleProvider, ScriptedProvider, applyEdit, applyEdits, buildAgentMessages, buildMessages, parseEdits, parseReasoningEffort, redactSecrets, summarizeDiffs, unifiedDiff };
1008
- //# sourceMappingURL=chunk-SHD5TCZ5.js.map
1009
- //# sourceMappingURL=chunk-SHD5TCZ5.js.map
1008
+ //# sourceMappingURL=chunk-R2FX4USU.js.map
1009
+ //# sourceMappingURL=chunk-R2FX4USU.js.map