codebase-snapshot 0.17.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/bin.js CHANGED
@@ -7,8 +7,8 @@ import * as path27 from "path";
7
7
  import { parseArgs } from "util";
8
8
 
9
9
  // src/diff.ts
10
- import * as fs8 from "fs";
11
- import * as path7 from "path";
10
+ import * as fs9 from "fs";
11
+ import * as path8 from "path";
12
12
 
13
13
  // src/scanner/files.ts
14
14
  import * as childProcess from "child_process";
@@ -2191,7 +2191,7 @@ function applySpansKeepingQuotes(line, spans) {
2191
2191
 
2192
2192
  // src/version.ts
2193
2193
  var GENERATOR_NAME = "codebase-snapshot";
2194
- var GENERATOR_VERSION = "0.17.0";
2194
+ var GENERATOR_VERSION = "0.18.0";
2195
2195
  var SCHEMA_VERSION = "3.0.0";
2196
2196
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2197
2197
  function isOurGeneratorName(name) {
@@ -2242,6 +2242,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2242
2242
  let branch = fallbackBranch;
2243
2243
  let commit = "unknown";
2244
2244
  let isDirty = false;
2245
+ let branchFromGit = false;
2245
2246
  const records = output.split("\0").flatMap((record) => record.split("\n"));
2246
2247
  for (const record of records) {
2247
2248
  if (record.length === 0) continue;
@@ -2257,13 +2258,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2257
2258
  const head = record.match(/^# branch\.head (.+)$/);
2258
2259
  if (head) {
2259
2260
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
2261
+ branchFromGit = head[1] !== "(detached)";
2260
2262
  }
2261
2263
  }
2262
- return { branch, commit, isDirty };
2264
+ return { branch, commit, isDirty, branchFromGit };
2263
2265
  } catch (err) {
2264
2266
  const code = err.code;
2265
2267
  const isDirty = code === "ENOBUFS";
2266
- return { branch: fallbackBranch, commit: "unknown", isDirty };
2268
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
2267
2269
  }
2268
2270
  }
2269
2271
  var DEFAULT_IGNORED_DIRS = [
@@ -3114,9 +3116,9 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3114
3116
  }
3115
3117
 
3116
3118
  // src/validator/validate.ts
3117
- import * as crypto from "crypto";
3118
- import * as fs7 from "fs";
3119
- import * as path6 from "path";
3119
+ import * as crypto2 from "crypto";
3120
+ import * as fs8 from "fs";
3121
+ import * as path7 from "path";
3120
3122
 
3121
3123
  // src/config.ts
3122
3124
  import * as fs3 from "fs";
@@ -4984,7 +4986,7 @@ function summarizeTypeScriptSource(relativePath, content) {
4984
4986
  }
4985
4987
  const callee = node.expression;
4986
4988
  if (ts2.isPropertyAccessExpression(callee) && ts2.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts2.isStringLiteral(firstArgument)) {
4987
- summary.routeHandlers.push(callee.name.text.toUpperCase());
4989
+ summary.routeHandlers.push(callee.name.text.toUpperCase() + " " + firstArgument.text);
4988
4990
  }
4989
4991
  }
