@vibgrate/cli 2026.731.2 → 2026.801.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/{agent-6PPW5GIV.js → agent-4DAECASW.js} +8 -8
  2. package/dist/{agent-6PPW5GIV.js.map → agent-4DAECASW.js.map} +1 -1
  3. package/dist/{baseline-ZMHL6DXF.js → baseline-4BDH4F2W.js} +3 -3
  4. package/dist/{baseline-ZMHL6DXF.js.map → baseline-4BDH4F2W.js.map} +1 -1
  5. package/dist/{chunk-X634FZVG.js → chunk-3LOWJSAF.js} +11 -16
  6. package/dist/{chunk-X634FZVG.js.map → chunk-3LOWJSAF.js.map} +1 -1
  7. package/dist/{chunk-QWOJO32H.js → chunk-76TDXGGF.js} +3 -3
  8. package/dist/{chunk-QWOJO32H.js.map → chunk-76TDXGGF.js.map} +1 -1
  9. package/dist/chunk-7G5S5KZN.js +99 -0
  10. package/dist/chunk-7G5S5KZN.js.map +1 -0
  11. package/dist/{chunk-RIWLXMMT.js → chunk-7PVCHLR2.js} +4 -4
  12. package/dist/{chunk-RIWLXMMT.js.map → chunk-7PVCHLR2.js.map} +1 -1
  13. package/dist/{chunk-RGEVBSLK.js → chunk-A43I2AJ4.js} +3 -3
  14. package/dist/{chunk-RGEVBSLK.js.map → chunk-A43I2AJ4.js.map} +1 -1
  15. package/dist/{chunk-TNCD5VFX.js → chunk-B3OMGYZZ.js} +3 -3
  16. package/dist/{chunk-TNCD5VFX.js.map → chunk-B3OMGYZZ.js.map} +1 -1
  17. package/dist/{chunk-LZX5NH4V.js → chunk-BNEHDLVZ.js} +8 -8
  18. package/dist/{chunk-LZX5NH4V.js.map → chunk-BNEHDLVZ.js.map} +1 -1
  19. package/dist/{chunk-4CGLQXSI.js → chunk-E6H2F2XF.js} +3 -3
  20. package/dist/{chunk-4CGLQXSI.js.map → chunk-E6H2F2XF.js.map} +1 -1
  21. package/dist/{chunk-MYM5VIJ4.js → chunk-G25STLE7.js} +15 -9
  22. package/dist/chunk-G25STLE7.js.map +1 -0
  23. package/dist/{chunk-4DZC3ADC.js → chunk-G7W4MFPZ.js} +4 -4
  24. package/dist/{chunk-4DZC3ADC.js.map → chunk-G7W4MFPZ.js.map} +1 -1
  25. package/dist/{chunk-FHJBGPJZ.js → chunk-I6RBAIS3.js} +3 -3
  26. package/dist/{chunk-FHJBGPJZ.js.map → chunk-I6RBAIS3.js.map} +1 -1
  27. package/dist/{chunk-Q7HUXIUF.js → chunk-IRCYOTRG.js} +30 -57
  28. package/dist/chunk-IRCYOTRG.js.map +1 -0
  29. package/dist/{chunk-EVLS2M5G.js → chunk-JFE7XCAE.js} +3 -3
  30. package/dist/{chunk-EVLS2M5G.js.map → chunk-JFE7XCAE.js.map} +1 -1
  31. package/dist/{chunk-4TC6RJ7U.js → chunk-JLWI2JGA.js} +4 -4
  32. package/dist/{chunk-4TC6RJ7U.js.map → chunk-JLWI2JGA.js.map} +1 -1
  33. package/dist/{chunk-Y44GPOBL.js → chunk-KL65SSR7.js} +7 -7
  34. package/dist/{chunk-Y44GPOBL.js.map → chunk-KL65SSR7.js.map} +1 -1
  35. package/dist/{chunk-US2DAKCM.js → chunk-MPP4S4OE.js} +4 -4
  36. package/dist/{chunk-US2DAKCM.js.map → chunk-MPP4S4OE.js.map} +1 -1
  37. package/dist/{chunk-EETK7S43.js → chunk-SDG242R4.js} +399 -23
  38. package/dist/chunk-SDG242R4.js.map +1 -0
  39. package/dist/{chunk-IZNOMGR6.js → chunk-T6DRYOMT.js} +3 -3
  40. package/dist/{chunk-IZNOMGR6.js.map → chunk-T6DRYOMT.js.map} +1 -1
  41. package/dist/chunk-TGDHOAXX.js +6 -0
  42. package/dist/{chunk-NNB2H4BA.js.map → chunk-TGDHOAXX.js.map} +1 -1
  43. package/dist/{chunk-EX2SH5CT.js → chunk-V2QK3IUY.js} +5 -5
  44. package/dist/{chunk-EX2SH5CT.js.map → chunk-V2QK3IUY.js.map} +1 -1
  45. package/dist/{chunk-L6BRBFBP.js → chunk-V3X3DBZL.js} +5 -5
  46. package/dist/{chunk-L6BRBFBP.js.map → chunk-V3X3DBZL.js.map} +1 -1
  47. package/dist/{chunk-WBMMRERH.js → chunk-WIDZ5IE7.js} +4 -4
  48. package/dist/{chunk-WBMMRERH.js.map → chunk-WIDZ5IE7.js.map} +1 -1
  49. package/dist/{chunk-5J45MN3K.js → chunk-XEJJGDGX.js} +7 -7
  50. package/dist/{chunk-5J45MN3K.js.map → chunk-XEJJGDGX.js.map} +1 -1
  51. package/dist/cli.js +67 -121
  52. package/dist/cli.js.map +1 -1
  53. package/dist/{ensure-map-C3NEC2GI.js → ensure-map-SMWHKOUY.js} +11 -11
  54. package/dist/{ensure-map-C3NEC2GI.js.map → ensure-map-SMWHKOUY.js.map} +1 -1
  55. package/dist/{graph-backend-G5Y6QQV4.js → graph-backend-I4I72J4W.js} +4 -4
  56. package/dist/{graph-backend-G5Y6QQV4.js.map → graph-backend-I4I72J4W.js.map} +1 -1
  57. package/dist/index.d.ts +11 -4
  58. package/dist/index.js +10 -10
  59. package/dist/{interactive-2TAYVEHE.js → interactive-TMQR6TXM.js} +23 -23
  60. package/dist/{interactive-2TAYVEHE.js.map → interactive-TMQR6TXM.js.map} +1 -1
  61. package/dist/{llm-host-DZBD5D36.js → llm-host-XFYFOAAX.js} +4 -4
  62. package/dist/{llm-host-DZBD5D36.js.map → llm-host-XFYFOAAX.js.map} +1 -1
  63. package/dist/load-E3OTM7BS.js +10 -0
  64. package/dist/{load-A5BGEQWP.js.map → load-E3OTM7BS.js.map} +1 -1
  65. package/dist/{run-outcome-OSIVMVT7.js → run-outcome-QWLNBASF.js} +5 -5
  66. package/dist/{run-outcome-OSIVMVT7.js.map → run-outcome-QWLNBASF.js.map} +1 -1
  67. package/dist/runtime-session-UQ7UVAPL.js +20 -0
  68. package/dist/{runtime-session-UPTC3E6N.js.map → runtime-session-UQ7UVAPL.js.map} +1 -1
  69. package/dist/{session-3OBIQLE4.js → session-MG6BJVAG.js} +6 -6
  70. package/dist/{session-3OBIQLE4.js.map → session-MG6BJVAG.js.map} +1 -1
  71. package/dist/session-store-SQECEXUU.js +4 -0
  72. package/dist/{session-store-O4XPXKOV.js.map → session-store-SQECEXUU.js.map} +1 -1
  73. package/dist/{stream-json-CFKBL3MR.js → stream-json-GM44SP7L.js} +8 -8
  74. package/dist/{stream-json-CFKBL3MR.js.map → stream-json-GM44SP7L.js.map} +1 -1
  75. package/dist/{vg-mcp-bridge-JHRKJBVT.js → vg-mcp-bridge-3WFC7LGE.js} +6 -6
  76. package/dist/{vg-mcp-bridge-JHRKJBVT.js.map → vg-mcp-bridge-3WFC7LGE.js.map} +1 -1
  77. package/dist/{vgd-HNPOSXKZ.js → vgd-ZUSBEVUL.js} +8 -8
  78. package/dist/vgd-ZUSBEVUL.js.map +1 -0
  79. package/package.json +4 -2
  80. package/dist/chunk-EETK7S43.js.map +0 -1
  81. package/dist/chunk-K3SLGULW.js +0 -50
  82. package/dist/chunk-K3SLGULW.js.map +0 -1
  83. package/dist/chunk-MYM5VIJ4.js.map +0 -1
  84. package/dist/chunk-NNB2H4BA.js +0 -6
  85. package/dist/chunk-Q7HUXIUF.js.map +0 -1
  86. package/dist/load-A5BGEQWP.js +0 -10
  87. package/dist/runtime-session-UPTC3E6N.js +0 -20
  88. package/dist/session-store-O4XPXKOV.js +0 -4
  89. package/dist/vgd-HNPOSXKZ.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/engine/relations.ts","../src/engine/lock.ts","../src/engine/embeddings.ts","../src/engine/query.ts","../src/engine/impact.ts"],"names":["fs","path","push","text","round"],"mappings":";;;;;;;;;AAGO,IAAM,aAAN,MAAiB;AAAA,EAKtB,YAAqB,KAAA,EAAgB;AAAhB,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AACnB,IAAA,KAAA,MAAW,CAAA,IAAK,MAAM,KAAA,EAAO,IAAA,CAAK,SAAS,GAAA,CAAI,CAAA,CAA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AA,UACX,IAAA,EAAM,KAAK,IAAA,CAAK,KAAA;AAAA,UAChB,KAAA;AAAA,UACA,UAAA,EAAY;AAAA,SACb,CAAA;AACD,QAAA,YAAA,CAAa,KAAK,EAAE,EAAA,EAAI,WAAA,EAAa,IAAA,EAAM,OAAO,CAAA;AAAA,MACpD;AAAA,IACF;AACA,IAAA,QAAA,GAAW,YAAA;AACX,IAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AAAA,EAC7B;AAEA,EAAA,MAAM,QAAQ,CAAC,GAAG,QAAA,CAAS,MAAA,EAAQ,CAAA,CAAE,IAAA;AAAA,IACnC,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,QAAQ,CAAA,CAAE,KAAA,IAAS,CAAA,CAAE,UAAA,GAAa,EAAE,UAAA,IAAc,CAAA,CAAE,IAAA,CAAK,aAAA,CAAc,EAAE,IAAI;AAAA,GAC3F;AAEA,EAAA,OAAO;AAAA,IACL,MAAM,EAAE,EAAA,EAAI,QAAQ,IAAA,EAAM,IAAA,EAAM,iBAAiB,MAAA,EAAO;AAAA,IACxD,KAAA,EAAO,QAAA;AAAA,IACP,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,MAAM,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,KAAA,KAAU,CAAC,CAAA,CAAE,MAAA;AAAA,IAC3C,UAAA,EAAY,MAAM,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,KAAA,GAAQ,CAAC,CAAA,CAAE,MAAA;AAAA,IAC7C,iBAAA,EAAmBA,OAAM,iBAAiB;AAAA,GAC5C;AACF;AAEA,SAASA,OAAM,CAAA,EAAmB;AAChC,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,CAAA,GAAI,GAAG,CAAA,GAAI,GAAA;AAC/B","file":"chunk-EETK7S43.js","sourcesContent":["import type { EdgeKind, GraphEdge, GraphNode, VgGraph } from '../schema.js';\n\n/** Indexes over a graph for O(1) neighbor lookups (built once per command). */\nexport class GraphIndex {\n readonly nodeById = new Map<string, GraphNode>();\n private outById = new Map<string, GraphEdge[]>();\n private inById = new Map<string, GraphEdge[]>();\n\n constructor(readonly graph: VgGraph) {\n for (const n of graph.nodes) this.nodeById.set(n.id, n);\n for (const e of graph.edges) {\n push(this.outById, e.src, e);\n push(this.inById, e.dst, e);\n }\n }\n\n out(id: string, kind?: EdgeKind): GraphEdge[] {\n const all = this.outById.get(id) ?? [];\n return kind ? all.filter((e) => e.kind === kind) : all;\n }\n\n in(id: string, kind?: EdgeKind): GraphEdge[] {\n const all = this.inById.get(id) ?? [];\n return kind ? all.filter((e) => e.kind === kind) : all;\n }\n\n node(id: string): GraphNode | undefined {\n return this.nodeById.get(id);\n }\n\n /**\n * Resolved nodes called by `id` — invocations (`call`) plus structural\n * dependency references (`references`, e.g. a constructor-injected field's\n * type), since both represent real usage a caller/impact question cares\n * about. `references` is otherwise only emitted by the precise SCIP/tsc\n * rungs and (for Java DI wiring) the heuristic rung — never a guess.\n */\n callees(id: string): { edge: GraphEdge; node: GraphNode }[] {\n return this.resolveTargets(this.out(id).filter(isUsageEdge), 'dst');\n }\n\n /** Resolved nodes that call or structurally reference `id`. */\n callers(id: string): { edge: GraphEdge; node: GraphNode }[] {\n return this.resolveTargets(this.in(id).filter(isUsageEdge), 'src');\n }\n\n private resolveTargets(edges: GraphEdge[], end: 'src' | 'dst') {\n const out: { edge: GraphEdge; node: GraphNode }[] = [];\n for (const e of edges) {\n const node = this.nodeById.get(e[end]);\n if (node) out.push({ edge: e, node });\n }\n return out;\n }\n}\n\nconst USAGE_KINDS: ReadonlySet<EdgeKind> = new Set(['call', 'references']);\nfunction isUsageEdge(e: GraphEdge): boolean {\n return USAGE_KINDS.has(e.kind);\n}\n\nfunction push(map: Map<string, GraphEdge[]>, key: string, value: GraphEdge): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\n/**\n * Memoized `GraphIndex`, keyed on the graph object's identity.\n *\n * The index (node-by-id + in/out adjacency) is a pure function of the graph's\n * content, and every read path rebuilds it from scratch — an O(nodes + edges)\n * pass that, on a large map, costs hundreds of milliseconds *per query*. Under\n * `vg serve` the same parsed graph object is reused across many tool calls\n * (`GraphSource` caches it by file mtime and only replaces the reference when\n * `graph.json` actually changes), so rebuilding the index on every call is pure\n * waste. Keying a `WeakMap` on that object identity builds the index once and\n * reuses it until the file is rebuilt — at which point `GraphSource` hands back a\n * *new* object, this map misses, and the stale index is collected with the old\n * graph. Correct and stale-safe by construction: a different graph is a\n * different object, so there is no cross-graph reuse and nothing to invalidate.\n *\n * `GraphIndex` is read-only (no method mutates its maps), so sharing one\n * instance across callers is safe.\n */\nconst INDEX_CACHE = new WeakMap<VgGraph, GraphIndex>();\n\nexport function indexFor(graph: VgGraph): GraphIndex {\n let idx = INDEX_CACHE.get(graph);\n if (!idx) {\n idx = new GraphIndex(graph);\n INDEX_CACHE.set(graph, idx);\n }\n return idx;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Cross-process single-writer lock (O_EXCL create), shared by the embedding\n * cache writer and the auto-refresh rebuild so two vg processes never write\n * the same repo-local artifact at once. A lock whose owning process is dead,\n * or that is older than `staleMs`, is presumed abandoned and reclaimed.\n */\n\n/** A lock older than this is presumed dead (crashed process). */\nexport const DEFAULT_LOCK_STALE_MS = 15 * 60 * 1000;\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (e) {\n return (e as NodeJS.ErrnoException).code === 'EPERM'; // exists, just not ours to signal\n }\n}\n\nfunction lockIsStale(file: string, staleMs: number): boolean {\n try {\n const { pid, at } = JSON.parse(fs.readFileSync(file, 'utf8')) as { pid?: number; at?: number };\n if (typeof at === 'number' && Date.now() - at > staleMs) return true;\n if (typeof pid === 'number' && !isProcessAlive(pid)) return true;\n return false;\n } catch {\n return true; // unreadable/corrupt → reclaim it\n }\n}\n\n/** Take the lock (O_EXCL), reclaiming a stale/dead one. Returns success. */\nexport function acquireLock(file: string, staleMs = DEFAULT_LOCK_STALE_MS): boolean {\n const write = (): boolean => {\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const fd = fs.openSync(file, 'wx');\n fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));\n fs.closeSync(fd);\n return true;\n } catch {\n return false;\n }\n };\n if (write()) return true;\n if (lockIsStale(file, staleMs)) {\n try {\n fs.rmSync(file, { force: true });\n } catch {\n /* another process may have reclaimed it */\n }\n return write();\n }\n return false;\n}\n\nexport function releaseLock(file: string): void {\n try {\n fs.rmSync(file, { force: true });\n } catch {\n /* best-effort */\n }\n}\n","import * as fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { hashString } from './hash.js';\nimport { cacheDir } from './cache.js';\nimport { acquireLock, releaseLock } from './lock.js';\nimport type { GraphNode, VgGraph } from '../schema.js';\n\n/**\n * Local-embedding semantic search for `vg ask --semantic`/`--deep` (no API key).\n *\n * The embedding backend is an OPTIONAL, lazily-loaded dependency (`fastembed`,\n * Apache-2.0, local ONNX) so the core install stays lean and `ask` never breaks:\n * if the backend or model isn't available it degrades to (prefix-fuzzy) lexical\n * search with a clear note. Embeddings are query-time + cached under\n * `.vibgrate/cache/` (keyed by node-text hash); they are NEVER written into the\n * committed `graph.json`, so the artifact stays byte-deterministic.\n *\n * `--local` disables the model download (semantic is skipped unless already\n * cached via an injected backend), keeping the air-gapped guarantee.\n */\n\nexport interface Embedder {\n /** Stable model id (recorded with cached vectors so a model change invalidates them). */\n id: string;\n /** Embed documents → unit-or-raw vectors (cosine handles normalization). */\n embed(texts: string[]): Promise<number[][]>;\n /** Embed a single query string. */\n embedQuery(text: string): Promise<number[]>;\n}\n\n/** Why semantic fell back to lexical — for calm, specific messaging. */\nexport type EmbedUnavailable = 'not-installed' | 'no-permission' | 'download-failed' | 'init-failed';\n\nexport interface LoadEmbedderOptions {\n local?: boolean; // --local: do not download a model\n model?: string; // override the embedding model id\n noDownload?: boolean; // only load if the model is already cached (never fetch)\n showDownloadProgress?: boolean; // let fastembed print its one-time download progress\n onUnavailable?: (reason: EmbedUnavailable) => void; // called (not thrown) when it can't load\n}\n\n/** The embedding model id in effect (explicit override → default). */\nexport function resolveEmbedModel(model?: string): string {\n return model ?? 'bge-small-en-v1.5';\n}\n\n/**\n * The **central, per-user** model cache — downloaded once per machine and shared\n * across every repo/folder (devs have many repos; the ~tens-of-MB model should\n * not re-download per project). Uses the XDG standard:\n * `$XDG_CACHE_HOME/vibgrate/models` (or `~/.cache/vibgrate/models`); relocate via\n * the standard `XDG_CACHE_HOME`. NB: fastembed's own default is the relative\n * `./local_cache`, i.e. per-CWD — which we override.\n */\nexport function modelCacheDir(): string {\n const base = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');\n return path.join(base, 'vibgrate', 'models');\n}\n\n/** A machine-global marker written once the model has loaded successfully. */\nfunction modelReadyMarker(modelId: string): string {\n return path.join(modelCacheDir(), `.ready-${safe(modelId)}`);\n}\n\n/**\n * Whether the embedding model is already present on this machine (loaded at least\n * once), so it can be used with **no network**. Lets the background warm-up\n * trigger only when it won't surprise-download.\n */\nexport function isModelReady(modelId = resolveEmbedModel()): boolean {\n return fs.existsSync(modelReadyMarker(modelId));\n}\n\n/**\n * A calm, specific, actionable one-liner for why semantic isn't available right\n * now — built to reassure (lexical still works) and inform, never to alarm. No\n * stack traces, no scary words; always names the off switch and the fix.\n */\nexport function unavailableMessage(reason: EmbedUnavailable): string {\n switch (reason) {\n case 'no-permission':\n return `semantic search couldn't write its model cache at ${modelCacheDir()} — using fast lexical search instead. Relocate it with the standard XDG_CACHE_HOME, or run with --local to stay lexical quietly. (No admin/sudo is ever needed — the cache lives in your home folder.)`;\n case 'download-failed':\n return `the semantic model isn't downloaded yet and couldn't be fetched (offline?) — using fast lexical search. It'll try again next time; run with --local to keep lexical without retrying.`;\n case 'not-installed':\n return `the optional semantic backend isn't available here — using fast lexical search.`;\n case 'init-failed':\n default:\n return `the semantic model couldn't load — using fast lexical search.`;\n }\n}\n\nexport interface ModelCacheInfo {\n dir: string;\n present: boolean;\n bytes: number;\n}\n\n/** Where the shared model lives, whether it's present, and how big it is. */\nexport function modelCacheInfo(modelId = resolveEmbedModel()): ModelCacheInfo {\n const dir = modelCacheDir();\n return { dir, present: isModelReady(modelId) || fs.existsSync(dir), bytes: dirSize(dir) };\n}\n\n/** Remove the shared, re-downloadable model from the central cache. Returns bytes freed. */\nexport function clearModelCache(): number {\n const dir = modelCacheDir();\n const bytes = dirSize(dir);\n try {\n fs.rmSync(dir, { recursive: true, force: true });\n } catch {\n /* best-effort */\n }\n return bytes;\n}\n\nfunction dirSize(dir: string): number {\n let total = 0;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return 0;\n }\n for (const e of entries) {\n const p = path.join(dir, e.name);\n if (e.isDirectory()) total += dirSize(p);\n else {\n try {\n total += fs.statSync(p).size;\n } catch {\n /* skip unreadable */\n }\n }\n }\n return total;\n}\n\nfunction isPermissionError(e: unknown): boolean {\n const code = (e as NodeJS.ErrnoException | undefined)?.code;\n return code === 'EACCES' || code === 'EPERM' || code === 'EROFS';\n}\n\n/**\n * Whether this repo already has a cached vector set for `modelId` — i.e. semantic\n * search has run here before, so the next run is fast (no first-use download/embed).\n * Lets `ask` show the one-time setup note only when it's actually warranted.\n */\nexport function embeddingsCached(root: string, modelId: string): boolean {\n return fs.existsSync(path.join(cacheDir(root), `embeddings-${safe(modelId)}.json`));\n}\n\n/**\n * Try to load the optional local embedding backend. Returns null (→ caller falls\n * back to lexical) when running `--local`, when the dependency isn't installed,\n * or when the model can't initialize.\n */\nexport async function loadEmbedder(options: LoadEmbedderOptions = {}): Promise<Embedder | null> {\n // `--local` forces the deterministic lexical floor with no model load/download\n // (air-gapped guarantee; also how tests stay offline).\n if (options.local) return null;\n const modelId = resolveEmbedModel(options.model);\n // noDownload (used by the background warm-up): never fetch — bail if not cached.\n if (options.noDownload && !isModelReady(modelId)) return null;\n const fail = (reason: EmbedUnavailable): null => {\n options.onUnavailable?.(reason);\n return null;\n };\n\n // Lazy, optional dependency (native ONNX): loaded only for `vg ask`/`embed`,\n // never by build/verify, so the graph artifact stays deterministic.\n const mod: any = await importEmbedBackend();\n if (!mod?.FlagEmbedding) return fail('not-installed');\n\n const cache = modelCacheDir(); // central, shared across all repos\n try {\n fs.mkdirSync(cache, { recursive: true });\n } catch (e) {\n return fail(isPermissionError(e) ? 'no-permission' : 'init-failed');\n }\n\n try {\n // First use fetches the model. A refused connection fails fast, but a\n // black-holing proxy (common on corporate networks) would hang the first\n // `vg ask` / MCP query_graph forever — bound the wait and fall back to\n // lexical instead. Cached loads are local disk and get the same generous\n // ceiling without ever hitting it.\n const model: any = await withTimeout(\n mod.FlagEmbedding.init({\n model: mapModel(mod, modelId),\n cacheDir: cache,\n showDownloadProgress: options.showDownloadProgress ?? false,\n }) as Promise<unknown>,\n embedInitTimeoutMs(),\n 'embedding model init timed out',\n );\n // Record machine-global readiness so future builds can warm up offline.\n try {\n fs.writeFileSync(modelReadyMarker(modelId), new Date(0).toISOString());\n } catch {\n /* marker is best-effort */\n }\n return {\n id: modelId,\n async embed(texts) {\n const out: number[][] = [];\n for await (const batch of model.embed(texts, 64)) {\n for (const v of batch) out.push(Array.from(v as ArrayLike<number>));\n }\n return out;\n },\n async embedQuery(text) {\n const v = await model.queryEmbed(text);\n return Array.from(v as ArrayLike<number>);\n },\n };\n } catch (e) {\n return fail(isPermissionError(e) ? 'no-permission' : 'download-failed');\n }\n}\n\n/**\n * Import the optional native backend. A host can supply it out-of-tree via\n * `VIBGRATE_EMBEDDER_PATH` — a directory whose `node_modules` contains\n * `fastembed`. Editor integrations use this when their bundled engine ships\n * without the native optional dependency (the VS Code extension installs it\n * into its own storage on consent); the host dir wins over this package's own\n * dependency tree so the copy the user consented to is the one that loads.\n * Any resolution failure falls through — never throws.\n */\nasync function importEmbedBackend(): Promise<any> {\n const hostDir = process.env.VIBGRATE_EMBEDDER_PATH;\n if (hostDir) {\n try {\n const req = createRequire(path.join(hostDir, 'package.json'));\n const mod: any = await import(pathToFileURL(req.resolve('fastembed')).href);\n // A CJS entry imported over ESM may nest its exports under `default`.\n const resolved = mod?.FlagEmbedding ? mod : mod?.default;\n if (resolved?.FlagEmbedding) return resolved;\n } catch {\n /* fall through to normal resolution */\n }\n }\n return await import('fastembed' as string).catch(() => null);\n}\n\n/** Ceiling for the one-time model fetch/init; override via VG_EMBED_TIMEOUT_MS. */\nfunction embedInitTimeoutMs(): number {\n const n = Number(process.env.VG_EMBED_TIMEOUT_MS);\n return Number.isFinite(n) && n > 0 ? n : 60_000;\n}\n\n/** Reject `promise` if it hasn't settled within `ms` (the work itself is not cancelled). */\nexport async function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(message)), ms);\n timer.unref?.();\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction mapModel(mod: any, id: string): unknown {\n const m = mod.EmbeddingModel ?? {};\n if (/bge-small/i.test(id)) return m.BGESmallENV15 ?? m.BGESmallEN ?? id;\n if (/bge-base/i.test(id)) return m.BGEBaseENV15 ?? id;\n if (/all-minilm/i.test(id)) return m.AllMiniLML6V2 ?? id;\n return id;\n}\n\n/** Path segments that carry no semantic signal — dropped from embed context. */\nconst PATH_NOISE = new Set([\n 'src', 'app', 'apps', 'lib', 'libs', 'dist', 'build', 'out', 'index', 'main',\n 'packages', 'pkg', 'test', 'tests', '__tests__', 'spec', 'node_modules', 'internal',\n 'com', 'example', 'demo', 'java', 'net', 'org', 'www',\n]);\n\n/** Meaningful path context for a node: a couple of parent dirs + the filename stem. */\nfunction pathContext(file: string): string {\n const parts = file.split('/');\n const stem = (parts.pop() ?? '').replace(/\\.[^.]+$/, '');\n const dirs = parts.filter((p) => p && !PATH_NOISE.has(p.toLowerCase()));\n return [...dirs.slice(-2), stem].filter(Boolean).join(' ');\n}\n\n/**\n * The text we embed for a node. Alongside identity + signature we add the\n * strongest available signal — the node's **doc-comment / docstring** summary —\n * plus lightweight context already on the graph (file-path words, area label), so\n * a tersely-named symbol (`Table`, `NotificationJob`) a concept query can reach.\n *\n * `document` nodes (markdown, manifests, Docker, CI, OpenAPI, …) put the\n * scrubbed body in `doc` — that body is the primary embed signal so `vg ask`\n * can answer project-context questions, not only code symbols.\n */\nexport function nodeEmbedText(node: GraphNode, areaLabel?: string): string {\n if (node.kind === 'document') {\n const category = (node.signature ?? 'document').replace(/^document:/, '');\n // Category keywords help ops/config queries land on the right file type.\n const categoryHints: Record<string, string> = {\n manifest: 'package dependencies scripts install dependencies versions',\n docker: 'dockerfile container image build runtime',\n compose: 'docker-compose services containers networking volumes',\n ci: 'continuous integration github actions workflow pipeline test build deploy',\n 'build-config': 'typescript tsconfig bundler vite webpack eslint prettier test',\n 'api-contract': 'openapi swagger graphql protobuf api schema endpoints',\n 'task-runner': 'makefile justfile tasks build test run commands',\n workspace: 'monorepo workspace packages pnpm turbo nx',\n infra: 'deploy infrastructure kubernetes kubernetes terraform helm kubernetes',\n 'env-example': 'environment variables configuration secrets template',\n markdown: 'documentation readme guide',\n };\n const hint = categoryHints[category] ?? category;\n return [\n node.qualifiedName,\n 'document',\n category,\n hint,\n pathContext(node.file),\n (node.doc ?? '').slice(0, 5000),\n ]\n .filter(Boolean)\n .join('\\n');\n }\n return [node.qualifiedName, node.kind, node.signature ?? '', node.doc ?? '', pathContext(node.file), areaLabel ?? '']\n .filter(Boolean)\n .join(' ');\n}\n\nexport function cosine(a: number[], b: number[]): number {\n let dot = 0;\n let na = 0;\n let nb = 0;\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i++) {\n dot += a[i] * b[i];\n na += a[i] * a[i];\n nb += b[i] * b[i];\n }\n if (na === 0 || nb === 0) return 0;\n return dot / (Math.sqrt(na) * Math.sqrt(nb));\n}\n\ninterface EmbedCache {\n model: string;\n entries: Record<string, { hash: string; vec: number[] }>;\n}\n\n/** Reports embedding progress: how many of `total` nodes are done so far. */\nexport type EmbedProgress = (done: number, total: number) => void;\n\n/** Nodes embedded per chunk — bounds memory and gives progress granularity. */\nconst EMBED_CHUNK = 256;\n/** Min gap between incremental cache writes (ms) — caps IO on big repos. */\nconst CACHE_WRITE_INTERVAL_MS = 1500;\n\nfunction vectorCachePath(root: string, modelId: string): string {\n return path.join(cacheDir(root), `embeddings-${safe(modelId)}.json`);\n}\n\n/**\n * How many searchable nodes still need embedding for `modelId` — cheap (hashes\n * the embed-text, reads only the cache; never loads the model). Lets the embed\n * command / background warm-up exit instantly when nothing changed.\n */\nexport function countPending(graph: VgGraph, root: string, modelId: string): number {\n const entries = readCacheEntries(vectorCachePath(root, modelId), modelId);\n const areaLabel = new Map(graph.areas.map((a) => [a.id, a.label] as const));\n let pending = 0;\n for (const n of graph.nodes) {\n // file/external stay out of the index; document (docs/env examples) are in.\n if (n.kind === 'file' || n.kind === 'external') continue;\n const h = hashString(nodeEmbedText(n, areaLabel.get(n.area)));\n const cached = entries[n.id];\n if (!cached || cached.hash !== h) pending++;\n }\n return pending;\n}\n\nfunction readCacheEntries(file: string, modelId: string): EmbedCache['entries'] {\n if (!fs.existsSync(file)) return {};\n try {\n const loaded = JSON.parse(fs.readFileSync(file, 'utf8')) as EmbedCache;\n if (loaded.model === modelId && loaded.entries) return loaded.entries;\n } catch {\n /* treat as empty */\n }\n return {};\n}\n\n// Single-writer lock (shared helper — see ./lock.ts) so a foreground `ask`\n// and a background `embed` never both embed the same repo at once (which\n// would race on the cache file).\n\n/**\n * Node embeddings for the searchable (non-file/external) nodes, cache-backed:\n * only nodes whose embed-text changed are re-embedded. The first run embeds in\n * chunks, **persists the cache incrementally** (so an interrupted/timed-out run\n * resumes instead of wasting the work), and reports progress via `onProgress`.\n */\nexport async function getNodeEmbeddings(\n graph: VgGraph,\n embedder: Embedder,\n root: string,\n onProgress?: EmbedProgress,\n): Promise<Map<string, number[]>> {\n const file = vectorCachePath(root, embedder.id);\n let cache: EmbedCache = { model: embedder.id, entries: {} };\n if (fs.existsSync(file)) {\n try {\n const loaded = JSON.parse(fs.readFileSync(file, 'utf8')) as EmbedCache;\n if (loaded.model === embedder.id && loaded.entries) cache = loaded;\n } catch {\n /* rebuild */\n }\n }\n\n const areaLabel = new Map(graph.areas.map((a) => [a.id, a.label] as const));\n // Include document nodes (markdown/txt/env examples) so ask can retrieve docs.\n const targets = graph.nodes.filter((n) => n.kind !== 'file' && n.kind !== 'external');\n const toEmbed: { id: string; text: string; hash: string }[] = [];\n const vectors = new Map<string, number[]>();\n for (const n of targets) {\n const text = nodeEmbedText(n, areaLabel.get(n.area));\n const h = hashString(text);\n const cached = cache.entries[n.id];\n if (cached && cached.hash === h) vectors.set(n.id, cached.vec);\n else toEmbed.push({ id: n.id, text, hash: h });\n }\n\n // Atomic write (temp + rename) so a reader never sees a half-written cache.\n const persist = (): void => {\n try {\n fs.mkdirSync(cacheDir(root), { recursive: true });\n const tmp = `${file}.tmp.${process.pid}`;\n fs.writeFileSync(tmp, JSON.stringify(cache));\n fs.renameSync(tmp, file);\n } catch {\n /* cache write best-effort */\n }\n };\n\n if (toEmbed.length) {\n // Single-writer: if another process (e.g. a background warm-up) is already\n // embedding this repo, don't double-work or race the cache — return what's\n // cached so far (lexical floor still applies). It will be complete next run.\n const lock = `${file}.lock`;\n if (!acquireLock(lock)) return vectors;\n try {\n onProgress?.(0, toEmbed.length);\n let lastWrite = Date.now();\n for (let i = 0; i < toEmbed.length; i += EMBED_CHUNK) {\n const slice = toEmbed.slice(i, i + EMBED_CHUNK);\n const vecs = await embedder.embed(slice.map((t) => t.text));\n slice.forEach((t, j) => {\n const vec = vecs[j] ?? [];\n vectors.set(t.id, vec);\n cache.entries[t.id] = { hash: t.hash, vec };\n });\n onProgress?.(Math.min(i + EMBED_CHUNK, toEmbed.length), toEmbed.length);\n // Persist periodically so a crash/timeout resumes from here next run.\n if (Date.now() - lastWrite >= CACHE_WRITE_INTERVAL_MS) {\n persist();\n lastWrite = Date.now();\n }\n }\n // prune entries for nodes no longer present, then a final authoritative write\n const live = new Set(targets.map((n) => n.id));\n for (const id of Object.keys(cache.entries)) if (!live.has(id)) delete cache.entries[id];\n persist();\n } finally {\n releaseLock(lock);\n }\n }\n\n return vectors;\n}\n\nfunction safe(id: string): string {\n return id.replace(/[^a-z0-9.-]+/gi, '_');\n}\n","import { indexFor, type GraphIndex } from './relations.js';\nimport { cosine, type Embedder } from './embeddings.js';\nimport type { GraphNode, VgGraph } from '../schema.js';\n\n/**\n * Deterministic retrieval for `vg ask` (VG-CLI-SPEC §3.2).\n *\n * Builds a structured, fact-annotated, budget-bounded context block for a\n * question — designed to drop straight into an assistant's context. The default\n * is deterministic lexical+structural retrieval (identifier/term matching with\n * morphological prefix-fuzzing, ranked by importance). `--semantic`/`--deep` adds\n * a hybrid local-embedding pass (`queryGraphSemantic`) that surfaces conceptually\n * related code even when no word is shared — still no API key.\n */\n\nexport interface QueryOptions {\n budget?: number; // approx token budget for the context block (default 2000)\n limit?: number; // max seed matches to expand (default 12)\n}\n\nexport interface QueryMatch {\n node: GraphNode;\n score: number;\n why: string;\n}\n\nexport interface QueryResult {\n question: string;\n matches: QueryMatch[];\n context: string;\n tokensEstimate: number;\n}\n\nconst STOPWORDS = new Set([\n 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'to', 'of', 'in', 'on', 'for', 'and', 'or',\n 'where', 'what', 'which', 'how', 'do', 'does', 'did', 'i', 'we', 'it', 'this', 'that', 'with',\n 'when', 'who', 'why', 'can', 'should', 'my', 'our', 'you', 'your', 'from', 'by', 'at', 'as',\n // Discovery-question scaffolding: words a caller uses to FRAME the ask\n // (\"find the code responsible for X\", \"I need to modify X, where do I\n // start?\", \"explain how X works in this codebase\") rather than to name the\n // target. Left in, these compete on equal footing with the real identifier\n // terms and can outrank it outright — e.g. \"find the code responsible for\n // deleteAsync\" let \"find\" alone drag in every FindByIdAsync/FindAll method\n // in the repo, none of them the target (VG-LOCATE-FAILURE-ANALYSIS.md).\n 'find', 'code', 'responsible', 'need', 'modify', 'me',\n 'implementation', 'explain', 'works', 'codebase', 'contains', 'file',\n // String/URL occurrence scaffolding: \"does not exist\", \"find occurrences of …\"\n // must not light up DoesNot*/NonExisting*/commandExists via weak substrings\n // (field report: https://…/signup does not exist find occurrences).\n 'not', 'no', 'exist', 'exists', 'existing', 'occurrence', 'occurrences',\n 'occurence', 'occurences', 'every', 'place', 'places', 'string', 'literal',\n 'text', 'search', 'locate', 'look', 'looking', 'show', 'list', 'all',\n]);\n\n/**\n * Strip sentence punctuation from a URL match without breaking real query\n * strings (`?key=value`). A lone trailing `?` / `!` is English punctuation\n * (\"where is https://…/signup?\") — leaving it in the needle makes the literal\n * sweep miss the bare path in source.\n */\nfunction cleanUrlNeedle(raw: string): string {\n let s = raw.trim();\n // Trailing ) ] } > , ; : ! . from markdown links / sentence ends.\n s = s.replace(/[.,;:!)\\]}>]+$/g, '');\n // Lone trailing `?` → drop. Keep `?key=…` (content after `?`).\n if (s.endsWith('?')) {\n const qi = s.lastIndexOf('?');\n if (qi === s.length - 1) s = s.slice(0, -1);\n }\n return s;\n}\n\n/**\n * Extract string/URL needles a caller is asking to *locate as text*, not as\n * bag-of-words symbol terms. URLs and quoted phrases are exact-match material\n * for the literal sweep (`search_symbols` / `search_code`); feeding their path\n * segments into lexical symbol ranking produces confidently wrong seeds\n * (dash → dashboard package, exist → NonExisting, …).\n */\nexport function extractLiteralNeedles(question: string): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const push = (raw: string, kind: 'url' | 'quote') => {\n let s = raw.trim();\n s = kind === 'url' ? cleanUrlNeedle(s) : s.replace(/[.,;:!)\\]}>?]+$/g, '');\n if (s.length < 2 || seen.has(s)) return;\n seen.add(s);\n out.push(s);\n };\n for (const m of question.matchAll(/https?:\\/\\/[^\\s\"'`<>]+/gi)) push(m[0]!, 'url');\n for (const m of question.matchAll(/([\"'`])((?:(?!\\1)[^\\\\]|\\\\.){2,})\\1/g)) {\n push(m[2]!.replace(/\\\\(.)/g, '$1'), 'quote');\n }\n return out;\n}\n\n/** Question text with URL/quoted needles removed so residual tokens can name symbols. */\nexport function stripLiteralNeedles(question: string): string {\n let s = question;\n // Strip raw URL spans first (may still carry a trailing `?` from the ask).\n for (const m of question.matchAll(/https?:\\/\\/[^\\s\"'`<>]+/gi)) {\n s = s.split(m[0]!).join(' ');\n }\n for (const lit of extractLiteralNeedles(question)) {\n s = s.split(lit).join(' ');\n }\n // Also strip bare quote pairs left behind.\n s = s.replace(/([\"'`])\\s*\\1/g, ' ');\n return s.replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Residual ask used for graph symbol ranking when the question embeds a\n * URL/quote. Empty when only framing words remain (\"where is …?\") so we do\n * not light up unrelated symbols like `applyPlan.where`.\n */\nexport function residualForSymbolSearch(question: string): string {\n const literals = extractLiteralNeedles(question);\n if (literals.length === 0) return question.trim();\n const stripped = stripLiteralNeedles(question);\n return tokenize(stripped).length === 0 ? '' : stripped;\n}\n\n/**\n * True when the instruction is a string/URL occurrence locate (not an edit).\n * Used to skip PatchIR grammar and answer from the literal sweep without\n * dumping constrained-decoding JSON into the VG Code panel.\n */\nexport function isLocateOnlyInstruction(instruction: string): boolean {\n const q = instruction.trim();\n if (!q) return false;\n const needles = extractLiteralNeedles(q);\n const hasLocateFrame =\n /\\b(where\\s+is|where\\s+are|find\\s+(all\\s+|every\\s+)?occurrence|find\\s+occurrences|does\\s+not\\s+exist|locate|search\\s+for)\\b/i.test(\n q,\n ) ||\n (needles.length > 0 && /^https?:\\/\\//i.test(q));\n // Strong edit verbs cancel locate-only (ignore \"does not exist\" as non-edit).\n const withoutExist = q.replace(/\\bdoes\\s+not\\s+exist\\b/gi, ' ');\n if (\n /\\b(fix|edit|change|replace|implement|refactor|rename|patch|create\\s+file|delete\\s+file|add\\s+a\\b|remove\\s+the\\b)\\b/i.test(\n withoutExist,\n )\n ) {\n return false;\n }\n if (needles.some((n) => /^https?:\\/\\//i.test(n))) return true;\n return hasLocateFrame && needles.length > 0;\n}\n\nexport function queryGraph(graph: VgGraph, question: string, options: QueryOptions = {}): QueryResult {\n const budget = options.budget ?? 2000;\n const limit = options.limit ?? 12;\n // When the ask embeds a URL or quoted string, score symbols only on the\n // residual framing text. Empty residual → empty matches (honest miss) rather\n // than path-token false positives that poison Task Capsules.\n const literals = extractLiteralNeedles(question);\n const forTokens = literals.length > 0 ? stripLiteralNeedles(question) : question;\n const terms = tokenize(forTokens);\n const weightOf = termWeights(graph, terms);\n const index = indexFor(graph);\n\n const scored: QueryMatch[] = [];\n // Literal-only locate: no identifier terms left after stripping needles → do\n // not invent symbol seeds from empty/weak residual framing.\n if (terms.length > 0) {\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n const { score, why } = scoreNode(node, terms, weightOf);\n if (score > 0) scored.push({ node, score: round(score * (1 + IMPORTANCE_WEIGHT * node.importance)), why });\n }\n scored.sort((a, b) => b.score - a.score || a.node.qualifiedName.localeCompare(b.node.qualifiedName));\n }\n\n const seeds = scored.slice(0, limit);\n const { context, tokensEstimate } = buildContext(graph, index, question, seeds, budget, literals);\n\n return { question, matches: seeds, context, tokensEstimate };\n}\n\nexport interface SemanticQueryOptions extends QueryOptions {\n embedder: Embedder;\n /** Precomputed node vectors (from getNodeEmbeddings); falls back to lexical for nodes without one. */\n nodeVectors: Map<string, number[]>;\n}\n\n/**\n * Hybrid lexical + local-embedding retrieval. Blends the normalized lexical score\n * with cosine similarity to the query embedding (50/50), so a question like\n * \"where do we handle auth failures?\" can surface `verify_token` even with no\n * shared identifier. Deterministic given the same model + cached vectors;\n * embeddings live only in the cache, never in `graph.json`.\n */\nexport async function queryGraphSemantic(\n graph: VgGraph,\n question: string,\n options: SemanticQueryOptions,\n): Promise<QueryResult> {\n const budget = options.budget ?? 2000;\n const limit = options.limit ?? 12;\n const literals = extractLiteralNeedles(question);\n const forTokens = literals.length > 0 ? stripLiteralNeedles(question) : question;\n const terms = tokenize(forTokens);\n const weightOf = termWeights(graph, terms);\n const index = indexFor(graph);\n // Embed the residual ask (without URL/quote noise) so semantic neighbours\n // aren't dragged toward package names that share host path segments.\n const queryVec = await options.embedder.embedQuery(forTokens || question);\n\n // Raw lexical scores (pre-importance) for normalization.\n const lexRaw = new Map<string, number>();\n let lexMax = 0;\n const whyById = new Map<string, string>();\n if (terms.length > 0) {\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n const { score, why } = scoreNode(node, terms, weightOf);\n lexRaw.set(node.id, score);\n whyById.set(node.id, why);\n if (score > lexMax) lexMax = score;\n }\n }\n\n const scored: QueryMatch[] = [];\n // Literal-only asks: skip the semantic loop entirely — embeddings over\n // \"does not exist find occurrences\" still surface unrelated hubs.\n if (terms.length > 0 || literals.length === 0) {\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n const lexNorm = lexMax > 0 ? (lexRaw.get(node.id) ?? 0) / lexMax : 0;\n const vec = options.nodeVectors.get(node.id);\n const sem = vec && terms.length > 0 ? Math.max(0, cosine(queryVec, vec)) : 0;\n const hybrid = 0.5 * lexNorm + 0.5 * sem;\n if (hybrid <= 0) continue;\n const lexWhy = whyById.get(node.id);\n const why = lexWhy || (sem > 0.3 ? `semantic match (${sem.toFixed(2)})` : 'weak match');\n scored.push({ node, score: round(hybrid * (1 + IMPORTANCE_WEIGHT * node.importance)), why });\n }\n scored.sort((a, b) => b.score - a.score || a.node.qualifiedName.localeCompare(b.node.qualifiedName));\n }\n\n const seeds = scored.slice(0, limit);\n const { context, tokensEstimate } = buildContext(graph, index, question, seeds, budget, literals);\n return { question, matches: seeds, context, tokensEstimate };\n}\n\n/**\n * Split on anything that isn't a Unicode letter/number (`\\p{L}\\p{N}`, not the\n * ASCII-only `[a-z0-9]`) so identifiers in non-Latin scripts (Japanese,\n * Cyrillic, ...) survive tokenization instead of vanishing entirely — the\n * ASCII-only split treated every character of e.g. `名前` as a separator,\n * producing zero terms and a guaranteed empty result for any question about\n * it (VG-LOCATE-FAILURE-ANALYSIS.md). Length floor is 1, not 2: a single\n * non-stopword letter/digit is still the whole identifier when that's genuinely\n * the symbol's name (adversarial fixtures deliberately use bare `f`/`x`/`h`\n * names to stress this) — STOPWORDS already screens out short function words.\n */\nfunction tokenize(q: string): string[] {\n return [\n ...new Set(\n q\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter((t) => t.length >= 1 && !STOPWORDS.has(t)),\n ),\n ];\n}\n\nfunction scoreNode(node: GraphNode, terms: string[], weightOf: (t: string) => number = () => 1): { score: number; why: string } {\n let score = 0;\n const hits: string[] = [];\n const name = node.name.toLowerCase();\n const qn = node.qualifiedName.toLowerCase();\n const file = node.file.toLowerCase();\n // Split the ORIGINAL name on camelCase / snake_case, then lowercase the parts\n // (splitting must see the capitals, so it happens before lowercasing).\n const nameParts = identifierParts(node.name);\n for (const t of terms) {\n // Each term's contribution is weighted by its specificity (IDF over symbol\n // names): a match on a distinctive term (\"toComparable\", \"layoutFor\") counts\n // for more than a match on a term shared by hundreds of symbols (\"code\",\n // \"get\", \"run\"). Without this, an incidental exact-name hit on a common word\n // in a natural-language question outranked the conceptually-correct symbol,\n // and importance weighting amplified the wrong hit (VG-NAVIGATION trace).\n const w = weightOf(t);\n if (name === t) {\n score += 10 * w;\n hits.push(t);\n } else if (nameParts.has(t)) {\n score += 6 * w;\n hits.push(t);\n } else if (name.includes(t)) {\n score += 4 * w;\n hits.push(t);\n } else if (qn.includes(t)) {\n score += 3 * w;\n hits.push(t);\n } else if (fuzzyPartMatch(t, nameParts)) {\n // Morphological / subword match: \"authentication\" ↔ \"authenticate\"\n // (shared prefix), so lexical ask survives word-form differences without\n // a model. The semantic path handles non-shared-root synonyms.\n score += 2 * w;\n hits.push(`~${t}`);\n } else if (file.includes(t)) {\n score += 1 * w;\n hits.push(t);\n }\n }\n return { score, why: hits.length ? `matched: ${hits.join(', ')}` : '' };\n}\n\n/**\n * Importance is a mild tiebreaker, not a doubling. The old `1 + importance`\n * let a hub (importance→1) double its score and outrank a stronger textual\n * match on the actual target; at 0.4 a top hub adds at most 40%, enough to\n * break genuine ties without overriding term evidence.\n */\nconst IMPORTANCE_WEIGHT = 0.4;\n\n/**\n * Per-term specificity weights (IDF) for one question, computed over the graph's\n * symbol-name vocabulary: `ln((N+1)/(df+1)) + 1`, clamped to a sane band. A term\n * that appears in one symbol name is highly discriminating; one that appears in\n * hundreds (\"get\", \"code\", \"run\", \"handler\") is near-noise. Clamped so a term\n * matching nothing (huge idf, but it scores 0 anyway) or everything can't\n * distort the scale. Cost is one O(nodes) pass, dwarfed by the scoring loop.\n */\nfunction termWeights(graph: VgGraph, terms: string[]): (t: string) => number {\n if (terms.length === 0) return () => 1;\n const df = new Map<string, number>();\n let n = 0;\n for (const node of graph.nodes) {\n if (node.kind === 'file' || node.kind === 'external') continue;\n n++;\n const name = node.name.toLowerCase();\n const parts = identifierParts(node.name);\n for (const t of terms) {\n if (parts.has(t) || name.includes(t)) df.set(t, (df.get(t) ?? 0) + 1);\n }\n }\n const w = new Map<string, number>();\n for (const t of terms) {\n const idf = Math.log((n + 1) / ((df.get(t) ?? 0) + 1)) + 1;\n // Ceiling of 8 (vs a natural df≈40 idf ≈ 5.4) keeps genuinely rare terms\n // dominant while a term matching nothing/only a file path can't distort.\n w.set(t, Math.max(0.5, Math.min(8, idf)));\n }\n return (t: string) => w.get(t) ?? 1;\n}\n\n/**\n * camelCase / snake_case / kebab split of an identifier → lowercased parts.\n * The separator alternative is Unicode-letter-aware (`\\p{L}\\p{N}`, not\n * ASCII-only `a-zA-Z0-9`) so non-Latin identifiers split on punctuation\n * without losing every character to it; the camelCase boundary lookaround\n * stays ASCII-only since upper/lowercase casing is itself an ASCII-script\n * concept — scripts without case simply never trigger it and fall through to\n * the separator split.\n */\nexport function identifierParts(name: string): Set<string> {\n return new Set(\n name\n .split(/[^\\p{L}\\p{N}]+|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/u)\n .filter(Boolean)\n .map((s) => s.toLowerCase()),\n );\n}\n\n/** A term fuzzily matches a part if they share a long-enough prefix (same root). */\nfunction fuzzyPartMatch(term: string, parts: Set<string>): boolean {\n for (const part of parts) {\n const shared = sharedPrefixLen(term, part);\n if (shared >= 5 && shared >= 0.6 * Math.min(term.length, part.length)) return true;\n }\n return false;\n}\n\nfunction sharedPrefixLen(a: string, b: string): number {\n const n = Math.min(a.length, b.length);\n let i = 0;\n while (i < n && a[i] === b[i]) i++;\n return i;\n}\n\nfunction buildContext(\n graph: VgGraph,\n index: GraphIndex,\n question: string,\n seeds: QueryMatch[],\n budget: number,\n literals: string[] = [],\n): { context: string; tokensEstimate: number } {\n const lines: string[] = [];\n lines.push(`# Context for: ${question}`);\n lines.push('');\n if (literals.length) {\n lines.push('## Literal string(s) to locate (exact text, not symbol names)');\n for (const lit of literals) lines.push(`- \\`${lit}\\``);\n lines.push(\n '_Use a quoted phrase / URL search (`search_symbols` or `search_code` with the exact needle) for occurrences. Graph symbols below (if any) are residual identifier hints only._',\n );\n lines.push('');\n }\n if (seeds.length === 0) {\n lines.push(\n literals.length\n ? '_No graph symbols matched residual terms — this is expected for a pure string/URL occurrence search. Run a literal sweep on the needle(s) above._'\n : '_No matching symbols found in the map. Try different terms, or `vg hubs` for the most important code._',\n );\n const text = lines.join('\\n');\n return { context: text, tokensEstimate: estimateTokens(text) };\n }\n\n for (const { node, why } of seeds) {\n const block: string[] = [];\n block.push(`## ${node.qualifiedName} (${node.kind}, ${node.file}:${node.span.start})`);\n if (node.signature) block.push('`' + node.signature + '`');\n const callees = index.callees(node.id).map((x) => x.node.qualifiedName);\n const callers = index.callers(node.id).map((x) => x.node.qualifiedName);\n if (callees.length) block.push(`calls: ${unique(callees).slice(0, 8).join(', ')}`);\n if (callers.length) block.push(`called by: ${unique(callers).slice(0, 8).join(', ')}`);\n block.push(`importance ${node.importance.toFixed(3)} · area #${node.area}${node.isHub ? ' · hub' : ''} · ${why}`);\n block.push('');\n\n const candidate = lines.concat(block).join('\\n');\n if (estimateTokens(candidate) > budget && lines.length > 2) break;\n lines.push(...block);\n }\n\n const text = lines.join('\\n');\n return { context: text, tokensEstimate: estimateTokens(text) };\n}\n\nfunction unique(xs: string[]): string[] {\n return [...new Set(xs)];\n}\n\nfunction estimateTokens(text: string): number {\n // ~4 chars per token, the standard rough estimate.\n return Math.ceil(text.length / 4);\n}\n\nfunction round(x: number): number {\n return Math.round(x * 1e6) / 1e6;\n}\n","import { indexFor } from './relations.js';\nimport type { EdgeKind, VgGraph } from '../schema.js';\n\n/**\n * Deterministic reverse-reachability impact analysis (VG-CLI-SPEC §3.5).\n *\n * \"What breaks if `<node>` changes\" = everything that (transitively) depends on\n * it: its callers, importers, and subtypes. We BFS *backwards* along dependency\n * edges, bounded by depth, with a confidence that decays with distance (direct =\n * high; transitive lower; ambiguous/dynamic edges already carry lower edge\n * confidence which we fold in). Test-impact selection (`--tests`) lands in\n * Phase 2; this is the structural blast radius.\n */\n\nconst DEPEND_EDGES = new Set<EdgeKind>(['call', 'import', 'extends', 'implements', 'references']);\n\nexport interface ImpactItem {\n id: string;\n name: string;\n kind: string;\n file: string;\n line: number;\n depth: number;\n confidence: number;\n}\n\nexport interface ImpactResult {\n root: { id: string; name: string };\n depth: number;\n affected: ImpactItem[];\n direct: number;\n transitive: number;\n /** Lowest edge confidence encountered (e.g. a dynamic-dispatch edge). */\n minEdgeConfidence: number;\n}\n\nexport function impactOf(graph: VgGraph, rootId: string, opts: { depth?: number } = {}): ImpactResult {\n const maxDepth = Math.max(1, opts.depth ?? 4);\n const index = indexFor(graph);\n const root = index.node(rootId);\n\n const affected = new Map<string, ImpactItem>();\n let minEdgeConfidence = 1;\n\n // BFS over incoming dependency edges (dependents of the frontier).\n let frontier: { id: string; conf: number }[] = [{ id: rootId, conf: 1 }];\n for (let depth = 1; depth <= maxDepth; depth++) {\n const nextFrontier: { id: string; conf: number }[] = [];\n for (const { id, conf } of frontier) {\n for (const e of index.in(id)) {\n if (!DEPEND_EDGES.has(e.kind)) continue;\n minEdgeConfidence = Math.min(minEdgeConfidence, e.confidence);\n const dependentId = e.src;\n if (dependentId === rootId || affected.has(dependentId)) continue;\n const node = index.node(dependentId);\n if (!node) continue;\n const conf2 = round(conf * e.confidence * 0.9); // decay with distance\n affected.set(dependentId, {\n id: node.id,\n name: node.qualifiedName,\n kind: node.kind,\n file: node.file,\n line: node.span.start,\n depth,\n confidence: conf2,\n });\n nextFrontier.push({ id: dependentId, conf: conf2 });\n }\n }\n frontier = nextFrontier;\n if (frontier.length === 0) break;\n }\n\n const items = [...affected.values()].sort(\n (a, b) => a.depth - b.depth || b.confidence - a.confidence || a.name.localeCompare(b.name),\n );\n\n return {\n root: { id: rootId, name: root?.qualifiedName ?? rootId },\n depth: maxDepth,\n affected: items,\n direct: items.filter((i) => i.depth === 1).length,\n transitive: items.filter((i) => i.depth > 1).length,\n minEdgeConfidence: round(minEdgeConfidence),\n };\n}\n\nfunction round(x: number): number {\n return Math.round(x * 1e6) / 1e6;\n}\n"]}
@@ -1,50 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
-
4
- // src/code/session-store.ts
5
- function sessionsDir(root) {
6
- return path.join(root, ".vibgrate", "code-sessions");
7
- }
8
- function latestPointer(root) {
9
- return path.join(sessionsDir(root), "latest.json");
10
- }
11
- function saveSession(root, session) {
12
- try {
13
- const dir = sessionsDir(root);
14
- fs.mkdirSync(dir, { recursive: true });
15
- fs.writeFileSync(path.join(dir, `${session.id}.json`), JSON.stringify(session, null, 2));
16
- fs.writeFileSync(latestPointer(root), JSON.stringify({ id: session.id }));
17
- } catch {
18
- }
19
- }
20
- function loadLatestSession(root) {
21
- try {
22
- const { id } = JSON.parse(fs.readFileSync(latestPointer(root), "utf8"));
23
- const raw = JSON.parse(fs.readFileSync(path.join(sessionsDir(root), `${id}.json`), "utf8"));
24
- if (Array.isArray(raw.tasks)) return raw;
25
- } catch {
26
- }
27
- return void 0;
28
- }
29
- function summarizeSession(session) {
30
- if (session.tasks.length === 0) return "";
31
- const lines = session.tasks.slice(-8).map((t, i) => `${i + 1}. ${t.instruction} \u2014 ${t.summary}${t.files.length ? ` (${t.files.join(", ")})` : ""}`);
32
- return `Earlier in this session (${session.provider}/${session.model}) you did:
33
- ${lines.join("\n")}`;
34
- }
35
- function newSession(id, provider, model, now) {
36
- return { id, provider, model, startedAt: now, updatedAt: now, tasks: [], lastChanges: [] };
37
- }
38
- function recordTask(session, task, now) {
39
- const files = [...new Set(task.changes.map((c) => c.file))];
40
- return {
41
- ...session,
42
- updatedAt: now,
43
- tasks: [...session.tasks, { instruction: task.instruction.slice(0, 300), summary: task.summary.slice(0, 300), files, stopped: task.stopped, ts: now }],
44
- lastChanges: task.changes.length ? task.changes : session.lastChanges
45
- };
46
- }
47
-
48
- export { loadLatestSession, newSession, recordTask, saveSession, sessionsDir, summarizeSession };
49
- //# sourceMappingURL=chunk-K3SLGULW.js.map
50
- //# sourceMappingURL=chunk-K3SLGULW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/code/session-store.ts"],"names":[],"mappings":";;;;AAqCO,SAAS,YAAY,IAAA,EAAsB;AAChD,EAAA,OAAY,IAAA,CAAA,IAAA,CAAK,IAAA,EAAM,WAAA,EAAa,eAAe,CAAA;AACrD;AACA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAY,IAAA,CAAA,IAAA,CAAK,WAAA,CAAY,IAAI,CAAA,EAAG,aAAa,CAAA;AACnD;AAGO,SAAS,WAAA,CAAY,MAAc,OAAA,EAA8B;AACtE,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,YAAY,IAAI,CAAA;AAC5B,IAAG,EAAA,CAAA,SAAA,CAAU,GAAA,EAAK,EAAE,SAAA,EAAW,MAAM,CAAA;AACrC,IAAG,EAAA,CAAA,aAAA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D;AACF","file":"chunk-K3SLGULW.js","sourcesContent":["/**\n * Session persistence for VG Code (VG-CLI-CODE §16) — `vg code --continue`.\n *\n * A coding session is a series of tasks; this stores a compact record of them\n * (what you asked, a one-line outcome, which files changed) plus the last\n * change-set so `/undo` survives a restart. `--continue` reloads the most recent\n * session and hands the model a short summary of what was already done, so you\n * can pick a conversation back up instead of re-explaining. We persist a\n * *summary*, never raw file contents or tool transcripts — small, private, and\n * safe to keep on disk.\n *\n * Pure over an injected clock; the store is JSON under `.vibgrate/code-sessions/`.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { FileChange } from './types.js';\n\nexport interface SessionTask {\n instruction: string;\n summary: string;\n files: string[];\n stopped: string;\n ts: number;\n}\n\nexport interface StoredSession {\n id: string;\n provider: string;\n model: string;\n startedAt: number;\n updatedAt: number;\n tasks: SessionTask[];\n /** The most recent change-set, so `/undo` works after `--continue`. */\n lastChanges: FileChange[];\n}\n\nexport function sessionsDir(root: string): string {\n return path.join(root, '.vibgrate', 'code-sessions');\n}\nfunction latestPointer(root: string): string {\n return path.join(sessionsDir(root), 'latest.json');\n}\n\n/** Write a session and update the `latest` pointer. Best-effort; never throws. */\nexport function saveSession(root: string, session: StoredSession): void {\n try {\n const dir = sessionsDir(root);\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(path.join(dir, `${session.id}.json`), JSON.stringify(session, null, 2));\n fs.writeFileSync(latestPointer(root), JSON.stringify({ id: session.id }));\n } catch {\n /* persistence is best-effort */\n }\n}\n\n/** Load the most recent session, or undefined if none/there was a read error. */\nexport function loadLatestSession(root: string): StoredSession | undefined {\n try {\n const { id } = JSON.parse(fs.readFileSync(latestPointer(root), 'utf8')) as { id: string };\n const raw = JSON.parse(fs.readFileSync(path.join(sessionsDir(root), `${id}.json`), 'utf8')) as StoredSession;\n if (Array.isArray(raw.tasks)) return raw;\n } catch {\n /* no session */\n }\n return undefined;\n}\n\n/** A short natural-language recap of a session to seed a continued run's context. */\nexport function summarizeSession(session: StoredSession): string {\n if (session.tasks.length === 0) return '';\n const lines = session.tasks.slice(-8).map((t, i) => `${i + 1}. ${t.instruction} — ${t.summary}${t.files.length ? ` (${t.files.join(', ')})` : ''}`);\n return `Earlier in this session (${session.provider}/${session.model}) you did:\\n${lines.join('\\n')}`;\n}\n\n/** A fresh session record. `id` and `now` are injected so this stays deterministic. */\nexport function newSession(id: string, provider: string, model: string, now: number): StoredSession {\n return { id, provider, model, startedAt: now, updatedAt: now, tasks: [], lastChanges: [] };\n}\n\n/** Append a completed task (immutably updating the record's timestamps). */\nexport function recordTask(\n session: StoredSession,\n task: { instruction: string; summary: string; changes: FileChange[]; stopped: string },\n now: number,\n): StoredSession {\n const files = [...new Set(task.changes.map((c) => c.file))];\n return {\n ...session,\n updatedAt: now,\n tasks: [...session.tasks, { instruction: task.instruction.slice(0, 300), summary: task.summary.slice(0, 300), files, stopped: task.stopped, ts: now }],\n lastChanges: task.changes.length ? task.changes : session.lastChanges,\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/code/prompt.ts","../src/code/apply.ts","../src/code/diff.ts","../src/code/providers.ts"],"names":["i","j"],"mappings":";;;AAoBO,IAAM,kBAAA,GAAqB;AAAA,EAChC,6EAAA;AAAA,EACA,wFAAA;AAAA,EACA,qEAAA;AAAA,EACA,EAAA;AAAA,EACA,mEAAA;AAAA,EACA,EAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,+BAAA;AAAA,EACA,SAAA;AAAA,EACA,qBAAA;AAAA,EACA,iBAAA;AAAA,EACA,EAAA;AAAA,EACA,qFAAA;AAAA,EACA,wBAAA;AAAA,EACA,uBAAA;AAAA,EACA,kBAAA;AAAA,EACA,YAAA;AAAA,EACA,6CAAA;AAAA,EACA,EAAA;AAAA,EACA;AACF,CAAA,CAAE,KAAK,IAAI,CAAA;AAWJ,SAAS,cAAc,OAAA,EAAqC;AACjE,EAAA,OAAO;AAAA,IACL,EAAE,I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A,CAAK,OAAA;AAAA,gBACd,gBAAgB,IAAA,CAAK,cAAA;AAAA,gBACrB,gBAAgB,IAAA,CAAK,cAAA;AAAA,gBACrB,0BAAA,EAA4B,CAAC,CAAC,IAAA,CAAK,cAAA;AAAA,gBACnC,iBAAiB,IAAA,CAAK,eAAA;AAAA,gBACtB,gBAAgB,IAAA,CAAK;AAAA;AACvB,aACF;AACA,YAAA,OAAO,EAAE,MAAM,GAAA,CAAI,IAAA,EAAM,OAAO,IAAA,CAAK,KAAA,EAAO,QAAA,EAAU,IAAA,CAAK,EAAA,EAAG;AAAA,UAChE;AAAA,QACF;AAAA,MACF,CAAA,CAAA,MAAQ;AAAA,MAER;AACA,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qCAAA,EAAwC,IAAA,CAAK,SAAS,WAAM,aAAA,CAAe,CAAA,CAAY,OAAO,CAAC,CAAA,CAAE,CAAA;AAAA,IACnH;AAAA,EACF;AACF","file":"chunk-MYM5VIJ4.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. Behaviour matches a full coding agent (Claude Code / Codex /\n * Grok Code class): edit by default, answer in Markdown, clarify when stuck.\n */\nexport const AGENT_SYSTEM_PROMPT = [\n 'You are VG Code — a full coding agent in a real repository (parity with Claude Code / Codex / Grok Code).',\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 'Tools: search_code (graph + literal string/URL sweep), 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 tasks: answer in finish (Markdown). Do not invent PatchIR or dummy edits.',\n '- For exact strings/URLs: search_code or mcp__vibgrate__search_symbols with the needle, then finish.',\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,6 +0,0 @@
1
- // src/version.ts
2
- var VERSION = "2026.731.2";
3
-
4
- export { VERSION };
5
- //# sourceMappingURL=chunk-NNB2H4BA.js.map
6
- //# sourceMappingURL=chunk-NNB2H4BA.js.map