@vibgrate/cli 2026.731.3 → 2026.803.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.
- package/dist/agent-HNV2VUCO.js +24 -0
- package/dist/{agent-6XOI7RVW.js.map → agent-HNV2VUCO.js.map} +1 -1
- package/dist/baseline-6WTULHM5.js +9 -0
- package/dist/{baseline-PY6TETA5.js.map → baseline-6WTULHM5.js.map} +1 -1
- package/dist/{chunk-B6S2DSBS.js → chunk-2TLQDF6C.js} +129 -20
- package/dist/chunk-2TLQDF6C.js.map +1 -0
- package/dist/{chunk-X634FZVG.js → chunk-3LOWJSAF.js} +11 -16
- package/dist/{chunk-X634FZVG.js.map → chunk-3LOWJSAF.js.map} +1 -1
- package/dist/{chunk-BMUTNUB7.js → chunk-4HFSUIIN.js} +117 -6
- package/dist/chunk-4HFSUIIN.js.map +1 -0
- package/dist/{chunk-3VSU7G75.js → chunk-536J6HUR.js} +235 -13
- package/dist/chunk-536J6HUR.js.map +1 -0
- package/dist/{chunk-EETK7S43.js → chunk-5VH3Y4QC.js} +111 -33
- package/dist/chunk-5VH3Y4QC.js.map +1 -0
- package/dist/{chunk-PHGAUWWF.js → chunk-6I4TXAI6.js} +3 -3
- package/dist/{chunk-PHGAUWWF.js.map → chunk-6I4TXAI6.js.map} +1 -1
- package/dist/{chunk-FF5ZQ6KI.js → chunk-6JP7HGIF.js} +4 -4
- package/dist/{chunk-FF5ZQ6KI.js.map → chunk-6JP7HGIF.js.map} +1 -1
- package/dist/chunk-AJ2KE3NT.js +446 -0
- package/dist/chunk-AJ2KE3NT.js.map +1 -0
- package/dist/{chunk-WK52LWRX.js → chunk-B2KLJPFY.js} +5 -5
- package/dist/{chunk-WK52LWRX.js.map → chunk-B2KLJPFY.js.map} +1 -1
- package/dist/{chunk-Z7VH4RPO.js → chunk-BBFQZ7CA.js} +4 -4
- package/dist/{chunk-Z7VH4RPO.js.map → chunk-BBFQZ7CA.js.map} +1 -1
- package/dist/{chunk-FHJBGPJZ.js → chunk-BWMMR5XA.js} +4 -4
- package/dist/{chunk-FHJBGPJZ.js.map → chunk-BWMMR5XA.js.map} +1 -1
- package/dist/{chunk-KLO2XBUX.js → chunk-CC6F75GI.js} +14 -7
- package/dist/chunk-CC6F75GI.js.map +1 -0
- package/dist/{chunk-SCTLOFNH.js → chunk-CE45STY5.js} +4 -4
- package/dist/{chunk-SCTLOFNH.js.map → chunk-CE45STY5.js.map} +1 -1
- package/dist/{chunk-MOLBANFB.js → chunk-DIU3MXB3.js} +4 -4
- package/dist/{chunk-MOLBANFB.js.map → chunk-DIU3MXB3.js.map} +1 -1
- package/dist/{chunk-5IA2TA57.js → chunk-FKFRASAB.js} +323 -152
- package/dist/chunk-FKFRASAB.js.map +1 -0
- package/dist/{chunk-EVLS2M5G.js → chunk-JFE7XCAE.js} +3 -3
- package/dist/{chunk-EVLS2M5G.js.map → chunk-JFE7XCAE.js.map} +1 -1
- package/dist/{chunk-RGEVBSLK.js → chunk-JUSXLCSE.js} +3 -3
- package/dist/{chunk-RGEVBSLK.js.map → chunk-JUSXLCSE.js.map} +1 -1
- package/dist/{chunk-7G5S5KZN.js → chunk-KUZLILN3.js} +16 -3
- package/dist/chunk-KUZLILN3.js.map +1 -0
- package/dist/{chunk-AVCBKQKA.js → chunk-N4IDP2M2.js} +218 -51
- package/dist/chunk-N4IDP2M2.js.map +1 -0
- package/dist/{chunk-XRN7DQGR.js → chunk-NJFQCDGA.js} +3 -3
- package/dist/{chunk-XRN7DQGR.js.map → chunk-NJFQCDGA.js.map} +1 -1
- package/dist/{chunk-LTTVCI5C.js → chunk-O7MTBC52.js} +134 -9
- package/dist/chunk-O7MTBC52.js.map +1 -0
- package/dist/chunk-QT2PMGN3.js +6 -0
- package/dist/{chunk-DEKGSQHL.js.map → chunk-QT2PMGN3.js.map} +1 -1
- package/dist/{chunk-5XIEVZLW.js → chunk-S4NSF5AZ.js} +6 -6
- package/dist/{chunk-5XIEVZLW.js.map → chunk-S4NSF5AZ.js.map} +1 -1
- package/dist/{chunk-TRKRRX2S.js → chunk-SJFBXCII.js} +35 -6
- package/dist/chunk-SJFBXCII.js.map +1 -0
- package/dist/{chunk-RIWLXMMT.js → chunk-SNKTD23L.js} +109 -10
- package/dist/chunk-SNKTD23L.js.map +1 -0
- package/dist/{chunk-IPICO2RV.js → chunk-VIWZ4QT7.js} +14 -3
- package/dist/chunk-VIWZ4QT7.js.map +1 -0
- package/dist/{chunk-US2DAKCM.js → chunk-Y7YKUZ3T.js} +8 -7
- package/dist/chunk-Y7YKUZ3T.js.map +1 -0
- package/dist/cli.js +732 -347
- package/dist/cli.js.map +1 -1
- package/dist/ensure-map-5YEI7R7V.js +29 -0
- package/dist/{ensure-map-UQL7SM34.js.map → ensure-map-5YEI7R7V.js.map} +1 -1
- package/dist/{graph-backend-G5Y6QQV4.js → graph-backend-CPHLUKUC.js} +5 -5
- package/dist/{graph-backend-G5Y6QQV4.js.map → graph-backend-CPHLUKUC.js.map} +1 -1
- package/dist/index.d.ts +127 -9
- package/dist/index.js +17 -16
- package/dist/index.js.map +1 -1
- package/dist/{interactive-QWT7ERXJ.js → interactive-TNRE4OEK.js} +46 -33
- package/dist/interactive-TNRE4OEK.js.map +1 -0
- package/dist/{llm-host-DZBD5D36.js → llm-host-XFYFOAAX.js} +4 -4
- package/dist/{llm-host-DZBD5D36.js.map → llm-host-XFYFOAAX.js.map} +1 -1
- package/dist/load-MWG6WZTK.js +10 -0
- package/dist/{load-WA53B3GW.js.map → load-MWG6WZTK.js.map} +1 -1
- package/dist/model-manager-GJ2YSTSK.js +1 -1
- package/dist/{run-outcome-J2IDIVYI.js → run-outcome-375HMSQG.js} +6 -6
- package/dist/{run-outcome-J2IDIVYI.js.map → run-outcome-375HMSQG.js.map} +1 -1
- package/dist/runtime-session-3MPWXNRL.js +20 -0
- package/dist/{runtime-session-52P2Y5LX.js.map → runtime-session-3MPWXNRL.js.map} +1 -1
- package/dist/session-2NGJLI5Y.js +15 -0
- package/dist/{session-L7SJNE55.js.map → session-2NGJLI5Y.js.map} +1 -1
- package/dist/session-store-F7NX7SZN.js +4 -0
- package/dist/{session-store-SQECEXUU.js.map → session-store-F7NX7SZN.js.map} +1 -1
- package/dist/{stream-json-TSGYC2MQ.js → stream-json-AUMU3NLV.js} +48 -16
- package/dist/stream-json-AUMU3NLV.js.map +1 -0
- package/dist/{vg-mcp-bridge-IFAXEQMZ.js → vg-mcp-bridge-D463EHQI.js} +13 -11
- package/dist/vg-mcp-bridge-D463EHQI.js.map +1 -0
- package/dist/{vgd-PNR7UKLL.js → vgd-Z23PXSP4.js} +10 -10
- package/dist/vgd-Z23PXSP4.js.map +1 -0
- package/package.json +4 -2
- package/dist/agent-6XOI7RVW.js +0 -22
- package/dist/baseline-PY6TETA5.js +0 -9
- package/dist/chunk-3VSU7G75.js.map +0 -1
- package/dist/chunk-5IA2TA57.js.map +0 -1
- package/dist/chunk-7G5S5KZN.js.map +0 -1
- package/dist/chunk-AVCBKQKA.js.map +0 -1
- package/dist/chunk-B6S2DSBS.js.map +0 -1
- package/dist/chunk-BMUTNUB7.js.map +0 -1
- package/dist/chunk-DEKGSQHL.js +0 -6
- package/dist/chunk-EETK7S43.js.map +0 -1
- package/dist/chunk-IPICO2RV.js.map +0 -1
- package/dist/chunk-KLO2XBUX.js.map +0 -1
- package/dist/chunk-LTTVCI5C.js.map +0 -1
- package/dist/chunk-RIWLXMMT.js.map +0 -1
- package/dist/chunk-TRKRRX2S.js.map +0 -1
- package/dist/chunk-US2DAKCM.js.map +0 -1
- package/dist/chunk-ZKNB4YH4.js +0 -102
- package/dist/chunk-ZKNB4YH4.js.map +0 -1
- package/dist/ensure-map-UQL7SM34.js +0 -28
- package/dist/interactive-QWT7ERXJ.js.map +0 -1
- package/dist/load-WA53B3GW.js +0 -10
- package/dist/runtime-session-52P2Y5LX.js +0 -20
- package/dist/session-L7SJNE55.js +0 -13
- package/dist/session-store-SQECEXUU.js +0 -4
- package/dist/stream-json-TSGYC2MQ.js.map +0 -1
- package/dist/vg-mcp-bridge-IFAXEQMZ.js.map +0 -1
- package/dist/vgd-PNR7UKLL.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/code/prompt.ts","../src/code/apply.ts","../src/code/diff.ts","../src/code/providers.ts"],"names":["i","j"],"mappings":";;;AAoBO,IAAM,kBAAA,GAAqB;AAAA,EAChC,6EAAA;AAAA,EACA,wFAAA;AAAA,EACA,qEAAA;AAAA,EACA,EAAA;AAAA,EACA,mEAAA;AAAA,EACA,EAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,+BAAA;AAAA,EACA,SAAA;AAAA,EACA,qBAAA;AAAA,EACA,iBAAA;AAAA,EACA,EAAA;AAAA,EACA,qFAAA;AAAA,EACA,wBAAA;AAAA,EACA,uBAAA;AAAA,EACA,kBAAA;AAAA,EACA,YAAA;AAAA,EACA,6CAAA;AAAA,EACA,EAAA;AAAA,EACA;AACF,CAAA,CAAE,KAAK,IAAI,CAAA;AAWJ,SAAS,cAAc,OAAA,EAAqC;AACjE,EAAA,OAAO;AAAA,IACL,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,kBAAA,EAAmB;AAAA,IAC9C,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,QAAQ,QAAA,EAAS;AAAA,IAC1C,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA,iCAAA,EAAoC,OAAA,CAAQ,WAAW,CAAA,CAAA;AAAG,GACrF;AACF;AAOO,IAAM,mBAAA,GAAsB;AAAA,EACjC,wHAAA;AAAA,EACA,wKAAA;AAAA,EACA,yGAAA;AAAA,EACA,wDAAA;AAAA,EACA,EAAA;AAAA,EACA,6FAAA;AAAA,EACA,uDAAA;AAAA,EACA,EAAA;AAAA,EACA,wHAAA;AAAA,EACA,4FAAA;AAAA,EACA,yDAAA;AAAA,EACA,EAAA;AAAA,EACA,0EAAA;AAAA,EACA,8EAAA;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A,CAAM,CAAA,qCAAA,EAAwC,IAAA,CAAK,SAAS,WAAM,aAAA,CAAe,CAAA,CAAY,OAAO,CAAC,CAAA,CAAE,CAAA;AAAA,IACnH;AAAA,EACF;AACF","file":"chunk-TRKRRX2S.js","sourcesContent":["/**\n * Prompt assembly with cache-stable ordering (VG-CLI-CODE §5.1).\n *\n * The fast coding tools lean hard on prompt caching — cached tokens are roughly\n * an order of magnitude cheaper and skip re-encoding, so hit-rate is a\n * first-class speed lever. A cache only helps if the *prefix* is byte-stable\n * across turns, which makes prompt ordering a scheduling constraint, not a\n * cosmetic choice: put the invariant material (the instruction contract + the\n * repo-derived context) first and the volatile turn-specific ask last. This\n * module is the single place that ordering is enforced, so every provider\n * inherits it.\n */\n\nimport type { ChatMessage, CodeContext } from './types.js';\n\n/**\n * The system contract for the planner. Intentionally fixed (no interpolation)\n * so it is a perfectly stable cache prefix. It pins the edit *format* the\n * deterministic applier expects — the model's only job is to emit these blocks.\n */\nexport const CODE_SYSTEM_PROMPT = [\n 'You are a precise code-editing assistant operating inside the Vibgrate CLI.',\n 'You are given repository context derived from a deterministic code graph, then a task.',\n 'Propose the smallest correct change. Do not restate unchanged code.',\n '',\n 'Reply ONLY with edit blocks in this exact format, one per change:',\n '',\n '<path/to/file>',\n '<<<<<<< SEARCH',\n '<exact current lines to find>',\n '=======',\n '<replacement lines>',\n '>>>>>>> REPLACE',\n '',\n 'The SEARCH text must match the current file (whitespace differences are tolerated).',\n 'To add a new file use:',\n 'CREATE <path/to/file>',\n '<full file body>',\n 'END CREATE',\n 'To remove a file use: DELETE <path/to/file>',\n '',\n 'Respect every hard constraint in the context. Keep edits minimal and self-consistent.',\n].join('\\n');\n\n/**\n * Build the chat messages for a planning turn, in cache-stable order:\n * 1. system contract (fixed)\n * 2. repository context (stable for the repo/turn — the big, reusable prefix)\n * 3. the task instruction (volatile — always last)\n *\n * Keeping the volatile instruction in its own trailing user turn maximizes the\n * reusable prefix when the same repo is edited across multiple asks.\n */\nexport function buildMessages(context: CodeContext): ChatMessage[] {\n return [\n { role: 'system', content: CODE_SYSTEM_PROMPT },\n { role: 'user', content: context.rendered },\n { role: 'user', content: `Now produce the edit blocks for: ${context.instruction}` },\n ];\n}\n\n/**\n * The system contract for the agentic loop (tool-calling). Fixed text → stable\n * cache prefix. Full coding agent (Claude Code / Codex / Cline / OpenHands class):\n * free tool use, Markdown answers, edits only via tools — never a forced edit IR.\n */\nexport const AGENT_SYSTEM_PROMPT = [\n 'You are VG Code — a full coding agent in a real repository (parity with Claude Code / Codex / Cline / OpenHands).',\n 'You handle every intent: questions, locate/search, design discussion, and multi-file edits. The host never forces an edit format on your turn — you choose tools.',\n 'Most requests change application source. Prefer editing code under packages/src, not package manifests,',\n 'unless the user asks for dependency or packaging work.',\n '',\n 'You receive a Task Capsule (ranked symbols + source slices) as first-turn evidence. Use it;',\n 'it does not replace tools when you need more context.',\n '',\n 'Tools: search_code (graph + literal string/URL sweep — like workspace Find), read_file, list_files, graph_impact,',\n 'library_docs, edit_file, create_file, delete_file, apply_patch, run_command, inspect_task,',\n 'inspect_change, verify_change, ask_user, finish, abort.',\n '',\n 'You also always have the local Vibgrate AI Context MCP tools (namespaced',\n 'mcp__vibgrate__*): search_symbols, query_graph, orient, get_node, impact_of,',\n 'library_docs, check_drift, and the rest of `vg serve`. Prefer them for deep',\n 'graph navigation, docs, and drift. Project MCP servers may add more mcp__* tools.',\n '',\n '## How to work',\n '- Search or read before you edit. Never invent file contents.',\n '- Smallest correct change; check graph_impact / mcp__vibgrate__impact_of before touching shared hubs.',\n '- edit_file SEARCH must match current file (whitespace-flexible). Prefer apply_patch for multi-file edits.',\n '- Run tests or build when useful; use verify_change after multi-file work.',\n '- Mutating tools and shell need user approval — adapt if declined.',\n '',\n '## Answers and task space',\n '- Call finish with a Markdown summary: what you did or found, key `file:line` refs, next steps.',\n '- Q&A / locate / explain: use search_code (pass the exact needle, e.g. stripe or \"stripe\"), then finish with Markdown.',\n '- Do not invent PatchIR, dummy edits, or raw JSON as the user-facing answer. Edits only via edit_file / apply_patch tools.',\n '',\n '## When stuck',\n '- If intent, scope, or trade-off is ambiguous, call ask_user with one clear question (optional options).',\n '- Prefer ask_user over abort when the user can unblock you. Do not guess product requirements.',\n '- abort only when the request is impossible after clarification or lookup.',\n '',\n 'Never dump raw JSON schemas, PatchIR templates, or tool wire formats as the user-facing answer.',\n].join('\\n');\n\n/** Build the opening messages for an agent run: system contract + graph-grounded context + task. */\nexport function buildAgentMessages(context: CodeContext): ChatMessage[] {\n return [\n { role: 'system', content: AGENT_SYSTEM_PROMPT },\n { role: 'user', content: context.rendered },\n { role: 'user', content: `Task: ${context.instruction}` },\n ];\n}\n","/**\n * The deterministic fast-apply merge engine (VG-CLI-CODE §4).\n *\n * Speed in the fast coding tools comes from letting the planner emit a *terse*\n * edit instead of rewriting a whole file; correctness comes from applying that\n * edit **deterministically and scoped**, never by letting the model free-hand\n * the merge. This module is that deterministic floor: it parses the\n * search/replace edit form and applies it with three escalating match\n * strategies — exact, whitespace-flexible, then graph-span-scoped — so an\n * ambiguous SEARCH is resolved to the symbol the planner actually named rather\n * than the first textual hit. No model is required to apply an edit; a hosted\n * fast-apply model is only ever an *acceleration* over this same contract.\n *\n * Everything here is pure and deterministic: identical (content, edit) always\n * yields the identical outcome, which is what makes it unit- and\n * benchmark-testable offline.\n */\n\nimport type { CodeEdit, EditOutcome } from './types.js';\n\n/** A symbol span the graph knows about, used to disambiguate a SEARCH match. */\nexport interface SymbolSpan {\n /** Qualified name, matched against `anchorSymbol`. */\n qualifiedName: string;\n file: string;\n /** 1-based inclusive line range. */\n start: number;\n end: number;\n}\n\n/**\n * Parse a model's reply into structured edits. The accepted form is the\n * widely-supported search/replace block (robust to surrounding prose and code\n * fences), plus explicit whole-file create/delete markers:\n *\n * ```\n * path/to/file.ts\n * <<<<<<< SEARCH\n * old code\n * =======\n * new code\n * >>>>>>> REPLACE\n * ```\n *\n * `CREATE path/to/new.ts` … `END CREATE` wraps a new file's whole body;\n * `DELETE path/to/gone.ts` removes a file. Parsing is forgiving of blank lines\n * and fences but strict about the block markers, so a malformed block surfaces\n * as an `invalid` outcome at apply time rather than silently corrupting a file.\n */\nexport function parseEdits(text: string): CodeEdit[] {\n const edits: CodeEdit[] = [];\n const lines = text.split('\\n');\n let i = 0;\n let pendingFile = '';\n\n const isFence = (s: string): boolean => /^\\s*```/.test(s);\n\n while (i < lines.length) {\n const line = lines[i];\n\n // Whole-file create: `CREATE <path>` … `END CREATE`.\n const create = /^\\s*CREATE\\s+(\\S.*?)\\s*$/.exec(line);\n if (create) {\n const file = create[1];\n const body: string[] = [];\n i++;\n while (i < lines.length && !/^\\s*END CREATE\\s*$/.test(lines[i])) {\n if (!isFence(lines[i])) body.push(lines[i]);\n i++;\n }\n i++; // consume END CREATE\n edits.push({ op: 'create', file, content: body.join('\\n') });\n pendingFile = '';\n continue;\n }\n\n // Whole-file delete: `DELETE <path>`.\n const del = /^\\s*DELETE\\s+(\\S.*?)\\s*$/.exec(line);\n if (del) {\n edits.push({ op: 'delete', file: del[1] });\n i++;\n pendingFile = '';\n continue;\n }\n\n // Search/replace block. The file path is the most recent non-fence,\n // non-blank line before the SEARCH marker (or an inline `path` on it).\n if (/^\\s*<{5,}\\s*SEARCH/.test(line)) {\n const file = pendingFile;\n const search: string[] = [];\n const replace: string[] = [];\n i++;\n while (i < lines.length && !/^\\s*={5,}\\s*$/.test(lines[i])) {\n search.push(lines[i]);\n i++;\n }\n i++; // consume =======\n while (i < lines.length && !/^\\s*>{5,}\\s*REPLACE/.test(lines[i])) {\n replace.push(lines[i]);\n i++;\n }\n i++; // consume >>>>>>> REPLACE\n edits.push({\n op: 'replace',\n file,\n search: search.join('\\n'),\n replace: replace.join('\\n'),\n anchorSymbol: undefined,\n });\n continue;\n }\n\n // Track the most recent file-path candidate: a lone token that looks like a\n // path (has a slash or a file extension) and isn't a fence/marker.\n const trimmed = line.trim();\n if (trimmed && !isFence(line) && looksLikePath(trimmed)) pendingFile = trimmed.replace(/[:`]+$/, '');\n i++;\n }\n\n return edits;\n}\n\nfunction looksLikePath(s: string): boolean {\n if (/\\s/.test(s.replace(/:$/, ''))) return false; // paths don't contain spaces\n return /\\//.test(s) || /\\.[A-Za-z0-9]{1,8}:?$/.test(s);\n}\n\n/**\n * Apply a single edit to a file's current content (or `null` when the file does\n * not exist). Pure: returns the new content and an outcome; never touches disk.\n * The `spans` are the graph's symbol spans for this file — when a SEARCH is\n * textually ambiguous, a match inside the `anchorSymbol` span wins, which is how\n * the graph makes a terse edit land where the planner meant it to.\n */\nexport function applyEdit(\n content: string | null,\n edit: CodeEdit,\n spans: SymbolSpan[] = [],\n): { content: string | null; outcome: EditOutcome } {\n if (edit.op === 'create') {\n if (content !== null && content !== edit.content) {\n return { content, outcome: { edit, status: 'conflict', reason: `${edit.file} already exists — refusing to overwrite it with a create; use a replace edit instead` } };\n }\n return { content: edit.content, outcome: { edit, status: content === edit.content ? 'no-op' : 'applied', matchedBy: 'exact' } };\n }\n\n if (edit.op === 'delete') {\n if (content === null) return { content: null, outcome: { edit, status: 'no-op', reason: `${edit.file} does not exist — nothing to delete` } };\n return { content: null, outcome: { edit, status: 'applied', matchedBy: 'exact' } };\n }\n\n // op === 'replace'\n if (content === null) {\n return { content: null, outcome: { edit, status: 'not-found', reason: `${edit.file} does not exist — a replace needs an existing file (did you mean CREATE ${edit.file}?)` } };\n }\n if (edit.search === '') {\n // Empty SEARCH means \"prepend\" only when the file is empty; otherwise it is\n // ambiguous and we refuse rather than guess a location.\n if (content === '') return { content: edit.replace, outcome: { edit, status: 'applied', matchedBy: 'exact' } };\n return { content, outcome: { edit, status: 'invalid', reason: 'empty SEARCH on a non-empty file is ambiguous — quote the exact lines to replace' } };\n }\n if (edit.search === edit.replace) {\n return { content, outcome: { edit, status: 'no-op', reason: 'SEARCH and REPLACE are identical — no change' } };\n }\n\n const located = locate(content, edit.search, edit.anchorSymbol, spans, edit.file);\n if (located.kind === 'none') {\n return { content, outcome: { edit, status: 'not-found', reason: `the SEARCH text was not found in ${edit.file} — it must match the current file exactly (whitespace-flexible)` } };\n }\n if (located.kind === 'ambiguous') {\n return {\n content,\n outcome: {\n edit,\n status: 'ambiguous',\n reason: `the SEARCH text matches ${located.count} places in ${edit.file} — add more surrounding lines, or name the symbol so the graph can disambiguate`,\n },\n };\n }\n const next = content.slice(0, located.from) + edit.replace + content.slice(located.to);\n return { content: next, outcome: { edit, status: 'applied', matchedBy: located.matchedBy } };\n}\n\n/**\n * Apply a set of edits across a set of files. `read(file)` returns current\n * content or `null`. Edits are applied in the order given, threading each\n * file's evolving content so two edits to the same file compose. Returns, per\n * file, its before/after content and the per-edit outcomes — the dry-run\n * product the session turns into diffs. Deterministic given a deterministic\n * `read`.\n */\nexport function applyEdits(\n edits: CodeEdit[],\n read: (file: string) => string | null,\n spansByFile: (file: string) => SymbolSpan[] = () => [],\n): Map<string, { before: string | null; after: string | null; outcomes: EditOutcome[] }> {\n const state = new Map<string, { before: string | null; after: string | null; outcomes: EditOutcome[] }>();\n for (const edit of edits) {\n let entry = state.get(edit.file);\n if (!entry) {\n const before = read(edit.file);\n entry = { before, after: before, outcomes: [] };\n state.set(edit.file, entry);\n }\n const { content, outcome } = applyEdit(entry.after, edit, spansByFile(edit.file));\n entry.after = content;\n entry.outcomes.push(outcome);\n }\n return state;\n}\n\ntype Located =\n | { kind: 'unique'; from: number; to: number; matchedBy: 'exact' | 'whitespace' | 'graph-span' }\n | { kind: 'ambiguous'; count: number }\n | { kind: 'none' };\n\n/**\n * Find the SEARCH text in the content. Escalates: (1) exact substring; (2)\n * whitespace-flexible (indentation/trailing-space differences tolerated); and\n * when either is ambiguous, (3) narrow to the `anchorSymbol`'s graph span so the\n * intended occurrence wins. Line-oriented so offsets map back to real edits.\n */\nfunction locate(content: string, search: string, anchor: string | undefined, spans: SymbolSpan[], file: string): Located {\n const exact = allIndexes(content, search);\n if (exact.length === 1) return { kind: 'unique', from: exact[0], to: exact[0] + search.length, matchedBy: 'exact' };\n if (exact.length > 1) {\n const scoped = scopeToAnchor(content, exact.map((from) => ({ from, to: from + search.length })), anchor, spans, file);\n if (scoped) return { ...scoped, matchedBy: 'graph-span' };\n return { kind: 'ambiguous', count: exact.length };\n }\n\n // Whitespace-flexible: compare with runs of whitespace collapsed and each\n // line trimmed, then map the match back to real character offsets.\n const flex = flexIndexes(content, search);\n if (flex.length === 1) return { kind: 'unique', from: flex[0].from, to: flex[0].to, matchedBy: 'whitespace' };\n if (flex.length > 1) {\n const scoped = scopeToAnchor(content, flex, anchor, spans, file);\n if (scoped) return { ...scoped, matchedBy: 'graph-span' };\n return { kind: 'ambiguous', count: flex.length };\n }\n return { kind: 'none' };\n}\n\n/** Every start index of `needle` in `hay` (non-overlapping left-to-right). */\nfunction allIndexes(hay: string, needle: string): number[] {\n const out: number[] = [];\n if (needle === '') return out;\n let from = 0;\n for (;;) {\n const idx = hay.indexOf(needle, from);\n if (idx === -1) break;\n out.push(idx);\n from = idx + needle.length;\n }\n return out;\n}\n\n/**\n * Whitespace-flexible match: align the search's trimmed non-empty lines against\n * the content's lines, tolerating indentation and trailing-whitespace drift\n * (the single most common reason an otherwise-correct terse edit fails to\n * apply). Returns real character offset ranges for each full-block match.\n */\nfunction flexIndexes(content: string, search: string): { from: number; to: number }[] {\n const cLines = content.split('\\n');\n const sLines = search.split('\\n');\n // Trim a possible leading/trailing blank line from the search block.\n while (sLines.length && sLines[0].trim() === '') sLines.shift();\n while (sLines.length && sLines[sLines.length - 1].trim() === '') sLines.pop();\n if (sLines.length === 0) return [];\n const sNorm = sLines.map((l) => l.trim());\n\n // Precompute char offset of the start of each content line.\n const lineStart: number[] = [];\n let acc = 0;\n for (const l of cLines) {\n lineStart.push(acc);\n acc += l.length + 1; // +1 for the '\\n'\n }\n\n const out: { from: number; to: number }[] = [];\n for (let i = 0; i + sNorm.length <= cLines.length; i++) {\n let ok = true;\n for (let j = 0; j < sNorm.length; j++) {\n if (cLines[i + j].trim() !== sNorm[j]) {\n ok = false;\n break;\n }\n }\n if (!ok) continue;\n const from = lineStart[i];\n const lastLine = i + sNorm.length - 1;\n const to = lineStart[lastLine] + cLines[lastLine].length; // end of the last matched line (exclusive of '\\n')\n out.push({ from, to });\n }\n return out;\n}\n\n/** If exactly one candidate falls inside the anchor symbol's span, pick it. */\nfunction scopeToAnchor(\n content: string,\n candidates: { from: number; to: number }[],\n anchor: string | undefined,\n spans: SymbolSpan[],\n file: string,\n): { kind: 'unique'; from: number; to: number } | null {\n if (!anchor) return null;\n const span = spans.find((s) => s.file === file && s.qualifiedName === anchor);\n if (!span) return null;\n const lineOf = lineIndexer(content);\n const inside = candidates.filter((c) => {\n const line = lineOf(c.from); // 1-based\n return line >= span.start && line <= span.end;\n });\n if (inside.length === 1) return { kind: 'unique', from: inside[0].from, to: inside[0].to };\n return null;\n}\n\n/** Returns a function mapping a char offset → 1-based line number. */\nfunction lineIndexer(content: string): (offset: number) => number {\n const starts: number[] = [0];\n for (let i = 0; i < content.length; i++) if (content[i] === '\\n') starts.push(i + 1);\n return (offset: number) => {\n // binary search for the greatest line start <= offset\n let lo = 0;\n let hi = starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (starts[mid] <= offset) lo = mid;\n else hi = mid - 1;\n }\n return lo + 1;\n };\n}\n","/**\n * Deterministic unified diff (VG-CLI-CODE §4.3).\n *\n * A `vg code` dry-run shows the human/agent exactly what would change *before*\n * anything is written — the \"inspect the proposal\" half of the governance\n * lifecycle. This is a small, dependency-free Myers-style line diff producing\n * standard unified-diff hunks. Identical (before, after) always renders the\n * identical text, so the dry-run output is stable and diff-able in tests and\n * benchmarks.\n */\n\n/** Render a unified diff for one file. Returns '' when there is no change. */\nexport function unifiedDiff(before: string | null, after: string | null, file: string, context = 3): string {\n if (before === after) return '';\n if (before === null) return newFileDiff(after ?? '', file);\n if (after === null) return deletedFileDiff(before, file);\n\n const a = splitLines(before);\n const b = splitLines(after);\n const ops = diffLines(a, b);\n const hunks = groupHunks(ops, context);\n if (hunks.length === 0) return '';\n\n const out: string[] = [`--- a/${file}`, `+++ b/${file}`];\n for (const h of hunks) {\n out.push(`@@ -${h.aStart},${h.aLen} +${h.bStart},${h.bLen} @@`);\n for (const line of h.lines) out.push(line);\n }\n return out.join('\\n');\n}\n\nfunction newFileDiff(after: string, file: string): string {\n const lines = splitLines(after);\n const out = [`--- /dev/null`, `+++ b/${file}`, `@@ -0,0 +1,${lines.length} @@`];\n for (const l of lines) out.push(`+${l}`);\n return out.join('\\n');\n}\n\nfunction deletedFileDiff(before: string, file: string): string {\n const lines = splitLines(before);\n const out = [`--- a/${file}`, `+++ /dev/null`, `@@ -1,${lines.length} +0,0 @@`];\n for (const l of lines) out.push(`-${l}`);\n return out.join('\\n');\n}\n\nfunction splitLines(s: string): string[] {\n if (s === '') return [];\n const lines = s.split('\\n');\n // A trailing newline yields a final '' element — drop it so line counts match.\n if (lines.length && lines[lines.length - 1] === '') lines.pop();\n return lines;\n}\n\ntype Op = { tag: 'eq' | 'del' | 'add'; line: string };\n\n/**\n * Line diff via LCS (dynamic programming). O(n·m) space is fine for source\n * files; the deterministic backtrace (favouring deletions before additions on\n * ties) keeps output stable.\n */\nfunction diffLines(a: string[], b: string[]): Op[] {\n const n = a.length;\n const m = b.length;\n const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);\n }\n }\n const ops: Op[] = [];\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (a[i] === b[j]) {\n ops.push({ tag: 'eq', line: a[i] });\n i++;\n j++;\n } else if (dp[i + 1][j] >= dp[i][j + 1]) {\n ops.push({ tag: 'del', line: a[i] });\n i++;\n } else {\n ops.push({ tag: 'add', line: b[j] });\n j++;\n }\n }\n while (i < n) ops.push({ tag: 'del', line: a[i++] });\n while (j < m) ops.push({ tag: 'add', line: b[j++] });\n return ops;\n}\n\ninterface Hunk {\n aStart: number;\n aLen: number;\n bStart: number;\n bLen: number;\n lines: string[];\n}\n\n/** Group the op stream into unified-diff hunks with `context` equal lines around changes. */\nfunction groupHunks(ops: Op[], context: number): Hunk[] {\n // Index of each op that is a change (del/add).\n const changeIdx = ops.map((o, i) => (o.tag === 'eq' ? -1 : i)).filter((i) => i >= 0);\n if (changeIdx.length === 0) return [];\n\n // Merge change indices into windows that share context.\n const windows: [number, number][] = [];\n let start = Math.max(0, changeIdx[0] - context);\n let end = Math.min(ops.length - 1, changeIdx[0] + context);\n for (let k = 1; k < changeIdx.length; k++) {\n const cs = Math.max(0, changeIdx[k] - context);\n const ce = Math.min(ops.length - 1, changeIdx[k] + context);\n if (cs <= end + 1) {\n end = ce;\n } else {\n windows.push([start, end]);\n start = cs;\n end = ce;\n }\n }\n windows.push([start, end]);\n\n const hunks: Hunk[] = [];\n // Running 1-based line numbers into a and b.\n let aLine = 1;\n let bLine = 1;\n let idx = 0;\n for (const [ws, we] of windows) {\n // advance line counters up to window start\n while (idx < ws) {\n const o = ops[idx];\n if (o.tag !== 'add') aLine++;\n if (o.tag !== 'del') bLine++;\n idx++;\n }\n const hunk: Hunk = { aStart: aLine, aLen: 0, bStart: bLine, bLen: 0, lines: [] };\n for (let k = ws; k <= we; k++) {\n const o = ops[k];\n if (o.tag === 'eq') {\n hunk.lines.push(` ${o.line}`);\n hunk.aLen++;\n hunk.bLen++;\n aLine++;\n bLine++;\n } else if (o.tag === 'del') {\n hunk.lines.push(`-${o.line}`);\n hunk.aLen++;\n aLine++;\n } else {\n hunk.lines.push(`+${o.line}`);\n hunk.bLen++;\n bLine++;\n }\n idx = k + 1;\n }\n // A hunk that starts at line 1 with zero length should report start 0.\n if (hunk.aLen === 0) hunk.aStart = Math.max(0, hunk.aStart - 1);\n if (hunk.bLen === 0) hunk.bStart = Math.max(0, hunk.bStart - 1);\n hunks.push(hunk);\n }\n return hunks;\n}\n\n/** A compact one-line changeset summary: `+adds -dels across N file(s)`. */\nexport function summarizeDiffs(diffs: { file: string; diff: string }[]): string {\n let adds = 0;\n let dels = 0;\n let touched = 0;\n for (const { diff } of diffs) {\n if (!diff) continue;\n touched++;\n for (const line of diff.split('\\n')) {\n if (line.startsWith('+') && !line.startsWith('+++')) adds++;\n else if (line.startsWith('-') && !line.startsWith('---')) dels++;\n }\n }\n return `+${adds} -${dels} across ${touched} file(s)`;\n}\n","/**\n * Model backends for `vg code` (VG-CLI-CODE §5).\n *\n * Every backend implements the same {@link Provider} contract, so the router and\n * session are provider-agnostic. Three families:\n * - **local HTTP** — Ollama and LM Studio, reached over `fetch` on localhost;\n * no package, no key, no egress. Selected under `--local`.\n * - **hosted HTTP** — any OpenAI-compatible endpoint (OpenRouter, LiteLLM,\n * Together, a self-hosted gateway, …). One shape covers the \"best in breed\n * router\" story: an ordered model list with automatic fallback lives in the\n * router, not here. Keys come from the environment only and are never logged.\n * - **local inference** — a llama.cpp binding loaded on demand via\n * {@link ensurePackage}; this is the one path that may install a package on\n * first use, and only with consent. Model weights are never auto-downloaded.\n *\n * A deterministic {@link MockProvider} backs the tests, the offline benchmark,\n * and the `--mock` flag, so the whole loop runs end-to-end with no network.\n */\n\nimport { ensurePackage, ensureUnavailableMessage } from './ensure.js';\nimport type { ChatMessage, ChatOptions, Provider, ProviderResult, ToolCall, ToolSpec } from './types.js';\n\n/* ------------------------------------------------------------------ *\\\n * Tool-calling wire helpers (shared by the HTTP providers)\n\\* ------------------------------------------------------------------ */\n\n/** Map our ChatMessage union to OpenAI-compatible wire messages (tool calls included). */\nfunction openAiMessages(messages: ChatMessage[]): unknown[] {\n return messages.map((m) => {\n if (m.role === 'tool') return { role: 'tool', tool_call_id: m.toolCallId, name: m.name, content: m.content };\n if (m.role === 'assistant' && m.toolCalls?.length) {\n return {\n role: 'assistant',\n content: m.content || null,\n tool_calls: m.toolCalls.map((t) => ({ id: t.id, type: 'function', function: { name: t.name, arguments: JSON.stringify(t.arguments) } })),\n };\n }\n return { role: m.role, content: m.content };\n });\n}\n\n/** OpenAI-compatible `tools` array from our specs. */\nfunction openAiTools(tools: ToolSpec[] | undefined): unknown[] | undefined {\n if (!tools?.length) return undefined;\n return tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }));\n}\n\n/** Parse OpenAI-shaped tool_calls, tolerating a malformed arguments string. */\nfunction parseToolCalls(raw: unknown, synthesizePrefix = 'call'): ToolCall[] {\n const calls = raw as { id?: string; function?: { name?: string; arguments?: unknown } }[] | undefined;\n if (!Array.isArray(calls)) return [];\n return calls.map((c, i) => ({\n id: typeof c.id === 'string' && c.id ? c.id : `${synthesizePrefix}_${i}`,\n name: c.function?.name ?? 'unknown',\n arguments: coerceArgs(c.function?.arguments),\n }));\n}\n\nfunction coerceArgs(raw: unknown): Record<string, unknown> {\n if (raw && typeof raw === 'object') return raw as Record<string, unknown>;\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/** Redact anything that looks like a credential before it can reach a log/error. */\nexport function redactSecrets(s: string): string {\n return s\n .replace(/\\b(sk|xoxb|ghp|gho|glpat|AKIA)[-_][A-Za-z0-9-_]{6,}/g, '$1-***redacted***')\n .replace(/Bearer\\s+[A-Za-z0-9._-]{8,}/gi, 'Bearer ***redacted***');\n}\n\n/** Common HTTP-completion error shaping: actionable, internals-free (GUARDRAILS §1.3). */\nfunction httpError(label: string, status: number, hint: string): Error {\n return new Error(`${label} returned HTTP ${status} — ${hint}`);\n}\n\n/** Yield newline-delimited lines from a streamed response body. */\nasync function* streamLines(res: Response): AsyncGenerator<string> {\n const reader = res.body?.getReader();\n if (!reader) return;\n const decoder = new TextDecoder();\n let buf = '';\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n let idx: number;\n while ((idx = buf.indexOf('\\n')) >= 0) {\n const line = buf.slice(0, idx).trim();\n buf = buf.slice(idx + 1);\n if (line) yield line;\n }\n }\n if (buf.trim()) yield buf.trim();\n}\n\n/** Accumulate an OpenAI-compatible SSE stream into text + tool calls + usage. */\nexport function accumulateOpenAiDelta(\n acc: { text: string; tools: Map<number, { id?: string; name?: string; args: string }>; usage: { promptTokens?: number; completionTokens?: number } },\n chunk: unknown,\n onToken?: (t: string) => void,\n): void {\n const c = chunk as { choices?: { delta?: { content?: string; tool_calls?: { index?: number; id?: string; function?: { name?: string; arguments?: string } }[] } }[]; usage?: { prompt_tokens?: number; completion_tokens?: number } };\n const delta = c.choices?.[0]?.delta;\n if (delta?.content) {\n acc.text += delta.content;\n onToken?.(delta.content);\n }\n for (const tc of delta?.tool_calls ?? []) {\n const idx = tc.index ?? 0;\n const e = acc.tools.get(idx) ?? { args: '' };\n if (tc.id) e.id = tc.id;\n if (tc.function?.name) e.name = tc.function.name;\n if (tc.function?.arguments) e.args += tc.function.arguments;\n acc.tools.set(idx, e);\n }\n if (c.usage) {\n acc.usage.promptTokens = c.usage.prompt_tokens;\n acc.usage.completionTokens = c.usage.completion_tokens;\n }\n}\n\n/** Turn accumulated OpenAI tool-call fragments into ToolCalls. */\nfunction finalizeTools(tools: Map<number, { id?: string; name?: string; args: string }>): ToolCall[] {\n return [...tools.entries()]\n .sort((a, b) => a[0] - b[0])\n .map(([i, e]) => ({ id: e.id ?? `call_${i}`, name: e.name ?? 'unknown', arguments: coerceArgs(e.args) }));\n}\n\nasync function postJson(url: string, body: unknown, headers: Record<string, string>, timeoutMs: number): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Deterministic mock (tests / offline / --mock)\n\\* ------------------------------------------------------------------ */\n\n/**\n * A provider that returns a fixed, scripted reply — the deterministic floor that\n * lets the entire `vg code` loop run offline. Used by tests, the benchmark, and\n * the `--mock` flag (which reads the scripted edit blocks from a file).\n */\nexport class MockProvider implements Provider {\n readonly id = 'mock';\n readonly label = 'Mock (deterministic)';\n readonly local = true;\n constructor(\n readonly model: string,\n private readonly reply: string,\n ) {}\n async chat(_messages?: ChatMessage[], _opts?: ChatOptions): Promise<ProviderResult> {\n return { text: this.reply, model: this.model, provider: this.id };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Ollama (local, no key)\n\\* ------------------------------------------------------------------ */\n\nexport class OllamaProvider implements Provider {\n readonly id = 'ollama';\n readonly label = 'Ollama (local)';\n readonly local = true;\n constructor(\n readonly model: string,\n private readonly host = process.env.OLLAMA_HOST || 'http://127.0.0.1:11434',\n ) {}\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const streaming = !!(opts.stream && opts.onToken);\n let res: Response;\n try {\n res = await postJson(\n `${this.host.replace(/\\/$/, '')}/api/chat`,\n { model: this.model, messages: openAiMessages(messages), stream: streaming, tools: openAiTools(opts.tools), options: { temperature: opts.temperature ?? 0 } },\n {},\n opts.timeoutMs ?? 120_000,\n );\n } catch {\n throw new Error(`couldn't reach Ollama at ${this.host} — is \\`ollama serve\\` running? (start it, or pass --provider to use a different backend)`);\n }\n if (!res.ok) throw httpError('Ollama', res.status, res.status === 404 ? `model \"${this.model}\" isn't pulled — run \\`ollama pull ${this.model}\\` or pick another with --model` : 'check `ollama serve` and the model name');\n\n if (streaming) {\n let text = '';\n let toolCallsRaw: unknown;\n const usage: { promptTokens?: number; completionTokens?: number } = {};\n for await (const line of streamLines(res)) {\n try {\n const obj = JSON.parse(line) as { message?: { content?: string; tool_calls?: unknown }; prompt_eval_count?: number; eval_count?: number };\n const delta = obj.message?.content;\n if (delta) {\n text += delta;\n opts.onToken?.(delta);\n }\n if (obj.message?.tool_calls) toolCallsRaw = obj.message.tool_calls;\n if (typeof obj.prompt_eval_count === 'number') usage.promptTokens = obj.prompt_eval_count;\n if (typeof obj.eval_count === 'number') usage.completionTokens = obj.eval_count;\n } catch {\n /* skip a malformed line */\n }\n }\n return { text, model: this.model, provider: this.id, toolCalls: parseToolCalls(toolCallsRaw), usage };\n }\n\n const data = (await res.json()) as { message?: { content?: string; tool_calls?: unknown }; prompt_eval_count?: number; eval_count?: number };\n return {\n text: data.message?.content ?? '',\n model: this.model,\n provider: this.id,\n toolCalls: parseToolCalls(data.message?.tool_calls),\n usage: { promptTokens: data.prompt_eval_count, completionTokens: data.eval_count },\n };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * OpenAI-compatible (LM Studio, OpenRouter, LiteLLM, …)\n\\* ------------------------------------------------------------------ */\n\nexport interface OpenAiCompatibleConfig {\n /** Base URL, e.g. `https://openrouter.ai/api/v1` or `http://127.0.0.1:1234/v1`. */\n baseUrl: string;\n /** Env var name holding the API key (never the key itself). Absent for local. */\n apiKeyEnv?: string;\n /** Whether this endpoint is on-device (LM Studio) vs hosted. */\n local: boolean;\n /** Display label. */\n label: string;\n id: string;\n}\n\nexport class OpenAiCompatibleProvider implements Provider {\n readonly id: string;\n readonly label: string;\n readonly local: boolean;\n constructor(\n readonly model: string,\n private readonly config: OpenAiCompatibleConfig,\n ) {\n this.id = config.id;\n this.label = config.label;\n this.local = config.local;\n }\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const headers: Record<string, string> = {};\n if (this.config.apiKeyEnv) {\n const key = process.env[this.config.apiKeyEnv];\n if (!key) {\n throw new Error(`${this.label} needs an API key in ${this.config.apiKeyEnv} — set it in your environment (never pass keys as flags), or use --local for an on-device backend.`);\n }\n headers.authorization = `Bearer ${key}`;\n }\n const streaming = !!(opts.stream && opts.onToken);\n const url = `${this.config.baseUrl.replace(/\\/$/, '')}/chat/completions`;\n const body = {\n model: this.model,\n messages: openAiMessages(messages),\n tools: openAiTools(opts.tools),\n temperature: opts.temperature ?? 0,\n max_tokens: opts.maxTokens,\n stream: streaming,\n ...(streaming ? { stream_options: { include_usage: true } } : {}),\n };\n let res: Response;\n try {\n res = await postJson(url, body, headers, opts.timeoutMs ?? 120_000);\n } catch {\n throw new Error(`couldn't reach ${this.label} at ${this.config.baseUrl} — check the endpoint is up (or use --local).`);\n }\n if (!res.ok) {\n const hint = res.status === 401 || res.status === 403 ? `the key in ${this.config.apiKeyEnv ?? '(none)'} was rejected — check it has access to \"${this.model}\"` : `check the model id \"${this.model}\" and the endpoint`;\n throw httpError(this.label, res.status, hint);\n }\n\n if (streaming) {\n const acc = { text: '', tools: new Map<number, { id?: string; name?: string; args: string }>(), usage: {} as { promptTokens?: number; completionTokens?: number } };\n for await (const line of streamLines(res)) {\n if (!line.startsWith('data:')) continue;\n const payload = line.slice(5).trim();\n if (payload === '[DONE]') break;\n try {\n accumulateOpenAiDelta(acc, JSON.parse(payload), opts.onToken);\n } catch {\n /* skip a malformed chunk */\n }\n }\n const tools = finalizeTools(acc.tools);\n return { text: acc.text, model: this.model, provider: this.id, toolCalls: tools.length ? tools : undefined, usage: acc.usage };\n }\n const data = (await res.json()) as { choices?: { message?: { content?: string; tool_calls?: unknown } }[]; usage?: { prompt_tokens?: number; completion_tokens?: number } };\n const message = data.choices?.[0]?.message;\n return {\n text: message?.content ?? '',\n model: this.model,\n provider: this.id,\n toolCalls: parseToolCalls(message?.tool_calls),\n usage: { promptTokens: data.usage?.prompt_tokens, completionTokens: data.usage?.completion_tokens },\n };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Scripted provider (agent-loop tests / offline demos)\n\\* ------------------------------------------------------------------ */\n\n/**\n * Returns a queued sequence of {@link ProviderResult}s — one per turn — so the\n * agentic loop can be driven deterministically offline: script the tool calls\n * the \"model\" makes (read → search → edit → run → finish) and assert what the\n * agent did. Ignores the incoming messages by design.\n */\nexport class ScriptedProvider implements Provider {\n readonly id = 'scripted';\n readonly label = 'Scripted (deterministic)';\n readonly local = true;\n private turn = 0;\n constructor(\n readonly model: string,\n private readonly steps: Array<{ text?: string; toolCalls?: ToolCall[] }>,\n ) {}\n // Match Provider.chat so tests can wrap/spy with the full signature.\n async chat(_messages?: ChatMessage[], _opts?: ChatOptions): Promise<ProviderResult> {\n const step = this.steps[Math.min(this.turn, this.steps.length - 1)];\n this.turn++;\n return { text: step.text ?? '', model: this.model, provider: this.id, toolCalls: step.toolCalls };\n }\n}\n\n/** The catalogue of known OpenAI-compatible endpoints, keyed by short id. */\nexport const OPENAI_COMPATIBLE: Record<string, Omit<OpenAiCompatibleConfig, 'label' | 'id'> & { label: string }> = {\n /**\n * Vibgrate Relay — the first-party hosted router. OpenAI-compatible, so it\n * needs no bespoke client. Reached with a Vibgrate token rather than a\n * provider key; the base URL is overridable for staging and self-hosting.\n */\n 'vibgrate-relay': {\n baseUrl: process.env.VIBGRATE_RELAY_URL || 'https://api.vibgrate.com/relay/v1',\n apiKeyEnv: 'VIBGRATE_RELAY_TOKEN',\n local: false,\n label: 'Vibgrate Relay',\n },\n openrouter: { baseUrl: 'https://openrouter.ai/api/v1', apiKeyEnv: 'OPENROUTER_API_KEY', local: false, label: 'OpenRouter' },\n litellm: { baseUrl: process.env.LITELLM_BASE_URL || 'http://127.0.0.1:4000', apiKeyEnv: 'LITELLM_API_KEY', local: false, label: 'LiteLLM' },\n openai: { baseUrl: 'https://api.openai.com/v1', apiKeyEnv: 'OPENAI_API_KEY', local: false, label: 'OpenAI' },\n together: { baseUrl: 'https://api.together.xyz/v1', apiKeyEnv: 'TOGETHER_API_KEY', local: false, label: 'Together' },\n lmstudio: { baseUrl: process.env.LMSTUDIO_BASE_URL || 'http://127.0.0.1:1234/v1', local: true, label: 'LM Studio (local)' },\n /**\n * Microsoft Foundry Local — OpenAI-compatible local endpoint (Windows NPU/GPU).\n * Default port matches current Foundry Local docs; override with FOUNDRY_LOCAL_BASE_URL.\n */\n 'foundry-local': {\n baseUrl: process.env.FOUNDRY_LOCAL_BASE_URL || 'http://127.0.0.1:5272/v1',\n local: true,\n label: 'Foundry Local',\n },\n};\n\n/* ------------------------------------------------------------------ *\\\n * Local llama.cpp (installs a package on first use, with consent)\n\\* ------------------------------------------------------------------ */\n\n/**\n * A fully-local inference backend backed by the dual-mode llm-host (ADR-005)\n * and `node-llama-cpp`. Install runtime deps via `vg models install` (or pass\n * consent so ensurePackage can run once). Model *weights* are never fetched\n * automatically: `modelPath` must point at a gguf the user already has.\n */\nexport class LocalLlamaProvider implements Provider {\n readonly id = 'llama-cpp';\n /** Surfaced as the Vibgrate model manager (embedded llama.cpp). */\n readonly label = 'Vibgrate (local)';\n readonly local = true;\n /** Process-wide warm binding + path (best-in-breed: no reload per turn). */\n private static warmBinding: unknown | null = null;\n private static warmHost: import('../runtime/llm-host/embedded.js').EmbeddedLlmHost | null = null;\n private static warmPath: string | null = null;\n\n constructor(\n readonly model: string,\n private readonly modelPath: string,\n private readonly ensure: typeof ensurePackage = ensurePackage,\n private readonly consent = false,\n /** Override isolation (default: env / embedded). */\n private readonly isolation: 'embedded' | 'process' = 'embedded',\n private readonly processEndpoint?: string,\n ) {}\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const {\n createLlmHost,\n EmbeddedLlmHost,\n resolveInferenceIsolation,\n acquireHostSession,\n generateOnSession,\n evictIdleSessions,\n } = await import('../runtime/llm-host/index.js');\n const isolation = resolveInferenceIsolation(this.isolation);\n try {\n const chatMessages = messages.map((m) => ({\n role: (m.role === 'tool' ? 'user' : m.role) as 'system' | 'user' | 'assistant',\n content: m.content,\n }));\n const genOpts = {\n temperature: opts.temperature ?? 0,\n maxTokens: opts.maxTokens,\n grammar: opts.grammar,\n requireGrammar: opts.requireGrammar,\n identifierTrie: opts.identifierTrie,\n annotateUnknownIdentifiers: !!opts.identifierTrie,\n draftCandidates: opts.draftCandidates,\n promptSegments: opts.promptSegments,\n };\n\n if (isolation === 'process') {\n const host = createLlmHost({ isolation: 'process', endpoint: this.processEndpoint });\n await host.load(this.modelPath);\n const out = await host.generate(chatMessages, genOpts);\n return { text: out.text, model: this.model, provider: this.id };\n }\n\n // Warm path: reuse binding + session across turns.\n if (!LocalLlamaProvider.warmBinding) {\n const res = await this.ensure('node-llama-cpp@^3', { consent: this.consent, onUnavailable: () => {} });\n if (!res.module) {\n throw new Error(ensureUnavailableMessage(res.reason ?? 'no-consent', 'node-llama-cpp', res.detail));\n }\n LocalLlamaProvider.warmBinding = res.module;\n }\n evictIdleSessions(2);\n\n // Prefer direct session API for metrics-rich generate.\n const session = await acquireHostSession(LocalLlamaProvider.warmBinding, this.modelPath);\n const report = await generateOnSession(session, chatMessages, genOpts);\n return {\n text: report.text,\n model: this.model,\n provider: this.id,\n usage: {\n // Surface host metrics in usage extension fields via completionTokens when useful.\n completionTokens: report.draftAcceptedChars || undefined,\n },\n };\n } catch (e) {\n // Fall back to EmbeddedLlmHost once if session path fails.\n try {\n if (LocalLlamaProvider.warmBinding) {\n if (\n !LocalLlamaProvider.warmHost ||\n LocalLlamaProvider.warmPath !== this.modelPath\n ) {\n const host = createLlmHost({\n isolation: 'embedded',\n binding: LocalLlamaProvider.warmBinding,\n preferGrammar: !!opts.grammar,\n });\n if (host instanceof EmbeddedLlmHost) {\n LocalLlamaProvider.warmHost = host;\n LocalLlamaProvider.warmPath = this.modelPath;\n await host.load(this.modelPath);\n }\n }\n if (LocalLlamaProvider.warmHost) {\n const out = await LocalLlamaProvider.warmHost.generate(\n messages.map((m) => ({\n role: (m.role === 'tool' ? 'user' : m.role) as 'system' | 'user' | 'assistant',\n content: m.content,\n })),\n {\n temperature: opts.temperature ?? 0,\n maxTokens: opts.maxTokens,\n grammar: opts.grammar,\n requireGrammar: opts.requireGrammar,\n identifierTrie: opts.identifierTrie,\n annotateUnknownIdentifiers: !!opts.identifierTrie,\n draftCandidates: opts.draftCandidates,\n promptSegments: opts.promptSegments,\n },\n );\n return { text: out.text, model: this.model, provider: this.id };\n }\n }\n } catch {\n /* rethrow outer */\n }\n throw new Error(`local llama.cpp inference failed for ${this.modelPath} — ${redactSecrets((e as Error).message)}`);\n }\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine/savings.ts","../src/code/context.ts","../src/code/capsule.ts"],"names":["estimateTokens","normalize"],"mappings":";;;;;;AAmBA,IAAM,MAAA,GAAS,eAAA;AAER,IAAM,eAAA,GAAkB;AAQxB,IAAM,gCAAgB,IAAI,GAAA,CAAI,CAAC,aAAA,EAAe,UAAA,EAAY,gBAAgB,CAAC;AAoB3E,IAAM,gBAAA,GAAqD;AAAA,EAChE,GAAA,EAAK,aAAA;AAAA,EACL,IAAA,EAAM,UAAA;AAAA,EACN,MAAA,EAAQ,WAAA;AAAA,EACR,IAAA,EAAM,WAAA;AAAA,EACN,IAAA,EAAM,WAAA;AAAA,EACN,KAAA,EAAO,YAAA;AAAA,EACP,IAAA,EAAM;AACR;AASO,SAAS,eAAe,IAAA,EAAyC;AACtE,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,EAAU,OAAO,SAAA;AACrC,EAAA,MAAM,UAAU,IAAA,CACb,IAAA,EAAK,CACL,WAAA,GACA,OAAA,CAAQ,gBAAA,EAAkB,GAAG,CAAA,CAC7B,QAAQ,UAAA,EAAY,EAAE,CAAA,CACtB,KAAA,CAAM,GAAG,EAAE,CAAA;AACd,EAAA,OAAO,OAAA,IAAW,SAAA;AACpB;AAsCO,SAAS,gBAAgB,IAAA,EAAqD;AACnF,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,EAAU,OAAO,MAAA;AACrC,EAAA,MAAM,UAAU,IAAA,CACb,IAAA,EAAK,CACL,WAAA,GACA,OAAA,CAAQ,kBAAA,EAAoB,GAAG,CAAA,CAC/B,QAAQ,UAAA,EAAY,EAAE,CAAA,CACtB,KAAA,CAAM,GAAG,EAAE,CAAA;AACd,EAAA,OAAO,OAAA,IAAW,MAAA;AACpB;AAQO,SAAS,aAAA,CACd,IAAA,EACA,KAAA,EACA,GAAA,EACM;AACN,EAAA,YAAA;AAAA,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,GAAS,CAAC,CAAA;AAClC","file":"chunk-US2DAKCM.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 { indexFor } from '../engine/relations.js';\nimport { impactOf } from '../engine/impact.js';\nimport type { CodeContext } from './types.js';\nimport type { GraphNode, VgGraph } from '../schema.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}\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 // Retrieval seeds: reuse the deterministic lexical/structural retrieval that\n // backs `vg ask`. When `--file` narrows the surface, keep only seeds in those\n // files (but still let impact reach outside them, so the review is honest).\n // URL / quoted-string needles are stripped inside queryGraph so path tokens\n // cannot poison seeds (dash→dashboard, exist→NonExisting, …).\n const q = queryGraph(graph, instruction, { budget: Math.floor(budget * 0.6), limit: seedLimit * 2 });\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(instruction),\n ...pinnedFactsFor(graph, seedIds),\n ];\n\n const rendered = render(instruction, seeds, [...impacted.values()], targetFiles, pinnedFacts, index, budget);\n return {\n instruction,\n seeds,\n targetFiles,\n impacted: [...impacted.values()],\n pinnedFacts,\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(instruction: string): string[] {\n const needles = extractLiteralNeedles(instruction);\n if (!needles.length) return [];\n return needles.map(\n (n) =>\n `literal-locate: search the workspace for the exact string \\`${n}\\` (use search_code with the quoted needle). This is not a graph symbol name. If there are zero hits, report that honestly and finish — do not invent an edit.`,\n );\n}\n\nfunction pinnedFactsFor(graph: VgGraph, seedIds: Set<string>): string[] {\n if (!graph.facts?.length) return [];\n const out: string[] = [];\n for (const f of graph.facts) {\n if (f.kind === 'characterization') continue; // keep hard constraints only\n if (!f.subjectIds.some((id) => seedIds.has(id))) continue;\n const subjects = f.subjectIds\n .map((id) => graph.nodes.find((n) => n.id === id)?.qualifiedName ?? id)\n .join(', ');\n out.push(`${f.kind}: ${subjects} — ${JSON.stringify(f.predicate)}`);\n }\n return out.sort().slice(0, 12);\n}\n\nfunction render(\n instruction: string,\n seeds: { node: GraphNode; why: string }[],\n impacted: { node: GraphNode; via: string }[],\n targetFiles: string[],\n pinnedFacts: string[],\n 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 lines.push('## Relevant symbols');\n for (const { node, why } of seeds) {\n const block: string[] = [];\n block.push(`### ${node.qualifiedName} (${node.kind}, ${node.file}:${node.span.start}-${node.span.end})`);\n if (node.signature) block.push('`' + node.signature + '`');\n const callees = uniqueNames(index.callees(node.id).map((x) => x.node.qualifiedName)).slice(0, 6);\n const callers = uniqueNames(index.callers(node.id).map((x) => x.node.qualifiedName)).slice(0, 6);\n if (callees.length) block.push(`calls: ${callees.join(', ')}`);\n if (callers.length) block.push(`called by: ${callers.join(', ')}`);\n block.push(`importance ${node.importance.toFixed(3)}${node.isHub ? ' · hub (high blast radius)' : ''} · ${why}`);\n block.push('');\n const candidate = lines.concat(block).join('\\n');\n if (estimateTokens(candidate) > budget && lines.length > 3) break;\n lines.push(...block);\n }\n\n if (impacted.length) {\n lines.push('## Blast radius (would be affected by a change here)');\n for (const { node, via } of impacted.slice(0, 10)) {\n lines.push(`- ${node.qualifiedName} (${node.file}:${node.span.start}) — depends on ${via}`);\n }\n lines.push('');\n }\n\n lines.push('## Files in scope for this edit');\n for (const f of targetFiles) lines.push(`- ${f}`);\n lines.push('');\n\n lines.push('## Task');\n lines.push(instruction);\n return lines.join('\\n');\n}\n\nfunction uniqueNames(xs: string[]): string[] {\n return [...new Set(xs)];\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n","/**\n * Source-bearing Task Capsule compiler (Fusion Runtime Phase 0).\n *\n * Today's {@link buildCodeContext} pays for graph metadata, then the model still\n * calls `read_file` — double payment. This module compiles a Task Capsule that\n * includes exact source ranges (from Tree-sitter spans already on graph nodes)\n * so the first inference can solve without navigation tool calls (ZNS@1 path).\n *\n * Deterministic given (graph, instruction, file contents, options). Injectable\n * `readFile` keeps unit tests offline and pure.\n *\n * Schema: docs/fusion/task-capsule-v0.schema.json\n */\n\nimport { queryGraph } from '../engine/query.js';\nimport { indexFor } from '../engine/relations.js';\nimport { impactOf } from '../engine/impact.js';\nimport { hashString } from '../engine/hash.js';\nimport type { GraphNode, VgGraph } from '../schema.js';\nimport type { CodeContext } from './types.js';\nimport { buildCodeContext, type BuildContextOptions } from './context.js';\n\nexport const TASK_CAPSULE_SCHEMA_VERSION = 'task-capsule/0' as const;\n/** Frozen ranking policy id — bump when the heuristic changes (benchmark gate). */\n/** Bumped 2026.07.1: strip URL/quoted needles from seed ranking (no path-token false positives). */\nexport const CAPSULE_RANKING_VERSION = 'capsule-rank@2026.07.1' 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 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 };\n}\n\nexport interface CapsuleProvenanceExtras {\n modelProfileId?: string | null;\n securityTier?: string | null;\n policyVersion?: string | null;\n}\n\n/** Host-safe capsule summary for VS Code / stream-json capsule transparency. */\nexport interface CapsuleSummary {\n schemaVersion: string;\n instruction: string;\n primary: Array<{ qualifiedName: string; file: string; kind: string }>;\n supporting: Array<{ qualifiedName: string; file: string; kind: string }>;\n sourceSliceCount: number;\n sourceFiles: string[];\n tokensEstimate: number;\n rankingVersion: string;\n /** Truncated rendered capsule for display (not the full prompt dump). */\n preview: string;\n}\n\n/** Host-safe capsule summary (capsule transparency UI / stream-json). */\nexport function summarizeCapsule(capsule: TaskCapsule): CapsuleSummary {\n const sourceFiles = [...new Set(capsule.sourceSlices.map((s) => s.file))].sort();\n const preview = capsule.rendered.length > 4000 ? `${capsule.rendered.slice(0, 4000)}\\n… (truncated)` : capsule.rendered;\n return {\n schemaVersion: capsule.schemaVersion,\n instruction: capsule.instruction,\n primary: capsule.primary.map((p) => ({ qualifiedName: p.qualifiedName, file: p.file, kind: p.kind })),\n supporting: capsule.supporting.map((p) => ({ qualifiedName: p.qualifiedName, file: p.file, kind: p.kind })),\n sourceSliceCount: capsule.sourceSlices.length,\n sourceFiles,\n tokensEstimate: capsule.tokensEstimate,\n rankingVersion: capsule.provenance.rankingVersion,\n preview,\n };\n}\n\n/**\n * Compile a source-bearing Task Capsule. Reuses the same seed / impact /\n * fact-pinning path as {@link buildCodeContext}, then attaches exact source\n * slices and a verification sketch.\n */\nexport function buildTaskCapsule(graph: VgGraph, instruction: string, options: BuildCapsuleOptions = {}): TaskCapsule {\n const base = buildCodeContext(graph, instruction, options);\n const padding = options.padding ?? 1;\n const maxSlices = options.maxSlices ?? 12;\n const budget = options.budget ?? 3000;\n const index = indexFor(graph);\n\n const primary = base.seeds.map((s) => toRef(s.node, s.why));\n const primaryIds = new Set(primary.map((p) => p.id));\n\n const supporting: CapsuleSymbolRef[] = [];\n for (const { node, via } of base.impacted) {\n if (primaryIds.has(node.id)) continue;\n supporting.push(toRef(node, `depends on ${via}`));\n }\n\n const relationships = collectRelationships(base, index);\n const sourceSlices = options.readFile\n ? buildSourceSlices(\n [...base.seeds.map((s) => s.node), ...base.impacted.map((i) => i.node)],\n options.readFile,\n padding,\n maxSlices,\n )\n : [];\n\n const extraFacts = (options.extraPinnedFacts ?? []).filter((f) => typeof f === 'string' && f.trim());\n const pinnedFacts = [...base.pinnedFacts, ...extraFacts];\n const verificationPlan = buildVerificationPlan(graph, base);\n const rendered = renderCapsule(instruction, primary, supporting, sourceSlices, pinnedFacts, base.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 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 },\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 impacted: capsule.supporting.map((s) => ({\n node: {\n id: s.id,\n qualifiedName: s.qualifiedName,\n kind: s.kind,\n file: s.file,\n span: s.span,\n signature: s.signature ?? undefined,\n importance: s.importance,\n } as GraphNode,\n via: s.why.replace(/^depends on /, ''),\n })),\n pinnedFacts: capsule.pinnedFacts,\n rendered: capsule.rendered,\n tokensEstimate: capsule.tokensEstimate,\n };\n}\n\nfunction toRef(node: GraphNode, why: string): CapsuleSymbolRef {\n return {\n id: node.id,\n qualifiedName: node.qualifiedName,\n kind: node.kind,\n file: normalize(node.file),\n span: { start: node.span.start, end: node.span.end },\n signature: node.signature ?? null,\n why,\n importance: node.importance,\n };\n}\n\nfunction collectRelationships(\n base: CodeContext,\n index: ReturnType<typeof indexFor>,\n): CapsuleRelationship[] {\n const out: CapsuleRelationship[] = [];\n const seen = new Set<string>();\n const push = (kind: CapsuleRelationship['kind'], from: string, to: string) => {\n const key = `${kind}|${from}|${to}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({ kind, from, to });\n };\n\n for (const { node } of base.seeds) {\n for (const c of index.callees(node.id).slice(0, 6)) {\n push('calls', node.qualifiedName, c.node.qualifiedName);\n }\n for (const c of index.callers(node.id).slice(0, 6)) {\n push('called-by', node.qualifiedName, c.node.qualifiedName);\n }\n }\n for (const { node, via } of base.impacted.slice(0, 10)) {\n push('impacts', via, node.qualifiedName);\n }\n\n // Stable order for determinism.\n return out.sort((a, b) => a.kind.localeCompare(b.kind) || a.from.localeCompare(b.from) || a.to.localeCompare(b.to));\n}\n\nfunction buildSourceSlices(\n nodes: GraphNode[],\n readFile: (relativePath: string) => string | null,\n padding: number,\n maxSlices: number,\n): SourceSlice[] {\n // Prefer concrete symbols over file/module containers for source evidence.\n const eligible = nodes.filter((n) => !['file', 'module', 'package'].includes(n.kind));\n const byFile = new Map<string, GraphNode[]>();\n for (const n of eligible) {\n const file = normalize(n.file);\n const list = byFile.get(file) ?? [];\n list.push(n);\n byFile.set(file, list);\n }\n\n type Range = { file: string; start: number; end: number; symbolIds: string[]; score: number };\n const ranges: Range[] = [];\n\n for (const [file, fileNodes] of [...byFile.entries()].sort(([a], [b]) => a.localeCompare(b))) {\n const sorted = [...fileNodes].sort((a, b) => a.span.start - b.span.start || b.importance - a.importance);\n let current: Range | null = null;\n for (const n of sorted) {\n const start = Math.max(1, n.span.start - padding);\n const end = n.span.end + padding;\n const score = n.importance + (n.isHub ? 0.25 : 0);\n if (current && current.file === file && start <= current.end + 2) {\n current.end = Math.max(current.end, end);\n current.symbolIds.push(n.id);\n current.score = Math.max(current.score, score);\n } else {\n if (current) ranges.push(current);\n current = { file, start, end, symbolIds: [n.id], score };\n }\n }\n if (current) ranges.push(current);\n }\n\n ranges.sort((a, b) => b.score - a.score || a.file.localeCompare(b.file) || a.start - b.start);\n\n const slices: SourceSlice[] = [];\n for (const range of ranges) {\n if (slices.length >= maxSlices) break;\n const raw = readFile(range.file);\n if (raw === null) continue;\n const lines = raw.split('\\n');\n const start = Math.min(range.start, lines.length);\n const end = Math.min(range.end, lines.length);\n if (start < 1 || end < start) continue;\n const content = lines.slice(start - 1, end).join('\\n');\n slices.push({\n file: range.file,\n start,\n end,\n content,\n contentHash: hashString(content),\n symbolIds: [...new Set(range.symbolIds)].sort(),\n });\n }\n\n // Stable final order: file then start line (score only used for selection).\n return slices.sort((a, b) => a.file.localeCompare(b.file) || a.start - b.start);\n}\n\nfunction buildVerificationPlan(graph: VgGraph, base: CodeContext): VerificationPlan {\n const syntaxFiles = [...base.targetFiles].sort();\n const seedIds = new Set(base.seeds.map((s) => s.node.id));\n const suggestedTests: string[] = [];\n\n for (const n of graph.nodes) {\n if (n.kind !== 'test') continue;\n // Prefer tests that share a file with seeds or whose name mentions a seed.\n const sameFile = base.seeds.some((s) => normalize(s.node.file) === normalize(n.file));\n const nameHit = base.seeds.some((s) => n.qualifiedName.toLowerCase().includes(s.node.name.toLowerCase()));\n if (sameFile || nameHit || seedIds.has(n.id)) {\n suggestedTests.push(n.qualifiedName);\n }\n }\n suggestedTests.sort();\n\n const notes: string[] = [];\n if (!suggestedTests.length) {\n notes.push('No graph-linked tests found for seed symbols; run the nearest project test command after apply.');\n }\n if (base.impacted.some((i) => i.node.isHub || i.node.importance >= 0.7)) {\n notes.push('High-importance dependents in blast radius — prefer targeted tests before a full build.');\n }\n\n return {\n syntaxFiles,\n suggestedTests: suggestedTests.slice(0, 12),\n notes,\n };\n}\n\nfunction renderCapsule(\n instruction: string,\n primary: CapsuleSymbolRef[],\n supporting: CapsuleSymbolRef[],\n slices: SourceSlice[],\n pinnedFacts: string[],\n targetFiles: string[],\n verification: VerificationPlan,\n relationships: CapsuleRelationship[],\n budget: number,\n): string {\n const lines: string[] = [];\n lines.push('# Task capsule (source-bearing, from the deterministic code graph)');\n lines.push('');\n lines.push('Use the exact source evidence below. Search or read outside it only if this capsule is insufficient.');\n lines.push('');\n\n if (pinnedFacts.length) {\n lines.push('## Hard constraints (do not violate)');\n for (const f of pinnedFacts) lines.push(`- ${f}`);\n lines.push('');\n }\n\n lines.push('## Primary symbols');\n for (const s of primary) {\n lines.push(`- ${s.qualifiedName} (${s.kind}, ${s.file}:${s.span.start}-${s.span.end})${s.signature ? ` — \\`${s.signature}\\`` : ''} — ${s.why}`);\n }\n lines.push('');\n\n if (supporting.length) {\n lines.push('## Supporting / blast radius');\n for (const s of supporting.slice(0, 10)) {\n lines.push(`- ${s.qualifiedName} (${s.file}:${s.span.start}) — ${s.why}`);\n }\n lines.push('');\n }\n\n if (relationships.length) {\n lines.push('## Relationships');\n for (const r of relationships.slice(0, 24)) {\n lines.push(`- ${r.kind}: ${r.from} → ${r.to}`);\n }\n lines.push('');\n }\n\n lines.push('## Exact source evidence');\n if (!slices.length) {\n lines.push('_No source slices available (file reader missing or spans unreadable)._');\n lines.push('');\n } else {\n let included = 0;\n for (const slice of slices) {\n const block = [\n `### ${slice.file}:${slice.start}-${slice.end}`,\n `\\`\\`\\`${langFor(slice.file)}`,\n slice.content,\n '```',\n '',\n ];\n const candidate = [...lines, ...block, '## Task', instruction].join('\\n');\n if (estimateTokens(candidate) > budget && included > 0) break;\n lines.push(...block);\n included += 1;\n }\n }\n\n lines.push('## Files in scope');\n for (const f of targetFiles) lines.push(`- ${f}`);\n lines.push('');\n\n lines.push('## Verification plan');\n for (const f of verification.syntaxFiles) lines.push(`- syntax: ${f}`);\n for (const t of verification.suggestedTests) lines.push(`- test: ${t}`);\n for (const n of verification.notes) lines.push(`- note: ${n}`);\n lines.push('');\n\n lines.push('## Task');\n lines.push(instruction);\n return lines.join('\\n');\n}\n\nfunction langFor(file: string): string {\n const ext = file.split('.').pop()?.toLowerCase() ?? '';\n const map: Record<string, string> = {\n ts: 'ts',\n tsx: 'tsx',\n js: 'js',\n jsx: 'jsx',\n mjs: 'js',\n cjs: 'js',\n py: 'python',\n rs: 'rust',\n go: 'go',\n java: 'java',\n cs: 'csharp',\n md: 'md',\n json: 'json',\n };\n return map[ext] ?? '';\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n// Re-export query touch so tree-shaking keeps the dependency explicit for tests.\nexport const __testing = { queryGraph, impactOf };\n"]}
|
package/dist/chunk-ZKNB4YH4.js
DELETED
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import * as fs from 'fs';
|
|
2
|
-
import * as path from 'path';
|
|
3
|
-
|
|
4
|
-
// src/engine/serialize.ts
|
|
5
|
-
function serializeGraph(graph, opts) {
|
|
6
|
-
const indent = opts?.compact ? 0 : 2;
|
|
7
|
-
return `${stableStringify(graph, indent)}
|
|
8
|
-
`;
|
|
9
|
-
}
|
|
10
|
-
function slimGraphForExport(graph) {
|
|
11
|
-
return {
|
|
12
|
-
...graph,
|
|
13
|
-
areas: graph.areas.map((a) => ({
|
|
14
|
-
...a,
|
|
15
|
-
members: []
|
|
16
|
-
// member id lists dominate XL exports; area id still on nodes
|
|
17
|
-
})),
|
|
18
|
-
grounding: void 0,
|
|
19
|
-
facts: graph.facts
|
|
20
|
-
// Keep summaries/unknowns — small and useful to agents.
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
function stableStringify(value, indent = 2) {
|
|
24
|
-
return JSON.stringify(sortKeys(value), null, indent);
|
|
25
|
-
}
|
|
26
|
-
function sortKeys(value) {
|
|
27
|
-
if (Array.isArray(value)) return value.map(sortKeys);
|
|
28
|
-
if (value && typeof value === "object") {
|
|
29
|
-
const input = value;
|
|
30
|
-
const out = {};
|
|
31
|
-
for (const key of Object.keys(input).sort()) {
|
|
32
|
-
const v = input[key];
|
|
33
|
-
if (v === void 0) continue;
|
|
34
|
-
out[key] = sortKeys(v);
|
|
35
|
-
}
|
|
36
|
-
return out;
|
|
37
|
-
}
|
|
38
|
-
return value;
|
|
39
|
-
}
|
|
40
|
-
function parseGraph(json) {
|
|
41
|
-
return JSON.parse(json);
|
|
42
|
-
}
|
|
43
|
-
var CACHE_VERSION = "vg-parse-cache/4";
|
|
44
|
-
function cacheDir(root) {
|
|
45
|
-
return path.join(root, ".vibgrate", "cache");
|
|
46
|
-
}
|
|
47
|
-
function cachePath(root) {
|
|
48
|
-
return path.join(cacheDir(root), "parse-cache.json");
|
|
49
|
-
}
|
|
50
|
-
function loadCache(root, opts) {
|
|
51
|
-
const file = cachePath(root);
|
|
52
|
-
let data = {
|
|
53
|
-
version: CACHE_VERSION,
|
|
54
|
-
toolVersion: opts.toolVersion,
|
|
55
|
-
grammars: opts.grammars,
|
|
56
|
-
entries: {}
|
|
57
|
-
};
|
|
58
|
-
if (!opts.disabled && fs.existsSync(file)) {
|
|
59
|
-
try {
|
|
60
|
-
const loaded = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
61
|
-
if ((loaded.version === CACHE_VERSION || loaded.version === "vg-parse-cache/3") && loaded.toolVersion === opts.toolVersion && loaded.grammars === opts.grammars && loaded.entries) {
|
|
62
|
-
data = { ...loaded, version: CACHE_VERSION };
|
|
63
|
-
}
|
|
64
|
-
} catch {
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
return {
|
|
68
|
-
get(rel, hash) {
|
|
69
|
-
const entry = data.entries[rel];
|
|
70
|
-
return entry && entry.hash === hash ? entry.parse : void 0;
|
|
71
|
-
},
|
|
72
|
-
getByStat(rel, mtimeMs, size) {
|
|
73
|
-
const entry = data.entries[rel];
|
|
74
|
-
if (!entry) return void 0;
|
|
75
|
-
if (entry.mtimeMs === mtimeMs && entry.size === size && entry.parse) {
|
|
76
|
-
return { parse: entry.parse, hash: entry.hash };
|
|
77
|
-
}
|
|
78
|
-
return void 0;
|
|
79
|
-
},
|
|
80
|
-
set(rel, parse, stat) {
|
|
81
|
-
data.entries[rel] = {
|
|
82
|
-
hash: parse.hash,
|
|
83
|
-
parse,
|
|
84
|
-
mtimeMs: stat?.mtimeMs,
|
|
85
|
-
size: stat?.size
|
|
86
|
-
};
|
|
87
|
-
},
|
|
88
|
-
prune(currentRels) {
|
|
89
|
-
for (const rel of Object.keys(data.entries)) {
|
|
90
|
-
if (!currentRels.has(rel)) delete data.entries[rel];
|
|
91
|
-
}
|
|
92
|
-
},
|
|
93
|
-
save() {
|
|
94
|
-
fs.mkdirSync(cacheDir(root), { recursive: true });
|
|
95
|
-
fs.writeFileSync(file, stableStringify(data, 0));
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export { cacheDir, loadCache, parseGraph, serializeGraph, slimGraphForExport, stableStringify };
|
|
101
|
-
//# sourceMappingURL=chunk-ZKNB4YH4.js.map
|
|
102
|
-
//# sourceMappingURL=chunk-ZKNB4YH4.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine/serialize.ts","../src/engine/cache.ts"],"names":[],"mappings":";;;;AAWO,SAAS,cAAA,CAAe,OAAgB,IAAA,EAAsC;AAEnF,EAAA,MAAM,MAAA,GAAS,IAAA,EAAM,OAAA,GAAU,CAAA,GAAI,CAAA;AACnC,EAAA,OAAO,CAAA,EAAG,eAAA,CAAgB,KAAA,EAAO,MAAM,CAAC;AAAA,CAAA;AAC1C;AAMO,SAAS,mBAAmB,KAAA,EAAyB;AAC1D,EAAA,OAAO;AAAA,IACL,GAAG,KAAA;AAAA,IACH,KAAA,EAAO,KAAA,CAAM,KAAA,CAAM,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,MAC7B,GAAG,CAAA;AAAA,MACH,SAAS;AAAC;AAAA,KACZ,CAAE,CAAA;AAAA,IACF,SAAA,EAAW,MAAA;AAAA,IACX,OAAO,KAAA,CAAM;AAAA;AAAA,GAEf;AACF;AAEO,SAAS,eAAA,CAAgB,KAAA,EAAgB,MAAA,GAAS,CAAA,EAAW;AAClE,EAAA,OAAO,KAAK,SAAA,CAAU,QAAA,CAAS,KAAK,CAAA,EAAG,MAAM,MAAM,CAAA;AACrD;AAEA,SAAS,SAAS,KAAA,EAAyB;AACzC,EAAA,IAAI,MAAM,OAAA,CAAQ,KAAK,GAAG,OAAO,KAAA,CAAM,IAAI,QAAQ,CAAA;AACnD,EAAA,IAAI,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU;AACtC,IAAA,MAAM,KAAA,GAAQ,KAAA;AACd,IAAA,MAAM,MAA+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IAAA,CAAK,IAAA,CAAK,OAAO,CAAA,EAAG;AAC3C,QAAA,IAAI,CAAC,YAAY,GAAA,CAAI,GAAG,GAAG,OAAO,IAAA,CAAK,QAAQ,GAAG,CAAA;AAAA,MACpD;AAAA,IACF,CAAA;AAAA,IACA,IAAA,GAAO;AACL,MAAG,aAAU,QAAA,CAAS,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAChD,MAAG,EAAA,CAAA,aAAA,CAAc,IAAA,EAAM,eAAA,CAAgB,IAAA,EAAM,CAAC,CAAC,CAAA;AAAA,IACjD;AAAA,GACF;AACF","file":"chunk-ZKNB4YH4.js","sourcesContent":["import type { VgGraph } from '../schema.js';\n\n/**\n * Deterministic serialization of `graph.json`.\n *\n * Object keys are sorted recursively and arrays are emitted in the (already\n * stable) order the engine produced them, so two runs over identical content\n * yield byte-identical output — the determinism contract (VG-CLI-SPEC §1.3).\n * Pretty-printed (2-space) and newline-terminated so the committed artifact is\n * human-diffable and plays well with the union merge driver.\n */\nexport function serializeGraph(graph: VgGraph, opts?: { compact?: boolean }): string {\n // Compact (no pretty-print) for large maps / CI artifacts — still deterministic.\n const indent = opts?.compact ? 0 : 2;\n return `${stableStringify(graph, indent)}\\n`;\n}\n\n/**\n * Drop heavy optional fields for export/sharing when size matters.\n * Does not mutate the input graph.\n */\nexport function slimGraphForExport(graph: VgGraph): VgGraph {\n return {\n ...graph,\n areas: graph.areas.map((a) => ({\n ...a,\n members: [], // member id lists dominate XL exports; area id still on nodes\n })),\n grounding: undefined,\n facts: graph.facts,\n // Keep summaries/unknowns — small and useful to agents.\n };\n}\n\nexport function stableStringify(value: unknown, indent = 2): string {\n return JSON.stringify(sortKeys(value), null, indent);\n}\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (value && typeof value === 'object') {\n const input = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(input).sort()) {\n const v = input[key];\n if (v === undefined) continue; // omit undefined for stable output\n out[key] = sortKeys(v);\n }\n return out;\n }\n return value;\n}\n\nexport function parseGraph(json: string): VgGraph {\n return JSON.parse(json) as VgGraph;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { stableStringify } from './serialize.js';\nimport type { FileParse } from './types.js';\n\n/**\n * Incremental parse cache. Maps a file's content hash to its parsed\n * symbol/edge tables, so a rebuild re-parses only files whose content actually\n * changed (VG-DEVELOPMENT-PLAN Phase 0.4). Lives under `.vibgrate/cache/` and is\n * gitignored — never part of the committed artifact.\n *\n * The cache is a pure performance optimisation: a reused FileParse is identical\n * to a freshly-parsed one (parsing is pure over content), so the graph is\n * byte-identical whether or not the cache was warm. `--no-cache` / `vg verify`\n * prove this.\n */\n\n// Bumped to /4: optional mtime+size fingerprint for stat-skip fast path.\nconst CACHE_VERSION = 'vg-parse-cache/4';\n\ninterface CacheEntry {\n hash: string;\n mtimeMs?: number;\n size?: number;\n parse: FileParse;\n}\n\ninterface CacheFile {\n version: string;\n toolVersion: string;\n grammars: string;\n entries: Record<string, CacheEntry>;\n}\n\nexport interface ParseCache {\n get(rel: string, hash: string): FileParse | undefined;\n /** Fast path: mtime+size match → reuse parse without re-reading bytes. */\n getByStat(rel: string, mtimeMs: number, size: number): { parse: FileParse; hash: string } | undefined;\n set(rel: string, parse: FileParse, stat?: { mtimeMs: number; size: number }): void;\n /** Drop entries for files no longer present. */\n prune(currentRels: Set<string>): void;\n save(): void;\n}\n\nexport function cacheDir(root: string): string {\n return path.join(root, '.vibgrate', 'cache');\n}\n\nfunction cachePath(root: string): string {\n return path.join(cacheDir(root), 'parse-cache.json');\n}\n\nexport function loadCache(\n root: string,\n opts: { toolVersion: string; grammars: string; disabled?: boolean },\n): ParseCache {\n const file = cachePath(root);\n let data: CacheFile = {\n version: CACHE_VERSION,\n toolVersion: opts.toolVersion,\n grammars: opts.grammars,\n entries: {},\n };\n\n if (!opts.disabled && fs.existsSync(file)) {\n try {\n const loaded = JSON.parse(fs.readFileSync(file, 'utf8')) as CacheFile;\n // Accept v3 → v4 (stat fields optional).\n if (\n (loaded.version === CACHE_VERSION || loaded.version === 'vg-parse-cache/3') &&\n loaded.toolVersion === opts.toolVersion &&\n loaded.grammars === opts.grammars &&\n loaded.entries\n ) {\n data = { ...loaded, version: CACHE_VERSION };\n }\n } catch {\n /* corrupt cache — start fresh */\n }\n }\n\n return {\n get(rel, hash) {\n const entry = data.entries[rel];\n return entry && entry.hash === hash ? entry.parse : undefined;\n },\n getByStat(rel, mtimeMs, size) {\n const entry = data.entries[rel];\n if (!entry) return undefined;\n if (entry.mtimeMs === mtimeMs && entry.size === size && entry.parse) {\n return { parse: entry.parse, hash: entry.hash };\n }\n return undefined;\n },\n set(rel, parse, stat) {\n data.entries[rel] = {\n hash: parse.hash,\n parse,\n mtimeMs: stat?.mtimeMs,\n size: stat?.size,\n };\n },\n prune(currentRels) {\n for (const rel of Object.keys(data.entries)) {\n if (!currentRels.has(rel)) delete data.entries[rel];\n }\n },\n save() {\n fs.mkdirSync(cacheDir(root), { recursive: true });\n fs.writeFileSync(file, stableStringify(data, 0));\n },\n };\n}\n"]}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
export { ensureCodeMap } from './chunk-SCTLOFNH.js';
|
|
2
|
-
import './chunk-LTTVCI5C.js';
|
|
3
|
-
import './chunk-CT5BS56U.js';
|
|
4
|
-
import './chunk-5IA2TA57.js';
|
|
5
|
-
import './chunk-RIWLXMMT.js';
|
|
6
|
-
import './chunk-XRN7DQGR.js';
|
|
7
|
-
import './chunk-HTLDXEHW.js';
|
|
8
|
-
import './chunk-CRAMOEBE.js';
|
|
9
|
-
import './chunk-IPICO2RV.js';
|
|
10
|
-
import './chunk-FHJBGPJZ.js';
|
|
11
|
-
import './chunk-3LSG7Z4I.js';
|
|
12
|
-
import './chunk-J7LKEB2R.js';
|
|
13
|
-
import './chunk-EETK7S43.js';
|
|
14
|
-
import './chunk-CQDUBAQY.js';
|
|
15
|
-
import './chunk-OV4KGXPD.js';
|
|
16
|
-
import './chunk-UTNNGKKX.js';
|
|
17
|
-
import './chunk-RXP66R2E.js';
|
|
18
|
-
import './chunk-MOLBANFB.js';
|
|
19
|
-
import './chunk-AVCBKQKA.js';
|
|
20
|
-
import './chunk-DEKGSQHL.js';
|
|
21
|
-
import './chunk-ZKNB4YH4.js';
|
|
22
|
-
import './chunk-BWPBB45M.js';
|
|
23
|
-
import './chunk-JFGYT6BI.js';
|
|
24
|
-
import './chunk-BPF3YX2U.js';
|
|
25
|
-
import './chunk-DT4KIVRI.js';
|
|
26
|
-
import './chunk-Z6ZWNWWR.js';
|
|
27
|
-
//# sourceMappingURL=ensure-map-UQL7SM34.js.map
|
|
28
|
-
//# sourceMappingURL=ensure-map-UQL7SM34.js.map
|