@vibgrate/cli 2026.721.3 → 2026.722.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/DOCS.md +185 -0
  2. package/README.md +2 -1
  3. package/dist/baseline-J44M7MWP.js +7 -0
  4. package/dist/{baseline-37G4TINM.js.map → baseline-J44M7MWP.js.map} +1 -1
  5. package/dist/chunk-2EVQKZTO.js +696 -0
  6. package/dist/chunk-2EVQKZTO.js.map +1 -0
  7. package/dist/chunk-6CXTPC74.js +234 -0
  8. package/dist/chunk-6CXTPC74.js.map +1 -0
  9. package/dist/chunk-CRAMOEBE.js +675 -0
  10. package/dist/chunk-CRAMOEBE.js.map +1 -0
  11. package/dist/chunk-CS37OBE3.js +861 -0
  12. package/dist/chunk-CS37OBE3.js.map +1 -0
  13. package/dist/chunk-CT5BS56U.js +23 -0
  14. package/dist/chunk-CT5BS56U.js.map +1 -0
  15. package/dist/{chunk-5PLKADD6.js → chunk-EXQV26MF.js} +4 -3
  16. package/dist/chunk-EXQV26MF.js.map +1 -0
  17. package/dist/chunk-GGJZA3Q6.js +961 -0
  18. package/dist/chunk-GGJZA3Q6.js.map +1 -0
  19. package/dist/chunk-JBXNQCGE.js +484 -0
  20. package/dist/chunk-JBXNQCGE.js.map +1 -0
  21. package/dist/chunk-JFGYT6BI.js +32 -0
  22. package/dist/chunk-JFGYT6BI.js.map +1 -0
  23. package/dist/{chunk-JLRF5TFA.js → chunk-JSNHZCIV.js} +42 -71
  24. package/dist/chunk-JSNHZCIV.js.map +1 -0
  25. package/dist/chunk-JYS4OBN2.js +148 -0
  26. package/dist/chunk-JYS4OBN2.js.map +1 -0
  27. package/dist/chunk-K3SLGULW.js +50 -0
  28. package/dist/chunk-K3SLGULW.js.map +1 -0
  29. package/dist/chunk-LEPTUB4H.js +108 -0
  30. package/dist/chunk-LEPTUB4H.js.map +1 -0
  31. package/dist/{chunk-IKJBELUV.js → chunk-PY3DNX5H.js} +4 -29
  32. package/dist/chunk-PY3DNX5H.js.map +1 -0
  33. package/dist/{chunk-ELUFCQDR.js → chunk-VXT6LUGP.js} +240 -2519
  34. package/dist/chunk-VXT6LUGP.js.map +1 -0
  35. package/dist/chunk-WNIIKCNF.js +972 -0
  36. package/dist/chunk-WNIIKCNF.js.map +1 -0
  37. package/dist/chunk-XKXKWYJF.js +417 -0
  38. package/dist/chunk-XKXKWYJF.js.map +1 -0
  39. package/dist/cli.js +2479 -1234
  40. package/dist/cli.js.map +1 -1
  41. package/dist/fs-KCABDURV.js +3 -0
  42. package/dist/fs-KCABDURV.js.map +1 -0
  43. package/dist/index.d.ts +3 -1
  44. package/dist/index.js +8 -3
  45. package/dist/index.js.map +1 -1
  46. package/dist/interactive-736PBC7J.js +820 -0
  47. package/dist/interactive-736PBC7J.js.map +1 -0
  48. package/dist/mcp-tools-I6PME3AV.js +3 -0
  49. package/dist/mcp-tools-I6PME3AV.js.map +1 -0
  50. package/dist/parse-worker.js +2 -1
  51. package/dist/parse-worker.js.map +1 -1
  52. package/dist/session-POJUDFPH.js +6 -0
  53. package/dist/session-POJUDFPH.js.map +1 -0
  54. package/dist/session-store-W5RZZHA3.js +3 -0
  55. package/dist/session-store-W5RZZHA3.js.map +1 -0
  56. package/dist/stream-json-Q2JGWPHB.js +65 -0
  57. package/dist/stream-json-Q2JGWPHB.js.map +1 -0
  58. package/dist/ui-HOVOPWMX.js +4 -0
  59. package/dist/ui-HOVOPWMX.js.map +1 -0
  60. package/package.json +1 -1
  61. package/dist/baseline-37G4TINM.js +0 -6
  62. package/dist/chunk-5PLKADD6.js.map +0 -1
  63. package/dist/chunk-ELUFCQDR.js.map +0 -1
  64. package/dist/chunk-IKJBELUV.js.map +0 -1
  65. package/dist/chunk-JLRF5TFA.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/util/logo.ts","../src/engine/attest.ts","../src/commands/attest-actions.ts","../src/util/progress.ts","../src/cli-options.ts","../src/commands/build.ts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,MAAM,IAAI,QAAA,CAAS,CAAA,WAAA,EAAc,OAAO,CAAA,mGAAA,CAAA,EAAuG,SAAS,SAAS,CAAA;AACnK;AAEA,SAAS,kBAAA,CAAmB,IAAA,EAAoB,GAAA,EAAwB,EAAA,EAAoB;AAC1F,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,IAAS,GAAA,CAAI,aAAA;AAChC,EAAA,IAAI,OAAO,OAAO,KAAA;AAClB,EAAA,MAAM,IAAI,QAAA;AAAA,IACR,CAAA,EAAG,iBAAA,CAAkB,EAAE,CAAA,CAAE,KAAK,CAAA,2KAAA,CAAA;AAAA,IAC9B,QAAA,CAAS;AAAA,GACX;AACF;AAEA,SAAS,cAAA,CAAe,QAAsB,OAAA,EAAoD;AAEhG,EAAA,MAAM,IAAI,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,YAAY,OAAO,CAAA;AAClD,EAAA,OAAO,CAAA,EAAG,IAAA;AACZ;AAEA,SAAS,aAAa,QAAA,EAA4C;AAChE,EAAA,IAAI;AACF,IAAA,OAAO,QAAA,EAAS;AAAA,EAClB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAEA,SAASD,UAAS,CAAA,EAAmB;AACnC,EAAA,OAAO,CAAA,CAAE,QAAQ,KAAA,EAAO,GAAG,EAAE,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,EAAI,IAAK,CAAA;AACnD","file":"chunk-2EVQKZTO.js","sourcesContent":["import { c } from './output.js';\nimport { VERSION } from '../version.js';\n\n/**\n * The `vg` brand banner — the same boxy robot mark and brand colours (teal/mint)\n * as the Vibgrate scanner (`vibgrate-cli/src/ui/progress.ts`), replicated here so\n * the open graph package stays standalone.\n *\n * The wordmark is stacked BELOW the mark rather than beside it: the robot's eye\n * (`◼`) and arrow (`➜`) glyphs are East-Asian \"ambiguous\"/wide, so terminals that\n * render them double-width make the rows unequal — text placed to their right\n * (the scanner's layout) then misaligns. Nothing sits beside the art here, so the\n * banner lines up in every terminal. Shown on `vg build` for a human at a TTY;\n * never on `--json`, `--quiet`, or under a pipe.\n */\n\nconst teal = (s: string): string => c.hex('#3FB0A4')(s);\nconst mint = (s: string): string => c.hex('#4FE3C1')(s);\n\n// ── Boxy robot mark — identical glyphs/colours to the scanner's ROBOT ──\nconst ROBOT = [\n ' ' + teal('╭──────╮') + mint('➜'),\n ' ' + c.dim('┤') + teal('│') + ' ' + mint('◼') + ' ' + mint('◼') + ' ' + teal('│') + c.dim('├'),\n ' ' + c.dim('┤') + teal('│') + ' ' + c.dim('▁▁') + ' ' + teal('│') + c.dim('├'),\n ' ' + teal('╰──────╯'),\n] as const;\n\n/**\n * The banner as lines (no I/O) so it is unit-testable. The robot mark is a\n * self-contained block; the wordmark/tagline sit on their OWN lines beneath it\n * (never beside the variable-width glyphs), so the banner aligns in any terminal.\n */\nexport function logoLines(root?: string, opts: { product?: string; tagline?: string } = {}): string[] {\n const product = opts.product ?? 'Graph';\n const tagline = opts.tagline ?? 'Code Intelligence Engine';\n return [\n '',\n ` ${ROBOT[0]}`,\n ` ${ROBOT[1]}`,\n ` ${ROBOT[2]}`,\n ` ${ROBOT[3]}`,\n ` ${c.bold.white('Vibgrate')} ${teal(product)} ${c.dim(`· ${tagline} · v${VERSION}`)}`,\n ...(root ? [` ${c.dim(root)}`] : []),\n '',\n ];\n}\n\n/** Print the banner to stderr, only for an interactive human (TTY). */\nexport function printLogo(root?: string, opts: { product?: string; tagline?: string } = {}): void {\n if (!process.stderr.isTTY) return;\n process.stderr.write(`${logoLines(root, opts).join('\\n')}\\n`);\n}\n\n/**\n * The **VG Code** banner (the approved marketing name for the code-editing\n * capability; see docs/NAMING-AND-MARKETING-STRATEGY.md). Same robot mark, but\n * the wordmark reads \"VG Code\" rather than \"Vibgrate Graph\".\n */\nexport function codeLogoLines(root?: string): string[] {\n return [\n '',\n ` ${ROBOT[0]}`,\n ` ${ROBOT[1]}`,\n ` ${ROBOT[2]}`,\n ` ${ROBOT[3]}`,\n ` ${c.bold.white('VG')} ${teal('Code')} ${c.dim(`· graph-grounded coding · v${VERSION}`)}`,\n ...(root ? [` ${c.dim(root)}`] : []),\n '',\n ];\n}\n\n/** Print the VG Code banner to stderr, only for an interactive human (TTY). */\nexport function printCodeLogo(root?: string): void {\n if (!process.stderr.isTTY) return;\n process.stderr.write(`${codeLogoLines(root).join('\\n')}\\n`);\n}\n","import * as crypto from 'node:crypto';\nimport { canonicalize } from './hash.js';\nimport { VERSION } from '../version.js';\nimport type { Toolchain, VgGraph } from '../schema.js';\n\n/**\n * `vg attest` — a signed, reproducible attestation over the code graph.\n *\n * This is the moat made load-bearing: a consumer can cryptographically verify,\n * offline, that a graph was produced by a named toolchain over a named commit and\n * has not changed since. We sign an in-toto Statement wrapped in a DSSE envelope\n * with Ed25519 (`node:crypto`, zero dependencies) — interoperable with\n * `cosign verify-blob-attestation`. Ed25519 signatures are deterministic\n * (RFC 8032), so the same graph + key produce a byte-identical envelope.\n *\n * The subject digest excludes the graph's volatile `generatedAt`, so it is\n * reproducible across rebuilds of identical content — which is exactly what makes\n * the attestation verifiable rather than a timestamped snapshot.\n */\n\nexport const DSSE_PAYLOAD_TYPE = 'application/vnd.in-toto+json';\nexport const IN_TOTO_STATEMENT_TYPE = 'https://in-toto.io/Statement/v1';\nexport const VG_PREDICATE_TYPE = 'https://vibgrate.com/attestation/code-graph/v1';\n\nexport interface CommitInfo {\n sha?: string;\n shortSha?: string;\n branch?: string;\n dirty?: boolean; // uncommitted changes vs sha — never verified-clean when true\n}\n\nexport interface AttestPredicate {\n tool: { name: 'vg'; version: string };\n toolchain?: Toolchain;\n corpusHash: string;\n graphDigest: string; // sha256 of the canonical graph (generatedAt excluded)\n counts: VgGraph['meta']['counts'];\n commit?: CommitInfo;\n sbomDigest?: string; // sha256 of an accompanying SBOM, if attested together\n timestamp?: string; // optional, opt-in (omitted by default for determinism)\n}\n\nexport interface InTotoStatement {\n _type: string;\n subject: { name: string; digest: { sha256: string } }[];\n predicateType: string;\n predicate: AttestPredicate;\n}\n\nexport interface DsseSignature {\n keyid: string;\n sig: string; // base64\n publicKey?: string; // PEM, embedded so the envelope self-verifies for integrity\n}\n\nexport interface DsseEnvelope {\n payloadType: string;\n payload: string; // base64 of the Statement JSON\n signatures: DsseSignature[];\n}\n\nexport function sha256Hex(input: string | Uint8Array): string {\n return crypto.createHash('sha256').update(input).digest('hex');\n}\n\n/**\n * sha256 over the canonical graph with the volatile `generatedAt` excluded, so\n * two builds of identical content attest to the same digest.\n */\nexport function graphSubjectDigest(graph: VgGraph): string {\n const { generatedAt: _omit, ...rest } = graph;\n return sha256Hex(canonicalize(rest));\n}\n\n/** The 16-hex key id: a truncated sha256 over the SPKI DER public key. */\nexport function keyId(publicKey: crypto.KeyObject): string {\n return sha256Hex(publicKey.export({ type: 'spki', format: 'der' })).slice(0, 16);\n}\n\nexport interface StatementInput {\n commit?: CommitInfo;\n sbomDigest?: string;\n timestamp?: string;\n}\n\nexport function buildStatement(graph: VgGraph, input: StatementInput = {}): InTotoStatement {\n const graphDigest = graphSubjectDigest(graph);\n const predicate: AttestPredicate = {\n tool: { name: 'vg', version: VERSION },\n toolchain: graph.provenance.toolchain,\n corpusHash: graph.provenance.corpusHash,\n graphDigest,\n counts: graph.meta.counts,\n };\n if (input.commit) predicate.commit = input.commit;\n if (input.sbomDigest) predicate.sbomDigest = input.sbomDigest;\n if (input.timestamp) predicate.timestamp = input.timestamp;\n return {\n _type: IN_TOTO_STATEMENT_TYPE,\n subject: [{ name: 'graph.json', digest: { sha256: graphDigest } }],\n predicateType: VG_PREDICATE_TYPE,\n predicate,\n };\n}\n\n/**\n * DSSE Pre-Authentication Encoding:\n * \"DSSEv1\" SP len(type) SP type SP len(body) SP body\n * with lengths as ASCII decimal byte counts. Signing the PAE (not the raw body)\n * is what binds the payloadType to the signature.\n */\nexport function dssePae(payloadType: string, body: Uint8Array): Buffer {\n const typeBytes = Buffer.from(payloadType, 'utf8');\n const header = Buffer.from(\n `DSSEv1 ${typeBytes.length} ${payloadType} ${body.length} `,\n 'utf8',\n );\n return Buffer.concat([header, Buffer.from(body)]);\n}\n\n/** Sign a statement, returning a self-contained DSSE envelope. */\nexport function signStatement(statement: InTotoStatement, privateKey: crypto.KeyObject): DsseEnvelope {\n const body = Buffer.from(JSON.stringify(statement), 'utf8');\n const pae = dssePae(DSSE_PAYLOAD_TYPE, body);\n const sig = crypto.sign(null, pae, privateKey);\n // Derive the public key from the private key (via its PEM, for @types/node compat).\n const publicKey = crypto.createPublicKey(privateKey.export({ type: 'pkcs8', format: 'pem' }).toString());\n return {\n payloadType: DSSE_PAYLOAD_TYPE,\n payload: body.toString('base64'),\n signatures: [\n {\n keyid: keyId(publicKey),\n sig: sig.toString('base64'),\n publicKey: publicKey.export({ type: 'spki', format: 'pem' }).toString(),\n },\n ],\n };\n}\n\nexport type AttestStatus = 'verified' | 'signature-valid' | 'failed';\n\nexport interface VerifyResult {\n status: AttestStatus;\n signatureValid: boolean;\n signerPinned: boolean; // signature verified against a caller-supplied trusted key\n digestMatches?: boolean; // recomputed graph digest matches the attested one\n dirty?: boolean; // the attested commit had uncommitted changes\n keyid: string;\n reason: string;\n statement: InTotoStatement;\n}\n\n/**\n * Verify an envelope. Honest states, never a fabricated pass:\n * failed — bad signature, or the on-disk graph no longer matches.\n * signature-valid — cryptographically intact, but signer not pinned (or dirty).\n * verified — pinned signer + matching digest + clean tree.\n */\n/** An empty statement for results where the envelope could not even be parsed. */\nfunction emptyStatement(): InTotoStatement {\n return {\n _type: '',\n subject: [],\n predicateType: '',\n predicate: {\n tool: { name: 'vg', version: '' },\n corpusHash: '',\n graphDigest: '',\n counts: { nodes: 0, edges: 0, areas: 0, tests: 0, untested: 0 },\n },\n };\n}\n\nfunction failedResult(reason: string): VerifyResult {\n return {\n status: 'failed',\n signatureValid: false,\n signerPinned: false,\n keyid: '',\n reason,\n statement: emptyStatement(),\n };\n}\n\nexport function verifyEnvelope(\n env: DsseEnvelope,\n opts: { publicKeyPem?: string; graph?: VgGraph } = {},\n): VerifyResult {\n // A `.intoto.jsonl` is attacker-supplied input: every decode/parse/key step\n // must degrade to an honest `failed`, never crash the command.\n let body: Buffer;\n let statement: InTotoStatement;\n try {\n body = Buffer.from(env?.payload ?? '', 'base64');\n const parsed = JSON.parse(body.toString('utf8')) as InTotoStatement;\n if (!parsed || typeof parsed !== 'object' || !parsed.predicate) {\n throw new Error('missing predicate');\n }\n statement = parsed;\n } catch {\n return failedResult('malformed attestation payload (not a valid in-toto statement)');\n }\n\n const pae = dssePae(env.payloadType, body);\n const sig0 = env.signatures?.[0];\n const keyid = sig0?.keyid ?? '';\n const sig = sig0?.sig ? Buffer.from(sig0.sig, 'base64') : Buffer.alloc(0);\n\n let signatureValid = false;\n let signerPinned = false;\n try {\n if (sig0 && sig.length) {\n if (opts.publicKeyPem) {\n const pinnedKey = crypto.createPublicKey(opts.publicKeyPem);\n signatureValid = crypto.verify(null, pae, pinnedKey, sig);\n signerPinned = signatureValid;\n } else if (sig0.publicKey) {\n const embeddedKey = crypto.createPublicKey(sig0.publicKey);\n signatureValid = crypto.verify(null, pae, embeddedKey, sig);\n }\n }\n } catch {\n // Malformed key or signature bytes → not a valid signature (not a crash).\n signatureValid = false;\n signerPinned = false;\n }\n\n const digestMatches = opts.graph\n ? graphSubjectDigest(opts.graph) === statement.predicate.graphDigest\n : undefined;\n const dirty = statement.predicate.commit?.dirty;\n\n let status: AttestStatus;\n let reason: string;\n if (!signatureValid) {\n status = 'failed';\n reason = sig0 ? 'signature verification failed' : 'no signature in envelope';\n } else if (digestMatches === false) {\n status = 'failed';\n reason = 'graph.json no longer matches the attested digest (content changed since signing)';\n } else if (signerPinned && !dirty) {\n status = 'verified';\n reason =\n digestMatches === true\n ? 'signature valid, signer trusted, graph digest matches'\n : 'signature valid, signer trusted';\n } else {\n status = 'signature-valid';\n reason = dirty\n ? 'signature valid but the attested tree was dirty (uncommitted changes)'\n : 'signature valid but signer not pinned — pass --pub to establish trust';\n }\n\n return { status, signatureValid, signerPinned, digestMatches, dirty, keyid, reason, statement };\n}\n\nexport interface GeneratedKeypair {\n privatePem: string;\n publicPem: string;\n keyid: string;\n}\n\n/** Mint a fresh Ed25519 keypair for signing attestations. */\nexport function generateKeypair(): GeneratedKeypair {\n const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');\n return {\n privatePem: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),\n publicPem: publicKey.export({ type: 'spki', format: 'pem' }).toString(),\n keyid: keyId(publicKey),\n };\n}\n\n/** Serialize an envelope as a single-line `.intoto.jsonl` record (deterministic). */\nexport function serializeEnvelope(env: DsseEnvelope): string {\n return `${JSON.stringify(env)}\\n`;\n}\n\nexport function parseEnvelope(text: string): DsseEnvelope {\n const line = text.trim().split('\\n')[0];\n return JSON.parse(line) as DsseEnvelope;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as crypto from 'node:crypto';\nimport { execFile } from 'node:child_process';\nimport { loadGraph } from '../engine/load.js';\nimport { resolveHead, workingTreeDirty } from '../core-open/utils/git-history.js';\nimport {\n buildStatement,\n signStatement,\n verifyEnvelope,\n generateKeypair,\n serializeEnvelope,\n parseEnvelope,\n type CommitInfo,\n type VerifyResult,\n} from '../engine/attest.js';\nimport { CliError, ExitCode } from '../util/exit.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * Attestation actions folded into the graph lifecycle: `vg build --attest` signs\n * the graph it just built; `vg build --verify` checks a committed attestation.\n * The crypto lives in engine/attest.ts; this is the file/key/git glue + output.\n */\n\nconst DEFAULT_ATTESTATION = 'attestation.intoto.jsonl';\nconst DEFAULT_KEY = 'attest-key.pem';\n\nexport interface SignOpts {\n /** Signing key PEM path; else $VG_ATTEST_KEY; else .vibgrate/attest-key.pem (auto-minted). */\n key?: string;\n /** Output path for the attestation (default .vibgrate/attestation.intoto.jsonl). */\n attestation?: string;\n}\n\nexport interface SignSummary {\n keyid: string;\n graphDigest: string;\n fingerprint?: string;\n commit?: CommitInfo;\n out: string;\n keyGeneratedAt?: string;\n}\n\n/** Sign an already-built graph, writing a DSSE attestation. Returns a summary +\n * human notices (the caller decides how to render them alongside build output). */\nexport async function signGraphAttestation(\n root: string,\n graph: VgGraph,\n opts: SignOpts,\n): Promise<{ summary: SignSummary; notices: string[] }> {\n const notices: string[] = [];\n const explicitKey = opts.key ?? process.env.VG_ATTEST_KEY;\n const keyPath = explicitKey ? path.resolve(explicitKey) : path.join(root, '.vibgrate', DEFAULT_KEY);\n\n let keyGeneratedAt: string | undefined;\n if (!fs.existsSync(keyPath)) {\n if (explicitKey) {\n throw new CliError(`signing key not found: ${explicitKey}`, ExitCode.USAGE_ERROR);\n }\n // First use with no key: mint one at the default path (loud — it must be kept\n // and gitignored to re-sign reproducibly).\n const kp = generateKeypair();\n fs.mkdirSync(path.dirname(keyPath), { recursive: true });\n fs.writeFileSync(keyPath, kp.privatePem, { mode: 0o600 });\n fs.writeFileSync(`${keyPath}.pub`, kp.publicPem);\n keyGeneratedAt = keyPath;\n notices.push(\n `minted a new Ed25519 signing key at ${rel(root, keyPath)} (keyid ${kp.keyid}) — ` +\n `keep it, add it to .gitignore, and reuse it to re-sign reproducibly`,\n );\n }\n\n let privateKey: crypto.KeyObject;\n try {\n privateKey = crypto.createPrivateKey(fs.readFileSync(keyPath, 'utf8'));\n } catch {\n throw new CliError(`could not read an Ed25519 private key from ${rel(root, keyPath)}`, ExitCode.USAGE_ERROR);\n }\n if (privateKey.asymmetricKeyType !== 'ed25519') {\n throw new CliError(\n `attest requires an Ed25519 key, but ${rel(root, keyPath)} is ${privateKey.asymmetricKeyType ?? 'unknown'}`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const commit = await gitCommitInfo(root);\n const statement = buildStatement(graph, { commit });\n const envelope = signStatement(statement, privateKey);\n const outPath = opts.attestation\n ? path.resolve(opts.attestation)\n : path.join(root, '.vibgrate', DEFAULT_ATTESTATION);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, serializeEnvelope(envelope));\n\n return {\n summary: {\n keyid: envelope.signatures[0]?.keyid ?? '',\n graphDigest: statement.predicate.graphDigest,\n fingerprint: statement.predicate.toolchain?.fingerprint,\n commit,\n out: rel(root, outPath),\n keyGeneratedAt: keyGeneratedAt ? rel(root, keyGeneratedAt) : undefined,\n },\n notices,\n };\n}\n\nexport interface VerifyOpts {\n /** Attestation path (default .vibgrate/attestation.intoto.jsonl). */\n attestation?: string;\n /** Public key PEM to pin the signer (else integrity-only verification). */\n pub?: string;\n}\n\nexport interface AttestVerifyOutcome {\n bundlePath: string;\n /** True when no attestation exists at the default path (and none was required). */\n missing: boolean;\n result?: VerifyResult;\n}\n\n/** Verify a committed attestation against the on-disk graph. Returns the outcome\n * (the caller renders + decides the exit code). Throws only when an attestation\n * was explicitly requested but is absent. */\nexport function verifyGraphAttestation(root: string, opts: VerifyOpts): AttestVerifyOutcome {\n const bundlePath = opts.attestation\n ? path.resolve(opts.attestation)\n : path.join(root, '.vibgrate', DEFAULT_ATTESTATION);\n if (!fs.existsSync(bundlePath)) {\n if (opts.attestation || opts.pub) {\n throw new CliError(\n `no attestation at ${rel(root, bundlePath)} — sign one with \\`vg build --attest\\``,\n ExitCode.NOT_FOUND,\n );\n }\n return { bundlePath, missing: true };\n }\n const envelope = parseEnvelope(fs.readFileSync(bundlePath, 'utf8'));\n const publicKeyPem = opts.pub ? fs.readFileSync(path.resolve(opts.pub), 'utf8') : undefined;\n const graph = loadGraph(root) ?? undefined;\n return { bundlePath, missing: false, result: verifyEnvelope(envelope, { publicKeyPem, graph }) };\n}\n\nasync function gitCommitInfo(root: string): Promise<CommitInfo | undefined> {\n const sha = await resolveHead(root);\n if (!sha) return undefined;\n const dirty = await workingTreeDirty(root);\n const branch = await gitBranch(root);\n return { sha, shortSha: sha.slice(0, 7), branch, dirty: dirty === true ? true : dirty === false ? false : undefined };\n}\n\n/** Best-effort current branch name; undefined on detached HEAD or no git. */\nfunction gitBranch(root: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['rev-parse', '--abbrev-ref', 'HEAD'],\n { cwd: root, timeout: 5000, windowsHide: true, encoding: 'utf8' },\n (err, stdout) => {\n if (err) return resolve(undefined);\n const name = String(stdout).trim();\n resolve(name && name !== 'HEAD' ? name : undefined);\n },\n );\n });\n}\n\nfunction rel(root: string, p: string): string {\n const r = path.relative(root, p);\n return r.startsWith('..') ? p : r;\n}\n","import { c } from './output.js';\nimport { brandProgressBar } from '../core-open/ui/bar.js';\n\n/**\n * A small progress bar matching the scanner's style\n * (`vibgrate-core-open/src/ui/progress.ts`): a smooth sub-cell gradient bar\n * (shared `brandProgressBar`), a braille spinner, percent, elapsed and ETA.\n * Renders to **stderr** in place, and only when stderr is a TTY — under a\n * pipe/CI it stays silent so logs aren't polluted.\n */\n\nconst FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const;\nconst WIDTH = 30;\n\nfunction fmtDuration(ms: number): string {\n const s = Math.max(0, Math.round(ms / 1000));\n if (s < 60) return `${s}s`;\n return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`;\n}\n\n/**\n * Pure render of one progress line (no I/O, no clock) so it is unit-testable.\n * `elapsedMs` and `frame` are passed in by the caller.\n */\nexport function formatProgressLine(\n label: string,\n done: number,\n total: number,\n elapsedMs: number,\n frame: number,\n): string {\n const ratio = total > 0 ? Math.min(done / total, 1) : 0;\n const bar = brandProgressBar(ratio, WIDTH);\n const pct = Math.round(ratio * 100);\n const spin = c.cyan(FRAMES[((frame % FRAMES.length) + FRAMES.length) % FRAMES.length]);\n const eta = ratio > 0.02 && ratio < 1 ? ` · eta ${fmtDuration((elapsedMs / ratio) * (1 - ratio))}` : '';\n return ` ${spin} ${label} ${bar} ${c.bold(`${pct}%`)} ${c.dim(`${done}/${total} · ${fmtDuration(elapsedMs)}${eta}`)}`;\n}\n\n/** Live, in-place progress bar on stderr (no-op when stderr isn't a TTY). */\nexport class ProgressBar {\n private readonly start = Date.now();\n private frame = 0;\n private readonly tty = Boolean(process.stderr.isTTY);\n\n constructor(private readonly label: string) {}\n\n update(done: number, total: number): void {\n if (!this.tty) return;\n const line = formatProgressLine(this.label, done, total, Date.now() - this.start, this.frame++);\n process.stderr.write(`\\r\\x1b[2K${line}`);\n }\n\n /** Clear the bar; optionally print a final summary line. */\n done(summary?: string): void {\n if (!this.tty) return;\n process.stderr.write('\\r\\x1b[2K');\n if (summary) process.stderr.write(`${summary}\\n`);\n }\n}\n","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 /** --local (never touch the network) */\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\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 .option('--local', 'never touch the network (lexical-only semantic)')\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-color', 'disable colored output');\n}\n\n/** Read the global subset from a command's parsed options. */\nexport function readGlobal(cmd: Command): GlobalOpts {\n const o = cmd.opts<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: o.local as boolean | undefined,\n quiet: o.quiet as boolean | undefined,\n client: o.client as string | undefined,\n };\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 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 { serializeGraph } from '../engine/serialize.js';\nimport { renderReport } from '../engine/report.js';\nimport { renderHtml } from '../engine/html.js';\nimport { UsageError } from '../engine/discover.js';\nimport { ResourceLimitError } from '../engine/limits.js';\nimport { CliError, ExitCode, usageError } from '../util/exit.js';\nimport { 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 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('--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 async function runBuild(\n paths: string[],\n opts: BuildCmdOpts,\n global: GlobalOpts,\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).\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 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 generatedAt: global.generatedAt,\n onParseProgress: bar ? (done, total) => bar.update(done, total) : undefined,\n grammarsDir: opts.grammars,\n });\n } catch (err) {\n bar?.done();\n if (err instanceof UsageError) throw usageError(err.message);\n // A resource safeguard fired (file-count cap, heap budget, worker OOM) —\n // the message already carries the remedy; surface it without a stack.\n if (err instanceof ResourceLimitError) throw new CliError(err.message, ExitCode.ERROR);\n throw err;\n }\n bar?.done();\n\n const written = writeArtifacts(result.graph, {\n root,\n html: opts.html,\n report: opts.report,\n graphPath: global.graph,\n });\n\n // Record the freshness snapshot (stat+hash per corpus file, plus this build's\n // scope) so `vg serve`/`vg ask` can auto-refresh the map when the tree drifts.\n // Skipped for a custom --graph target: that is an explicit artifact the\n // auto-refresh machinery must not manage.\n if (!global.graph) {\n writeSnapshot(root, result.graph.provenance.corpusHash, result.fileStats, {\n only,\n exclude: opts.exclude,\n paths: paths.length ? paths : undefined,\n deep: global.deep,\n noGround: opts.ground === false,\n scip: typeof opts.scip === 'string' ? opts.scip : undefined,\n noScip: opts.scip === false,\n noTsc: opts.tsc === false,\n grammarsDir: opts.grammars,\n });\n }\n\n 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 }\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 });\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 maybeWarmEmbeddings(root, result.graph, global, opts.warm !== false);\n}\n\n/**\n * `vg build --verify` — the single verification entry point. Runs the determinism\n * self-check (byte-identical rebuilds + toolchain fingerprint) and, when an\n * attestation is present, verifies it against the on-disk graph. Exit 4 on a\n * determinism failure, exit 2 on an attestation failure.\n */\nasync function verifyGraph(root: string, opts: BuildCmdOpts, global: GlobalOpts): Promise<void> {\n const only = opts.only ? opts.only.split(',').map((s) => s.trim()).filter(Boolean) : undefined;\n const jobs = opts.jobs ? Number(opts.jobs) : undefined;\n const det = await verifyDeterminism({ root, only, exclude: opts.exclude, jobs });\n const attest = verifyGraphAttestation(root, { attestation: opts.attestation, pub: opts.pub });\n const attestFailed = !attest.missing && attest.result?.status === 'failed';\n\n if (global.json) {\n json({\n ok: det.ok && !attestFailed,\n determinism: { ok: det.ok, checks: det.checks, digest: det.digest },\n attestation: attest.missing\n ? null\n : {\n status: attest.result?.status,\n signatureValid: attest.result?.signatureValid,\n signerPinned: attest.result?.signerPinned,\n digestMatches: attest.result?.digestMatches,\n dirty: attest.result?.dirty,\n keyid: attest.result?.keyid,\n reason: attest.result?.reason,\n },\n });\n } else {\n info(`${c.cyan('vg build --verify')} · ${path.relative(process.cwd(), root) || '.'}`);\n for (const check of det.checks) {\n const mark = check.ok ? c.green('✔') : c.red('✘');\n const detail = check.detail ? c.dim(` (${check.detail})`) : '';\n info(` ${mark} ${check.name}${detail}`);\n }\n info(det.ok ? c.green(` deterministic · digest ${det.digest.slice(0, 16)}…`) : c.red(' NON-DETERMINISTIC'));\n if (attest.missing) {\n info(c.dim(` attestation: none (sign one with \\`vg build --attest\\`)`));\n } else {\n const r = attest.result;\n const badge =\n r?.status === 'verified'\n ? c.green('✔ attestation verified')\n : r?.status === 'signature-valid'\n ? c.yellow('~ attestation signature valid')\n : c.red('✘ attestation failed');\n info(` ${badge}${r?.keyid ? c.dim(` · keyid ${r.keyid}`) : ''}`);\n info(c.dim(` ${r?.reason ?? ''}`));\n }\n }\n\n if (!det.ok) throw new CliError('determinism self-check failed', ExitCode.NON_DETERMINISTIC);\n if (attestFailed) throw new CliError('attestation verification failed', ExitCode.GATE_FAILED);\n}\n\n/**\n * After an interactive build we have just committed to a code graph, so the\n * user is likely to run `vg ask`/`vg serve` next — start warming the semantic\n * index in the background now so that first semantic call is instant instead of\n * paying a cold model load. If the model isn't downloaded yet, the background\n * warm fetches it (once, centrally) rather than deferring the whole cost to the\n * first `ask`. Disabled with `--no-warm`; skipped under --json/--quiet/--local\n * and when not at a TTY (so CI never auto-downloads). The detached child runs\n * `vg embed --bg [--download]`; a lock prevents it racing a foreground `ask`.\n */\nfunction maybeWarmEmbeddings(root: string, graph: VgGraph, global: GlobalOpts, warm: boolean): void {\n if (!warm || global.json || global.quiet || global.local) return;\n if (!process.stdout.isTTY && !process.stderr.isTTY) return;\n const cli = process.argv[1];\n if (!cli) return;\n const modelId = resolveEmbedModel();\n const ready = isModelReady(modelId);\n // Already fully warm: model present and every node embedded → nothing to do.\n if (ready && countPending(graph, root, modelId) === 0) return;\n // When the model isn't on this machine yet, start the one-time download now\n // (the graph is built; the next semantic call shouldn't wait for it).\n const args = ready\n ? [cli, 'embed', '-C', root, '--bg']\n : [cli, 'embed', '-C', root, '--bg', '--download'];\n try {\n const child = spawn(process.execPath, args, { detached: true, stdio: 'ignore' });\n child.unref();\n info(\n c.dim(\n ready\n ? ' warming the semantic index in the background — `vg ask` will be instant'\n : ' downloading the semantic model in the background (once) — `vg ask`/`vg serve` will be instant; disable with --no-warm',\n ),\n );\n } catch {\n /* warm-up is best-effort */\n }\n}\n\nfunction writeExport(graph: Parameters<typeof serializeGraph>[0], target: string): void {\n if (target === '-') {\n out(serializeGraph(graph).trimEnd());\n return;\n }\n const ext = path.extname(target).toLowerCase();\n let content: string;\n switch (ext) {\n case '.json':\n content = serializeGraph(graph);\n break;\n case '.md':\n content = renderReport(graph);\n break;\n case '.html':\n content = renderHtml(graph);\n break;\n default:\n throw new CliError(\n `cannot export to \"${ext || target}\" yet — supported in Phase 0: .json, .md, .html, \"-\" (stdout). ` +\n `More formats (graphml, dot, cypher) arrive with \\`vg export\\` in Phase 1.`,\n ExitCode.USAGE_ERROR,\n );\n }\n fs.mkdirSync(path.dirname(path.resolve(target)), { recursive: true });\n fs.writeFileSync(target, content);\n}\n\nfunction collect(value: string, prev: string[]): string[] {\n return [...prev, value];\n}\n\nfunction rel(root: string): string {\n const r = path.relative(process.cwd(), root);\n return r === '' ? '.' : r;\n}\n","/**\n * Model routing for `vg code` (VG-CLI-CODE §5.2).\n *\n * The \"best in breed\" story is an ordered set of backends with automatic\n * fallback — the OpenRouter/LiteLLM model — expressed as a *scheduling* decision\n * the session can execute: try the preferred provider, and on a transport\n * failure fall through to the next available one. This resolver is pure over its\n * injected inputs (flags, environment, the discovered local fleet), so it is\n * fully testable, and it holds two hard rules from the guardrails:\n *\n * - **No surprise egress or install.** With no explicit selection it picks a\n * backend only from signals already present (a configured hosted key, or a\n * model already pulled locally). It never dials a default cloud endpoint you\n * didn't configure, and never triggers an install to pick a default.\n * - **`--local` stays local.** Under `--local` only on-device backends are\n * eligible; if none are available it fails with an actionable message rather\n * than silently reaching the network.\n */\n\nimport { CliError, ExitCode } from '../util/exit.js';\nimport { discoverModels, type LocalModel } from '../engine/models.js';\nimport {\n LocalLlamaProvider,\n MockProvider,\n OllamaProvider,\n OpenAiCompatibleProvider,\n OPENAI_COMPATIBLE,\n type OpenAiCompatibleConfig,\n} from './providers.js';\nimport type { Provider } from './types.js';\n\nexport interface RouteOptions {\n /** Explicit `--provider` (ollama, lmstudio, openrouter, litellm, openai, together, llama-cpp). */\n provider?: string;\n /** Explicit `--model`. */\n model?: string;\n /** `--local`: on-device backends only. */\n local?: boolean;\n /** `--yes`: consent to a first-use install (only relevant to llama-cpp). */\n consent?: boolean;\n /** Path to a gguf for the llama-cpp backend. */\n modelPath?: string;\n /** A scripted reply → force the deterministic MockProvider (tests/`--mock`). */\n mockReply?: string;\n}\n\nexport interface RouteDeps {\n env?: NodeJS.ProcessEnv;\n discover?: () => LocalModel[];\n}\n\nexport interface RouteResult {\n /** Providers to try in order; the session falls through on transport failure. */\n providers: Provider[];\n /** A short, human explanation of the choice (for the run header / --json). */\n reason: string;\n}\n\nconst HOSTED_IDS = new Set(['openrouter', 'litellm', 'openai', 'together']);\n\n/** Resolve the ordered provider list for a run. Throws an actionable CliError when nothing is eligible. */\nexport function resolveProviders(opts: RouteOptions, deps: RouteDeps = {}): RouteResult {\n const env = deps.env ?? process.env;\n const discover = deps.discover ?? discoverModels;\n\n // Deterministic offline floor — used by tests, the benchmark, and `--mock`.\n if (opts.mockReply !== undefined) {\n return { providers: [new MockProvider(opts.model ?? 'mock-1', opts.mockReply)], reason: 'mock provider (scripted, offline)' };\n }\n\n // Explicit provider wins.\n if (opts.provider) {\n const provider = buildExplicit(opts.provider, opts, env, discover);\n const fallbacks = opts.local || provider.local ? localFallbacks(opts, env, discover, provider.id) : [];\n return { providers: [provider, ...fallbacks], reason: `explicit --provider ${opts.provider}` };\n }\n\n // --local: on-device only, in preference order.\n if (opts.local) {\n const locals = localFallbacks(opts, env, discover, '');\n if (locals.length === 0) {\n throw new CliError(\n 'no local model backend available for --local. Start Ollama (`ollama serve` + `ollama pull <model>`), run LM Studio, or point --provider llama-cpp at a gguf. See `vg models`.',\n ExitCode.NOT_FOUND,\n );\n }\n return { providers: locals, reason: '--local (on-device backends only)' };\n }\n\n // No explicit selection: choose from signals already present, best first.\n // 1) A configured hosted router key (OpenRouter is the reference best-in-breed router).\n if (env.OPENROUTER_API_KEY) {\n const model = resolveHostedModel(opts, env, 'openrouter');\n const primary = buildHosted('openrouter', model);\n return { providers: [primary, ...localFallbacks(opts, env, discover, 'openrouter')], reason: 'OPENROUTER_API_KEY is set → OpenRouter (with local fallback)' };\n }\n // 2) A locally-pulled model.\n const locals = localFallbacks(opts, env, discover, '');\n if (locals.length) return { providers: locals, reason: 'a local model is available → on-device (no key needed)' };\n // 3) Any other configured hosted key.\n for (const id of ['litellm', 'openai', 'together'] as const) {\n const keyEnv = OPENAI_COMPATIBLE[id].apiKeyEnv;\n if (keyEnv && env[keyEnv]) {\n const model = resolveHostedModel(opts, env, id);\n return { providers: [buildHosted(id, model)], reason: `${keyEnv} is set → ${OPENAI_COMPATIBLE[id].label}` };\n }\n }\n\n throw new CliError(\n 'no model backend configured. Do one of: set OPENROUTER_API_KEY for the hosted router, run Ollama locally (`ollama serve`), or use --local with a local model. Set the model with --model or VG_CODE_MODEL. (No models are installed by default.)',\n ExitCode.NOT_FOUND,\n );\n}\n\nfunction buildExplicit(id: string, opts: RouteOptions, env: NodeJS.ProcessEnv, discover: () => LocalModel[]): Provider {\n if (id === 'ollama') return new OllamaProvider(resolveLocalModel(opts, discover, 'ollama'), env.OLLAMA_HOST);\n if (id === 'llama-cpp') {\n const modelPath = opts.modelPath || env.VG_CODE_MODEL_PATH;\n if (!modelPath) throw new CliError('--provider llama-cpp needs a gguf path via --model-path or VG_CODE_MODEL_PATH (no weights are downloaded automatically; see `vg models`).', ExitCode.USAGE_ERROR);\n return new LocalLlamaProvider(opts.model ?? basename(modelPath), modelPath, undefined, !!opts.consent);\n }\n if (id === 'lmstudio') return buildHosted('lmstudio', resolveHostedModel(opts, env, 'lmstudio'));\n if (HOSTED_IDS.has(id)) return buildHosted(id, resolveHostedModel(opts, env, id));\n throw new CliError(`unknown --provider \"${id}\". Known: ollama, lmstudio, openrouter, litellm, openai, together, llama-cpp.`, ExitCode.USAGE_ERROR);\n}\n\nfunction buildHosted(id: string, model: string): OpenAiCompatibleProvider {\n const base = OPENAI_COMPATIBLE[id];\n const config: OpenAiCompatibleConfig = { ...base, id };\n return new OpenAiCompatibleProvider(model, config);\n}\n\n/** On-device backends in preference order, skipping the one already chosen as primary. */\nfunction localFallbacks(opts: RouteOptions, env: NodeJS.ProcessEnv, discover: () => LocalModel[], exclude: string): Provider[] {\n const out: Provider[] = [];\n const models = safeDiscover(discover);\n const ollamaModel = opts.model ?? firstOfRuntime(models, 'ollama');\n if (exclude !== 'ollama' && ollamaModel) out.push(new OllamaProvider(ollamaModel, env.OLLAMA_HOST));\n // LM Studio serves an OpenAI-compatible endpoint locally; include if a model id is known.\n const lmModel = opts.model ?? firstOfRuntime(models, 'lm-studio');\n if (exclude !== 'lmstudio' && lmModel) out.push(buildHosted('lmstudio', lmModel));\n return out;\n}\n\nfunction resolveLocalModel(opts: RouteOptions, discover: () => LocalModel[], runtime: LocalModel['runtime']): string {\n if (opts.model) return opts.model;\n const found = firstOfRuntime(safeDiscover(discover), runtime);\n if (found) return found;\n throw new CliError(`--provider ${runtime} needs a model. Pull one (\\`ollama pull <model>\\`) then re-run, or pass --model. See \\`vg models\\`.`, ExitCode.NOT_FOUND);\n}\n\nfunction resolveHostedModel(opts: RouteOptions, env: NodeJS.ProcessEnv, id: string): string {\n const model = opts.model || env.VG_CODE_MODEL;\n if (model) return model;\n throw new CliError(\n `${OPENAI_COMPATIBLE[id].label} needs a model id — pass --model (e.g. a current best-in-breed coding model) or set VG_CODE_MODEL. We don't hard-code a model so you always pick the current best one.`,\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction firstOfRuntime(models: LocalModel[], runtime: LocalModel['runtime']): string | undefined {\n // Deterministic: discoverModels() already returns a sorted list.\n const m = models.find((x) => x.runtime === runtime);\n return m?.name;\n}\n\nfunction safeDiscover(discover: () => LocalModel[]): LocalModel[] {\n try {\n return discover();\n } catch {\n return [];\n }\n}\n\nfunction basename(p: string): string {\n return p.replace(/\\\\/g, '/').split('/').pop() ?? p;\n}\n"]}
