@vibgrate/cli 2026.825.2 → 2026.829.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DOCS.md +204 -9
- package/README.md +2 -0
- package/dist/{agent-DHQYEHVW.js → agent-5GW7C7EB.js} +14 -14
- package/dist/{agent-DHQYEHVW.js.map → agent-5GW7C7EB.js.map} +1 -1
- package/dist/{approvals-KBM72NU2.js → approvals-ISJFILVK.js} +5 -5
- package/dist/{approvals-KBM72NU2.js.map → approvals-ISJFILVK.js.map} +1 -1
- package/dist/{attach-O74NL4M5.js → attach-JUSALQ75.js} +3 -3
- package/dist/{attach-O74NL4M5.js.map → attach-JUSALQ75.js.map} +1 -1
- package/dist/baseline-YL2IZZ4Y.js +9 -0
- package/dist/{baseline-4X6MQBDA.js.map → baseline-YL2IZZ4Y.js.map} +1 -1
- package/dist/{chunk-JAEHLTVX.js → chunk-5RW5PIBH.js} +3 -3
- package/dist/{chunk-JAEHLTVX.js.map → chunk-5RW5PIBH.js.map} +1 -1
- package/dist/{chunk-TT2J2TB6.js → chunk-65YN3BG3.js} +1207 -40
- package/dist/chunk-65YN3BG3.js.map +1 -0
- package/dist/{chunk-VMPKOMHG.js → chunk-B5VCPIKT.js} +7 -6
- package/dist/chunk-B5VCPIKT.js.map +1 -0
- package/dist/{chunk-FQHWPOTS.js → chunk-BA6YBVNT.js} +3 -3
- package/dist/{chunk-FQHWPOTS.js.map → chunk-BA6YBVNT.js.map} +1 -1
- package/dist/{chunk-3E7QT4NE.js → chunk-BODXEZEY.js} +9 -9
- package/dist/{chunk-3E7QT4NE.js.map → chunk-BODXEZEY.js.map} +1 -1
- package/dist/{chunk-BICZR6UJ.js → chunk-D3SV3JWB.js} +3 -3
- package/dist/{chunk-BICZR6UJ.js.map → chunk-D3SV3JWB.js.map} +1 -1
- package/dist/chunk-EGMBHPXV.js +127 -0
- package/dist/chunk-EGMBHPXV.js.map +1 -0
- package/dist/{chunk-DIZ5KI5Q.js → chunk-FHSEK64W.js} +7 -7
- package/dist/{chunk-DIZ5KI5Q.js.map → chunk-FHSEK64W.js.map} +1 -1
- package/dist/{chunk-E3XVIFSH.js → chunk-FKCN653F.js} +3 -3
- package/dist/{chunk-E3XVIFSH.js.map → chunk-FKCN653F.js.map} +1 -1
- package/dist/{chunk-OIUVWCKM.js → chunk-FPIMNVLI.js} +12 -4
- package/dist/chunk-FPIMNVLI.js.map +1 -0
- package/dist/{chunk-NS4DL3QR.js → chunk-HHMWE52J.js} +10 -135
- package/dist/chunk-HHMWE52J.js.map +1 -0
- package/dist/{chunk-5UG4UHKU.js → chunk-HUJZO4K5.js} +281 -106
- package/dist/chunk-HUJZO4K5.js.map +1 -0
- package/dist/{chunk-HFQIYM6E.js → chunk-JWQ2JCQS.js} +4 -4
- package/dist/{chunk-HFQIYM6E.js.map → chunk-JWQ2JCQS.js.map} +1 -1
- package/dist/{chunk-27TS2AUJ.js → chunk-K7QR7U3V.js} +12 -11
- package/dist/chunk-K7QR7U3V.js.map +1 -0
- package/dist/{chunk-IJVWKZRS.js → chunk-KCKG3EEJ.js} +3 -3
- package/dist/{chunk-IJVWKZRS.js.map → chunk-KCKG3EEJ.js.map} +1 -1
- package/dist/{chunk-GWSJYDK7.js → chunk-MMIIVRQC.js} +7 -7
- package/dist/chunk-MMIIVRQC.js.map +1 -0
- package/dist/chunk-N6R4XPLX.js +27 -0
- package/dist/chunk-N6R4XPLX.js.map +1 -0
- package/dist/{chunk-GR7SFCQJ.js → chunk-NQQT75AN.js} +77 -27
- package/dist/chunk-NQQT75AN.js.map +1 -0
- package/dist/{chunk-6MIJLO5B.js → chunk-NSC7ZK62.js} +3 -3
- package/dist/{chunk-6MIJLO5B.js.map → chunk-NSC7ZK62.js.map} +1 -1
- package/dist/{chunk-SYMJSRYF.js → chunk-OAYSRM7J.js} +12 -14
- package/dist/chunk-OAYSRM7J.js.map +1 -0
- package/dist/{chunk-L7GCJNDT.js → chunk-QMROD7MI.js} +15 -8
- package/dist/chunk-QMROD7MI.js.map +1 -0
- package/dist/{chunk-SHD5TCZ5.js → chunk-R2FX4USU.js} +7 -7
- package/dist/chunk-R2FX4USU.js.map +1 -0
- package/dist/{chunk-7M4E7UGX.js → chunk-RL7JYG3D.js} +3 -3
- package/dist/{chunk-7M4E7UGX.js.map → chunk-RL7JYG3D.js.map} +1 -1
- package/dist/{chunk-QLNJ3VWO.js → chunk-RRSUNTZI.js} +3 -3
- package/dist/{chunk-QLNJ3VWO.js.map → chunk-RRSUNTZI.js.map} +1 -1
- package/dist/{chunk-NZES47ST.js → chunk-TWFPHXPN.js} +3 -3
- package/dist/{chunk-NZES47ST.js.map → chunk-TWFPHXPN.js.map} +1 -1
- package/dist/chunk-UGRUG2FA.js +6 -0
- package/dist/{chunk-G3ACLBMG.js.map → chunk-UGRUG2FA.js.map} +1 -1
- package/dist/{chunk-KYM55VZX.js → chunk-VOEEYCR3.js} +6 -6
- package/dist/{chunk-KYM55VZX.js.map → chunk-VOEEYCR3.js.map} +1 -1
- package/dist/{chunk-SIXWWQ6S.js → chunk-WBDRBP22.js} +4 -4
- package/dist/{chunk-SIXWWQ6S.js.map → chunk-WBDRBP22.js.map} +1 -1
- package/dist/{chunk-K3SXWOTT.js → chunk-YL332BU2.js} +20 -15
- package/dist/chunk-YL332BU2.js.map +1 -0
- package/dist/{chunk-2NUS5BOR.js → chunk-ZQY5TWCB.js} +3 -3
- package/dist/{chunk-2NUS5BOR.js.map → chunk-ZQY5TWCB.js.map} +1 -1
- package/dist/cli.d.ts +16 -1
- package/dist/cli.js +2362 -342
- package/dist/cli.js.map +1 -1
- package/dist/{daemon-RZS5FPIW.js → daemon-NRIIDMX2.js} +10 -10
- package/dist/{daemon-RZS5FPIW.js.map → daemon-NRIIDMX2.js.map} +1 -1
- package/dist/embed-worker-main.js +3 -3
- package/dist/{ensure-map-DL2S774J.js → ensure-map-VAIYCCEJ.js} +17 -16
- package/dist/{ensure-map-DL2S774J.js.map → ensure-map-VAIYCCEJ.js.map} +1 -1
- package/dist/explain-EXPJTCB5.js +126 -0
- package/dist/explain-EXPJTCB5.js.map +1 -0
- package/dist/{graph-backend-JXARVT3R.js → graph-backend-V5A2H5ZB.js} +7 -7
- package/dist/{graph-backend-JXARVT3R.js.map → graph-backend-V5A2H5ZB.js.map} +1 -1
- package/dist/index.d.ts +217 -13
- package/dist/index.js +17 -16
- package/dist/index.js.map +1 -1
- package/dist/{interactive-2XRBRFRB.js → interactive-VQM2CTE2.js} +37 -32
- package/dist/interactive-VQM2CTE2.js.map +1 -0
- package/dist/load-UAVA732M.js +11 -0
- package/dist/{load-7C5VETRD.js.map → load-UAVA732M.js.map} +1 -1
- package/dist/parse-worker.js +2 -2
- package/dist/{rules-ASYEUNB5.js → rules-TLRGB5L4.js} +12 -4
- package/dist/rules-TLRGB5L4.js.map +1 -0
- package/dist/{run-outcome-TMB5TJNA.js → run-outcome-EATWIKLR.js} +5 -5
- package/dist/{run-outcome-TMB5TJNA.js.map → run-outcome-EATWIKLR.js.map} +1 -1
- package/dist/{runtime-session-Y23NVY7R.js → runtime-session-Y2BRBXUW.js} +9 -9
- package/dist/{runtime-session-Y23NVY7R.js.map → runtime-session-Y2BRBXUW.js.map} +1 -1
- package/dist/{session-KXT2ZTPE.js → session-N2FTYIHQ.js} +9 -9
- package/dist/{session-KXT2ZTPE.js.map → session-N2FTYIHQ.js.map} +1 -1
- package/dist/{stream-json-NW6AOE47.js → stream-json-GCZAHORX.js} +14 -14
- package/dist/{stream-json-NW6AOE47.js.map → stream-json-GCZAHORX.js.map} +1 -1
- package/dist/version-XNZ4GLMQ.js +4 -0
- package/dist/{version-7ABYXWOZ.js.map → version-XNZ4GLMQ.js.map} +1 -1
- package/dist/{vg-mcp-bridge-LXBHKEFR.js → vg-mcp-bridge-VDZWFEO2.js} +22 -11
- package/dist/vg-mcp-bridge-VDZWFEO2.js.map +1 -0
- package/dist/{vgd-RW7HCEIP.js → vgd-3A2TRNP5.js} +8 -8
- package/dist/vgd-3A2TRNP5.js.map +1 -0
- package/package.json +2 -2
- package/dist/baseline-4X6MQBDA.js +0 -9
- package/dist/chunk-27TS2AUJ.js.map +0 -1
- package/dist/chunk-5UG4UHKU.js.map +0 -1
- package/dist/chunk-G3ACLBMG.js +0 -6
- package/dist/chunk-GR7SFCQJ.js.map +0 -1
- package/dist/chunk-GWSJYDK7.js.map +0 -1
- package/dist/chunk-K3SXWOTT.js.map +0 -1
- package/dist/chunk-L7GCJNDT.js.map +0 -1
- package/dist/chunk-NS4DL3QR.js.map +0 -1
- package/dist/chunk-OIUVWCKM.js.map +0 -1
- package/dist/chunk-SHD5TCZ5.js.map +0 -1
- package/dist/chunk-SYMJSRYF.js.map +0 -1
- package/dist/chunk-TT2J2TB6.js.map +0 -1
- package/dist/chunk-VMPKOMHG.js.map +0 -1
- package/dist/chunk-YENM3HT7.js +0 -23
- package/dist/chunk-YENM3HT7.js.map +0 -1
- package/dist/interactive-2XRBRFRB.js.map +0 -1
- package/dist/load-7C5VETRD.js +0 -11
- package/dist/rules-ASYEUNB5.js.map +0 -1
- package/dist/version-7ABYXWOZ.js +0 -4
- package/dist/vg-mcp-bridge-LXBHKEFR.js.map +0 -1
- package/dist/vgd-RW7HCEIP.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { runBuild } from './chunk-
|
|
2
|
-
import { loadGraph } from './chunk-
|
|
1
|
+
import { runBuild } from './chunk-K7QR7U3V.js';
|
|
2
|
+
import { loadGraph } from './chunk-RL7JYG3D.js';
|
|
3
3
|
|
|
4
4
|
// src/code/ensure-map.ts
|
|
5
5
|
async function ensureCodeMap(root, global, hooks) {
|
|
@@ -38,5 +38,5 @@ async function ensureCodeMap(root, global, hooks) {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
export { ensureCodeMap };
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
42
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
//# sourceMappingURL=chunk-JWQ2JCQS.js.map
|
|
42
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AAA,CAAK,cAAA,EAAgB,CAAA,CAAA,EAAI,KAAA,CAAM,cAAA,EAAgB,CAAA,CAAA,GACjE,qBAAA;AAAA,YACN;AAAA,WACD,CAAA;AAAA,QACH;AAAA;AACF,KACF;AACA,IAAA,KAAA,EAAO,UAAA,GAAa,EAAE,KAAA,EAAO,MAAA,EAAQ,SAAS,gDAAA,EAAwC,GAAA,EAAK,KAAK,CAAA;AAChG,IAAA,OAAO,OAAA;AAAA,EACT,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,UAAU,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,OAAO,CAAC,CAAA;AACzD,IAAA,KAAA,EAAO,UAAA,GAAa;AAAA,MAClB,KAAA,EAAO,OAAA;AAAA,MACP,OAAA,EAAS,iCAAiC,OAAO,CAAA;AAAA,KAClD,CAAA;AACD,IAAA,MAAM,CAAA;AAAA,EACR;AACF","file":"chunk-JWQ2JCQS.js","sourcesContent":["/**\n * Ensure a code map exists before VG Code (or any host) starts work.\n *\n * Interactive CLI, `vg code --stream-json`, and VS Code all share this path so\n * the first turn never fails with \"no map found\" — we build once (with progress\n * callbacks for host UIs) and then proceed.\n */\n\nimport { loadGraph } from '../engine/load.js';\nimport { runBuild } from '../commands/build.js';\nimport type { GlobalOpts } from '../cli-options.js';\n\nexport type EnsureMapPhase = 'start' | 'progress' | 'done' | 'error';\n\nexport interface EnsureMapProgress {\n phase: EnsureMapPhase;\n message: string;\n /** 0–100 when known (parse phase); omitted when indeterminate. */\n pct?: number;\n}\n\nexport interface EnsureMapHooks {\n onProgress?: (p: EnsureMapProgress) => void;\n}\n\n/**\n * @returns `ready` when a map already existed; `built` when this call built one.\n */\nexport async function ensureCodeMap(\n root: string,\n global: GlobalOpts,\n hooks?: EnsureMapHooks,\n): Promise<'ready' | 'built'> {\n if (loadGraph(root, global.graph)) return 'ready';\n\n hooks?.onProgress?.({\n phase: 'start',\n message: 'Building the code map for this project… (first run only)',\n pct: 0,\n });\n\n try {\n await runBuild(\n [root],\n { html: false, report: false },\n { ...global, quiet: true },\n {\n onParseProgress: (done, total) => {\n const pct = total > 0 ? Math.min(99, Math.round((done / total) * 100)) : undefined;\n hooks?.onProgress?.({\n phase: 'progress',\n message:\n total > 0\n ? `Parsing files… ${done.toLocaleString()}/${total.toLocaleString()}`\n : 'Parsing files…',\n pct,\n });\n },\n },\n );\n hooks?.onProgress?.({ phase: 'done', message: 'Code map ready — starting your task…', pct: 100 });\n return 'built';\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n hooks?.onProgress?.({\n phase: 'error',\n message: `Could not build the code map: ${message}`,\n });\n throw e;\n }\n}\n"]}
|
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
import { readGlobal, applyGlobalOptions } from './chunk-
|
|
1
|
+
import { readGlobal, applyGlobalOptions } from './chunk-N6R4XPLX.js';
|
|
2
2
|
import { ActivityLog } from './chunk-H5Q4JUY4.js';
|
|
3
3
|
import { c, info, json, out } from './chunk-CT5BS56U.js';
|
|
4
|
-
import { buildGraph, ResourceLimitError, writeSnapshot, refreshInstalledInstructions, SMALL_REPO_FILES, epistemicBreakdown, verifyDeterminism
|
|
5
|
-
import {
|
|
4
|
+
import { buildGraph, ResourceLimitError, writeSnapshot, refreshInstalledInstructions, SMALL_REPO_FILES, epistemicBreakdown, verifyDeterminism } from './chunk-HHMWE52J.js';
|
|
5
|
+
import { versionMarker } from './chunk-EGMBHPXV.js';
|
|
6
|
+
import { brandProgressBar, resolveHead, workingTreeDirty } from './chunk-HUJZO4K5.js';
|
|
6
7
|
import { usageError, CliError, ExitCode } from './chunk-MS6V5XKB.js';
|
|
7
|
-
import { attachVgd } from './chunk-
|
|
8
|
+
import { attachVgd } from './chunk-KCKG3EEJ.js';
|
|
8
9
|
import { init_cli_invocation, resolveSelfJsEntry } from './chunk-EZ7UC5Y5.js';
|
|
9
|
-
import { loadGraph } from './chunk-
|
|
10
|
+
import { loadGraph } from './chunk-RL7JYG3D.js';
|
|
10
11
|
import { UsageError, mergeExcludes } from './chunk-RTURQXQL.js';
|
|
11
|
-
import { resolveEmbedModel, isModelReady, countPending } from './chunk-
|
|
12
|
-
import { writeArtifacts, renderHtml, renderReport } from './chunk-
|
|
12
|
+
import { resolveEmbedModel, isModelReady, countPending } from './chunk-BA6YBVNT.js';
|
|
13
|
+
import { writeArtifacts, renderHtml, renderReport } from './chunk-FPIMNVLI.js';
|
|
13
14
|
import { serializeGraph } from './chunk-O3LABX6I.js';
|
|
14
|
-
import { VERSION } from './chunk-
|
|
15
|
+
import { VERSION } from './chunk-UGRUG2FA.js';
|
|
15
16
|
import { canonicalize } from './chunk-JFGYT6BI.js';
|
|
16
17
|
import * as path from 'path';
|
|
17
18
|
import * as fs from 'fs';
|
|
@@ -767,7 +768,7 @@ async function verifyGraph(root, opts, global) {
|
|
|
767
768
|
if (attestFailed) throw new CliError("attestation verification failed", ExitCode.GATE_FAILED);
|
|
768
769
|
}
|
|
769
770
|
function maybeWarmEmbeddings(root, graph, global, warm) {
|
|
770
|
-
if (!warm || global.json || global.quiet || global.
|
|
771
|
+
if (!warm || global.json || global.quiet || global.offline) return;
|
|
771
772
|
if (!process.stdout.isTTY && !process.stderr.isTTY) return;
|
|
772
773
|
const cli = resolveSelfJsEntry() ?? process.argv[1];
|
|
773
774
|
if (!cli) return;
|
|
@@ -825,5 +826,5 @@ function rel2(root) {
|
|
|
825
826
|
}
|
|
826
827
|
|
|
827
828
|
export { DSSE_PAYLOAD_TYPE, LiveStatus, ProgressBar, dssePae, generateKeypair, keyId, printCodeLogo, printLogo, registerBuild, runBuild, sha256Hex };
|
|
828
|
-
//# sourceMappingURL=chunk-
|
|
829
|
-
//# sourceMappingURL=chunk-
|
|
829
|
+
//# sourceMappingURL=chunk-K7QR7U3V.js.map
|
|
830
|
+
//# sourceMappingURL=chunk-K7QR7U3V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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,CAAK,QAAG,CAAA,GAAI,GAAA,GAAM,KAAK,QAAG,CAAA,GAAI,CAAA,CAAE,GAAA,CAAI,QAAG,CAAA;AAAA,EAChG,OAAO,CAAA,CAAE,GAAA,CAAI,QAAG,CAAA,GAAI,IAAA,CAAK,QAAG,CAAA,GAAI,IAAA,GAAO,EAAE,GAAA,CAAI,cAAI,IAAI,IAAA,GAAO,IAAA,CAAK,QAAG,CAAA,GAAI,CAAA,CAAE,IAAI,QAAG,CAAA;AAAA,EACjF,KAAA,GAAQ,KAAK,kDAAU;AACzB,CAAA;AAOO,SAAS,SAAA,CAAU,IAAA,EAAe,IAAA,GAA+C,EAAC,EAAa;AACpG,EAAA,MAAM,OAAA,GAAU,KAAK,OAAA,IAAW,OAAA;AAChC,EAAA,MAAM,OAAA,GAAU,KAAK,OAAA,IAAW,0BAAA;AAChC,EAAA,OAAO;AAAA,IACL,EAAA;AAAA,IACA,CAAA,EAAA,EAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAAA,IACb,CAAA,EAAA,EAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAAA,IACb,CAAA,EAAA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} 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 off by default. A repo opts in with `\"areaSkills\": true` in\n * `vibgrate.config.json`, and only then if the assistant family is installed\n * (its `<skills>/vg/SKILL.md` exists). Repos that never ran `vg install` get\n * nothing written either way.\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 * Generated `vg-area-*` skills are off unless `vibgrate.config.json` sets\n * `\"areaSkills\": true`. Missing or malformed config keeps the default (off).\n */\nexport function areaSkillsEnabled(root: string): boolean {\n try {\n const parsed = JSON.parse(\n fs.readFileSync(path.join(root, 'vibgrate.config.json'), 'utf8'),\n ) as { areaSkills?: unknown };\n return parsed.areaSkills === true;\n } catch {\n return false;\n }\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 *\n * Off by default: writes nothing and removes every generated `vg-area-*`\n * skill. `\"areaSkills\": true` turns generation on. The vg install skill itself\n * is never touched.\n */\nexport function writeAreaSkills(root: string, graph: VgGraph): AreaSkillChanges {\n const changes: AreaSkillChanges = { written: [], removed: [] };\n const files = areaSkillsEnabled(root) ? areaSkillFiles(graph) : new Map<string, string>();\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, mergeExcludes } 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: mergeExcludes(root, 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: off unless vibgrate.config.json sets areaSkills: true.\n // When on, deterministic content → zero churn if the graph didn't change.\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.offline) 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 // On Windows, `detached` (DETACHED_PROCESS) would strip the child of any\n // console, making every console-subsystem grandchild (git, node) pop a\n // visible console window; windowsHide gives it a windowless console the\n // grandchildren inherit. Children outlive their parent on Windows anyway,\n // so nothing is lost. POSIX keeps detached so the warm survives the\n // terminal closing.\n const child = spawn(process.execPath, args, {\n detached: process.platform !== 'win32',\n stdio: 'ignore',\n windowsHide: true,\n });\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/** Pure status line (spinner + message + elapsed). Used by {@link LiveStatus}. */\nexport function formatStatusLine(message: string, elapsedMs: number, frame: number): string {\n const spin = c.cyan(FRAMES[((frame % FRAMES.length) + FRAMES.length) % FRAMES.length]);\n return ` ${spin} ${message} ${c.dim(`· ${fmtDuration(elapsedMs)}`)}`;\n}\n\nexport interface LiveStatusOptions {\n /** Destination (tests inject a buffer). Default stderr. */\n stream?: { write(chunk: string): unknown; isTTY?: boolean };\n /** Force TTY / non-TTY. Default: stream.isTTY. */\n tty?: boolean;\n /** Spinner cadence in ms (default 120). */\n intervalMs?: number;\n now?: () => number;\n}\n\n/**\n * A ticking in-place status line on stderr.\n *\n * `vg ask` used to print nothing until the answer was ready, so a 30s daemon\n * wait looked like a hang — and clearing the terminal left a blank screen\n * because nothing redrew. This line paints immediately, then again every tick,\n * so the user always sees what is happening.\n *\n * Non-TTY (pipe/CI): one line when the message changes, never a spinner.\n */\nexport class LiveStatus {\n private message = '';\n private frame = 0;\n private timer: ReturnType<typeof setInterval> | null = null;\n private startedAt = 0;\n private stopped = true;\n private readonly stream: { write(chunk: string): unknown; isTTY?: boolean };\n private readonly tty: boolean;\n private readonly intervalMs: number;\n private readonly now: () => number;\n\n constructor(options: LiveStatusOptions = {}) {\n this.stream = options.stream ?? process.stderr;\n this.tty = options.tty ?? Boolean(this.stream.isTTY);\n this.intervalMs = options.intervalMs ?? 120;\n this.now = options.now ?? ((): number => Date.now());\n }\n\n start(message: string): void {\n if (!this.stopped) {\n this.set(message);\n return;\n }\n this.stopped = false;\n this.message = message;\n this.startedAt = this.now();\n this.frame = 0;\n if (this.tty) {\n this.paint();\n this.timer = setInterval(() => this.paint(), this.intervalMs);\n (this.timer as unknown as { unref?: () => void }).unref?.();\n } else {\n this.stream.write(` ${message}\\n`);\n }\n }\n\n set(message: string): void {\n if (this.stopped || message === this.message) return;\n this.message = message;\n if (this.tty) this.paint();\n else this.stream.write(` ${message}\\n`);\n }\n\n /** Clear the live line. Optionally leave a final (non-spinner) line. */\n stop(final?: string): void {\n if (this.stopped) return;\n this.stopped = true;\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n if (this.tty) {\n this.stream.write('\\r\\x1b[2K');\n if (final) this.stream.write(`${final}\\n`);\n } else if (final) {\n this.stream.write(` ${final}\\n`);\n }\n }\n\n private paint(): void {\n if (this.stopped) return;\n const line = formatStatusLine(this.message, this.now() - this.startedAt, this.frame++);\n this.stream.write(`\\r\\x1b[2K${line}`);\n }\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"]}
|
|
@@ -91,10 +91,10 @@ async function currentSlot(root, socketPath, request) {
|
|
|
91
91
|
return { repositoryId: reg.workspace.id, gitRef: summary.gitRef, corpusHash: summary.summary.corpusHash };
|
|
92
92
|
}
|
|
93
93
|
async function defaultEnsure() {
|
|
94
|
-
const { ensureVgdSoft } = await import('./daemon-
|
|
94
|
+
const { ensureVgdSoft } = await import('./daemon-NRIIDMX2.js');
|
|
95
95
|
return (socketPath, readyBudgetMs) => ensureVgdSoft(socketPath, readyBudgetMs);
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
export { attachVgd, daemonDisabledReason };
|
|
99
|
-
//# sourceMappingURL=chunk-
|
|
100
|
-
//# sourceMappingURL=chunk-
|
|
99
|
+
//# sourceMappingURL=chunk-KCKG3EEJ.js.map
|
|
100
|
+
//# sourceMappingURL=chunk-KCKG3EEJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/vgd/attach.ts"],"names":[],"mappings":";;;;;AA0EA,SAAS,OAAO,KAAA,EAAoC;AAClD,EAAA,IAAI,CAAC,OAAO,OAAO,KAAA;AACnB,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,IAAA,EAAK,CAAE,WAAA,EAAY;AAC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A,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-IJVWKZRS.js","sourcesContent":["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
|
+
{"version":3,"sources":["../src/runtime/vgd/attach.ts"],"names":[],"mappings":";;;;;AA0EA,SAAS,OAAO,KAAA,EAAoC;AAClD,EAAA,IAAI,CAAC,OAAO,OAAO,KAAA;AACnB,EAAA,MAAM,CAAA,GAAI,KAAA,CAAM,IAAA,EAAK,CAAE,WAAA,EAAY;AACnC,EAAA,OAAO,MAAM,EAAA,IAAM,CAAA,KAAM,GAAA,IAAO,CAAA,KAAM,WAAW,CAAA,KAAM,IAAA;AACzD;AAMO,SAAS,oBAAA,CACd,OAAA,GAA2D,EAAC,EAC7C;AACf,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAO,OAAA,CAAQ,GAAA;AACnC,EAAA,IAAI,OAAA,CAAQ,UAAU,OAAO,yBAAA;AAC7B,EAAA,IAAI,MAAA,CAAO,IAAI,YAAY,CAAA,IAAK,OAAO,GAAA,CAAI,kBAAkB,GAAG,OAAO,0BAAA;AAGvE,EAAA,IAAI,M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CAAc,YAAY,aAAa,CAAA;AAC/E","file":"chunk-KCKG3EEJ.js","sourcesContent":["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,7 +1,7 @@
|
|
|
1
|
-
import { buildMessages, parseEdits, applyEdits, unifiedDiff, redactSecrets } from './chunk-
|
|
2
|
-
import { recordCliCall, CLI_TOOL_ALIASES, buildCodeContext, buildTaskCapsule, capsuleToCodeContext } from './chunk-
|
|
3
|
-
import {
|
|
4
|
-
import { loadTopicTags, rankQuestion } from './chunk-
|
|
1
|
+
import { buildMessages, parseEdits, applyEdits, unifiedDiff, redactSecrets } from './chunk-R2FX4USU.js';
|
|
2
|
+
import { recordCliCall, CLI_TOOL_ALIASES, buildCodeContext, buildTaskCapsule, capsuleToCodeContext } from './chunk-OAYSRM7J.js';
|
|
3
|
+
import { rankingAskFrom } from './chunk-YL332BU2.js';
|
|
4
|
+
import { loadTopicTags, rankQuestion } from './chunk-FPIMNVLI.js';
|
|
5
5
|
import { repositoryIdFromRoot } from './chunk-XP6UUCZZ.js';
|
|
6
6
|
import * as fs from 'fs';
|
|
7
7
|
import * as path from 'path';
|
|
@@ -30,7 +30,7 @@ async function runCodeSession(options) {
|
|
|
30
30
|
};
|
|
31
31
|
phase("inspect", options.capsule ? "building source-bearing task capsule" : "building graph-grounded context");
|
|
32
32
|
const topicTags = await loadTopicTags(graph, root);
|
|
33
|
-
const ranked = await rankQuestion(graph,
|
|
33
|
+
const ranked = await rankQuestion(graph, rankingAskFrom(instruction), { limit: 48, topicTags });
|
|
34
34
|
const context = buildSessionContext(graph, instruction, {
|
|
35
35
|
budget,
|
|
36
36
|
files,
|
|
@@ -257,5 +257,5 @@ function shortId() {
|
|
|
257
257
|
}
|
|
258
258
|
|
|
259
259
|
export { commitChanges, nodeCodeFs, runCodeSession, undoChanges };
|
|
260
|
-
//# sourceMappingURL=chunk-
|
|
261
|
-
//# sourceMappingURL=chunk-
|
|
260
|
+
//# sourceMappingURL=chunk-MMIIVRQC.js.map
|
|
261
|
+
//# sourceMappingURL=chunk-MMIIVRQC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/code/session.ts"],"names":["resolve"],"mappings":";;;;;;;;AAsFA,eAAsB,eAAe,OAAA,EAAwD;AAC3F,EAAA,MAAM;AAAA,IACJ,KAAA;AAAA,IACA,IAAA;AAAA,IACA,WAAA;AAAA,IACA,SAAA;AAAA,IACA,KAAA,GAAQ,KAAA;AAAA,IACR,OAAA,GAAU,KAAA;AAAA,IACV,KAAA;AAAA,IACA,MAAA;AAAA,IACA,WAAA;AAAA,IACA,MAAM,MAAM,CAAA;AAAA,IACZ,UAAU,MAAM;AAAA,IAAC;AAAA,GACnB,GAAI,OAAA;AACJ,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,IAAU,UAAA,CAAW,IAAI,CAAA;AAChD,EAAA,MAAM,aAAA,GAAgB,OAAA,CAAQ,aAAA,IAAiB,OAAA,EAAQ;AACvD,EAAA,MAAM,YAA8B,EAAC;AACrC,EAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,EAAmB,MAAA,KAAyB;AACzD,IAAA,SAAA,CAAU,KAAK,CAAC,CAAA;AAChB,IAAA,OAAA,CAAQ,GAAG,MAAM,CAAA;AAAA,EACnB,CAAA;AAGA,EAAA,KAAA,CAAM,SAAA,EAAW,OAAA,CAAQ,OAAA,GAAU,sCAAA,GAAyC,iCAAiC,CAAA;AAG7G,EAAA,MAAM,SAAA,GAAY,MAAM,aAAA,CAAc,KAAA,EAAO,IAAI,CAAA;AACjD,EAAA,MAAM,MAAA,GAAS,MAAM,YAAA,CAAa,KAAA,EAAO,cAAA,CAAe,WAAW,CAAA,EAAG,EAAE,KAAA,EAAO,EAAA,EAAI,SAAA,EAAW,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AA,MAAM,GAAA,GAAW,IAAA,CAAA,IAAA,CAAK,IAAA,EAAM,WAAW,CAAA;AACvC,MAAG,EAAA,CAAA,SAAA,CAAU,GAAA,EAAK,EAAE,SAAA,EAAW,MAAM,CAAA;AACrC,MAAG,kBAAoB,IAAA,CAAA,IAAA,CAAK,GAAA,EAAK,kBAAkB,CAAA,EAAG,OAAO,IAAI,CAAA;AAAA,IACnE;AAAA,GACF;AACF;AAGA,SAAS,OAAA,GAAkB;AACzB,EAAA,IAAI,CAAA,GAAI,EAAA;AACR,EAAA,MAAM,QAAA,GAAW,sCAAA;AACjB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,CAAA,EAAG,KAAK,CAAA,IAAK,QAAA,CAAS,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,EAAO,GAAI,QAAA,CAAS,MAAM,CAAC,CAAA;AACrF,EAAA,OAAO,CAAA;AACT","file":"chunk-MMIIVRQC.js","sourcesContent":["/**\n * The `vg code` governance session (VG-CLI-CODE §7).\n *\n * This is the load-bearing rule the whole platform is built on, applied to code\n * edits: a state-altering change goes **through** the lifecycle, never around it\n * (GUARDRAILS §5). One run walks inspect → assess → dry-run → approve → execute\n * → verify → log:\n *\n * inspect build the graph-grounded context for the instruction\n * assess ask the routed model for a terse edit; apply it deterministically\n * (in memory); compute the diff and the blast radius\n * dry-run the DEFAULT terminal state — propose the change, write nothing\n * approve writing requires explicit consent; without it we stop at dry-run\n * execute write the approved changes to disk\n * verify confirm the files on disk match what was approved (+ optional cmd)\n * log append an immutable, secret-free audit record with a correlation id\n *\n * Everything is deterministic except the single model call, which is isolated\n * behind the provider list (tried in order, falling back on transport failure).\n * The filesystem and clock are injectable so the whole session is testable\n * offline with no writes escaping a temp dir.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { buildCodeContext } from './context.js';\nimport { rankQuestion, type SanitizedRank } from '../engine/relevance-provider.js';\nimport { loadTopicTags } from '../engine/relevance-enrich.js';\nimport { rankingAskFrom } from '../engine/user-ask.js';\nimport { buildTaskCapsule, capsuleToCodeContext } from './capsule.js';\nimport { recordCliCall, CLI_TOOL_ALIASES } from '../engine/savings.js';\nimport { repositoryIdFromRoot } from '../runtime/paths.js';\nimport { parseEdits, applyEdits, type SymbolSpan } from './apply.js';\nimport { unifiedDiff } from './diff.js';\nimport { buildMessages } from './prompt.js';\nimport { redactSecrets } from './providers.js';\nimport type { ChatOptions, CodeContext, CodeSessionResult, FileChange, LifecyclePhase, Provider, ProviderResult } from './types.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Minimal filesystem seam so the session is testable without touching real disk. */\nexport interface CodeFs {\n read(file: string): string | null;\n write(file: string, content: string): void;\n remove(file: string): void;\n appendAudit(line: string): void;\n}\n\nexport interface RunSessionOptions {\n graph: VgGraph;\n root: string;\n instruction: string;\n /** Providers to try in order (from the router); the first that answers wins. */\n providers: Provider[];\n /** Write to disk? Default false — dry-run is the safe default (GUARDRAILS §3.2). */\n apply?: boolean;\n /** Explicit consent for the write (`--yes`); without it, a requested apply stops at dry-run. */\n consent?: boolean;\n /** Restrict the edit surface to these files. */\n files?: string[];\n /** Context token budget. */\n budget?: number;\n chatOptions?: ChatOptions;\n /** Injectable filesystem (defaults to a real, root-scoped fs). */\n fsImpl?: CodeFs;\n /** Injectable clock (ms) for the audit timestamp. */\n now?: () => number;\n /** Injectable correlation id (defaults to a random short id). */\n correlationId?: string;\n /** Progress callback per phase. */\n onPhase?: (phase: LifecyclePhase, detail: string) => void;\n /** Skip appending to the audit log (used by tests/dry programmatic calls). */\n noAudit?: boolean;\n /**\n * Who is making the graph-backed call, for per-model savings auditing. When\n * `client` is set, the context-assembly step (a `query_graph`-equivalent) is\n * recorded to the local savings ledger tagged with the provider + model, so\n * `vg savings` can break usage down per model. VG Code always sets this.\n */\n attribution?: { client: string; provider?: string; model?: string };\n /**\n * Use a source-bearing Task Capsule for the inspect context (Fusion Runtime\n * Phase 0 A/B). Default false keeps the metadata-only path.\n */\n capsule?: boolean;\n}\n\nexport async function runCodeSession(options: RunSessionOptions): Promise<CodeSessionResult> {\n const {\n graph,\n root,\n instruction,\n providers,\n apply = false,\n consent = false,\n files,\n budget,\n chatOptions,\n now = () => 0,\n onPhase = () => {},\n } = options;\n const fsImpl = options.fsImpl ?? nodeCodeFs(root);\n const correlationId = options.correlationId ?? shortId();\n const phasesRun: LifecyclePhase[] = [];\n const phase = (p: LifecyclePhase, detail: string): void => {\n phasesRun.push(p);\n onPhase(p, detail);\n };\n\n // ── inspect ──────────────────────────────────────────────────────────────\n phase('inspect', options.capsule ? 'building source-bearing task capsule' : 'building graph-grounded context');\n // The relevance module ranks the seeds when installed (auto-provisioned);\n // null → the mechanical fallback.\n const topicTags = await loadTopicTags(graph, root);\n const ranked = await rankQuestion(graph, rankingAskFrom(instruction), { limit: 48, topicTags });\n const context = buildSessionContext(graph, instruction, {\n budget,\n files,\n capsule: options.capsule,\n root,\n fsImpl,\n ranked,\n });\n\n // Per-model savings: the context build is VG Code's `query_graph`-equivalent.\n // Record it (counts only — never code or the instruction) tagged with the\n // model, so `vg savings` audits usage per model. Local-only, best-effort.\n if (options.attribution?.client) {\n const seedFiles = new Set(context.seeds.map((s) => s.node.file).filter(Boolean));\n recordCliCall(\n root,\n {\n tool: CLI_TOOL_ALIASES.ask,\n client: options.attribution.client,\n provider: options.attribution.provider,\n model: options.attribution.model,\n outcome: context.seeds.length ? 'complete' : 'miss',\n vgTokens: context.tokensEstimate,\n baselineFiles: seedFiles.size,\n },\n now(),\n );\n }\n\n // ── assess ──────────────────────────────────────────────────────────────\n phase('assess', 'asking the routed model for a minimal edit');\n const messages = buildMessages(context);\n const { result, provider, fellBack } = await complete(providers, messages, chatOptions, correlationId);\n\n const edits = parseEdits(result.text);\n const spans = spanIndex(graph);\n const applied = applyEdits(\n edits,\n (file) => fsImpl.read(file),\n (file) => spans.get(normalize(file)) ?? [],\n );\n\n const changes: FileChange[] = [];\n for (const [file, entry] of [...applied.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n changes.push({\n file,\n before: entry.before,\n after: entry.after,\n outcomes: entry.outcomes,\n diff: unifiedDiff(entry.before, entry.after, file),\n });\n }\n\n // ── dry-run (always produced) ─────────────────────────────────────────────\n phase('dry-run', `${changes.length} file(s) would change`);\n\n const anyApplicable = changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n const base: CodeSessionResult = {\n instruction,\n provider: { id: provider.id, model: provider.model, local: provider.local, fellBack },\n phasesRun,\n changes,\n applied: false,\n verification: { ran: false, ok: false, detail: 'dry-run — no changes written' },\n correlationId,\n };\n\n // ── approve ───────────────────────────────────────────────────────────────\n // Writing is opt-in AND consent-gated. A requested apply without consent is\n // not an error — it degrades to a dry-run so the caller can review, then\n // re-run with --yes. This is the \"never destructive-by-default\" guardrail.\n if (!apply) {\n if (!options.noAudit) writeAudit(fsImpl, base, now());\n return base;\n }\n if (!consent) {\n const stopped = { ...base, verification: { ran: false, ok: false, detail: 'apply requested without consent — re-run with --yes to write these changes' } };\n if (!options.noAudit) writeAudit(fsImpl, stopped, now());\n return stopped;\n }\n if (!anyApplicable) {\n const nothing = { ...base, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n if (!options.noAudit) writeAudit(fsImpl, nothing, now());\n return nothing;\n }\n phase('approve', 'consent given (--yes)');\n\n // ── execute ───────────────────────────────────────────────────────────────\n phase('execute', 'writing approved changes');\n for (const change of changes) {\n if (change.diff === '') continue; // no-op file\n if (!change.outcomes.some((o) => o.status === 'applied')) continue; // nothing applied cleanly here\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n\n // ── verify ────────────────────────────────────────────────────────────────\n phase('verify', 'confirming on-disk content matches the approved change');\n const verification = verifyWrites(fsImpl, changes);\n\n // ── log ───────────────────────────────────────────────────────────────────\n phase('log', 'recording an audit entry');\n const final: CodeSessionResult = { ...base, applied: true, verification };\n if (!options.noAudit) writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Commit an already-computed dry-run result: write the cleanly-applied changes,\n * verify them on disk, and append the audit record — the \"approve → execute →\n * verify → log\" tail of the lifecycle, run against a proposal the caller has\n * already shown and had approved (the interactive REPL uses this so it never\n * calls the model twice or writes something different from what was reviewed).\n */\nexport function commitChanges(result: CodeSessionResult, fsImpl: CodeFs, now: () => number = () => 0): CodeSessionResult {\n const anyApplicable = result.changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n if (!anyApplicable) {\n return { ...result, applied: false, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n }\n for (const change of result.changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n const verification = verifyWrites(fsImpl, result.changes);\n const final: CodeSessionResult = { ...result, applied: true, verification, phasesRun: [...result.phasesRun, 'approve', 'execute', 'verify', 'log'] };\n writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Undo a set of applied changes by restoring each file's prior content — the\n * `/undo` command. A created file (before === null) is removed; an edited or\n * deleted file is restored to its `before`. Only cleanly-applied changes are\n * reverted. Returns the files it restored.\n */\nexport function undoChanges(changes: FileChange[], fsImpl: CodeFs): string[] {\n const restored: string[] = [];\n for (const ch of changes) {\n if (!ch.outcomes.some((o) => o.status === 'applied')) continue;\n if (ch.before === null) fsImpl.remove(ch.file);\n else fsImpl.write(ch.file, ch.before);\n restored.push(ch.file);\n }\n return restored;\n}\n\nfunction buildSessionContext(\n graph: VgGraph,\n instruction: string,\n opts: { budget?: number; files?: string[]; capsule?: boolean; root: string; fsImpl: CodeFs; ranked?: SanitizedRank | null },\n): CodeContext {\n const budget = opts.budget;\n const files = opts.files;\n if (!opts.capsule) {\n return buildCodeContext(graph, instruction, { budget, files, ranked: opts.ranked });\n }\n const capsule = buildTaskCapsule(graph, instruction, {\n budget,\n files,\n readFile: (rel) => opts.fsImpl.read(rel),\n repositoryId: repositoryIdFromRoot(opts.root),\n ranked: opts.ranked,\n });\n return capsuleToCodeContext(capsule);\n}\n\n/** Try each provider in order; fall back on transport failure. Throws the last actionable error. */\nasync function complete(\n providers: Provider[],\n messages: ReturnType<typeof buildMessages>,\n chatOptions: ChatOptions | undefined,\n correlationId: string,\n): Promise<{ result: ProviderResult; provider: Provider; fellBack: boolean }> {\n if (providers.length === 0) throw new Error(`no model provider available (ref ${correlationId})`);\n let lastErr: unknown;\n for (let i = 0; i < providers.length; i++) {\n const provider = providers[i];\n try {\n const result = await provider.chat(messages, { temperature: 0, ...chatOptions });\n return { result, provider, fellBack: i > 0 };\n } catch (e) {\n lastErr = e;\n }\n }\n const message = lastErr instanceof Error ? redactSecrets(lastErr.message) : String(lastErr);\n throw new Error(`${message} (ref ${correlationId})`);\n}\n\n/** Confirm each written file's on-disk content equals what we approved. */\nfunction verifyWrites(fsImpl: CodeFs, changes: FileChange[]): { ran: boolean; ok: boolean; detail: string } {\n let checked = 0;\n const mismatches: string[] = [];\n for (const change of changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n checked++;\n const onDisk = fsImpl.read(change.file);\n if (onDisk !== change.after) mismatches.push(change.file);\n }\n if (mismatches.length) return { ran: true, ok: false, detail: `on-disk content differs for: ${mismatches.join(', ')}` };\n return { ran: true, ok: true, detail: `wrote and verified ${checked} file(s)` };\n}\n\n/** An append-only, secret-free audit record (GUARDRAILS §2.6 / §5). No file contents, no keys. */\nfunction writeAudit(fsImpl: CodeFs, r: CodeSessionResult, ts: number): void {\n const record = {\n ts,\n correlationId: r.correlationId,\n instruction: r.instruction.slice(0, 500),\n provider: r.provider.id,\n model: r.provider.model,\n local: r.provider.local,\n applied: r.applied,\n files: r.changes.map((c) => ({ file: c.file, statuses: c.outcomes.map((o) => o.status) })),\n verification: r.verification,\n phases: r.phasesRun,\n };\n try {\n fsImpl.appendAudit(JSON.stringify(record));\n } catch {\n /* audit is best-effort; never fail the run on a logging problem */\n }\n}\n\n/** Build a per-file map of symbol spans for graph-scoped edit disambiguation. */\nfunction spanIndex(graph: VgGraph): Map<string, SymbolSpan[]> {\n const map = new Map<string, SymbolSpan[]>();\n for (const n of graph.nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const file = normalize(n.file);\n const list = map.get(file) ?? [];\n list.push({ qualifiedName: n.qualifiedName, file, start: n.span.start, end: n.span.end });\n map.set(file, list);\n }\n return map;\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\n/** Default filesystem impl, scoped to `root`. Refuses paths that escape the root. */\nexport function nodeCodeFs(root: string): CodeFs {\n const resolve = (file: string): string => {\n const abs = path.resolve(root, file);\n const rel = path.relative(root, abs);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`edit path escapes the project root: ${file} — refusing to touch files outside ${root}`);\n }\n return abs;\n };\n return {\n read(file) {\n try {\n return fs.readFileSync(resolve(file), 'utf8');\n } catch {\n return null;\n }\n },\n write(file, content) {\n const abs = resolve(file);\n fs.mkdirSync(path.dirname(abs), { recursive: true });\n fs.writeFileSync(abs, content);\n },\n remove(file) {\n try {\n fs.rmSync(resolve(file));\n } catch {\n /* already gone */\n }\n },\n appendAudit(line) {\n const dir = path.join(root, '.vibgrate');\n fs.mkdirSync(dir, { recursive: true });\n fs.appendFileSync(path.join(dir, 'code-audit.jsonl'), line + '\\n');\n },\n };\n}\n\n/** Short, URL-safe correlation id. Not a graph artifact, so runtime randomness is fine here. */\nfunction shortId(): string {\n let s = '';\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';\n for (let i = 0; i < 8; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)];\n return s;\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// src/cli-options.ts
|
|
2
|
+
function applyGlobalOptions(cmd) {
|
|
3
|
+
return cmd.option("-C, --cwd <dir>", "run as if started in <dir>", ".").option("--deep", "do more: precise resolution, all edges, semantic links").option("--json", "machine-readable JSON on stdout").option("--generated-at <iso>", "pin the artifact timestamp for byte-deterministic output").option("--graph <file>", "override the map path").option("--no-cache", "full rebuild (ignore the incremental cache)").option("--offline", "never touch the network (no model download, no catalog fetch, no upload)").option("--local", "run inference on-device only \u2014 never a hosted model (implies --offline)").option("--quiet", "suppress progress output").option("--client <name>", "identify the AI client (e.g. claude) so navigation calls are counted in vg savings").option("--no-daemon", "never auto-start or use the local runtime (vgd) \u2014 run everything in this process").option("--no-color", "disable colored output");
|
|
4
|
+
}
|
|
5
|
+
function readGlobal(cmd) {
|
|
6
|
+
const o = cmd.optsWithGlobals();
|
|
7
|
+
return {
|
|
8
|
+
cwd: o.cwd,
|
|
9
|
+
deep: o.deep,
|
|
10
|
+
json: o.json,
|
|
11
|
+
generatedAt: o.generatedAt,
|
|
12
|
+
graph: o.graph,
|
|
13
|
+
noCache: o.cache === false,
|
|
14
|
+
// `--local` implies `--offline`: an on-device run has nothing to fetch, and
|
|
15
|
+
// folding it in here is what makes every existing `--local` invocation keep
|
|
16
|
+
// working without each consumer having to remember the implication.
|
|
17
|
+
offline: o.offline === true || o.local === true,
|
|
18
|
+
local: o.local,
|
|
19
|
+
quiet: o.quiet,
|
|
20
|
+
client: o.client,
|
|
21
|
+
daemon: o.daemon
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export { applyGlobalOptions, readGlobal };
|
|
26
|
+
//# sourceMappingURL=chunk-N6R4XPLX.js.map
|
|
27
|
+
//# sourceMappingURL=chunk-N6R4XPLX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli-options.ts"],"names":[],"mappings":";AAwDO,SAAS,mBAAmB,GAAA,EAAuB;AACxD,EAAA,OAAO,GAAA,CACJ,OAAO,iBAAA,EAAmB,4BAAA,EAA8B,GAAG,CAAA,CAC3D,MAAA,CAAO,QAAA,EAAU,wDAAwD,CAAA,CACzE,MAAA,CAAO,UAAU,iCAAiC,CAAA,CAClD,OAAO,sBAAA,EAAwB,0DAA0D,EACzF,MAAA,CAAO,gBAAA,EAAkB,uBAAuB,CAAA,CAChD,MAAA,CAAO,YAAA,EAAc,6CAA6C,CAAA,CAclE,MAAA,CAAO,aAAa,0EAA0E,CAAA,CAC9F,OAAO,SAAA,EAAW,8EAAyE,CAAA,CAC3F,MAAA,CAAO,SAAA,EAAW,0BAA0B,EAC5C,MAAA,CAAO,iBAAA,EAAmB,oFAAoF,CAAA,CAC9G,MAAA,CAAO,eAAe,uFAAkF,CAAA,CACxG,MAAA,CAAO,YAAA,EAAc,wBAAwB,CAAA;AAClD;AAGO,SAAS,WAAW,GAAA,EAA0B;AAInD,EAAA,MAAM,CAAA,GAAI,IAAI,eAAA,EAAgB;AAC9B,EAAA,OAAO;AAAA,IACL,KAAK,CAAA,CAAE,GAAA;AAAA,IACP,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,aAAa,CAAA,CAAE,WAAA;AAAA,IACf,OAAO,CAAA,CAAE,KAAA;AAAA,IACT,OAAA,EAAS,EAAE,KAAA,KAAU,KAAA;AAAA;AAAA;AAAA;AAAA,IAIrB,OAAA,EAAU,CAAA,CAAE,OAAA,KAAoC,IAAA,IAAS,EAAE,KAAA,KAAkC,IAAA;AAAA,IAC7F,OAAO,CAAA,CAAE,KAAA;AAAA,IACT,OAAO,CAAA,CAAE,KAAA;AAAA,IACT,QAAQ,CAAA,CAAE,MAAA;AAAA,IACV,QAAQ,CAAA,CAAE;AAAA,GACZ;AACF","file":"chunk-N6R4XPLX.js","sourcesContent":["import type { Command } from 'commander';\n\n/** Global flags shared across all `vg` commands (VG-CLI-SPEC §1.1). */\nexport interface GlobalOpts {\n /** -C, --cwd <dir> */\n cwd?: string;\n /** --deep */\n deep?: boolean;\n /** --json */\n json?: boolean;\n /** --generated-at <iso> */\n generatedAt?: string;\n /** --graph <file> (override the map path) */\n graph?: string;\n /** --no-cache (commander exposes this as `cache: false`) */\n noCache?: boolean;\n /**\n * `--offline` — never reach the network. Skip the embedding model, the\n * relevance module, the hosted catalog, and any upload.\n *\n * **Read this, not `local`, for every network decision.** `--local` implies\n * `--offline`, so this is already true whenever the user passed either.\n */\n offline?: boolean;\n /**\n * `--local` — run inference **on-device only**: pick a local backend\n * (embedded → ollama), never a hosted model. Consumed by `vg code` alone.\n *\n * It implies {@link offline} (an on-device run has nothing to fetch), which\n * is what keeps every pre-existing `--local` script working unchanged. The\n * converse does not hold: `--offline` says nothing about where inference runs.\n */\n local?: boolean;\n /** --quiet */\n quiet?: boolean;\n /**\n * --client <name> — the AI on the other end (e.g. `claude`, `cursor`). When an\n * AI host runs `vg`, passing this lets navigation calls be counted in the local\n * savings ledger with the command-vs-MCP split, so `vg savings` and the opt-in\n * share-stats upload can attribute usage. Counts only; a coarse label, not\n * identity (sanitized before it's recorded). Absent for human-run commands.\n */\n client?: string;\n /**\n * --no-daemon (commander exposes this as `daemon: false`) — never auto-start\n * or use the local runtime; run everything in this process, as vg did before\n * vgd existed. Also settable once via `VG_NO_DAEMON=1`.\n */\n daemon?: boolean;\n}\n\n/**\n * Attach the global flags to a command. They live on every subcommand (rather\n * than only the program) so the \"simple as Google\" dispatch can put the command\n * token first and let flags appear in any order after it.\n */\nexport function applyGlobalOptions(cmd: Command): Command {\n return cmd\n .option('-C, --cwd <dir>', 'run as if started in <dir>', '.')\n .option('--deep', 'do more: precise resolution, all edges, semantic links')\n .option('--json', 'machine-readable JSON on stdout')\n .option('--generated-at <iso>', 'pin the artifact timestamp for byte-deterministic output')\n .option('--graph <file>', 'override the map path')\n .option('--no-cache', 'full rebuild (ignore the incremental cache)')\n // Two distinct questions, two flags.\n //\n // `--offline` answers \"may this reach the network?\" — the same question\n // `vg scan --offline` and `vg evidence --offline` already answer, so the\n // whole CLI now spells it the same way.\n //\n // `--local` answers \"where does inference run?\" — on-device only, never a\n // hosted model. That is a choice you may want while fully online, which is\n // why it cannot simply be renamed: `vg code --local` on a connected machine\n // is meaningful, and `--offline` would not say it.\n //\n // `--local` implies `--offline`, so every script that already passes\n // `--local` keeps its exact current behaviour. The converse does not hold.\n .option('--offline', 'never touch the network (no model download, no catalog fetch, no upload)')\n .option('--local', 'run inference on-device only — never a hosted model (implies --offline)')\n .option('--quiet', 'suppress progress output')\n .option('--client <name>', 'identify the AI client (e.g. claude) so navigation calls are counted in vg savings')\n .option('--no-daemon', 'never auto-start or use the local runtime (vgd) — run everything in this process')\n .option('--no-color', 'disable colored output');\n}\n\n/** Read the global subset from a command's parsed options. */\nexport function readGlobal(cmd: Command): GlobalOpts {\n // `optsWithGlobals()`, not `opts()`: a global flag (e.g. `--json`) declared on\n // both a command and its parent binds to the parent in commander, so a nested\n // subcommand (`vg models uninstall … --json`) would otherwise never see it.\n const o = cmd.optsWithGlobals() as Record<string, unknown>;\n return {\n cwd: o.cwd as string | undefined,\n deep: o.deep as boolean | undefined,\n json: o.json as boolean | undefined,\n generatedAt: o.generatedAt as string | undefined,\n graph: o.graph as string | undefined,\n noCache: o.cache === false,\n // `--local` implies `--offline`: an on-device run has nothing to fetch, and\n // folding it in here is what makes every existing `--local` invocation keep\n // working without each consumer having to remember the implication.\n offline: (o.offline as boolean | undefined) === true || (o.local as boolean | undefined) === true,\n local: o.local as boolean | undefined,\n quiet: o.quiet as boolean | undefined,\n client: o.client as string | undefined,\n daemon: o.daemon as boolean | undefined,\n };\n}\n"]}
|