@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 +0,0 @@
1
- {"version":3,"sources":["../src/code/session.ts"],"names":["resolve"],"mappings":";;;;;;;;AAsFA,eAAsB,eAAe,OAAA,EAAwD;AAC3F,EAAA,MAAM;AAAA,IACJ,KAAA;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EAAA,MAAM,QAAA,GAAW,sCAAA;AACjB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,CAAA,EAAG,KAAK,CAAA,IAAK,QAAA,CAAS,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,EAAO,GAAI,QAAA,CAAS,MAAM,CAAC,CAAA;AACrF,EAAA,OAAO,CAAA;AACT","file":"chunk-GWSJYDK7.js","sourcesContent":["/**\n * The `vg code` governance session (VG-CLI-CODE §7).\n *\n * This is the load-bearing rule the whole platform is built on, applied to code\n * edits: a state-altering change goes **through** the lifecycle, never around it\n * (GUARDRAILS §5). One run walks inspect → assess → dry-run → approve → execute\n * → verify → log:\n *\n * inspect build the graph-grounded context for the instruction\n * assess ask the routed model for a terse edit; apply it deterministically\n * (in memory); compute the diff and the blast radius\n * dry-run the DEFAULT terminal state — propose the change, write nothing\n * approve writing requires explicit consent; without it we stop at dry-run\n * execute write the approved changes to disk\n * verify confirm the files on disk match what was approved (+ optional cmd)\n * log append an immutable, secret-free audit record with a correlation id\n *\n * Everything is deterministic except the single model call, which is isolated\n * behind the provider list (tried in order, falling back on transport failure).\n * The filesystem and clock are injectable so the whole session is testable\n * offline with no writes escaping a temp dir.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { buildCodeContext } from './context.js';\nimport { rankQuestion, type SanitizedRank } from '../engine/relevance-provider.js';\nimport { loadTopicTags } from '../engine/relevance-enrich.js';\nimport { userAskFromInstruction } from '../engine/user-ask.js';\nimport { buildTaskCapsule, capsuleToCodeContext } from './capsule.js';\nimport { recordCliCall, CLI_TOOL_ALIASES } from '../engine/savings.js';\nimport { repositoryIdFromRoot } from '../runtime/paths.js';\nimport { parseEdits, applyEdits, type SymbolSpan } from './apply.js';\nimport { unifiedDiff } from './diff.js';\nimport { buildMessages } from './prompt.js';\nimport { redactSecrets } from './providers.js';\nimport type { ChatOptions, CodeContext, CodeSessionResult, FileChange, LifecyclePhase, Provider, ProviderResult } from './types.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Minimal filesystem seam so the session is testable without touching real disk. */\nexport interface CodeFs {\n read(file: string): string | null;\n write(file: string, content: string): void;\n remove(file: string): void;\n appendAudit(line: string): void;\n}\n\nexport interface RunSessionOptions {\n graph: VgGraph;\n root: string;\n instruction: string;\n /** Providers to try in order (from the router); the first that answers wins. */\n providers: Provider[];\n /** Write to disk? Default false — dry-run is the safe default (GUARDRAILS §3.2). */\n apply?: boolean;\n /** Explicit consent for the write (`--yes`); without it, a requested apply stops at dry-run. */\n consent?: boolean;\n /** Restrict the edit surface to these files. */\n files?: string[];\n /** Context token budget. */\n budget?: number;\n chatOptions?: ChatOptions;\n /** Injectable filesystem (defaults to a real, root-scoped fs). */\n fsImpl?: CodeFs;\n /** Injectable clock (ms) for the audit timestamp. */\n now?: () => number;\n /** Injectable correlation id (defaults to a random short id). */\n correlationId?: string;\n /** Progress callback per phase. */\n onPhase?: (phase: LifecyclePhase, detail: string) => void;\n /** Skip appending to the audit log (used by tests/dry programmatic calls). */\n noAudit?: boolean;\n /**\n * Who is making the graph-backed call, for per-model savings auditing. When\n * `client` is set, the context-assembly step (a `query_graph`-equivalent) is\n * recorded to the local savings ledger tagged with the provider + model, so\n * `vg savings` can break usage down per model. VG Code always sets this.\n */\n attribution?: { client: string; provider?: string; model?: string };\n /**\n * Use a source-bearing Task Capsule for the inspect context (Fusion Runtime\n * Phase 0 A/B). Default false keeps the metadata-only path.\n */\n capsule?: boolean;\n}\n\nexport async function runCodeSession(options: RunSessionOptions): Promise<CodeSessionResult> {\n const {\n graph,\n root,\n instruction,\n providers,\n apply = false,\n consent = false,\n files,\n budget,\n chatOptions,\n now = () => 0,\n onPhase = () => {},\n } = options;\n const fsImpl = options.fsImpl ?? nodeCodeFs(root);\n const correlationId = options.correlationId ?? shortId();\n const phasesRun: LifecyclePhase[] = [];\n const phase = (p: LifecyclePhase, detail: string): void => {\n phasesRun.push(p);\n onPhase(p, detail);\n };\n\n // ── inspect ──────────────────────────────────────────────────────────────\n phase('inspect', options.capsule ? 'building source-bearing task capsule' : 'building graph-grounded context');\n // The relevance module ranks the seeds when installed (auto-provisioned);\n // null → the mechanical fallback.\n const topicTags = await loadTopicTags(graph, root);\n const ranked = await rankQuestion(graph, userAskFromInstruction(instruction), { limit: 48, topicTags });\n const context = buildSessionContext(graph, instruction, {\n budget,\n files,\n capsule: options.capsule,\n root,\n fsImpl,\n ranked,\n });\n\n // Per-model savings: the context build is VG Code's `query_graph`-equivalent.\n // Record it (counts only — never code or the instruction) tagged with the\n // model, so `vg savings` audits usage per model. Local-only, best-effort.\n if (options.attribution?.client) {\n const seedFiles = new Set(context.seeds.map((s) => s.node.file).filter(Boolean));\n recordCliCall(\n root,\n {\n tool: CLI_TOOL_ALIASES.ask,\n client: options.attribution.client,\n provider: options.attribution.provider,\n model: options.attribution.model,\n outcome: context.seeds.length ? 'complete' : 'miss',\n vgTokens: context.tokensEstimate,\n baselineFiles: seedFiles.size,\n },\n now(),\n );\n }\n\n // ── assess ──────────────────────────────────────────────────────────────\n phase('assess', 'asking the routed model for a minimal edit');\n const messages = buildMessages(context);\n const { result, provider, fellBack } = await complete(providers, messages, chatOptions, correlationId);\n\n const edits = parseEdits(result.text);\n const spans = spanIndex(graph);\n const applied = applyEdits(\n edits,\n (file) => fsImpl.read(file),\n (file) => spans.get(normalize(file)) ?? [],\n );\n\n const changes: FileChange[] = [];\n for (const [file, entry] of [...applied.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n changes.push({\n file,\n before: entry.before,\n after: entry.after,\n outcomes: entry.outcomes,\n diff: unifiedDiff(entry.before, entry.after, file),\n });\n }\n\n // ── dry-run (always produced) ─────────────────────────────────────────────\n phase('dry-run', `${changes.length} file(s) would change`);\n\n const anyApplicable = changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n const base: CodeSessionResult = {\n instruction,\n provider: { id: provider.id, model: provider.model, local: provider.local, fellBack },\n phasesRun,\n changes,\n applied: false,\n verification: { ran: false, ok: false, detail: 'dry-run — no changes written' },\n correlationId,\n };\n\n // ── approve ───────────────────────────────────────────────────────────────\n // Writing is opt-in AND consent-gated. A requested apply without consent is\n // not an error — it degrades to a dry-run so the caller can review, then\n // re-run with --yes. This is the \"never destructive-by-default\" guardrail.\n if (!apply) {\n if (!options.noAudit) writeAudit(fsImpl, base, now());\n return base;\n }\n if (!consent) {\n const stopped = { ...base, verification: { ran: false, ok: false, detail: 'apply requested without consent — re-run with --yes to write these changes' } };\n if (!options.noAudit) writeAudit(fsImpl, stopped, now());\n return stopped;\n }\n if (!anyApplicable) {\n const nothing = { ...base, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n if (!options.noAudit) writeAudit(fsImpl, nothing, now());\n return nothing;\n }\n phase('approve', 'consent given (--yes)');\n\n // ── execute ───────────────────────────────────────────────────────────────\n phase('execute', 'writing approved changes');\n for (const change of changes) {\n if (change.diff === '') continue; // no-op file\n if (!change.outcomes.some((o) => o.status === 'applied')) continue; // nothing applied cleanly here\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n\n // ── verify ────────────────────────────────────────────────────────────────\n phase('verify', 'confirming on-disk content matches the approved change');\n const verification = verifyWrites(fsImpl, changes);\n\n // ── log ───────────────────────────────────────────────────────────────────\n phase('log', 'recording an audit entry');\n const final: CodeSessionResult = { ...base, applied: true, verification };\n if (!options.noAudit) writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Commit an already-computed dry-run result: write the cleanly-applied changes,\n * verify them on disk, and append the audit record — the \"approve → execute →\n * verify → log\" tail of the lifecycle, run against a proposal the caller has\n * already shown and had approved (the interactive REPL uses this so it never\n * calls the model twice or writes something different from what was reviewed).\n */\nexport function commitChanges(result: CodeSessionResult, fsImpl: CodeFs, now: () => number = () => 0): CodeSessionResult {\n const anyApplicable = result.changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n if (!anyApplicable) {\n return { ...result, applied: false, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n }\n for (const change of result.changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n const verification = verifyWrites(fsImpl, result.changes);\n const final: CodeSessionResult = { ...result, applied: true, verification, phasesRun: [...result.phasesRun, 'approve', 'execute', 'verify', 'log'] };\n writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Undo a set of applied changes by restoring each file's prior content — the\n * `/undo` command. A created file (before === null) is removed; an edited or\n * deleted file is restored to its `before`. Only cleanly-applied changes are\n * reverted. Returns the files it restored.\n */\nexport function undoChanges(changes: FileChange[], fsImpl: CodeFs): string[] {\n const restored: string[] = [];\n for (const ch of changes) {\n if (!ch.outcomes.some((o) => o.status === 'applied')) continue;\n if (ch.before === null) fsImpl.remove(ch.file);\n else fsImpl.write(ch.file, ch.before);\n restored.push(ch.file);\n }\n return restored;\n}\n\nfunction buildSessionContext(\n graph: VgGraph,\n instruction: string,\n opts: { budget?: number; files?: string[]; capsule?: boolean; root: string; fsImpl: CodeFs; ranked?: SanitizedRank | null },\n): CodeContext {\n const budget = opts.budget;\n const files = opts.files;\n if (!opts.capsule) {\n return buildCodeContext(graph, instruction, { budget, files, ranked: opts.ranked });\n }\n const capsule = buildTaskCapsule(graph, instruction, {\n budget,\n files,\n readFile: (rel) => opts.fsImpl.read(rel),\n repositoryId: repositoryIdFromRoot(opts.root),\n ranked: opts.ranked,\n });\n return capsuleToCodeContext(capsule);\n}\n\n/** Try each provider in order; fall back on transport failure. Throws the last actionable error. */\nasync function complete(\n providers: Provider[],\n messages: ReturnType<typeof buildMessages>,\n chatOptions: ChatOptions | undefined,\n correlationId: string,\n): Promise<{ result: ProviderResult; provider: Provider; fellBack: boolean }> {\n if (providers.length === 0) throw new Error(`no model provider available (ref ${correlationId})`);\n let lastErr: unknown;\n for (let i = 0; i < providers.length; i++) {\n const provider = providers[i];\n try {\n const result = await provider.chat(messages, { temperature: 0, ...chatOptions });\n return { result, provider, fellBack: i > 0 };\n } catch (e) {\n lastErr = e;\n }\n }\n const message = lastErr instanceof Error ? redactSecrets(lastErr.message) : String(lastErr);\n throw new Error(`${message} (ref ${correlationId})`);\n}\n\n/** Confirm each written file's on-disk content equals what we approved. */\nfunction verifyWrites(fsImpl: CodeFs, changes: FileChange[]): { ran: boolean; ok: boolean; detail: string } {\n let checked = 0;\n const mismatches: string[] = [];\n for (const change of changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n checked++;\n const onDisk = fsImpl.read(change.file);\n if (onDisk !== change.after) mismatches.push(change.file);\n }\n if (mismatches.length) return { ran: true, ok: false, detail: `on-disk content differs for: ${mismatches.join(', ')}` };\n return { ran: true, ok: true, detail: `wrote and verified ${checked} file(s)` };\n}\n\n/** An append-only, secret-free audit record (GUARDRAILS §2.6 / §5). No file contents, no keys. */\nfunction writeAudit(fsImpl: CodeFs, r: CodeSessionResult, ts: number): void {\n const record = {\n ts,\n correlationId: r.correlationId,\n instruction: r.instruction.slice(0, 500),\n provider: r.provider.id,\n model: r.provider.model,\n local: r.provider.local,\n applied: r.applied,\n files: r.changes.map((c) => ({ file: c.file, statuses: c.outcomes.map((o) => o.status) })),\n verification: r.verification,\n phases: r.phasesRun,\n };\n try {\n fsImpl.appendAudit(JSON.stringify(record));\n } catch {\n /* audit is best-effort; never fail the run on a logging problem */\n }\n}\n\n/** Build a per-file map of symbol spans for graph-scoped edit disambiguation. */\nfunction spanIndex(graph: VgGraph): Map<string, SymbolSpan[]> {\n const map = new Map<string, SymbolSpan[]>();\n for (const n of graph.nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const file = normalize(n.file);\n const list = map.get(file) ?? [];\n list.push({ qualifiedName: n.qualifiedName, file, start: n.span.start, end: n.span.end });\n map.set(file, list);\n }\n return map;\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\n/** Default filesystem impl, scoped to `root`. Refuses paths that escape the root. */\nexport function nodeCodeFs(root: string): CodeFs {\n const resolve = (file: string): string => {\n const abs = path.resolve(root, file);\n const rel = path.relative(root, abs);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`edit path escapes the project root: ${file} — refusing to touch files outside ${root}`);\n }\n return abs;\n };\n return {\n read(file) {\n try {\n return fs.readFileSync(resolve(file), 'utf8');\n } catch {\n return null;\n }\n },\n write(file, content) {\n const abs = resolve(file);\n fs.mkdirSync(path.dirname(abs), { recursive: true });\n fs.writeFileSync(abs, content);\n },\n remove(file) {\n try {\n fs.rmSync(resolve(file));\n } catch {\n /* already gone */\n }\n },\n appendAudit(line) {\n const dir = path.join(root, '.vibgrate');\n fs.mkdirSync(dir, { recursive: true });\n fs.appendFileSync(path.join(dir, 'code-audit.jsonl'), line + '\\n');\n },\n };\n}\n\n/** Short, URL-safe correlation id. Not a graph artifact, so runtime randomness is fine here. */\nfunction shortId(): string {\n let s = '';\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';\n for (let i = 0; i < 8; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)];\n return s;\n}\n"]}
@@ -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","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,C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A,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-K3SXWOTT.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 type { SanitizedRank } from './relevance-provider.js';\nimport type { GraphNode, VgGraph } from '../schema.js';\nimport { userAskFromInstruction } from './user-ask.js';\n\n/**\n * Retrieval front-end for `vg ask` / `vg code` capsule seeds (VG-CLI-SPEC\n * §3.2).\n *\n * Since the 2026-08 relevance relocation, the RANKING ENGINE lives in the\n * optional relevance module (`@vibgrate/relevance`, auto-provisioned): the\n * async callers run the ask through the module via\n * `relevance-provider.rankQuestion` and pass the SANITIZED result in as\n * `options.ranked`. This file keeps only what is mechanical:\n *\n * - literal string/URL needle handling (the locate path — exact-text\n * matching, not relevance);\n * - a deliberately dumb module-less fallback: exact identifier-name and\n * name-part matching, nothing that understands language (no lexicon, no\n * term roles, no IDF, no typo repair, no expansion) — enough that an ask\n * NAMING a symbol still pins its file when the module is unavailable;\n * - context-block rendering and the semantic Reciprocal Rank Fusion\n * plumbing (`--semantic`), which fuses ORDERINGS and carries no ranking\n * heuristics of its own.\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 /** Sanitized module ranking (engine/relevance-provider.ts rankQuestion),\n * injected by async callers so this module stays pure and sync. When\n * absent — module not installed, predates the ranking API, or failed —\n * the mechanical fallback below answers. */\n ranked?: SanitizedRank | 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\n/**\n * Function-word hygiene for the mechanical fallback tokenizer. This is NOT a\n * relevance stopword model (that moved into the module): nothing here scores,\n * ranks, weights, or reorders anything. It is a purely SUBTRACTIVE floor —\n * the words a caller uses to FRAME an ask rather than to name the code they\n * mean, which therefore cannot be identifier evidence.\n *\n * The floor exists because `mechanicalRank` treats every surviving token as\n * equal evidence, and English framing words collide with real identifier\n * parts constantly. Without it, `\"add a new feature\"` scores `AddBlogForm`\n * on the camel-part tier (`add`) and `FeatureFlagStore` (`feature`) and fills\n * the entire seed window — a grab-bag Task Capsule for an ask that named\n * nothing. That is the capsule-poisoning failure of the 2026-07 field report,\n * and an empty result is the correct answer.\n *\n * Note this is the floor ONLY. Deciding which of several genuine candidates\n * is most relevant remains the module's job, and no part of that logic —\n * term roles, weighting, expansion, morphology — belongs in this file.\n */\nconst FUNCTION_WORDS = new Set([\n // Closed-class English: could only ever match by coincidence.\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 // Process verbs. A caller says what they want DONE with these; they never\n // name the code it should be done to. Left in, bare `add` seeds every\n // Add*/*Add* symbol in the repo ahead of the terms that carry the subject.\n 'add', 'adds', 'added', 'adding',\n 'create', 'creates', 'created', 'creating',\n 'make', 'makes', 'making', 'made',\n 'remove', 'removes', 'removed', 'removing',\n 'delete', 'deletes', 'deleted', 'deleting',\n 'update', 'updates', 'updated', 'updating',\n 'change', 'changes', 'changed', 'changing',\n 'set', 'sets', 'setting', 'setup', 'get', 'gets', 'getting',\n 'use', 'uses', 'used', 'using', 'want', 'wants', 'wanted', 'doing', 'done',\n 'support', 'supports', 'supported', 'supporting',\n 'enable', 'enables', 'enabled', 'enabling',\n 'disable', 'disables', 'disabled', 'disabling',\n 'allow', 'allows', 'allowed', 'handle', 'handles', 'handling',\n 'implement', 'implements', 'implemented', 'implementing',\n 'build', 'builds', 'building', 'built', 'need', 'needs', 'needed',\n // Filler nouns and connectives: the generic scaffolding of a request.\n 'new', 'newly', 'via', 'through', 'into', 'onto',\n 'way', 'ways', 'thing', 'things', 'stuff',\n 'feature', 'features', 'functionality',\n 'method', 'methods', 'option', 'options', 'ability',\n 'form', 'forms', 'page', 'pages', 'screen', 'screens', 'button', 'buttons',\n 'help', 'start', 'begin', 'work', 'works', 'working',\n 'also', 'currently', 'properly', 'correctly', 'please',\n 'happens', 'happen', 'something', 'somewhere',\n 'step', 'steps', 'flow', 'process',\n // Discovery-question scaffolding: words that FRAME the search itself\n // (\"find the code responsible for X\", \"explain how X works\").\n 'find', 'code', 'responsible', 'modify', 'me',\n 'implementation', 'explain', 'codebase', 'contains', 'file',\n // Bug-report framing: says something is WRONG, never what is wrong.\n // `fix` alone lit up `export_fixed_width_records`, `out` lit up every\n // *Router*/*rollout* symbol (vg code prompt-relevance corpus).\n 'fix', 'fixes', 'fixing', 'bug', 'bugs', 'broken', 'busted', 'borked',\n 'wrong', 'incorrect', 'incorrectly', 'figure', 'out', 'sure',\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 const literals = extractLiteralNeedles(question);\n const index = indexFor(graph);\n\n let seeds: QueryMatch[];\n if (options.ranked) {\n // Module ranking (already sanitized: every id names a real symbol).\n // An honest miss from the engine stays an honest miss here.\n const byId = new Map<string, GraphNode>();\n for (const node of graph.nodes) byId.set(node.id, node);\n seeds = options.ranked.hasContent\n ? options.ranked.seeds\n .map((s) => {\n const node = byId.get(s.id);\n return node ? { node, score: s.score, why: s.why } : null;\n })\n .filter((m): m is QueryMatch => m !== null)\n .slice(0, limit)\n : [];\n } else {\n seeds = mechanicalRank(graph, question, literals).slice(0, limit);\n }\n\n const { context, tokensEstimate } = buildContext(graph, index, question, seeds, budget, literals);\n return { question, matches: seeds, context, tokensEstimate };\n}\n\n/**\n * The module-less fallback: mechanical identifier matching, deliberately free\n * of language understanding. A token scores only when it IS a symbol's name,\n * one of its camel/snake parts, or (length ≥ 4) a substring of the qualified\n * name — so \"write tests for chargeCard\" or a pasted `src/…/File.ts` path\n * still pins the right file, while intent phrasings honestly miss until the\n * relevance module is available. No lexicon, no term roles, no IDF, no typo\n * repair, no expansions — that is the module's job now.\n */\nfunction mechanicalRank(graph: VgGraph, question: string, literals: string[]): QueryMatch[] {\n const forTokens = literals.length > 0 ? stripLiteralNeedles(question) : question;\n let tokens = tokenize(forTokens);\n // A literal ask's residual framing (\"does not exist\", \"find occurrences\")\n // must not light up DoesNot*/NonExisting*/commandExists lookalikes — the\n // honest-miss contract of the locate path holds module-less too.\n if (literals.length > 0) tokens = tokens.filter((t) => !LOCATE_SCAFFOLD.has(t));\n if (tokens.length === 0) return [];\n const scored: QueryMatch[] = [];\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n const name = node.name.toLowerCase();\n const qn = node.qualifiedName.toLowerCase();\n const parts = identifierParts(node.name);\n let score = 0;\n const hits: string[] = [];\n for (const t of tokens) {\n if (name === t) {\n score += 10;\n hits.push(t);\n } else if (parts.has(t)) {\n score += 6;\n hits.push(t);\n } else if (t.length >= 4 && qn.includes(t)) {\n score += 3;\n hits.push(t);\n }\n }\n if (score > 0) {\n scored.push({\n node,\n score: round(score * (1 + IMPORTANCE_WEIGHT * node.importance)),\n why: `matched: ${hits.join(', ')}`,\n });\n }\n }\n scored.sort((a, b) => b.score - a.score || a.node.qualifiedName.localeCompare(b.node.qualifiedName));\n return diversifyByFile(scored);\n}\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 && !FUNCTION_WORDS.has(t)),\n ),\n ];\n}\n\n/**\n * Importance is a mild tiebreaker, not a doubling: at 0.4 a top hub adds at\n * most 40%, enough to break genuine ties without overriding term evidence.\n */\nconst IMPORTANCE_WEIGHT = 0.4;\n\n/** Residual framing of a string/URL locate ask — never symbol evidence. */\nconst LOCATE_SCAFFOLD = new Set([\n 'not', 'no', 'exist', 'exists', 'existing', 'occurrence', 'occurrences',\n 'occurence', 'occurences', 'find', 'every', 'place', 'places', 'string',\n 'literal', 'text', 'search', 'locate', 'look', 'looking', 'show', 'list', 'all',\n]);\n\n/**\n * Stable file-diversity pass over the ranked list: each file's best node\n * keeps its rank; further nodes from an already-represented file are demoted\n * behind the first representative of every other matching file (never\n * dropped). Mechanical presentation hygiene — the seed window is a coverage\n * budget either way.\n */\nfunction diversifyByFile(matches: QueryMatch[]): QueryMatch[] {\n const seen = new Set<string>();\n const firstPerFile: QueryMatch[] = [];\n const rest: QueryMatch[] = [];\n for (const m of matches) {\n if (seen.has(m.node.file)) {\n rest.push(m);\n } else {\n seen.add(m.node.file);\n firstPerFile.push(m);\n }\n }\n return firstPerFile.concat(rest);\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: a node's fused score is Σ 1/(k + rankᵢ) over the\n * lists it appears in, so agreement between signals dominates and a single\n * 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 retrieval, combined with Reciprocal Rank Fusion: the module ranking\n * (or the mechanical fallback) is one arm, the local-embedding pass the\n * other, so a question like \"where do we handle auth failures?\" can surface\n * `verify_token` even with no shared word. Deterministic given the same\n * model + cached vectors; embeddings live in a binary sidecar next to the\n * 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 residualTokens = tokenize(forTokens);\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 const index = indexFor(graph);\n\n // Lexical arm: module ranking order when available, mechanical otherwise.\n // RRF consumes only the ORDER. An honest miss contributes an empty arm.\n const lexRaw = new Map<string, number>();\n const whyById = new Map<string, string>();\n const lexSeeds = options.ranked\n ? options.ranked.hasContent\n ? options.ranked.seeds.map((s) => ({ id: s.id, score: s.score, why: s.why }))\n : []\n : mechanicalRank(graph, question, literals).map((m) => ({ id: m.node.id, score: m.score, why: m.why }));\n for (const s of lexSeeds) {\n lexRaw.set(s.id, s.score);\n whyById.set(s.id, s.why);\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 (residualTokens.length > 0 || literals.length === 0) {\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 && residualTokens.length > 0 ? Math.max(0, cosine(queryVec, vec)) : 0;\n if (sem > 0) semRaw.set(node.id, sem);\n }\n if (options.semanticRanked && residualTokens.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 why = lexWhy || (sem > 0.3 ? `semantic match (${sem.toFixed(2)})` : 'weak match');\n scored.push({ node, score: round(fused * (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 = diversifyByFile(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 * camelCase / snake_case / kebab / letter↔digit split of an identifier →\n * lowercased parts. The separator alternative is Unicode-letter-aware\n * (`\\p{L}\\p{N}`, not ASCII-only) so non-Latin identifiers split on\n * punctuation without losing every character to it; the camelCase boundary\n * lookaround stays ASCII-only since casing is itself an ASCII-script concept.\n * Letter↔digit boundaries split too, so `Session2` keeps `session` reachable.\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])|(?<=[\\p{L}])(?=[0-9])|(?<=[0-9])(?=[\\p{L}])/u)\n .filter(Boolean)\n .map((s) => s.toLowerCase()),\n );\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/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,OAAO,IAAA,CAAK,IAAA,CAAK,KAAA,GAAQ,CAAC,CAAA;AAC5B;AAMO,SAAS,cAAA,CAAe,OAAgB,WAAA,EAA8B;AAC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OAAA,CAAQ,SAAS,EAAE,CAAA;AACrD;AAEA,SAAS,QAAQ,IAAA,EAAsB;AACrC,EAAA,MAAM,GAAA,GAAM,KAAK,KAAA,CAAM,GAAG,EAAE,GAAA,EAAI,EAAG,aAAY,IAAK,EAAA;AACpD,EAAA,MAAM,GAAA,GAA8B;AAAA,IAClC,EAAA,EAAI,IAAA;AAAA,IACJ,GAAA,EAAK,KAAA;AAAA,IACL,EAAA,EAAI,IAAA;AAAA,IACJ,GAAA,EAAK,KAAA;AAAA,IACL,GAAA,EAAK,IAAA;AAAA,IACL,GAAA,EAAK,IAAA;AAAA,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","file":"chunk-L7GCJNDT.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\nexport function capsuleMode(input: { sourceTokens: number; askNamesSymbol: boolean }): CapsuleMode {\n const mass = Math.max(0, input.sourceTokens);\n if (mass <= WHOLE_REPO_MAX_SOURCE_TOKENS) return 'whole-repo';\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 */\nexport function buildWholeRepoPacket(\n instruction: string,\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, '## Task', instruction].join('\\n');\n if (included.length > 0 && estimateSourceTokens(candidate) > budget) break;\n lines.push(...block);\n included.push(f.path);\n }\n lines.push('## Task');\n lines.push(instruction);\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"]}