codebase-snapshot 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -4,7 +4,7 @@ var childProcess = require('child_process');
4
4
  var fs24 = require('fs');
5
5
  var path27 = require('path');
6
6
  var util = require('util');
7
- var crypto4 = require('crypto');
7
+ var crypto = require('crypto');
8
8
  var module$1 = require('module');
9
9
  var url = require('url');
10
10
  var ts2 = require('typescript');
@@ -40,7 +40,7 @@ function _interopNamespace(e) {
40
40
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
41
41
  var fs24__namespace = /*#__PURE__*/_interopNamespace(fs24);
42
42
  var path27__namespace = /*#__PURE__*/_interopNamespace(path27);
43
- var crypto4__namespace = /*#__PURE__*/_interopNamespace(crypto4);
43
+ var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
44
44
  var ts2__default = /*#__PURE__*/_interopDefault(ts2);
45
45
  var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
46
46
  var os2__namespace = /*#__PURE__*/_interopNamespace(os2);
@@ -2221,7 +2221,7 @@ function applySpansKeepingQuotes(line, spans) {
2221
2221
 
2222
2222
  // src/version.ts
2223
2223
  var GENERATOR_NAME = "codebase-snapshot";
2224
- var GENERATOR_VERSION = "0.16.0";
2224
+ var GENERATOR_VERSION = "0.18.0";
2225
2225
  var SCHEMA_VERSION = "3.0.0";
2226
2226
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2227
2227
  function isOurGeneratorName(name) {
@@ -2272,6 +2272,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2272
2272
  let branch = fallbackBranch;
2273
2273
  let commit = "unknown";
2274
2274
  let isDirty = false;
2275
+ let branchFromGit = false;
2275
2276
  const records = output.split("\0").flatMap((record) => record.split("\n"));
2276
2277
  for (const record of records) {
2277
2278
  if (record.length === 0) continue;
@@ -2287,13 +2288,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2287
2288
  const head = record.match(/^# branch\.head (.+)$/);
2288
2289
  if (head) {
2289
2290
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
2291
+ branchFromGit = head[1] !== "(detached)";
2290
2292
  }
2291
2293
  }
2292
- return { branch, commit, isDirty };
2294
+ return { branch, commit, isDirty, branchFromGit };
2293
2295
  } catch (err) {
2294
2296
  const code = err.code;
2295
2297
  const isDirty = code === "ENOBUFS";
2296
- return { branch: fallbackBranch, commit: "unknown", isDirty };
2298
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
2297
2299
  }
2298
2300
  }
2299
2301
  var DEFAULT_IGNORED_DIRS = [
@@ -3389,7 +3391,7 @@ function parseOwnerBrief(filePath, text2) {
3389
3391
  return {
3390
3392
  brief: {
3391
3393
  path: filePath,
3392
- digest: crypto4.createHash("sha256").update(text2, "utf8").digest("hex"),
3394
+ digest: crypto.createHash("sha256").update(text2, "utf8").digest("hex"),
3393
3395
  ...recognised["Stakes"] ? { stakes: recognised["Stakes"] } : {},
3394
3396
  ...recognised["The system"] ? { system: recognised["The system"] } : {},
3395
3397
  ...recognised["What came before"] ? { history: recognised["What came before"] } : {},
@@ -3661,7 +3663,7 @@ function readConfigExport(exported, file) {
3661
3663
  var lastModuleConfig = null;
3662
3664
  function moduleConfigKey(fullPath) {
3663
3665
  try {
3664
- return crypto4.createHash("sha256").update(fs24__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3666
+ return crypto.createHash("sha256").update(fs24__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3665
3667
  } catch {
3666
3668
  try {
3667
3669
  const stats = fs24__namespace.statSync(fullPath);
@@ -4509,7 +4511,7 @@ function configDigest(config) {
4509
4511
  (rule) => `${rule.rule}:${rule.pattern.source}/${rule.pattern.flags}:${rule.valueGroup ?? ""}`
4510
4512
  ).sort()
4511
4513
  };
4512
- return crypto4.createHash("sha256").update(JSON.stringify(material)).digest("hex");
4514
+ return crypto.createHash("sha256").update(JSON.stringify(material)).digest("hex");
4513
4515
  }
4514
4516
  function gitPaths(cwd, args) {
4515
4517
  let output;
@@ -4985,7 +4987,7 @@ function summarizeTypeScriptSource(relativePath, content) {
4985
4987
  }
4986
4988
  const callee = node.expression;
4987
4989
  if (ts2__default.default.isPropertyAccessExpression(callee) && ts2__default.default.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts2__default.default.isStringLiteral(firstArgument)) {
4988
- summary.routeHandlers.push(callee.name.text.toUpperCase());
4990
+ summary.routeHandlers.push(callee.name.text.toUpperCase() + " " + firstArgument.text);
4989
4991
  }
4990
4992
  }
4991
4993
  if (ts2__default.default.isExportDeclaration(node)) {
@@ -6225,6 +6227,69 @@ function importsOfFile(relativePath, absolutePath) {
6225
6227
  if (decoded.binary) return [];
6226
6228
  return importsOfText(relativePath, decoded.text);
6227
6229
  }
6230
+ var SIGNATURE_FILE = "signature.json";
6231
+ function loadSigningKey(environment = process.env) {
6232
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
6233
+ if (pem === void 0 || pem.trim() === "") return null;
6234
+ return crypto__namespace.createPrivateKey({ key: pem, format: "pem" });
6235
+ }
6236
+ function signManifest(manifestPath, options = {}) {
6237
+ const bytes = fs24__namespace.readFileSync(manifestPath);
6238
+ const manifest = JSON.parse(bytes.toString("utf8"));
6239
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
6240
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
6241
+ }
6242
+ const configured = options.key ?? null;
6243
+ const key = configured ?? crypto__namespace.generateKeyPairSync("ed25519").privateKey;
6244
+ const publicKey = crypto__namespace.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
6245
+ const signature = crypto__namespace.sign(null, bytes, key).toString("base64");
6246
+ return {
6247
+ algorithm: "ed25519",
6248
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6249
+ fingerprint: manifest.fingerprint,
6250
+ manifestSha256: crypto__namespace.createHash("sha256").update(bytes).digest("hex"),
6251
+ publicKey,
6252
+ signature,
6253
+ keyOrigin: configured === null ? "generated" : "configured"
6254
+ };
6255
+ }
6256
+ function writeSignature(snapshotDir, record) {
6257
+ const target = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
6258
+ fs24__namespace.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
6259
+ return target;
6260
+ }
6261
+ function verifySnapshotSignature(snapshotDir) {
6262
+ const signaturePath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
6263
+ const manifestPath = path27__namespace.join(snapshotDir, "manifest.json");
6264
+ if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
6265
+ let record;
6266
+ try {
6267
+ record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
6268
+ } catch (error) {
6269
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
6270
+ }
6271
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
6272
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
6273
+ }
6274
+ let bytes;
6275
+ try {
6276
+ bytes = fs24__namespace.readFileSync(manifestPath);
6277
+ } catch {
6278
+ return { ok: false, reason: "the signed manifest is missing" };
6279
+ }
6280
+ const sha2562 = crypto__namespace.createHash("sha256").update(bytes).digest("hex");
6281
+ if (sha2562 !== record.manifestSha256) {
6282
+ return { ok: false, reason: "manifest.json changed after it was signed" };
6283
+ }
6284
+ let verified = false;
6285
+ try {
6286
+ const key = crypto__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
6287
+ verified = crypto__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
6288
+ } catch (error) {
6289
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
6290
+ }
6291
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
6292
+ }
6228
6293
 
6229
6294
  // src/validator/validate.ts
6230
6295
  function maskedPath(value, secretRules) {
@@ -6290,7 +6355,7 @@ function emptyDrift() {
6290
6355
  };
6291
6356
  }
6292
6357
  function sha256Hex(buffer) {
6293
- return crypto4__namespace.createHash("sha256").update(buffer).digest("hex");
6358
+ return crypto__namespace.createHash("sha256").update(buffer).digest("hex");
6294
6359
  }
6295
6360
  function wouldNowBeIncluded(cwd, relativePath) {
6296
6361
  const absolutePath = path27__namespace.join(cwd, relativePath);
@@ -7227,6 +7292,11 @@ function validateSnapshot(configInput) {
7227
7292
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
7228
7293
  );
7229
7294
  }
7295
+ const signaturePath = path27__namespace.join(path27__namespace.dirname(manifestPath), "signature.json");
7296
+ if (fs24__namespace.existsSync(signaturePath)) {
7297
+ const outcome = verifySnapshotSignature(path27__namespace.dirname(manifestPath));
7298
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
7299
+ }
7230
7300
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
7231
7301
  warnings.push(
7232
7302
  "This snapshot is a selection (" + (manifest.slice !== void 0 ? "--slice" : "--budget-tokens") + "); validate checks what is present and does not re-run the planner, so a file the selection left out is not reported as missing."
@@ -9374,7 +9444,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
9374
9444
  "# Codebase Health & Security Audit",
9375
9445
  "",
9376
9446
  `**Generated:** ${manifest.generatedAt} `,
9377
- `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
9447
+ `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})${manifest.git.branchFromGit === false ? " \u2014 fallback; git reported no branch here" : ""} `,
9378
9448
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
9379
9449
  `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
9380
9450
  `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
@@ -9531,7 +9601,7 @@ var BUILTIN_RULE_IDS = new Map(
9531
9601
  function ruleIdFor(name) {
9532
9602
  const builtin = BUILTIN_RULE_IDS.get(name);
9533
9603
  if (builtin !== void 0) return builtin;
9534
- const digest = crypto4__namespace.createHash("sha256").update(name).digest("hex").slice(0, 8);
9604
+ const digest = crypto__namespace.createHash("sha256").update(name).digest("hex").slice(0, 8);
9535
9605
  return `CS${digest.toUpperCase()}`;
9536
9606
  }
9537
9607
  function generateSarifReport(manifest, findings, rules, toolVersion) {
@@ -9871,7 +9941,7 @@ function rehashPart(part, markdown) {
9871
9941
  metadata: {
9872
9942
  ...part.metadata,
9873
9943
  byteSize: Buffer.byteLength(redistributed, "utf8"),
9874
- sha256: crypto4__namespace.createHash("sha256").update(redistributed).digest("hex"),
9944
+ sha256: crypto__namespace.createHash("sha256").update(redistributed).digest("hex"),
9875
9945
  lines: countLines(redistributed),
9876
9946
  estimatedTokens
9877
9947
  }
@@ -9952,7 +10022,7 @@ function renderGroups(groups, contentFingerprint, assemble = (group, index, tota
9952
10022
  return groups.map((group, index) => {
9953
10023
  const { filename, content, estimatedTokens } = assemble(group, index, total);
9954
10024
  const byteSize = Buffer.byteLength(content, "utf8");
9955
- const sha2562 = crypto4__namespace.createHash("sha256").update(content).digest("hex");
10025
+ const sha2562 = crypto__namespace.createHash("sha256").update(content).digest("hex");
9956
10026
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
9957
10027
  const includedFiles = group.sections.map(({ file }) => ({
9958
10028
  relativePath: file.relativePath,
@@ -10034,7 +10104,7 @@ function renderSummary(summary, inclusionMode) {
10034
10104
  }
10035
10105
  function anchorForPath(filePath) {
10036
10106
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
10037
- const digest = crypto4__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
10107
+ const digest = crypto__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
10038
10108
  return `${slug || "file"}-${digest}`;
10039
10109
  }
10040
10110
 
@@ -10381,13 +10451,19 @@ function planForQuestion(manifest, question, options = {}) {
10381
10451
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
10382
10452
  }
10383
10453
  const notes = [];
10454
+ if (manifest.files.length === 0) {
10455
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
10456
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
10457
+ }
10384
10458
  if (scored.length === 0) {
10385
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10386
10459
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
10387
10460
  for (const hub of hubs) {
10388
10461
  const file = byPath.get(hub.path);
10389
10462
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
10390
10463
  }
10464
+ if (scored.length > 0) {
10465
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10466
+ }
10391
10467
  }
10392
10468
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
10393
10469
  const chosen = /* @__PURE__ */ new Map();
@@ -10451,7 +10527,14 @@ function planForQuestion(manifest, question, options = {}) {
10451
10527
  }
10452
10528
  }
10453
10529
  }
10454
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
10530
+ if (chosen.size === 0) {
10531
+ if (scored.length === 0) {
10532
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
10533
+ } else {
10534
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
10535
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber2(cheapest) + " tokens.");
10536
+ }
10537
+ }
10455
10538
  notes.push(
10456
10539
  formatNumber2(chosen.size) + " file(s) chosen of " + formatNumber2(manifest.files.length) + " in the snapshot; " + formatNumber2(skipped.length) + " skipped for budget."
10457
10540
  );
@@ -11017,7 +11100,7 @@ function snapshotSection(manifest, code, partsWritten) {
11017
11100
  const out = ["## This snapshot", ""];
11018
11101
  out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
11019
11102
  out.push(
11020
- "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
11103
+ "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + (manifest.git.branchFromGit === false ? " (the branch is a configured fallback; git reported none)." : ".")
11021
11104
  );
11022
11105
  out.push(
11023
11106
  manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
@@ -11190,7 +11273,7 @@ function generateReadme(manifest, artifacts) {
11190
11273
  "",
11191
11274
  `- **Generated At:** \`${manifest.generatedAt}\``,
11192
11275
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
11193
- `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
11276
+ `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})${manifest.git.branchFromGit === false ? " \u2014 fallback; git reported no branch here" : ""}`,
11194
11277
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
11195
11278
  `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
11196
11279
  `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
@@ -11767,69 +11850,6 @@ function negotiateLegacyVersion(requested) {
11767
11850
  }
11768
11851
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
11769
11852
  }
11770
- var SIGNATURE_FILE = "signature.json";
11771
- function loadSigningKey(environment = process.env) {
11772
- const pem = environment.SNAPSHOT_SIGNING_KEY;
11773
- if (pem === void 0 || pem.trim() === "") return null;
11774
- return crypto4__namespace.createPrivateKey({ key: pem, format: "pem" });
11775
- }
11776
- function signManifest(manifestPath, options = {}) {
11777
- const bytes = fs24__namespace.readFileSync(manifestPath);
11778
- const manifest = JSON.parse(bytes.toString("utf8"));
11779
- if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
11780
- throw new Error("refusing to sign: the manifest has no valid fingerprint");
11781
- }
11782
- const configured = options.key ?? null;
11783
- const key = configured ?? crypto4__namespace.generateKeyPairSync("ed25519").privateKey;
11784
- const publicKey = crypto4__namespace.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
11785
- const signature = crypto4__namespace.sign(null, bytes, key).toString("base64");
11786
- return {
11787
- algorithm: "ed25519",
11788
- signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
11789
- fingerprint: manifest.fingerprint,
11790
- manifestSha256: crypto4__namespace.createHash("sha256").update(bytes).digest("hex"),
11791
- publicKey,
11792
- signature,
11793
- keyOrigin: configured === null ? "generated" : "configured"
11794
- };
11795
- }
11796
- function writeSignature(snapshotDir, record) {
11797
- const target = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
11798
- fs24__namespace.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
11799
- return target;
11800
- }
11801
- function verifySnapshotSignature(snapshotDir) {
11802
- const signaturePath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
11803
- const manifestPath = path27__namespace.join(snapshotDir, "manifest.json");
11804
- if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
11805
- let record;
11806
- try {
11807
- record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
11808
- } catch (error) {
11809
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
11810
- }
11811
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
11812
- return { ok: false, reason: "signature.json is not an ed25519 record" };
11813
- }
11814
- let bytes;
11815
- try {
11816
- bytes = fs24__namespace.readFileSync(manifestPath);
11817
- } catch {
11818
- return { ok: false, reason: "the signed manifest is missing" };
11819
- }
11820
- const sha2562 = crypto4__namespace.createHash("sha256").update(bytes).digest("hex");
11821
- if (sha2562 !== record.manifestSha256) {
11822
- return { ok: false, reason: "manifest.json changed after it was signed" };
11823
- }
11824
- let verified = false;
11825
- try {
11826
- const key = crypto4__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
11827
- verified = crypto4__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
11828
- } catch (error) {
11829
- return { ok: false, reason: "the signature could not be checked: " + error.message };
11830
- }
11831
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
11832
- }
11833
11853
 
11834
11854
  // src/partitioner/part-format.ts
11835
11855
  var FILE_HEADING = "### FILE: ";
@@ -11935,7 +11955,7 @@ var ARTIFACT_FILES = {
11935
11955
  };
11936
11956
  var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
11937
11957
  function sha256(buffer) {
11938
- return crypto4.createHash("sha256").update(buffer).digest("hex");
11958
+ return crypto.createHash("sha256").update(buffer).digest("hex");
11939
11959
  }
11940
11960
  function readBytes(file) {
11941
11961
  try {
@@ -12410,8 +12430,9 @@ function auditSnapshot(options) {
12410
12430
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
12411
12431
  disagreements.push("file count");
12412
12432
  }
12433
+ const sourceGone = typeof member.path === "string" && !fs24__namespace.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
12413
12434
  checks.push(
12414
- disagreements.length === 0 ? check(
12435
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
12415
12436
  "workspace.index",
12416
12437
  "The workspace index agrees with this member",
12417
12438
  "warning",
@@ -12433,6 +12454,7 @@ function auditSnapshot(options) {
12433
12454
  let scannedBytes = 0;
12434
12455
  for (const relative15 of walk(snapshotDir)) {
12435
12456
  if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
12457
+ if (relative15 === SIGNATURE_FILE) continue;
12436
12458
  const text2 = readText2(path27__namespace.join(snapshotDir, relative15));
12437
12459
  if (text2 === null) continue;
12438
12460
  scannedBytes += Buffer.byteLength(text2, "utf8");
@@ -12441,6 +12463,28 @@ function auditSnapshot(options) {
12441
12463
  leakHits.push(relative15 + " (" + found.findings.length + " line(s))");
12442
12464
  }
12443
12465
  }
12466
+ const signatureRecordPath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
12467
+ if (fs24__namespace.existsSync(signatureRecordPath)) {
12468
+ const recordText = readText2(signatureRecordPath);
12469
+ if (recordText !== null) {
12470
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
12471
+ let scanText = recordText;
12472
+ try {
12473
+ const record = JSON.parse(recordText);
12474
+ const rest = { ...record };
12475
+ delete rest.publicKey;
12476
+ delete rest.signature;
12477
+ delete rest.manifestSha256;
12478
+ delete rest.fingerprint;
12479
+ scanText = JSON.stringify(rest, null, 2);
12480
+ } catch {
12481
+ }
12482
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
12483
+ if (found.findings.length > 0) {
12484
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
12485
+ }
12486
+ }
12487
+ }
12444
12488
  checks.push(
12445
12489
  leakHits.length === 0 ? check(
12446
12490
  "secrets.artifacts",
@@ -12936,6 +12980,10 @@ var WRITES = {
12936
12980
  openWorldHint: false
12937
12981
  };
12938
12982
  var MAX_RESULT_BYTES = 64 * 1024;
12983
+ function capResultText(text2) {
12984
+ const clipped = truncateToBytes(text2, MAX_RESULT_BYTES);
12985
+ return { text: clipped.isTruncated ? clipped.content : text2, clipped: clipped.isTruncated };
12986
+ }
12939
12987
  var ROOT_PROPERTY = {
12940
12988
  type: "string",
12941
12989
  description: "Repository root. Defaults to the directory this server was started in."
@@ -13123,6 +13171,17 @@ var historyTool = {
13123
13171
  isError: true
13124
13172
  };
13125
13173
  }
13174
+ const manifestRead = readManifest3(prepared.workspace);
13175
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
13176
+ if (recordedLog !== void 0 && recordedLog !== null) {
13177
+ const digest = crypto.createHash("sha256").update(text2, "utf8").digest("hex");
13178
+ if (digest !== recordedLog.sha256) {
13179
+ return {
13180
+ text: "reports/log.md changed after the snapshot was generated (its digest no longer matches the manifest). Regenerate the snapshot rather than trusting this history.",
13181
+ isError: true
13182
+ };
13183
+ }
13184
+ }
13126
13185
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
13127
13186
  const commits = parseHistoryReport(text2).slice(0, limit);
13128
13187
  return {
@@ -13182,9 +13241,12 @@ var budgetTool = {
13182
13241
  });
13183
13242
  }
13184
13243
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
13244
+ if (read.manifest.files.length === 0) {
13245
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
13246
+ }
13185
13247
  for (const row of rows) {
13186
13248
  lines.push(
13187
- row.budget.toLocaleString("en-US") + " tokens: " + row.files + " file(s), " + row.usedTokens.toLocaleString("en-US") + " used" + (row.gained.length === 0 ? "" : ", " + row.gained.length + " gained (" + row.gained.slice(0, 4).join(", ") + (row.gained.length > 4 ? ", \u2026" : "") + ")")
13249
+ row.budget.toLocaleString("en-US") + " tokens: " + row.files + " file(s), " + row.usedTokens.toLocaleString("en-US") + " used" + (row.files === 0 && read.manifest.files.length > 0 ? " - no file fits this budget" : "") + (row.gained.length === 0 ? "" : ", " + row.gained.length + " gained (" + row.gained.slice(0, 4).join(", ") + (row.gained.length > 4 ? ", \u2026" : "") + ")")
13188
13250
  );
13189
13251
  }
13190
13252
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -13436,7 +13498,7 @@ var routesTool = {
13436
13498
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
13437
13499
  const text2 = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
13438
13500
  routes.length + " route(s):",
13439
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
13501
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
13440
13502
  ].join("\n");
13441
13503
  return { text: text2, structured: { total: routes.length, routes } };
13442
13504
  }
@@ -13605,8 +13667,9 @@ var searchTool = {
13605
13667
  }
13606
13668
  }
13607
13669
  }
13670
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
13608
13671
  const lines = [
13609
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
13672
+ matches.length === 0 ? "No match in " + read.manifest.files.length + " file(s)." : matches.length + " match(es) in " + matchedFiles + " file(s) of " + read.manifest.files.length + " searched." + (truncated ? " Results are capped, so not every file was searched; narrow the query." : ""),
13610
13673
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
13611
13674
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
13612
13675
  ];
@@ -13629,7 +13692,9 @@ var statsTool = {
13629
13692
  parts: { type: "integer" },
13630
13693
  tokens: { type: "integer" },
13631
13694
  layers: { type: "object" },
13632
- kinds: { type: "object" }
13695
+ kinds: { type: "object" },
13696
+ heaviest: { type: "array", items: { type: "object" } },
13697
+ partSizes: { type: "array", items: { type: "object" } }
13633
13698
  }
13634
13699
  },
13635
13700
  annotations: READ_ONLY,
@@ -13640,7 +13705,11 @@ var statsTool = {
13640
13705
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13641
13706
  const manifest = read.manifest;
13642
13707
  const heaviest = [...manifest.files].sort((left, right) => right.includedBytes - left.includedBytes).slice(0, 10).map((file) => ({ path: file.relativePath, tokens: Math.ceil(file.includedBytes / 4), part: file.part }));
13643
- const parts = manifest.parts.map((part) => ({ filename: part.filename, tokens: part.estimatedTokens }));
13708
+ const parts = manifest.parts.map((part) => ({
13709
+ filename: part.filename,
13710
+ bytes: part.byteSize,
13711
+ tokens: part.estimatedTokens
13712
+ }));
13644
13713
  const lines = [
13645
13714
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
13646
13715
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -13696,7 +13765,7 @@ var reviewTool = {
13696
13765
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13697
13766
  let validation;
13698
13767
  try {
13699
- validation = validateSnapshot(workspace.config);
13768
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
13700
13769
  } catch (error) {
13701
13770
  return { text: error.message, isError: true };
13702
13771
  }
@@ -13796,24 +13865,17 @@ var diffContextTool = {
13796
13865
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
13797
13866
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
13798
13867
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
13868
+ const resolver = buildImportResolver(read.manifest.files, {
13869
+ tsconfig: tsconfigPathsFor(workspace.root)
13870
+ });
13799
13871
  const importers = /* @__PURE__ */ new Map();
13800
13872
  for (const entry of read.manifest.indexes.imports.byFile) {
13801
13873
  for (const specifier of entry.imports) {
13802
- if (!specifier.startsWith(".")) continue;
13803
- const base = entry.path.includes("/") ? entry.path.slice(0, entry.path.lastIndexOf("/")) : "";
13804
- const parts = [];
13805
- for (const segment of (base + "/" + specifier).split("/")) {
13806
- if (segment === "" || segment === ".") continue;
13807
- if (segment === "..") parts.pop();
13808
- else parts.push(segment);
13809
- }
13810
- const joined = parts.join("/").toLowerCase();
13811
- const withoutExtension = joined.replace(/\.[cm]?[jt]sx?$/, "");
13812
- const target = byPath.get(joined) ?? byPath.get(withoutExtension + ".ts") ?? byPath.get(withoutExtension + ".tsx") ?? byPath.get(withoutExtension + ".js") ?? byPath.get(withoutExtension + ".py") ?? byPath.get(withoutExtension + "/index.ts") ?? byPath.get(withoutExtension);
13813
- if (target === void 0) continue;
13814
- const list2 = importers.get(target.relativePath) ?? [];
13874
+ const target = resolveSpecifier(entry.path, specifier, resolver);
13875
+ if (target === null) continue;
13876
+ const list2 = importers.get(target) ?? [];
13815
13877
  list2.push(entry.path);
13816
- importers.set(target.relativePath, list2);
13878
+ importers.set(target, list2);
13817
13879
  }
13818
13880
  }
13819
13881
  const missing = [];
@@ -13848,9 +13910,12 @@ var diffContextTool = {
13848
13910
  continue;
13849
13911
  }
13850
13912
  used += tokens;
13913
+ const capped2 = capResultText(window.text);
13851
13914
  changed.push({ path: file.relativePath, part: file.part, tokens });
13852
- text2.push("### " + file.relativePath + " (" + file.part + ")");
13853
- text2.push(window.text);
13915
+ text2.push(
13916
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
13917
+ );
13918
+ text2.push(capped2.text);
13854
13919
  }
13855
13920
  const dependents = [];
13856
13921
  for (const entry of changed) {
@@ -13932,11 +13997,13 @@ var symbolTool = {
13932
13997
  if (index === -1) continue;
13933
13998
  const from = Math.max(0, index - 3);
13934
13999
  const to = Math.min(lines.length, index + windowSize);
14000
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
13935
14001
  matches.push({
13936
14002
  path: file.relativePath,
13937
14003
  part: file.part,
13938
14004
  line: index + 1,
13939
- text: lines.slice(from, to).join("\n")
14005
+ text: capped2.text,
14006
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
13940
14007
  });
13941
14008
  }
13942
14009
  if (matches.length === 0) {
@@ -14067,7 +14134,8 @@ var contextTool = {
14067
14134
  continue;
14068
14135
  }
14069
14136
  const window = windowText(section.body, 1, linesPerFile);
14070
- const body = window.text;
14137
+ const capped2 = capResultText(window.text);
14138
+ const body = capped2.text;
14071
14139
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
14072
14140
  if (used + tokens > budget) {
14073
14141
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -14076,14 +14144,19 @@ var contextTool = {
14076
14144
  missing.push(file.relativePath + " (budget)");
14077
14145
  continue;
14078
14146
  }
14079
- const partial = Math.max(1, Math.ceil(Buffer.byteLength(smaller.text, "utf8") / 4));
14080
- text2.push("### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines)");
14081
- text2.push(smaller.text);
14147
+ const smallerCapped = capResultText(smaller.text);
14148
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
14149
+ text2.push(
14150
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
14151
+ );
14152
+ text2.push(smallerCapped.text);
14082
14153
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
14083
14154
  used += partial;
14084
14155
  continue;
14085
14156
  }
14086
- text2.push("### " + file.relativePath + " (" + file.part + ")");
14157
+ text2.push(
14158
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
14159
+ );
14087
14160
  text2.push(body);
14088
14161
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
14089
14162
  used += tokens;
@@ -14257,8 +14330,17 @@ var answerTool = {
14257
14330
  maxTokens,
14258
14331
  ...args.includeTests === true ? { includeTests: true } : {}
14259
14332
  });
14333
+ if (read.manifest.files.length === 0) {
14334
+ return {
14335
+ text: "The snapshot holds no files, so nothing can be assembled for this question. manifest.skipped records why paths were not emitted (excluded, binary, unchanged).",
14336
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
14337
+ };
14338
+ }
14260
14339
  const blocks = [];
14261
- const omitted = [];
14340
+ const omitted = plan.skipped.map((entry) => ({
14341
+ path: entry.path,
14342
+ reason: entry.reason
14343
+ }));
14262
14344
  let used = 0;
14263
14345
  const parts = /* @__PURE__ */ new Map();
14264
14346
  for (const planned of plan.files) {
@@ -14287,14 +14369,23 @@ var answerTool = {
14287
14369
  continue;
14288
14370
  }
14289
14371
  const window = windowText(section.body, 1, linesPerFile);
14290
- const text2 = window.text;
14291
- const tokens = estimateTokens(text2);
14372
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
14373
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
14374
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
14375
+ const tokens = estimateTokens(bodyText);
14292
14376
  if (used + tokens > maxTokens && blocks.length > 0) {
14293
14377
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
14294
14378
  continue;
14295
14379
  }
14296
- const numbered = text2.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
14297
- blocks.push({ path: planned.path, why: planned.why, tokens, text: numbered, truncated: window.truncated, totalLines: window.totalLines });
14380
+ blocks.push({
14381
+ path: planned.path,
14382
+ why: planned.why,
14383
+ tokens,
14384
+ text: bodyText,
14385
+ truncated: window.truncated || clipped.isTruncated,
14386
+ totalLines: window.totalLines,
14387
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
14388
+ });
14298
14389
  used += tokens;
14299
14390
  }
14300
14391
  const lines = [
@@ -14303,7 +14394,9 @@ var answerTool = {
14303
14394
  ];
14304
14395
  for (const block of blocks) {
14305
14396
  lines.push("");
14306
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
14397
+ lines.push(
14398
+ "## " + block.path + " (" + block.tokens + " tokens, " + (block.clippedAtBytes !== void 0 ? "first " + Math.round(block.clippedAtBytes / 1024) + " KiB of the window" : block.truncated ? "first lines of " + block.totalLines : "whole file") + ")"
14399
+ );
14307
14400
  lines.push("Why: " + block.why);
14308
14401
  lines.push("```");
14309
14402
  lines.push(block.text);
@@ -14314,6 +14407,11 @@ var answerTool = {
14314
14407
  lines.push("Not included:");
14315
14408
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
14316
14409
  }
14410
+ if (plan.notes.length > 0) {
14411
+ lines.push("");
14412
+ lines.push("Notes:");
14413
+ for (const note of plan.notes) lines.push("- " + note);
14414
+ }
14317
14415
  return {
14318
14416
  text: lines.join("\n"),
14319
14417
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -14428,7 +14526,7 @@ var statusTool = {
14428
14526
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
14429
14527
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
14430
14528
  `Fingerprint: ${manifest.fingerprint}`,
14431
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
14529
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
14432
14530
  ];
14433
14531
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
14434
14532
  if (!versionMatches) {
@@ -14579,6 +14677,16 @@ var generateTool = {
14579
14677
  minimum: 500,
14580
14678
  description: "Fit the snapshot into this token budget, highest value first."
14581
14679
  },
14680
+ only: {
14681
+ type: "array",
14682
+ items: { type: "string" },
14683
+ description: "Globs to include: replaces the config allow-list for this run."
14684
+ },
14685
+ ignore: {
14686
+ type: "array",
14687
+ items: { type: "string" },
14688
+ description: "Globs to exclude, added to the config deny-list for this run."
14689
+ },
14582
14690
  ...SCOPE_PROPERTIES
14583
14691
  },
14584
14692
  additionalProperties: false
@@ -14607,7 +14715,9 @@ var generateTool = {
14607
14715
  ...args.tokenTree === true ? { tokenTree: true } : {},
14608
14716
  ...args.stripComments === true ? { stripComments: true } : {},
14609
14717
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
14610
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
14718
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
14719
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
14720
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
14611
14721
  };
14612
14722
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
14613
14723
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -14651,6 +14761,20 @@ var generateTool = {
14651
14761
  };
14652
14762
  }
14653
14763
  };
14764
+ function configAsGenerated(workspace, manifest) {
14765
+ const recorded = manifest.config;
14766
+ return {
14767
+ ...workspace.config,
14768
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
14769
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
14770
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
14771
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
14772
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
14773
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
14774
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
14775
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
14776
+ };
14777
+ }
14654
14778
  var validateTool = {
14655
14779
  name: "snapshot_validate",
14656
14780
  title: "Validate the snapshot",
@@ -14672,9 +14796,11 @@ var validateTool = {
14672
14796
  const prepared = await prepare(args, context, workspaceOverrides(args));
14673
14797
  if (!prepared.ok) return prepared.outcome;
14674
14798
  const workspace = prepared.workspace;
14799
+ const read = readManifest3(workspace);
14800
+ if (!read.ok) return failure(read.message);
14675
14801
  let result;
14676
14802
  try {
14677
- result = validateSnapshot(workspace.config);
14803
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
14678
14804
  } catch (error) {
14679
14805
  return failure(error instanceof Error ? error.message : String(error));
14680
14806
  }
@@ -15038,6 +15164,12 @@ var readTool = {
15038
15164
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
15039
15165
  );
15040
15166
  }
15167
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
15168
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
15169
+ }
15170
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
15171
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
15172
+ }
15041
15173
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
15042
15174
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
15043
15175
  const window = windowText(section.body, fromLine, lineCount);
@@ -15487,6 +15619,8 @@ var COMMAND_OPTION_SCOPE = {
15487
15619
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
15488
15620
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
15489
15621
  // list, so removing them narrows the two together.
15622
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
15623
+ update: ["format", "help"],
15490
15624
  report: [
15491
15625
  "cwd",
15492
15626
  "out-dir",
@@ -15848,6 +15982,13 @@ function buildAgentContract() {
15848
15982
  positionals: [],
15849
15983
  exits: [0]
15850
15984
  },
15985
+ {
15986
+ name: "update",
15987
+ aliases: [],
15988
+ summary: "Ask the npm registry whether a newer release exists and print the version it compared against. Exit 0 when current, 1 when an update is available, 2 when the registry could not be reached. The passive notice is suppressed in CI and JSON output; this command always asks and bypasses the cache.",
15989
+ positionals: [],
15990
+ exits: [0, 1, 2]
15991
+ },
15851
15992
  {
15852
15993
  name: "skill",
15853
15994
  aliases: [],
@@ -16143,14 +16284,14 @@ function buildAgentContract() {
16143
16284
  type: "boolean",
16144
16285
  default: false,
16145
16286
  appliesTo: optionAppliesTo("include-diffs"),
16146
- summary: "Also write reports/diff.md: the unstaged and staged diff, with the command that produced each, bounded to 200 KiB and truncated with a note. Absent when there is no change."
16287
+ summary: "Also write reports/diff.md: the unstaged and staged diff, with the command that produced each, bounded to 200 KiB and truncated with a note. Absent when there is no change; outside a git repository the run warns and writes nothing."
16147
16288
  },
16148
16289
  {
16149
16290
  flag: "--include-logs",
16150
16291
  type: "string",
16151
16292
  default: "unset",
16152
16293
  appliesTo: optionAppliesTo("include-logs"),
16153
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
16294
+ summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first. Outside a git repository the run warns and writes nothing."
16154
16295
  },
16155
16296
  {
16156
16297
  flag: "--token-tree",
@@ -17144,6 +17285,18 @@ function createMcpServer(options) {
17144
17285
  if (!isJsonObject(rawArguments)) {
17145
17286
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
17146
17287
  }
17288
+ const missing = (prompt.arguments ?? []).filter((argument) => {
17289
+ if (argument.required !== true) return false;
17290
+ const value = rawArguments[argument.name];
17291
+ return typeof value !== "string" || value.trim() === "";
17292
+ });
17293
+ if (missing.length > 0) {
17294
+ return errorResponse(
17295
+ id,
17296
+ ERROR_CODES.invalidParams,
17297
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
17298
+ );
17299
+ }
17147
17300
  const built = prompt.build(rawArguments);
17148
17301
  const messages = built.messages.map((message) => ({
17149
17302
  role: message.role,
@@ -17611,20 +17764,20 @@ var SERVE_PAGE = `<!doctype html>
17611
17764
  <header><b>codebase-snapshot</b><span>a snapshot an agent can trust</span></header>
17612
17765
  <main>
17613
17766
  <form id="gen">
17614
- <input id="source" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
17615
- <select id="mode" title="What to generate">
17767
+ <input id="source" aria-label="repository path or URL" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
17768
+ <select id="mode" aria-label="What to generate" title="What to generate">
17616
17769
  <option value="full">whole repository</option>
17617
17770
  <option value="slice">a slice for a question</option>
17618
17771
  <option value="budget">fit a token budget</option>
17619
17772
  </select>
17620
- <input id="question" placeholder="the question (slice mode)" spellcheck="false" hidden>
17621
- <input id="budget" type="number" min="500" step="500" value="30000" title="token budget" hidden>
17773
+ <input id="question" aria-label="Question for the slice" placeholder="the question (slice mode)" spellcheck="false" hidden>
17774
+ <input id="budget" type="number" min="500" step="500" value="30000" aria-label="Token budget" title="token budget" hidden>
17622
17775
  <button id="run" type="submit">Generate</button>
17623
17776
  <button id="download" type="button" disabled>Download .zip</button>
17624
17777
  </form>
17625
- <div id="status">Paste an absolute path, or a repository URL (https://github.com/owner/repo). Remote fetches are shallow and public-only.</div>
17778
+ <div id="status" role="status" aria-live="polite">Paste an absolute path, or a repository URL (https://github.com/owner/repo). Remote fetches are shallow and public-only.</div>
17626
17779
  <div id="auth" hidden>
17627
- <form id="token-form"><input id="token" type="password" placeholder="paste the token printed by snapshot serve" style="flex:1"><button type="submit">Use token</button></form>
17780
+ <form id="token-form"><input id="token" type="password" aria-label="Server token" placeholder="paste the token printed by snapshot serve" style="flex:1"><button type="submit">Use token</button></form>
17628
17781
  </div>
17629
17782
  <div class="row">
17630
17783
  <section><h2>Brief <span id="fingerprint"></span> <span id="health"></span></h2><pre id="brief">No snapshot loaded.</pre></section>
@@ -17739,7 +17892,7 @@ async function startWebServer(options) {
17739
17892
  const host = options.host ?? "127.0.0.1";
17740
17893
  const port = options.port ?? DEFAULT_PORT;
17741
17894
  const log = options.log ?? ((line) => process.stderr.write(line + "\n"));
17742
- const token = options.token === void 0 ? crypto4.randomBytes(18).toString("base64url") : options.token;
17895
+ const token = options.token === void 0 ? crypto.randomBytes(18).toString("base64url") : options.token;
17743
17896
  if (token === null && !["127.0.0.1", "localhost", "::1"].includes(host)) {
17744
17897
  throw new Error("Refusing to serve " + host + " without a token.");
17745
17898
  }
@@ -17760,7 +17913,7 @@ async function startWebServer(options) {
17760
17913
  if (match === null) return false;
17761
17914
  const given = Buffer.from(match[1].trim(), "utf8");
17762
17915
  const expected = Buffer.from(token, "utf8");
17763
- return given.length === expected.length && crypto4.timingSafeEqual(given, expected);
17916
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
17764
17917
  };
17765
17918
  const server = http__namespace.createServer((request, response) => {
17766
17919
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
@@ -17919,9 +18072,14 @@ async function startWebServer(options) {
17919
18072
  send(400, { error: "not a directory: " + target });
17920
18073
  return;
17921
18074
  }
18075
+ const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
18076
+ if (loaded.errors.length > 0) {
18077
+ send(400, { error: loaded.errors.join("; ") });
18078
+ return;
18079
+ }
17922
18080
  const started = Date.now();
17923
18081
  try {
17924
- const manifest = generateSnapshot({ cwd: target }, {
18082
+ const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
17925
18083
  ...provenance === void 0 ? {} : { source: provenance },
17926
18084
  ...mode === "slice" ? { slice: { question } } : {},
17927
18085
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
@@ -18054,8 +18212,8 @@ async function startWebServer(options) {
18054
18212
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
18055
18213
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
18056
18214
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
18057
- var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
18058
- var REQUEST_TIMEOUT_MS = 1200;
18215
+ var FAILURE_INTERVAL_MS = 5 * 60 * 1e3;
18216
+ var REQUEST_TIMEOUT_MS = 2500;
18059
18217
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
18060
18218
  const normalise = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
18061
18219
  const script = normalise(scriptPath);
@@ -18119,7 +18277,7 @@ function shouldCheck(argv, env) {
18119
18277
  if (env.CI !== void 0 && env.CI !== "" && env.CI !== "false" && env.CI !== "0") return false;
18120
18278
  const args = argv.map((argument) => argument.toLowerCase());
18121
18279
  if (args.includes("--no-update-check")) return false;
18122
- for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
18280
+ for (const skip of ["mcp", "describe", "skill", "update", "--version", "-v", "--help", "-h"]) {
18123
18281
  if (args.includes(skip)) return false;
18124
18282
  }
18125
18283
  let format = null;
@@ -18215,13 +18373,19 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
18215
18373
  });
18216
18374
  }
18217
18375
  async function checkForUpdate(options) {
18376
+ const latest = await resolveLatest(options);
18377
+ if (!latest) return null;
18378
+ return isNewer(latest, options.current) ? { current: options.current, latest } : null;
18379
+ }
18380
+ async function resolveLatest(options) {
18218
18381
  if (options.enabled === false) return null;
18219
18382
  const now = options.now ?? (() => Date.now());
18220
18383
  const fetchLatest = options.fetchLatest ?? fetchLatestVersion;
18384
+ const latestUrl = options.latestUrl ?? PACKAGE_LATEST_URL;
18221
18385
  let latest = null;
18222
18386
  try {
18223
18387
  const cached = readCache(options.cacheFile);
18224
- let needsFetch = cached === null;
18388
+ let needsFetch = cached === null || options.force === true;
18225
18389
  if (cached) {
18226
18390
  const age = now() - cached.checkedAt;
18227
18391
  if (cached.latest === null) {
@@ -18233,15 +18397,14 @@ async function checkForUpdate(options) {
18233
18397
  }
18234
18398
  }
18235
18399
  if (needsFetch) {
18236
- const fetched = await fetchLatest(PACKAGE_LATEST_URL, REQUEST_TIMEOUT_MS);
18400
+ const fetched = await fetchLatest(latestUrl, REQUEST_TIMEOUT_MS);
18237
18401
  writeCache(options.cacheFile, { checkedAt: now(), latest: fetched });
18238
- latest = fetched;
18402
+ latest = fetched ?? latest;
18239
18403
  }
18240
18404
  } catch {
18241
18405
  return null;
18242
18406
  }
18243
- if (!latest) return null;
18244
- return isNewer(latest, options.current) ? { current: options.current, latest } : null;
18407
+ return latest;
18245
18408
  }
18246
18409
  function formatUpdateNotice(notice, kind) {
18247
18410
  return `\u2191 codebase-snapshot ${notice.latest} is available \u2014 you have ${notice.current}.
@@ -18551,7 +18714,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
18551
18714
  };
18552
18715
  }
18553
18716
  function sha256Hex2(input) {
18554
- return crypto4__namespace.createHash("sha256").update(input).digest("hex");
18717
+ return crypto__namespace.createHash("sha256").update(input).digest("hex");
18555
18718
  }
18556
18719
  var TS_EXTENSIONS = [
18557
18720
  ".ts",
@@ -19301,7 +19464,7 @@ function acquireRunLock(stagingRoot) {
19301
19464
  pid: process.pid,
19302
19465
  stagingRoot,
19303
19466
  host: os2__namespace.hostname(),
19304
- runId: crypto4__namespace.randomUUID(),
19467
+ runId: crypto__namespace.randomUUID(),
19305
19468
  heartbeatMs: LOCK_HEARTBEAT_MS,
19306
19469
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
19307
19470
  })}
@@ -19990,6 +20153,11 @@ function generateSnapshot(configInput, options) {
19990
20153
  detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
19991
20154
  files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
19992
20155
  };
20156
+ if (plan.files.length === 0) {
20157
+ warnings.push(
20158
+ "The slice selected no files for this question, so the snapshot is empty. " + (plan.notes.length > 0 ? plan.notes[0] : "See the plan notes in the manifest.")
20159
+ );
20160
+ }
19993
20161
  }
19994
20162
  let budgetBlock;
19995
20163
  if (options?.budgetTokens !== void 0) {
@@ -20081,6 +20249,11 @@ function generateSnapshot(configInput, options) {
20081
20249
  warnings.push("No file fits --budget-tokens " + budget + "; the snapshot is empty.");
20082
20250
  }
20083
20251
  }
20252
+ if (config.include.length > 0 && files.length === 0) {
20253
+ warnings.push(
20254
+ "No file matched the include allow-list (" + config.include.length + " pattern(s): " + config.include.join(", ") + "), so the snapshot is empty."
20255
+ );
20256
+ }
20084
20257
  if (changedScope !== null || options?.deltaBase !== void 0) {
20085
20258
  const detail = changedScope !== null ? `not ${changedScope.detail}` : "identical to the base snapshot given with --delta";
20086
20259
  for (const relativePath of unchangedPaths) {
@@ -20219,6 +20392,12 @@ function generateSnapshot(configInput, options) {
20219
20392
  maxMonolithBytes: config.maxMonolithBytes ?? null,
20220
20393
  includeSensitiveFiles: config.includeSensitiveFiles,
20221
20394
  ...config.stripComments === true ? { stripComments: true } : {},
20395
+ // The other three settings the digest covers and the manifest did not record: without them a
20396
+ // validator (or `snapshot_review`) had no way to reconstruct the run, so a snapshot taken
20397
+ // with `--remove-empty-lines`, `--pack` or `--include-logs 3` looked stale forever.
20398
+ ...config.removeEmptyLines === true ? { removeEmptyLines: true } : {},
20399
+ ...config.pack === null ? {} : { pack: config.pack },
20400
+ logCount: config.logCount,
20222
20401
  // The destination the instructions were written for. Not part of `digest`: the payload is
20223
20402
  // identical whatever this says, and a new delivery preference must not make an existing
20224
20403
  // snapshot fail `validate` as configuration drift.
@@ -20362,6 +20541,18 @@ function generateSnapshot(configInput, options) {
20362
20541
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
20363
20542
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20364
20543
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
20544
+ if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20545
+ manifest.warnings.push(
20546
+ "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
20547
+ );
20548
+ manifest.totals.warningCount = manifest.warnings.length;
20549
+ }
20550
+ if (artifacts.log && logReport === null && !isGitRepository(config.cwd)) {
20551
+ manifest.warnings.push(
20552
+ "--include-logs was requested, but the generated directory is not a git repository; reports/log.md was not written."
20553
+ );
20554
+ manifest.totals.warningCount = manifest.warnings.length;
20555
+ }
20365
20556
  if (logReport !== null) manifest.artifacts.log = artifactRecord(logReport.text);
20366
20557
  const tokenTree = artifacts.tokenTree ? generateTokenTree(manifest) : null;
20367
20558
  if (tokenTree !== null) manifest.artifacts.tokenTree = artifactRecord(tokenTree.text);
@@ -20411,17 +20602,19 @@ function generateSnapshot(configInput, options) {
20411
20602
  if (wantsXml) manifest.warnings.push(`full-codebase.xml skipped: ${reason}`);
20412
20603
  }
20413
20604
  const markdown = definitelyTooLarge || !wantsMarkdown ? null : generateMonolithMarkdown(manifest, fullFiles);
20414
- const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
20415
- if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
20416
- monolithMarkdown = markdown;
20417
- manifest.artifacts.fullMarkdown = {
20418
- byteSize: markdownBytes,
20419
- sha256: sha256Hex2(markdown)
20420
- };
20421
- } else if (!definitelyTooLarge) {
20422
- manifest.warnings.push(
20423
- `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20424
- );
20605
+ if (markdown !== null) {
20606
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
20607
+ if (config.maxMonolithBytes === null || markdownBytes <= config.maxMonolithBytes) {
20608
+ monolithMarkdown = markdown;
20609
+ manifest.artifacts.fullMarkdown = {
20610
+ byteSize: markdownBytes,
20611
+ sha256: sha256Hex2(markdown)
20612
+ };
20613
+ } else {
20614
+ manifest.warnings.push(
20615
+ `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20616
+ );
20617
+ }
20425
20618
  }
20426
20619
  if (wantsXml && !definitelyTooLarge) {
20427
20620
  const xml = generateMonolithXml(manifest, fullFiles);
@@ -20437,14 +20630,16 @@ function generateSnapshot(configInput, options) {
20437
20630
  }
20438
20631
  manifest.totals.warningCount = manifest.warnings.length;
20439
20632
  const json = definitelyTooLarge || !wantsJson ? null : generateMonolithJson(manifest, fullFiles);
20440
- const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
20441
- if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
20442
- monolithJson = json;
20443
- manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20444
- } else if (!definitelyTooLarge) {
20445
- manifest.warnings.push(
20446
- `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20447
- );
20633
+ if (json !== null) {
20634
+ const jsonBytes = Buffer.byteLength(json, "utf8");
20635
+ if (config.maxMonolithBytes === null || jsonBytes <= config.maxMonolithBytes) {
20636
+ monolithJson = json;
20637
+ manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20638
+ } else {
20639
+ manifest.warnings.push(
20640
+ `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20641
+ );
20642
+ }
20448
20643
  }
20449
20644
  manifest.totals.warningCount = manifest.warnings.length;
20450
20645
  }
@@ -20473,7 +20668,7 @@ function generateSnapshot(configInput, options) {
20473
20668
  ensureParentDirectory(outDir, "outDir");
20474
20669
  fs24__namespace.mkdirSync(tmpDir, { recursive: true });
20475
20670
  cleanStaleRunDirs(tmpDir);
20476
- const snapshotId = crypto4__namespace.randomUUID();
20671
+ const snapshotId = crypto__namespace.randomUUID();
20477
20672
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
20478
20673
  stagingDir = path27__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
20479
20674
  fs24__namespace.mkdirSync(stagingDir);
@@ -20719,7 +20914,7 @@ var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
20719
20914
  var RATE_LIMIT = 60;
20720
20915
  var RATE_WINDOW_MS = 1e4;
20721
20916
  function generateToken() {
20722
- return crypto4__namespace.randomBytes(24).toString("base64url");
20917
+ return crypto__namespace.randomBytes(24).toString("base64url");
20723
20918
  }
20724
20919
  function isLoopbackOrigin(origin) {
20725
20920
  try {
@@ -20735,7 +20930,7 @@ function timingSafeEqual3(left, right) {
20735
20930
  const a = Buffer.from(left, "utf8");
20736
20931
  const b = Buffer.from(right, "utf8");
20737
20932
  if (a.length !== b.length) return false;
20738
- return crypto4__namespace.timingSafeEqual(a, b);
20933
+ return crypto__namespace.timingSafeEqual(a, b);
20739
20934
  }
20740
20935
  async function startHttpTransport(options) {
20741
20936
  const host = options.host ?? "127.0.0.1";
@@ -20780,6 +20975,7 @@ async function startHttpTransport(options) {
20780
20975
  noteRequest(request);
20781
20976
  const send = (status, body, extra = {}) => {
20782
20977
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
20978
+ if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
20783
20979
  response.writeHead(status, {
20784
20980
  "content-type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json",
20785
20981
  "content-length": Buffer.byteLength(text2, "utf8"),
@@ -20791,7 +20987,6 @@ async function startHttpTransport(options) {
20791
20987
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
20792
20988
  const allowed = allowedOrigin(origin);
20793
20989
  if (origin !== void 0 && allowed === null) {
20794
- metrics.refused += 1;
20795
20990
  send(403, { error: "origin not allowed" });
20796
20991
  return;
20797
20992
  }
@@ -20829,7 +21024,7 @@ async function startHttpTransport(options) {
20829
21024
  "# HELP snapshot_requests_total HTTP requests received.",
20830
21025
  "# TYPE snapshot_requests_total counter",
20831
21026
  "snapshot_requests_total " + metrics.requests,
20832
- "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
21027
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch (4xx other than 429).",
20833
21028
  "# TYPE snapshot_requests_refused_total counter",
20834
21029
  "snapshot_requests_refused_total " + metrics.refused,
20835
21030
  "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
@@ -20854,7 +21049,7 @@ async function startHttpTransport(options) {
20854
21049
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
20855
21050
  return;
20856
21051
  }
20857
- const id = crypto4__namespace.randomBytes(12).toString("hex");
21052
+ const id = crypto__namespace.randomBytes(12).toString("hex");
20858
21053
  response.writeHead(200, {
20859
21054
  ...cors,
20860
21055
  "content-type": "text/event-stream",
@@ -21031,6 +21226,7 @@ var COMMAND_ALIASES = /* @__PURE__ */ new Map([
21031
21226
  ["describe", "describe"],
21032
21227
  ["skill", "skill"],
21033
21228
  ["mcp", "mcp"],
21229
+ ["update", "update"],
21034
21230
  ["serve", "serve"]
21035
21231
  ]);
21036
21232
  var COMMAND_ARITY = {
@@ -21045,6 +21241,7 @@ var COMMAND_ARITY = {
21045
21241
  describe: 0,
21046
21242
  skill: 0,
21047
21243
  mcp: 0,
21244
+ update: 0,
21048
21245
  serve: 0
21049
21246
  };
21050
21247
  var CLI_OPTIONS = {
@@ -21140,6 +21337,7 @@ Commands:
21140
21337
  explain <path> Show how one path would be treated: layer, kind, part, skips
21141
21338
  diff <a> <b> Compare two snapshots (directories or manifest.json files)
21142
21339
  describe Print the machine-readable contract (--format json for agents)
21340
+ update Ask the registry whether a newer release exists (exit 1 if one does)
21143
21341
  skill Print the bundled agent skill; --install writes it into the repo
21144
21342
  mcp Serve this repository to an MCP client (stdio, or --http for the web)
21145
21343
  serve Open a browser UI: generate, preview, download a zip; MCP at /mcp
@@ -21982,6 +22180,37 @@ async function firstRun(invocation) {
21982
22180
  );
21983
22181
  return await runSetupCommand(invocation, { interactive: plan.interactive });
21984
22182
  }
22183
+ async function runUpdateCommand(invocation) {
22184
+ const current = GENERATOR_VERSION;
22185
+ const latestUrl = process.env.CODEBASE_SNAPSHOT_REGISTRY_URL;
22186
+ const latest = await resolveLatest({
22187
+ current,
22188
+ cacheFile: cacheFilePath(),
22189
+ force: true,
22190
+ ...latestUrl === void 0 || latestUrl === "" ? {} : { latestUrl }
22191
+ });
22192
+ if (latest === null) {
22193
+ emit(invocation.format, { current, latest: null, updateAvailable: false }, () => {
22194
+ info(
22195
+ "Could not reach the npm registry, so the installed version could not be compared. Nothing was changed; try again when the network is available."
22196
+ );
22197
+ });
22198
+ return 2;
22199
+ }
22200
+ const kind = installKind();
22201
+ const updateAvailable = isNewer(latest, current);
22202
+ const command = updateCommand(kind);
22203
+ emit(invocation.format, { current, latest, updateAvailable, command }, () => {
22204
+ if (updateAvailable) {
22205
+ info(formatUpdateNotice({ current, latest }, kind));
22206
+ } else {
22207
+ info(
22208
+ `You are on codebase-snapshot ${current}, and the registry publishes ${latest}. No update is available.`
22209
+ );
22210
+ }
22211
+ });
22212
+ return updateAvailable ? 1 : 0;
22213
+ }
21985
22214
  function runSkillCommand(invocation) {
21986
22215
  if (!invocation.install) {
21987
22216
  if (invocation.format === "json") {
@@ -22123,6 +22352,9 @@ ${USAGE}
22123
22352
  if (invocation.command === "skill") {
22124
22353
  return runSkillCommand(invocation);
22125
22354
  }
22355
+ if (invocation.command === "update") {
22356
+ return runUpdateCommand(invocation);
22357
+ }
22126
22358
  if (invocation.command === "serve") {
22127
22359
  const server = await startWebServer({
22128
22360
  cwd: path27__namespace.resolve(invocation.cwd),
@@ -22540,8 +22772,9 @@ ${USAGE}
22540
22772
  }
22541
22773
  const started = performance.now();
22542
22774
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
22775
+ const headerGit = getGitInfo(resolved.cwd, resolved.branch);
22543
22776
  info(
22544
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
22777
+ ` Branch: ${resolved.branch}${headerGit.branchFromGit ? "" : " (fallback)"} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
22545
22778
  );
22546
22779
  try {
22547
22780
  let deltaBase;