4990
4992
  if (ts2.isExportDeclaration(node)) {
@@ -6229,39 +6231,107 @@ function importsOfFile(relativePath, absolutePath) {
6229
6231
  return importsOfText(relativePath, decoded.text);
6230
6232
  }
6231
6233
 
6234
+ // src/signing.ts
6235
+ import * as crypto from "crypto";
6236
+ import * as fs7 from "fs";
6237
+ import * as path6 from "path";
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.createPrivateKey({ key: pem, format: "pem" });
6243
+ }
6244
+ function signManifest(manifestPath, options = {}) {
6245
+ const bytes = fs7.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.generateKeyPairSync("ed25519").privateKey;
6252
+ const publicKey = crypto.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
6253
+ const signature = crypto.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.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 = path6.join(snapshotDir, SIGNATURE_FILE);
6266
+ fs7.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
6267
+ return target;
6268
+ }
6269
+ function verifySnapshotSignature(snapshotDir) {
6270
+ const signaturePath = path6.join(snapshotDir, SIGNATURE_FILE);
6271
+ const manifestPath = path6.join(snapshotDir, "manifest.json");
6272
+ if (!fs7.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
6273
+ let record;
6274
+ try {
6275
+ record = JSON.parse(fs7.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 = fs7.readFileSync(manifestPath);
6285
+ } catch {
6286
+ return { ok: false, reason: "the signed manifest is missing" };
6287
+ }
6288
+ const sha2562 = crypto.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.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
6295
+ verified = crypto.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
+ }
6301
+
6232
6302
  // src/validator/validate.ts
6233
6303
  function maskedPath(value, secretRules) {
6234
6304
  return findSecretInPath(value, secretRules)?.masked ?? value;
6235
6305
  }
6236
6306
  function confineToDirectory(directory, filename) {
6237
6307
  if (filename.includes("\0")) return null;
6238
- if (path6.isAbsolute(filename)) return null;
6239
- const base = path6.resolve(directory);
6240
- const resolved = path6.resolve(base, filename);
6308
+ if (path7.isAbsolute(filename)) return null;
6309
+ const base = path7.resolve(directory);
6310
+ const resolved = path7.resolve(base, filename);
6241
6311
  const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
6242
- const prefix = caseInsensitive ? `${base}${path6.sep}`.toLowerCase() : `${base}${path6.sep}`;
6312
+ const prefix = caseInsensitive ? `${base}${path7.sep}`.toLowerCase() : `${base}${path7.sep}`;
6243
6313
  const candidate = caseInsensitive ? resolved.toLowerCase() : resolved;
6244
6314
  return candidate.startsWith(prefix) ? resolved : null;
6245
6315
  }
6246
6316
  function findStagingDirectory(config) {
6247
- const tmpDir = path6.resolve(config.cwd, config.tmpDir);
6317
+ const tmpDir = path7.resolve(config.cwd, config.tmpDir);
6248
6318
  let entries;
6249
6319
  try {
6250
- entries = fs7.readdirSync(tmpDir);
6320
+ entries = fs8.readdirSync(tmpDir);
6251
6321
  } catch {
6252
6322
  return null;
6253
6323
  }
6254
6324
  const runs = entries.filter((name) => name.startsWith("run-")).sort();
6255
6325
  const newest = runs[runs.length - 1];
6256
- return newest ? path6.join(tmpDir, newest) : null;
6326
+ return newest ? path7.join(tmpDir, newest) : null;
6257
6327
  }
6258
6328
  function describeMissingManifest(config, manifestPath) {
6259
- const outDir = path6.resolve(config.cwd, config.outDir);
6260
- const markerPath = path6.join(outDir, ".codebase-snapshot");
6329
+ const outDir = path7.resolve(config.cwd, config.outDir);
6330
+ const markerPath = path7.join(outDir, ".codebase-snapshot");
6261
6331
  let marker2 = null;
6262
6332
  try {
6263
- if (fs7.existsSync(markerPath)) {
6264
- const parsed = JSON.parse(fs7.readFileSync(markerPath, "utf8"));
6333
+ if (fs8.existsSync(markerPath)) {
6334
+ const parsed = JSON.parse(fs8.readFileSync(markerPath, "utf8"));
6265
6335
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
6266
6336
  marker2 = parsed;
6267
6337
  }
@@ -6293,16 +6363,16 @@ function emptyDrift() {
6293
6363
  };
6294
6364
  }
6295
6365
  function sha256Hex(buffer) {
6296
- return crypto.createHash("sha256").update(buffer).digest("hex");
6366
+ return crypto2.createHash("sha256").update(buffer).digest("hex");
6297
6367
  }
6298
6368
  function wouldNowBeIncluded(cwd, relativePath) {
6299
- const absolutePath = path6.join(cwd, relativePath);
6369
+ const absolutePath = path7.join(cwd, relativePath);
6300
6370
  try {
6301
- const stats = fs7.statSync(absolutePath);
6371
+ const stats = fs8.statSync(absolutePath);
6302
6372
  if (!stats.isFile()) return false;
6303
6373
  if (isBinaryExtension(absolutePath)) return false;
6304
6374
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
6305
- return !decodeText(fs7.readFileSync(absolutePath)).binary;
6375
+ return !decodeText(fs8.readFileSync(absolutePath)).binary;
6306
6376
  } catch {
6307
6377
  return false;
6308
6378
  }
@@ -6314,7 +6384,7 @@ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
6314
6384
  ]);
6315
6385
  function isConfinedRelative(value) {
6316
6386
  if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
6317
- if (path6.isAbsolute(value)) return false;
6387
+ if (path7.isAbsolute(value)) return false;
6318
6388
  return !value.split("/").includes("..");
6319
6389
  }
6320
6390
  function describeManifestShapeProblem(value) {
@@ -6508,7 +6578,7 @@ function describeManifestShapeProblem(value) {
6508
6578
  if (typeof filename !== "string" || filename.trim() === "") {
6509
6579
  return 'a "parts" entry has no "filename"';
6510
6580
  }
6511
- if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path6.isAbsolute(filename)) {
6581
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path7.isAbsolute(filename)) {
6512
6582
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
6513
6583
  }
6514
6584
  if (currentSchema) {
@@ -6534,8 +6604,8 @@ function describeManifestShapeProblem(value) {
6534
6604
  function validateSnapshot(configInput) {
6535
6605
  assertUsableConfigInput(configInput);
6536
6606
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
6537
- const manifestPath = path6.resolve(config.cwd, config.outDir, "manifest.json");
6538
- if (!fs7.existsSync(manifestPath)) {
6607
+ const manifestPath = path7.resolve(config.cwd, config.outDir, "manifest.json");
6608
+ if (!fs8.existsSync(manifestPath)) {
6539
6609
  return {
6540
6610
  valid: false,
6541
6611
  manifestPresent: false,
@@ -6546,7 +6616,7 @@ function validateSnapshot(configInput) {
6546
6616
  }
6547
6617
  let manifest;
6548
6618
  try {
6549
- manifest = JSON.parse(fs7.readFileSync(manifestPath, "utf8"));
6619
+ manifest = JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
6550
6620
  } catch (err) {
6551
6621
  return {
6552
6622
  valid: false,
@@ -6568,7 +6638,7 @@ function validateSnapshot(configInput) {
6568
6638
  }
6569
6639
  const drift = emptyDrift();
6570
6640
  const warnings = [];
6571
- const snapshotDir = path6.resolve(config.cwd, config.outDir);
6641
+ const snapshotDir = path7.resolve(config.cwd, config.outDir);
6572
6642
  const unreadableSkips = manifest.skipped.filter(
6573
6643
  (entry) => entry.reason === "missing" || entry.reason === "read-error"
6574
6644
  );
@@ -6671,7 +6741,7 @@ function validateSnapshot(configInput) {
6671
6741
  );
6672
6742
  return importsChangedFile(
6673
6743
  diskFile,
6674
- importsOfFile(diskFile, path6.join(config.cwd, diskFile)),
6744
+ importsOfFile(diskFile, path7.join(config.cwd, diskFile)),
6675
6745
  unchangedScope,
6676
6746
  dependentResolver
6677
6747
  );
@@ -6689,7 +6759,7 @@ function validateSnapshot(configInput) {
6689
6759
  // own output directory as a set of files missing from the snapshot, so a correct
6690
6760
  // snapshot was reported as drifting.
6691
6761
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6692
- (directory) => path6.relative(config.cwd, path6.resolve(config.cwd, directory)).replace(/\\/g, "/")
6762
+ (directory) => path7.relative(config.cwd, path7.resolve(config.cwd, directory)).replace(/\\/g, "/")
6693
6763
  ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
6694
6764
  });
6695
6765
  for (const diskFile of collection.files) {
@@ -6716,7 +6786,7 @@ function validateSnapshot(configInput) {
6716
6786
  }
6717
6787
  let diskHash;
6718
6788
  try {
6719
- diskHash = sha256Hex(fs7.readFileSync(path6.join(config.cwd, diskFile)));
6789
+ diskHash = sha256Hex(fs8.readFileSync(path7.join(config.cwd, diskFile)));
6720
6790
  } catch (err) {
6721
6791
  if (err.code === "ENOENT") {
6722
6792
  drift.missingOnDisk.push(diskFile);
@@ -6740,7 +6810,7 @@ function validateSnapshot(configInput) {
6740
6810
  }
6741
6811
  let statFailure = null;
6742
6812
  try {
6743
- fs7.statSync(confined);
6813
+ fs8.statSync(confined);
6744
6814
  } catch (err) {
6745
6815
  statFailure = err;
6746
6816
  }
@@ -6760,7 +6830,7 @@ function validateSnapshot(configInput) {
6760
6830
  ...Object.values(config.budgets.byLayer)
6761
6831
  );
6762
6832
  const partNames = /* @__PURE__ */ new Set();
6763
- const partsDir = path6.join(snapshotDir, "parts");
6833
+ const partsDir = path7.join(snapshotDir, "parts");
6764
6834
  for (const part of manifest.parts) {
6765
6835
  if (!part || typeof part.filename !== "string") continue;
6766
6836
  partNames.add(part.filename);
@@ -6775,7 +6845,7 @@ function validateSnapshot(configInput) {
6775
6845
  }
6776
6846
  let buffer;
6777
6847
  try {
6778
- buffer = fs7.readFileSync(partPath);
6848
+ buffer = fs8.readFileSync(partPath);
6779
6849
  } catch {
6780
6850
  drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
6781
6851
  continue;
@@ -7152,11 +7222,11 @@ function validateSnapshot(configInput) {
7152
7222
  ];
7153
7223
  for (const [key, artifact] of declaredArtifacts) {
7154
7224
  if (!artifact) continue;
7155
- const artifactPath = path6.join(snapshotDir, ...key.split("/"));
7225
+ const artifactPath = path7.join(snapshotDir, ...key.split("/"));
7156
7226
  let buffer;
7157
7227
  try {
7158
- if (!fs7.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7159
- buffer = fs7.readFileSync(artifactPath);
7228
+ if (!fs8.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7229
+ buffer = fs8.readFileSync(artifactPath);
7160
7230
  } catch {
7161
7231
  drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
7162
7232
  continue;
@@ -7169,9 +7239,9 @@ function validateSnapshot(configInput) {
7169
7239
  for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
7170
7240
  const target = match[1].split("#")[0];
7171
7241
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7172
- const resolved = path6.resolve(snapshotDir, "reports", target);
7173
- const relative15 = path6.relative(snapshotDir, resolved);
7174
- if (relative15.startsWith("..") || path6.isAbsolute(relative15) || !fs7.existsSync(resolved)) {
7242
+ const resolved = path7.resolve(snapshotDir, "reports", target);
7243
+ const relative15 = path7.relative(snapshotDir, resolved);
7244
+ if (relative15.startsWith("..") || path7.isAbsolute(relative15) || !fs8.existsSync(resolved)) {
7175
7245
  drift.partIssues.push({
7176
7246
  part: key,
7177
7247
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7184,7 +7254,7 @@ function validateSnapshot(configInput) {
7184
7254
  if (sarifArtifact) {
7185
7255
  const sarifKey = "reports/audit.sarif";
7186
7256
  try {
7187
- const buffer = fs7.readFileSync(path6.join(snapshotDir, "reports", "audit.sarif"));
7257
+ const buffer = fs8.readFileSync(path7.join(snapshotDir, "reports", "audit.sarif"));
7188
7258
  if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
7189
7259
  drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7190
7260
  }
@@ -7230,6 +7300,11 @@ function validateSnapshot(configInput) {
7230
7300
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
7231
7301
  );
7232
7302
  }
7303
+ const signaturePath = path7.join(path7.dirname(manifestPath), "signature.json");
7304
+ if (fs8.existsSync(signaturePath)) {
7305
+ const outcome = verifySnapshotSignature(path7.dirname(manifestPath));
7306
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
7307
+ }
7233
7308
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
7234
7309
  warnings.push(
7235
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."
@@ -7473,14 +7548,14 @@ function compareManifests(before, after, secretRules) {
7473
7548
  function loadManifest(target) {
7474
7549
  let isDirectory;
7475
7550
  try {
7476
- isDirectory = fs8.statSync(target).isDirectory();
7551
+ isDirectory = fs9.statSync(target).isDirectory();
7477
7552
  } catch {
7478
7553
  throw new Error(`No snapshot found at ${target}: the path does not exist.`);
7479
7554
  }
7480
- const manifestPath = isDirectory ? path7.join(target, "manifest.json") : target;
7555
+ const manifestPath = isDirectory ? path8.join(target, "manifest.json") : target;
7481
7556
  let raw;
7482
7557
  try {
7483
- raw = fs8.readFileSync(manifestPath, "utf8");
7558
+ raw = fs9.readFileSync(manifestPath, "utf8");
7484
7559
  } catch {
7485
7560
  throw new Error(`Could not read a manifest at ${manifestPath}.`);
7486
7561
  }
@@ -7536,8 +7611,8 @@ function renderDiffText(diff) {
7536
7611
  }
7537
7612
 
7538
7613
  // src/explain.ts
7539
- import * as fs9 from "fs";
7540
- import * as path9 from "path";
7614
+ import * as fs10 from "fs";
7615
+ import * as path10 from "path";
7541
7616
 
7542
7617
  // src/ast/skeleton.ts
7543
7618
  import ts3 from "typescript";
@@ -7717,7 +7792,7 @@ function truncatePreview(content, headLines, tailLines) {
7717
7792
  }
7718
7793
 
7719
7794
  // src/scanner/language.ts
7720
- import * as path8 from "path";
7795
+ import * as path9 from "path";
7721
7796
  var LANGUAGE_BY_EXTENSION = {
7722
7797
  ".ts": "typescript",
7723
7798
  ".mts": "typescript",
@@ -7775,10 +7850,10 @@ var LANGUAGE_BY_BASENAME = {
7775
7850
  };
7776
7851
  function detectLanguage(filePath) {
7777
7852
  const normalized = filePath.replace(/\\/g, "/");
7778
- const base = path8.posix.basename(normalized);
7853
+ const base = path9.posix.basename(normalized);
7779
7854
  if (LANGUAGE_BY_BASENAME[base]) return LANGUAGE_BY_BASENAME[base];
7780
7855
  if (base === ".env" || base.startsWith(".env.")) return "dotenv";
7781
- const ext = path8.posix.extname(base).toLowerCase();
7856
+ const ext = path9.posix.extname(base).toLowerCase();
7782
7857
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
7783
7858
  }
7784
7859
 
@@ -7820,13 +7895,13 @@ function describeMatcher(matcher) {
7820
7895
  return String(matcher);
7821
7896
  }
7822
7897
  function normalizeTarget(cwd, target) {
7823
- const resolvedCwd = path9.resolve(cwd);
7824
- const absolute = path9.resolve(resolvedCwd, target);
7825
- const relative15 = path9.relative(resolvedCwd, absolute);
7826
- if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path9.sep}`) || path9.isAbsolute(relative15)) {
7898
+ const resolvedCwd = path10.resolve(cwd);
7899
+ const absolute = path10.resolve(resolvedCwd, target);
7900
+ const relative15 = path10.relative(resolvedCwd, absolute);
7901
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative15)) {
7827
7902
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7828
7903
  }
7829
- return { relative: relative15.split(path9.sep).join("/"), outsideRoot: false };
7904
+ return { relative: relative15.split(path10.sep).join("/"), outsideRoot: false };
7830
7905
  }
7831
7906
  function findRuleMatch(rules, relativePath) {
7832
7907
  return rules.find(
@@ -7845,9 +7920,9 @@ function findRecordedAncestor(skipped, relative15, maskedPath2) {
7845
7920
  return nearest;
7846
7921
  }
7847
7922
  function readManifest2(config) {
7848
- const manifestPath = path9.resolve(config.cwd, config.outDir, "manifest.json");
7923
+ const manifestPath = path10.resolve(config.cwd, config.outDir, "manifest.json");
7849
7924
  try {
7850
- return JSON.parse(fs9.readFileSync(manifestPath, "utf8"));
7925
+ return JSON.parse(fs10.readFileSync(manifestPath, "utf8"));
7851
7926
  } catch {
7852
7927
  return null;
7853
7928
  }
@@ -7865,10 +7940,10 @@ function explainPath(config, target) {
7865
7940
  detail: "path resolves outside the configured repository root and was not inspected"
7866
7941
  };
7867
7942
  }
7868
- const absolute = path9.join(config.cwd, relative15);
7943
+ const absolute = path10.join(config.cwd, relative15);
7869
7944
  const result = {
7870
7945
  path: maskedPath2,
7871
- exists: fs9.existsSync(absolute),
7946
+ exists: fs10.existsSync(absolute),
7872
7947
  included: false
7873
7948
  };
7874
7949
  const collection = collectFiles(config.cwd, {
@@ -7882,7 +7957,7 @@ function explainPath(config, target) {
7882
7957
  // Same exclusion `generate` applies, so `explain` never says "not-discovered" about a file
7883
7958
  // that is only missing because the walker dropped the tool's own output directory.
7884
7959
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7885
- (directory) => path9.relative(config.cwd, path9.resolve(config.cwd, directory)).replace(/\\/g, "/")
7960
+ (directory) => path10.relative(config.cwd, path10.resolve(config.cwd, directory)).replace(/\\/g, "/")
7886
7961
  ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
7887
7962
  });
7888
7963
  if (!collection.files.includes(relative15)) {
@@ -7947,7 +8022,7 @@ function explainPath(config, target) {
7947
8022
  }
7948
8023
  let sizeOnDisk = null;
7949
8024
  try {
7950
- sizeOnDisk = fs9.statSync(absolute).size;
8025
+ sizeOnDisk = fs10.statSync(absolute).size;
7951
8026
  } catch {
7952
8027
  sizeOnDisk = null;
7953
8028
  }
@@ -7957,10 +8032,10 @@ function explainPath(config, target) {
7957
8032
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
7958
8033
  return result;
7959
8034
  }
7960
- if (fs9.existsSync(absolute) && fs9.statSync(absolute).isFile()) {
8035
+ if (fs10.existsSync(absolute) && fs10.statSync(absolute).isFile()) {
7961
8036
  let buffer;
7962
8037
  try {
7963
- buffer = fs9.readFileSync(absolute);
8038
+ buffer = fs10.readFileSync(absolute);
7964
8039
  } catch (err) {
7965
8040
  result.included = false;
7966
8041
  result.reason = "read-error";
@@ -8051,12 +8126,12 @@ function renderExplainText(result) {
8051
8126
  }
8052
8127
 
8053
8128
  // src/wizard/init.ts
8054
- import * as fs11 from "fs";
8055
- import * as path11 from "path";
8129
+ import * as fs12 from "fs";
8130
+ import * as path12 from "path";
8056
8131
 
8057
8132
  // src/gitignore.ts
8058
- import * as fs10 from "fs";
8059
- import * as path10 from "path";
8133
+ import * as fs11 from "fs";
8134
+ import * as path11 from "path";
8060
8135
  function decodeGitignore(buffer) {
8061
8136
  const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
8062
8137
  if (startsWith(239, 187, 191)) {
@@ -8105,15 +8180,15 @@ function canonicalIgnorePattern(line) {
8105
8180
  function appendGitignoreEntries(cwd, entries) {
8106
8181
  const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
8107
8182
  if (wanted.length === 0) return { added: [], note: null };
8108
- const ignorePath = path10.join(cwd, ".gitignore");
8183
+ const ignorePath = path11.join(cwd, ".gitignore");
8109
8184
  const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
8110
8185
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
8111
8186
  try {
8112
- if (fs10.existsSync(ignorePath)) {
8113
- if (fs10.statSync(ignorePath).isDirectory()) {
8187
+ if (fs11.existsSync(ignorePath)) {
8188
+ if (fs11.statSync(ignorePath).isDirectory()) {
8114
8189
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
8115
8190
  }
8116
- const read = decodeGitignore(fs10.readFileSync(ignorePath));
8191
+ const read = decodeGitignore(fs11.readFileSync(ignorePath));
8117
8192
  if (read === null) {
8118
8193
  return {
8119
8194
  added: [],
@@ -8135,7 +8210,7 @@ function appendGitignoreEntries(cwd, entries) {
8135
8210
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
8136
8211
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
8137
8212
  try {
8138
- fs10.writeFileSync(
8213
+ fs11.writeFileSync(
8139
8214
  ignorePath,
8140
8215
  encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
8141
8216
  );
@@ -8145,7 +8220,7 @@ function appendGitignoreEntries(cwd, entries) {
8145
8220
  return { added, note: null };
8146
8221
  }
8147
8222
  function gitignorePath(cwd, filePath) {
8148
- return path10.relative(cwd, filePath).split(path10.sep).join("/");
8223
+ return path11.relative(cwd, filePath).split(path11.sep).join("/");
8149
8224
  }
8150
8225
 
8151
8226
  // src/wizard/brief-template.ts
@@ -8756,7 +8831,7 @@ function parsePackageJson(raw) {
8756
8831
  }
8757
8832
  function readPackageJson(cwd) {
8758
8833
  try {
8759
- return parsePackageJson(fs11.readFileSync(path11.join(cwd, "package.json"), "utf8"));
8834
+ return parsePackageJson(fs12.readFileSync(path12.join(cwd, "package.json"), "utf8"));
8760
8835
  } catch {
8761
8836
  return null;
8762
8837
  }
@@ -8793,7 +8868,7 @@ function artifactAnswers(options) {
8793
8868
  }
8794
8869
  function topLevelDirs(cwd) {
8795
8870
  try {
8796
- return fs11.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
8871
+ return fs12.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
8797
8872
  } catch {
8798
8873
  return [];
8799
8874
  }
@@ -8808,7 +8883,7 @@ function writeFileOrExplain(target, content) {
8808
8883
  try {
8809
8884
  let stats = null;
8810
8885
  try {
8811
- stats = fs11.lstatSync(target);
8886
+ stats = fs12.lstatSync(target);
8812
8887
  } catch {
8813
8888
  stats = null;
8814
8889
  }
@@ -8823,12 +8898,12 @@ function writeFileOrExplain(target, content) {
8823
8898
  );
8824
8899
  }
8825
8900
  const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
8826
- fs11.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
8901
+ fs12.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
8827
8902
  try {
8828
- fs11.renameSync(temporary, target);
8903
+ fs12.renameSync(temporary, target);
8829
8904
  } catch (err) {
8830
8905
  try {
8831
- fs11.unlinkSync(temporary);
8906
+ fs12.unlinkSync(temporary);
8832
8907
  } catch {
8833
8908
  }
8834
8909
  throw err;
@@ -8876,19 +8951,19 @@ function serializePackageJson(raw, value) {
8876
8951
  return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
8877
8952
  }
8878
8953
  function updatePackageJson(cwd, notes) {
8879
- const packagePath = path11.join(cwd, "package.json");
8954
+ const packagePath = path12.join(cwd, "package.json");
8880
8955
  const unchanged = {
8881
8956
  scripts: [],
8882
8957
  dependency: { name: GENERATOR_NAME, range: null, added: false }
8883
8958
  };
8884
- if (!fs11.existsSync(packagePath)) {
8959
+ if (!fs12.existsSync(packagePath)) {
8885
8960
  notes.push("No package.json found, so npm scripts and the devDependency were not added.");
8886
8961
  return unchanged;
8887
8962
  }
8888
8963
  let raw;
8889
8964
  let parsed;
8890
8965
  try {
8891
- raw = fs11.readFileSync(packagePath, "utf8");
8966
+ raw = fs12.readFileSync(packagePath, "utf8");
8892
8967
  parsed = parsePackageJson(raw);
8893
8968
  } catch {
8894
8969
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
@@ -8963,8 +9038,8 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
8963
9038
  const entries = [];
8964
9039
  for (const directory of [outDir, tmpDir]) {
8965
9040
  if (directory === null) continue;
8966
- const relative15 = path11.relative(cwd, path11.resolve(cwd, directory)).replace(/\\/g, "/");
8967
- if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path11.isAbsolute(relative15)) {
9041
+ const relative15 = path12.relative(cwd, path12.resolve(cwd, directory)).replace(/\\/g, "/");
9042
+ if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path12.isAbsolute(relative15)) {
8968
9043
  continue;
8969
9044
  }
8970
9045
  entries.push(`/${relative15}/`);
@@ -9219,7 +9294,7 @@ async function runInit(options) {
9219
9294
  const configText = renderConfig(answers);
9220
9295
  const preferredName = chooseConfigFileName(options.cwd);
9221
9296
  const presentConfigs = CONFIG_CANDIDATES.filter(
9222
- (name) => fs11.existsSync(path11.join(options.cwd, name))
9297
+ (name) => fs12.existsSync(path12.join(options.cwd, name))
9223
9298
  );
9224
9299
  const present = presentConfigs[0] ?? null;
9225
9300
  if (presentConfigs.length > 1) {
@@ -9228,7 +9303,7 @@ async function runInit(options) {
9228
9303
  );
9229
9304
  }
9230
9305
  const configName = present !== null && options.force ? present : preferredName;
9231
- const configPath = path11.join(options.cwd, configName);
9306
+ const configPath = path12.join(options.cwd, configName);
9232
9307
  const reused = present !== null && options.force !== true && options.reuseConfig === true;
9233
9308
  if (reused) notes.push(`Kept the existing ${present} instead of writing a new one.`);
9234
9309
  if (options.dryRun) {
@@ -9245,7 +9320,7 @@ async function runInit(options) {
9245
9320
  dependency: { name: GENERATOR_NAME, range: `^${GENERATOR_VERSION}`, added: false },
9246
9321
  notes,
9247
9322
  outDir: answers.outDir,
9248
- briefPath: path11.join(options.cwd, BRIEF_SCAFFOLD_FILE),
9323
+ briefPath: path12.join(options.cwd, BRIEF_SCAFFOLD_FILE),
9249
9324
  briefWritten: false
9250
9325
  };
9251
9326
  }
@@ -9264,13 +9339,13 @@ async function runInit(options) {
9264
9339
  'package.json already defines a "snapshot" config. Remove that key, or re-run with --force to write a config file that takes precedence over it.'
9265
9340
  );
9266
9341
  }
9267
- if (fs11.existsSync(configPath) && !options.force && !reused) {
9342
+ if (fs12.existsSync(configPath) && !options.force && !reused) {
9268
9343
  throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
9269
9344
  }
9270
9345
  if (!reused) writeFileOrExplain(configPath, configText);
9271
- const briefPath = path11.join(options.cwd, BRIEF_SCAFFOLD_FILE);
9346
+ const briefPath = path12.join(options.cwd, BRIEF_SCAFFOLD_FILE);
9272
9347
  let briefWritten = false;
9273
- if (!fs11.existsSync(briefPath)) {
9348
+ if (!fs12.existsSync(briefPath)) {
9274
9349
  writeFileOrExplain(briefPath, BRIEF_SCAFFOLD);
9275
9350
  briefWritten = true;
9276
9351
  }
@@ -9299,12 +9374,12 @@ async function runInit(options) {
9299
9374
  }
9300
9375
 
9301
9376
  // src/wizard/autopilot.ts
9302
- import * as fs12 from "fs";
9303
- import * as path12 from "path";
9377
+ import * as fs13 from "fs";
9378
+ import * as path13 from "path";
9304
9379
  function describeTarget(cwd) {
9305
- const relative15 = path12.relative(process.cwd(), cwd);
9380
+ const relative15 = path13.relative(process.cwd(), cwd);
9306
9381
  if (relative15 === "") return "this directory";
9307
- if (relative15.startsWith("..") || path12.isAbsolute(relative15)) return cwd;
9382
+ if (relative15.startsWith("..") || path13.isAbsolute(relative15)) return cwd;
9308
9383
  return relative15;
9309
9384
  }
9310
9385
  function firstRunMessage(reason, cwd) {
@@ -9328,7 +9403,7 @@ function planFirstRun(facts) {
9328
9403
  var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
9329
9404
  function isEffectivelyEmpty(cwd) {
9330
9405
  try {
9331
- return fs12.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
9406
+ return fs13.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
9332
9407
  } catch {
9333
9408
  return false;
9334
9409
  }
@@ -9336,7 +9411,7 @@ function isEffectivelyEmpty(cwd) {
9336
9411
  function hasPriorSnapshot(cwd, outDir) {
9337
9412
  let parsed;
9338
9413
  try {
9339
- parsed = JSON.parse(fs12.readFileSync(path12.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
9414
+ parsed = JSON.parse(fs13.readFileSync(path13.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
9340
9415
  } catch {
9341
9416
  return false;
9342
9417
  }
@@ -9422,7 +9497,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
9422
9497
  "# Codebase Health & Security Audit",
9423
9498
  "",
9424
9499
  `**Generated:** ${manifest.generatedAt} `,
9425
- `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
9500
+ `**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" : ""} `,
9426
9501
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
9427
9502
  `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
9428
9503
  `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
@@ -9569,7 +9644,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
9569
9644
  }
9570
9645
 
9571
9646
  // src/generator/sarif.ts
9572
- import * as crypto2 from "crypto";
9647
+ import * as crypto3 from "crypto";
9573
9648
  var SARIF_VERSION = "2.1.0";
9574
9649
  var SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json";
9575
9650
  var BUILTIN_RULE_IDS = new Map(
@@ -9582,7 +9657,7 @@ var BUILTIN_RULE_IDS = new Map(
9582
9657
  function ruleIdFor(name) {
9583
9658
  const builtin = BUILTIN_RULE_IDS.get(name);
9584
9659
  if (builtin !== void 0) return builtin;
9585
- const digest = crypto2.createHash("sha256").update(name).digest("hex").slice(0, 8);
9660
+ const digest = crypto3.createHash("sha256").update(name).digest("hex").slice(0, 8);
9586
9661
  return `CS${digest.toUpperCase()}`;
9587
9662
  }
9588
9663
  function generateSarifReport(manifest, findings, rules, toolVersion) {
@@ -9661,7 +9736,7 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
9661
9736
  }
9662
9737
 
9663
9738
  // src/partitioner/chunker.ts
9664
- import * as crypto3 from "crypto";
9739
+ import * as crypto4 from "crypto";
9665
9740
  var HEADER_RESERVE_BYTES = 2048 + Buffer.byteLength(UNTRUSTED_CONTENT_NOTICE, "utf8") + 8;
9666
9741
  var MIN_SECTION_BUDGET_BYTES = 512;
9667
9742
  var MIN_PART_BUDGET_BYTES = MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES;
@@ -9925,7 +10000,7 @@ function rehashPart(part, markdown) {
9925
10000
  metadata: {
9926
10001
  ...part.metadata,
9927
10002
  byteSize: Buffer.byteLength(redistributed, "utf8"),
9928
- sha256: crypto3.createHash("sha256").update(redistributed).digest("hex"),
10003
+ sha256: crypto4.createHash("sha256").update(redistributed).digest("hex"),
9929
10004
  lines: countLines(redistributed),
9930
10005
  estimatedTokens
9931
10006
  }
@@ -10006,7 +10081,7 @@ function renderGroups(groups, contentFingerprint, assemble = (group, index, tota
10006
10081
  return groups.map((group, index) => {
10007
10082
  const { filename, content, estimatedTokens } = assemble(group, index, total);
10008
10083
  const byteSize = Buffer.byteLength(content, "utf8");
10009
- const sha2562 = crypto3.createHash("sha256").update(content).digest("hex");
10084
+ const sha2562 = crypto4.createHash("sha256").update(content).digest("hex");
10010
10085
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
10011
10086
  const includedFiles = group.sections.map(({ file }) => ({
10012
10087
  relativePath: file.relativePath,
@@ -10088,7 +10163,7 @@ function renderSummary(summary, inclusionMode) {
10088
10163
  }
10089
10164
  function anchorForPath(filePath) {
10090
10165
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
10091
- const digest = crypto3.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
10166
+ const digest = crypto4.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
10092
10167
  return `${slug || "file"}-${digest}`;
10093
10168
  }
10094
10169
 
@@ -10435,13 +10510,19 @@ function planForQuestion(manifest, question, options = {}) {
10435
10510
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
10436
10511
  }
10437
10512
  const notes = [];
10513
+ if (manifest.files.length === 0) {
10514
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
10515
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
10516
+ }
10438
10517
  if (scored.length === 0) {
10439
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10440
10518
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
10441
10519
  for (const hub of hubs) {
10442
10520
  const file = byPath.get(hub.path);
10443
10521
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
10444
10522
  }
10523
+ if (scored.length > 0) {
10524
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10525
+ }
10445
10526
  }
10446
10527
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
10447
10528
  const chosen = /* @__PURE__ */ new Map();
@@ -10505,7 +10586,14 @@ function planForQuestion(manifest, question, options = {}) {
10505
10586
  }
10506
10587
  }
10507
10588
  }
10508
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
10589
+ if (chosen.size === 0) {
10590
+ if (scored.length === 0) {
10591
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
10592
+ } else {
10593
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
10594
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber2(cheapest) + " tokens.");
10595
+ }
10596
+ }
10509
10597
  notes.push(
10510
10598
  formatNumber2(chosen.size) + " file(s) chosen of " + formatNumber2(manifest.files.length) + " in the snapshot; " + formatNumber2(skipped.length) + " skipped for budget."
10511
10599
  );
@@ -11077,7 +11165,7 @@ function snapshotSection(manifest, code, partsWritten) {
11077
11165
  const out = ["## This snapshot", ""];
11078
11166
  out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
11079
11167
  out.push(
11080
- "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
11168
+ "- 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)." : ".")
11081
11169
  );
11082
11170
  out.push(
11083
11171
  manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
@@ -11250,7 +11338,7 @@ function generateReadme(manifest, artifacts) {
11250
11338
  "",
11251
11339
  `- **Generated At:** \`${manifest.generatedAt}\``,
11252
11340
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
11253
- `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
11341
+ `- **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" : ""}`,
11254
11342
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
11255
11343
  `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
11256
11344
  `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
@@ -11396,8 +11484,8 @@ function treeTruncationWarnings(treeText) {
11396
11484
  }
11397
11485
 
11398
11486
  // src/generator/overview.ts
11399
- import * as fs13 from "fs";
11400
- import * as path13 from "path";
11487
+ import * as fs14 from "fs";
11488
+ import * as path14 from "path";
11401
11489
  var SUMMARY_LIMIT = 400;
11402
11490
  var MAX_RELEASES = 2;
11403
11491
  function readProjectOverview(cwd) {
@@ -11409,13 +11497,13 @@ function readProjectOverview(cwd) {
11409
11497
  }
11410
11498
  function readText(file) {
11411
11499
  try {
11412
- return fs13.readFileSync(file, "utf8");
11500
+ return fs14.readFileSync(file, "utf8");
11413
11501
  } catch {
11414
11502
  return null;
11415
11503
  }
11416
11504
  }
11417
11505
  function readDescription(cwd) {
11418
- const raw = readText(path13.join(cwd, "package.json"));
11506
+ const raw = readText(path14.join(cwd, "package.json"));
11419
11507
  if (raw === null) return {};
11420
11508
  try {
11421
11509
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -11425,7 +11513,7 @@ function readDescription(cwd) {
11425
11513
  }
11426
11514
  }
11427
11515
  function readSummary(cwd) {
11428
- const raw = readText(path13.join(cwd, "README.md"));
11516
+ const raw = readText(path14.join(cwd, "README.md"));
11429
11517
  if (raw === null) return {};
11430
11518
  const text2 = raw.replace(/<h[1-6][^>]*>[\s\S]*?<\/h[1-6]>/gi, "\n").replace(/<\/(p|div|section|header|footer|li)>/gi, "\n").replace(/<br\s*\/?>/gi, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
11431
11519
  const paragraph = [];
@@ -11451,16 +11539,16 @@ function truncate(text2, limit) {
11451
11539
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
11452
11540
  }
11453
11541
  function readReleases(cwd) {
11454
- const raw = readText(path13.join(cwd, "CHANGELOG.md"));
11542
+ const raw = readText(path14.join(cwd, "CHANGELOG.md"));
11455
11543
  if (raw === null) return [];
11456
11544
  const headings = raw.split(/\r?\n/).map((line) => /^##\s+(.+?)\s*$/.exec(line)?.[1]?.trim()).filter((heading) => heading !== void 0 && /^v?\d+\.\d+/.test(heading));
11457
11545
  return headings.slice(0, MAX_RELEASES);
11458
11546
  }
11459
11547
 
11460
11548
  // src/remote/source.ts
11461
- import * as fs14 from "fs";
11549
+ import * as fs15 from "fs";
11462
11550
  import * as os from "os";
11463
- import * as path14 from "path";
11551
+ import * as path15 from "path";
11464
11552
  import { spawnSync as spawnSync3 } from "child_process";
11465
11553
  import { lookup } from "dns/promises";
11466
11554
  import { fileURLToPath } from "url";
@@ -11504,7 +11592,7 @@ function parseRemoteSource(input, options = {}) {
11504
11592
  const directory = fileURLToPath(url2);
11505
11593
  return {
11506
11594
  ok: true,
11507
- source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path14.basename(directory), ref: null }
11595
+ source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path15.basename(directory), ref: null }
11508
11596
  };
11509
11597
  }
11510
11598
  let url;
@@ -11571,9 +11659,9 @@ function gitEnvironment(token, host) {
11571
11659
  async function cloneRepository(source, options) {
11572
11660
  const log = options.log ?? (() => {
11573
11661
  });
11574
- const dest = path14.resolve(options.dest);
11575
- fs14.rmSync(dest, { recursive: true, force: true });
11576
- fs14.mkdirSync(dest, { recursive: true });
11662
+ const dest = path15.resolve(options.dest);
11663
+ fs15.rmSync(dest, { recursive: true, force: true });
11664
+ fs15.mkdirSync(dest, { recursive: true });
11577
11665
  const args = ["clone", "--depth", "1", "--single-branch", "--no-tags", "--quiet"];
11578
11666
  if (options.ref !== void 0 && options.ref !== null && options.ref !== "") {
11579
11667
  args.push("--branch", options.ref);
@@ -11623,16 +11711,16 @@ function directorySize(root) {
11623
11711
  const current = stack.pop();
11624
11712
  let entries;
11625
11713
  try {
11626
- entries = fs14.readdirSync(current, { withFileTypes: true });
11714
+ entries = fs15.readdirSync(current, { withFileTypes: true });
11627
11715
  } catch {
11628
11716
  continue;
11629
11717
  }
11630
11718
  for (const entry of entries) {
11631
- const full = path14.join(current, entry.name);
11719
+ const full = path15.join(current, entry.name);
11632
11720
  if (entry.isDirectory()) stack.push(full);
11633
11721
  else if (entry.isFile()) {
11634
11722
  try {
11635
- total += fs14.statSync(full).size;
11723
+ total += fs15.statSync(full).size;
11636
11724
  } catch {
11637
11725
  }
11638
11726
  }
@@ -11641,7 +11729,7 @@ function directorySize(root) {
11641
11729
  return total;
11642
11730
  }
11643
11731
  function makeCloneDirectory() {
11644
- return fs14.mkdtempSync(path14.join(os.tmpdir(), "codebase-snapshot-clone-"));
11732
+ return fs15.mkdtempSync(path15.join(os.tmpdir(), "codebase-snapshot-clone-"));
11645
11733
  }
11646
11734
 
11647
11735
  // src/web/server.ts
@@ -11864,74 +11952,6 @@ import * as path16 from "path";
11864
11952
  import { execFileSync as execFileSync3 } from "child_process";
11865
11953
  import { createHash as createHash7 } from "crypto";
11866
11954
 
11867
- // src/signing.ts
11868
- import * as crypto4 from "crypto";
11869
- import * as fs15 from "fs";
11870
- import * as path15 from "path";
11871
- var SIGNATURE_FILE = "signature.json";
11872
- function loadSigningKey(environment = process.env) {
11873
- const pem = environment.SNAPSHOT_SIGNING_KEY;
11874
- if (pem === void 0 || pem.trim() === "") return null;
11875
- return crypto4.createPrivateKey({ key: pem, format: "pem" });
11876
- }
11877
- function signManifest(manifestPath, options = {}) {
11878
- const bytes = fs15.readFileSync(manifestPath);
11879
- const manifest = JSON.parse(bytes.toString("utf8"));
11880
- if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
11881
- throw new Error("refusing to sign: the manifest has no valid fingerprint");
11882
- }
11883
- const configured = options.key ?? null;
11884
- const key = configured ?? crypto4.generateKeyPairSync("ed25519").privateKey;
11885
- const publicKey = crypto4.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
11886
- const signature = crypto4.sign(null, bytes, key).toString("base64");
11887
- return {
11888
- algorithm: "ed25519",
11889
- signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
11890
- fingerprint: manifest.fingerprint,
11891
- manifestSha256: crypto4.createHash("sha256").update(bytes).digest("hex"),
11892
- publicKey,
11893
- signature,
11894
- keyOrigin: configured === null ? "generated" : "configured"
11895
- };
11896
- }
11897
- function writeSignature(snapshotDir, record) {
11898
- const target = path15.join(snapshotDir, SIGNATURE_FILE);
11899
- fs15.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
11900
- return target;
11901
- }
11902
- function verifySnapshotSignature(snapshotDir) {
11903
- const signaturePath = path15.join(snapshotDir, SIGNATURE_FILE);
11904
- const manifestPath = path15.join(snapshotDir, "manifest.json");
11905
- if (!fs15.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
11906
- let record;
11907
- try {
11908
- record = JSON.parse(fs15.readFileSync(signaturePath, "utf8"));
11909
- } catch (error) {
11910
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
11911
- }
11912
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
11913
- return { ok: false, reason: "signature.json is not an ed25519 record" };
11914
- }
11915
- let bytes;
11916
- try {
11917
- bytes = fs15.readFileSync(manifestPath);
11918
- } catch {
11919
- return { ok: false, reason: "the signed manifest is missing" };
11920
- }
11921
- const sha2562 = crypto4.createHash("sha256").update(bytes).digest("hex");
11922
- if (sha2562 !== record.manifestSha256) {
11923
- return { ok: false, reason: "manifest.json changed after it was signed" };
11924
- }
11925
- let verified = false;
11926
- try {
11927
- const key = crypto4.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
11928
- verified = crypto4.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
11929
- } catch (error) {
11930
- return { ok: false, reason: "the signature could not be checked: " + error.message };
11931
- }
11932
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
11933
- }
11934
-
11935
11955
  // src/partitioner/part-format.ts
11936
11956
  var FILE_HEADING = "### FILE: ";
11937
11957
  var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
@@ -12511,8 +12531,9 @@ function auditSnapshot(options) {
12511
12531
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
12512
12532
  disagreements.push("file count");
12513
12533
  }
12534
+ const sourceGone = typeof member.path === "string" && !fs16.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
12514
12535
  checks.push(
12515
- disagreements.length === 0 ? check(
12536
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
12516
12537
  "workspace.index",
12517
12538
  "The workspace index agrees with this member",
12518
12539
  "warning",
@@ -12534,6 +12555,7 @@ function auditSnapshot(options) {
12534
12555
  let scannedBytes = 0;
12535
12556
  for (const relative15 of walk(snapshotDir)) {
12536
12557
  if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
12558
+ if (relative15 === SIGNATURE_FILE) continue;
12537
12559
  const text2 = readText2(path16.join(snapshotDir, relative15));
12538
12560
  if (text2 === null) continue;
12539
12561
  scannedBytes += Buffer.byteLength(text2, "utf8");
@@ -12542,6 +12564,28 @@ function auditSnapshot(options) {
12542
12564
  leakHits.push(relative15 + " (" + found.findings.length + " line(s))");
12543
12565
  }
12544
12566
  }
12567
+ const signatureRecordPath = path16.join(snapshotDir, SIGNATURE_FILE);
12568
+ if (fs16.existsSync(signatureRecordPath)) {
12569
+ const recordText = readText2(signatureRecordPath);
12570
+ if (recordText !== null) {
12571
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
12572
+ let scanText = recordText;
12573
+ try {
12574
+ const record = JSON.parse(recordText);
12575
+ const rest = { ...record };
12576
+ delete rest.publicKey;
12577
+ delete rest.signature;
12578
+ delete rest.manifestSha256;
12579
+ delete rest.fingerprint;
12580
+ scanText = JSON.stringify(rest, null, 2);
12581
+ } catch {
12582
+ }
12583
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
12584
+ if (found.findings.length > 0) {
12585
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
12586
+ }
12587
+ }
12588
+ }
12545
12589
  checks.push(
12546
12590
  leakHits.length === 0 ? check(
12547
12591
  "secrets.artifacts",
@@ -12825,6 +12869,9 @@ function windowText(body, fromLine, lineCount) {
12825
12869
  };
12826
12870
  }
12827
12871
 
12872
+ // src/mcp/tools.ts
12873
+ import { createHash as createHash8 } from "crypto";
12874
+
12828
12875
  // src/mcp/workspace.ts
12829
12876
  import * as fs17 from "fs";
12830
12877
  import * as path18 from "path";
@@ -13046,6 +13093,10 @@ var WRITES = {
13046
13093
  openWorldHint: false
13047
13094
  };
13048
13095
  var MAX_RESULT_BYTES = 64 * 1024;
13096
+ function capResultText(text2) {
13097
+ const clipped = truncateToBytes(text2, MAX_RESULT_BYTES);
13098
+ return { text: clipped.isTruncated ? clipped.content : text2, clipped: clipped.isTruncated };
13099
+ }
13049
13100
  var ROOT_PROPERTY = {
13050
13101
  type: "string",
13051
13102
  description: "Repository root. Defaults to the directory this server was started in."
@@ -13233,6 +13284,17 @@ var historyTool = {
13233
13284
  isError: true
13234
13285
  };
13235
13286
  }
13287
+ const manifestRead = readManifest3(prepared.workspace);
13288
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
13289
+ if (recordedLog !== void 0 && recordedLog !== null) {
13290
+ const digest = createHash8("sha256").update(text2, "utf8").digest("hex");
13291
+ if (digest !== recordedLog.sha256) {
13292
+ return {
13293
+ 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.",
13294
+ isError: true
13295
+ };
13296
+ }
13297
+ }
13236
13298
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
13237
13299
  const commits = parseHistoryReport(text2).slice(0, limit);
13238
13300
  return {
@@ -13292,9 +13354,12 @@ var budgetTool = {
13292
13354
  });
13293
13355
  }
13294
13356
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
13357
+ if (read.manifest.files.length === 0) {
13358
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
13359
+ }
13295
13360
  for (const row of rows) {
13296
13361
  lines.push(
13297
- 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" : "") + ")")
13362
+ 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" : "") + ")")
13298
13363
  );
13299
13364
  }
13300
13365
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -13546,7 +13611,7 @@ var routesTool = {
13546
13611
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
13547
13612
  const text2 = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
13548
13613
  routes.length + " route(s):",
13549
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
13614
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
13550
13615
  ].join("\n");
13551
13616
  return { text: text2, structured: { total: routes.length, routes } };
13552
13617
  }
@@ -13715,8 +13780,9 @@ var searchTool = {
13715
13780
  }
13716
13781
  }
13717
13782
  }
13783
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
13718
13784
  const lines = [
13719
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
13785
+ 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." : ""),
13720
13786
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
13721
13787
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
13722
13788
  ];
@@ -13739,7 +13805,9 @@ var statsTool = {
13739
13805
  parts: { type: "integer" },
13740
13806
  tokens: { type: "integer" },
13741
13807
  layers: { type: "object" },
13742
- kinds: { type: "object" }
13808
+ kinds: { type: "object" },
13809
+ heaviest: { type: "array", items: { type: "object" } },
13810
+ partSizes: { type: "array", items: { type: "object" } }
13743
13811
  }
13744
13812
  },
13745
13813
  annotations: READ_ONLY,
@@ -13750,7 +13818,11 @@ var statsTool = {
13750
13818
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13751
13819
  const manifest = read.manifest;
13752
13820
  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 }));
13753
- const parts = manifest.parts.map((part) => ({ filename: part.filename, tokens: part.estimatedTokens }));
13821
+ const parts = manifest.parts.map((part) => ({
13822
+ filename: part.filename,
13823
+ bytes: part.byteSize,
13824
+ tokens: part.estimatedTokens
13825
+ }));
13754
13826
  const lines = [
13755
13827
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
13756
13828
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -13806,7 +13878,7 @@ var reviewTool = {
13806
13878
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13807
13879
  let validation;
13808
13880
  try {
13809
- validation = validateSnapshot(workspace.config);
13881
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
13810
13882
  } catch (error) {
13811
13883
  return { text: error.message, isError: true };
13812
13884
  }
@@ -13906,24 +13978,17 @@ var diffContextTool = {
13906
13978
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
13907
13979
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
13908
13980
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
13981
+ const resolver = buildImportResolver(read.manifest.files, {
13982
+ tsconfig: tsconfigPathsFor(workspace.root)
13983
+ });
13909
13984
  const importers = /* @__PURE__ */ new Map();
13910
13985
  for (const entry of read.manifest.indexes.imports.byFile) {
13911
13986
  for (const specifier of entry.imports) {
13912
- if (!specifier.startsWith(".")) continue;
13913
- const base = entry.path.includes("/") ? entry.path.slice(0, entry.path.lastIndexOf("/")) : "";
13914
- const parts = [];
13915
- for (const segment of (base + "/" + specifier).split("/")) {
13916
- if (segment === "" || segment === ".") continue;
13917
- if (segment === "..") parts.pop();
13918
- else parts.push(segment);
13919
- }
13920
- const joined = parts.join("/").toLowerCase();
13921
- const withoutExtension = joined.replace(/\.[cm]?[jt]sx?$/, "");
13922
- 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);
13923
- if (target === void 0) continue;
13924
- const list2 = importers.get(target.relativePath) ?? [];
13987
+ const target = resolveSpecifier(entry.path, specifier, resolver);
13988
+ if (target === null) continue;
13989
+ const list2 = importers.get(target) ?? [];
13925
13990
  list2.push(entry.path);
13926
- importers.set(target.relativePath, list2);
13991
+ importers.set(target, list2);
13927
13992
  }
13928
13993
  }
13929
13994
  const missing = [];
@@ -13958,9 +14023,12 @@ var diffContextTool = {
13958
14023
  continue;
13959
14024
  }
13960
14025
  used += tokens;
14026
+ const capped2 = capResultText(window.text);
13961
14027
  changed.push({ path: file.relativePath, part: file.part, tokens });
13962
- text2.push("### " + file.relativePath + " (" + file.part + ")");
13963
- text2.push(window.text);
14028
+ text2.push(
14029
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
14030
+ );
14031
+ text2.push(capped2.text);
13964
14032
  }
13965
14033
  const dependents = [];
13966
14034
  for (const entry of changed) {
@@ -14042,11 +14110,13 @@ var symbolTool = {
14042
14110
  if (index === -1) continue;
14043
14111
  const from = Math.max(0, index - 3);
14044
14112
  const to = Math.min(lines.length, index + windowSize);
14113
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
14045
14114
  matches.push({
14046
14115
  path: file.relativePath,
14047
14116
  part: file.part,
14048
14117
  line: index + 1,
14049
- text: lines.slice(from, to).join("\n")
14118
+ text: capped2.text,
14119
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
14050
14120
  });
14051
14121
  }
14052
14122
  if (matches.length === 0) {
@@ -14177,7 +14247,8 @@ var contextTool = {
14177
14247
  continue;
14178
14248
  }
14179
14249
  const window = windowText(section.body, 1, linesPerFile);
14180
- const body = window.text;
14250
+ const capped2 = capResultText(window.text);
14251
+ const body = capped2.text;
14181
14252
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
14182
14253
  if (used + tokens > budget) {
14183
14254
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -14186,14 +14257,19 @@ var contextTool = {
14186
14257
  missing.push(file.relativePath + " (budget)");
14187
14258
  continue;
14188
14259
  }
14189
- const partial = Math.max(1, Math.ceil(Buffer.byteLength(smaller.text, "utf8") / 4));
14190
- text2.push("### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines)");
14191
- text2.push(smaller.text);
14260
+ const smallerCapped = capResultText(smaller.text);
14261
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
14262
+ text2.push(
14263
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
14264
+ );
14265
+ text2.push(smallerCapped.text);
14192
14266
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
14193
14267
  used += partial;
14194
14268
  continue;
14195
14269
  }
14196
- text2.push("### " + file.relativePath + " (" + file.part + ")");
14270
+ text2.push(
14271
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
14272
+ );
14197
14273
  text2.push(body);
14198
14274
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
14199
14275
  used += tokens;
@@ -14367,8 +14443,17 @@ var answerTool = {
14367
14443
  maxTokens,
14368
14444
  ...args.includeTests === true ? { includeTests: true } : {}
14369
14445
  });
14446
+ if (read.manifest.files.length === 0) {
14447
+ return {
14448
+ 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).",
14449
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
14450
+ };
14451
+ }
14370
14452
  const blocks = [];
14371
- const omitted = [];
14453
+ const omitted = plan.skipped.map((entry) => ({
14454
+ path: entry.path,
14455
+ reason: entry.reason
14456
+ }));
14372
14457
  let used = 0;
14373
14458
  const parts = /* @__PURE__ */ new Map();
14374
14459
  for (const planned of plan.files) {
@@ -14397,14 +14482,23 @@ var answerTool = {
14397
14482
  continue;
14398
14483
  }
14399
14484
  const window = windowText(section.body, 1, linesPerFile);
14400
- const text2 = window.text;
14401
- const tokens = estimateTokens(text2);
14485
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
14486
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
14487
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
14488
+ const tokens = estimateTokens(bodyText);
14402
14489
  if (used + tokens > maxTokens && blocks.length > 0) {
14403
14490
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
14404
14491
  continue;
14405
14492
  }
14406
- const numbered = text2.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
14407
- blocks.push({ path: planned.path, why: planned.why, tokens, text: numbered, truncated: window.truncated, totalLines: window.totalLines });
14493
+ blocks.push({
14494
+ path: planned.path,
14495
+ why: planned.why,
14496
+ tokens,
14497
+ text: bodyText,
14498
+ truncated: window.truncated || clipped.isTruncated,
14499
+ totalLines: window.totalLines,
14500
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
14501
+ });
14408
14502
  used += tokens;
14409
14503
  }
14410
14504
  const lines = [
@@ -14413,7 +14507,9 @@ var answerTool = {
14413
14507
  ];
14414
14508
  for (const block of blocks) {
14415
14509
  lines.push("");
14416
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
14510
+ lines.push(
14511
+ "## " + 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") + ")"
14512
+ );
14417
14513
  lines.push("Why: " + block.why);
14418
14514
  lines.push("```");
14419
14515
  lines.push(block.text);
@@ -14424,6 +14520,11 @@ var answerTool = {
14424
14520
  lines.push("Not included:");
14425
14521
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
14426
14522
  }
14523
+ if (plan.notes.length > 0) {
14524
+ lines.push("");
14525
+ lines.push("Notes:");
14526
+ for (const note of plan.notes) lines.push("- " + note);
14527
+ }
14427
14528
  return {
14428
14529
  text: lines.join("\n"),
14429
14530
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -14538,7 +14639,7 @@ var statusTool = {
14538
14639
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
14539
14640
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
14540
14641
  `Fingerprint: ${manifest.fingerprint}`,
14541
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
14642
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
14542
14643
  ];
14543
14644
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
14544
14645
  if (!versionMatches) {
@@ -14689,6 +14790,16 @@ var generateTool = {
14689
14790
  minimum: 500,
14690
14791
  description: "Fit the snapshot into this token budget, highest value first."
14691
14792
  },
14793
+ only: {
14794
+ type: "array",
14795
+ items: { type: "string" },
14796
+ description: "Globs to include: replaces the config allow-list for this run."
14797
+ },
14798
+ ignore: {
14799
+ type: "array",
14800
+ items: { type: "string" },
14801
+ description: "Globs to exclude, added to the config deny-list for this run."
14802
+ },
14692
14803
  ...SCOPE_PROPERTIES
14693
14804
  },
14694
14805
  additionalProperties: false
@@ -14717,7 +14828,9 @@ var generateTool = {
14717
14828
  ...args.tokenTree === true ? { tokenTree: true } : {},
14718
14829
  ...args.stripComments === true ? { stripComments: true } : {},
14719
14830
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
14720
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
14831
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
14832
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
14833
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
14721
14834
  };
14722
14835
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
14723
14836
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -14761,6 +14874,20 @@ var generateTool = {
14761
14874
  };
14762
14875
  }
14763
14876
  };
14877
+ function configAsGenerated(workspace, manifest) {
14878
+ const recorded = manifest.config;
14879
+ return {
14880
+ ...workspace.config,
14881
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
14882
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
14883
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
14884
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
14885
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
14886
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
14887
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
14888
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
14889
+ };
14890
+ }
14764
14891
  var validateTool = {
14765
14892
  name: "snapshot_validate",
14766
14893
  title: "Validate the snapshot",
@@ -14782,9 +14909,11 @@ var validateTool = {
14782
14909
  const prepared = await prepare(args, context, workspaceOverrides(args));
14783
14910
  if (!prepared.ok) return prepared.outcome;
14784
14911
  const workspace = prepared.workspace;
14912
+ const read = readManifest3(workspace);
14913
+ if (!read.ok) return failure(read.message);
14785
14914
  let result;
14786
14915
  try {
14787
- result = validateSnapshot(workspace.config);
14916
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
14788
14917
  } catch (error) {
14789
14918
  return failure(error instanceof Error ? error.message : String(error));
14790
14919
  }
@@ -15148,6 +15277,12 @@ var readTool = {
15148
15277
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
15149
15278
  );
15150
15279
  }
15280
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
15281
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
15282
+ }
15283
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
15284
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
15285
+ }
15151
15286
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
15152
15287
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
15153
15288
  const window = windowText(section.body, fromLine, lineCount);
@@ -15597,6 +15732,8 @@ var COMMAND_OPTION_SCOPE = {
15597
15732
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
15598
15733
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
15599
15734
  // list, so removing them narrows the two together.
15735
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
15736
+ update: ["format", "help"],
15600
15737
  report: [
15601
15738
  "cwd",
15602
15739
  "out-dir",
@@ -15958,6 +16095,13 @@ function buildAgentContract() {
15958
16095
  positionals: [],
15959
16096
  exits: [0]
15960
16097
  },
16098
+ {
16099
+ name: "update",
16100
+ aliases: [],
16101
+ 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.",
16102
+ positionals: [],
16103
+ exits: [0, 1, 2]
16104
+ },
15961
16105
  {
15962
16106
  name: "skill",
15963
16107
  aliases: [],
@@ -16253,14 +16397,14 @@ function buildAgentContract() {
16253
16397
  type: "boolean",
16254
16398
  default: false,
16255
16399
  appliesTo: optionAppliesTo("include-diffs"),
16256
- 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."
16400
+ 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."
16257
16401
  },
16258
16402
  {
16259
16403
  flag: "--include-logs",
16260
16404
  type: "string",
16261
16405
  default: "unset",
16262
16406
  appliesTo: optionAppliesTo("include-logs"),
16263
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
16407
+ 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."
16264
16408
  },
16265
16409
  {
16266
16410
  flag: "--token-tree",
@@ -17254,6 +17398,18 @@ function createMcpServer(options) {
17254
17398
  if (!isJsonObject(rawArguments)) {
17255
17399
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
17256
17400
  }
17401
+ const missing = (prompt.arguments ?? []).filter((argument) => {
17402
+ if (argument.required !== true) return false;
17403
+ const value = rawArguments[argument.name];
17404
+ return typeof value !== "string" || value.trim() === "";
17405
+ });
17406
+ if (missing.length > 0) {
17407
+ return errorResponse(
17408
+ id,
17409
+ ERROR_CODES.invalidParams,
17410
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
17411
+ );
17412
+ }
17257
17413
  const built = prompt.build(rawArguments);
17258
17414
  const messages = built.messages.map((message) => ({
17259
17415
  role: message.role,
@@ -17727,20 +17883,20 @@ var SERVE_PAGE = `<!doctype html>
17727
17883
  <header><b>codebase-snapshot</b><span>a snapshot an agent can trust</span></header>
17728
17884
  <main>
17729
17885
  <form id="gen">
17730
- <input id="source" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
17731
- <select id="mode" title="What to generate">
17886
+ <input id="source" aria-label="repository path or URL" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
17887
+ <select id="mode" aria-label="What to generate" title="What to generate">
17732
17888
  <option value="full">whole repository</option>
17733
17889
  <option value="slice">a slice for a question</option>
17734
17890
  <option value="budget">fit a token budget</option>
17735
17891
  </select>
17736
- <input id="question" placeholder="the question (slice mode)" spellcheck="false" hidden>
17737
- <input id="budget" type="number" min="500" step="500" value="30000" title="token budget" hidden>
17892
+ <input id="question" aria-label="Question for the slice" placeholder="the question (slice mode)" spellcheck="false" hidden>
17893
+ <input id="budget" type="number" min="500" step="500" value="30000" aria-label="Token budget" title="token budget" hidden>
17738
17894
  <button id="run" type="submit">Generate</button>
17739
17895
  <button id="download" type="button" disabled>Download .zip</button>
17740
17896
  </form>
17741
- <div id="status">Paste an absolute path, or a repository URL (https://github.com/owner/repo). Remote fetches are shallow and public-only.</div>
17897
+ <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>
17742
17898
  <div id="auth" hidden>
17743
- <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>
17899
+ <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>
17744
17900
  </div>
17745
17901
  <div class="row">
17746
17902
  <section><h2>Brief <span id="fingerprint"></span> <span id="health"></span></h2><pre id="brief">No snapshot loaded.</pre></section>
@@ -18035,9 +18191,14 @@ async function startWebServer(options) {
18035
18191
  send(400, { error: "not a directory: " + target });
18036
18192
  return;
18037
18193
  }
18194
+ const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
18195
+ if (loaded.errors.length > 0) {
18196
+ send(400, { error: loaded.errors.join("; ") });
18197
+ return;
18198
+ }
18038
18199
  const started = Date.now();
18039
18200
  try {
18040
- const manifest = generateSnapshot({ cwd: target }, {
18201
+ const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
18041
18202
  ...provenance === void 0 ? {} : { source: provenance },
18042
18203
  ...mode === "slice" ? { slice: { question } } : {},
18043
18204
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
@@ -18177,8 +18338,8 @@ import * as path23 from "path";
18177
18338
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
18178
18339
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
18179
18340
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
18180
- var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
18181
- var REQUEST_TIMEOUT_MS = 1200;
18341
+ var FAILURE_INTERVAL_MS = 5 * 60 * 1e3;
18342
+ var REQUEST_TIMEOUT_MS = 2500;
18182
18343
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
18183
18344
  const normalise = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
18184
18345
  const script = normalise(scriptPath);
@@ -18242,7 +18403,7 @@ function shouldCheck(argv, env) {
18242
18403
  if (env.CI !== void 0 && env.CI !== "" && env.CI !== "false" && env.CI !== "0") return false;
18243
18404
  const args = argv.map((argument) => argument.toLowerCase());
18244
18405
  if (args.includes("--no-update-check")) return false;
18245
- for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
18406
+ for (const skip of ["mcp", "describe", "skill", "update", "--version", "-v", "--help", "-h"]) {
18246
18407
  if (args.includes(skip)) return false;
18247
18408
  }
18248
18409
  let format = null;
@@ -18338,13 +18499,19 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
18338
18499
  });
18339
18500
  }
18340
18501
  async function checkForUpdate(options) {
18502
+ const latest = await resolveLatest(options);
18503
+ if (!latest) return null;
18504
+ return isNewer(latest, options.current) ? { current: options.current, latest } : null;
18505
+ }
18506
+ async function resolveLatest(options) {
18341
18507
  if (options.enabled === false) return null;
18342
18508
  const now = options.now ?? (() => Date.now());
18343
18509
  const fetchLatest = options.fetchLatest ?? fetchLatestVersion;
18510
+ const latestUrl = options.latestUrl ?? PACKAGE_LATEST_URL;
18344
18511
  let latest = null;
18345
18512
  try {
18346
18513
  const cached = readCache(options.cacheFile);
18347
- let needsFetch = cached === null;
18514
+ let needsFetch = cached === null || options.force === true;
18348
18515
  if (cached) {
18349
18516
  const age = now() - cached.checkedAt;
18350
18517
  if (cached.latest === null) {
@@ -18356,15 +18523,14 @@ async function checkForUpdate(options) {
18356
18523
  }
18357
18524
  }
18358
18525
  if (needsFetch) {
18359
- const fetched = await fetchLatest(PACKAGE_LATEST_URL, REQUEST_TIMEOUT_MS);
18526
+ const fetched = await fetchLatest(latestUrl, REQUEST_TIMEOUT_MS);
18360
18527
  writeCache(options.cacheFile, { checkedAt: now(), latest: fetched });
18361
- latest = fetched;
18528
+ latest = fetched ?? latest;
18362
18529
  }
18363
18530
  } catch {
18364
18531
  return null;
18365
18532
  }
18366
- if (!latest) return null;
18367
- return isNewer(latest, options.current) ? { current: options.current, latest } : null;
18533
+ return latest;
18368
18534
  }
18369
18535
  function formatUpdateNotice(notice, kind) {
18370
18536
  return `\u2191 codebase-snapshot ${notice.latest} is available \u2014 you have ${notice.current}.
@@ -20119,6 +20285,11 @@ function generateSnapshot(configInput, options) {
20119
20285
  detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
20120
20286
  files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
20121
20287
  };
20288
+ if (plan.files.length === 0) {
20289
+ warnings.push(
20290
+ "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.")
20291
+ );
20292
+ }
20122
20293
  }
20123
20294
  let budgetBlock;
20124
20295
  if (options?.budgetTokens !== void 0) {
@@ -20210,6 +20381,11 @@ function generateSnapshot(configInput, options) {
20210
20381
  warnings.push("No file fits --budget-tokens " + budget + "; the snapshot is empty.");
20211
20382
  }
20212
20383
  }
20384
+ if (config.include.length > 0 && files.length === 0) {
20385
+ warnings.push(
20386
+ "No file matched the include allow-list (" + config.include.length + " pattern(s): " + config.include.join(", ") + "), so the snapshot is empty."
20387
+ );
20388
+ }
20213
20389
  if (changedScope !== null || options?.deltaBase !== void 0) {
20214
20390
  const detail = changedScope !== null ? `not ${changedScope.detail}` : "identical to the base snapshot given with --delta";
20215
20391
  for (const relativePath of unchangedPaths) {
@@ -20348,6 +20524,12 @@ function generateSnapshot(configInput, options) {
20348
20524
  maxMonolithBytes: config.maxMonolithBytes ?? null,
20349
20525
  includeSensitiveFiles: config.includeSensitiveFiles,
20350
20526
  ...config.stripComments === true ? { stripComments: true } : {},
20527
+ // The other three settings the digest covers and the manifest did not record: without them a
20528
+ // validator (or `snapshot_review`) had no way to reconstruct the run, so a snapshot taken
20529
+ // with `--remove-empty-lines`, `--pack` or `--include-logs 3` looked stale forever.
20530
+ ...config.removeEmptyLines === true ? { removeEmptyLines: true } : {},
20531
+ ...config.pack === null ? {} : { pack: config.pack },
20532
+ logCount: config.logCount,
20351
20533
  // The destination the instructions were written for. Not part of `digest`: the payload is
20352
20534
  // identical whatever this says, and a new delivery preference must not make an existing
20353
20535
  // snapshot fail `validate` as configuration drift.
@@ -20491,6 +20673,18 @@ function generateSnapshot(configInput, options) {
20491
20673
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
20492
20674
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20493
20675
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
20676
+ if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20677
+ manifest.warnings.push(
20678
+ "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
20679
+ );
20680
+ manifest.totals.warningCount = manifest.warnings.length;
20681
+ }
20682
+ if (artifacts.log && logReport === null && !isGitRepository(config.cwd)) {
20683
+ manifest.warnings.push(
20684
+ "--include-logs was requested, but the generated directory is not a git repository; reports/log.md was not written."
20685
+ );
20686
+ manifest.totals.warningCount = manifest.warnings.length;
20687
+ }
20494
20688
  if (logReport !== null) manifest.artifacts.log = artifactRecord(logReport.text);
20495
20689
  const tokenTree = artifacts.tokenTree ? generateTokenTree(manifest) : null;
20496
20690
  if (tokenTree !== null) manifest.artifacts.tokenTree = artifactRecord(tokenTree.text);
@@ -20540,17 +20734,19 @@ function generateSnapshot(configInput, options) {
20540
20734
  if (wantsXml) manifest.warnings.push(`full-codebase.xml skipped: ${reason}`);
20541
20735
  }
20542
20736
  const markdown = definitelyTooLarge || !wantsMarkdown ? null : generateMonolithMarkdown(manifest, fullFiles);
20543
- const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
20544
- if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
20545
- monolithMarkdown = markdown;
20546
- manifest.artifacts.fullMarkdown = {
20547
- byteSize: markdownBytes,
20548
- sha256: sha256Hex2(markdown)
20549
- };
20550
- } else if (!definitelyTooLarge) {
20551
- manifest.warnings.push(
20552
- `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20553
- );
20737
+ if (markdown !== null) {
20738
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
20739
+ if (config.maxMonolithBytes === null || markdownBytes <= config.maxMonolithBytes) {
20740
+ monolithMarkdown = markdown;
20741
+ manifest.artifacts.fullMarkdown = {
20742
+ byteSize: markdownBytes,
20743
+ sha256: sha256Hex2(markdown)
20744
+ };
20745
+ } else {
20746
+ manifest.warnings.push(
20747
+ `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20748
+ );
20749
+ }
20554
20750
  }
20555
20751
  if (wantsXml && !definitelyTooLarge) {
20556
20752
  const xml = generateMonolithXml(manifest, fullFiles);
@@ -20566,14 +20762,16 @@ function generateSnapshot(configInput, options) {
20566
20762
  }
20567
20763
  manifest.totals.warningCount = manifest.warnings.length;
20568
20764
  const json = definitelyTooLarge || !wantsJson ? null : generateMonolithJson(manifest, fullFiles);
20569
- const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
20570
- if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
20571
- monolithJson = json;
20572
- manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20573
- } else if (!definitelyTooLarge) {
20574
- manifest.warnings.push(
20575
- `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20576
- );
20765
+ if (json !== null) {
20766
+ const jsonBytes = Buffer.byteLength(json, "utf8");
20767
+ if (config.maxMonolithBytes === null || jsonBytes <= config.maxMonolithBytes) {
20768
+ monolithJson = json;
20769
+ manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20770
+ } else {
20771
+ manifest.warnings.push(
20772
+ `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20773
+ );
20774
+ }
20577
20775
  }
20578
20776
  manifest.totals.warningCount = manifest.warnings.length;
20579
20777
  }
@@ -20919,6 +21117,7 @@ async function startHttpTransport(options) {
20919
21117
  noteRequest(request);
20920
21118
  const send = (status, body, extra = {}) => {
20921
21119
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
21120
+ if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
20922
21121
  response.writeHead(status, {
20923
21122
  "content-type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json",
20924
21123
  "content-length": Buffer.byteLength(text2, "utf8"),
@@ -20930,7 +21129,6 @@ async function startHttpTransport(options) {
20930
21129
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
20931
21130
  const allowed = allowedOrigin(origin);
20932
21131
  if (origin !== void 0 && allowed === null) {
20933
- metrics.refused += 1;
20934
21132
  send(403, { error: "origin not allowed" });
20935
21133
  return;
20936
21134
  }
@@ -20968,7 +21166,7 @@ async function startHttpTransport(options) {
20968
21166
  "# HELP snapshot_requests_total HTTP requests received.",
20969
21167
  "# TYPE snapshot_requests_total counter",
20970
21168
  "snapshot_requests_total " + metrics.requests,
20971
- "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
21169
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch (4xx other than 429).",
20972
21170
  "# TYPE snapshot_requests_refused_total counter",
20973
21171
  "snapshot_requests_refused_total " + metrics.refused,
20974
21172
  "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
@@ -21170,6 +21368,7 @@ var COMMAND_ALIASES = /* @__PURE__ */ new Map([
21170
21368
  ["describe", "describe"],
21171
21369
  ["skill", "skill"],
21172
21370
  ["mcp", "mcp"],
21371
+ ["update", "update"],
21173
21372
  ["serve", "serve"]
21174
21373
  ]);
21175
21374
  var COMMAND_ARITY = {
@@ -21184,6 +21383,7 @@ var COMMAND_ARITY = {
21184
21383
  describe: 0,
21185
21384
  skill: 0,
21186
21385
  mcp: 0,
21386
+ update: 0,
21187
21387
  serve: 0
21188
21388
  };
21189
21389
  var CLI_OPTIONS = {
@@ -21279,6 +21479,7 @@ Commands:
21279
21479
  explain <path> Show how one path would be treated: layer, kind, part, skips
21280
21480
  diff <a> <b> Compare two snapshots (directories or manifest.json files)
21281
21481
  describe Print the machine-readable contract (--format json for agents)
21482
+ update Ask the registry whether a newer release exists (exit 1 if one does)
21282
21483
  skill Print the bundled agent skill; --install writes it into the repo
21283
21484
  mcp Serve this repository to an MCP client (stdio, or --http for the web)
21284
21485
  serve Open a browser UI: generate, preview, download a zip; MCP at /mcp
@@ -22121,6 +22322,37 @@ async function firstRun(invocation) {
22121
22322
  );
22122
22323
  return await runSetupCommand(invocation, { interactive: plan.interactive });
22123
22324
  }
22325
+ async function runUpdateCommand(invocation) {
22326
+ const current = GENERATOR_VERSION;
22327
+ const latestUrl = process.env.CODEBASE_SNAPSHOT_REGISTRY_URL;
22328
+ const latest = await resolveLatest({
22329
+ current,
22330
+ cacheFile: cacheFilePath(),
22331
+ force: true,
22332
+ ...latestUrl === void 0 || latestUrl === "" ? {} : { latestUrl }
22333
+ });
22334
+ if (latest === null) {
22335
+ emit(invocation.format, { current, latest: null, updateAvailable: false }, () => {
22336
+ info(
22337
+ "Could not reach the npm registry, so the installed version could not be compared. Nothing was changed; try again when the network is available."
22338
+ );
22339
+ });
22340
+ return 2;
22341
+ }
22342
+ const kind = installKind();
22343
+ const updateAvailable = isNewer(latest, current);
22344
+ const command = updateCommand(kind);
22345
+ emit(invocation.format, { current, latest, updateAvailable, command }, () => {
22346
+ if (updateAvailable) {
22347
+ info(formatUpdateNotice({ current, latest }, kind));
22348
+ } else {
22349
+ info(
22350
+ `You are on codebase-snapshot ${current}, and the registry publishes ${latest}. No update is available.`
22351
+ );
22352
+ }
22353
+ });
22354
+ return updateAvailable ? 1 : 0;
22355
+ }
22124
22356
  function runSkillCommand(invocation) {
22125
22357
  if (!invocation.install) {
22126
22358
  if (invocation.format === "json") {
@@ -22262,6 +22494,9 @@ ${USAGE}
22262
22494
  if (invocation.command === "skill") {
22263
22495
  return runSkillCommand(invocation);
22264
22496
  }
22497
+ if (invocation.command === "update") {
22498
+ return runUpdateCommand(invocation);
22499
+ }
22265
22500
  if (invocation.command === "serve") {
22266
22501
  const server = await startWebServer({
22267
22502
  cwd: path27.resolve(invocation.cwd),
@@ -22679,8 +22914,9 @@ ${USAGE}
22679
22914
  }
22680
22915
  const started = performance.now();
22681
22916
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
22917
+ const headerGit = getGitInfo(resolved.cwd, resolved.branch);
22682
22918
  info(
22683
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
22919
+ ` Branch: ${resolved.branch}${headerGit.branchFromGit ? "" : " (fallback)"} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
22684
22920
  );
22685
22921
  try {
22686
22922
  let deltaBase;