@@ -0,0 +1,234 @@
1
+ import { buildCodeContext, buildMessages, parseEdits, applyEdits, unifiedDiff, redactSecrets } from './chunk-CS37OBE3.js';
2
+ import { recordCliCall, CLI_TOOL_ALIASES } from './chunk-WNIIKCNF.js';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+
6
+ async function runCodeSession(options) {
7
+ const {
8
+ graph,
9
+ root,
10
+ instruction,
11
+ providers,
12
+ apply = false,
13
+ consent = false,
14
+ files,
15
+ budget,
16
+ chatOptions,
17
+ now = () => 0,
18
+ onPhase = () => {
19
+ }
20
+ } = options;
21
+ const fsImpl = options.fsImpl ?? nodeCodeFs(root);
22
+ const correlationId = options.correlationId ?? shortId();
23
+ const phasesRun = [];
24
+ const phase = (p, detail) => {
25
+ phasesRun.push(p);
26
+ onPhase(p, detail);
27
+ };
28
+ phase("inspect", "building graph-grounded context");
29
+ const context = buildCodeContext(graph, instruction, { budget, files });
30
+ if (options.attribution?.client) {
31
+ const seedFiles = new Set(context.seeds.map((s) => s.node.file).filter(Boolean));
32
+ recordCliCall(
33
+ root,
34
+ {
35
+ tool: CLI_TOOL_ALIASES.ask,
36
+ client: options.attribution.client,
37
+ provider: options.attribution.provider,
38
+ model: options.attribution.model,
39
+ outcome: context.seeds.length ? "complete" : "miss",
40
+ vgTokens: context.tokensEstimate,
41
+ baselineFiles: seedFiles.size
42
+ },
43
+ now()
44
+ );
45
+ }
46
+ phase("assess", "asking the routed model for a minimal edit");
47
+ const messages = buildMessages(context);
48
+ const { result, provider, fellBack } = await complete(providers, messages, chatOptions, correlationId);
49
+ const edits = parseEdits(result.text);
50
+ const spans = spanIndex(graph);
51
+ const applied = applyEdits(
52
+ edits,
53
+ (file) => fsImpl.read(file),
54
+ (file) => spans.get(normalize(file)) ?? []
55
+ );
56
+ const changes = [];
57
+ for (const [file, entry] of [...applied.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
58
+ changes.push({
59
+ file,
60
+ before: entry.before,
61
+ after: entry.after,
62
+ outcomes: entry.outcomes,
63
+ diff: unifiedDiff(entry.before, entry.after, file)
64
+ });
65
+ }
66
+ phase("dry-run", `${changes.length} file(s) would change`);
67
+ const anyApplicable = changes.some((c) => c.diff !== "" && c.outcomes.some((o) => o.status === "applied"));
68
+ const base = {
69
+ instruction,
70
+ provider: { id: provider.id, model: provider.model, local: provider.local, fellBack },
71
+ phasesRun,
72
+ changes,
73
+ applied: false,
74
+ verification: { ran: false, ok: false, detail: "dry-run \u2014 no changes written" },
75
+ correlationId
76
+ };
77
+ if (!apply) {
78
+ if (!options.noAudit) writeAudit(fsImpl, base, now());
79
+ return base;
80
+ }
81
+ if (!consent) {
82
+ const stopped = { ...base, verification: { ran: false, ok: false, detail: "apply requested without consent \u2014 re-run with --yes to write these changes" } };
83
+ if (!options.noAudit) writeAudit(fsImpl, stopped, now());
84
+ return stopped;
85
+ }
86
+ if (!anyApplicable) {
87
+ const nothing = { ...base, verification: { ran: false, ok: false, detail: "nothing to write \u2014 no edit applied cleanly" } };
88
+ if (!options.noAudit) writeAudit(fsImpl, nothing, now());
89
+ return nothing;
90
+ }
91
+ phase("approve", "consent given (--yes)");
92
+ phase("execute", "writing approved changes");
93
+ for (const change of changes) {
94
+ if (change.diff === "") continue;
95
+ if (!change.outcomes.some((o) => o.status === "applied")) continue;
96
+ if (change.after === null) fsImpl.remove(change.file);
97
+ else fsImpl.write(change.file, change.after);
98
+ }
99
+ phase("verify", "confirming on-disk content matches the approved change");
100
+ const verification = verifyWrites(fsImpl, changes);
101
+ phase("log", "recording an audit entry");
102
+ const final = { ...base, applied: true, verification };
103
+ if (!options.noAudit) writeAudit(fsImpl, final, now());
104
+ return final;
105
+ }
106
+ function commitChanges(result, fsImpl, now = () => 0) {
107
+ const anyApplicable = result.changes.some((c) => c.diff !== "" && c.outcomes.some((o) => o.status === "applied"));
108
+ if (!anyApplicable) {
109
+ return { ...result, applied: false, verification: { ran: false, ok: false, detail: "nothing to write \u2014 no edit applied cleanly" } };
110
+ }
111
+ for (const change of result.changes) {
112
+ if (change.diff === "" || !change.outcomes.some((o) => o.status === "applied")) continue;
113
+ if (change.after === null) fsImpl.remove(change.file);
114
+ else fsImpl.write(change.file, change.after);
115
+ }
116
+ const verification = verifyWrites(fsImpl, result.changes);
117
+ const final = { ...result, applied: true, verification, phasesRun: [...result.phasesRun, "approve", "execute", "verify", "log"] };
118
+ writeAudit(fsImpl, final, now());
119
+ return final;
120
+ }
121
+ function undoChanges(changes, fsImpl) {
122
+ const restored = [];
123
+ for (const ch of changes) {
124
+ if (!ch.outcomes.some((o) => o.status === "applied")) continue;
125
+ if (ch.before === null) fsImpl.remove(ch.file);
126
+ else fsImpl.write(ch.file, ch.before);
127
+ restored.push(ch.file);
128
+ }
129
+ return restored;
130
+ }
131
+ async function complete(providers, messages, chatOptions, correlationId) {
132
+ if (providers.length === 0) throw new Error(`no model provider available (ref ${correlationId})`);
133
+ let lastErr;
134
+ for (let i = 0; i < providers.length; i++) {
135
+ const provider = providers[i];
136
+ try {
137
+ const result = await provider.chat(messages, { temperature: 0, ...chatOptions });
138
+ return { result, provider, fellBack: i > 0 };
139
+ } catch (e) {
140
+ lastErr = e;
141
+ }
142
+ }
143
+ const message = lastErr instanceof Error ? redactSecrets(lastErr.message) : String(lastErr);
144
+ throw new Error(`${message} (ref ${correlationId})`);
145
+ }
146
+ function verifyWrites(fsImpl, changes) {
147
+ let checked = 0;
148
+ const mismatches = [];
149
+ for (const change of changes) {
150
+ if (change.diff === "" || !change.outcomes.some((o) => o.status === "applied")) continue;
151
+ checked++;
152
+ const onDisk = fsImpl.read(change.file);
153
+ if (onDisk !== change.after) mismatches.push(change.file);
154
+ }
155
+ if (mismatches.length) return { ran: true, ok: false, detail: `on-disk content differs for: ${mismatches.join(", ")}` };
156
+ return { ran: true, ok: true, detail: `wrote and verified ${checked} file(s)` };
157
+ }
158
+ function writeAudit(fsImpl, r, ts) {
159
+ const record = {
160
+ ts,
161
+ correlationId: r.correlationId,
162
+ instruction: r.instruction.slice(0, 500),
163
+ provider: r.provider.id,
164
+ model: r.provider.model,
165
+ local: r.provider.local,
166
+ applied: r.applied,
167
+ files: r.changes.map((c) => ({ file: c.file, statuses: c.outcomes.map((o) => o.status) })),
168
+ verification: r.verification,
169
+ phases: r.phasesRun
170
+ };
171
+ try {
172
+ fsImpl.appendAudit(JSON.stringify(record));
173
+ } catch {
174
+ }
175
+ }
176
+ function spanIndex(graph) {
177
+ const map = /* @__PURE__ */ new Map();
178
+ for (const n of graph.nodes) {
179
+ if (n.kind === "file" || n.kind === "external") continue;
180
+ const file = normalize(n.file);
181
+ const list = map.get(file) ?? [];
182
+ list.push({ qualifiedName: n.qualifiedName, file, start: n.span.start, end: n.span.end });
183
+ map.set(file, list);
184
+ }
185
+ return map;
186
+ }
187
+ function normalize(file) {
188
+ return file.replace(/\\/g, "/").replace(/^\.\//, "");
189
+ }
190
+ function nodeCodeFs(root) {
191
+ const resolve2 = (file) => {
192
+ const abs = path.resolve(root, file);
193
+ const rel = path.relative(root, abs);
194
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
195
+ throw new Error(`edit path escapes the project root: ${file} \u2014 refusing to touch files outside ${root}`);
196
+ }
197
+ return abs;
198
+ };
199
+ return {
200
+ read(file) {
201
+ try {
202
+ return fs.readFileSync(resolve2(file), "utf8");
203
+ } catch {
204
+ return null;
205
+ }
206
+ },
207
+ write(file, content) {
208
+ const abs = resolve2(file);
209
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
210
+ fs.writeFileSync(abs, content);
211
+ },
212
+ remove(file) {
213
+ try {
214
+ fs.rmSync(resolve2(file));
215
+ } catch {
216
+ }
217
+ },
218
+ appendAudit(line) {
219
+ const dir = path.join(root, ".vibgrate");
220
+ fs.mkdirSync(dir, { recursive: true });
221
+ fs.appendFileSync(path.join(dir, "code-audit.jsonl"), line + "\n");
222
+ }
223
+ };
224
+ }
225
+ function shortId() {
226
+ let s = "";
227
+ const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
228
+ for (let i = 0; i < 8; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)];
229
+ return s;
230
+ }
231
+
232
+ export { commitChanges, nodeCodeFs, runCodeSession, undoChanges };
233
+ //# sourceMappingURL=chunk-6CXTPC74.js.map
234
+ //# sourceMappingURL=chunk-6CXTPC74.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/code/session.ts"],"names":["resolve"],"mappings":";;;;;AA4EA,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,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AO,GAAI,QAAA,CAAS,MAAM,CAAC,CAAA;AACrF,EAAA,OAAO,CAAA;AACT","file":"chunk-6CXTPC74.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 { recordCliCall, CLI_TOOL_ALIASES } from '../engine/savings.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, 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\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', 'building graph-grounded context');\n const context = buildCodeContext(graph, instruction, { budget, files });\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\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"]}