@vibgrate/cli 2026.818.1 → 2026.818.2
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-CUK24AWF.js → agent-X6VYCE63.js} +13 -13
- package/dist/{agent-CUK24AWF.js.map → agent-X6VYCE63.js.map} +1 -1
- package/dist/{approvals-YFOU6GVB.js → approvals-TPQFQSWG.js} +5 -5
- package/dist/{approvals-YFOU6GVB.js.map → approvals-TPQFQSWG.js.map} +1 -1
- package/dist/attach-G5JUIWIT.js +10 -0
- package/dist/{attach-6S3XS7VO.js.map → attach-G5JUIWIT.js.map} +1 -1
- package/dist/{baseline-OBZJRCCP.js → baseline-DXI64VLW.js} +3 -3
- package/dist/{baseline-OBZJRCCP.js.map → baseline-DXI64VLW.js.map} +1 -1
- package/dist/{chunk-WVTGF2MP.js → chunk-2C33WR5O.js} +3 -3
- package/dist/{chunk-WVTGF2MP.js.map → chunk-2C33WR5O.js.map} +1 -1
- package/dist/chunk-4NTNMT6T.js +6 -0
- package/dist/{chunk-SUD54UGN.js.map → chunk-4NTNMT6T.js.map} +1 -1
- package/dist/chunk-5IQBIXHS.js +23 -0
- package/dist/chunk-5IQBIXHS.js.map +1 -0
- package/dist/{chunk-43ESHUM5.js → chunk-6PFHDHOL.js} +8 -8
- package/dist/{chunk-43ESHUM5.js.map → chunk-6PFHDHOL.js.map} +1 -1
- package/dist/{chunk-LHQYYBCH.js → chunk-AEJYA6HZ.js} +5 -5
- package/dist/{chunk-LHQYYBCH.js.map → chunk-AEJYA6HZ.js.map} +1 -1
- package/dist/{chunk-J7CVFTLG.js → chunk-B4EXD5LK.js} +5 -5
- package/dist/{chunk-J7CVFTLG.js.map → chunk-B4EXD5LK.js.map} +1 -1
- package/dist/{chunk-E7RVA2ZI.js → chunk-BMOFJIMG.js} +3 -3
- package/dist/{chunk-E7RVA2ZI.js.map → chunk-BMOFJIMG.js.map} +1 -1
- package/dist/{chunk-ZWFMJUXC.js → chunk-E3O5UKNA.js} +7 -7
- package/dist/{chunk-ZWFMJUXC.js.map → chunk-E3O5UKNA.js.map} +1 -1
- package/dist/{chunk-NO4BMW7M.js → chunk-E53WBVUQ.js} +6 -3
- package/dist/chunk-E53WBVUQ.js.map +1 -0
- package/dist/{chunk-FFYO7G3T.js → chunk-FFXGWFAE.js} +3 -3
- package/dist/{chunk-FFYO7G3T.js.map → chunk-FFXGWFAE.js.map} +1 -1
- package/dist/{chunk-H6RV2OAX.js → chunk-HF6R73UC.js} +78 -10
- package/dist/chunk-HF6R73UC.js.map +1 -0
- package/dist/{chunk-4QAMUBAC.js → chunk-JGA63RGF.js} +11 -11
- package/dist/{chunk-4QAMUBAC.js.map → chunk-JGA63RGF.js.map} +1 -1
- package/dist/{chunk-SBHK4ECM.js → chunk-KU7FI5EV.js} +3 -3
- package/dist/{chunk-SBHK4ECM.js.map → chunk-KU7FI5EV.js.map} +1 -1
- package/dist/{chunk-DM6MJ7IF.js → chunk-L2OS4WHT.js} +4 -4
- package/dist/{chunk-DM6MJ7IF.js.map → chunk-L2OS4WHT.js.map} +1 -1
- package/dist/chunk-LJSJX6U4.js +38 -0
- package/dist/chunk-LJSJX6U4.js.map +1 -0
- package/dist/{chunk-DUCEKH7Q.js → chunk-MRZHNUN7.js} +4 -4
- package/dist/{chunk-DUCEKH7Q.js.map → chunk-MRZHNUN7.js.map} +1 -1
- package/dist/{chunk-G7ZFSH5J.js → chunk-NJQZRM55.js} +6 -38
- package/dist/chunk-NJQZRM55.js.map +1 -0
- package/dist/{chunk-OS4YFOFJ.js → chunk-NKLYDSB7.js} +7 -7
- package/dist/{chunk-OS4YFOFJ.js.map → chunk-NKLYDSB7.js.map} +1 -1
- package/dist/{chunk-X4DECFUG.js → chunk-O5IJDMTB.js} +4 -4
- package/dist/{chunk-X4DECFUG.js.map → chunk-O5IJDMTB.js.map} +1 -1
- package/dist/{chunk-J3A3O4IA.js → chunk-PRHH4DVO.js} +3 -3
- package/dist/{chunk-J3A3O4IA.js.map → chunk-PRHH4DVO.js.map} +1 -1
- package/dist/{chunk-OVUZWR67.js → chunk-RHKOUPWT.js} +3 -3
- package/dist/{chunk-OVUZWR67.js.map → chunk-RHKOUPWT.js.map} +1 -1
- package/dist/{chunk-I3PKYYRP.js → chunk-V6WONSIK.js} +4 -4
- package/dist/{chunk-I3PKYYRP.js.map → chunk-V6WONSIK.js.map} +1 -1
- package/dist/{chunk-Q7TWHJJ6.js → chunk-VMAIDM4K.js} +3 -3
- package/dist/{chunk-Q7TWHJJ6.js.map → chunk-VMAIDM4K.js.map} +1 -1
- package/dist/{chunk-MHJBIGWV.js → chunk-VQ5KMHW6.js} +117 -23
- package/dist/chunk-VQ5KMHW6.js.map +1 -0
- package/dist/{chunk-GKZU6MII.js → chunk-X2MQ7UFL.js} +109 -23
- package/dist/chunk-X2MQ7UFL.js.map +1 -0
- package/dist/{chunk-6LY3JH6S.js → chunk-YF54UMOU.js} +3 -3
- package/dist/{chunk-6LY3JH6S.js.map → chunk-YF54UMOU.js.map} +1 -1
- package/dist/{chunk-DH6EDSQP.js → chunk-ZUOBPKVK.js} +3 -3
- package/dist/{chunk-DH6EDSQP.js.map → chunk-ZUOBPKVK.js.map} +1 -1
- package/dist/cli.js +234 -108
- package/dist/cli.js.map +1 -1
- package/dist/client-UQIELEEZ.js +8 -0
- package/dist/client-UQIELEEZ.js.map +1 -0
- package/dist/{daemon-4Q5QBBAF.js → daemon-GUMWMKCA.js} +11 -11
- package/dist/{daemon-4Q5QBBAF.js.map → daemon-GUMWMKCA.js.map} +1 -1
- package/dist/embed-worker-main.js +3 -3
- package/dist/{ensure-map-B2PS5ALS.js → ensure-map-FHDJTO7Y.js} +20 -19
- package/dist/{ensure-map-B2PS5ALS.js.map → ensure-map-FHDJTO7Y.js.map} +1 -1
- package/dist/{graph-backend-EEXMD6XY.js → graph-backend-W2D3HRRD.js} +8 -8
- package/dist/{graph-backend-EEXMD6XY.js.map → graph-backend-W2D3HRRD.js.map} +1 -1
- package/dist/index.d.ts +29 -2
- package/dist/index.js +20 -18
- package/dist/index.js.map +1 -1
- package/dist/{interactive-KEPGE5HD.js → interactive-2MK4TLRD.js} +32 -31
- package/dist/interactive-2MK4TLRD.js.map +1 -0
- package/dist/load-4R4HYMBB.js +11 -0
- package/dist/{load-H5HAME25.js.map → load-4R4HYMBB.js.map} +1 -1
- package/dist/parse-worker.js +2 -2
- package/dist/publish-7YHRTBRA.js +9 -0
- package/dist/publish-7YHRTBRA.js.map +1 -0
- package/dist/{run-outcome-V3L4GAN4.js → run-outcome-H5GVDDZJ.js} +5 -5
- package/dist/{run-outcome-V3L4GAN4.js.map → run-outcome-H5GVDDZJ.js.map} +1 -1
- package/dist/{runtime-session-M2FRGTDS.js → runtime-session-JBIHHH5N.js} +11 -11
- package/dist/{runtime-session-M2FRGTDS.js.map → runtime-session-JBIHHH5N.js.map} +1 -1
- package/dist/semantic-status-2JFLIQQJ.js +4 -0
- package/dist/semantic-status-2JFLIQQJ.js.map +1 -0
- package/dist/{session-77YXFUC7.js → session-N5IU4K5Q.js} +8 -8
- package/dist/{session-77YXFUC7.js.map → session-N5IU4K5Q.js.map} +1 -1
- package/dist/{stream-json-S6E3W2US.js → stream-json-4WLSUF6I.js} +13 -13
- package/dist/{stream-json-S6E3W2US.js.map → stream-json-4WLSUF6I.js.map} +1 -1
- package/dist/version-DTEU3SQD.js +4 -0
- package/dist/{version-VRZT5G4T.js.map → version-DTEU3SQD.js.map} +1 -1
- package/dist/{vg-mcp-bridge-HCPJWJKJ.js → vg-mcp-bridge-KDVYIMFX.js} +9 -9
- package/dist/{vg-mcp-bridge-HCPJWJKJ.js.map → vg-mcp-bridge-KDVYIMFX.js.map} +1 -1
- package/dist/{vgd-R2PNIDEP.js → vgd-M7UOPWLB.js} +10 -10
- package/dist/vgd-M7UOPWLB.js.map +1 -0
- package/package.json +1 -1
- package/dist/attach-6S3XS7VO.js +0 -9
- package/dist/chunk-G7ZFSH5J.js.map +0 -1
- package/dist/chunk-GKZU6MII.js.map +0 -1
- package/dist/chunk-H6RV2OAX.js.map +0 -1
- package/dist/chunk-MHJBIGWV.js.map +0 -1
- package/dist/chunk-NO4BMW7M.js.map +0 -1
- package/dist/chunk-SUD54UGN.js +0 -6
- package/dist/interactive-KEPGE5HD.js.map +0 -1
- package/dist/load-H5HAME25.js +0 -11
- package/dist/version-VRZT5G4T.js +0 -4
- package/dist/vgd-R2PNIDEP.js.map +0 -1
package/dist/attach-6S3XS7VO.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
export { attachVgd, daemonDisabledReason } from './chunk-G7ZFSH5J.js';
|
|
2
|
-
import './chunk-NO4BMW7M.js';
|
|
3
|
-
import './chunk-NDNNOAS6.js';
|
|
4
|
-
import './chunk-BWPBB45M.js';
|
|
5
|
-
import './chunk-JFGYT6BI.js';
|
|
6
|
-
import './chunk-BPF3YX2U.js';
|
|
7
|
-
import './chunk-Z6ZWNWWR.js';
|
|
8
|
-
//# sourceMappingURL=attach-6S3XS7VO.js.map
|
|
9
|
-
//# sourceMappingURL=attach-6S3XS7VO.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/vgd/publish.ts","../src/runtime/vgd/attach.ts"],"names":[],"mappings":";;;;AA2CA,eAAsB,iBAAA,CAAkB,IAAA,EAAc,OAAA,GAA6B,EAAC,EAA+B;AACjH,EAAA,MAAM,EAAE,YAAW,GAAI,OAAA;AACvB,EAAA,MAAM,SAAA,GAAY,QAAQ,SAAA,IAAa,YAAA;AACvC,EAAA,MAAM,OAAA,GAAU,QAAQ,OAAA,IAAW,UAAA;AACnC,EAAA,IAAI;AACF,IAAA,IAAI,CAAE,MAAM,SAAA,CAAU,EAAE,UAAA,EAAY,CAAA,EAAI,OAAO,EAAE,MAAA,EAAQ,aAAA,EAAc;AAEvE,IAAA,MAAM,SAAS,MAAM,OAAA;AAAA,MACnB,EAAE,IAAI,YAAA,EAAc,IAAA,EAAM,QAAQ,OAAA,CAAQ,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,EAAc,GAAA,CAAI,SAAA,CAAU,EAAA,EAAG,EAAG,EAAE,YAAY,CAAA;AACrG,EAAA,IAAI,CAAC,OAAA,CAAQ,EAAA,IAAM,EAAE,SAAA,IAAa,UAAU,OAAO,IAAA;AACnD,EAAA,OAAO,EAAE,YAAA,EAAc,GAAA,CAAI,SAAA,CAAU,EAAA,EAAI,MAAA,EAAQ,OAAA,CAAQ,MAAA,EAAQ,UAAA,EAAY,OAAA,CAAQ,OAAA,CAAQ,UAAA,EAAW;AAC1G;AAEA,eAAe,aAAA,GAAyH;AAGtI,EAAA,MAAM,EAAE,aAAA,EAAc,GAAI,MAAM,OAAO,sBAA0B,CAAA;AACjE,EAAA,OAAO,CAAC,UAAA,EAAY,aAAA,KAAkB,aAAA,CAAc,YAAY,aAAa,CAAA;AAC/E","file":"chunk-G7ZFSH5J.js","sourcesContent":["import { vgdIsRunning, vgdRequest } from './client.js';\n\nexport type VgdPublishOutcome =\n | { status: 'not-running' }\n | { status: 'failed'; error: string }\n /** The daemon already holds this exact map — nothing was sent. */\n | { status: 'current'; repositoryId: string; gitRef: string }\n | { status: 'published'; repositoryId: string; gitRef: string; nodeCount: number; semantic?: string };\n\nexport interface VgdPublishOptions {\n /** Override socket path (tests). */\n socketPath?: string;\n /** Branch / detached SHA this map describes; the daemon detects it otherwise. */\n gitRef?: string;\n /** Custom `--graph` artifact, when the map is not at its default location. */\n graphPath?: string;\n /**\n * Also wait for the slot's semantic index. Off by default: publishing already\n * queues a background warm, and a build should not block on embedding.\n */\n warmSemantic?: boolean;\n /** Injected transport (tests). */\n isRunning?: typeof vgdIsRunning;\n request?: typeof vgdRequest;\n}\n\n/**\n * Hand a freshly-built code map to a vgd that is **already** running.\n *\n * Without this the daemon only ever learned about a repo through `vg code`, so\n * an ordinary `vg build` left it reporting `0 graph slot(s)` — and because the\n * semantic index hangs off the graph slot, the index never warmed either. The\n * daemon looked idle on a machine that had just spent ten seconds building the\n * very map it was supposed to be holding.\n *\n * `load-graph` rather than `put-graph`: the daemon reads the snapshot from\n * disk itself (binary sidecar when fresh), so a 40k-node map never crosses the\n * socket as one multi-MB JSON line. Storing it runs the registry's slot funnel,\n * which invalidates and re-warms the semantic index for exactly that slot.\n *\n * Never starts a daemon, never throws, and never changes the command's exit\n * status: a machine with no vgd is a supported configuration, not an error.\n */\nexport async function publishGraphToVgd(root: string, options: VgdPublishOptions = {}): Promise<VgdPublishOutcome> {\n const { socketPath } = options;\n const isRunning = options.isRunning ?? vgdIsRunning;\n const request = options.request ?? vgdRequest;\n try {\n if (!(await isRunning({ socketPath }))) return { status: 'not-running' };\n\n const loaded = await request(\n { op: 'load-graph', root, gitRef: options.gitRef, graphPath: options.graphPath },\n { socketPath },\n );\n if (!loaded.ok) return { status: 'failed', error: loaded.error };\n if (!('stored' in loaded)) return { status: 'failed', error: 'vgd did not store the map' };\n\n let semantic: string | undefined;\n if (options.warmSemantic) {\n const indexed = await request(\n { op: 'embed-index', repositoryId: loaded.repositoryId, gitRef: loaded.gitRef },\n { socketPath },\n ).catch((e: unknown) => ({ ok: false as const, error: e instanceof Error ? e.message : String(e) }));\n if (indexed.ok && 'state' in indexed) semantic = indexed.state;\n }\n return {\n status: 'published',\n repositoryId: loaded.repositoryId,\n gitRef: loaded.gitRef,\n nodeCount: loaded.nodeCount,\n semantic,\n };\n } catch (e) {\n return { status: 'failed', error: e instanceof Error ? e.message : String(e) };\n }\n}\n","import { vgdIsRunning, vgdRequest } from './client.js';\nimport { vgdSocketPath } from './paths.js';\nimport { publishGraphToVgd, type VgdPublishOutcome } from './publish.js';\n\n/**\n * The one way an ordinary command joins the local runtime.\n *\n * Until now vgd only ever existed because `vg code` or the VS Code extension\n * started it, so a developer running `vg`, `vg build` and `vg ask` all day\n * never had a runtime at all — every invocation re-read the map and re-loaded\n * the embedder from cold. Auto-start makes the daemon the normal case, and\n * publishing on attach makes it hold the thing it is supposed to accelerate.\n *\n * Three rules keep this safe to put in front of every command:\n *\n * - **Never blocking.** `ensureVgdSoft` spawns and waits ~1.5s, not the 30s\n * `vg daemon ensure` waits. A daemon that is still coming up simply is not\n * used this time; the command runs its in-process path and finds a warm\n * runtime on the next call.\n * - **Never fatal.** Every outcome is a value, never a throw. \"No daemon\" is a\n * supported configuration, and it must stay one — the fallbacks are the\n * code paths that exist today.\n * - **Always escapable.** `--no-daemon`, `VG_NO_DAEMON=1`, and `CI` all turn\n * auto-start off. A one-shot CI job should not leave a background process\n * behind, and a user who does not want one must be able to say so once.\n */\n\nexport type AttachStatus = 'attached' | 'disabled' | 'unavailable';\n\nexport interface AttachResult {\n status: AttachStatus;\n /** Why, when not attached — safe to show verbatim. */\n reason?: string;\n /** True when this call is what started the daemon. */\n started?: boolean;\n socketPath?: string;\n repositoryId?: string;\n gitRef?: string;\n /** Outcome of the map publish, when one was requested. */\n published?: VgdPublishOutcome;\n}\n\nexport interface AttachOptions {\n socketPath?: string;\n /** Spawn a daemon when none is listening (default true). */\n autoStart?: boolean;\n /** How long to wait for a just-spawned daemon before giving up (default 1500ms). */\n readyBudgetMs?: number;\n /** Publish this repo's map after attaching (default true). */\n publish?: boolean;\n /**\n * The corpus hash of the map the caller already holds. When the daemon's\n * slot reports the same hash the publish is skipped entirely.\n *\n * This matters more than it looks: `load-graph` runs the registry's slot\n * funnel, and `onGraphPut` deliberately drops the slot's vectors — so\n * re-publishing an unchanged map on every `vg ask` invalidated and re-seeded\n * the semantic index once per command, for nothing.\n */\n corpusHash?: string;\n /** Also wait for the slot's semantic index (default false — warming is background work). */\n warmSemantic?: boolean;\n gitRef?: string;\n /** Custom `--graph` artifact path. */\n graphPath?: string;\n /** Explicit opt-out from the caller's parsed flags (`--no-daemon`). */\n disabled?: boolean;\n /** Injected (tests). */\n isRunning?: typeof vgdIsRunning;\n request?: typeof vgdRequest;\n ensure?: (socketPath: string, readyBudgetMs: number) => Promise<{ running: boolean; started: boolean }>;\n env?: NodeJS.ProcessEnv;\n}\n\nfunction truthy(value: string | undefined): boolean {\n if (!value) return false;\n const v = value.trim().toLowerCase();\n return v !== '' && v !== '0' && v !== 'false' && v !== 'no';\n}\n\n/**\n * Why auto-start is off, or null when it is on. Exposed so `vg doctor` can\n * explain a missing daemon instead of leaving the user to guess.\n */\nexport function daemonDisabledReason(\n options: { disabled?: boolean; env?: NodeJS.ProcessEnv } = {},\n): string | null {\n const env = options.env ?? process.env;\n if (options.disabled) return 'disabled by --no-daemon';\n if (truthy(env.VG_NO_DAEMON) || truthy(env.VIBGRATE_NO_DAEMON)) return 'disabled by VG_NO_DAEMON';\n // A CI job is one-shot by definition: starting a background daemon there\n // costs a cold start and leaves a process behind for no second call.\n if (truthy(env.CI)) return 'skipped in CI';\n return null;\n}\n\n/**\n * Ensure a local vgd is running and knows about this repository's map.\n * Resolves to a description of what happened; never throws.\n */\nexport async function attachVgd(root: string, options: AttachOptions = {}): Promise<AttachResult> {\n const disabled = daemonDisabledReason(options);\n if (disabled) return { status: 'disabled', reason: disabled };\n\n const socketPath = options.socketPath ?? vgdSocketPath();\n const isRunning = options.isRunning ?? vgdIsRunning;\n const readyBudgetMs = options.readyBudgetMs ?? 1500;\n\n try {\n let running = await isRunning({ socketPath });\n let started = false;\n if (!running && options.autoStart !== false) {\n const ensure = options.ensure ?? (await defaultEnsure());\n const r = await ensure(socketPath, readyBudgetMs);\n running = r.running;\n started = r.started;\n }\n if (!running) {\n return {\n status: 'unavailable',\n reason: started ? 'vgd is still starting — this run uses the in-process path' : 'no vgd is running',\n started,\n socketPath,\n };\n }\n\n const request = options.request ?? vgdRequest;\n\n // Register even when not publishing: \"attached\" should always mean the\n // caller knows which slot it is talking to, or `embed-rank` has no target.\n if (options.publish === false) {\n const reg = await request({ op: 'register', root }, { socketPath });\n const workspace = reg.ok && 'workspace' in reg ? reg.workspace : undefined;\n return {\n status: 'attached',\n started,\n socketPath,\n repositoryId: workspace?.id,\n gitRef: workspace?.gitRef,\n };\n }\n\n // Already current? Then registering is all this call needs to do.\n if (options.corpusHash) {\n const current = await currentSlot(root, socketPath, request);\n if (current && current.corpusHash === options.corpusHash) {\n return {\n status: 'attached',\n started,\n socketPath,\n repositoryId: current.repositoryId,\n gitRef: current.gitRef,\n published: { status: 'current', repositoryId: current.repositoryId, gitRef: current.gitRef },\n };\n }\n }\n\n const published = await publishGraphToVgd(root, {\n socketPath,\n gitRef: options.gitRef,\n graphPath: options.graphPath,\n warmSemantic: options.warmSemantic,\n isRunning: () => Promise.resolve(true),\n request: options.request,\n });\n return {\n status: 'attached',\n started,\n socketPath,\n repositoryId: published.status === 'published' ? published.repositoryId : undefined,\n gitRef: published.status === 'published' ? published.gitRef : undefined,\n published,\n };\n } catch (e) {\n return { status: 'unavailable', reason: e instanceof Error ? e.message : String(e), socketPath };\n }\n}\n\n/**\n * Register the workspace and ask what the daemon already holds for it.\n * Returns null when there is no slot yet (the common first-run case).\n */\nasync function currentSlot(\n root: string,\n socketPath: string,\n request: typeof vgdRequest,\n): Promise<{ repositoryId: string; gitRef: string; corpusHash: string | null } | null> {\n const reg = await request({ op: 'register', root }, { socketPath });\n if (!reg.ok || !('workspace' in reg)) return null;\n const summary = await request({ op: 'graph-summary', repositoryId: reg.workspace.id }, { socketPath });\n if (!summary.ok || !('summary' in summary)) return null;\n return { repositoryId: reg.workspace.id, gitRef: summary.gitRef, corpusHash: summary.summary.corpusHash };\n}\n\nasync function defaultEnsure(): Promise<(socketPath: string, readyBudgetMs: number) => Promise<{ running: boolean; started: boolean }>> {\n // Imported lazily: `commands/daemon.ts` pulls in commander and the whole\n // daemon command surface, which no fast path should pay for up front.\n const { ensureVgdSoft } = await import('../../commands/daemon.js');\n return (socketPath, readyBudgetMs) => ensureVgdSoft(socketPath, readyBudgetMs);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine/refresh-scheduler.ts","../src/runtime/vgd/semantic-client.ts","../src/mcp/server.ts","../src/engine/export.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAkCO,IAAM,iBAAA,GAAoB,GAAA;AAE1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I,IAAA;AACxC;AAEA,SAAS,KAAK,GAAA,EAA4B;AACxC,EAAA,MAAM,YAAY,GAAA,CAAI,IAAA,IAAQ,EAAC,EAAG,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,IAC5C,MAAA,EAAQ,CAAA,gBAAA,EAAmB,WAAA,CAAY,CAAA,CAAE,IAAI,CAAC,CAAA,CAAA;AAAA,IAC9C,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,WAAA,EAAa,CAAA,CAAE,SAAA,IAAa,CAAA,CAAE,QAAA;AAAA,IAC9B,gBAAA,EAAkB;AAAA,GACpB,CAAE,CAAA;AACF,EAAA,MAAM,GAAA,GAAM;AAAA,IACV,WAAA,EAAa,UAAA;AAAA,IACb,WAAA,EAAa,SAAA;AAAA,IACb,MAAA,EAAQ,kBAAA;AAAA,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-GKZU6MII.js","sourcesContent":["import { refreshIfStale, type RefreshOutcome } from './refresh.js';\n\n/**\n * Debounced, single-flight, budget-capped auto-refresh.\n *\n * `refreshIfStale` is expensive and **synchronous in its hot half**: the\n * freshness probe walks the whole corpus (`discover` + `discoverDocs`) and\n * `statSync`s every file before anything can drift-check, and a real drift then\n * runs a full incremental `buildGraph`. On a 22k-file repo that is seconds for a\n * clean tree and over a minute for a dirty one.\n *\n * No interactive surface may pay that inline. This scheduler is the shared\n * discipline that keeps it off the request path, and it exists as one module\n * precisely because the previous per-server copies diverged: `vg serve` (MCP)\n * grew the guard while `vg lsp` kept a bare `await refreshIfStale(...)`, which\n * made a single editor Ask block for ~90s on a large workspace.\n *\n * Four properties, all load-bearing:\n * - **Single-flight** — concurrent callers share one refresh, never stack.\n * - **Debounced** — at most one probe per `probeIntervalMs`.\n * - **Self-tuning** — the interval grows with the *measured* cost of the last\n * refresh, so probe/rebuild work stays under ~1/`PROBE_DUTY_FACTOR` of wall\n * time however big the repo is.\n * - **Budget-capped** — a caller waits `refreshBudgetMs` at most, then proceeds\n * with the map it already has. A warm probe lands inside the budget; a\n * rebuild never does, and shouldn't.\n *\n * Answering from a map that is one edit stale is always better than making the\n * user wait: the rebuild lands for the next call.\n */\n\nexport type RefreshImpl = typeof refreshIfStale;\n\n/** Min gap between freshness probes — bounds stat-walk cost under bursty calls. */\nexport const PROBE_INTERVAL_MS = 2000;\n/** Ceiling for the self-tuned probe interval on very large repos. */\nexport const MAX_PROBE_INTERVAL_MS = 30_000;\n/** Probe/rebuild may consume at most ~1/PROBE_DUTY_FACTOR of wall-time (20 → ≤5%). */\nexport const PROBE_DUTY_FACTOR = 20;\n/**\n * How long a caller waits for an in-flight refresh before answering from the\n * current map. Deliberately small: warm lookups are sub-10ms, so a multi-second\n * budget turns every call during a large-repo rebuild into a multi-second stall.\n */\nexport const REFRESH_BUDGET_MS = 100;\n/** After a refresh failure (e.g. read-only checkout), don't retry for this long. */\nexport const FAILURE_COOLDOWN_MS = 60_000;\n\nexport interface RefreshSchedulerOptions {\n /** Workspace root for freshness probes and rebuilds. */\n root: string;\n /**\n * The already-resolved map path, or a getter for it. Passing it through spares\n * `refreshIfStale` a `defaultGraphPath` re-resolution (which consults git).\n */\n graphPath?: string | (() => string | undefined);\n /** Min gap between probes. `0` probes every call (tests). */\n probeIntervalMs?: number;\n /** Max wait before a caller gives up and uses the current map. */\n refreshBudgetMs?: number;\n /** Tests only: inject a slow/fake refresh to assert the micro-budget. */\n refreshImpl?: RefreshImpl;\n /** Force single-threaded parsing on a rebuild (constrained hosts / tests). */\n inline?: boolean;\n /**\n * Called when a refresh settles, with the outcome (`null` if it threw) and the\n * ms timestamp the refresh started at. Lets an owner react — invalidate a\n * cached graph, clear a pending-change set — without re-implementing any of\n * the scheduling above.\n */\n onSettled?: (outcome: RefreshOutcome | null, startedAt: number) => void;\n}\n\nexport class RefreshScheduler {\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 tunedIntervalMs = PROBE_INTERVAL_MS;\n private readonly refreshImpl: RefreshImpl;\n\n constructor(private readonly opts: RefreshSchedulerOptions) {\n this.refreshImpl = opts.refreshImpl ?? refreshIfStale;\n }\n\n /** The interval currently in force — diagnostics and tests. */\n get probeIntervalMs(): number {\n return this.opts.probeIntervalMs ?? this.tunedIntervalMs;\n }\n\n /** Is a refresh running right now? Lets a caller report \"refreshing\" state. */\n get busy(): boolean {\n return this.inflight !== null;\n }\n\n /**\n * Re-arm the next probe regardless of the debounce interval — for a watcher\n * event or an explicit user action, where waiting out the interval would feel\n * broken. Clears the failure cooldown too: a real event is evidence the tree\n * moved, not a poll, and the condition that failed may be exactly what\n * changed. Does not itself start a refresh; the next `maybeRefresh` does.\n */\n arm(): void {\n this.lastProbeAt = 0;\n this.failedUntil = 0;\n }\n\n /**\n * Probe/rebuild if due, and wait at most the budget for it. Never throws —\n * a refresh problem must degrade to \"answer from the current map\", not break\n * the caller.\n */\n async maybeRefresh(): Promise<void> {\n const now = Date.now();\n if (!this.inflight) {\n if (now < this.failedUntil || now - this.lastProbeAt < this.probeIntervalMs) return;\n this.lastProbeAt = now;\n const graphPath =\n typeof this.opts.graphPath === 'function' ? this.opts.graphPath() : this.opts.graphPath;\n this.inflight = this.refreshImpl(this.opts.root, { graphPath, inline: this.opts.inline })\n .then((outcome) => {\n if (outcome.status === 'error') this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n this.tune(outcome, now);\n this.opts.onSettled?.(outcome, now);\n })\n .catch(() => {\n this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n this.tune(null, now);\n this.opts.onSettled?.(null, now);\n })\n .finally(() => {\n this.inflight = null;\n });\n }\n await Promise.race([this.inflight, sleep(this.opts.refreshBudgetMs ?? REFRESH_BUDGET_MS)]);\n }\n\n /**\n * Back off proportionally to what the refresh actually cost — including a\n * multi-second rebuild. Tuning off probe-only outcomes alone would re-arm\n * after the floor and make every sequential call pay the budget again for the\n * whole duration of a large rebuild.\n */\n private tune(outcome: RefreshOutcome | null, startedAt: number): void {\n const elapsed = Date.now() - startedAt;\n const cost =\n outcome?.status === 'refreshed' && typeof outcome.ms === 'number'\n ? Math.max(outcome.ms, elapsed)\n : elapsed;\n this.tunedIntervalMs = Math.min(\n MAX_PROBE_INTERVAL_MS,\n Math.max(PROBE_INTERVAL_MS, cost * PROBE_DUTY_FACTOR),\n );\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.();\n });\n}\n","import { attachVgd, type AttachOptions } from './attach.js';\nimport { vgdRequest } from './client.js';\n\n/**\n * One way to ask the daemon for a semantic ranking, shared by every surface.\n *\n * `vg ask`, `vg serve` and `vg lsp` each grew their own copy of \"load the\n * embedder, embed the corpus, rank\" — and `engine/refresh-scheduler.ts` records\n * what that costs: the per-server copies diverged, and one of them blocked an\n * editor Ask for ninety seconds. This is the single implementation of the\n * daemon path so that cannot happen again.\n *\n * Long-lived callers (the MCP server, the language server) hold one of these\n * for the process: it attaches once, remembers the slot, and per request sends\n * only the question. Short-lived callers get the same behaviour with the attach\n * folded into the first call.\n *\n * Every failure resolves to `null`, never a throw. `null` means \"rank it\n * yourself\" — the in-process path each caller already has, which is also what\n * happens when no daemon is running at all.\n */\n\nexport interface DaemonRanking {\n ranked: Array<{ id: string; score: number }>;\n /** How many vectors the slot holds — for logging, not correctness. */\n vectors: number;\n model?: string;\n}\n\nexport interface SemanticSessionOptions extends Omit<AttachOptions, 'corpusHash'> {\n /** How long to wait before retrying after a failed attach (default 30s). */\n retryAfterMs?: number;\n now?: () => number;\n /** Injected (tests). */\n attach?: typeof attachVgd;\n request?: typeof vgdRequest;\n}\n\nexport class DaemonSemanticSession {\n private repositoryId: string | undefined;\n private gitRef: string | undefined;\n private socketPath: string | undefined;\n /** The map the daemon was last told about, so an unchanged one is not resent. */\n private publishedHash: string | undefined;\n /** Do not re-attach before this time — a down daemon must not cost every request. */\n private retryAfter = 0;\n private attaching: Promise<void> | null = null;\n\n private readonly root: string;\n private readonly options: SemanticSessionOptions;\n private readonly retryAfterMs: number;\n private readonly now: () => number;\n private readonly attachImpl: typeof attachVgd;\n private readonly requestImpl: typeof vgdRequest;\n\n constructor(root: string, options: SemanticSessionOptions = {}) {\n this.root = root;\n this.options = options;\n this.retryAfterMs = options.retryAfterMs ?? 30_000;\n this.now = options.now ?? ((): number => Date.now());\n this.attachImpl = options.attach ?? attachVgd;\n this.requestImpl = options.request ?? vgdRequest;\n }\n\n /** True once a slot is known — useful for a one-line status log. */\n get attached(): boolean {\n return !!this.repositoryId;\n }\n\n /**\n * Rank `question` against the daemon's index for this repo.\n * `corpusHash` is the caller's current map: when it differs from what the\n * daemon holds, the map is republished before ranking, so a locally\n * refreshed map never ranks against yesterday's vectors.\n */\n async rank(question: string, corpusHash?: string): Promise<DaemonRanking | null> {\n await this.ensureAttached(corpusHash);\n if (!this.repositoryId) return null;\n try {\n const res = await this.requestImpl(\n { op: 'embed-rank', repositoryId: this.repositoryId, gitRef: this.gitRef, text: question },\n { socketPath: this.socketPath },\n );\n if (!res.ok || !('ranked' in res) || res.ranked.length === 0) return null;\n return { ranked: res.ranked, vectors: res.vectors, model: res.model };\n } catch {\n // The daemon went away mid-session (a restart, an upgrade). Forget the\n // slot so the next call re-attaches instead of retrying a dead socket.\n this.reset();\n return null;\n }\n }\n\n /**\n * The daemon's shared dependency context for this repo — the manifest digest\n * and the dependency records — computed once per daemon instead of once per\n * process. Null whenever the daemon cannot answer, so the caller falls back\n * to computing it locally.\n */\n async depContext(): Promise<{\n manifestHash: string;\n dependencies: Array<{ name: string; ecosystem: string; declared: string; installed?: string }>;\n } | null> {\n await this.ensureAttached();\n if (!this.repositoryId) return null;\n try {\n const res = await this.requestImpl(\n { op: 'dep-context', repositoryId: this.repositoryId },\n { socketPath: this.socketPath },\n );\n if (!res.ok || !('manifestHash' in res)) return null;\n return { manifestHash: res.manifestHash, dependencies: res.dependencies };\n } catch {\n this.reset();\n return null;\n }\n }\n\n private reset(): void {\n this.repositoryId = undefined;\n this.gitRef = undefined;\n this.publishedHash = undefined;\n this.retryAfter = this.now() + this.retryAfterMs;\n }\n\n /** Attach once; concurrent callers share the one attempt. */\n private ensureAttached(corpusHash?: string): Promise<void> {\n // Already attached and the map has not moved under us.\n if (this.repositoryId && (!corpusHash || corpusHash === this.publishedHash)) return Promise.resolve();\n if (this.now() < this.retryAfter) return Promise.resolve();\n if (this.attaching) return this.attaching;\n\n this.attaching = (async () => {\n const result = await this.attachImpl(this.root, { ...this.options, corpusHash });\n if (result.status === 'attached' && result.repositoryId) {\n this.repositoryId = result.repositoryId;\n this.gitRef = result.gitRef;\n this.socketPath = result.socketPath;\n this.publishedHash = corpusHash;\n } else {\n this.reset();\n }\n })().finally(() => {\n this.attaching = null;\n });\n return this.attaching;\n }\n}\n","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 type { RefreshOutcome, refreshIfStale } from '../engine/refresh.js';\nimport { RefreshScheduler, REFRESH_BUDGET_MS as SCHEDULER_BUDGET_MS } from '../engine/refresh-scheduler.js';\nimport { TOOLS, budgetSuffix, listedToolNames, warmEmbedderInBackground, type ToolSurface } from './tools.js';\nimport { isRelevantChange } from '../engine/watch-filter.js';\nimport { DaemonSemanticSession } from '../runtime/vgd/semantic-client.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/**\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 *\n * Re-exported from the shared scheduler, which owns this and the probe-interval\n * tuning for every surface (`vg serve` and `vg lsp` alike).\n */\nexport const REFRESH_BUDGET_MS = SCHEDULER_BUDGET_MS;\n/** Settle time between a watcher event and the background refresh it triggers. */\nconst WATCH_DEBOUNCE_MS = 400;\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 /** `--no-daemon`: never auto-start or use the local runtime. */\n daemon?: boolean;\n /**\n * Event-driven refresh: recursive fs.watch on the workspace so a save\n * rebuilds in ~400 ms instead of waiting out the freshness poll (default\n * true when refresh is on; `--no-watch` opts out). Where recursive watch is\n * unavailable the poll silently remains the only mechanism.\n */\n watch?: 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 * Listing surface (`--surface hot` / `--tools a,b`). Filters ONLY what\n * `tools/list` advertises; every tool stays callable so behaviour is\n * byte-identical across surfaces. See `listedToolNames` in ./tools.ts.\n */\n toolSurface?: ToolSurface;\n}\n\nexport class GraphSource {\n private cachedMtimeMs = -1;\n /**\n * True while the daemon owns freshness for this workspace. Set only after\n * the daemon confirms a subscription, cleared the instant it drops — so the\n * failure mode is \"this process watches again\", never \"nobody watches\".\n */\n private daemonOwnsFreshness = false;\n private cached: VgGraph | null = null;\n /** Project root used for freshness probes and rebuilds. */\n readonly root: string;\n /** Debounce, single-flight, self-tuning and budget cap — shared with `vg lsp`. */\n private readonly refresher: RefreshScheduler;\n /**\n * Files seen changing since the last COMMITTED refresh (watcher events,\n * filename → last-seen ms). Entries are cleared only after a refresh that\n * started at-or-after their last event completes with 'fresh'/'refreshed' —\n * a change landing mid-refresh stays pending, so the staleness signal can\n * be a false positive but never a false negative.\n */\n private readonly pendingChanges = new Map<string, number>();\n private watcher: fs.FSWatcher | null = null;\n private watchTimer: ReturnType<typeof setTimeout> | null = null;\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.refresher = new RefreshScheduler({\n root: this.root,\n graphPath,\n probeIntervalMs: tuning.probeIntervalMs,\n refreshBudgetMs: tuning.refreshBudgetMs,\n refreshImpl: tuning.refreshImpl,\n onSettled: (outcome, startedAt) => this.onRefreshSettled(outcome, startedAt),\n });\n }\n\n /**\n * Hand freshness to the daemon: stop probing on every call and stop watching.\n * The daemon pushes `slot-changed` and we reload from disk then.\n */\n deferFreshnessToDaemon(): void {\n this.daemonOwnsFreshness = true;\n this.stopWatching();\n }\n\n /** The daemon went away — resume owning freshness locally. */\n resumeLocalFreshness(): void {\n this.daemonOwnsFreshness = false;\n this.startWatching();\n }\n\n /** The daemon says the map moved; drop the cache so the next get() re-reads. */\n reloadFromDisk(): void {\n this.cachedMtimeMs = -1;\n this.pendingChanges.clear();\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 && !this.daemonOwnsFreshness) 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 — the shared scheduler does the work (see\n * engine/refresh-scheduler.ts). Never throws: a refresh problem must degrade\n * to \"answer from the current map\", not break the tool call.\n */\n private maybeRefresh(): Promise<void> {\n return this.refresher.maybeRefresh();\n }\n\n /**\n * A COMMITTED outcome (map verified fresh, or rebuilt) clears the pending\n * set — but only entries whose last event predates the refresh start.\n * 'locked'/'error'/'no-snapshot' clear nothing: the map may still be behind\n * those changes.\n */\n private onRefreshSettled(outcome: RefreshOutcome | null, startedAt: number): void {\n if (outcome?.status !== 'fresh' && outcome?.status !== 'refreshed') return;\n for (const [file, seenAt] of this.pendingChanges) {\n if (seenAt <= startedAt) this.pendingChanges.delete(file);\n }\n }\n\n /**\n * Record a source change (watcher event, or a test). Arms the next probe to\n * run immediately (bypassing the self-tuned interval — a real event is not a\n * poll) and schedules a debounced background refresh so the rebuild happens\n * BETWEEN tool calls instead of on the next call's 100 ms budget.\n */\n notePendingChange(filename: string): void {\n this.pendingChanges.set(filename, Date.now());\n this.refresher.arm();\n if (!this.refresh) return;\n if (this.watchTimer) clearTimeout(this.watchTimer);\n this.watchTimer = setTimeout(() => {\n this.watchTimer = null;\n void this.maybeRefresh();\n }, WATCH_DEBOUNCE_MS);\n this.watchTimer.unref?.();\n }\n\n /**\n * Event-driven freshness (the serve-loop watcher): a recursive `fs.watch`\n * on the workspace feeds `notePendingChange`, so a save triggers a rebuild\n * in ~WATCH_DEBOUNCE_MS instead of waiting out the 2–30 s poll. The poll\n * stays armed as the fallback — on filesystems where recursive watch fails\n * (some containers/NFS) this returns false and behaviour is unchanged.\n */\n startWatching(): boolean {\n if (this.watcher) return true;\n try {\n this.watcher = fs.watch(this.root, { recursive: true }, (_event, filename) => {\n if (!filename) return;\n if (!isRelevantChange(filename)) return;\n this.notePendingChange(filename);\n });\n this.watcher.unref?.();\n return true;\n } catch {\n this.watcher = null;\n return false;\n }\n }\n\n stopWatching(): void {\n this.watcher?.close();\n this.watcher = null;\n if (this.watchTimer) clearTimeout(this.watchTimer);\n this.watchTimer = null;\n }\n\n /**\n * In-band staleness signal for tool responses: what has changed since the\n * last committed refresh. Null when the map is current (the common case —\n * responses carry zero overhead then).\n */\n stalenessNote(): string | null {\n const n = this.pendingChanges.size;\n if (n === 0) return null;\n const names = [...this.pendingChanges.keys()].sort().slice(0, 3);\n const more = n > names.length ? `, +${n - names.length} more` : '';\n return `map freshness: ${n} file(s) changed since the last rebuild (${names.join(', ')}${more}) — auto-refresh pending; symbol locations may have shifted`;\n }\n}\n\n/**\n * Prefer the daemon's watcher to our own.\n *\n * Both notice the same edits and both drive the same incremental rebuild, so\n * running them together means two inotify registrations over one tree and two\n * rebuilds racing for one lock. The daemon wins when it is there: it is the\n * process that already holds the map and, unlike this one, is shared by every\n * other client on the machine.\n *\n * Standing down is conditional on the daemon *confirming* the subscription,\n * and reversed the instant that connection drops — a dead daemon degrades this\n * server to watching for itself, never to nothing watching at all.\n */\nasync function watchViaDaemonOrLocally(source: GraphSource, opts: ServeOptions): Promise<void> {\n if (opts.daemon === false) {\n source.startWatching();\n return;\n }\n try {\n const { subscribeToSlots } = await import('../runtime/vgd/slot-subscription.js');\n const subscription = await subscribeToSlots({\n onChange: () => source.reloadFromDisk(),\n onDetach: () => source.resumeLocalFreshness(),\n });\n if (subscription.active) {\n source.deferFreshnessToDaemon();\n return;\n }\n } catch {\n /* no daemon, or it cannot push — watch locally */\n }\n source.startWatching();\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 // One runtime session for the life of the server: attach once, then send only\n // the question per navigation call. Absent a daemon it stays null-returning\n // and every tool answers exactly as it does today.\n const semanticSession = local\n ? undefined\n : new DaemonSemanticSession(root, { disabled: opts.daemon === false });\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 const listed = new Set(listedToolNames(opts.toolSurface));\n // Repo-size call budget on orient's listed description: the stop-discipline\n // where the model decides, priced once per list, not per step. Best-effort —\n // when no map is loadable yet the description ships without the line.\n let budget = '';\n try {\n const graph = await source.get();\n budget = budgetSuffix(new Set(graph.nodes.map((n) => n.file)).size);\n } catch {\n /* no map yet — plain description */\n }\n return {\n tools: TOOLS.filter((t) => listed.has(t.name)).map((t) => ({\n name: t.name,\n description: t.name === 'orient' && budget ? `${t.description}${budget}` : t.description,\n inputSchema: t.inputSchema,\n annotations: { readOnlyHint: true, openWorldHint: false },\n })),\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, {\n root,\n local,\n dedup,\n seen,\n graphPath: source.graphPath,\n semanticSession,\n });\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 const rendered = renderToolResult(result);\n // In-band staleness (serve-loop watcher): when the working tree has\n // drifted past the served map, say so ON the response — the agent is the\n // one acting on possibly-moved symbols, and stderr never reaches it.\n // Zero overhead when the map is current (the overwhelmingly common case).\n const staleness = source.stalenessNote();\n if (staleness) rendered.content = [...(rendered.content ?? []), { type: 'text', text: `[${staleness}]` }];\n return rendered;\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 wantWatch = opts.refresh !== false && opts.watch !== false;\n if (wantWatch) await watchViaDaemonOrLocally(source, opts);\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\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/util/logo.ts","../src/engine/attest.ts","../src/commands/attest-actions.ts","../src/install/area-skills.ts","../src/commands/build.ts","../src/util/progress.ts"],"names":["crypto2","resolve","out","fs2","path2","path3","rel","fs3"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,OAAO,CAAC,CAAA,KAAsB,EAAE,GAAA,CAAI,SAAS,EAAE,CAAC,CAAA;AACtD,IAAM,OAAO,CAAC,CAAA,KAAsB,EAAE,GAAA,CAAI,SAAS,EAAE,CAAC,CAAA;AAGtD,IAAM,KAAA,GAAQ;AAAA,EACZ,KAAA,GAAQ,IAAA,CAAK,kDAAU,CAAA,GAAI,KAAK,QAAG,CAAA;AAAA,EACnC,IAAA,GAAO,EAAE,GAAA,CAAI,QAAG,IAAI,IAAA,CAAK,QAAG,CAAA,GAAI,GAAA,GAAM,IAAA,CAAK,QAAG,IAAI,IAAA,GAAO,IAAA,C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,CAAA,OAAA,CAAQ,MAAM,CAAA,CAAE,WAAA,EAAY;AAC7C,EAAA,IAAI,OAAA;AACJ,EAAA,QAAQ,GAAA;AAAK,IACX,KAAK,OAAA;AACH,MAAA,OAAA,GAAU,eAAe,KAAK,CAAA;AAC9B,MAAA;AAAA,IACF,KAAK,KAAA;AACH,MAAA,OAAA,GAAU,aAAa,KAAK,CAAA;AAC5B,MAAA;AAAA,IACF,KAAK,OAAA;AACH,MAAA,OAAA,GAAU,WAAW,KAAK,CAAA;AAC1B,MAAA;AAAA,IACF;AACE,MAAA,MAAM,IAAI,QAAA;AAAA,QACR,CAAA,kBAAA,EAAqB,OAAO,MAAM,CAAA,6IAAA,CAAA;AAAA,QAElC,QAAA,CAAS;AAAA,OACX;AAAA;AAEJ,EAAGE,EAAA,CAAA,SAAA,CAAeF,aAAaA,IAAA,CAAA,OAAA,CAAQ,MAAM,CAAC,CAAA,EAAG,EAAE,SAAA,EAAW,IAAA,EAAM,CAAA;AACpE,EAAGE,EAAA,CAAA,aAAA,CAAc,QAAQ,OAAO,CAAA;AAClC;AAEA,SAAS,OAAA,CAAQ,OAAe,IAAA,EAA0B;AACxD,EAAA,OAAO,CAAC,GAAG,IAAA,EAAM,KAAK,CAAA;AACxB;AAEA,SAASD,KAAI,IAAA,EAAsB;AACjC,EAAA,MAAM,CAAA,GAASD,IAAA,CAAA,QAAA,CAAS,OAAA,CAAQ,GAAA,IAAO,IAAI,CAAA;AAC3C,EAAA,OAAO,CAAA,KAAM,KAAK,GAAA,GAAM,CAAA;AAC1B","file":"chunk-H6RV2OAX.js","sourcesContent":["import { c } from './output.js';\nimport { VERSION } from '../version.js';\n\n/**\n * The `vg` brand banner — the same boxy robot mark and brand colours (teal/mint)\n * as the Vibgrate scanner (`vibgrate-cli/src/ui/progress.ts`), replicated here so\n * the open graph package stays standalone.\n *\n * The wordmark is stacked BELOW the mark rather than beside it: the robot's eye\n * (`◼`) and arrow (`➜`) glyphs are East-Asian \"ambiguous\"/wide, so terminals that\n * render them double-width make the rows unequal — text placed to their right\n * (the scanner's layout) then misaligns. Nothing sits beside the art here, so the\n * banner lines up in every terminal. Shown on `vg build` for a human at a TTY;\n * never on `--json`, `--quiet`, or under a pipe.\n */\n\nconst teal = (s: string): string => c.hex('#3FB0A4')(s);\nconst mint = (s: string): string => c.hex('#4FE3C1')(s);\n\n// ── Boxy robot mark — identical glyphs/colours to the scanner's ROBOT ──\nconst ROBOT = [\n ' ' + teal('╭──────╮') + mint('➜'),\n ' ' + c.dim('┤') + teal('│') + ' ' + mint('◼') + ' ' + mint('◼') + ' ' + teal('│') + c.dim('├'),\n ' ' + c.dim('┤') + teal('│') + ' ' + c.dim('▁▁') + ' ' + teal('│') + c.dim('├'),\n ' ' + teal('╰──────╯'),\n] as const;\n\n/**\n * The banner as lines (no I/O) so it is unit-testable. The robot mark is a\n * self-contained block; the wordmark/tagline sit on their OWN lines beneath it\n * (never beside the variable-width glyphs), so the banner aligns in any terminal.\n */\nexport function logoLines(root?: string, opts: { product?: string; tagline?: string } = {}): string[] {\n const product = opts.product ?? 'Graph';\n const tagline = opts.tagline ?? 'Code Intelligence Engine';\n return [\n '',\n ` ${ROBOT[0]}`,\n ` ${ROBOT[1]}`,\n ` ${ROBOT[2]}`,\n ` ${ROBOT[3]}`,\n ` ${c.bold.white('Vibgrate')} ${teal(product)} ${c.dim(`· ${tagline} · v${VERSION}`)}`,\n ...(root ? [` ${c.dim(root)}`] : []),\n '',\n ];\n}\n\n/** Print the banner to stderr, only for an interactive human (TTY). */\nexport function printLogo(root?: string, opts: { product?: string; tagline?: string } = {}): void {\n if (!process.stderr.isTTY) return;\n process.stderr.write(`${logoLines(root, opts).join('\\n')}\\n`);\n}\n\n/**\n * The **VG Code** banner (the approved marketing name for the code-editing\n * capability; see docs/NAMING-AND-MARKETING-STRATEGY.md). Same robot mark, but\n * the wordmark reads \"VG Code\" rather than \"Vibgrate Graph\".\n */\nexport function codeLogoLines(root?: string): string[] {\n return [\n '',\n ` ${ROBOT[0]}`,\n ` ${ROBOT[1]}`,\n ` ${ROBOT[2]}`,\n ` ${ROBOT[3]}`,\n ` ${c.bold.white('VG')} ${teal('Code')} ${c.dim(`· graph-grounded coding · v${VERSION}`)}`,\n ...(root ? [` ${c.dim(root)}`] : []),\n '',\n ];\n}\n\n/** Print the VG Code banner to stderr, only for an interactive human (TTY). */\nexport function printCodeLogo(root?: string): void {\n if (!process.stderr.isTTY) return;\n process.stderr.write(`${codeLogoLines(root).join('\\n')}\\n`);\n}\n","import * as crypto from 'node:crypto';\nimport { canonicalize } from './hash.js';\nimport { VERSION } from '../version.js';\nimport type { Toolchain, VgGraph } from '../schema.js';\n\n/**\n * `vg attest` — a signed, reproducible attestation over the code graph.\n *\n * This is the moat made load-bearing: a consumer can cryptographically verify,\n * offline, that a graph was produced by a named toolchain over a named commit and\n * has not changed since. We sign an in-toto Statement wrapped in a DSSE envelope\n * with Ed25519 (`node:crypto`, zero dependencies) — interoperable with\n * `cosign verify-blob-attestation`. Ed25519 signatures are deterministic\n * (RFC 8032), so the same graph + key produce a byte-identical envelope.\n *\n * The subject digest excludes the graph's volatile `generatedAt`, so it is\n * reproducible across rebuilds of identical content — which is exactly what makes\n * the attestation verifiable rather than a timestamped snapshot.\n */\n\nexport const DSSE_PAYLOAD_TYPE = 'application/vnd.in-toto+json';\nexport const IN_TOTO_STATEMENT_TYPE = 'https://in-toto.io/Statement/v1';\nexport const VG_PREDICATE_TYPE = 'https://vibgrate.com/attestation/code-graph/v1';\n\nexport interface CommitInfo {\n sha?: string;\n shortSha?: string;\n branch?: string;\n dirty?: boolean; // uncommitted changes vs sha — never verified-clean when true\n}\n\nexport interface AttestPredicate {\n tool: { name: 'vg'; version: string };\n toolchain?: Toolchain;\n corpusHash: string;\n graphDigest: string; // sha256 of the canonical graph (generatedAt excluded)\n counts: VgGraph['meta']['counts'];\n commit?: CommitInfo;\n sbomDigest?: string; // sha256 of an accompanying SBOM, if attested together\n timestamp?: string; // optional, opt-in (omitted by default for determinism)\n}\n\nexport interface InTotoStatement {\n _type: string;\n subject: { name: string; digest: { sha256: string } }[];\n predicateType: string;\n predicate: AttestPredicate;\n}\n\nexport interface DsseSignature {\n keyid: string;\n sig: string; // base64\n publicKey?: string; // PEM, embedded so the envelope self-verifies for integrity\n}\n\nexport interface DsseEnvelope {\n payloadType: string;\n payload: string; // base64 of the Statement JSON\n signatures: DsseSignature[];\n}\n\nexport function sha256Hex(input: string | Uint8Array): string {\n return crypto.createHash('sha256').update(input).digest('hex');\n}\n\n/**\n * sha256 over the canonical graph with the volatile `generatedAt` excluded, so\n * two builds of identical content attest to the same digest.\n */\nexport function graphSubjectDigest(graph: VgGraph): string {\n const { generatedAt: _omit, ...rest } = graph;\n return sha256Hex(canonicalize(rest));\n}\n\n/** The 16-hex key id: a truncated sha256 over the SPKI DER public key. */\nexport function keyId(publicKey: crypto.KeyObject): string {\n return sha256Hex(publicKey.export({ type: 'spki', format: 'der' })).slice(0, 16);\n}\n\nexport interface StatementInput {\n commit?: CommitInfo;\n sbomDigest?: string;\n timestamp?: string;\n}\n\nexport function buildStatement(graph: VgGraph, input: StatementInput = {}): InTotoStatement {\n const graphDigest = graphSubjectDigest(graph);\n const predicate: AttestPredicate = {\n tool: { name: 'vg', version: VERSION },\n toolchain: graph.provenance.toolchain,\n corpusHash: graph.provenance.corpusHash,\n graphDigest,\n counts: graph.meta.counts,\n };\n if (input.commit) predicate.commit = input.commit;\n if (input.sbomDigest) predicate.sbomDigest = input.sbomDigest;\n if (input.timestamp) predicate.timestamp = input.timestamp;\n return {\n _type: IN_TOTO_STATEMENT_TYPE,\n subject: [{ name: 'graph.json', digest: { sha256: graphDigest } }],\n predicateType: VG_PREDICATE_TYPE,\n predicate,\n };\n}\n\n/**\n * DSSE Pre-Authentication Encoding:\n * \"DSSEv1\" SP len(type) SP type SP len(body) SP body\n * with lengths as ASCII decimal byte counts. Signing the PAE (not the raw body)\n * is what binds the payloadType to the signature.\n */\nexport function dssePae(payloadType: string, body: Uint8Array): Buffer {\n const typeBytes = Buffer.from(payloadType, 'utf8');\n const header = Buffer.from(\n `DSSEv1 ${typeBytes.length} ${payloadType} ${body.length} `,\n 'utf8',\n );\n return Buffer.concat([header, Buffer.from(body)]);\n}\n\n/** Sign a statement, returning a self-contained DSSE envelope. */\nexport function signStatement(statement: InTotoStatement, privateKey: crypto.KeyObject): DsseEnvelope {\n const body = Buffer.from(JSON.stringify(statement), 'utf8');\n const pae = dssePae(DSSE_PAYLOAD_TYPE, body);\n const sig = crypto.sign(null, pae, privateKey);\n // Derive the public key from the private key (via its PEM, for @types/node compat).\n const publicKey = crypto.createPublicKey(privateKey.export({ type: 'pkcs8', format: 'pem' }).toString());\n return {\n payloadType: DSSE_PAYLOAD_TYPE,\n payload: body.toString('base64'),\n signatures: [\n {\n keyid: keyId(publicKey),\n sig: sig.toString('base64'),\n publicKey: publicKey.export({ type: 'spki', format: 'pem' }).toString(),\n },\n ],\n };\n}\n\nexport type AttestStatus = 'verified' | 'signature-valid' | 'failed';\n\nexport interface VerifyResult {\n status: AttestStatus;\n signatureValid: boolean;\n signerPinned: boolean; // signature verified against a caller-supplied trusted key\n digestMatches?: boolean; // recomputed graph digest matches the attested one\n dirty?: boolean; // the attested commit had uncommitted changes\n keyid: string;\n reason: string;\n statement: InTotoStatement;\n}\n\n/**\n * Verify an envelope. Honest states, never a fabricated pass:\n * failed — bad signature, or the on-disk graph no longer matches.\n * signature-valid — cryptographically intact, but signer not pinned (or dirty).\n * verified — pinned signer + matching digest + clean tree.\n */\n/** An empty statement for results where the envelope could not even be parsed. */\nfunction emptyStatement(): InTotoStatement {\n return {\n _type: '',\n subject: [],\n predicateType: '',\n predicate: {\n tool: { name: 'vg', version: '' },\n corpusHash: '',\n graphDigest: '',\n counts: { nodes: 0, edges: 0, areas: 0, tests: 0, untested: 0 },\n },\n };\n}\n\nfunction failedResult(reason: string): VerifyResult {\n return {\n status: 'failed',\n signatureValid: false,\n signerPinned: false,\n keyid: '',\n reason,\n statement: emptyStatement(),\n };\n}\n\nexport function verifyEnvelope(\n env: DsseEnvelope,\n opts: { publicKeyPem?: string; graph?: VgGraph } = {},\n): VerifyResult {\n // A `.intoto.jsonl` is attacker-supplied input: every decode/parse/key step\n // must degrade to an honest `failed`, never crash the command.\n let body: Buffer;\n let statement: InTotoStatement;\n try {\n body = Buffer.from(env?.payload ?? '', 'base64');\n const parsed = JSON.parse(body.toString('utf8')) as InTotoStatement;\n if (!parsed || typeof parsed !== 'object' || !parsed.predicate) {\n throw new Error('missing predicate');\n }\n statement = parsed;\n } catch {\n return failedResult('malformed attestation payload (not a valid in-toto statement)');\n }\n\n const pae = dssePae(env.payloadType, body);\n const sig0 = env.signatures?.[0];\n const keyid = sig0?.keyid ?? '';\n const sig = sig0?.sig ? Buffer.from(sig0.sig, 'base64') : Buffer.alloc(0);\n\n let signatureValid = false;\n let signerPinned = false;\n try {\n if (sig0 && sig.length) {\n if (opts.publicKeyPem) {\n const pinnedKey = crypto.createPublicKey(opts.publicKeyPem);\n signatureValid = crypto.verify(null, pae, pinnedKey, sig);\n signerPinned = signatureValid;\n } else if (sig0.publicKey) {\n const embeddedKey = crypto.createPublicKey(sig0.publicKey);\n signatureValid = crypto.verify(null, pae, embeddedKey, sig);\n }\n }\n } catch {\n // Malformed key or signature bytes → not a valid signature (not a crash).\n signatureValid = false;\n signerPinned = false;\n }\n\n const digestMatches = opts.graph\n ? graphSubjectDigest(opts.graph) === statement.predicate.graphDigest\n : undefined;\n const dirty = statement.predicate.commit?.dirty;\n\n let status: AttestStatus;\n let reason: string;\n if (!signatureValid) {\n status = 'failed';\n reason = sig0 ? 'signature verification failed' : 'no signature in envelope';\n } else if (digestMatches === false) {\n status = 'failed';\n reason = 'graph.json no longer matches the attested digest (content changed since signing)';\n } else if (signerPinned && !dirty) {\n status = 'verified';\n reason =\n digestMatches === true\n ? 'signature valid, signer trusted, graph digest matches'\n : 'signature valid, signer trusted';\n } else {\n status = 'signature-valid';\n reason = dirty\n ? 'signature valid but the attested tree was dirty (uncommitted changes)'\n : 'signature valid but signer not pinned — pass --pub to establish trust';\n }\n\n return { status, signatureValid, signerPinned, digestMatches, dirty, keyid, reason, statement };\n}\n\nexport interface GeneratedKeypair {\n privatePem: string;\n publicPem: string;\n keyid: string;\n}\n\n/** Mint a fresh Ed25519 keypair for signing attestations. */\nexport function generateKeypair(): GeneratedKeypair {\n const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');\n return {\n privatePem: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),\n publicPem: publicKey.export({ type: 'spki', format: 'pem' }).toString(),\n keyid: keyId(publicKey),\n };\n}\n\n/** Serialize an envelope as a single-line `.intoto.jsonl` record (deterministic). */\nexport function serializeEnvelope(env: DsseEnvelope): string {\n return `${JSON.stringify(env)}\\n`;\n}\n\nexport function parseEnvelope(text: string): DsseEnvelope {\n const line = text.trim().split('\\n')[0];\n return JSON.parse(line) as DsseEnvelope;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as crypto from 'node:crypto';\nimport { execFile } from 'node:child_process';\nimport { loadGraph } from '../engine/load.js';\nimport { resolveHead, workingTreeDirty } from '../core-open/utils/git-history.js';\nimport {\n buildStatement,\n signStatement,\n verifyEnvelope,\n generateKeypair,\n serializeEnvelope,\n parseEnvelope,\n type CommitInfo,\n type VerifyResult,\n} from '../engine/attest.js';\nimport { CliError, ExitCode } from '../util/exit.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * Attestation actions folded into the graph lifecycle: `vg build --attest` signs\n * the graph it just built; `vg build --verify` checks a committed attestation.\n * The crypto lives in engine/attest.ts; this is the file/key/git glue + output.\n */\n\nconst DEFAULT_ATTESTATION = 'attestation.intoto.jsonl';\nconst DEFAULT_KEY = 'attest-key.pem';\n\nexport interface SignOpts {\n /** Signing key PEM path; else $VG_ATTEST_KEY; else .vibgrate/attest-key.pem (auto-minted). */\n key?: string;\n /** Output path for the attestation (default .vibgrate/attestation.intoto.jsonl). */\n attestation?: string;\n}\n\nexport interface SignSummary {\n keyid: string;\n graphDigest: string;\n fingerprint?: string;\n commit?: CommitInfo;\n out: string;\n keyGeneratedAt?: string;\n}\n\n/** Sign an already-built graph, writing a DSSE attestation. Returns a summary +\n * human notices (the caller decides how to render them alongside build output). */\nexport async function signGraphAttestation(\n root: string,\n graph: VgGraph,\n opts: SignOpts,\n): Promise<{ summary: SignSummary; notices: string[] }> {\n const notices: string[] = [];\n const explicitKey = opts.key ?? process.env.VG_ATTEST_KEY;\n const keyPath = explicitKey ? path.resolve(explicitKey) : path.join(root, '.vibgrate', DEFAULT_KEY);\n\n let keyGeneratedAt: string | undefined;\n if (!fs.existsSync(keyPath)) {\n if (explicitKey) {\n throw new CliError(`signing key not found: ${explicitKey}`, ExitCode.USAGE_ERROR);\n }\n // First use with no key: mint one at the default path (loud — it must be kept\n // and gitignored to re-sign reproducibly).\n const kp = generateKeypair();\n fs.mkdirSync(path.dirname(keyPath), { recursive: true });\n fs.writeFileSync(keyPath, kp.privatePem, { mode: 0o600 });\n fs.writeFileSync(`${keyPath}.pub`, kp.publicPem);\n keyGeneratedAt = keyPath;\n notices.push(\n `minted a new Ed25519 signing key at ${rel(root, keyPath)} (keyid ${kp.keyid}) — ` +\n `keep it, add it to .gitignore, and reuse it to re-sign reproducibly`,\n );\n }\n\n let privateKey: crypto.KeyObject;\n try {\n privateKey = crypto.createPrivateKey(fs.readFileSync(keyPath, 'utf8'));\n } catch {\n throw new CliError(`could not read an Ed25519 private key from ${rel(root, keyPath)}`, ExitCode.USAGE_ERROR);\n }\n if (privateKey.asymmetricKeyType !== 'ed25519') {\n throw new CliError(\n `attest requires an Ed25519 key, but ${rel(root, keyPath)} is ${privateKey.asymmetricKeyType ?? 'unknown'}`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const commit = await gitCommitInfo(root);\n const statement = buildStatement(graph, { commit });\n const envelope = signStatement(statement, privateKey);\n const outPath = opts.attestation\n ? path.resolve(opts.attestation)\n : path.join(root, '.vibgrate', DEFAULT_ATTESTATION);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, serializeEnvelope(envelope));\n\n return {\n summary: {\n keyid: envelope.signatures[0]?.keyid ?? '',\n graphDigest: statement.predicate.graphDigest,\n fingerprint: statement.predicate.toolchain?.fingerprint,\n commit,\n out: rel(root, outPath),\n keyGeneratedAt: keyGeneratedAt ? rel(root, keyGeneratedAt) : undefined,\n },\n notices,\n };\n}\n\nexport interface VerifyOpts {\n /** Attestation path (default .vibgrate/attestation.intoto.jsonl). */\n attestation?: string;\n /** Public key PEM to pin the signer (else integrity-only verification). */\n pub?: string;\n}\n\nexport interface AttestVerifyOutcome {\n bundlePath: string;\n /** True when no attestation exists at the default path (and none was required). */\n missing: boolean;\n result?: VerifyResult;\n}\n\n/** Verify a committed attestation against the on-disk graph. Returns the outcome\n * (the caller renders + decides the exit code). Throws only when an attestation\n * was explicitly requested but is absent. */\nexport function verifyGraphAttestation(root: string, opts: VerifyOpts): AttestVerifyOutcome {\n const bundlePath = opts.attestation\n ? path.resolve(opts.attestation)\n : path.join(root, '.vibgrate', DEFAULT_ATTESTATION);\n if (!fs.existsSync(bundlePath)) {\n if (opts.attestation || opts.pub) {\n throw new CliError(\n `no attestation at ${rel(root, bundlePath)} — sign one with \\`vg build --attest\\``,\n ExitCode.NOT_FOUND,\n );\n }\n return { bundlePath, missing: true };\n }\n const envelope = parseEnvelope(fs.readFileSync(bundlePath, 'utf8'));\n const publicKeyPem = opts.pub ? fs.readFileSync(path.resolve(opts.pub), 'utf8') : undefined;\n const graph = loadGraph(root) ?? undefined;\n return { bundlePath, missing: false, result: verifyEnvelope(envelope, { publicKeyPem, graph }) };\n}\n\nasync function gitCommitInfo(root: string): Promise<CommitInfo | undefined> {\n const sha = await resolveHead(root);\n if (!sha) return undefined;\n const dirty = await workingTreeDirty(root);\n const branch = await gitBranch(root);\n return { sha, shortSha: sha.slice(0, 7), branch, dirty: dirty === true ? true : dirty === false ? false : undefined };\n}\n\n/** Best-effort current branch name; undefined on detached HEAD or no git. */\nfunction gitBranch(root: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['rev-parse', '--abbrev-ref', 'HEAD'],\n { cwd: root, timeout: 5000, windowsHide: true, encoding: 'utf8' },\n (err, stdout) => {\n if (err) return resolve(undefined);\n const name = String(stdout).trim();\n resolve(name && name !== 'HEAD' ? name : undefined);\n },\n );\n });\n}\n\nfunction rel(root: string, p: string): string {\n const r = path.relative(root, p);\n return r.startsWith('..') ? p : r;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Area, GraphNode, VgGraph } from '../schema.js';\nimport { versionMarker } from './content.js';\n\n/**\n * Per-area generated skills: one SKILL.md per top graph area, so the host\n * assistant can route \"working on X\" tasks straight to that area's entry\n * points without a discovery loop. Content is derived from the ranked graph —\n * entry points, hubs, key files, test posture — under two hard contracts:\n *\n * - DETERMINISTIC: the same graph produces byte-identical skills (no\n * timestamps, everything sorted with explicit tiebreaks), so regeneration\n * on every build causes zero churn.\n * - OWNED NAMESPACE: skills live under `vg-area-<slug>` directories and are\n * the only thing vg creates or deletes there. A file whose version marker\n * was removed is user-owned — never rewritten, never deleted (the same\n * opt-out contract as every other installed instruction file).\n *\n * Generation is gated on the assistant family being installed at all (its\n * `<skills>/vg/SKILL.md` exists): repos that never ran `vg install` get\n * nothing written.\n */\n\nexport const AREA_SKILL_PREFIX = 'vg-area-';\n/** Skill roots that receive per-area skills, per assistant family. */\nconst SKILL_BASES = ['.claude/skills', '.agents/skills'];\n\nconst MAX_AREAS = 8;\nconst MIN_AREA_SIZE = 4;\nconst MAX_ENTRY_POINTS = 6;\nconst MAX_KEY_FILES = 8;\n\nexport function areaSlug(area: Area): string {\n const s = area.label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n .replace(/-+$/g, '');\n return s || `area-${area.id}`;\n}\n\nfunction byImportanceDesc(a: GraphNode, b: GraphNode): number {\n return b.importance - a.importance || (a.qualifiedName < b.qualifiedName ? -1 : 1);\n}\n\n/** The areas worth a skill: largest first, deterministic tiebreak on label. */\nexport function topAreas(graph: VgGraph): Area[] {\n return [...graph.areas]\n .filter((a) => a.size >= MIN_AREA_SIZE)\n .sort((a, b) => b.size - a.size || (a.label < b.label ? -1 : 1))\n .slice(0, MAX_AREAS);\n}\n\nfunction renderAreaSkill(graph: VgGraph, area: Area, slug: string): string {\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const members = area.members.map((id) => byId.get(id)).filter((n): n is GraphNode => Boolean(n));\n const code = members.filter((n) => n.kind !== 'file');\n\n const fileCounts = new Map<string, number>();\n for (const n of members) fileCounts.set(n.file, (fileCounts.get(n.file) ?? 0) + 1);\n const keyFiles = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))\n .slice(0, MAX_KEY_FILES);\n\n const entryPoints = [...code].sort(byImportanceDesc).slice(0, MAX_ENTRY_POINTS);\n const hubs = code.filter((n) => n.isHub).sort(byImportanceDesc).slice(0, 4);\n const testable = code.filter((n) => n.tested !== null);\n const tested = testable.filter((n) => n.tested === true);\n\n const lines: string[] = [];\n lines.push('---');\n lines.push(`name: ${AREA_SKILL_PREFIX}${slug}`);\n lines.push(\n `description: Navigate the \"${area.label}\" area of this repo (${area.size} symbols across ${fileCounts.size} files). ` +\n `Use when the task touches ${keyFiles.slice(0, 3).map(([f]) => f).join(', ')}.`,\n );\n lines.push('---');\n lines.push('');\n lines.push(versionMarker());\n lines.push('');\n lines.push(`# Area: ${area.label}`);\n lines.push('');\n lines.push(\n `${area.size} symbols · ${fileCounts.size} files · cohesion ${(area.cohesion * 100).toFixed(0)}% · ` +\n `${area.externalEdges} cross-area edge(s)` +\n (testable.length ? ` · ${tested.length}/${testable.length} analyzable symbols tested` : ''),\n );\n lines.push('');\n lines.push('## Entry points (start here)');\n lines.push('');\n for (const n of entryPoints) {\n lines.push(`- \\`${n.qualifiedName}\\` — ${n.file}:${n.span.start}${n.doc ? ` — ${n.doc.split('\\n')[0]}` : ''}`);\n }\n if (hubs.length) {\n lines.push('');\n lines.push('## Hubs (high blast radius — check impact before changing)');\n lines.push('');\n for (const n of hubs) lines.push(`- \\`${n.qualifiedName}\\` — ${n.file}:${n.span.start}`);\n }\n lines.push('');\n lines.push('## Key files');\n lines.push('');\n for (const [file, count] of keyFiles) lines.push(`- ${file} (${count} symbol${count === 1 ? '' : 's'})`);\n lines.push('');\n lines.push('## How to work here');\n lines.push('');\n lines.push(\n '- Confirm the target with one `search_symbols`/`orient` call against the names above, then edit — the map above usually removes the discovery loop entirely.',\n );\n lines.push('- Before changing a hub, run `impact_of` on it: cross-area edges mean the blast radius leaves this area.');\n lines.push('');\n return lines.join('\\n');\n}\n\n/** All per-area skill files for a graph: relative skill-dir name → content. */\nexport function areaSkillFiles(graph: VgGraph): Map<string, string> {\n const out = new Map<string, string>();\n const used = new Set<string>();\n for (const area of topAreas(graph)) {\n let slug = areaSlug(area);\n // Deterministic de-dup for label collisions (two areas named \"utils\").\n if (used.has(slug)) slug = `${slug}-${area.id}`;\n used.add(slug);\n out.set(`${AREA_SKILL_PREFIX}${slug}`, renderAreaSkill(graph, area, slug));\n }\n return out;\n}\n\nexport interface AreaSkillChanges {\n written: string[];\n removed: string[];\n}\n\n/**\n * Write per-area skills into every installed assistant skill root, and remove\n * stale `vg-area-*` directories from previous graphs. Only files carrying our\n * version marker are ever rewritten or removed — marker-less files are\n * user-owned and left untouched (including their directory).\n */\nexport function writeAreaSkills(root: string, graph: VgGraph): AreaSkillChanges {\n const changes: AreaSkillChanges = { written: [], removed: [] };\n const files = areaSkillFiles(graph);\n for (const base of SKILL_BASES) {\n // Gate: this assistant family is installed here at all.\n if (!fs.existsSync(path.join(root, base, 'vg', 'SKILL.md'))) continue;\n const baseDir = path.join(root, base);\n // Remove stale generated areas (ours only — marker required).\n let existing: string[] = [];\n try {\n existing = fs.readdirSync(baseDir).filter((d) => d.startsWith(AREA_SKILL_PREFIX));\n } catch {\n existing = [];\n }\n for (const dir of existing) {\n if (files.has(dir)) continue;\n const skillFile = path.join(baseDir, dir, 'SKILL.md');\n try {\n const text = fs.readFileSync(skillFile, 'utf8');\n if (!/<!--\\s*vg:v\\d+\\b/.test(text)) continue; // user took ownership\n fs.rmSync(path.join(baseDir, dir), { recursive: true, force: true });\n changes.removed.push(path.join(base, dir));\n } catch {\n /* unreadable/missing — leave the directory alone */\n }\n }\n // Write current areas (skip user-owned files; skip unchanged content).\n for (const [dir, content] of files) {\n const skillFile = path.join(baseDir, dir, 'SKILL.md');\n try {\n const current = fs.existsSync(skillFile) ? fs.readFileSync(skillFile, 'utf8') : null;\n if (current !== null && !/<!--\\s*vg:v\\d+\\b/.test(current)) continue; // user took ownership\n if (current === content) continue; // deterministic content — no churn\n fs.mkdirSync(path.dirname(skillFile), { recursive: true });\n fs.writeFileSync(skillFile, content);\n changes.written.push(path.join(base, dir, 'SKILL.md'));\n } catch {\n /* unwritable — skip, never fail the build over a skill file */\n }\n }\n }\n return changes;\n}\n","import * as path from 'node:path';\nimport * as fs from 'node:fs';\nimport { spawn } from 'node:child_process';\nimport { Command } from 'commander';\nimport { buildGraph } from '../engine/build.js';\nimport { verifyDeterminism } from '../engine/verify.js';\nimport { epistemicBreakdown } from '../engine/epistemic.js';\nimport { signGraphAttestation, verifyGraphAttestation, type SignSummary } from './attest-actions.js';\nimport { isModelReady, countPending, resolveEmbedModel } from '../engine/embeddings.js';\nimport { attachVgd } from '../runtime/vgd/attach.js';\nimport { ActivityLog } from '../runtime/vgd/activity.js';\nimport type { VgGraph } from '../schema.js';\nimport { writeArtifacts } from '../engine/artifacts.js';\nimport { writeSnapshot } from '../engine/freshness.js';\nimport { refreshInstalledInstructions, SMALL_REPO_FILES } from '../install/registry.js';\nimport { writeAreaSkills } from '../install/area-skills.js';\nimport { serializeGraph } from '../engine/serialize.js';\nimport { renderReport } from '../engine/report.js';\nimport { renderHtml } from '../engine/html.js';\nimport { UsageError } from '../engine/discover.js';\nimport { ResourceLimitError } from '../engine/limits.js';\nimport { CliError, ExitCode, usageError } from '../util/exit.js';\nimport { resolveSelfJsEntry } from '../util/cli-invocation.js';\nimport { c, info, out, json } from '../util/output.js';\nimport { printLogo } from '../util/logo.js';\nimport { ProgressBar } from '../util/progress.js';\nimport { applyGlobalOptions, readGlobal, type GlobalOpts } from '../cli-options.js';\n\ninterface BuildCmdOpts {\n only?: string;\n exclude?: string[];\n html?: boolean;\n report?: boolean;\n ground?: boolean;\n jobs?: string;\n scip?: string | boolean;\n tsc?: boolean;\n export?: string;\n warm?: boolean;\n grammars?: string;\n fast?: boolean;\n index?: boolean;\n analysisTier?: string;\n attest?: boolean;\n verify?: boolean;\n attestKey?: string;\n attestation?: string;\n pub?: string;\n}\n\nexport function registerBuild(program: Command): void {\n const cmd = program\n .command('build')\n .description('build / update the code map (incremental, deterministic)')\n .argument('[paths...]', 'folders or files to map (default: current folder)')\n .option('--only <langs>', 'restrict to languages, e.g. ts,py,go')\n .option('--exclude <glob>', 'extra ignore glob (repeatable)', collect, [])\n .option('--no-html', 'do not write graph.html')\n .option('--no-report', 'do not write GRAPH_REPORT.md')\n .option('--no-ground', 'do not attach grounding (Phase 2)')\n .option('--jobs <n>', 'worker count (1 = single-threaded)')\n .option('--scip <file>', 'ingest a SCIP index for precise resolution (default: auto-detect index.scip)')\n .option('--no-scip', 'ignore any SCIP index')\n .option('--no-tsc', 'skip the in-process TypeScript resolver (heuristic floor only)')\n .option('--fast', 'skip precise tsc resolve (heuristic only — faster XL cold builds)')\n .option('--no-index', 'do not write the SQLite serve index under .vibgrate/cache/')\n .option('--analysis-tier <tier>', 'force analysis tier: full | large | xl (default: auto)')\n .option('--no-warm', 'do not warm the semantic index in the background after building')\n .option('--grammars <dir>', 'directory of grammar .wasm files (offline / air-gapped)')\n .option('-o, --export <file>', 'also write the map to a file (format inferred)')\n .option('--attest', 'sign the built graph → .vibgrate/attestation.intoto.jsonl')\n .option('--verify', 'verify a committed attestation against the graph (no rebuild)')\n .option('--attest-key <path>', 'signing key PEM (else $VG_ATTEST_KEY, else .vibgrate/attest-key.pem)')\n .option('--attestation <file>', 'attestation path (out for --attest, in for --verify)')\n .option('--pub <path>', 'public key PEM to pin the signer (with --verify)')\n .action(async function (this: Command, paths: string[], opts: BuildCmdOpts) {\n await runBuild(paths, opts, readGlobal(this));\n });\n applyGlobalOptions(cmd);\n}\n\nexport interface RunBuildHooks {\n /** Invoked during the parse phase (even under --quiet / non-TTY hosts). */\n onParseProgress?: (done: number, total: number) => void;\n}\n\nexport async function runBuild(\n paths: string[],\n opts: BuildCmdOpts,\n global: GlobalOpts,\n hooks?: RunBuildHooks,\n): Promise<void> {\n const root = path.resolve(global.cwd ?? '.');\n\n // `vg build --verify`: the single verification entry point — determinism\n // self-check plus (if present) attestation verification.\n if (opts.verify) {\n await verifyGraph(root, opts, global);\n return;\n }\n\n // Brand banner + live parse progress for an interactive human while the index\n // builds (TTY only; both are no-ops under --json/--quiet/pipe so machine output\n // stays clean). Hosts can still receive progress via hooks.onParseProgress.\n const interactive = !global.json && !global.quiet;\n if (interactive) printLogo(path.basename(root) || root);\n const bar = interactive ? new ProgressBar(c.dim('parsing')) : undefined;\n const jobs = opts.jobs ? Number(opts.jobs) : undefined;\n if (jobs !== undefined && (!Number.isInteger(jobs) || jobs < 1)) {\n throw usageError(`--jobs must be a positive integer (got \"${opts.jobs}\")`);\n }\n\n const only = opts.only ? opts.only.split(',').map((s) => s.trim()).filter(Boolean) : undefined;\n const tierRaw = opts.analysisTier?.toLowerCase();\n const analysisTier =\n tierRaw === 'full' || tierRaw === 'large' || tierRaw === 'xl' ? tierRaw : undefined;\n if (opts.analysisTier && !analysisTier) {\n throw usageError(`--analysis-tier must be full, large, or xl (got \"${opts.analysisTier}\")`);\n }\n let result;\n try {\n result = await buildGraph({\n root,\n paths: paths.length ? paths : undefined,\n only,\n exclude: opts.exclude,\n jobs,\n noCache: global.noCache,\n deep: global.deep,\n noGround: opts.ground === false,\n scip: typeof opts.scip === 'string' ? opts.scip : undefined,\n noScip: opts.scip === false,\n noTsc: opts.tsc === false,\n fast: opts.fast === true,\n noIndex: opts.index === false,\n analysisTier,\n generatedAt: global.generatedAt,\n onParseProgress: (done, total) => {\n bar?.update(done, total);\n hooks?.onParseProgress?.(done, total);\n },\n grammarsDir: opts.grammars,\n });\n } catch (err) {\n bar?.done();\n if (err instanceof UsageError) throw usageError(err.message);\n // A resource safeguard fired (file-count cap, heap budget, worker OOM) —\n // the message already carries the remedy; surface it without a stack.\n if (err instanceof ResourceLimitError) throw new CliError(err.message, ExitCode.ERROR);\n throw err;\n }\n bar?.done();\n\n const written = writeArtifacts(result.graph, {\n root,\n html: opts.html,\n report: opts.report,\n graphPath: global.graph,\n });\n\n // Record the freshness snapshot (stat+hash per corpus file, plus this build's\n // scope) so `vg serve`/`vg ask` can auto-refresh the map when the tree drifts.\n // Skipped for a custom --graph target: that is an explicit artifact the\n // auto-refresh machinery must not manage.\n if (!global.graph) {\n writeSnapshot(root, result.graph.provenance.corpusHash, result.fileStats, {\n only,\n exclude: opts.exclude,\n paths: paths.length ? paths : undefined,\n deep: global.deep,\n noGround: opts.ground === false,\n scip: typeof opts.scip === 'string' ? opts.scip : undefined,\n noScip: opts.scip === false,\n noTsc: opts.tsc === false,\n grammarsDir: opts.grammars,\n });\n }\n\n // The map is on disk now — start the local runtime if it is not up, and hand\n // it the map. `vg build` used to leave the daemon at `0 graph slot(s)` no\n // matter how many times it ran. Done here rather than with the summary below\n // so a `--json` build (which returns early) warms the daemon too; the notice\n // is printed in order later.\n const activity = new ActivityLog();\n await activity.time(\n 'attach',\n () => attachVgd(root, { graphPath: global.graph, disabled: global.daemon === false }),\n (a) => {\n if (a.status !== 'attached') return { outcome: 'skip' as const, detail: `${a.reason} — the map stays on disk only` };\n const started = a.started ? 'started vgd' : 'attached to vgd';\n if (a.published?.status === 'published') {\n return { outcome: 'ok' as const, detail: `${started} · map published ${a.published.gitRef} · ${a.published.nodeCount} nodes · semantic index warming` };\n }\n if (a.published?.status === 'failed') {\n return { outcome: 'warn' as const, detail: `${started} · map not published (${a.published.error})` };\n }\n return { outcome: 'ok' as const, detail: started };\n },\n );\n\n if (opts.export) writeExport(result.graph, opts.export);\n\n // Bring previously-installed assistant instructions (skill/nudge files from\n // `vg install`) up to the current content version — so evolved instructions\n // reach this repo the first time a new CLI builds here. Only files carrying\n // vg's own version marker (or the exact legacy generated content) are\n // touched; a custom --graph build is an explicit artifact and skips this.\n if (!global.graph) {\n const fileCount = result.graph.nodes.filter((n) => n.kind === 'file').length;\n const refreshed = refreshInstalledInstructions(root, fileCount > 0 && fileCount < SMALL_REPO_FILES);\n if (interactive) {\n for (const r of refreshed) {\n info(c.dim(`vg · refreshed assistant instructions ${r.file} (v${r.from} → v${r.to})`));\n }\n }\n // Per-area skills, regenerated from the fresh graph on every build.\n // Deterministic content → zero churn when the graph didn't change; only\n // repos that ran `vg install` (skill root present) receive anything.\n const areaChanges = writeAreaSkills(root, result.graph);\n if (interactive && (areaChanges.written.length || areaChanges.removed.length)) {\n const parts = [\n areaChanges.written.length ? `${areaChanges.written.length} area skill(s) updated` : '',\n areaChanges.removed.length ? `${areaChanges.removed.length} stale removed` : '',\n ].filter(Boolean);\n info(c.dim(`vg · ${parts.join(', ')}`));\n }\n }\n\n // `--attest`: sign the freshly-built graph → .vibgrate/attestation.intoto.jsonl.\n let attestation: SignSummary | undefined;\n const attestNotices: string[] = [];\n if (opts.attest) {\n const signed = await signGraphAttestation(root, result.graph, {\n key: opts.attestKey,\n attestation: opts.attestation,\n });\n attestation = signed.summary;\n attestNotices.push(...signed.notices);\n }\n\n if (global.json) {\n json({\n ok: true,\n counts: result.graph.meta.counts,\n languages: result.graph.meta.languages,\n reparsed: result.reparsed,\n reused: result.reused,\n totalFiles: result.totalFiles,\n resolve: result.resolveStats,\n tsc: result.tsc,\n scip: result.scip,\n epistemic: epistemicBreakdown(result.graph.edges),\n artifacts: written,\n corpusHash: result.graph.provenance.corpusHash,\n toolchain: result.graph.provenance.toolchain,\n attestation,\n timingMs: result.timing.totalMs,\n warnings: result.warnings,\n activity: activity.toJSON(),\n });\n return;\n }\n\n const { counts } = result.graph.meta;\n const incremental =\n result.reused > 0\n ? `incremental: ${result.reparsed} of ${result.totalFiles} files re-parsed`\n : `${result.totalFiles} files parsed`;\n const seconds = (result.timing.totalMs / 1000).toFixed(2);\n info(`${c.cyan('vg')} · mapped ${rel(root)} in ${seconds}s (${incremental})`);\n info(\n ` nodes ${c.bold(String(counts.nodes))} edges ${c.bold(String(counts.edges))} ` +\n `areas ${counts.areas} langs ${result.graph.meta.languages.join(',') || '—'}`,\n );\n const callPct =\n result.resolveStats.callsResolved + result.resolveStats.callsUnresolved > 0\n ? Math.round(\n (100 * result.resolveStats.callsResolved) /\n (result.resolveStats.callsResolved + result.resolveStats.callsUnresolved),\n )\n : 100;\n // When a precise rung ran it is authoritative; callPct is only the heuristic\n // floor (label it so, to avoid understating the precise result below).\n const precise = result.tsc || result.scip;\n const callLabel = precise ? `heuristic floor ${callPct}%` : `calls resolved ${callPct}%`;\n info(c.dim(` ${callLabel} · resolver ${result.graph.provenance.resolver.join(',')}`));\n if (result.tsc) {\n const jsx = result.tsc.jsx > 0 ? `, ${result.tsc.jsx} JSX` : '';\n info(c.dim(` tsc: ${result.tsc.resolved} precise edges across ${result.tsc.files} TS/JS files (${result.tsc.calls} calls${jsx})`));\n }\n if (result.scip) {\n info(c.dim(` scip: ${result.scip.resolved} precise edges from ${result.scip.tool ?? 'index'} (${result.scip.documents} docs)`));\n }\n const ep = epistemicBreakdown(result.graph.edges);\n info(\n c.dim(\n ` edges by evidence · observed ${ep.observed} · name-matched ${ep['name-matched']} · declared ${ep.declared}`,\n ),\n );\n const artifactList = [written.graphPath, written.htmlPath, written.reportPath]\n .filter(Boolean)\n .map((p) => path.relative(root, p as string))\n .join(' ');\n info(` → ${artifactList}`);\n if (result.warnings.length) {\n info(c.yellow(` ${result.warnings.length} parse warning(s) — run with --json for detail`));\n }\n if (attestation) {\n for (const n of attestNotices) info(c.yellow(` ${n}`));\n info(\n c.dim(\n ` attested · keyid ${attestation.keyid} · digest ${attestation.graphDigest.slice(0, 16)}… → ${attestation.out}`,\n ),\n );\n }\n\n for (const line of activity.render()) info(line);\n\n maybeWarmEmbeddings(root, result.graph, global, opts.warm !== false);\n}\n\n/**\n * `vg build --verify` — the single verification entry point. Runs the determinism\n * self-check (byte-identical rebuilds + toolchain fingerprint) and, when an\n * attestation is present, verifies it against the on-disk graph. Exit 4 on a\n * determinism failure, exit 2 on an attestation failure.\n */\nasync function verifyGraph(root: string, opts: BuildCmdOpts, global: GlobalOpts): Promise<void> {\n const only = opts.only ? opts.only.split(',').map((s) => s.trim()).filter(Boolean) : undefined;\n const jobs = opts.jobs ? Number(opts.jobs) : undefined;\n const det = await verifyDeterminism({ root, only, exclude: opts.exclude, jobs });\n const attest = verifyGraphAttestation(root, { attestation: opts.attestation, pub: opts.pub });\n const attestFailed = !attest.missing && attest.result?.status === 'failed';\n\n if (global.json) {\n json({\n ok: det.ok && !attestFailed,\n determinism: { ok: det.ok, checks: det.checks, digest: det.digest },\n attestation: attest.missing\n ? null\n : {\n status: attest.result?.status,\n signatureValid: attest.result?.signatureValid,\n signerPinned: attest.result?.signerPinned,\n digestMatches: attest.result?.digestMatches,\n dirty: attest.result?.dirty,\n keyid: attest.result?.keyid,\n reason: attest.result?.reason,\n },\n });\n } else {\n info(`${c.cyan('vg build --verify')} · ${path.relative(process.cwd(), root) || '.'}`);\n for (const check of det.checks) {\n const mark = check.ok ? c.green('✔') : c.red('✘');\n const detail = check.detail ? c.dim(` (${check.detail})`) : '';\n info(` ${mark} ${check.name}${detail}`);\n }\n info(det.ok ? c.green(` deterministic · digest ${det.digest.slice(0, 16)}…`) : c.red(' NON-DETERMINISTIC'));\n if (attest.missing) {\n info(c.dim(` attestation: none (sign one with \\`vg build --attest\\`)`));\n } else {\n const r = attest.result;\n const badge =\n r?.status === 'verified'\n ? c.green('✔ attestation verified')\n : r?.status === 'signature-valid'\n ? c.yellow('~ attestation signature valid')\n : c.red('✘ attestation failed');\n info(` ${badge}${r?.keyid ? c.dim(` · keyid ${r.keyid}`) : ''}`);\n info(c.dim(` ${r?.reason ?? ''}`));\n }\n }\n\n if (!det.ok) throw new CliError('determinism self-check failed', ExitCode.NON_DETERMINISTIC);\n if (attestFailed) throw new CliError('attestation verification failed', ExitCode.GATE_FAILED);\n}\n\n/**\n * After an interactive build we have just committed to a code graph, so the\n * user is likely to run `vg ask`/`vg serve` next — start warming the semantic\n * index in the background now so that first semantic call is instant instead of\n * paying a cold model load. If the model isn't downloaded yet, the background\n * warm fetches it (once, centrally) rather than deferring the whole cost to the\n * first `ask`. Disabled with `--no-warm`; skipped under --json/--quiet/--local\n * and when not at a TTY (so CI never auto-downloads). The detached child runs\n * `vg embed --bg [--download]`; a lock prevents it racing a foreground `ask`.\n */\nfunction maybeWarmEmbeddings(root: string, graph: VgGraph, global: GlobalOpts, warm: boolean): void {\n if (!warm || global.json || global.quiet || global.local) return;\n if (!process.stdout.isTTY && !process.stderr.isTTY) return;\n const cli = resolveSelfJsEntry() ?? process.argv[1];\n if (!cli) return;\n const modelId = resolveEmbedModel();\n const ready = isModelReady(modelId);\n // Already fully warm: model present and every node embedded → nothing to do.\n if (ready && countPending(graph, root, modelId) === 0) return;\n // When the model isn't on this machine yet, start the one-time download now\n // (the graph is built; the next semantic call shouldn't wait for it).\n const args = ready\n ? [cli, 'embed', '-C', root, '--bg']\n : [cli, 'embed', '-C', root, '--bg', '--download'];\n try {\n const child = spawn(process.execPath, args, { detached: true, stdio: 'ignore' });\n child.unref();\n info(\n c.dim(\n ready\n ? ' warming the semantic index in the background — `vg ask` will be instant'\n : ' downloading the semantic model in the background (once) — `vg ask`/`vg serve` will be instant; disable with --no-warm',\n ),\n );\n } catch {\n /* warm-up is best-effort */\n }\n}\n\nfunction writeExport(graph: Parameters<typeof serializeGraph>[0], target: string): void {\n if (target === '-') {\n out(serializeGraph(graph).trimEnd());\n return;\n }\n const ext = path.extname(target).toLowerCase();\n let content: string;\n switch (ext) {\n case '.json':\n content = serializeGraph(graph);\n break;\n case '.md':\n content = renderReport(graph);\n break;\n case '.html':\n content = renderHtml(graph);\n break;\n default:\n throw new CliError(\n `cannot export to \"${ext || target}\" yet — supported in Phase 0: .json, .md, .html, \"-\" (stdout). ` +\n `More formats (graphml, dot, cypher) arrive with \\`vg export\\` in Phase 1.`,\n ExitCode.USAGE_ERROR,\n );\n }\n fs.mkdirSync(path.dirname(path.resolve(target)), { recursive: true });\n fs.writeFileSync(target, content);\n}\n\nfunction collect(value: string, prev: string[]): string[] {\n return [...prev, value];\n}\n\nfunction rel(root: string): string {\n const r = path.relative(process.cwd(), root);\n return r === '' ? '.' : r;\n}\n","import { c } from './output.js';\nimport { brandProgressBar } from '../core-open/ui/bar.js';\n\n/**\n * A small progress bar matching the scanner's style\n * (`vibgrate-core-open/src/ui/progress.ts`): a smooth sub-cell gradient bar\n * (shared `brandProgressBar`), a braille spinner, percent, elapsed and ETA.\n * Renders to **stderr** in place, and only when stderr is a TTY — under a\n * pipe/CI it stays silent so logs aren't polluted.\n */\n\nconst FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const;\nconst WIDTH = 30;\n\nfunction fmtDuration(ms: number): string {\n const s = Math.max(0, Math.round(ms / 1000));\n if (s < 60) return `${s}s`;\n return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`;\n}\n\n/**\n * Pure render of one progress line (no I/O, no clock) so it is unit-testable.\n * `elapsedMs` and `frame` are passed in by the caller.\n */\nexport function formatProgressLine(\n label: string,\n done: number,\n total: number,\n elapsedMs: number,\n frame: number,\n): string {\n const ratio = total > 0 ? Math.min(done / total, 1) : 0;\n const bar = brandProgressBar(ratio, WIDTH);\n const pct = Math.round(ratio * 100);\n const spin = c.cyan(FRAMES[((frame % FRAMES.length) + FRAMES.length) % FRAMES.length]);\n const eta = ratio > 0.02 && ratio < 1 ? ` · eta ${fmtDuration((elapsedMs / ratio) * (1 - ratio))}` : '';\n return ` ${spin} ${label} ${bar} ${c.bold(`${pct}%`)} ${c.dim(`${done}/${total} · ${fmtDuration(elapsedMs)}${eta}`)}`;\n}\n\n/** Live, in-place progress bar on stderr (no-op when stderr isn't a TTY). */\nexport class ProgressBar {\n private readonly start = Date.now();\n private frame = 0;\n private readonly tty = Boolean(process.stderr.isTTY);\n\n constructor(private readonly label: string) {}\n\n update(done: number, total: number): void {\n if (!this.tty) return;\n const line = formatProgressLine(this.label, done, total, Date.now() - this.start, this.frame++);\n process.stderr.write(`\\r\\x1b[2K${line}`);\n }\n\n /** Clear the bar; optionally print a final summary line. */\n done(summary?: string): void {\n if (!this.tty) return;\n process.stderr.write('\\r\\x1b[2K');\n if (summary) process.stderr.write(`${summary}\\n`);\n }\n}\n"]}
|