@vibgrate/cli 2026.729.3 → 2026.730.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-Z4Z66IGM.js → agent-33BMKWJC.js} +4 -4
- package/dist/{agent-Z4Z66IGM.js.map → agent-33BMKWJC.js.map} +1 -1
- package/dist/baseline-V6MYDEMS.js +9 -0
- package/dist/{baseline-Q3QQF5QF.js.map → baseline-V6MYDEMS.js.map} +1 -1
- package/dist/{chunk-JXMZCTVZ.js → chunk-5G7C6H2G.js} +14 -204
- package/dist/chunk-5G7C6H2G.js.map +1 -0
- package/dist/{chunk-RIEUPFXO.js → chunk-6D4BCGRQ.js} +6 -62
- package/dist/chunk-6D4BCGRQ.js.map +1 -0
- package/dist/{chunk-YMSXP6AO.js → chunk-6WNJJXFY.js} +4 -4
- package/dist/{chunk-YMSXP6AO.js.map → chunk-6WNJJXFY.js.map} +1 -1
- package/dist/{chunk-HWFVBYX4.js → chunk-CFL3QQQZ.js} +7 -6
- package/dist/chunk-CFL3QQQZ.js.map +1 -0
- package/dist/{chunk-EQ3IOFIG.js → chunk-CQDCZQFV.js} +3 -3
- package/dist/{chunk-EQ3IOFIG.js.map → chunk-CQDCZQFV.js.map} +1 -1
- package/dist/{chunk-KBPNH67Q.js → chunk-DBMYWNLC.js} +3 -3
- package/dist/{chunk-KBPNH67Q.js.map → chunk-DBMYWNLC.js.map} +1 -1
- package/dist/{chunk-5MNX3OLS.js → chunk-EKCNSRNJ.js} +7 -6
- package/dist/chunk-EKCNSRNJ.js.map +1 -0
- package/dist/{chunk-G4HTI4ZM.js → chunk-FHJBGPJZ.js} +3 -2
- package/dist/chunk-FHJBGPJZ.js.map +1 -0
- package/dist/{chunk-3FQSBVQD.js → chunk-GLT3N7T2.js} +8 -5
- package/dist/chunk-GLT3N7T2.js.map +1 -0
- package/dist/chunk-HTLDXEHW.js +60 -0
- package/dist/chunk-HTLDXEHW.js.map +1 -0
- package/dist/{chunk-GI6W53LM.js → chunk-IDAQV3NQ.js} +4 -2
- package/dist/chunk-IDAQV3NQ.js.map +1 -0
- package/dist/{chunk-42RDYQFF.js → chunk-KGWEBM2J.js} +3 -3
- package/dist/{chunk-42RDYQFF.js.map → chunk-KGWEBM2J.js.map} +1 -1
- package/dist/{chunk-4BOWWYSE.js → chunk-ON7PZNYV.js} +12 -11
- package/dist/chunk-ON7PZNYV.js.map +1 -0
- package/dist/chunk-Q4UQ73NA.js +6 -0
- package/dist/{chunk-N3HCPBFY.js.map → chunk-Q4UQ73NA.js.map} +1 -1
- package/dist/chunk-TJ3WIJ7H.js +216 -0
- package/dist/chunk-TJ3WIJ7H.js.map +1 -0
- package/dist/chunk-VOEYUAER.js +203 -0
- package/dist/chunk-VOEYUAER.js.map +1 -0
- package/dist/cli.js +390 -507
- package/dist/cli.js.map +1 -1
- package/dist/{fs-6JKZNQ3U.js → fs-HNR6LAI7.js} +3 -3
- package/dist/fs-HNR6LAI7.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +10 -8
- package/dist/index.js.map +1 -1
- package/dist/{interactive-MJVMY5JP.js → interactive-NJG6467J.js} +16 -14
- package/dist/interactive-NJG6467J.js.map +1 -0
- package/dist/load-YPSEDYIW.js +10 -0
- package/dist/{load-4PARCNMD.js.map → load-YPSEDYIW.js.map} +1 -1
- package/dist/run-outcome-5FQWHWYK.js +253 -0
- package/dist/run-outcome-5FQWHWYK.js.map +1 -0
- package/dist/{runtime-session-AILFASQV.js → runtime-session-Y4ZD3QDO.js} +7 -6
- package/dist/{runtime-session-AILFASQV.js.map → runtime-session-Y4ZD3QDO.js.map} +1 -1
- package/dist/{stream-json-MTPWWVRR.js → stream-json-3YOPU3LF.js} +4 -4
- package/dist/{stream-json-MTPWWVRR.js.map → stream-json-3YOPU3LF.js.map} +1 -1
- package/dist/{vg-mcp-bridge-BLHEIWMT.js → vg-mcp-bridge-PZFGTZSA.js} +8 -7
- package/dist/vg-mcp-bridge-PZFGTZSA.js.map +1 -0
- package/dist/{vgd-S7D2SITC.js → vgd-DH7AHQ23.js} +6 -5
- package/dist/vgd-DH7AHQ23.js.map +1 -0
- package/package.json +1 -1
- package/dist/baseline-Q3QQF5QF.js +0 -9
- package/dist/chunk-3FQSBVQD.js.map +0 -1
- package/dist/chunk-4BOWWYSE.js.map +0 -1
- package/dist/chunk-5MNX3OLS.js.map +0 -1
- package/dist/chunk-G4HTI4ZM.js.map +0 -1
- package/dist/chunk-GI6W53LM.js.map +0 -1
- package/dist/chunk-HWFVBYX4.js.map +0 -1
- package/dist/chunk-JXMZCTVZ.js.map +0 -1
- package/dist/chunk-N3HCPBFY.js +0 -6
- package/dist/chunk-RIEUPFXO.js.map +0 -1
- package/dist/fs-6JKZNQ3U.js.map +0 -1
- package/dist/interactive-MJVMY5JP.js.map +0 -1
- package/dist/load-4PARCNMD.js +0 -9
- package/dist/vg-mcp-bridge-BLHEIWMT.js.map +0 -1
- package/dist/vgd-S7D2SITC.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/server.ts","../src/engine/export.ts"],"names":[],"mappings":";;;;;;;;;;;;AAsCA,IAAM,iBAAA,GAAoB,GAAA;AAE1B,IAAM,qBAAA,GAAwB,GAAA;AAE9B,IAAM,iBAAA,GAAoB,EAAA;AAUnB,IAAM,iBAAA,GAAoB,GAAA;AAEjC,IAAM,mBAAA,GAAsB,GAAA;AA8CrB,IAAM,cAAN,MAAkB;AAAA,EAYvB,YACW,SAAA,EACQ,OAAA,GAAU,KAAA,EAEV,MAAA,GAA4B,EAAC,EAC9C;AAJS,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AACQ,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAEA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAIjB,IAAA,IAAA,CAAK,OAAO,MAAA,CAAO,IAAA,IAAa,IAAA,CAAA,OAAA,CAAa,IAAA,CAAA,OAAA,CAAQ,SAA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,IACR,IAAA,EAAM,SAAA;AAAA,IACN,YAAA,EAAc,EAAE,OAAA,EAAS,GAAA,CAAI,WAAA,EAAa,QAAA,EAAU,CAAC,CAAA,SAAA,EAAY,GAAA,CAAI,KAAA,CAAM,UAAA,CAAW,OAAO,EAAE,CAAA,EAAE;AAAA,IACjG;AAAA,GACF;AACA,EAAA,OAAO,IAAA,CAAK,SAAA,CAAU,GAAA,EAAK,IAAA,EAAM,CAAC,CAAA,GAAI,IAAA;AACxC","file":"chunk-HWFVBYX4.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { parseGraph } from '../engine/serialize.js';\nimport { mapFileStat } from '../engine/snapshot.js';\nimport { loadGraphPreferIndex } from '../engine/index-db.js';\nimport { refreshIfStale } from '../engine/refresh.js';\nimport { TOOLS, warmEmbedderInBackground } from './tools.js';\nimport { renderToolResult } from './response.js';\nimport { recordSaving, sanitizeClient, PER_FILE_TOKENS, SAVINGS_TOOLS, type Outcome } from '../engine/savings.js';\nimport type { SessionStats } from './serve-stats.js';\nimport { countTokens } from '../engine/tokens.js';\nimport { VERSION } from '../version.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * The local `vg serve` MCP server. Self-contained and offline. Freshness is\n * two-layered, with no filesystem watcher (freshness only matters at the\n * moment of a query, so we check on read instead of watching):\n *\n * 1. **Hot reload** — `graph.json` is re-read whenever its mtime changes, so a\n * rebuild from ANY source (a foreground `vg`, another serve process, CI)\n * is picked up on the next tool call.\n * 2. **Auto-refresh** (default on) — each tool call runs a debounced, stat-only\n * freshness probe against the last build's snapshot; if the working tree\n * drifted, an incremental rebuild runs in-process (cross-process locked,\n * single-flight). The call waits only a **micro-budget** so a warm probe can\n * land without stalling MCP tools — otherwise it answers from the current\n * map while the rebuild finishes for a later call (hot-reload picks it up).\n *\n * Every tool remains read-only and auto-approvable; the refresh only rewrites\n * vg's own artifacts under `.vibgrate/`, never user code.\n */\n\n/** Min gap between freshness probes — bounds stat-walk cost under bursty tool calls. */\nconst PROBE_INTERVAL_MS = 2000;\n/** Ceiling for the self-tuned probe interval on very large repos. */\nconst MAX_PROBE_INTERVAL_MS = 30_000;\n/** Probe/rebuild may consume at most ~1/PROBE_DUTY_FACTOR of serve wall-time (20 → ≤5%). */\nconst PROBE_DUTY_FACTOR = 20;\n/**\n * How long a tool call waits for an in-flight refresh before answering from\n * the current map. Kept deliberately small: MCP tool latency is sub-10ms on\n * warm maps, and a multi-second budget (the previous 5s ceiling matched\n * `git rev-parse`'s spawn timeout) turned every sequential tool call during a\n * large-repo rebuild into a multi-second stall — measured as TypeScript p50\n * ~5.2s on the release benchmark for the `vg-cli-public` corpus entry.\n * Warm probes still finish inside this window; heavy rebuilds never should.\n */\nexport const REFRESH_BUDGET_MS = 100;\n/** After a refresh failure (e.g. read-only checkout), don't retry for this long. */\nconst FAILURE_COOLDOWN_MS = 60_000;\n\nexport type RefreshImpl = typeof refreshIfStale;\n\nexport interface GraphSourceTuning {\n probeIntervalMs?: number;\n refreshBudgetMs?: number;\n /**\n * Workspace root for freshness probes. Prefer passing this explicitly —\n * deriving it from `graphPath` via `dirname` twice only works for the legacy\n * `root/.vibgrate/graph.json` layout, not the global branch-keyed store.\n */\n root?: string;\n /** Tests only: inject a slow/fake refresh to assert the micro-budget. */\n refreshImpl?: RefreshImpl;\n}\n\nexport interface ServeOptions {\n /** Record local, counts-only usage savings (opt-in). */\n savings?: boolean;\n /**\n * Periodically upload the counts-only ledger to Vibgrate (opt-in; off by\n * default). Implies recording. The upload itself is driven by the serve\n * command (see commands/serve.ts + engine/stats-share.ts); here it just also\n * turns recording on so there's something to send.\n */\n shareStats?: boolean;\n /** Air-gapped mode (no model downloads). */\n local?: boolean;\n /** Collapse repeat heavy relation lists within a session (opt-in). */\n dedup?: boolean;\n /** Auto-refresh the map when the working tree drifts (default true). */\n refresh?: boolean;\n /**\n * Workspace root (project directory). When set, freshness probes and tools\n * use this instead of inferring root from the graph path.\n */\n root?: string;\n /**\n * In-memory session stats behind the live `vg serve` status display. Always\n * safe to pass: nothing recorded here is persisted or uploaded — it dies with\n * the process (the opt-in ledger above is a separate concern).\n */\n stats?: SessionStats;\n}\n\nexport class GraphSource {\n private cachedMtimeMs = -1;\n private cached: VgGraph | null = null;\n /** Project root used for freshness probes and rebuilds. */\n readonly root: string;\n private lastProbeAt = 0;\n private failedUntil = 0;\n private inflight: Promise<void> | null = null;\n /** Self-tuned: grows with measured probe/rebuild cost so huge repos aren't penalized. */\n private probeIntervalMs = PROBE_INTERVAL_MS;\n private readonly refreshImpl: RefreshImpl;\n\n constructor(\n readonly graphPath: string,\n private readonly refresh = false,\n /** Timing / root overrides (production passes `root`; tests may pass more). */\n private readonly tuning: GraphSourceTuning = {},\n ) {\n // Prefer an explicit root. Fallback assumes legacy `root/.vibgrate/graph.json`\n // (dirname twice); wrong for the global store — callers should pass `root`.\n this.root = tuning.root ?? path.dirname(path.dirname(graphPath));\n this.refreshImpl = tuning.refreshImpl ?? refreshIfStale;\n }\n\n /** Current graph: auto-refreshed if the tree drifted, reloaded if the file changed. */\n async get(): Promise<VgGraph> {\n if (this.refresh) await this.maybeRefresh();\n // JSON when present, else the standalone snapshot (global-store mode);\n // throws if neither exists → surfaced as tool error.\n const stat = mapFileStat(this.graphPath);\n if (stat.mtimeMs !== this.cachedMtimeMs || !this.cached) {\n // Prefer SQLite reconstruct when corpusHash matches (scale past JSON parse).\n const preferred = loadGraphPreferIndex(this.root, this.graphPath);\n this.cached = preferred\n ? preferred.graph\n : parseGraph(fs.readFileSync(this.graphPath, 'utf8'));\n this.cachedMtimeMs = stat.mtimeMs;\n }\n return this.cached;\n }\n\n /**\n * Debounced, single-flight refresh. Never throws — a refresh problem must\n * degrade to \"answer from the current map\", not break the tool call.\n */\n private async maybeRefresh(): Promise<void> {\n const now = Date.now();\n if (!this.inflight) {\n const interval = this.tuning.probeIntervalMs ?? this.probeIntervalMs;\n if (now < this.failedUntil || now - this.lastProbeAt < interval) return;\n this.lastProbeAt = now;\n this.inflight = this.refreshImpl(this.root, { graphPath: this.graphPath })\n .then((r) => {\n if (r.status === 'error') this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n // Self-tune off the full wall cost of *every* outcome — including a\n // multi-second incremental rebuild. Previously only probe-only\n // outcomes (fresh/no-snapshot/locked) backed off, so a 20s rebuild\n // of a large repo re-armed after the 2s floor and every sequential\n // tool call blocked on the refresh budget for the whole suite.\n const cost =\n r.status === 'refreshed' && typeof r.ms === 'number' ? Math.max(r.ms, Date.now() - now) : Date.now() - now;\n this.probeIntervalMs = Math.min(\n MAX_PROBE_INTERVAL_MS,\n Math.max(PROBE_INTERVAL_MS, cost * PROBE_DUTY_FACTOR),\n );\n })\n .catch(() => {\n this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n })\n .finally(() => {\n this.inflight = null;\n });\n }\n await Promise.race([this.inflight, sleep(this.tuning.refreshBudgetMs ?? REFRESH_BUDGET_MS)]);\n }\n}\n\nexport function createServer(source: GraphSource, opts: ServeOptions = {}): Server {\n const { savings = false, shareStats = false, local = false, dedup = false, stats } = opts;\n // Recording feeds both the local `vg savings` report and the opt-in upload, so\n // enabling either turns it on. Absent both, `vg serve` records nothing.\n const record = savings || shareStats;\n // Prefer GraphSource's explicit root (set by serve from the project cwd).\n const root = opts.root ?? source.root;\n // Per-session memory of node ids whose full detail was already returned — the\n // basis for opt-in cross-call dedup (`--dedup`). Scoped to this server\n // instance so it never leaks across sessions. Node ids are content-addressed\n // (blake3 of content), so an edited node gets a new id and is never falsely\n // treated as already-seen — dedup is stale-safe by construction.\n const seen = new Set<string>();\n const server = new Server(\n { name: 'vg', version: VERSION },\n {\n capabilities: { tools: {} },\n // Routing guidance once at the server level (hosts that surface\n // `instructions` get it at zero per-step schema cost): the flashlight\n // vs the map.\n instructions:\n 'vg is a code map. Use search_symbols to find a known name or literal string fast — ' +\n 'a multi-word/quoted phrase runs a complete literal sweep and reports totalTextMatches, ' +\n 'so reach for it instead of grep even for plain-string \"find every occurrence\" lookups. ' +\n 'Use orient/query_graph for meaning: symptoms, relationships, and what-breaks-if. ' +\n 'Responses are concise by default; pass response_format:\"detailed\" only when a node proves load-bearing. ' +\n // Stop-discipline: the failure mode on a focused task is over-navigation\n // — one more query, one more get_node — which re-bills the whole context\n // every step. One good navigation call usually locates the code.\n 'Navigate as little as possible: one good search/query usually locates the code. ' +\n 'As soon as you have the file and line, read that file and make the edit — ' +\n 'do not call further graph tools unless the edit fails or the match was wrong. ' +\n // Library docs: position against web search (version-correct beats\n // SEO results), and give a stopping rule so a thin doc doesn't turn\n // into an open-ended search loop.\n 'For how-do-I-use-this-library questions call resolve_library once, then library_docs ' +\n 'with the returned targetId and a focused query: the docs are official and matched to ' +\n 'the version THIS project has installed (drift-annotated) — prefer them over web search ' +\n 'or training-data recall when they conflict. Skip them for language built-ins or APIs ' +\n 'already shown in context. If two library_docs calls have not surfaced the section you ' +\n 'need, read the package source under node_modules instead of searching again.',\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: TOOLS.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n annotations: { readOnlyHint: true, openWorldHint: false },\n })),\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const tool = TOOLS.find((t) => t.name === request.params.name);\n if (!tool) {\n return errorResult(`unknown tool \"${request.params.name}\"`);\n }\n let graph: VgGraph;\n try {\n graph = await source.get();\n } catch {\n return errorResult(\n 'no code map found. Run `vg` in the project to build .vibgrate/graph.json, then retry.',\n );\n }\n const startedAt = Date.now();\n try {\n const args = (request.params.arguments ?? {}) as Record<string, unknown>;\n const result = await tool.handler(graph, args, { root, local, dedup, seen });\n const ms = Date.now() - startedAt;\n // Live, in-memory session stats for the serve status display — always on\n // when a serve process passed them (nothing leaves the process).\n stats?.record({ ...measureCall(tool.name, result), client: sanitizeClient(detectClient(server)), ms });\n // Opt-in, counts-only usage ledger: one entry per navigation call, with its\n // outcome, the grep-baseline token counts, and — so `vg savings` can show\n // the command-vs-MCP split and which AI is calling — the source (`mcp`) and\n // the client detected from the initialize handshake.\n if (record) recordUsage(root, tool.name, result, detectClient(server), ms);\n // Compact → clamp to the token ceiling → compact-serialise. See ./response.ts.\n return renderToolResult(result);\n } catch (err) {\n // A failed call still counts in the live display — as a miss, so the\n // operator sees trouble instead of a silently frozen dashboard.\n stats?.record({\n tool: tool.name,\n client: sanitizeClient(detectClient(server)),\n outcome: 'miss',\n ms: Date.now() - startedAt,\n vgTokens: 0,\n baselineTokens: 0,\n });\n return errorResult(`tool \"${tool.name}\" failed: ${(err as Error).message}`);\n }\n });\n\n return server;\n}\n\nexport async function serveStdio(graphPath: string, opts: ServeOptions = {}): Promise<void> {\n const source = new GraphSource(graphPath, opts.refresh !== false, { root: opts.root });\n const server = createServer(source, opts);\n // Start the semantic-model warm-up as soon as the server boots, so the first\n // orient/query_graph doesn't pay a cold download. Non-blocking: navigation\n // answers lexically until the model is ready, then upgrades to semantic.\n warmEmbedderInBackground(opts.local);\n await server.connect(new StdioServerTransport());\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.(); // never keep the server process alive just for the budget timer\n });\n}\n\n/**\n * Append a counts-only usage entry for a navigation call: which tool, how it\n * resolved (complete/partial/miss), and — for the grep-baseline tools — the\n * tokens vg spent vs the grep/read baseline it replaced.\n *\n * `vgTokens` is the size of the payload vg ACTUALLY returned — the rendered text\n * block the model receives and re-pays on every subsequent turn — measured with\n * the same token counter the budget uses. It is deliberately NOT read from a\n * `tokensEstimate` field: only query_graph's rarely-used *detailed* mode ever\n * set that (get_node never did), so the old code recorded nothing under normal\n * concise usage and `vg savings` always reported \"recording is off\".\n */\nexport function recordUsage(root: string, tool: string, result: unknown, client?: string, ms?: number): void {\n recordSaving(\n root,\n { ...measureCall(tool, result), source: 'mcp', client: sanitizeClient(client), ...(ms !== undefined ? { ms } : {}) },\n Date.now(),\n );\n}\n\n/**\n * Measure one tool call for the ledger and the live session stats: its outcome\n * plus — for the grep-baseline tools only — the context tokens vg returned and\n * the baseline they replaced (other tools report zeros, meaning \"no baseline\").\n */\nfunction measureCall(tool: string, result: unknown): { tool: string; outcome: Outcome; vgTokens: number; baselineTokens: number } {\n const outcome = classifyOutcome(result);\n let vgTokens = 0;\n let baselineTokens = 0;\n if (SAVINGS_TOOLS.has(tool) && result && typeof result === 'object') {\n vgTokens = countTokens(renderedText(renderToolResult(result)));\n // Grep/read baseline: ~PER_FILE_TOKENS per distinct file the answer points\n // at — the files a grep/read agent would have had to open to learn the same\n // thing. query_graph surfaces them as `matches[].file`; get_node as its own\n // `file` plus the files of the callers/callees it returned in one call.\n baselineTokens = referencedFiles(result).size * PER_FILE_TOKENS;\n }\n return { tool, outcome, vgTokens, baselineTokens };\n}\n\n/**\n * The coarse client label from the MCP `initialize` handshake, if the host sent\n * `clientInfo`. Read defensively — `getClientVersion()` exists on the SDK Server\n * once initialized, but we never want telemetry bookkeeping to throw. Returns\n * undefined when unknown (then sanitized to `'unknown'`).\n */\nfunction detectClient(server: Server): string | undefined {\n try {\n const info = (server as { getClientVersion?: () => { name?: string } | undefined }).getClientVersion?.();\n return typeof info?.name === 'string' ? info.name : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Bucket a tool result into complete / partial / miss. A `miss` is an answer\n * that found nothing (no match, not-found, not-connected, or an empty listing);\n * a `partial` found results but capped or paginated some of them; everything\n * else is `complete`. Note that a legitimately empty `affected`/`covers` (e.g.\n * \"nothing depends on this\") is a successful answer, not a miss — only the\n * primary discovery signals below mark a miss.\n */\nfunction classifyOutcome(result: unknown): Outcome {\n if (Array.isArray(result)) return result.length === 0 ? 'miss' : 'complete';\n if (!result || typeof result !== 'object') return 'miss';\n const r = result as Record<string, unknown>;\n if (typeof r.error === 'string' && r.error) return 'miss'; // not_found / ambiguous / unresolved\n if (r.connected === false) return 'miss'; // find_path\n if (Array.isArray(r.matches) && r.matches.length === 0) return 'miss'; // query_graph / search_symbols\n return isPartial(r) ? 'partial' : 'complete';\n}\n\n/** True when a hit left results on the table: paginated, or a capped relation list. */\nfunction isPartial(r: Record<string, unknown>): boolean {\n if (r.moreAvailable === true) return true;\n if (r._truncated && typeof r._truncated === 'object') return true;\n // A `<name>Total` greater than the length of its sibling `<name>` array means\n // the array was capped (e.g. get_node's callsTotal vs the shown calls).\n for (const [key, value] of Object.entries(r)) {\n if (typeof value !== 'number' || !key.endsWith('Total')) continue;\n const base = key.slice(0, -'Total'.length);\n const shown = Array.isArray(r[base]) ? (r[base] as unknown[]).length : 0;\n if (value > shown) return true;\n }\n return false;\n}\n\n/** The text block of a rendered tool result — what the model is billed for. */\nfunction renderedText(rendered: CallToolResult): string {\n const block = rendered.content?.find((b) => b.type === 'text');\n return block && 'text' in block && typeof block.text === 'string' ? block.text : '';\n}\n\n/** Distinct files a navigation result points at (its grep/read baseline set). */\nfunction referencedFiles(result: unknown): Set<string> {\n const r = result as { file?: unknown; matches?: unknown; calls?: unknown; calledBy?: unknown };\n const files = new Set<string>();\n if (typeof r.file === 'string' && r.file) files.add(r.file);\n for (const m of asArray(r.matches)) {\n const f = (m as { file?: unknown }).file;\n if (typeof f === 'string' && f) files.add(f);\n }\n // get_node's calls/calledBy are qualified names of the form `path:symbol`; the\n // path prefix is the file a grep/read agent would open to inspect that edge.\n for (const name of [...asArray(r.calls), ...asArray(r.calledBy)]) {\n if (typeof name !== 'string') continue;\n const i = name.indexOf(':');\n if (i > 0) files.add(name.slice(0, i));\n }\n return files;\n}\n\nfunction asArray(v: unknown): unknown[] {\n return Array.isArray(v) ? v : [];\n}\n\nfunction errorResult(message: string) {\n return { content: [{ type: 'text', text: message }], isError: true };\n}\n","import { serializeGraph, slimGraphForExport } from './serialize.js';\nimport { renderReport } from './report.js';\nimport { renderHtml } from './html.js';\nimport type { DepRecord } from './drift.js';\nimport type { LocalModel } from './models.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Above this node count, JSON export defaults to compact (no pretty-print). */\nexport const COMPACT_JSON_NODES = 5_000;\n\n/**\n * Deterministic exporters (VG-CLI-SPEC §4.2). One `vg export <file>` verb, format\n * inferred from the extension. Live graph-DB push is deliberately out (a file\n * import covers the same need offline). CycloneDX/SPDX power the SBOM/AI-BOM seam\n * (VG-LOCAL-MODELS §9.4).\n */\n\nexport type ExportFormat =\n | 'json'\n | 'ndjson'\n | 'graphml'\n | 'dot'\n | 'cypher'\n | 'sql'\n | 'md'\n | 'html'\n | 'cyclonedx'\n | 'spdx';\n\nexport function formatForExt(ext: string): ExportFormat | null {\n switch (ext.toLowerCase()) {\n case '.json':\n return 'json';\n case '.ndjson':\n return 'ndjson';\n case '.graphml':\n return 'graphml';\n case '.dot':\n case '.gv':\n return 'dot';\n case '.cypher':\n return 'cypher';\n case '.sql':\n return 'sql';\n case '.md':\n return 'md';\n case '.html':\n return 'html';\n default:\n return null;\n }\n}\n\nexport interface ExportContext {\n graph: VgGraph;\n deps?: DepRecord[];\n models?: LocalModel[];\n generatedAt: string;\n /** Force compact JSON (no indent). Default: auto when nodes > COMPACT_JSON_NODES. */\n compact?: boolean;\n /** Drop area members + grounding for smaller artifacts. */\n slim?: boolean;\n}\n\nexport function exportGraph(format: ExportFormat, ctx: ExportContext): string {\n const graph = ctx.slim ? slimGraphForExport(ctx.graph) : ctx.graph;\n const compact =\n ctx.compact === true ||\n (ctx.compact !== false && format === 'json' && graph.meta.counts.nodes > COMPACT_JSON_NODES);\n\n switch (format) {\n case 'json':\n return serializeGraph(graph, { compact });\n case 'md':\n return renderReport(graph);\n case 'html':\n return renderHtml(graph);\n case 'ndjson':\n return ndjson(graph);\n case 'graphml':\n return graphml(graph);\n case 'dot':\n return dot(graph);\n case 'cypher':\n return cypher(graph);\n case 'sql':\n return sql({ ...ctx, graph });\n case 'cyclonedx':\n return cyclonedx({ ...ctx, graph });\n case 'spdx':\n return spdx({ ...ctx, graph });\n }\n}\n\nfunction ndjson(graph: VgGraph): string {\n // Facts stream if present, else the node stream — one JSON object per line.\n const rows = graph.facts && graph.facts.length ? graph.facts : graph.nodes;\n return rows.map((r) => JSON.stringify(r)).join('\\n') + '\\n';\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n}\n\nfunction graphml(graph: VgGraph): string {\n const lines: string[] = [];\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n lines.push('<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\">');\n lines.push(' <key id=\"name\" for=\"node\" attr.name=\"name\" attr.type=\"string\"/>');\n lines.push(' <key id=\"kind\" for=\"node\" attr.name=\"kind\" attr.type=\"string\"/>');\n lines.push(' <key id=\"file\" for=\"node\" attr.name=\"file\" attr.type=\"string\"/>');\n lines.push(' <key id=\"ekind\" for=\"edge\" attr.name=\"kind\" attr.type=\"string\"/>');\n lines.push(' <graph edgedefault=\"directed\">');\n for (const n of graph.nodes) {\n lines.push(` <node id=\"${esc(n.id)}\"><data key=\"name\">${esc(n.qualifiedName)}</data><data key=\"kind\">${esc(n.kind)}</data><data key=\"file\">${esc(n.file)}</data></node>`);\n }\n for (const e of graph.edges) {\n lines.push(` <edge source=\"${esc(e.src)}\" target=\"${esc(e.dst)}\"><data key=\"ekind\">${esc(e.kind)}</data></edge>`);\n }\n lines.push(' </graph>');\n lines.push('</graphml>');\n return lines.join('\\n') + '\\n';\n}\n\nfunction dot(graph: VgGraph): string {\n const lines: string[] = ['digraph vg {'];\n for (const n of graph.nodes) lines.push(` \"${n.id}\" [label=\"${dotEsc(n.qualifiedName)}\"];`);\n for (const e of graph.edges) lines.push(` \"${e.src}\" -> \"${e.dst}\" [label=\"${e.kind}\"];`);\n lines.push('}');\n return lines.join('\\n') + '\\n';\n}\nfunction dotEsc(s: string): string {\n return s.replace(/\"/g, '\\\\\"');\n}\n\nfunction cypher(graph: VgGraph): string {\n const lines: string[] = [];\n for (const n of graph.nodes) {\n lines.push(\n `CREATE (:\\`${cypherLabel(n.kind)}\\` {id:${q(n.id)}, name:${q(n.qualifiedName)}, file:${q(n.file)}});`,\n );\n }\n for (const e of graph.edges) {\n lines.push(\n `MATCH (a {id:${q(e.src)}}),(b {id:${q(e.dst)}}) CREATE (a)-[:\\`${cypherLabel(e.kind)}\\`]->(b);`,\n );\n }\n return lines.join('\\n') + '\\n';\n}\nfunction cypherLabel(s: string): string {\n return s.replace(/[^A-Za-z0-9_]/g, '_');\n}\nfunction q(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Portable SQL fact-DB (VG-CLI-SPEC §4.2, agent-consumption). Emits deterministic\n * DDL + INSERT text — NOT a native driver — that loads identically into BOTH\n * sqlite3 and duckdb (`sqlite3 map.db < map.sql` / `duckdb map.db < map.sql`).\n * Text keeps the CLI dependency-free, offline, and byte-diffable; an identical\n * graph yields identical bytes. An agent can then run e.g.\n * SELECT src, dst FROM edges WHERE epistemic = 'observed' AND confidence >= 0.9;\n * Determinism: single transaction, `CREATE TABLE IF NOT EXISTS`, rows emitted in\n * the graph's own (already-sorted) array order, single quotes doubled, NULL for\n * absent optionals, booleans as 0/1, and no timestamp but the graph's generatedAt.\n */\nfunction sql(ctx: ExportContext): string {\n const graph = ctx.graph;\n const lines: string[] = [];\n lines.push('BEGIN;');\n\n // meta — provenance / toolchain fingerprint (key/value; agent can read the corpus hash).\n lines.push('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);');\n const meta: [string, string | null][] = [\n ['schemaVersion', graph.schemaVersion],\n ['generatedAt', ctx.generatedAt],\n ['corpusHash', graph.provenance.corpusHash],\n ['tool', graph.provenance.tool],\n ['toolVersion', graph.provenance.version],\n ['resolver', graph.provenance.resolver.join(',')],\n ['fingerprint', graph.provenance.toolchain?.fingerprint ?? null],\n ];\n for (const [k, v] of meta) lines.push(`INSERT INTO meta VALUES (${sqlStr(k)}, ${sqlStr(v)});`);\n\n // nodes\n lines.push(\n 'CREATE TABLE IF NOT EXISTS nodes (id TEXT PRIMARY KEY, kind TEXT, name TEXT, qualified_name TEXT, file TEXT, span_start INTEGER, span_end INTEGER, lang TEXT, visibility TEXT, signature TEXT, importance REAL, area INTEGER, is_hub INTEGER, tested INTEGER, coverage REAL);',\n );\n for (const n of graph.nodes) {\n lines.push(\n `INSERT INTO nodes VALUES (${sqlStr(n.id)}, ${sqlStr(n.kind)}, ${sqlStr(n.name)}, ${sqlStr(n.qualifiedName)}, ${sqlStr(n.file)}, ${sqlNum(n.span.start)}, ${sqlNum(n.span.end)}, ${sqlStr(n.lang)}, ${sqlStr(n.visibility)}, ${sqlStr(n.signature)}, ${sqlNum(n.importance)}, ${sqlNum(n.area)}, ${sqlBool(n.isHub)}, ${sqlBool(n.tested)}, ${sqlNum(n.coverage)});`,\n );\n }\n\n // edges — the epistemic column is the point: SELECT ... WHERE epistemic='observed'.\n lines.push(\n 'CREATE TABLE IF NOT EXISTS edges (id TEXT PRIMARY KEY, kind TEXT, src TEXT, dst TEXT, resolution TEXT, confidence REAL, epistemic TEXT, surprise REAL, \"count\" INTEGER);',\n );\n for (const e of graph.edges) {\n lines.push(\n `INSERT INTO edges VALUES (${sqlStr(e.id)}, ${sqlStr(e.kind)}, ${sqlStr(e.src)}, ${sqlStr(e.dst)}, ${sqlStr(e.resolution)}, ${sqlNum(e.confidence)}, ${sqlStr(e.epistemic)}, ${sqlNum(e.surprise)}, ${sqlNum(e.count)});`,\n );\n }\n\n // areas (+ members)\n lines.push('CREATE TABLE IF NOT EXISTS areas (id INTEGER PRIMARY KEY, label TEXT, size INTEGER, cohesion REAL, external_edges INTEGER);');\n lines.push('CREATE TABLE IF NOT EXISTS area_members (area_id INTEGER, node_id TEXT);');\n for (const a of graph.areas) {\n lines.push(`INSERT INTO areas VALUES (${sqlNum(a.id)}, ${sqlStr(a.label)}, ${sqlNum(a.size)}, ${sqlNum(a.cohesion)}, ${sqlNum(a.externalEdges)});`);\n for (const m of a.members) lines.push(`INSERT INTO area_members VALUES (${sqlNum(a.id)}, ${sqlStr(m)});`);\n }\n\n // facts (+ subjects, evidence) when the graph carried them.\n if (graph.facts && graph.facts.length) {\n lines.push('CREATE TABLE IF NOT EXISTS facts (id TEXT PRIMARY KEY, kind TEXT, predicate_json TEXT, derived_by TEXT, confidence TEXT);');\n lines.push('CREATE TABLE IF NOT EXISTS fact_subjects (fact_id TEXT, node_id TEXT);');\n lines.push('CREATE TABLE IF NOT EXISTS fact_evidence (fact_id TEXT, file TEXT, span_start INTEGER, span_end INTEGER);');\n for (const f of graph.facts) {\n lines.push(`INSERT INTO facts VALUES (${sqlStr(f.id)}, ${sqlStr(f.kind)}, ${sqlStr(JSON.stringify(f.predicate))}, ${sqlStr(f.derivedBy)}, ${sqlStr(f.confidence)});`);\n for (const s of f.subjectIds) lines.push(`INSERT INTO fact_subjects VALUES (${sqlStr(f.id)}, ${sqlStr(s)});`);\n for (const ev of f.evidence) lines.push(`INSERT INTO fact_evidence VALUES (${sqlStr(f.id)}, ${sqlStr(ev.file)}, ${sqlNum(ev.span.start)}, ${sqlNum(ev.span.end)});`);\n }\n }\n\n lines.push('COMMIT;');\n return lines.join('\\n') + '\\n';\n}\n\n/** SQL string literal (single quotes doubled) or NULL for absent values. */\nfunction sqlStr(v: string | null | undefined): string {\n if (v == null) return 'NULL';\n return `'${v.replace(/'/g, \"''\")}'`;\n}\n/** Numeric literal or NULL for absent values. */\nfunction sqlNum(v: number | null | undefined): string {\n return v == null || !Number.isFinite(v) ? 'NULL' : String(v);\n}\n/** Boolean as 0/1, NULL when unknown (e.g. an unanalyzable node's `tested`). */\nfunction sqlBool(v: boolean | null | undefined): string {\n return v == null ? 'NULL' : v ? '1' : '0';\n}\n\nfunction cyclonedx(ctx: ExportContext): string {\n // CycloneDX 1.6 JSON — dependencies as library components + local models as\n // machine-learning-model components (AI-BOM). Deterministic ordering; no\n // timestamps beyond the pinned generatedAt.\n const components: unknown[] = [];\n for (const d of ctx.deps ?? []) {\n components.push({\n type: 'library',\n name: d.name,\n version: d.installed ?? d.declared,\n purl: d.ecosystem === 'npm' ? `pkg:npm/${d.name}@${d.installed ?? ''}` : undefined,\n });\n }\n for (const m of ctx.models ?? []) {\n components.push({ type: 'machine-learning-model', name: m.name, properties: [{ name: 'vg:runtime', value: m.runtime }] });\n }\n const bom = {\n bomFormat: 'CycloneDX',\n specVersion: '1.6',\n metadata: { timestamp: ctx.generatedAt, tools: [{ name: 'vg', version: ctx.graph.provenance.version }] },\n components,\n };\n return JSON.stringify(bom, null, 2) + '\\n';\n}\n\nfunction spdx(ctx: ExportContext): string {\n const packages = (ctx.deps ?? []).map((d) => ({\n SPDXID: `SPDXRef-Package-${cypherLabel(d.name)}`,\n name: d.name,\n versionInfo: d.installed ?? d.declared,\n downloadLocation: 'NOASSERTION',\n }));\n const doc = {\n spdxVersion: 'SPDX-2.3',\n dataLicense: 'CC0-1.0',\n SPDXID: 'SPDXRef-DOCUMENT',\n name: 'vg-sbom',\n creationInfo: { created: ctx.generatedAt, creators: [`Tool: vg-${ctx.graph.provenance.version}`] },\n packages,\n };\n return JSON.stringify(doc, null, 2) + '\\n';\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine/snapshot.ts","../src/engine/report.ts","../src/engine/html.ts","../src/engine/artifacts.ts","../src/schema.ts","../src/engine/index-db.ts","../src/engine/load.ts"],"names":["crc32","fs","legacy","path2","fs3"],"mappings":";;;;;;;;;;AAsCA,IAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,WAAA,EAAa,QAAQ,CAAA;AAG/C,IAAMA,SAA2C,IAAA,CAAA,KAAA,IAAS,OAAA;AAE1D,IAAI,QAAA,GAA+B,IAAA;AAEnC,SAAS,QAAQ,IAAA,EAA0B;AACzC,EA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,EAAY,CAAA,CAAE,UAAA,GAAa,WAAA;AAClC,MAAA,IAAI,CAAC,CAAA,CAAE,SAAA,EAAW,CAAA,CAAE,SAAA,GAAY,UAAA;AAAA,IAClC;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAOO,SAAS,oBAAA,CACd,MACA,aAAA,EACqD;AAIrD,EAAA,MAAM,SAAA,GAA4B,0BAA0B,aAAa,CAAA;AAEzE,EAAA,MAAM,SAAA,GAAY,mBAAmB,IAAI,CAAA;AACzC,EAAA,IAAI,SAAA,EAAW;AACb,IAAA,IAAI,CAAC,SAAA,IAAa,SAAA,CAAU,WAAW,UAAA,KAAe,SAAA,CAAU,WAAW,UAAA,EAAY;AACrF,MAAA,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,MAAA,EAAQ,OAAA,EAAQ;AAAA,IAC7C;AAAA,EAEF;AACA,EAAA,IAAI,WAAW,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,QAAQ,MAAA,EAAO;AACzD,EAAA,OAAO,IAAA;AACT;;;ACvWO,SAAS,SAAA,CAAU,MAAc,SAAA,EAAoC;AAC1E,EAAA,MAAM,IAAA,GAAO,gBAAA,CAAiB,IAAA,EAAM,SAAS,CAAA;AAG7C,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,MAAM,SAAA,GAAY,oBAAA,CAAqB,IAAA,EAAM,IAAI,CAAA;AACjD,IAAA,IAAI,SAAA,SAAkB,SAAA,CAAU,KAAA;AAAA,EAClC;AACA,EAAA,OAAO,0BAA0B,IAAI,CAAA;AACvC","file":"chunk-JXMZCTVZ.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as zlib from 'node:zlib';\nimport { Packr } from 'msgpackr';\nimport { parseGraph } from './serialize.js';\nimport { VERSION } from '../version.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * Binary graph snapshot — a derived, local **cache** beside `graph.json`.\n *\n * `graph.json` stays the canonical, committed, human-diffable artifact and the\n * only interchange format (`vg export` / `share` / `bundle` are unchanged); the\n * determinism contract attaches to it, not to this file. The snapshot exists\n * purely so hot paths (`vg ask`/`serve`/`code`, vgd session attach) skip the\n * large-string `JSON.parse` on load and the pretty-print on write — measured\n * ~2.6× faster cold load and ~4× faster encode on XL maps, at ~40% of the size.\n *\n * Robustness rules (each one keeps JSON as the unquestioned fallback):\n * - The loader trusts a snapshot only when its recorded (size, mtimeMs) of\n * the source `graph.json` still match — any rebuild or hand-edit of the\n * JSON silently invalidates it. Staleness never needs to parse the JSON.\n * - A CRC-32 over the payload rejects torn/corrupted files; any decode error\n * (unknown magic, short file, bad msgpack, version skew) returns null\n * rather than throwing, and the caller re-reads JSON and rewrites the\n * snapshot (\"self-healing\" — first load after upgrade migrates for free).\n * - Writes are atomic (temp + rename) and best-effort: a full disk or\n * read-only store must never fail a build or a query.\n * - The engine VERSION is recorded and must match: the msgpack record layout\n * tracks the in-memory graph shape, which may change between releases.\n *\n * Format: MAGIC (\"VGSNAP1\\0\") · u32LE header length · msgpack header\n * {engine, sourceSize, sourceMtimeMs, crc32} · msgpack graph payload.\n * Everything is explicit little-endian via DataView/Buffer — no platform\n * variance. msgpackr runs its pure-JS path (its native accelerator is an\n * optional dependency we do not rely on); a fresh Packr per encode/decode\n * keeps record-id assignment deterministic for identical input.\n */\n\nconst MAGIC = Buffer.from('VGSNAP1\\0', 'latin1');\n\n/** node:zlib gained crc32 in 22.2; fall back to a table crc for 22.0/22.1. */\nconst crc32: (data: Uint8Array) => number = zlib.crc32 ?? jsCrc32;\n\nlet crcTable: Uint32Array | null = null;\n\nfunction jsCrc32(data: Uint8Array): number {\n if (!crcTable) {\n crcTable = new Uint32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n crcTable[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) crc = crcTable[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\ninterface SnapshotHeader {\n engine: string;\n crc32: number;\n /**\n * True when the snapshot IS the map (global-store mode, no graph.json\n * beside it). False/absent = sidecar of a canonical graph.json, valid only\n * while that JSON's recorded stat still matches.\n */\n standalone?: boolean;\n sourceSize?: number;\n sourceMtimeMs?: number;\n}\n\n/** Sidecar path for a map file: `…/graph.json` → `…/graph.snap`. */\nexport function snapshotPathFor(graphPath: string): string {\n return graphPath.endsWith('.json') ? `${graphPath.slice(0, -5)}.snap` : `${graphPath}.snap`;\n}\n\nfunction newPackr(): Packr {\n return new Packr({ useRecords: true });\n}\n\n/** Msgpack payload bytes for a graph (exported for the determinism test). */\nexport function encodeGraphPayload(graph: VgGraph): Buffer {\n return Buffer.from(newPackr().pack(graph));\n}\n\n/**\n * Write the snapshot beside `graphPath`.\n *\n * Sidecar mode (default): call after `graph.json` is on disk — the header\n * records its stat so readers can cheaply detect staleness.\n * `standalone: true` (global-store mode): the snapshot IS the map; no\n * `graph.json` is required or consulted.\n * Best-effort: returns false (never throws) when the file can't be written.\n */\nexport function writeGraphSnapshot(\n graphPath: string,\n graph: VgGraph,\n opts: { standalone?: boolean } = {},\n): boolean {\n try {\n const payload = encodeGraphPayload(graph);\n let header: Buffer;\n if (opts.standalone) {\n header = newPackr().pack({\n engine: VERSION,\n crc32: crc32(payload),\n standalone: true,\n } satisfies SnapshotHeader);\n } else {\n const stat = fs.statSync(graphPath);\n header = newPackr().pack({\n engine: VERSION,\n sourceSize: stat.size,\n sourceMtimeMs: stat.mtimeMs,\n crc32: crc32(payload),\n } satisfies SnapshotHeader);\n }\n const lenBuf = Buffer.alloc(4);\n lenBuf.writeUInt32LE(header.length, 0);\n const file = snapshotPathFor(graphPath);\n const tmp = `${file}.${process.pid}.tmp`;\n try {\n fs.writeFileSync(tmp, Buffer.concat([MAGIC, lenBuf, header, payload]));\n fs.renameSync(tmp, file);\n } catch (err) {\n fs.rmSync(tmp, { force: true });\n throw err;\n }\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Load the snapshot for `graphPath`, or null when it is absent, stale,\n * or corrupted.\n *\n * Sidecar snapshots additionally require their source `graph.json` to exist\n * with an unchanged stat AND an identical engine version — the JSON fallback\n * is free, so any doubt invalidates. Standalone snapshots are the map itself:\n * they are accepted on magic + CRC + a structural sanity check, including\n * across engine versions (msgpack embeds its record layout, so an older\n * snapshot decodes the same way an older committed graph.json would parse).\n */\nexport function readGraphSnapshot(graphPath: string): VgGraph | null {\n try {\n const file = snapshotPathFor(graphPath);\n if (!fs.existsSync(file)) return null;\n const raw = fs.readFileSync(file);\n if (raw.length < MAGIC.length + 4 || !raw.subarray(0, MAGIC.length).equals(MAGIC)) return null;\n const headerLen = raw.readUInt32LE(MAGIC.length);\n const payloadStart = MAGIC.length + 4 + headerLen;\n if (payloadStart > raw.length) return null;\n const header = newPackr().unpack(raw.subarray(MAGIC.length + 4, payloadStart)) as SnapshotHeader;\n if (!header.standalone) {\n if (header.engine !== VERSION) return null;\n const sourceStat = fs.statSync(graphPath); // no source JSON → nothing to be a cache of\n if (header.sourceSize !== sourceStat.size || header.sourceMtimeMs !== sourceStat.mtimeMs) return null;\n }\n const payload = raw.subarray(payloadStart);\n if (crc32(payload) !== header.crc32) return null;\n const graph = newPackr().unpack(payload) as VgGraph;\n if (!graph || !Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) return null;\n return graph;\n } catch {\n return null;\n }\n}\n\n/**\n * Does a map exist at `graphPath` in either representation — the canonical\n * `graph.json`, or a standalone binary snapshot (global-store mode)?\n * Cheap: reads only the snapshot header, never the payload or the JSON.\n */\nexport function mapFileExists(graphPath: string): boolean {\n if (fs.existsSync(graphPath)) return true;\n return readSnapshotHeader(snapshotPathFor(graphPath))?.standalone === true;\n}\n\n/**\n * Stat for \"did the map change on disk\" mtime tracking: the JSON when\n * present, else the standalone snapshot file. Throws when neither exists —\n * same contract callers had with `fs.statSync(graphPath)`.\n */\nexport function mapFileStat(graphPath: string): fs.Stats {\n try {\n return fs.statSync(graphPath);\n } catch (err) {\n const snap = snapshotPathFor(graphPath);\n if (fs.existsSync(snap)) return fs.statSync(snap);\n throw err;\n }\n}\n\n/** Parse just the envelope header of a snapshot file (null on any problem). */\nfunction readSnapshotHeader(file: string): SnapshotHeader | null {\n let fd: number | null = null;\n try {\n fd = fs.openSync(file, 'r');\n const prefix = Buffer.alloc(4096);\n const read = fs.readSync(fd, prefix, 0, prefix.length, 0);\n if (read < MAGIC.length + 4 || !prefix.subarray(0, MAGIC.length).equals(MAGIC)) return null;\n const headerLen = prefix.readUInt32LE(MAGIC.length);\n if (MAGIC.length + 4 + headerLen > read) return null;\n return newPackr().unpack(prefix.subarray(MAGIC.length + 4, MAGIC.length + 4 + headerLen)) as SnapshotHeader;\n } catch {\n return null;\n } finally {\n if (fd !== null) fs.closeSync(fd);\n }\n}\n\n/**\n * Load a map file, preferring the binary snapshot and self-healing it.\n * Fast path: valid snapshot (sidecar or standalone) → decode it. Fallback:\n * parse `graph.json`, then (best-effort) rewrite the sidecar so the next load\n * takes the fast path. Returns null only when neither representation yields a\n * graph — exactly the cases the pre-snapshot code treated as \"no graph\".\n */\nexport function loadGraphFileWithSnapshot(graphPath: string): VgGraph | null {\n const snap = readGraphSnapshot(graphPath);\n if (snap) return snap;\n let json: string;\n try {\n json = fs.readFileSync(graphPath, 'utf8');\n } catch {\n return null;\n }\n let graph: VgGraph;\n try {\n graph = parseGraph(json);\n } catch {\n return null;\n }\n writeGraphSnapshot(graphPath, graph);\n return graph;\n}\n","import type { VgGraph } from '../schema.js';\n\n/**\n * Deterministic Markdown summary (`GRAPH_REPORT.md`). Given a pinned\n * `generatedAt`, the report is byte-stable. Numbers are derived purely from the\n * graph, so the report can be regenerated from a committed `graph.json`.\n */\nexport function renderReport(graph: VgGraph): string {\n const { meta, provenance, nodes, edges } = graph;\n const lines: string[] = [];\n\n lines.push('# Code Graph Report');\n lines.push('');\n lines.push(`Generated by \\`vg\\` ${provenance.version} · schema \\`${graph.schemaVersion}\\``);\n lines.push('');\n lines.push('## Summary');\n lines.push('');\n lines.push(`- **Nodes:** ${meta.counts.nodes.toLocaleString('en-US')}`);\n lines.push(`- **Edges:** ${meta.counts.edges.toLocaleString('en-US')}`);\n lines.push(`- **Areas:** ${meta.counts.areas.toLocaleString('en-US')}`);\n lines.push(`- **Languages:** ${meta.languages.join(', ') || '—'}`);\n lines.push(`- **Clustering:** ${meta.cluster}`);\n lines.push(`- **Resolvers:** ${provenance.resolver.join(', ')}`);\n lines.push(`- **Edge kinds:** ${meta.edgeKinds.join(', ') || '—'}`);\n lines.push('');\n\n // Files by definition count.\n const fileNodes = nodes.filter((n) => n.kind === 'file');\n const defsByFile = new Map<string, number>();\n for (const n of nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n defsByFile.set(n.file, (defsByFile.get(n.file) ?? 0) + 1);\n }\n const topFiles = [...defsByFile.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 15);\n if (topFiles.length) {\n lines.push('## Largest files (by definitions)');\n lines.push('');\n lines.push('| File | Definitions |');\n lines.push('| --- | ---: |');\n for (const [file, count] of topFiles) lines.push(`| \\`${file}\\` | ${count} |`);\n lines.push('');\n }\n\n // Most-connected nodes (Phase 0 importance = normalised degree).\n const topNodes = nodes\n .filter((n) => n.kind !== 'file' && n.kind !== 'external')\n .sort((a, b) => b.importance - a.importance || a.qualifiedName.localeCompare(b.qualifiedName))\n .slice(0, 15);\n if (topNodes.length) {\n lines.push('## Most-connected definitions');\n lines.push('');\n lines.push('| Symbol | Kind | File | Importance |');\n lines.push('| --- | --- | --- | ---: |');\n for (const n of topNodes) {\n lines.push(\n `| \\`${n.qualifiedName}\\` | ${n.kind} | \\`${n.file}\\`:${n.span.start} | ${n.importance.toFixed(3)} |`,\n );\n }\n lines.push('');\n }\n\n // Edge-kind breakdown.\n const byKind = new Map<string, number>();\n for (const e of edges) byKind.set(e.kind, (byKind.get(e.kind) ?? 0) + 1);\n if (byKind.size) {\n lines.push('## Edges by kind');\n lines.push('');\n lines.push('| Kind | Count |');\n lines.push('| --- | ---: |');\n for (const [kind, count] of [...byKind.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n lines.push(`| ${kind} | ${count} |`);\n }\n lines.push('');\n }\n\n lines.push('---');\n lines.push('');\n lines.push(`_Files: ${fileNodes.length} · Corpus: \\`${provenance.corpusHash.slice(0, 16)}…\\`_`);\n lines.push('');\n\n return lines.join('\\n');\n}\n","import { stableStringify } from './serialize.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * `graph.html`: self-contained, dependency-free, deterministic overview.\n *\n * For small/medium maps we embed the full graph JSON for tooling.\n * For large maps (default: >5k nodes) we embed only a\n * **hub + area summary** so the HTML stays openable; full data stays in\n * graph.json / graph.db. Interactive WebGL (sigma.js) remains a follow-up.\n */\n\nconst EMBED_NODE_LIMIT = 5_000;\n\nexport function renderHtml(graph: VgGraph): string {\n const top = graph.nodes\n .filter((n) => n.kind !== 'file' && n.kind !== 'external')\n .sort((a, b) => b.importance - a.importance || a.qualifiedName.localeCompare(b.qualifiedName))\n .slice(0, 50);\n\n const areas = [...graph.areas]\n .sort((a, b) => b.size - a.size || a.id - b.id)\n .slice(0, 40);\n\n const rows = top\n .map(\n (n) =>\n `<tr><td><code>${esc(n.qualifiedName)}</code></td><td>${esc(n.kind)}</td>` +\n `<td><code>${esc(n.file)}</code>:${n.span.start}</td><td>${n.importance.toFixed(3)}</td></tr>`,\n )\n .join('\\n');\n\n const areaRows = areas\n .map(\n (a) =>\n `<tr><td>${a.id}</td><td><code>${esc(a.label)}</code></td>` +\n `<td>${a.size}</td><td>${a.cohesion.toFixed(3)}</td><td>${a.externalEdges}</td></tr>`,\n )\n .join('\\n');\n\n const large = graph.meta.counts.nodes > EMBED_NODE_LIMIT;\n const embedPayload = large\n ? {\n schemaVersion: graph.schemaVersion,\n generatedAt: graph.generatedAt,\n provenance: graph.provenance,\n meta: graph.meta,\n hubs: top.map((n) => ({\n id: n.id,\n name: n.qualifiedName,\n kind: n.kind,\n file: n.file,\n line: n.span.start,\n importance: n.importance,\n area: n.area,\n })),\n areas: areas.map((a) => ({\n id: a.id,\n label: a.label,\n size: a.size,\n cohesion: a.cohesion,\n externalEdges: a.externalEdges,\n })),\n note: `Full graph omitted (${graph.meta.counts.nodes} nodes > ${EMBED_NODE_LIMIT}). Use graph.json or .vibgrate/cache/graph.db.`,\n }\n : graph;\n\n const embedded = stableStringify(embedPayload, 0);\n const tier = graph.meta.analysisTier ?? 'full';\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>vg · code graph</title>\n<style>\n :root { color-scheme: light dark; }\n body { font: 14px/1.5 system-ui, sans-serif; margin: 2rem auto; max-width: 60rem; padding: 0 1rem; }\n h1 { font-size: 1.4rem; } h2 { font-size: 1.1rem; margin-top: 2rem; }\n table { border-collapse: collapse; width: 100%; }\n th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid #8884; }\n td:last-child, th:last-child { text-align: right; }\n .meta { color: #888; } code { font-size: 0.9em; }\n .banner { background: #8882; padding: 0.6rem 0.8rem; border-radius: 6px; margin: 1rem 0; }\n</style>\n</head>\n<body>\n<h1>vg · code graph</h1>\n<p class=\"meta\">${graph.meta.counts.nodes} nodes · ${graph.meta.counts.edges} edges ·\n${graph.meta.counts.areas} areas · ${esc(graph.meta.languages.join(', ') || '—')} ·\nclustering: ${esc(graph.meta.cluster)} · tier: ${esc(tier)} · vg ${esc(graph.provenance.version)}</p>\n${\n large\n ? `<p class=\"banner\">Large map (${graph.meta.counts.nodes} nodes): HTML shows hubs + areas only.\nFull graph remains in <code>graph.json</code> / <code>.vibgrate/cache/graph.db</code> (query via <code>vg serve</code>).</p>`\n : ''\n}\n<h2>Areas (subsystems)</h2>\n<table>\n<thead><tr><th>Id</th><th>Label</th><th>Size</th><th>Cohesion</th><th>External</th></tr></thead>\n<tbody>\n${areaRows || '<tr><td colspan=\"5\" class=\"meta\">no areas</td></tr>'}\n</tbody>\n</table>\n<h2>Most-connected definitions (hubs)</h2>\n<table>\n<thead><tr><th>Symbol</th><th>Kind</th><th>Location</th><th>Importance</th></tr></thead>\n<tbody>\n${rows}\n</tbody>\n</table>\n<p class=\"meta\">${large ? 'Summary payload' : 'Full graph'} embedded below for tooling.</p>\n<script type=\"application/json\" id=\"vg-graph\">\n${embedded}\n</script>\n</body>\n</html>\n`;\n}\n\nfunction esc(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { serializeGraph } from './serialize.js';\nimport { mapFileExists, snapshotPathFor, writeGraphSnapshot } from './snapshot.js';\nimport { renderReport } from './report.js';\nimport { renderHtml } from './html.js';\nimport { globalGraphPath, globalGraphPathForRef, repositoryStoreDir } from '../runtime/paths.js';\nimport { detectGitRef } from '../runtime/git-ref.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * Graph artifact layout (Fusion Runtime Phase 1).\n *\n * By default the code map lives in the **global** application store\n * (XDG / Application Support), keyed by repository id — not inside the repo.\n * That keeps `vg` / `vg serve` / auto-refresh from dirtying the working tree.\n *\n * Legacy in-repo path `.vibgrate/graph.json` is still **read** when present\n * (migration), and is still the write target when:\n * - `VIBGRATE_GRAPH_IN_REPO=1` (or true/yes), or\n * - callers pass an explicit `graphPath` / `--graph`.\n *\n * `vg share` continues to opt into a committed in-repo map by writing under\n * `.vibgrate/` (and rewriting its gitignore).\n */\n\nexport interface WriteOptions {\n root: string;\n html?: boolean; // default true\n report?: boolean; // default true\n graphPath?: string; // override graph.json path\n}\n\nexport interface WrittenArtifacts {\n graphPath: string;\n reportPath?: string;\n htmlPath?: string;\n factsPath?: string;\n}\n\nexport function vibgrateDir(root: string): string {\n return path.join(root, '.vibgrate');\n}\n\n/** Historical in-repo map path (still read as a fallback). */\nexport function legacyGraphPath(root: string): string {\n return path.join(vibgrateDir(root), 'graph.json');\n}\n\n/**\n * When true, default writes go to `.vibgrate/graph.json` (pre–Phase-1 layout).\n * Useful for CI that asserts in-repo artifacts, and for `vg share` workflows.\n */\nexport function preferInRepoGraph(env: NodeJS.ProcessEnv = process.env): boolean {\n const v = env.VIBGRATE_GRAPH_IN_REPO?.trim().toLowerCase();\n return v === '1' || v === 'true' || v === 'yes';\n}\n\n/**\n * Default **write** path for the map. Global store unless the operator opts\n * into the legacy in-repo layout. When git is available, prefer a\n * branch-keyed snapshot (Fusion §4.1.1) so switching branches does not\n * overwrite another ref's on-disk map.\n */\nexport function defaultGraphPath(root: string, env: NodeJS.ProcessEnv = process.env): string {\n if (preferInRepoGraph(env)) return legacyGraphPath(root);\n const { ref, kind } = detectGitRef(root);\n if (kind !== 'none' && ref) return globalGraphPathForRef(root, ref, env);\n return globalGraphPath(root, 'current', env);\n}\n\n/**\n * Resolve where to **read** the map from.\n * Order: explicit override → legacy in-repo when `VIBGRATE_GRAPH_IN_REPO` is set\n * → branch-keyed global (if on a git ref) → `current` global snapshot →\n * legacy in-repo → default write path.\n *\n * The in-repo env short-circuit matters for CI and the release benchmark: they\n * force portable `.vibgrate/graph.json` artifacts and must not pay a synchronous\n * `git rev-parse` (or prefer a leftover global snapshot) on every resolve.\n */\nexport function resolveGraphPath(root: string, override?: string, env: NodeJS.ProcessEnv = process.env): string {\n if (override?.trim()) return path.resolve(override.trim());\n if (preferInRepoGraph(env)) {\n const legacy = legacyGraphPath(root);\n if (fs.existsSync(legacy)) return legacy;\n return legacy;\n }\n const { ref, kind } = detectGitRef(root);\n if (kind !== 'none' && ref) {\n const branchPath = globalGraphPathForRef(root, ref, env);\n if (mapFileExists(branchPath)) return branchPath;\n }\n const globalPath = globalGraphPath(root, 'current', env);\n if (mapFileExists(globalPath)) return globalPath;\n const legacy = legacyGraphPath(root);\n if (fs.existsSync(legacy)) return legacy;\n return defaultGraphPath(root, env);\n}\n\n/**\n * By default the graph artifacts are *local*: builds and auto-refreshes rewrite\n * them constantly, and without an ignore file every `vg ask`/`vg serve` leaves\n * the branch dirty (untracked or modified `.vibgrate/` files) — irritating for\n * humans and a source of junk commits from AI agents. So the first time vg\n * writes into `.vibgrate/` it also drops a `.gitignore` covering the graph\n * artifacts, the cache, and itself.\n *\n * Deliberately create-once: an existing `.vibgrate/.gitignore` is NEVER\n * touched, whatever its content — `vg share` owns it after opt-in (rewritten to\n * commit `graph.json`), and a user-managed file (even an empty one) is theirs.\n * Scanner artifacts meant for git (`baseline.json`, `standards.json`,\n * `attestation.intoto.jsonl`) are intentionally not listed.\n *\n * With the global store default, this gitignore is only created when something\n * is still written under `.vibgrate/` (in-repo mode or other in-repo writers).\n */\nconst DEFAULT_GITIGNORE = [\n '# Created once by vg — local graph artifacts stay out of git by default.',\n '# Run `vg share` to commit the map for your team (it rewrites this file).',\n '# vg never touches an existing .vibgrate/.gitignore: edit it (or leave it',\n '# empty) to manage these ignores yourself.',\n '.gitignore',\n 'cache/',\n 'graph.json',\n 'graph.snap',\n 'graph.html',\n 'GRAPH_REPORT.md',\n 'facts.jsonl',\n 'mcp-navigation.json',\n];\n\nexport function ensureVibgrateGitignore(root: string): void {\n const file = path.join(vibgrateDir(root), '.gitignore');\n if (fs.existsSync(file)) return;\n fs.mkdirSync(vibgrateDir(root), { recursive: true });\n fs.writeFileSync(file, `${DEFAULT_GITIGNORE.join('\\n')}\\n`);\n}\n\n/**\n * Directory for companion artifacts (report, html, facts) next to the map.\n * Global maps → repository store root; in-repo maps → `.vibgrate/`.\n */\nexport function companionArtifactDir(root: string, graphPath: string, env: NodeJS.ProcessEnv = process.env): string {\n const resolved = path.resolve(graphPath);\n const legacy = path.resolve(legacyGraphPath(root));\n if (resolved === legacy) return vibgrateDir(root);\n const globalDefault = path.resolve(globalGraphPath(root, 'current', env));\n if (resolved === globalDefault) return repositoryStoreDir(root, env);\n // Custom --graph: keep companions next to the map file.\n return path.dirname(resolved);\n}\n\nexport function writeArtifacts(graph: VgGraph, options: WriteOptions): WrittenArtifacts {\n const graphPath = options.graphPath ?? defaultGraphPath(options.root);\n const companions = companionArtifactDir(options.root, graphPath);\n const inRepo = isPathInside(companions, options.root) || isPathInside(graphPath, options.root);\n\n fs.mkdirSync(path.dirname(graphPath), { recursive: true });\n fs.mkdirSync(companions, { recursive: true });\n\n // Only drop `.vibgrate/.gitignore` when we still touch the in-repo layout.\n if (inRepo && isPathInside(companions, vibgrateDir(options.root))) {\n ensureVibgrateGitignore(options.root);\n } else if (path.resolve(graphPath) === path.resolve(legacyGraphPath(options.root))) {\n ensureVibgrateGitignore(options.root);\n }\n\n // Global-store maps are machine-consumed only, so the snapshot IS the map\n // there — skipping the pretty-JSON serialize is the bulk of the write cost\n // on large repos. Everywhere a human (or git) can see the file — legacy\n // in-repo layout, VIBGRATE_GRAPH_IN_REPO, `vg share`, an explicit --graph\n // path — the canonical graph.json is still written, with the snapshot as a\n // sidecar cache.\n const storeMode = isPathInside(graphPath, repositoryStoreDir(options.root));\n\n if (storeMode) {\n if (!writeGraphSnapshot(graphPath, graph, { standalone: true })) {\n // Store not writable for the binary — fall back to the JSON write below\n // rather than losing the build.\n } else {\n // Drop any JSON left by an older CLI at this path so a downgrade can\n // never silently serve a stale map from beside a newer snapshot.\n fs.rmSync(graphPath, { force: true });\n }\n }\n\n if (!storeMode || !fs.existsSync(snapshotPathFor(graphPath))) {\n // Atomic write (temp + rename): `vg serve` hot-reloads the map on mtime\n // change, so a rebuild — including its own in-process auto-refresh — must\n // never expose a half-written file to a concurrent reader.\n const tmp = `${graphPath}.${process.pid}.tmp`;\n try {\n fs.writeFileSync(tmp, serializeGraph(graph));\n fs.renameSync(tmp, graphPath);\n } catch (err) {\n fs.rmSync(tmp, { force: true });\n throw err;\n }\n // Binary sidecar cache for fast loads; best-effort, JSON stays canonical.\n writeGraphSnapshot(graphPath, graph);\n }\n\n const written: WrittenArtifacts = {\n graphPath: storeMode && !fs.existsSync(graphPath) ? snapshotPathFor(graphPath) : graphPath,\n };\n\n if (options.report !== false) {\n const reportPath = path.join(companions, 'GRAPH_REPORT.md');\n fs.writeFileSync(reportPath, renderReport(graph));\n written.reportPath = reportPath;\n }\n\n if (options.html !== false) {\n const htmlPath = path.join(companions, 'graph.html');\n fs.writeFileSync(htmlPath, renderHtml(graph));\n written.htmlPath = htmlPath;\n }\n\n // facts.jsonl (deterministic NDJSON) when facts were derived.\n if (graph.facts && graph.facts.length) {\n const factsPath = path.join(companions, 'facts.jsonl');\n fs.writeFileSync(factsPath, graph.facts.map((f) => JSON.stringify(f)).join('\\n') + '\\n');\n written.factsPath = factsPath;\n }\n\n return written;\n}\n\nfunction isPathInside(child: string, parent: string): boolean {\n const rel = path.relative(path.resolve(parent), path.resolve(child));\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n}\n","/**\n * The `vg-graph/1.0` on-disk schema.\n *\n * This is vg's own open schema (VG-PACKAGE-AND-SCHEMA.md §4) — informed by good\n * ideas (content-hashed ids, epistemic typing of facts) but standalone and\n * self-contained. Every collection is deterministically serialized\n * (sorted keys, stable element order). These TypeScript shapes are normative.\n */\n\nexport const SCHEMA_VERSION = 'vg-graph/1.0' as const;\n\nexport type ResolverKind = 'scip' | 'stackgraph' | 'tsc' | 'heuristic';\n\n/** Coarse, honest resolution tier for an edge (see engine/epistemic.ts). */\nexport type EpistemicTier = 'observed' | 'name-matched' | 'declared';\n\n/**\n * The toolchain that produced this graph — the reproducibility fingerprint.\n * Everything here deterministically affects graph *content* (parse trees change\n * between grammar releases; resolvers change which edges resolve), so a CI run\n * and a laptop run that disagree can be caught by comparing `fingerprint`.\n * Deliberately excludes the Node/OS version so the graph stays byte-stable\n * across host runtimes; `fingerprint` pins the parse/resolve toolchain only.\n */\nexport interface Toolchain {\n schema: string; // SCHEMA_VERSION\n tool: string; // vg calendar version\n grammars: string; // tree-sitter grammar set version string\n resolvers: ResolverKind[]; // resolver kinds available, sorted\n fingerprint: string; // shortId over the fields above — the value `vg attest` signs\n}\n\nexport interface Provenance {\n tool: 'vg';\n version: string; // calendar version\n grammars: Record<string, string>; // lang → grammar version (determinism input)\n resolver: ResolverKind[];\n deep: boolean; // did the heavier open passes run\n semanticModel?: string; // embedding model id+version if --deep semantic links\n corpusHash: string; // blake3 over the included file set + hashes\n toolchain?: Toolchain; // reproducibility fingerprint (checked by `vg verify`)\n}\n\n/** Analysis cost tier — auto-selected by node count (or forced). Reported honestly. */\nexport type AnalysisTier = 'full' | 'large' | 'xl';\n\nexport interface GraphMeta {\n root: string; // relative; portable across machines\n languages: string[];\n counts: {\n nodes: number;\n edges: number;\n areas: number;\n tests: number;\n untested: number;\n };\n cluster: 'leiden' | 'louvain' | 'none';\n /** Auto-selected (or forced) analysis tier for large maps. */\n analysisTier?: AnalysisTier;\n edgeKinds: EdgeKind[];\n}\n\nexport type NodeKind =\n | 'file'\n | 'module'\n | 'package'\n | 'class'\n | 'interface'\n | 'function'\n | 'method'\n | 'property'\n | 'test'\n | 'route'\n | 'component'\n /** Documentation / config text ingested for semantic ask (markdown, txt, env examples). */\n | 'document'\n | 'external';\n\nexport interface Span {\n start: number; // 1-based start line\n end: number; // 1-based end line\n}\n\nexport interface Centrality {\n degree: number;\n pagerank: number;\n betweenness: number;\n eigenvector: number;\n}\n\nexport interface GraphNode {\n id: string; // blake3(canonical(kind, qualifiedName, file, signature))\n kind: NodeKind;\n name: string; // short name\n qualifiedName: string;\n file: string; // relative path\n span: Span; // line range (excluded from id hash)\n lang: string;\n visibility?: 'public' | 'private' | 'protected' | 'internal';\n signature?: string;\n doc?: string; // short leading doc-comment / docstring summary (deterministic; not a full body)\n importance: number; // 0..1 blended centrality\n centrality: Centrality;\n area: number; // area id (the node's community); -1 = unassigned (cluster \"none\")\n isHub: boolean; // centrality outlier — surfaced by `vg hubs`\n tested: boolean | null; // null = not analyzable (e.g. external)\n coverage?: number; // 0..1 line coverage if a coverage report was ingested\n changeCoupling?: string[]; // node ids that historically change together\n}\n\nexport type EdgeKind =\n | 'call'\n | 'import'\n | 'contains'\n | 'extends'\n | 'implements'\n | 'references'\n | 'test'\n | 'coverage';\n\nexport interface GraphEdge {\n id: string; // blake3(canonical(kind, src, dst))\n kind: EdgeKind;\n src: string; // node id\n dst: string; // node id\n resolution: ResolverKind; // how the edge was resolved\n confidence: number; // 0..1 (1.0 for scip/declared; lower for heuristic/dynamic)\n epistemic?: EpistemicTier; // coarse honesty tier derived from resolution+kind\n surprise?: number; // 0..1 improbability under the area model (`vg oddities`)\n count?: number; // call-site multiplicity\n}\n\nexport interface Area {\n id: number; // stable across runs (remapped to previous committed map)\n label: string; // most-central member's name (editable via `vg label`)\n size: number;\n members: string[]; // node ids, sorted\n cohesion: number; // 0..1\n externalEdges: number; // cross-area edge count\n}\n\nexport type FactKind = 'contract' | 'invariant' | 'characterization';\nexport type DerivedBy = 'declared' | 'static';\nexport type FactConfidence = 'Observed' | 'Derived';\n\nexport interface Fact {\n id: string; // blake3(canonical(kind, subjectIds, predicate))\n kind: FactKind;\n subjectIds: string[]; // node ids this fact constrains\n predicate: unknown; // the constraint\n derivedBy: DerivedBy;\n confidence: FactConfidence;\n evidence: { file: string; span: Span }[];\n}\n\n/**\n * A reference the graph could not resolve — surfaced by `vg unknowns`. Reporting\n * what it *cannot* connect (ranked by blast radius) is the honest inverse of a\n * scanner that hides its unknowns. Only unknowns the precise rungs (tsc/scip)\n * did not supersede are recorded, so a compiler-resolved file never shows here.\n */\nexport interface Unknown {\n from: string; // node id where the unresolved reference occurs\n name: string; // the callee/type name that could not be resolved\n kind: 'call' | 'extends' | 'implements';\n count: number; // occurrences at this site\n}\n\nexport type GroundingKind = 'should_follow' | 'smells_like' | 'relevant_to';\n\nexport interface GroundingEdge {\n src: string; // node id\n packEntryId: string;\n kind: GroundingKind;\n confidence: number; // 0..1\n rationale: 'recommended' | 'conjectured';\n citation: { title: string; url: string };\n}\n\n/** Precomputed hub blast-radius counts for fast agent answers (optional). */\nexport interface HubBlastSummary {\n id: string;\n name: string;\n kind: string;\n file: string;\n importance: number;\n direct: number;\n depth2: number;\n files: number;\n tested: boolean | null;\n}\n\nexport interface GraphSummaries {\n hubs: HubBlastSummary[];\n}\n\nexport interface VgGraph {\n schemaVersion: typeof SCHEMA_VERSION;\n generatedAt: string; // ISO; the ONLY nondeterministic field (pinned by --generated-at)\n provenance: Provenance;\n meta: GraphMeta;\n nodes: GraphNode[]; // sorted by id\n edges: GraphEdge[]; // sorted by (kind, src, dst)\n areas: Area[]; // sorted by id\n facts?: Fact[]; // open facts (contract/invariant/characterization); sorted by id\n grounding?: GroundingEdge[]; // free-pack grounding (default on; omit with --no-ground)\n unknowns?: Unknown[]; // heuristic references left unresolved; sorted by (from, kind, name)\n /** Build-time hub blast-radius summaries (always on; tiny). */\n summaries?: GraphSummaries;\n}\n","/**\n * SQLite serve index for large maps (scale past flat-JSON-only serve).\n *\n * The canonical artifact remains `graph.json` (determinism / git). The index\n * at `.vibgrate/cache/graph.db` is a derived, gitignored structure built after\n * every successful build:\n * - denormalized name/edge columns for O(log n) lookup\n * - full node/edge/area JSON for reconstructing a `VgGraph` without parsing\n * the pretty-printed graph.json (faster cold serve on XL maps)\n *\n * Uses Node's built-in `node:sqlite` (Node ≥22) — no native npm dependency.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { cacheDir } from './cache.js';\nimport { loadGraphFileWithSnapshot } from './snapshot.js';\nimport type {\n Area,\n EpistemicTier,\n GraphEdge,\n GraphNode,\n ResolverKind,\n VgGraph,\n} from '../schema.js';\nimport { SCHEMA_VERSION } from '../schema.js';\n\nexport interface IndexWriteResult {\n path: string;\n nodes: number;\n edges: number;\n /** False when node:sqlite is unavailable — callers should not fail the build. */\n ok: boolean;\n reason?: string;\n}\n\nexport function indexDbPath(root: string): string {\n return path.join(cacheDir(root), 'graph.db');\n}\n\n/** Write (replace) the SQLite index from a built graph. Never throws to callers. */\nexport function writeGraphIndex(root: string, graph: VgGraph): IndexWriteResult {\n const file = indexDbPath(root);\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const tmp = `${file}.${process.pid}.tmp`;\n try {\n if (fs.existsSync(tmp)) fs.unlinkSync(tmp);\n } catch {\n /* ignore */\n }\n\n const db = new DatabaseSync(tmp);\n db.exec(`\n PRAGMA journal_mode = OFF;\n PRAGMA synchronous = OFF;\n CREATE TABLE meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n CREATE TABLE nodes (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL,\n kind TEXT NOT NULL,\n file TEXT NOT NULL,\n line INTEGER NOT NULL,\n importance REAL NOT NULL,\n area INTEGER NOT NULL,\n is_hub INTEGER NOT NULL,\n lang TEXT NOT NULL,\n json TEXT NOT NULL\n );\n CREATE TABLE edges (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL,\n src TEXT NOT NULL,\n dst TEXT NOT NULL,\n resolution TEXT NOT NULL,\n confidence REAL NOT NULL,\n epistemic TEXT NOT NULL,\n json TEXT NOT NULL\n );\n CREATE TABLE areas (\n id INTEGER PRIMARY KEY,\n json TEXT NOT NULL\n );\n CREATE INDEX idx_nodes_name ON nodes(name);\n CREATE INDEX idx_nodes_qn ON nodes(qualified_name);\n CREATE INDEX idx_nodes_file ON nodes(file);\n CREATE INDEX idx_edges_src ON edges(src);\n CREATE INDEX idx_edges_dst ON edges(dst);\n CREATE INDEX idx_edges_kind ON edges(kind);\n `);\n\n const insMeta = db.prepare('INSERT INTO meta(key, value) VALUES (?, ?)');\n insMeta.run('corpusHash', graph.provenance.corpusHash);\n insMeta.run('schemaVersion', graph.schemaVersion);\n insMeta.run('generatedAt', graph.generatedAt);\n insMeta.run('nodeCount', String(graph.nodes.length));\n insMeta.run('edgeCount', String(graph.edges.length));\n insMeta.run('analysisTier', graph.meta.analysisTier ?? 'full');\n insMeta.run('indexVersion', 'vg-graph-index/2');\n // Full meta + provenance for reconstruct without graph.json parse.\n insMeta.run('graphMeta', JSON.stringify(graph.meta));\n insMeta.run('graphProvenance', JSON.stringify(graph.provenance));\n if (graph.facts) insMeta.run('factsJson', JSON.stringify(graph.facts));\n if (graph.grounding) insMeta.run('groundingJson', JSON.stringify(graph.grounding));\n if (graph.summaries) insMeta.run('summariesJson', JSON.stringify(graph.summaries));\n if (graph.unknowns) insMeta.run('unknownsJson', JSON.stringify(graph.unknowns));\n\n const insNode = db.prepare(\n `INSERT INTO nodes(id, name, qualified_name, kind, file, line, importance, area, is_hub, lang, json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const n of graph.nodes) {\n insNode.run(\n n.id,\n n.name,\n n.qualifiedName,\n n.kind,\n n.file,\n n.span.start,\n n.importance,\n n.area,\n n.isHub ? 1 : 0,\n n.lang,\n JSON.stringify(n),\n );\n }\n\n const insEdge = db.prepare(\n `INSERT INTO edges(id, kind, src, dst, resolution, confidence, epistemic, json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const e of graph.edges) {\n insEdge.run(\n e.id,\n e.kind,\n e.src,\n e.dst,\n e.resolution,\n e.confidence,\n e.epistemic ?? 'observed',\n JSON.stringify(e),\n );\n }\n\n const insArea = db.prepare('INSERT INTO areas(id, json) VALUES (?, ?)');\n for (const a of graph.areas) {\n insArea.run(a.id, JSON.stringify(a));\n }\n\n db.close();\n fs.renameSync(tmp, file);\n return { path: file, nodes: graph.nodes.length, edges: graph.edges.length, ok: true };\n } catch (err) {\n return {\n path: file,\n nodes: 0,\n edges: 0,\n ok: false,\n reason: (err as Error).message,\n };\n }\n}\n\nexport interface NameHit {\n id: string;\n name: string;\n qualifiedName: string;\n kind: string;\n file: string;\n line: number;\n importance: number;\n}\n\n/** Fast name / prefix lookup against the index. Empty if index missing. */\nexport function lookupNameIndex(root: string, query: string, limit = 20): NameHit[] {\n const file = indexDbPath(root);\n if (!fs.existsSync(file) || !query.trim()) return [];\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const q = query.trim();\n const rows = db\n .prepare(\n `SELECT id, name, qualified_name, kind, file, line, importance\n FROM nodes\n WHERE name = ? OR qualified_name = ? OR name LIKE ? OR qualified_name LIKE ?\n ORDER BY\n CASE WHEN name = ? OR qualified_name = ? THEN 0\n WHEN name LIKE ? THEN 1\n ELSE 2 END,\n importance DESC\n LIMIT ?`,\n )\n .all(q, q, `${q}%`, `%${q}%`, q, q, `${q}%`, limit) as Record<string, unknown>[];\n db.close();\n return rows.map((r) => ({\n id: String(r.id),\n name: String(r.name),\n qualifiedName: String(r.qualified_name),\n kind: String(r.kind),\n file: String(r.file),\n line: Number(r.line),\n importance: Number(r.importance),\n }));\n } catch {\n return [];\n }\n}\n\n/** Neighbor edges for a node id (src or dst). Empty if index missing. */\nexport function lookupNeighbors(\n root: string,\n nodeId: string,\n direction: 'out' | 'in' | 'both' = 'both',\n limit = 50,\n): GraphEdge[] {\n const file = indexDbPath(root);\n if (!fs.existsSync(file) || !nodeId) return [];\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n let rows: Record<string, unknown>[] = [];\n if (direction === 'out' || direction === 'both') {\n rows = rows.concat(\n db\n .prepare(`SELECT json FROM edges WHERE src = ? LIMIT ?`)\n .all(nodeId, limit) as Record<string, unknown>[],\n );\n }\n if (direction === 'in' || direction === 'both') {\n rows = rows.concat(\n db\n .prepare(`SELECT json FROM edges WHERE dst = ? LIMIT ?`)\n .all(nodeId, limit) as Record<string, unknown>[],\n );\n }\n db.close();\n const byId = new Map<string, GraphEdge>();\n for (const r of rows) {\n try {\n const e = JSON.parse(String(r.json)) as GraphEdge;\n byId.set(e.id, e);\n } catch {\n /* skip bad row */\n }\n }\n return [...byId.values()];\n } catch {\n return [];\n }\n}\n\n/** Read index meta (corpusHash etc.) or null if missing. */\nexport function readIndexMeta(root: string): Record<string, string> | null {\n const file = indexDbPath(root);\n if (!fs.existsSync(file)) return null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const rows = db.prepare('SELECT key, value FROM meta').all() as { key: string; value: string }[];\n db.close();\n const out: Record<string, string> = {};\n for (const r of rows) out[r.key] = r.value;\n return out;\n } catch {\n return null;\n }\n}\n\n/**\n * Reconstruct a full `VgGraph` from the SQLite index (indexVersion ≥ 2).\n * Returns null if the index is missing, stale schema, or incomplete.\n * Prefer this over JSON.parse of pretty graph.json for cold serve on large maps.\n */\nexport function loadGraphFromIndex(root: string): VgGraph | null {\n const file = indexDbPath(root);\n if (!fs.existsSync(file)) return null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const metaRows = db.prepare('SELECT key, value FROM meta').all() as {\n key: string;\n value: string;\n }[];\n const meta: Record<string, string> = {};\n for (const r of metaRows) meta[r.key] = r.value;\n\n if (meta.indexVersion !== 'vg-graph-index/2' || !meta.graphMeta || !meta.graphProvenance) {\n db.close();\n return null;\n }\n\n const nodeRows = db.prepare('SELECT json FROM nodes ORDER BY id').all() as {\n json: string;\n }[];\n const edgeRows = db.prepare('SELECT json FROM edges ORDER BY id').all() as {\n json: string;\n }[];\n const areaRows = db.prepare('SELECT json FROM areas ORDER BY id').all() as {\n json: string;\n }[];\n db.close();\n\n const nodes = nodeRows.map((r) => JSON.parse(r.json) as GraphNode);\n const edges = edgeRows.map((r) => JSON.parse(r.json) as GraphEdge);\n const areas = areaRows.map((r) => JSON.parse(r.json) as Area);\n\n // Stable sorts match serialize contract (ids already ordered by SQL, re-sort for safety).\n nodes.sort((a, b) => a.id.localeCompare(b.id));\n edges.sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n areas.sort((a, b) => a.id - b.id);\n\n const graph: VgGraph = {\n schemaVersion: (meta.schemaVersion as typeof SCHEMA_VERSION) || SCHEMA_VERSION,\n generatedAt: meta.generatedAt ?? new Date(0).toISOString(),\n provenance: JSON.parse(meta.graphProvenance),\n meta: JSON.parse(meta.graphMeta),\n nodes,\n edges,\n areas,\n };\n if (meta.factsJson) graph.facts = JSON.parse(meta.factsJson);\n if (meta.groundingJson) graph.grounding = JSON.parse(meta.groundingJson);\n if (meta.summariesJson) graph.summaries = JSON.parse(meta.summariesJson);\n if (meta.unknownsJson) graph.unknowns = JSON.parse(meta.unknownsJson);\n\n // Lightweight integrity: edge resolution types stay valid.\n for (const e of edges) {\n if (!e.resolution) e.resolution = 'heuristic' as ResolverKind;\n if (!e.epistemic) e.epistemic = 'observed' as EpistemicTier;\n }\n return graph;\n } catch {\n return null;\n }\n}\n\n/**\n * Load the graph preferring the SQLite index when its corpusHash matches the\n * committed graph.json provenance (or when only the index exists). Falls back\n * to graph.json. Returns null if neither is usable.\n */\nexport function loadGraphPreferIndex(\n root: string,\n graphJsonPath: string,\n): { graph: VgGraph; source: 'index' | 'json' } | null {\n // Snapshot-first: skips the large-string JSON.parse when a fresh binary\n // snapshot exists (sidecar or store-mode standalone), and self-heals the\n // sidecar when not (see engine/snapshot.ts).\n const jsonGraph: VgGraph | null = loadGraphFileWithSnapshot(graphJsonPath);\n\n const fromIndex = loadGraphFromIndex(root);\n if (fromIndex) {\n if (!jsonGraph || fromIndex.provenance.corpusHash === jsonGraph.provenance.corpusHash) {\n return { graph: fromIndex, source: 'index' };\n }\n // Index stale vs graph.json — prefer canonical JSON and let next build refresh.\n }\n if (jsonGraph) return { graph: jsonGraph, source: 'json' };\n return null;\n}\n","import * as fs from 'node:fs';\nimport { resolveGraphPath } from './artifacts.js';\nimport { loadGraphFileWithSnapshot } from './snapshot.js';\nimport { loadGraphPreferIndex } from './index-db.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * Load the code map for a repository.\n *\n * When `graphPath` is omitted, prefers an existing global-store snapshot, then\n * the legacy `.vibgrate/graph.json`, matching {@link resolveGraphPath}.\n * Prefers the SQLite index when its corpusHash matches the committed map\n * (faster cold serve on large repos). Returns null if none exists.\n */\nexport function loadGraph(root: string, graphPath?: string): VgGraph | null {\n const file = resolveGraphPath(root, graphPath);\n // Index is always rooted at the project root; only use it when loading the\n // default map for that root (not an arbitrary --graph path).\n if (!graphPath) {\n const preferred = loadGraphPreferIndex(root, file);\n if (preferred) return preferred.graph;\n }\n return loadGraphFileWithSnapshot(file);\n}\n"]}
|