codebase-snapshot 0.17.0 → 0.19.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);
@@ -1903,7 +1903,11 @@ function scanAndRedactSecrets(content, rules, filePath) {
1903
1903
  let finalText = segments.join("");
1904
1904
  finalText = redactStructuredValues(finalText, filePath, recordFinding);
1905
1905
  finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
1906
- const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
1906
+ const originalLines = content.split(/\r\n|\r|\n/);
1907
+ const findings = [...findingsByLine.entries()].filter(([line]) => {
1908
+ const original = originalLines[line - 1] ?? "";
1909
+ return !original.includes(REDACTION_MARKER) && !original.includes(PEM_REDACTION_MARKER);
1910
+ }).sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
1907
1911
  rules: [...rulesForLine],
1908
1912
  line,
1909
1913
  path: filePath
@@ -1971,8 +1975,8 @@ function redactStructuredValues(text2, filePath, recordFinding) {
1971
1975
  if (body.trim() !== "") {
1972
1976
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
1973
1977
  if (indent <= baseIndent) break;
1978
+ if (!isMarkerLine(body)) masked2 = true;
1974
1979
  segments[cursor2] = maskLineContent(body);
1975
- masked2 = true;
1976
1980
  }
1977
1981
  cursor2 += 2;
1978
1982
  }
@@ -1992,8 +1996,8 @@ function redactStructuredValues(text2, filePath, recordFinding) {
1992
1996
  if (body.trim() !== "") {
1993
1997
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
1994
1998
  if (indent < valueIndent) break;
1999
+ if (!isMarkerLine(body)) masked = true;
1995
2000
  segments[cursor] = maskValueLine(body);
1996
- masked = true;
1997
2001
  }
1998
2002
  cursor += 2;
1999
2003
  }
@@ -2103,10 +2107,14 @@ var PLACEHOLDER_PATTERNS = [
2103
2107
  /^your[-_ ].*$/i,
2104
2108
  /^(?:example|sample)(?:[-_ ].*)?$/i
2105
2109
  ];
2110
+ function isMarkerLine(value) {
2111
+ return value.includes(REDACTION_MARKER) || value.includes(PEM_REDACTION_MARKER);
2112
+ }
2106
2113
  function isPlaceholderValue(value) {
2107
2114
  const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
2108
2115
  if (trimmed.length === 0) return false;
2109
2116
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2117
+ if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
2110
2118
  return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2111
2119
  }
2112
2120
  function quotesAreBalanced(text2) {
@@ -2221,7 +2229,7 @@ function applySpansKeepingQuotes(line, spans) {
2221
2229
 
2222
2230
  // src/version.ts
2223
2231
  var GENERATOR_NAME = "codebase-snapshot";
2224
- var GENERATOR_VERSION = "0.17.0";
2232
+ var GENERATOR_VERSION = "0.19.0";
2225
2233
  var SCHEMA_VERSION = "3.0.0";
2226
2234
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2227
2235
  function isOurGeneratorName(name) {
@@ -2272,6 +2280,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2272
2280
  let branch = fallbackBranch;
2273
2281
  let commit = "unknown";
2274
2282
  let isDirty = false;
2283
+ let branchFromGit = false;
2275
2284
  const records = output.split("\0").flatMap((record) => record.split("\n"));
2276
2285
  for (const record of records) {
2277
2286
  if (record.length === 0) continue;
@@ -2287,13 +2296,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2287
2296
  const head = record.match(/^# branch\.head (.+)$/);
2288
2297
  if (head) {
2289
2298
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
2299
+ branchFromGit = head[1] !== "(detached)";
2290
2300
  }
2291
2301
  }
2292
- return { branch, commit, isDirty };
2302
+ return { branch, commit, isDirty, branchFromGit };
2293
2303
  } catch (err) {
2294
2304
  const code = err.code;
2295
2305
  const isDirty = code === "ENOBUFS";
2296
- return { branch: fallbackBranch, commit: "unknown", isDirty };
2306
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
2297
2307
  }
2298
2308
  }
2299
2309
  var DEFAULT_IGNORED_DIRS = [
@@ -3389,7 +3399,7 @@ function parseOwnerBrief(filePath, text2) {
3389
3399
  return {
3390
3400
  brief: {
3391
3401
  path: filePath,
3392
- digest: crypto4.createHash("sha256").update(text2, "utf8").digest("hex"),
3402
+ digest: crypto.createHash("sha256").update(text2, "utf8").digest("hex"),
3393
3403
  ...recognised["Stakes"] ? { stakes: recognised["Stakes"] } : {},
3394
3404
  ...recognised["The system"] ? { system: recognised["The system"] } : {},
3395
3405
  ...recognised["What came before"] ? { history: recognised["What came before"] } : {},
@@ -3661,7 +3671,7 @@ function readConfigExport(exported, file) {
3661
3671
  var lastModuleConfig = null;
3662
3672
  function moduleConfigKey(fullPath) {
3663
3673
  try {
3664
- return crypto4.createHash("sha256").update(fs24__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3674
+ return crypto.createHash("sha256").update(fs24__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3665
3675
  } catch {
3666
3676
  try {
3667
3677
  const stats = fs24__namespace.statSync(fullPath);
@@ -4509,7 +4519,7 @@ function configDigest(config) {
4509
4519
  (rule) => `${rule.rule}:${rule.pattern.source}/${rule.pattern.flags}:${rule.valueGroup ?? ""}`
4510
4520
  ).sort()
4511
4521
  };
4512
- return crypto4.createHash("sha256").update(JSON.stringify(material)).digest("hex");
4522
+ return crypto.createHash("sha256").update(JSON.stringify(material)).digest("hex");
4513
4523
  }
4514
4524
  function gitPaths(cwd, args) {
4515
4525
  let output;
@@ -4985,7 +4995,7 @@ function summarizeTypeScriptSource(relativePath, content) {
4985
4995
  }
4986
4996
  const callee = node.expression;
4987
4997
  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());
4998
+ summary.routeHandlers.push(callee.name.text.toUpperCase() + " " + firstArgument.text);
4989
4999
  }
4990
5000
  }
4991
5001
  if (ts2__default.default.isExportDeclaration(node)) {
@@ -6225,6 +6235,69 @@ function importsOfFile(relativePath, absolutePath) {
6225
6235
  if (decoded.binary) return [];
6226
6236
  return importsOfText(relativePath, decoded.text);
6227
6237
  }
6238
+ var SIGNATURE_FILE = "signature.json";
6239
+ function loadSigningKey(environment = process.env) {
6240
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
6241
+ if (pem === void 0 || pem.trim() === "") return null;
6242
+ return crypto__namespace.createPrivateKey({ key: pem, format: "pem" });
6243
+ }
6244
+ function signManifest(manifestPath, options = {}) {
6245
+ const bytes = fs24__namespace.readFileSync(manifestPath);
6246
+ const manifest = JSON.parse(bytes.toString("utf8"));
6247
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
6248
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
6249
+ }
6250
+ const configured = options.key ?? null;
6251
+ const key = configured ?? crypto__namespace.generateKeyPairSync("ed25519").privateKey;
6252
+ const publicKey = crypto__namespace.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
6253
+ const signature = crypto__namespace.sign(null, bytes, key).toString("base64");
6254
+ return {
6255
+ algorithm: "ed25519",
6256
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6257
+ fingerprint: manifest.fingerprint,
6258
+ manifestSha256: crypto__namespace.createHash("sha256").update(bytes).digest("hex"),
6259
+ publicKey,
6260
+ signature,
6261
+ keyOrigin: configured === null ? "generated" : "configured"
6262
+ };
6263
+ }
6264
+ function writeSignature(snapshotDir, record) {
6265
+ const target = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
6266
+ fs24__namespace.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
6267
+ return target;
6268
+ }
6269
+ function verifySnapshotSignature(snapshotDir) {
6270
+ const signaturePath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
6271
+ const manifestPath = path27__namespace.join(snapshotDir, "manifest.json");
6272
+ if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
6273
+ let record;
6274
+ try {
6275
+ record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
6276
+ } catch (error) {
6277
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
6278
+ }
6279
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
6280
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
6281
+ }
6282
+ let bytes;
6283
+ try {
6284
+ bytes = fs24__namespace.readFileSync(manifestPath);
6285
+ } catch {
6286
+ return { ok: false, reason: "the signed manifest is missing" };
6287
+ }
6288
+ const sha2562 = crypto__namespace.createHash("sha256").update(bytes).digest("hex");
6289
+ if (sha2562 !== record.manifestSha256) {
6290
+ return { ok: false, reason: "manifest.json changed after it was signed" };
6291
+ }
6292
+ let verified = false;
6293
+ try {
6294
+ const key = crypto__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
6295
+ verified = crypto__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
6296
+ } catch (error) {
6297
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
6298
+ }
6299
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
6300
+ }
6228
6301
 
6229
6302
  // src/validator/validate.ts
6230
6303
  function maskedPath(value, secretRules) {
@@ -6290,7 +6363,7 @@ function emptyDrift() {
6290
6363
  };
6291
6364
  }
6292
6365
  function sha256Hex(buffer) {
6293
- return crypto4__namespace.createHash("sha256").update(buffer).digest("hex");
6366
+ return crypto__namespace.createHash("sha256").update(buffer).digest("hex");
6294
6367
  }
6295
6368
  function wouldNowBeIncluded(cwd, relativePath) {
6296
6369
  const absolutePath = path27__namespace.join(cwd, relativePath);
@@ -7227,6 +7300,11 @@ function validateSnapshot(configInput) {
7227
7300
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
7228
7301
  );
7229
7302
  }
7303
+ const signaturePath = path27__namespace.join(path27__namespace.dirname(manifestPath), "signature.json");
7304
+ if (fs24__namespace.existsSync(signaturePath)) {
7305
+ const outcome = verifySnapshotSignature(path27__namespace.dirname(manifestPath));
7306
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
7307
+ }
7230
7308
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
7231
7309
  warnings.push(
7232
7310
  "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 +9452,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
9374
9452
  "# Codebase Health & Security Audit",
9375
9453
  "",
9376
9454
  `**Generated:** ${manifest.generatedAt} `,
9377
- `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
9455
+ `**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
9456
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
9379
9457
  `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
9380
9458
  `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
@@ -9531,7 +9609,7 @@ var BUILTIN_RULE_IDS = new Map(
9531
9609
  function ruleIdFor(name) {
9532
9610
  const builtin = BUILTIN_RULE_IDS.get(name);
9533
9611
  if (builtin !== void 0) return builtin;
9534
- const digest = crypto4__namespace.createHash("sha256").update(name).digest("hex").slice(0, 8);
9612
+ const digest = crypto__namespace.createHash("sha256").update(name).digest("hex").slice(0, 8);
9535
9613
  return `CS${digest.toUpperCase()}`;
9536
9614
  }
9537
9615
  function generateSarifReport(manifest, findings, rules, toolVersion) {
@@ -9871,7 +9949,7 @@ function rehashPart(part, markdown) {
9871
9949
  metadata: {
9872
9950
  ...part.metadata,
9873
9951
  byteSize: Buffer.byteLength(redistributed, "utf8"),
9874
- sha256: crypto4__namespace.createHash("sha256").update(redistributed).digest("hex"),
9952
+ sha256: crypto__namespace.createHash("sha256").update(redistributed).digest("hex"),
9875
9953
  lines: countLines(redistributed),
9876
9954
  estimatedTokens
9877
9955
  }
@@ -9952,7 +10030,7 @@ function renderGroups(groups, contentFingerprint, assemble = (group, index, tota
9952
10030
  return groups.map((group, index) => {
9953
10031
  const { filename, content, estimatedTokens } = assemble(group, index, total);
9954
10032
  const byteSize = Buffer.byteLength(content, "utf8");
9955
- const sha2562 = crypto4__namespace.createHash("sha256").update(content).digest("hex");
10033
+ const sha2562 = crypto__namespace.createHash("sha256").update(content).digest("hex");
9956
10034
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
9957
10035
  const includedFiles = group.sections.map(({ file }) => ({
9958
10036
  relativePath: file.relativePath,
@@ -10034,7 +10112,7 @@ function renderSummary(summary, inclusionMode) {
10034
10112
  }
10035
10113
  function anchorForPath(filePath) {
10036
10114
  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);
10115
+ const digest = crypto__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
10038
10116
  return `${slug || "file"}-${digest}`;
10039
10117
  }
10040
10118
 
@@ -10381,13 +10459,19 @@ function planForQuestion(manifest, question, options = {}) {
10381
10459
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
10382
10460
  }
10383
10461
  const notes = [];
10462
+ if (manifest.files.length === 0) {
10463
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
10464
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
10465
+ }
10384
10466
  if (scored.length === 0) {
10385
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10386
10467
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
10387
10468
  for (const hub of hubs) {
10388
10469
  const file = byPath.get(hub.path);
10389
10470
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
10390
10471
  }
10472
+ if (scored.length > 0) {
10473
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10474
+ }
10391
10475
  }
10392
10476
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
10393
10477
  const chosen = /* @__PURE__ */ new Map();
@@ -10451,7 +10535,14 @@ function planForQuestion(manifest, question, options = {}) {
10451
10535
  }
10452
10536
  }
10453
10537
  }
10454
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
10538
+ if (chosen.size === 0) {
10539
+ if (scored.length === 0) {
10540
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
10541
+ } else {
10542
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
10543
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber2(cheapest) + " tokens.");
10544
+ }
10545
+ }
10455
10546
  notes.push(
10456
10547
  formatNumber2(chosen.size) + " file(s) chosen of " + formatNumber2(manifest.files.length) + " in the snapshot; " + formatNumber2(skipped.length) + " skipped for budget."
10457
10548
  );
@@ -11017,7 +11108,7 @@ function snapshotSection(manifest, code, partsWritten) {
11017
11108
  const out = ["## This snapshot", ""];
11018
11109
  out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
11019
11110
  out.push(
11020
- "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
11111
+ "- 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
11112
  );
11022
11113
  out.push(
11023
11114
  manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
@@ -11190,7 +11281,7 @@ function generateReadme(manifest, artifacts) {
11190
11281
  "",
11191
11282
  `- **Generated At:** \`${manifest.generatedAt}\``,
11192
11283
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
11193
- `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
11284
+ `- **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
11285
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
11195
11286
  `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
11196
11287
  `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
@@ -11767,69 +11858,6 @@ function negotiateLegacyVersion(requested) {
11767
11858
  }
11768
11859
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
11769
11860
  }
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
11861
 
11834
11862
  // src/partitioner/part-format.ts
11835
11863
  var FILE_HEADING = "### FILE: ";
@@ -11935,7 +11963,7 @@ var ARTIFACT_FILES = {
11935
11963
  };
11936
11964
  var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
11937
11965
  function sha256(buffer) {
11938
- return crypto4.createHash("sha256").update(buffer).digest("hex");
11966
+ return crypto.createHash("sha256").update(buffer).digest("hex");
11939
11967
  }
11940
11968
  function readBytes(file) {
11941
11969
  try {
@@ -12410,8 +12438,9 @@ function auditSnapshot(options) {
12410
12438
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
12411
12439
  disagreements.push("file count");
12412
12440
  }
12441
+ 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
12442
  checks.push(
12414
- disagreements.length === 0 ? check(
12443
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
12415
12444
  "workspace.index",
12416
12445
  "The workspace index agrees with this member",
12417
12446
  "warning",
@@ -12433,12 +12462,45 @@ function auditSnapshot(options) {
12433
12462
  let scannedBytes = 0;
12434
12463
  for (const relative15 of walk(snapshotDir)) {
12435
12464
  if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
12465
+ if (relative15 === SIGNATURE_FILE) continue;
12436
12466
  const text2 = readText2(path27__namespace.join(snapshotDir, relative15));
12437
12467
  if (text2 === null) continue;
12438
12468
  scannedBytes += Buffer.byteLength(text2, "utf8");
12439
- const found = scanAndRedactSecrets(text2, rules, relative15);
12440
- if (found.findings.length > 0) {
12441
- leakHits.push(relative15 + " (" + found.findings.length + " line(s))");
12469
+ let findingCount = 0;
12470
+ if (/^parts[\\/].*\.md$/i.test(relative15)) {
12471
+ let headerText = text2;
12472
+ for (const section of parsePartSections(text2)) {
12473
+ findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
12474
+ headerText = headerText.replace(section.body, "");
12475
+ }
12476
+ findingCount += scanAndRedactSecrets(headerText, rules, relative15).findings.length;
12477
+ } else {
12478
+ findingCount = scanAndRedactSecrets(text2, rules, relative15).findings.length;
12479
+ }
12480
+ if (findingCount > 0) {
12481
+ leakHits.push(relative15 + " (" + findingCount + " line(s))");
12482
+ }
12483
+ }
12484
+ const signatureRecordPath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
12485
+ if (fs24__namespace.existsSync(signatureRecordPath)) {
12486
+ const recordText = readText2(signatureRecordPath);
12487
+ if (recordText !== null) {
12488
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
12489
+ let scanText = recordText;
12490
+ try {
12491
+ const record = JSON.parse(recordText);
12492
+ const rest = { ...record };
12493
+ delete rest.publicKey;
12494
+ delete rest.signature;
12495
+ delete rest.manifestSha256;
12496
+ delete rest.fingerprint;
12497
+ scanText = JSON.stringify(rest, null, 2);
12498
+ } catch {
12499
+ }
12500
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
12501
+ if (found.findings.length > 0) {
12502
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
12503
+ }
12442
12504
  }
12443
12505
  }
12444
12506
  checks.push(
@@ -12936,6 +12998,10 @@ var WRITES = {
12936
12998
  openWorldHint: false
12937
12999
  };
12938
13000
  var MAX_RESULT_BYTES = 64 * 1024;
13001
+ function capResultText(text2) {
13002
+ const clipped = truncateToBytes(text2, MAX_RESULT_BYTES);
13003
+ return { text: clipped.isTruncated ? clipped.content : text2, clipped: clipped.isTruncated };
13004
+ }
12939
13005
  var ROOT_PROPERTY = {
12940
13006
  type: "string",
12941
13007
  description: "Repository root. Defaults to the directory this server was started in."
@@ -13123,6 +13189,17 @@ var historyTool = {
13123
13189
  isError: true
13124
13190
  };
13125
13191
  }
13192
+ const manifestRead = readManifest3(prepared.workspace);
13193
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
13194
+ if (recordedLog !== void 0 && recordedLog !== null) {
13195
+ const digest = crypto.createHash("sha256").update(text2, "utf8").digest("hex");
13196
+ if (digest !== recordedLog.sha256) {
13197
+ return {
13198
+ 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.",
13199
+ isError: true
13200
+ };
13201
+ }
13202
+ }
13126
13203
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
13127
13204
  const commits = parseHistoryReport(text2).slice(0, limit);
13128
13205
  return {
@@ -13182,9 +13259,12 @@ var budgetTool = {
13182
13259
  });
13183
13260
  }
13184
13261
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
13262
+ if (read.manifest.files.length === 0) {
13263
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
13264
+ }
13185
13265
  for (const row of rows) {
13186
13266
  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" : "") + ")")
13267
+ 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
13268
  );
13189
13269
  }
13190
13270
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -13436,7 +13516,7 @@ var routesTool = {
13436
13516
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
13437
13517
  const text2 = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
13438
13518
  routes.length + " route(s):",
13439
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
13519
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
13440
13520
  ].join("\n");
13441
13521
  return { text: text2, structured: { total: routes.length, routes } };
13442
13522
  }
@@ -13605,8 +13685,9 @@ var searchTool = {
13605
13685
  }
13606
13686
  }
13607
13687
  }
13688
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
13608
13689
  const lines = [
13609
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
13690
+ 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
13691
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
13611
13692
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
13612
13693
  ];
@@ -13629,7 +13710,9 @@ var statsTool = {
13629
13710
  parts: { type: "integer" },
13630
13711
  tokens: { type: "integer" },
13631
13712
  layers: { type: "object" },
13632
- kinds: { type: "object" }
13713
+ kinds: { type: "object" },
13714
+ heaviest: { type: "array", items: { type: "object" } },
13715
+ partSizes: { type: "array", items: { type: "object" } }
13633
13716
  }
13634
13717
  },
13635
13718
  annotations: READ_ONLY,
@@ -13640,7 +13723,11 @@ var statsTool = {
13640
13723
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13641
13724
  const manifest = read.manifest;
13642
13725
  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 }));
13726
+ const parts = manifest.parts.map((part) => ({
13727
+ filename: part.filename,
13728
+ bytes: part.byteSize,
13729
+ tokens: part.estimatedTokens
13730
+ }));
13644
13731
  const lines = [
13645
13732
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
13646
13733
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -13696,7 +13783,7 @@ var reviewTool = {
13696
13783
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13697
13784
  let validation;
13698
13785
  try {
13699
- validation = validateSnapshot(workspace.config);
13786
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
13700
13787
  } catch (error) {
13701
13788
  return { text: error.message, isError: true };
13702
13789
  }
@@ -13796,24 +13883,17 @@ var diffContextTool = {
13796
13883
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
13797
13884
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
13798
13885
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
13886
+ const resolver = buildImportResolver(read.manifest.files, {
13887
+ tsconfig: tsconfigPathsFor(workspace.root)
13888
+ });
13799
13889
  const importers = /* @__PURE__ */ new Map();
13800
13890
  for (const entry of read.manifest.indexes.imports.byFile) {
13801
13891
  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) ?? [];
13892
+ const target = resolveSpecifier(entry.path, specifier, resolver);
13893
+ if (target === null) continue;
13894
+ const list2 = importers.get(target) ?? [];
13815
13895
  list2.push(entry.path);
13816
- importers.set(target.relativePath, list2);
13896
+ importers.set(target, list2);
13817
13897
  }
13818
13898
  }
13819
13899
  const missing = [];
@@ -13848,9 +13928,12 @@ var diffContextTool = {
13848
13928
  continue;
13849
13929
  }
13850
13930
  used += tokens;
13931
+ const capped2 = capResultText(window.text);
13851
13932
  changed.push({ path: file.relativePath, part: file.part, tokens });
13852
- text2.push("### " + file.relativePath + " (" + file.part + ")");
13853
- text2.push(window.text);
13933
+ text2.push(
13934
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
13935
+ );
13936
+ text2.push(capped2.text);
13854
13937
  }
13855
13938
  const dependents = [];
13856
13939
  for (const entry of changed) {
@@ -13932,11 +14015,13 @@ var symbolTool = {
13932
14015
  if (index === -1) continue;
13933
14016
  const from = Math.max(0, index - 3);
13934
14017
  const to = Math.min(lines.length, index + windowSize);
14018
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
13935
14019
  matches.push({
13936
14020
  path: file.relativePath,
13937
14021
  part: file.part,
13938
14022
  line: index + 1,
13939
- text: lines.slice(from, to).join("\n")
14023
+ text: capped2.text,
14024
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
13940
14025
  });
13941
14026
  }
13942
14027
  if (matches.length === 0) {
@@ -14067,7 +14152,8 @@ var contextTool = {
14067
14152
  continue;
14068
14153
  }
14069
14154
  const window = windowText(section.body, 1, linesPerFile);
14070
- const body = window.text;
14155
+ const capped2 = capResultText(window.text);
14156
+ const body = capped2.text;
14071
14157
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
14072
14158
  if (used + tokens > budget) {
14073
14159
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -14076,14 +14162,19 @@ var contextTool = {
14076
14162
  missing.push(file.relativePath + " (budget)");
14077
14163
  continue;
14078
14164
  }
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);
14165
+ const smallerCapped = capResultText(smaller.text);
14166
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
14167
+ text2.push(
14168
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
14169
+ );
14170
+ text2.push(smallerCapped.text);
14082
14171
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
14083
14172
  used += partial;
14084
14173
  continue;
14085
14174
  }
14086
- text2.push("### " + file.relativePath + " (" + file.part + ")");
14175
+ text2.push(
14176
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
14177
+ );
14087
14178
  text2.push(body);
14088
14179
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
14089
14180
  used += tokens;
@@ -14257,8 +14348,17 @@ var answerTool = {
14257
14348
  maxTokens,
14258
14349
  ...args.includeTests === true ? { includeTests: true } : {}
14259
14350
  });
14351
+ if (read.manifest.files.length === 0) {
14352
+ return {
14353
+ 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).",
14354
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
14355
+ };
14356
+ }
14260
14357
  const blocks = [];
14261
- const omitted = [];
14358
+ const omitted = plan.skipped.map((entry) => ({
14359
+ path: entry.path,
14360
+ reason: entry.reason
14361
+ }));
14262
14362
  let used = 0;
14263
14363
  const parts = /* @__PURE__ */ new Map();
14264
14364
  for (const planned of plan.files) {
@@ -14287,14 +14387,23 @@ var answerTool = {
14287
14387
  continue;
14288
14388
  }
14289
14389
  const window = windowText(section.body, 1, linesPerFile);
14290
- const text2 = window.text;
14291
- const tokens = estimateTokens(text2);
14390
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
14391
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
14392
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
14393
+ const tokens = estimateTokens(bodyText);
14292
14394
  if (used + tokens > maxTokens && blocks.length > 0) {
14293
14395
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
14294
14396
  continue;
14295
14397
  }
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 });
14398
+ blocks.push({
14399
+ path: planned.path,
14400
+ why: planned.why,
14401
+ tokens,
14402
+ text: bodyText,
14403
+ truncated: window.truncated || clipped.isTruncated,
14404
+ totalLines: window.totalLines,
14405
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
14406
+ });
14298
14407
  used += tokens;
14299
14408
  }
14300
14409
  const lines = [
@@ -14303,7 +14412,9 @@ var answerTool = {
14303
14412
  ];
14304
14413
  for (const block of blocks) {
14305
14414
  lines.push("");
14306
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
14415
+ lines.push(
14416
+ "## " + 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") + ")"
14417
+ );
14307
14418
  lines.push("Why: " + block.why);
14308
14419
  lines.push("```");
14309
14420
  lines.push(block.text);
@@ -14314,6 +14425,11 @@ var answerTool = {
14314
14425
  lines.push("Not included:");
14315
14426
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
14316
14427
  }
14428
+ if (plan.notes.length > 0) {
14429
+ lines.push("");
14430
+ lines.push("Notes:");
14431
+ for (const note of plan.notes) lines.push("- " + note);
14432
+ }
14317
14433
  return {
14318
14434
  text: lines.join("\n"),
14319
14435
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -14428,7 +14544,7 @@ var statusTool = {
14428
14544
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
14429
14545
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
14430
14546
  `Fingerprint: ${manifest.fingerprint}`,
14431
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
14547
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
14432
14548
  ];
14433
14549
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
14434
14550
  if (!versionMatches) {
@@ -14579,6 +14695,16 @@ var generateTool = {
14579
14695
  minimum: 500,
14580
14696
  description: "Fit the snapshot into this token budget, highest value first."
14581
14697
  },
14698
+ only: {
14699
+ type: "array",
14700
+ items: { type: "string" },
14701
+ description: "Globs to include: replaces the config allow-list for this run."
14702
+ },
14703
+ ignore: {
14704
+ type: "array",
14705
+ items: { type: "string" },
14706
+ description: "Globs to exclude, added to the config deny-list for this run."
14707
+ },
14582
14708
  ...SCOPE_PROPERTIES
14583
14709
  },
14584
14710
  additionalProperties: false
@@ -14607,7 +14733,9 @@ var generateTool = {
14607
14733
  ...args.tokenTree === true ? { tokenTree: true } : {},
14608
14734
  ...args.stripComments === true ? { stripComments: true } : {},
14609
14735
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
14610
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
14736
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
14737
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
14738
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
14611
14739
  };
14612
14740
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
14613
14741
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -14651,6 +14779,20 @@ var generateTool = {
14651
14779
  };
14652
14780
  }
14653
14781
  };
14782
+ function configAsGenerated(workspace, manifest) {
14783
+ const recorded = manifest.config;
14784
+ return {
14785
+ ...workspace.config,
14786
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
14787
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
14788
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
14789
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
14790
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
14791
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
14792
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
14793
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
14794
+ };
14795
+ }
14654
14796
  var validateTool = {
14655
14797
  name: "snapshot_validate",
14656
14798
  title: "Validate the snapshot",
@@ -14672,9 +14814,11 @@ var validateTool = {
14672
14814
  const prepared = await prepare(args, context, workspaceOverrides(args));
14673
14815
  if (!prepared.ok) return prepared.outcome;
14674
14816
  const workspace = prepared.workspace;
14817
+ const read = readManifest3(workspace);
14818
+ if (!read.ok) return failure(read.message);
14675
14819
  let result;
14676
14820
  try {
14677
- result = validateSnapshot(workspace.config);
14821
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
14678
14822
  } catch (error) {
14679
14823
  return failure(error instanceof Error ? error.message : String(error));
14680
14824
  }
@@ -15038,6 +15182,12 @@ var readTool = {
15038
15182
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
15039
15183
  );
15040
15184
  }
15185
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
15186
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
15187
+ }
15188
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
15189
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
15190
+ }
15041
15191
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
15042
15192
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
15043
15193
  const window = windowText(section.body, fromLine, lineCount);
@@ -15487,6 +15637,8 @@ var COMMAND_OPTION_SCOPE = {
15487
15637
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
15488
15638
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
15489
15639
  // list, so removing them narrows the two together.
15640
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
15641
+ update: ["format", "help"],
15490
15642
  report: [
15491
15643
  "cwd",
15492
15644
  "out-dir",
@@ -15848,6 +16000,13 @@ function buildAgentContract() {
15848
16000
  positionals: [],
15849
16001
  exits: [0]
15850
16002
  },
16003
+ {
16004
+ name: "update",
16005
+ aliases: [],
16006
+ 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.",
16007
+ positionals: [],
16008
+ exits: [0, 1, 2]
16009
+ },
15851
16010
  {
15852
16011
  name: "skill",
15853
16012
  aliases: [],
@@ -16143,14 +16302,14 @@ function buildAgentContract() {
16143
16302
  type: "boolean",
16144
16303
  default: false,
16145
16304
  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."
16305
+ 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
16306
  },
16148
16307
  {
16149
16308
  flag: "--include-logs",
16150
16309
  type: "string",
16151
16310
  default: "unset",
16152
16311
  appliesTo: optionAppliesTo("include-logs"),
16153
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
16312
+ 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
16313
  },
16155
16314
  {
16156
16315
  flag: "--token-tree",
@@ -17144,6 +17303,18 @@ function createMcpServer(options) {
17144
17303
  if (!isJsonObject(rawArguments)) {
17145
17304
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
17146
17305
  }
17306
+ const missing = (prompt.arguments ?? []).filter((argument) => {
17307
+ if (argument.required !== true) return false;
17308
+ const value = rawArguments[argument.name];
17309
+ return typeof value !== "string" || value.trim() === "";
17310
+ });
17311
+ if (missing.length > 0) {
17312
+ return errorResponse(
17313
+ id,
17314
+ ERROR_CODES.invalidParams,
17315
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
17316
+ );
17317
+ }
17147
17318
  const built = prompt.build(rawArguments);
17148
17319
  const messages = built.messages.map((message) => ({
17149
17320
  role: message.role,
@@ -17611,20 +17782,20 @@ var SERVE_PAGE = `<!doctype html>
17611
17782
  <header><b>codebase-snapshot</b><span>a snapshot an agent can trust</span></header>
17612
17783
  <main>
17613
17784
  <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">
17785
+ <input id="source" aria-label="repository path or URL" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
17786
+ <select id="mode" aria-label="What to generate" title="What to generate">
17616
17787
  <option value="full">whole repository</option>
17617
17788
  <option value="slice">a slice for a question</option>
17618
17789
  <option value="budget">fit a token budget</option>
17619
17790
  </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>
17791
+ <input id="question" aria-label="Question for the slice" placeholder="the question (slice mode)" spellcheck="false" hidden>
17792
+ <input id="budget" type="number" min="500" step="500" value="30000" aria-label="Token budget" title="token budget" hidden>
17622
17793
  <button id="run" type="submit">Generate</button>
17623
17794
  <button id="download" type="button" disabled>Download .zip</button>
17624
17795
  </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>
17796
+ <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
17797
  <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>
17798
+ <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
17799
  </div>
17629
17800
  <div class="row">
17630
17801
  <section><h2>Brief <span id="fingerprint"></span> <span id="health"></span></h2><pre id="brief">No snapshot loaded.</pre></section>
@@ -17739,7 +17910,7 @@ async function startWebServer(options) {
17739
17910
  const host = options.host ?? "127.0.0.1";
17740
17911
  const port = options.port ?? DEFAULT_PORT;
17741
17912
  const log = options.log ?? ((line) => process.stderr.write(line + "\n"));
17742
- const token = options.token === void 0 ? crypto4.randomBytes(18).toString("base64url") : options.token;
17913
+ const token = options.token === void 0 ? crypto.randomBytes(18).toString("base64url") : options.token;
17743
17914
  if (token === null && !["127.0.0.1", "localhost", "::1"].includes(host)) {
17744
17915
  throw new Error("Refusing to serve " + host + " without a token.");
17745
17916
  }
@@ -17760,7 +17931,7 @@ async function startWebServer(options) {
17760
17931
  if (match === null) return false;
17761
17932
  const given = Buffer.from(match[1].trim(), "utf8");
17762
17933
  const expected = Buffer.from(token, "utf8");
17763
- return given.length === expected.length && crypto4.timingSafeEqual(given, expected);
17934
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
17764
17935
  };
17765
17936
  const server = http__namespace.createServer((request, response) => {
17766
17937
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
@@ -17919,9 +18090,14 @@ async function startWebServer(options) {
17919
18090
  send(400, { error: "not a directory: " + target });
17920
18091
  return;
17921
18092
  }
18093
+ const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
18094
+ if (loaded.errors.length > 0) {
18095
+ send(400, { error: loaded.errors.join("; ") });
18096
+ return;
18097
+ }
17922
18098
  const started = Date.now();
17923
18099
  try {
17924
- const manifest = generateSnapshot({ cwd: target }, {
18100
+ const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
17925
18101
  ...provenance === void 0 ? {} : { source: provenance },
17926
18102
  ...mode === "slice" ? { slice: { question } } : {},
17927
18103
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
@@ -18054,8 +18230,8 @@ async function startWebServer(options) {
18054
18230
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
18055
18231
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
18056
18232
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
18057
- var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
18058
- var REQUEST_TIMEOUT_MS = 1200;
18233
+ var FAILURE_INTERVAL_MS = 5 * 60 * 1e3;
18234
+ var REQUEST_TIMEOUT_MS = 2500;
18059
18235
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
18060
18236
  const normalise = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
18061
18237
  const script = normalise(scriptPath);
@@ -18119,7 +18295,7 @@ function shouldCheck(argv, env) {
18119
18295
  if (env.CI !== void 0 && env.CI !== "" && env.CI !== "false" && env.CI !== "0") return false;
18120
18296
  const args = argv.map((argument) => argument.toLowerCase());
18121
18297
  if (args.includes("--no-update-check")) return false;
18122
- for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
18298
+ for (const skip of ["mcp", "describe", "skill", "update", "--version", "-v", "--help", "-h"]) {
18123
18299
  if (args.includes(skip)) return false;
18124
18300
  }
18125
18301
  let format = null;
@@ -18215,13 +18391,19 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
18215
18391
  });
18216
18392
  }
18217
18393
  async function checkForUpdate(options) {
18394
+ const latest = await resolveLatest(options);
18395
+ if (!latest) return null;
18396
+ return isNewer(latest, options.current) ? { current: options.current, latest } : null;
18397
+ }
18398
+ async function resolveLatest(options) {
18218
18399
  if (options.enabled === false) return null;
18219
18400
  const now = options.now ?? (() => Date.now());
18220
18401
  const fetchLatest = options.fetchLatest ?? fetchLatestVersion;
18402
+ const latestUrl = options.latestUrl ?? PACKAGE_LATEST_URL;
18221
18403
  let latest = null;
18222
18404
  try {
18223
18405
  const cached = readCache(options.cacheFile);
18224
- let needsFetch = cached === null;
18406
+ let needsFetch = cached === null || options.force === true;
18225
18407
  if (cached) {
18226
18408
  const age = now() - cached.checkedAt;
18227
18409
  if (cached.latest === null) {
@@ -18233,15 +18415,14 @@ async function checkForUpdate(options) {
18233
18415
  }
18234
18416
  }
18235
18417
  if (needsFetch) {
18236
- const fetched = await fetchLatest(PACKAGE_LATEST_URL, REQUEST_TIMEOUT_MS);
18418
+ const fetched = await fetchLatest(latestUrl, REQUEST_TIMEOUT_MS);
18237
18419
  writeCache(options.cacheFile, { checkedAt: now(), latest: fetched });
18238
- latest = fetched;
18420
+ latest = fetched ?? latest;
18239
18421
  }
18240
18422
  } catch {
18241
18423
  return null;
18242
18424
  }
18243
- if (!latest) return null;
18244
- return isNewer(latest, options.current) ? { current: options.current, latest } : null;
18425
+ return latest;
18245
18426
  }
18246
18427
  function formatUpdateNotice(notice, kind) {
18247
18428
  return `\u2191 codebase-snapshot ${notice.latest} is available \u2014 you have ${notice.current}.
@@ -18551,7 +18732,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
18551
18732
  };
18552
18733
  }
18553
18734
  function sha256Hex2(input) {
18554
- return crypto4__namespace.createHash("sha256").update(input).digest("hex");
18735
+ return crypto__namespace.createHash("sha256").update(input).digest("hex");
18555
18736
  }
18556
18737
  var TS_EXTENSIONS = [
18557
18738
  ".ts",
@@ -19301,7 +19482,7 @@ function acquireRunLock(stagingRoot) {
19301
19482
  pid: process.pid,
19302
19483
  stagingRoot,
19303
19484
  host: os2__namespace.hostname(),
19304
- runId: crypto4__namespace.randomUUID(),
19485
+ runId: crypto__namespace.randomUUID(),
19305
19486
  heartbeatMs: LOCK_HEARTBEAT_MS,
19306
19487
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
19307
19488
  })}
@@ -19990,6 +20171,11 @@ function generateSnapshot(configInput, options) {
19990
20171
  detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
19991
20172
  files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
19992
20173
  };
20174
+ if (plan.files.length === 0) {
20175
+ warnings.push(
20176
+ "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.")
20177
+ );
20178
+ }
19993
20179
  }
19994
20180
  let budgetBlock;
19995
20181
  if (options?.budgetTokens !== void 0) {
@@ -20081,6 +20267,11 @@ function generateSnapshot(configInput, options) {
20081
20267
  warnings.push("No file fits --budget-tokens " + budget + "; the snapshot is empty.");
20082
20268
  }
20083
20269
  }
20270
+ if (config.include.length > 0 && files.length === 0) {
20271
+ warnings.push(
20272
+ "No file matched the include allow-list (" + config.include.length + " pattern(s): " + config.include.join(", ") + "), so the snapshot is empty."
20273
+ );
20274
+ }
20084
20275
  if (changedScope !== null || options?.deltaBase !== void 0) {
20085
20276
  const detail = changedScope !== null ? `not ${changedScope.detail}` : "identical to the base snapshot given with --delta";
20086
20277
  for (const relativePath of unchangedPaths) {
@@ -20219,6 +20410,12 @@ function generateSnapshot(configInput, options) {
20219
20410
  maxMonolithBytes: config.maxMonolithBytes ?? null,
20220
20411
  includeSensitiveFiles: config.includeSensitiveFiles,
20221
20412
  ...config.stripComments === true ? { stripComments: true } : {},
20413
+ // The other three settings the digest covers and the manifest did not record: without them a
20414
+ // validator (or `snapshot_review`) had no way to reconstruct the run, so a snapshot taken
20415
+ // with `--remove-empty-lines`, `--pack` or `--include-logs 3` looked stale forever.
20416
+ ...config.removeEmptyLines === true ? { removeEmptyLines: true } : {},
20417
+ ...config.pack === null ? {} : { pack: config.pack },
20418
+ logCount: config.logCount,
20222
20419
  // The destination the instructions were written for. Not part of `digest`: the payload is
20223
20420
  // identical whatever this says, and a new delivery preference must not make an existing
20224
20421
  // snapshot fail `validate` as configuration drift.
@@ -20362,6 +20559,18 @@ function generateSnapshot(configInput, options) {
20362
20559
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
20363
20560
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20364
20561
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
20562
+ if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20563
+ manifest.warnings.push(
20564
+ "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
20565
+ );
20566
+ manifest.totals.warningCount = manifest.warnings.length;
20567
+ }
20568
+ if (artifacts.log && logReport === null && !isGitRepository(config.cwd)) {
20569
+ manifest.warnings.push(
20570
+ "--include-logs was requested, but the generated directory is not a git repository; reports/log.md was not written."
20571
+ );
20572
+ manifest.totals.warningCount = manifest.warnings.length;
20573
+ }
20365
20574
  if (logReport !== null) manifest.artifacts.log = artifactRecord(logReport.text);
20366
20575
  const tokenTree = artifacts.tokenTree ? generateTokenTree(manifest) : null;
20367
20576
  if (tokenTree !== null) manifest.artifacts.tokenTree = artifactRecord(tokenTree.text);
@@ -20411,17 +20620,19 @@ function generateSnapshot(configInput, options) {
20411
20620
  if (wantsXml) manifest.warnings.push(`full-codebase.xml skipped: ${reason}`);
20412
20621
  }
20413
20622
  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
- );
20623
+ if (markdown !== null) {
20624
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
20625
+ if (config.maxMonolithBytes === null || markdownBytes <= config.maxMonolithBytes) {
20626
+ monolithMarkdown = markdown;
20627
+ manifest.artifacts.fullMarkdown = {
20628
+ byteSize: markdownBytes,
20629
+ sha256: sha256Hex2(markdown)
20630
+ };
20631
+ } else {
20632
+ manifest.warnings.push(
20633
+ `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20634
+ );
20635
+ }
20425
20636
  }
20426
20637
  if (wantsXml && !definitelyTooLarge) {
20427
20638
  const xml = generateMonolithXml(manifest, fullFiles);
@@ -20437,14 +20648,16 @@ function generateSnapshot(configInput, options) {
20437
20648
  }
20438
20649
  manifest.totals.warningCount = manifest.warnings.length;
20439
20650
  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
- );
20651
+ if (json !== null) {
20652
+ const jsonBytes = Buffer.byteLength(json, "utf8");
20653
+ if (config.maxMonolithBytes === null || jsonBytes <= config.maxMonolithBytes) {
20654
+ monolithJson = json;
20655
+ manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20656
+ } else {
20657
+ manifest.warnings.push(
20658
+ `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20659
+ );
20660
+ }
20448
20661
  }
20449
20662
  manifest.totals.warningCount = manifest.warnings.length;
20450
20663
  }
@@ -20473,7 +20686,7 @@ function generateSnapshot(configInput, options) {
20473
20686
  ensureParentDirectory(outDir, "outDir");
20474
20687
  fs24__namespace.mkdirSync(tmpDir, { recursive: true });
20475
20688
  cleanStaleRunDirs(tmpDir);
20476
- const snapshotId = crypto4__namespace.randomUUID();
20689
+ const snapshotId = crypto__namespace.randomUUID();
20477
20690
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
20478
20691
  stagingDir = path27__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
20479
20692
  fs24__namespace.mkdirSync(stagingDir);
@@ -20719,7 +20932,7 @@ var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
20719
20932
  var RATE_LIMIT = 60;
20720
20933
  var RATE_WINDOW_MS = 1e4;
20721
20934
  function generateToken() {
20722
- return crypto4__namespace.randomBytes(24).toString("base64url");
20935
+ return crypto__namespace.randomBytes(24).toString("base64url");
20723
20936
  }
20724
20937
  function isLoopbackOrigin(origin) {
20725
20938
  try {
@@ -20735,7 +20948,7 @@ function timingSafeEqual3(left, right) {
20735
20948
  const a = Buffer.from(left, "utf8");
20736
20949
  const b = Buffer.from(right, "utf8");
20737
20950
  if (a.length !== b.length) return false;
20738
- return crypto4__namespace.timingSafeEqual(a, b);
20951
+ return crypto__namespace.timingSafeEqual(a, b);
20739
20952
  }
20740
20953
  async function startHttpTransport(options) {
20741
20954
  const host = options.host ?? "127.0.0.1";
@@ -20780,6 +20993,7 @@ async function startHttpTransport(options) {
20780
20993
  noteRequest(request);
20781
20994
  const send = (status, body, extra = {}) => {
20782
20995
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
20996
+ if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
20783
20997
  response.writeHead(status, {
20784
20998
  "content-type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json",
20785
20999
  "content-length": Buffer.byteLength(text2, "utf8"),
@@ -20791,7 +21005,6 @@ async function startHttpTransport(options) {
20791
21005
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
20792
21006
  const allowed = allowedOrigin(origin);
20793
21007
  if (origin !== void 0 && allowed === null) {
20794
- metrics.refused += 1;
20795
21008
  send(403, { error: "origin not allowed" });
20796
21009
  return;
20797
21010
  }
@@ -20829,7 +21042,7 @@ async function startHttpTransport(options) {
20829
21042
  "# HELP snapshot_requests_total HTTP requests received.",
20830
21043
  "# TYPE snapshot_requests_total counter",
20831
21044
  "snapshot_requests_total " + metrics.requests,
20832
- "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
21045
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch (4xx other than 429).",
20833
21046
  "# TYPE snapshot_requests_refused_total counter",
20834
21047
  "snapshot_requests_refused_total " + metrics.refused,
20835
21048
  "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
@@ -20854,7 +21067,7 @@ async function startHttpTransport(options) {
20854
21067
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
20855
21068
  return;
20856
21069
  }
20857
- const id = crypto4__namespace.randomBytes(12).toString("hex");
21070
+ const id = crypto__namespace.randomBytes(12).toString("hex");
20858
21071
  response.writeHead(200, {
20859
21072
  ...cors,
20860
21073
  "content-type": "text/event-stream",
@@ -21031,6 +21244,7 @@ var COMMAND_ALIASES = /* @__PURE__ */ new Map([
21031
21244
  ["describe", "describe"],
21032
21245
  ["skill", "skill"],
21033
21246
  ["mcp", "mcp"],
21247
+ ["update", "update"],
21034
21248
  ["serve", "serve"]
21035
21249
  ]);
21036
21250
  var COMMAND_ARITY = {
@@ -21045,6 +21259,7 @@ var COMMAND_ARITY = {
21045
21259
  describe: 0,
21046
21260
  skill: 0,
21047
21261
  mcp: 0,
21262
+ update: 0,
21048
21263
  serve: 0
21049
21264
  };
21050
21265
  var CLI_OPTIONS = {
@@ -21140,6 +21355,7 @@ Commands:
21140
21355
  explain <path> Show how one path would be treated: layer, kind, part, skips
21141
21356
  diff <a> <b> Compare two snapshots (directories or manifest.json files)
21142
21357
  describe Print the machine-readable contract (--format json for agents)
21358
+ update Ask the registry whether a newer release exists (exit 1 if one does)
21143
21359
  skill Print the bundled agent skill; --install writes it into the repo
21144
21360
  mcp Serve this repository to an MCP client (stdio, or --http for the web)
21145
21361
  serve Open a browser UI: generate, preview, download a zip; MCP at /mcp
@@ -21982,6 +22198,37 @@ async function firstRun(invocation) {
21982
22198
  );
21983
22199
  return await runSetupCommand(invocation, { interactive: plan.interactive });
21984
22200
  }
22201
+ async function runUpdateCommand(invocation) {
22202
+ const current = GENERATOR_VERSION;
22203
+ const latestUrl = process.env.CODEBASE_SNAPSHOT_REGISTRY_URL;
22204
+ const latest = await resolveLatest({
22205
+ current,
22206
+ cacheFile: cacheFilePath(),
22207
+ force: true,
22208
+ ...latestUrl === void 0 || latestUrl === "" ? {} : { latestUrl }
22209
+ });
22210
+ if (latest === null) {
22211
+ emit(invocation.format, { current, latest: null, updateAvailable: false }, () => {
22212
+ info(
22213
+ "Could not reach the npm registry, so the installed version could not be compared. Nothing was changed; try again when the network is available."
22214
+ );
22215
+ });
22216
+ return 2;
22217
+ }
22218
+ const kind = installKind();
22219
+ const updateAvailable = isNewer(latest, current);
22220
+ const command = updateCommand(kind);
22221
+ emit(invocation.format, { current, latest, updateAvailable, command }, () => {
22222
+ if (updateAvailable) {
22223
+ info(formatUpdateNotice({ current, latest }, kind));
22224
+ } else {
22225
+ info(
22226
+ `You are on codebase-snapshot ${current}, and the registry publishes ${latest}. No update is available.`
22227
+ );
22228
+ }
22229
+ });
22230
+ return updateAvailable ? 1 : 0;
22231
+ }
21985
22232
  function runSkillCommand(invocation) {
21986
22233
  if (!invocation.install) {
21987
22234
  if (invocation.format === "json") {
@@ -22123,6 +22370,9 @@ ${USAGE}
22123
22370
  if (invocation.command === "skill") {
22124
22371
  return runSkillCommand(invocation);
22125
22372
  }
22373
+ if (invocation.command === "update") {
22374
+ return runUpdateCommand(invocation);
22375
+ }
22126
22376
  if (invocation.command === "serve") {
22127
22377
  const server = await startWebServer({
22128
22378
  cwd: path27__namespace.resolve(invocation.cwd),
@@ -22540,8 +22790,9 @@ ${USAGE}
22540
22790
  }
22541
22791
  const started = performance.now();
22542
22792
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
22793
+ const headerGit = getGitInfo(resolved.cwd, resolved.branch);
22543
22794
  info(
22544
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
22795
+ ` Branch: ${resolved.branch}${headerGit.branchFromGit ? "" : " (fallback)"} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
22545
22796
  );
22546
22797
  try {
22547
22798
  let deltaBase;