codebase-snapshot 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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";
@@ -1873,7 +1873,11 @@ function scanAndRedactSecrets(content, rules, filePath) {
1873
1873
  let finalText = segments.join("");
1874
1874
  finalText = redactStructuredValues(finalText, filePath, recordFinding);
1875
1875
  finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
1876
- const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
1876
+ const originalLines = content.split(/\r\n|\r|\n/);
1877
+ const findings = [...findingsByLine.entries()].filter(([line]) => {
1878
+ const original = originalLines[line - 1] ?? "";
1879
+ return !original.includes(REDACTION_MARKER) && !original.includes(PEM_REDACTION_MARKER);
1880
+ }).sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
1877
1881
  rules: [...rulesForLine],
1878
1882
  line,
1879
1883
  path: filePath
@@ -1941,8 +1945,8 @@ function redactStructuredValues(text2, filePath, recordFinding) {
1941
1945
  if (body.trim() !== "") {
1942
1946
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
1943
1947
  if (indent <= baseIndent) break;
1948
+ if (!isMarkerLine(body)) masked2 = true;
1944
1949
  segments[cursor2] = maskLineContent(body);
1945
- masked2 = true;
1946
1950
  }
1947
1951
  cursor2 += 2;
1948
1952
  }
@@ -1962,8 +1966,8 @@ function redactStructuredValues(text2, filePath, recordFinding) {
1962
1966
  if (body.trim() !== "") {
1963
1967
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
1964
1968
  if (indent < valueIndent) break;
1969
+ if (!isMarkerLine(body)) masked = true;
1965
1970
  segments[cursor] = maskValueLine(body);
1966
- masked = true;
1967
1971
  }
1968
1972
  cursor += 2;
1969
1973
  }
@@ -2073,10 +2077,14 @@ var PLACEHOLDER_PATTERNS = [
2073
2077
  /^your[-_ ].*$/i,
2074
2078
  /^(?:example|sample)(?:[-_ ].*)?$/i
2075
2079
  ];
2080
+ function isMarkerLine(value) {
2081
+ return value.includes(REDACTION_MARKER) || value.includes(PEM_REDACTION_MARKER);
2082
+ }
2076
2083
  function isPlaceholderValue(value) {
2077
2084
  const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
2078
2085
  if (trimmed.length === 0) return false;
2079
2086
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2087
+ if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
2080
2088
  return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2081
2089
  }
2082
2090
  function quotesAreBalanced(text2) {
@@ -2191,7 +2199,7 @@ function applySpansKeepingQuotes(line, spans) {
2191
2199
 
2192
2200
  // src/version.ts
2193
2201
  var GENERATOR_NAME = "codebase-snapshot";
2194
- var GENERATOR_VERSION = "0.17.0";
2202
+ var GENERATOR_VERSION = "0.19.0";
2195
2203
  var SCHEMA_VERSION = "3.0.0";
2196
2204
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2197
2205
  function isOurGeneratorName(name) {
@@ -2242,6 +2250,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2242
2250
  let branch = fallbackBranch;
2243
2251
  let commit = "unknown";
2244
2252
  let isDirty = false;
2253
+ let branchFromGit = false;
2245
2254
  const records = output.split("\0").flatMap((record) => record.split("\n"));
2246
2255
  for (const record of records) {
2247
2256
  if (record.length === 0) continue;
@@ -2257,13 +2266,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2257
2266
  const head = record.match(/^# branch\.head (.+)$/);
2258
2267
  if (head) {
2259
2268
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
2269
+ branchFromGit = head[1] !== "(detached)";
2260
2270
  }
2261
2271
  }
2262
- return { branch, commit, isDirty };
2272
+ return { branch, commit, isDirty, branchFromGit };
2263
2273
  } catch (err) {
2264
2274
  const code = err.code;
2265
2275
  const isDirty = code === "ENOBUFS";
2266
- return { branch: fallbackBranch, commit: "unknown", isDirty };
2276
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
2267
2277
  }
2268
2278
  }
2269
2279
  var DEFAULT_IGNORED_DIRS = [
@@ -3114,9 +3124,9 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3114
3124
  }
3115
3125
 
3116
3126
  // src/validator/validate.ts
3117
- import * as crypto from "crypto";
3118
- import * as fs7 from "fs";
3119
- import * as path6 from "path";
3127
+ import * as crypto2 from "crypto";
3128
+ import * as fs8 from "fs";
3129
+ import * as path7 from "path";
3120
3130
 
3121
3131
  // src/config.ts
3122
3132
  import * as fs3 from "fs";
@@ -4984,7 +4994,7 @@ function summarizeTypeScriptSource(relativePath, content) {
4984
4994
  }
4985
4995
  const callee = node.expression;
4986
4996
  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());
4997
+ summary.routeHandlers.push(callee.name.text.toUpperCase() + " " + firstArgument.text);
4988
4998
  }
4989
4999
  }
4990
5000
  if (ts2.isExportDeclaration(node)) {
@@ -6229,39 +6239,107 @@ function importsOfFile(relativePath, absolutePath) {
6229
6239
  return importsOfText(relativePath, decoded.text);
6230
6240
  }
6231
6241
 
6242
+ // src/signing.ts
6243
+ import * as crypto from "crypto";
6244
+ import * as fs7 from "fs";
6245
+ import * as path6 from "path";
6246
+ var SIGNATURE_FILE = "signature.json";
6247
+ function loadSigningKey(environment = process.env) {
6248
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
6249
+ if (pem === void 0 || pem.trim() === "") return null;
6250
+ return crypto.createPrivateKey({ key: pem, format: "pem" });
6251
+ }
6252
+ function signManifest(manifestPath, options = {}) {
6253
+ const bytes = fs7.readFileSync(manifestPath);
6254
+ const manifest = JSON.parse(bytes.toString("utf8"));
6255
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
6256
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
6257
+ }
6258
+ const configured = options.key ?? null;
6259
+ const key = configured ?? crypto.generateKeyPairSync("ed25519").privateKey;
6260
+ const publicKey = crypto.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
6261
+ const signature = crypto.sign(null, bytes, key).toString("base64");
6262
+ return {
6263
+ algorithm: "ed25519",
6264
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6265
+ fingerprint: manifest.fingerprint,
6266
+ manifestSha256: crypto.createHash("sha256").update(bytes).digest("hex"),
6267
+ publicKey,
6268
+ signature,
6269
+ keyOrigin: configured === null ? "generated" : "configured"
6270
+ };
6271
+ }
6272
+ function writeSignature(snapshotDir, record) {
6273
+ const target = path6.join(snapshotDir, SIGNATURE_FILE);
6274
+ fs7.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
6275
+ return target;
6276
+ }
6277
+ function verifySnapshotSignature(snapshotDir) {
6278
+ const signaturePath = path6.join(snapshotDir, SIGNATURE_FILE);
6279
+ const manifestPath = path6.join(snapshotDir, "manifest.json");
6280
+ if (!fs7.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
6281
+ let record;
6282
+ try {
6283
+ record = JSON.parse(fs7.readFileSync(signaturePath, "utf8"));
6284
+ } catch (error) {
6285
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
6286
+ }
6287
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
6288
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
6289
+ }
6290
+ let bytes;
6291
+ try {
6292
+ bytes = fs7.readFileSync(manifestPath);
6293
+ } catch {
6294
+ return { ok: false, reason: "the signed manifest is missing" };
6295
+ }
6296
+ const sha2562 = crypto.createHash("sha256").update(bytes).digest("hex");
6297
+ if (sha2562 !== record.manifestSha256) {
6298
+ return { ok: false, reason: "manifest.json changed after it was signed" };
6299
+ }
6300
+ let verified = false;
6301
+ try {
6302
+ const key = crypto.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
6303
+ verified = crypto.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
6304
+ } catch (error) {
6305
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
6306
+ }
6307
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
6308
+ }
6309
+
6232
6310
  // src/validator/validate.ts
6233
6311
  function maskedPath(value, secretRules) {
6234
6312
  return findSecretInPath(value, secretRules)?.masked ?? value;
6235
6313
  }
6236
6314
  function confineToDirectory(directory, filename) {
6237
6315
  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);
6316
+ if (path7.isAbsolute(filename)) return null;
6317
+ const base = path7.resolve(directory);
6318
+ const resolved = path7.resolve(base, filename);
6241
6319
  const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
6242
- const prefix = caseInsensitive ? `${base}${path6.sep}`.toLowerCase() : `${base}${path6.sep}`;
6320
+ const prefix = caseInsensitive ? `${base}${path7.sep}`.toLowerCase() : `${base}${path7.sep}`;
6243
6321
  const candidate = caseInsensitive ? resolved.toLowerCase() : resolved;
6244
6322
  return candidate.startsWith(prefix) ? resolved : null;
6245
6323
  }
6246
6324
  function findStagingDirectory(config) {
6247
- const tmpDir = path6.resolve(config.cwd, config.tmpDir);
6325
+ const tmpDir = path7.resolve(config.cwd, config.tmpDir);
6248
6326
  let entries;
6249
6327
  try {
6250
- entries = fs7.readdirSync(tmpDir);
6328
+ entries = fs8.readdirSync(tmpDir);
6251
6329
  } catch {
6252
6330
  return null;
6253
6331
  }
6254
6332
  const runs = entries.filter((name) => name.startsWith("run-")).sort();
6255
6333
  const newest = runs[runs.length - 1];
6256
- return newest ? path6.join(tmpDir, newest) : null;
6334
+ return newest ? path7.join(tmpDir, newest) : null;
6257
6335
  }
6258
6336
  function describeMissingManifest(config, manifestPath) {
6259
- const outDir = path6.resolve(config.cwd, config.outDir);
6260
- const markerPath = path6.join(outDir, ".codebase-snapshot");
6337
+ const outDir = path7.resolve(config.cwd, config.outDir);
6338
+ const markerPath = path7.join(outDir, ".codebase-snapshot");
6261
6339
  let marker2 = null;
6262
6340
  try {
6263
- if (fs7.existsSync(markerPath)) {
6264
- const parsed = JSON.parse(fs7.readFileSync(markerPath, "utf8"));
6341
+ if (fs8.existsSync(markerPath)) {
6342
+ const parsed = JSON.parse(fs8.readFileSync(markerPath, "utf8"));
6265
6343
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
6266
6344
  marker2 = parsed;
6267
6345
  }
@@ -6293,16 +6371,16 @@ function emptyDrift() {
6293
6371
  };
6294
6372
  }
6295
6373
  function sha256Hex(buffer) {
6296
- return crypto.createHash("sha256").update(buffer).digest("hex");
6374
+ return crypto2.createHash("sha256").update(buffer).digest("hex");
6297
6375
  }
6298
6376
  function wouldNowBeIncluded(cwd, relativePath) {
6299
- const absolutePath = path6.join(cwd, relativePath);
6377
+ const absolutePath = path7.join(cwd, relativePath);
6300
6378
  try {
6301
- const stats = fs7.statSync(absolutePath);
6379
+ const stats = fs8.statSync(absolutePath);
6302
6380
  if (!stats.isFile()) return false;
6303
6381
  if (isBinaryExtension(absolutePath)) return false;
6304
6382
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
6305
- return !decodeText(fs7.readFileSync(absolutePath)).binary;
6383
+ return !decodeText(fs8.readFileSync(absolutePath)).binary;
6306
6384
  } catch {
6307
6385
  return false;
6308
6386
  }
@@ -6314,7 +6392,7 @@ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
6314
6392
  ]);
6315
6393
  function isConfinedRelative(value) {
6316
6394
  if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
6317
- if (path6.isAbsolute(value)) return false;
6395
+ if (path7.isAbsolute(value)) return false;
6318
6396
  return !value.split("/").includes("..");
6319
6397
  }
6320
6398
  function describeManifestShapeProblem(value) {
@@ -6508,7 +6586,7 @@ function describeManifestShapeProblem(value) {
6508
6586
  if (typeof filename !== "string" || filename.trim() === "") {
6509
6587
  return 'a "parts" entry has no "filename"';
6510
6588
  }
6511
- if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path6.isAbsolute(filename)) {
6589
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path7.isAbsolute(filename)) {
6512
6590
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
6513
6591
  }
6514
6592
  if (currentSchema) {
@@ -6534,8 +6612,8 @@ function describeManifestShapeProblem(value) {
6534
6612
  function validateSnapshot(configInput) {
6535
6613
  assertUsableConfigInput(configInput);
6536
6614
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
6537
- const manifestPath = path6.resolve(config.cwd, config.outDir, "manifest.json");
6538
- if (!fs7.existsSync(manifestPath)) {
6615
+ const manifestPath = path7.resolve(config.cwd, config.outDir, "manifest.json");
6616
+ if (!fs8.existsSync(manifestPath)) {
6539
6617
  return {
6540
6618
  valid: false,
6541
6619
  manifestPresent: false,
@@ -6546,7 +6624,7 @@ function validateSnapshot(configInput) {
6546
6624
  }
6547
6625
  let manifest;
6548
6626
  try {
6549
- manifest = JSON.parse(fs7.readFileSync(manifestPath, "utf8"));
6627
+ manifest = JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
6550
6628
  } catch (err) {
6551
6629
  return {
6552
6630
  valid: false,
@@ -6568,7 +6646,7 @@ function validateSnapshot(configInput) {
6568
6646
  }
6569
6647
  const drift = emptyDrift();
6570
6648
  const warnings = [];
6571
- const snapshotDir = path6.resolve(config.cwd, config.outDir);
6649
+ const snapshotDir = path7.resolve(config.cwd, config.outDir);
6572
6650
  const unreadableSkips = manifest.skipped.filter(
6573
6651
  (entry) => entry.reason === "missing" || entry.reason === "read-error"
6574
6652
  );
@@ -6671,7 +6749,7 @@ function validateSnapshot(configInput) {
6671
6749
  );
6672
6750
  return importsChangedFile(
6673
6751
  diskFile,
6674
- importsOfFile(diskFile, path6.join(config.cwd, diskFile)),
6752
+ importsOfFile(diskFile, path7.join(config.cwd, diskFile)),
6675
6753
  unchangedScope,
6676
6754
  dependentResolver
6677
6755
  );
@@ -6689,7 +6767,7 @@ function validateSnapshot(configInput) {
6689
6767
  // own output directory as a set of files missing from the snapshot, so a correct
6690
6768
  // snapshot was reported as drifting.
6691
6769
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6692
- (directory) => path6.relative(config.cwd, path6.resolve(config.cwd, directory)).replace(/\\/g, "/")
6770
+ (directory) => path7.relative(config.cwd, path7.resolve(config.cwd, directory)).replace(/\\/g, "/")
6693
6771
  ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
6694
6772
  });
6695
6773
  for (const diskFile of collection.files) {
@@ -6716,7 +6794,7 @@ function validateSnapshot(configInput) {
6716
6794
  }
6717
6795
  let diskHash;
6718
6796
  try {
6719
- diskHash = sha256Hex(fs7.readFileSync(path6.join(config.cwd, diskFile)));
6797
+ diskHash = sha256Hex(fs8.readFileSync(path7.join(config.cwd, diskFile)));
6720
6798
  } catch (err) {
6721
6799
  if (err.code === "ENOENT") {
6722
6800
  drift.missingOnDisk.push(diskFile);
@@ -6740,7 +6818,7 @@ function validateSnapshot(configInput) {
6740
6818
  }
6741
6819
  let statFailure = null;
6742
6820
  try {
6743
- fs7.statSync(confined);
6821
+ fs8.statSync(confined);
6744
6822
  } catch (err) {
6745
6823
  statFailure = err;
6746
6824
  }
@@ -6760,7 +6838,7 @@ function validateSnapshot(configInput) {
6760
6838
  ...Object.values(config.budgets.byLayer)
6761
6839
  );
6762
6840
  const partNames = /* @__PURE__ */ new Set();
6763
- const partsDir = path6.join(snapshotDir, "parts");
6841
+ const partsDir = path7.join(snapshotDir, "parts");
6764
6842
  for (const part of manifest.parts) {
6765
6843
  if (!part || typeof part.filename !== "string") continue;
6766
6844
  partNames.add(part.filename);
@@ -6775,7 +6853,7 @@ function validateSnapshot(configInput) {
6775
6853
  }
6776
6854
  let buffer;
6777
6855
  try {
6778
- buffer = fs7.readFileSync(partPath);
6856
+ buffer = fs8.readFileSync(partPath);
6779
6857
  } catch {
6780
6858
  drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
6781
6859
  continue;
@@ -7152,11 +7230,11 @@ function validateSnapshot(configInput) {
7152
7230
  ];
7153
7231
  for (const [key, artifact] of declaredArtifacts) {
7154
7232
  if (!artifact) continue;
7155
- const artifactPath = path6.join(snapshotDir, ...key.split("/"));
7233
+ const artifactPath = path7.join(snapshotDir, ...key.split("/"));
7156
7234
  let buffer;
7157
7235
  try {
7158
- if (!fs7.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7159
- buffer = fs7.readFileSync(artifactPath);
7236
+ if (!fs8.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7237
+ buffer = fs8.readFileSync(artifactPath);
7160
7238
  } catch {
7161
7239
  drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
7162
7240
  continue;
@@ -7169,9 +7247,9 @@ function validateSnapshot(configInput) {
7169
7247
  for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
7170
7248
  const target = match[1].split("#")[0];
7171
7249
  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)) {
7250
+ const resolved = path7.resolve(snapshotDir, "reports", target);
7251
+ const relative15 = path7.relative(snapshotDir, resolved);
7252
+ if (relative15.startsWith("..") || path7.isAbsolute(relative15) || !fs8.existsSync(resolved)) {
7175
7253
  drift.partIssues.push({
7176
7254
  part: key,
7177
7255
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7184,7 +7262,7 @@ function validateSnapshot(configInput) {
7184
7262
  if (sarifArtifact) {
7185
7263
  const sarifKey = "reports/audit.sarif";
7186
7264
  try {
7187
- const buffer = fs7.readFileSync(path6.join(snapshotDir, "reports", "audit.sarif"));
7265
+ const buffer = fs8.readFileSync(path7.join(snapshotDir, "reports", "audit.sarif"));
7188
7266
  if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
7189
7267
  drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7190
7268
  }
@@ -7230,6 +7308,11 @@ function validateSnapshot(configInput) {
7230
7308
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
7231
7309
  );
7232
7310
  }
7311
+ const signaturePath = path7.join(path7.dirname(manifestPath), "signature.json");
7312
+ if (fs8.existsSync(signaturePath)) {
7313
+ const outcome = verifySnapshotSignature(path7.dirname(manifestPath));
7314
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
7315
+ }
7233
7316
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
7234
7317
  warnings.push(
7235
7318
  "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 +7556,14 @@ function compareManifests(before, after, secretRules) {
7473
7556
  function loadManifest(target) {
7474
7557
  let isDirectory;
7475
7558
  try {
7476
- isDirectory = fs8.statSync(target).isDirectory();
7559
+ isDirectory = fs9.statSync(target).isDirectory();
7477
7560
  } catch {
7478
7561
  throw new Error(`No snapshot found at ${target}: the path does not exist.`);
7479
7562
  }
7480
- const manifestPath = isDirectory ? path7.join(target, "manifest.json") : target;
7563
+ const manifestPath = isDirectory ? path8.join(target, "manifest.json") : target;
7481
7564
  let raw;
7482
7565
  try {
7483
- raw = fs8.readFileSync(manifestPath, "utf8");
7566
+ raw = fs9.readFileSync(manifestPath, "utf8");
7484
7567
  } catch {
7485
7568
  throw new Error(`Could not read a manifest at ${manifestPath}.`);
7486
7569
  }
@@ -7536,8 +7619,8 @@ function renderDiffText(diff) {
7536
7619
  }
7537
7620
 
7538
7621
  // src/explain.ts
7539
- import * as fs9 from "fs";
7540
- import * as path9 from "path";
7622
+ import * as fs10 from "fs";
7623
+ import * as path10 from "path";
7541
7624
 
7542
7625
  // src/ast/skeleton.ts
7543
7626
  import ts3 from "typescript";
@@ -7717,7 +7800,7 @@ function truncatePreview(content, headLines, tailLines) {
7717
7800
  }
7718
7801
 
7719
7802
  // src/scanner/language.ts
7720
- import * as path8 from "path";
7803
+ import * as path9 from "path";
7721
7804
  var LANGUAGE_BY_EXTENSION = {
7722
7805
  ".ts": "typescript",
7723
7806
  ".mts": "typescript",
@@ -7775,10 +7858,10 @@ var LANGUAGE_BY_BASENAME = {
7775
7858
  };
7776
7859
  function detectLanguage(filePath) {
7777
7860
  const normalized = filePath.replace(/\\/g, "/");
7778
- const base = path8.posix.basename(normalized);
7861
+ const base = path9.posix.basename(normalized);
7779
7862
  if (LANGUAGE_BY_BASENAME[base]) return LANGUAGE_BY_BASENAME[base];
7780
7863
  if (base === ".env" || base.startsWith(".env.")) return "dotenv";
7781
- const ext = path8.posix.extname(base).toLowerCase();
7864
+ const ext = path9.posix.extname(base).toLowerCase();
7782
7865
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
7783
7866
  }
7784
7867
 
@@ -7820,13 +7903,13 @@ function describeMatcher(matcher) {
7820
7903
  return String(matcher);
7821
7904
  }
7822
7905
  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)) {
7906
+ const resolvedCwd = path10.resolve(cwd);
7907
+ const absolute = path10.resolve(resolvedCwd, target);
7908
+ const relative15 = path10.relative(resolvedCwd, absolute);
7909
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative15)) {
7827
7910
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7828
7911
  }
7829
- return { relative: relative15.split(path9.sep).join("/"), outsideRoot: false };
7912
+ return { relative: relative15.split(path10.sep).join("/"), outsideRoot: false };
7830
7913
  }
7831
7914
  function findRuleMatch(rules, relativePath) {
7832
7915
  return rules.find(
@@ -7845,9 +7928,9 @@ function findRecordedAncestor(skipped, relative15, maskedPath2) {
7845
7928
  return nearest;
7846
7929
  }
7847
7930
  function readManifest2(config) {
7848
- const manifestPath = path9.resolve(config.cwd, config.outDir, "manifest.json");
7931
+ const manifestPath = path10.resolve(config.cwd, config.outDir, "manifest.json");
7849
7932
  try {
7850
- return JSON.parse(fs9.readFileSync(manifestPath, "utf8"));
7933
+ return JSON.parse(fs10.readFileSync(manifestPath, "utf8"));
7851
7934
  } catch {
7852
7935
  return null;
7853
7936
  }
@@ -7865,10 +7948,10 @@ function explainPath(config, target) {
7865
7948
  detail: "path resolves outside the configured repository root and was not inspected"
7866
7949
  };
7867
7950
  }
7868
- const absolute = path9.join(config.cwd, relative15);
7951
+ const absolute = path10.join(config.cwd, relative15);
7869
7952
  const result = {
7870
7953
  path: maskedPath2,
7871
- exists: fs9.existsSync(absolute),
7954
+ exists: fs10.existsSync(absolute),
7872
7955
  included: false
7873
7956
  };
7874
7957
  const collection = collectFiles(config.cwd, {
@@ -7882,7 +7965,7 @@ function explainPath(config, target) {
7882
7965
  // Same exclusion `generate` applies, so `explain` never says "not-discovered" about a file
7883
7966
  // that is only missing because the walker dropped the tool's own output directory.
7884
7967
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7885
- (directory) => path9.relative(config.cwd, path9.resolve(config.cwd, directory)).replace(/\\/g, "/")
7968
+ (directory) => path10.relative(config.cwd, path10.resolve(config.cwd, directory)).replace(/\\/g, "/")
7886
7969
  ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
7887
7970
  });
7888
7971
  if (!collection.files.includes(relative15)) {
@@ -7947,7 +8030,7 @@ function explainPath(config, target) {
7947
8030
  }
7948
8031
  let sizeOnDisk = null;
7949
8032
  try {
7950
- sizeOnDisk = fs9.statSync(absolute).size;
8033
+ sizeOnDisk = fs10.statSync(absolute).size;
7951
8034
  } catch {
7952
8035
  sizeOnDisk = null;
7953
8036
  }
@@ -7957,10 +8040,10 @@ function explainPath(config, target) {
7957
8040
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
7958
8041
  return result;
7959
8042
  }
7960
- if (fs9.existsSync(absolute) && fs9.statSync(absolute).isFile()) {
8043
+ if (fs10.existsSync(absolute) && fs10.statSync(absolute).isFile()) {
7961
8044
  let buffer;
7962
8045
  try {
7963
- buffer = fs9.readFileSync(absolute);
8046
+ buffer = fs10.readFileSync(absolute);
7964
8047
  } catch (err) {
7965
8048
  result.included = false;
7966
8049
  result.reason = "read-error";
@@ -8051,12 +8134,12 @@ function renderExplainText(result) {
8051
8134
  }
8052
8135
 
8053
8136
  // src/wizard/init.ts
8054
- import * as fs11 from "fs";
8055
- import * as path11 from "path";
8137
+ import * as fs12 from "fs";
8138
+ import * as path12 from "path";
8056
8139
 
8057
8140
  // src/gitignore.ts
8058
- import * as fs10 from "fs";
8059
- import * as path10 from "path";
8141
+ import * as fs11 from "fs";
8142
+ import * as path11 from "path";
8060
8143
  function decodeGitignore(buffer) {
8061
8144
  const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
8062
8145
  if (startsWith(239, 187, 191)) {
@@ -8105,15 +8188,15 @@ function canonicalIgnorePattern(line) {
8105
8188
  function appendGitignoreEntries(cwd, entries) {
8106
8189
  const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
8107
8190
  if (wanted.length === 0) return { added: [], note: null };
8108
- const ignorePath = path10.join(cwd, ".gitignore");
8191
+ const ignorePath = path11.join(cwd, ".gitignore");
8109
8192
  const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
8110
8193
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
8111
8194
  try {
8112
- if (fs10.existsSync(ignorePath)) {
8113
- if (fs10.statSync(ignorePath).isDirectory()) {
8195
+ if (fs11.existsSync(ignorePath)) {
8196
+ if (fs11.statSync(ignorePath).isDirectory()) {
8114
8197
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
8115
8198
  }
8116
- const read = decodeGitignore(fs10.readFileSync(ignorePath));
8199
+ const read = decodeGitignore(fs11.readFileSync(ignorePath));
8117
8200
  if (read === null) {
8118
8201
  return {
8119
8202
  added: [],
@@ -8135,7 +8218,7 @@ function appendGitignoreEntries(cwd, entries) {
8135
8218
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
8136
8219
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
8137
8220
  try {
8138
- fs10.writeFileSync(
8221
+ fs11.writeFileSync(
8139
8222
  ignorePath,
8140
8223
  encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
8141
8224
  );
@@ -8145,7 +8228,7 @@ function appendGitignoreEntries(cwd, entries) {
8145
8228
  return { added, note: null };
8146
8229
  }
8147
8230
  function gitignorePath(cwd, filePath) {
8148
- return path10.relative(cwd, filePath).split(path10.sep).join("/");
8231
+ return path11.relative(cwd, filePath).split(path11.sep).join("/");
8149
8232
  }
8150
8233
 
8151
8234
  // src/wizard/brief-template.ts
@@ -8756,7 +8839,7 @@ function parsePackageJson(raw) {
8756
8839
  }
8757
8840
  function readPackageJson(cwd) {
8758
8841
  try {
8759
- return parsePackageJson(fs11.readFileSync(path11.join(cwd, "package.json"), "utf8"));
8842
+ return parsePackageJson(fs12.readFileSync(path12.join(cwd, "package.json"), "utf8"));
8760
8843
  } catch {
8761
8844
  return null;
8762
8845
  }
@@ -8793,7 +8876,7 @@ function artifactAnswers(options) {
8793
8876
  }
8794
8877
  function topLevelDirs(cwd) {
8795
8878
  try {
8796
- return fs11.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
8879
+ return fs12.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
8797
8880
  } catch {
8798
8881
  return [];
8799
8882
  }
@@ -8808,7 +8891,7 @@ function writeFileOrExplain(target, content) {
8808
8891
  try {
8809
8892
  let stats = null;
8810
8893
  try {
8811
- stats = fs11.lstatSync(target);
8894
+ stats = fs12.lstatSync(target);
8812
8895
  } catch {
8813
8896
  stats = null;
8814
8897
  }
@@ -8823,12 +8906,12 @@ function writeFileOrExplain(target, content) {
8823
8906
  );
8824
8907
  }
8825
8908
  const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
8826
- fs11.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
8909
+ fs12.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
8827
8910
  try {
8828
- fs11.renameSync(temporary, target);
8911
+ fs12.renameSync(temporary, target);
8829
8912
  } catch (err) {
8830
8913
  try {
8831
- fs11.unlinkSync(temporary);
8914
+ fs12.unlinkSync(temporary);
8832
8915
  } catch {
8833
8916
  }
8834
8917
  throw err;
@@ -8876,19 +8959,19 @@ function serializePackageJson(raw, value) {
8876
8959
  return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
8877
8960
  }
8878
8961
  function updatePackageJson(cwd, notes) {
8879
- const packagePath = path11.join(cwd, "package.json");
8962
+ const packagePath = path12.join(cwd, "package.json");
8880
8963
  const unchanged = {
8881
8964
  scripts: [],
8882
8965
  dependency: { name: GENERATOR_NAME, range: null, added: false }
8883
8966
  };
8884
- if (!fs11.existsSync(packagePath)) {
8967
+ if (!fs12.existsSync(packagePath)) {
8885
8968
  notes.push("No package.json found, so npm scripts and the devDependency were not added.");
8886
8969
  return unchanged;
8887
8970
  }
8888
8971
  let raw;
8889
8972
  let parsed;
8890
8973
  try {
8891
- raw = fs11.readFileSync(packagePath, "utf8");
8974
+ raw = fs12.readFileSync(packagePath, "utf8");
8892
8975
  parsed = parsePackageJson(raw);
8893
8976
  } catch {
8894
8977
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
@@ -8963,8 +9046,8 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
8963
9046
  const entries = [];
8964
9047
  for (const directory of [outDir, tmpDir]) {
8965
9048
  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)) {
9049
+ const relative15 = path12.relative(cwd, path12.resolve(cwd, directory)).replace(/\\/g, "/");
9050
+ if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path12.isAbsolute(relative15)) {
8968
9051
  continue;
8969
9052
  }
8970
9053
  entries.push(`/${relative15}/`);
@@ -9219,7 +9302,7 @@ async function runInit(options) {
9219
9302
  const configText = renderConfig(answers);
9220
9303
  const preferredName = chooseConfigFileName(options.cwd);
9221
9304
  const presentConfigs = CONFIG_CANDIDATES.filter(
9222
- (name) => fs11.existsSync(path11.join(options.cwd, name))
9305
+ (name) => fs12.existsSync(path12.join(options.cwd, name))
9223
9306
  );
9224
9307
  const present = presentConfigs[0] ?? null;
9225
9308
  if (presentConfigs.length > 1) {
@@ -9228,7 +9311,7 @@ async function runInit(options) {
9228
9311
  );
9229
9312
  }
9230
9313
  const configName = present !== null && options.force ? present : preferredName;
9231
- const configPath = path11.join(options.cwd, configName);
9314
+ const configPath = path12.join(options.cwd, configName);
9232
9315
  const reused = present !== null && options.force !== true && options.reuseConfig === true;
9233
9316
  if (reused) notes.push(`Kept the existing ${present} instead of writing a new one.`);
9234
9317
  if (options.dryRun) {
@@ -9245,7 +9328,7 @@ async function runInit(options) {
9245
9328
  dependency: { name: GENERATOR_NAME, range: `^${GENERATOR_VERSION}`, added: false },
9246
9329
  notes,
9247
9330
  outDir: answers.outDir,
9248
- briefPath: path11.join(options.cwd, BRIEF_SCAFFOLD_FILE),
9331
+ briefPath: path12.join(options.cwd, BRIEF_SCAFFOLD_FILE),
9249
9332
  briefWritten: false
9250
9333
  };
9251
9334
  }
@@ -9264,13 +9347,13 @@ async function runInit(options) {
9264
9347
  '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
9348
  );
9266
9349
  }
9267
- if (fs11.existsSync(configPath) && !options.force && !reused) {
9350
+ if (fs12.existsSync(configPath) && !options.force && !reused) {
9268
9351
  throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
9269
9352
  }
9270
9353
  if (!reused) writeFileOrExplain(configPath, configText);
9271
- const briefPath = path11.join(options.cwd, BRIEF_SCAFFOLD_FILE);
9354
+ const briefPath = path12.join(options.cwd, BRIEF_SCAFFOLD_FILE);
9272
9355
  let briefWritten = false;
9273
- if (!fs11.existsSync(briefPath)) {
9356
+ if (!fs12.existsSync(briefPath)) {
9274
9357
  writeFileOrExplain(briefPath, BRIEF_SCAFFOLD);
9275
9358
  briefWritten = true;
9276
9359
  }
@@ -9299,12 +9382,12 @@ async function runInit(options) {
9299
9382
  }
9300
9383
 
9301
9384
  // src/wizard/autopilot.ts
9302
- import * as fs12 from "fs";
9303
- import * as path12 from "path";
9385
+ import * as fs13 from "fs";
9386
+ import * as path13 from "path";
9304
9387
  function describeTarget(cwd) {
9305
- const relative15 = path12.relative(process.cwd(), cwd);
9388
+ const relative15 = path13.relative(process.cwd(), cwd);
9306
9389
  if (relative15 === "") return "this directory";
9307
- if (relative15.startsWith("..") || path12.isAbsolute(relative15)) return cwd;
9390
+ if (relative15.startsWith("..") || path13.isAbsolute(relative15)) return cwd;
9308
9391
  return relative15;
9309
9392
  }
9310
9393
  function firstRunMessage(reason, cwd) {
@@ -9328,7 +9411,7 @@ function planFirstRun(facts) {
9328
9411
  var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
9329
9412
  function isEffectivelyEmpty(cwd) {
9330
9413
  try {
9331
- return fs12.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
9414
+ return fs13.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
9332
9415
  } catch {
9333
9416
  return false;
9334
9417
  }
@@ -9336,7 +9419,7 @@ function isEffectivelyEmpty(cwd) {
9336
9419
  function hasPriorSnapshot(cwd, outDir) {
9337
9420
  let parsed;
9338
9421
  try {
9339
- parsed = JSON.parse(fs12.readFileSync(path12.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
9422
+ parsed = JSON.parse(fs13.readFileSync(path13.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
9340
9423
  } catch {
9341
9424
  return false;
9342
9425
  }
@@ -9422,7 +9505,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
9422
9505
  "# Codebase Health & Security Audit",
9423
9506
  "",
9424
9507
  `**Generated:** ${manifest.generatedAt} `,
9425
- `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
9508
+ `**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
9509
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
9427
9510
  `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
9428
9511
  `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
@@ -9569,7 +9652,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
9569
9652
  }
9570
9653
 
9571
9654
  // src/generator/sarif.ts
9572
- import * as crypto2 from "crypto";
9655
+ import * as crypto3 from "crypto";
9573
9656
  var SARIF_VERSION = "2.1.0";
9574
9657
  var SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json";
9575
9658
  var BUILTIN_RULE_IDS = new Map(
@@ -9582,7 +9665,7 @@ var BUILTIN_RULE_IDS = new Map(
9582
9665
  function ruleIdFor(name) {
9583
9666
  const builtin = BUILTIN_RULE_IDS.get(name);
9584
9667
  if (builtin !== void 0) return builtin;
9585
- const digest = crypto2.createHash("sha256").update(name).digest("hex").slice(0, 8);
9668
+ const digest = crypto3.createHash("sha256").update(name).digest("hex").slice(0, 8);
9586
9669
  return `CS${digest.toUpperCase()}`;
9587
9670
  }
9588
9671
  function generateSarifReport(manifest, findings, rules, toolVersion) {
@@ -9661,7 +9744,7 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
9661
9744
  }
9662
9745
 
9663
9746
  // src/partitioner/chunker.ts
9664
- import * as crypto3 from "crypto";
9747
+ import * as crypto4 from "crypto";
9665
9748
  var HEADER_RESERVE_BYTES = 2048 + Buffer.byteLength(UNTRUSTED_CONTENT_NOTICE, "utf8") + 8;
9666
9749
  var MIN_SECTION_BUDGET_BYTES = 512;
9667
9750
  var MIN_PART_BUDGET_BYTES = MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES;
@@ -9925,7 +10008,7 @@ function rehashPart(part, markdown) {
9925
10008
  metadata: {
9926
10009
  ...part.metadata,
9927
10010
  byteSize: Buffer.byteLength(redistributed, "utf8"),
9928
- sha256: crypto3.createHash("sha256").update(redistributed).digest("hex"),
10011
+ sha256: crypto4.createHash("sha256").update(redistributed).digest("hex"),
9929
10012
  lines: countLines(redistributed),
9930
10013
  estimatedTokens
9931
10014
  }
@@ -10006,7 +10089,7 @@ function renderGroups(groups, contentFingerprint, assemble = (group, index, tota
10006
10089
  return groups.map((group, index) => {
10007
10090
  const { filename, content, estimatedTokens } = assemble(group, index, total);
10008
10091
  const byteSize = Buffer.byteLength(content, "utf8");
10009
- const sha2562 = crypto3.createHash("sha256").update(content).digest("hex");
10092
+ const sha2562 = crypto4.createHash("sha256").update(content).digest("hex");
10010
10093
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
10011
10094
  const includedFiles = group.sections.map(({ file }) => ({
10012
10095
  relativePath: file.relativePath,
@@ -10088,7 +10171,7 @@ function renderSummary(summary, inclusionMode) {
10088
10171
  }
10089
10172
  function anchorForPath(filePath) {
10090
10173
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
10091
- const digest = crypto3.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
10174
+ const digest = crypto4.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
10092
10175
  return `${slug || "file"}-${digest}`;
10093
10176
  }
10094
10177
 
@@ -10435,13 +10518,19 @@ function planForQuestion(manifest, question, options = {}) {
10435
10518
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
10436
10519
  }
10437
10520
  const notes = [];
10521
+ if (manifest.files.length === 0) {
10522
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
10523
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
10524
+ }
10438
10525
  if (scored.length === 0) {
10439
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10440
10526
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
10441
10527
  for (const hub of hubs) {
10442
10528
  const file = byPath.get(hub.path);
10443
10529
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
10444
10530
  }
10531
+ if (scored.length > 0) {
10532
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10533
+ }
10445
10534
  }
10446
10535
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
10447
10536
  const chosen = /* @__PURE__ */ new Map();
@@ -10505,7 +10594,14 @@ function planForQuestion(manifest, question, options = {}) {
10505
10594
  }
10506
10595
  }
10507
10596
  }
10508
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
10597
+ if (chosen.size === 0) {
10598
+ if (scored.length === 0) {
10599
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
10600
+ } else {
10601
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
10602
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber2(cheapest) + " tokens.");
10603
+ }
10604
+ }
10509
10605
  notes.push(
10510
10606
  formatNumber2(chosen.size) + " file(s) chosen of " + formatNumber2(manifest.files.length) + " in the snapshot; " + formatNumber2(skipped.length) + " skipped for budget."
10511
10607
  );
@@ -11077,7 +11173,7 @@ function snapshotSection(manifest, code, partsWritten) {
11077
11173
  const out = ["## This snapshot", ""];
11078
11174
  out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
11079
11175
  out.push(
11080
- "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
11176
+ "- 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
11177
  );
11082
11178
  out.push(
11083
11179
  manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
@@ -11250,7 +11346,7 @@ function generateReadme(manifest, artifacts) {
11250
11346
  "",
11251
11347
  `- **Generated At:** \`${manifest.generatedAt}\``,
11252
11348
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
11253
- `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
11349
+ `- **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
11350
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
11255
11351
  `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
11256
11352
  `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
@@ -11396,8 +11492,8 @@ function treeTruncationWarnings(treeText) {
11396
11492
  }
11397
11493
 
11398
11494
  // src/generator/overview.ts
11399
- import * as fs13 from "fs";
11400
- import * as path13 from "path";
11495
+ import * as fs14 from "fs";
11496
+ import * as path14 from "path";
11401
11497
  var SUMMARY_LIMIT = 400;
11402
11498
  var MAX_RELEASES = 2;
11403
11499
  function readProjectOverview(cwd) {
@@ -11409,13 +11505,13 @@ function readProjectOverview(cwd) {
11409
11505
  }
11410
11506
  function readText(file) {
11411
11507
  try {
11412
- return fs13.readFileSync(file, "utf8");
11508
+ return fs14.readFileSync(file, "utf8");
11413
11509
  } catch {
11414
11510
  return null;
11415
11511
  }
11416
11512
  }
11417
11513
  function readDescription(cwd) {
11418
- const raw = readText(path13.join(cwd, "package.json"));
11514
+ const raw = readText(path14.join(cwd, "package.json"));
11419
11515
  if (raw === null) return {};
11420
11516
  try {
11421
11517
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -11425,7 +11521,7 @@ function readDescription(cwd) {
11425
11521
  }
11426
11522
  }
11427
11523
  function readSummary(cwd) {
11428
- const raw = readText(path13.join(cwd, "README.md"));
11524
+ const raw = readText(path14.join(cwd, "README.md"));
11429
11525
  if (raw === null) return {};
11430
11526
  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
11527
  const paragraph = [];
@@ -11451,16 +11547,16 @@ function truncate(text2, limit) {
11451
11547
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
11452
11548
  }
11453
11549
  function readReleases(cwd) {
11454
- const raw = readText(path13.join(cwd, "CHANGELOG.md"));
11550
+ const raw = readText(path14.join(cwd, "CHANGELOG.md"));
11455
11551
  if (raw === null) return [];
11456
11552
  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
11553
  return headings.slice(0, MAX_RELEASES);
11458
11554
  }
11459
11555
 
11460
11556
  // src/remote/source.ts
11461
- import * as fs14 from "fs";
11557
+ import * as fs15 from "fs";
11462
11558
  import * as os from "os";
11463
- import * as path14 from "path";
11559
+ import * as path15 from "path";
11464
11560
  import { spawnSync as spawnSync3 } from "child_process";
11465
11561
  import { lookup } from "dns/promises";
11466
11562
  import { fileURLToPath } from "url";
@@ -11504,7 +11600,7 @@ function parseRemoteSource(input, options = {}) {
11504
11600
  const directory = fileURLToPath(url2);
11505
11601
  return {
11506
11602
  ok: true,
11507
- source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path14.basename(directory), ref: null }
11603
+ source: { kind: "file", url: trimmed, host: "file", owner: "", repo: path15.basename(directory), ref: null }
11508
11604
  };
11509
11605
  }
11510
11606
  let url;
@@ -11571,9 +11667,9 @@ function gitEnvironment(token, host) {
11571
11667
  async function cloneRepository(source, options) {
11572
11668
  const log = options.log ?? (() => {
11573
11669
  });
11574
- const dest = path14.resolve(options.dest);
11575
- fs14.rmSync(dest, { recursive: true, force: true });
11576
- fs14.mkdirSync(dest, { recursive: true });
11670
+ const dest = path15.resolve(options.dest);
11671
+ fs15.rmSync(dest, { recursive: true, force: true });
11672
+ fs15.mkdirSync(dest, { recursive: true });
11577
11673
  const args = ["clone", "--depth", "1", "--single-branch", "--no-tags", "--quiet"];
11578
11674
  if (options.ref !== void 0 && options.ref !== null && options.ref !== "") {
11579
11675
  args.push("--branch", options.ref);
@@ -11623,16 +11719,16 @@ function directorySize(root) {
11623
11719
  const current = stack.pop();
11624
11720
  let entries;
11625
11721
  try {
11626
- entries = fs14.readdirSync(current, { withFileTypes: true });
11722
+ entries = fs15.readdirSync(current, { withFileTypes: true });
11627
11723
  } catch {
11628
11724
  continue;
11629
11725
  }
11630
11726
  for (const entry of entries) {
11631
- const full = path14.join(current, entry.name);
11727
+ const full = path15.join(current, entry.name);
11632
11728
  if (entry.isDirectory()) stack.push(full);
11633
11729
  else if (entry.isFile()) {
11634
11730
  try {
11635
- total += fs14.statSync(full).size;
11731
+ total += fs15.statSync(full).size;
11636
11732
  } catch {
11637
11733
  }
11638
11734
  }
@@ -11641,7 +11737,7 @@ function directorySize(root) {
11641
11737
  return total;
11642
11738
  }
11643
11739
  function makeCloneDirectory() {
11644
- return fs14.mkdtempSync(path14.join(os.tmpdir(), "codebase-snapshot-clone-"));
11740
+ return fs15.mkdtempSync(path15.join(os.tmpdir(), "codebase-snapshot-clone-"));
11645
11741
  }
11646
11742
 
11647
11743
  // src/web/server.ts
@@ -11864,74 +11960,6 @@ import * as path16 from "path";
11864
11960
  import { execFileSync as execFileSync3 } from "child_process";
11865
11961
  import { createHash as createHash7 } from "crypto";
11866
11962
 
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
11963
  // src/partitioner/part-format.ts
11936
11964
  var FILE_HEADING = "### FILE: ";
11937
11965
  var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
@@ -12511,8 +12539,9 @@ function auditSnapshot(options) {
12511
12539
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
12512
12540
  disagreements.push("file count");
12513
12541
  }
12542
+ 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
12543
  checks.push(
12515
- disagreements.length === 0 ? check(
12544
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
12516
12545
  "workspace.index",
12517
12546
  "The workspace index agrees with this member",
12518
12547
  "warning",
@@ -12534,12 +12563,45 @@ function auditSnapshot(options) {
12534
12563
  let scannedBytes = 0;
12535
12564
  for (const relative15 of walk(snapshotDir)) {
12536
12565
  if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
12566
+ if (relative15 === SIGNATURE_FILE) continue;
12537
12567
  const text2 = readText2(path16.join(snapshotDir, relative15));
12538
12568
  if (text2 === null) continue;
12539
12569
  scannedBytes += Buffer.byteLength(text2, "utf8");
12540
- const found = scanAndRedactSecrets(text2, rules, relative15);
12541
- if (found.findings.length > 0) {
12542
- leakHits.push(relative15 + " (" + found.findings.length + " line(s))");
12570
+ let findingCount = 0;
12571
+ if (/^parts[\\/].*\.md$/i.test(relative15)) {
12572
+ let headerText = text2;
12573
+ for (const section of parsePartSections(text2)) {
12574
+ findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
12575
+ headerText = headerText.replace(section.body, "");
12576
+ }
12577
+ findingCount += scanAndRedactSecrets(headerText, rules, relative15).findings.length;
12578
+ } else {
12579
+ findingCount = scanAndRedactSecrets(text2, rules, relative15).findings.length;
12580
+ }
12581
+ if (findingCount > 0) {
12582
+ leakHits.push(relative15 + " (" + findingCount + " line(s))");
12583
+ }
12584
+ }
12585
+ const signatureRecordPath = path16.join(snapshotDir, SIGNATURE_FILE);
12586
+ if (fs16.existsSync(signatureRecordPath)) {
12587
+ const recordText = readText2(signatureRecordPath);
12588
+ if (recordText !== null) {
12589
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
12590
+ let scanText = recordText;
12591
+ try {
12592
+ const record = JSON.parse(recordText);
12593
+ const rest = { ...record };
12594
+ delete rest.publicKey;
12595
+ delete rest.signature;
12596
+ delete rest.manifestSha256;
12597
+ delete rest.fingerprint;
12598
+ scanText = JSON.stringify(rest, null, 2);
12599
+ } catch {
12600
+ }
12601
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
12602
+ if (found.findings.length > 0) {
12603
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
12604
+ }
12543
12605
  }
12544
12606
  }
12545
12607
  checks.push(
@@ -12825,6 +12887,9 @@ function windowText(body, fromLine, lineCount) {
12825
12887
  };
12826
12888
  }
12827
12889
 
12890
+ // src/mcp/tools.ts
12891
+ import { createHash as createHash8 } from "crypto";
12892
+
12828
12893
  // src/mcp/workspace.ts
12829
12894
  import * as fs17 from "fs";
12830
12895
  import * as path18 from "path";
@@ -13046,6 +13111,10 @@ var WRITES = {
13046
13111
  openWorldHint: false
13047
13112
  };
13048
13113
  var MAX_RESULT_BYTES = 64 * 1024;
13114
+ function capResultText(text2) {
13115
+ const clipped = truncateToBytes(text2, MAX_RESULT_BYTES);
13116
+ return { text: clipped.isTruncated ? clipped.content : text2, clipped: clipped.isTruncated };
13117
+ }
13049
13118
  var ROOT_PROPERTY = {
13050
13119
  type: "string",
13051
13120
  description: "Repository root. Defaults to the directory this server was started in."
@@ -13233,6 +13302,17 @@ var historyTool = {
13233
13302
  isError: true
13234
13303
  };
13235
13304
  }
13305
+ const manifestRead = readManifest3(prepared.workspace);
13306
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
13307
+ if (recordedLog !== void 0 && recordedLog !== null) {
13308
+ const digest = createHash8("sha256").update(text2, "utf8").digest("hex");
13309
+ if (digest !== recordedLog.sha256) {
13310
+ return {
13311
+ 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.",
13312
+ isError: true
13313
+ };
13314
+ }
13315
+ }
13236
13316
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
13237
13317
  const commits = parseHistoryReport(text2).slice(0, limit);
13238
13318
  return {
@@ -13292,9 +13372,12 @@ var budgetTool = {
13292
13372
  });
13293
13373
  }
13294
13374
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
13375
+ if (read.manifest.files.length === 0) {
13376
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
13377
+ }
13295
13378
  for (const row of rows) {
13296
13379
  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" : "") + ")")
13380
+ 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
13381
  );
13299
13382
  }
13300
13383
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -13546,7 +13629,7 @@ var routesTool = {
13546
13629
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
13547
13630
  const text2 = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
13548
13631
  routes.length + " route(s):",
13549
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
13632
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
13550
13633
  ].join("\n");
13551
13634
  return { text: text2, structured: { total: routes.length, routes } };
13552
13635
  }
@@ -13715,8 +13798,9 @@ var searchTool = {
13715
13798
  }
13716
13799
  }
13717
13800
  }
13801
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
13718
13802
  const lines = [
13719
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
13803
+ 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
13804
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
13721
13805
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
13722
13806
  ];
@@ -13739,7 +13823,9 @@ var statsTool = {
13739
13823
  parts: { type: "integer" },
13740
13824
  tokens: { type: "integer" },
13741
13825
  layers: { type: "object" },
13742
- kinds: { type: "object" }
13826
+ kinds: { type: "object" },
13827
+ heaviest: { type: "array", items: { type: "object" } },
13828
+ partSizes: { type: "array", items: { type: "object" } }
13743
13829
  }
13744
13830
  },
13745
13831
  annotations: READ_ONLY,
@@ -13750,7 +13836,11 @@ var statsTool = {
13750
13836
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13751
13837
  const manifest = read.manifest;
13752
13838
  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 }));
13839
+ const parts = manifest.parts.map((part) => ({
13840
+ filename: part.filename,
13841
+ bytes: part.byteSize,
13842
+ tokens: part.estimatedTokens
13843
+ }));
13754
13844
  const lines = [
13755
13845
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
13756
13846
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -13806,7 +13896,7 @@ var reviewTool = {
13806
13896
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13807
13897
  let validation;
13808
13898
  try {
13809
- validation = validateSnapshot(workspace.config);
13899
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
13810
13900
  } catch (error) {
13811
13901
  return { text: error.message, isError: true };
13812
13902
  }
@@ -13906,24 +13996,17 @@ var diffContextTool = {
13906
13996
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
13907
13997
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
13908
13998
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
13999
+ const resolver = buildImportResolver(read.manifest.files, {
14000
+ tsconfig: tsconfigPathsFor(workspace.root)
14001
+ });
13909
14002
  const importers = /* @__PURE__ */ new Map();
13910
14003
  for (const entry of read.manifest.indexes.imports.byFile) {
13911
14004
  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) ?? [];
14005
+ const target = resolveSpecifier(entry.path, specifier, resolver);
14006
+ if (target === null) continue;
14007
+ const list2 = importers.get(target) ?? [];
13925
14008
  list2.push(entry.path);
13926
- importers.set(target.relativePath, list2);
14009
+ importers.set(target, list2);
13927
14010
  }
13928
14011
  }
13929
14012
  const missing = [];
@@ -13958,9 +14041,12 @@ var diffContextTool = {
13958
14041
  continue;
13959
14042
  }
13960
14043
  used += tokens;
14044
+ const capped2 = capResultText(window.text);
13961
14045
  changed.push({ path: file.relativePath, part: file.part, tokens });
13962
- text2.push("### " + file.relativePath + " (" + file.part + ")");
13963
- text2.push(window.text);
14046
+ text2.push(
14047
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
14048
+ );
14049
+ text2.push(capped2.text);
13964
14050
  }
13965
14051
  const dependents = [];
13966
14052
  for (const entry of changed) {
@@ -14042,11 +14128,13 @@ var symbolTool = {
14042
14128
  if (index === -1) continue;
14043
14129
  const from = Math.max(0, index - 3);
14044
14130
  const to = Math.min(lines.length, index + windowSize);
14131
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
14045
14132
  matches.push({
14046
14133
  path: file.relativePath,
14047
14134
  part: file.part,
14048
14135
  line: index + 1,
14049
- text: lines.slice(from, to).join("\n")
14136
+ text: capped2.text,
14137
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
14050
14138
  });
14051
14139
  }
14052
14140
  if (matches.length === 0) {
@@ -14177,7 +14265,8 @@ var contextTool = {
14177
14265
  continue;
14178
14266
  }
14179
14267
  const window = windowText(section.body, 1, linesPerFile);
14180
- const body = window.text;
14268
+ const capped2 = capResultText(window.text);
14269
+ const body = capped2.text;
14181
14270
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
14182
14271
  if (used + tokens > budget) {
14183
14272
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -14186,14 +14275,19 @@ var contextTool = {
14186
14275
  missing.push(file.relativePath + " (budget)");
14187
14276
  continue;
14188
14277
  }
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);
14278
+ const smallerCapped = capResultText(smaller.text);
14279
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
14280
+ text2.push(
14281
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
14282
+ );
14283
+ text2.push(smallerCapped.text);
14192
14284
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
14193
14285
  used += partial;
14194
14286
  continue;
14195
14287
  }
14196
- text2.push("### " + file.relativePath + " (" + file.part + ")");
14288
+ text2.push(
14289
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
14290
+ );
14197
14291
  text2.push(body);
14198
14292
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
14199
14293
  used += tokens;
@@ -14367,8 +14461,17 @@ var answerTool = {
14367
14461
  maxTokens,
14368
14462
  ...args.includeTests === true ? { includeTests: true } : {}
14369
14463
  });
14464
+ if (read.manifest.files.length === 0) {
14465
+ return {
14466
+ 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).",
14467
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
14468
+ };
14469
+ }
14370
14470
  const blocks = [];
14371
- const omitted = [];
14471
+ const omitted = plan.skipped.map((entry) => ({
14472
+ path: entry.path,
14473
+ reason: entry.reason
14474
+ }));
14372
14475
  let used = 0;
14373
14476
  const parts = /* @__PURE__ */ new Map();
14374
14477
  for (const planned of plan.files) {
@@ -14397,14 +14500,23 @@ var answerTool = {
14397
14500
  continue;
14398
14501
  }
14399
14502
  const window = windowText(section.body, 1, linesPerFile);
14400
- const text2 = window.text;
14401
- const tokens = estimateTokens(text2);
14503
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
14504
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
14505
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
14506
+ const tokens = estimateTokens(bodyText);
14402
14507
  if (used + tokens > maxTokens && blocks.length > 0) {
14403
14508
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
14404
14509
  continue;
14405
14510
  }
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 });
14511
+ blocks.push({
14512
+ path: planned.path,
14513
+ why: planned.why,
14514
+ tokens,
14515
+ text: bodyText,
14516
+ truncated: window.truncated || clipped.isTruncated,
14517
+ totalLines: window.totalLines,
14518
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
14519
+ });
14408
14520
  used += tokens;
14409
14521
  }
14410
14522
  const lines = [
@@ -14413,7 +14525,9 @@ var answerTool = {
14413
14525
  ];
14414
14526
  for (const block of blocks) {
14415
14527
  lines.push("");
14416
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
14528
+ lines.push(
14529
+ "## " + 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") + ")"
14530
+ );
14417
14531
  lines.push("Why: " + block.why);
14418
14532
  lines.push("```");
14419
14533
  lines.push(block.text);
@@ -14424,6 +14538,11 @@ var answerTool = {
14424
14538
  lines.push("Not included:");
14425
14539
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
14426
14540
  }
14541
+ if (plan.notes.length > 0) {
14542
+ lines.push("");
14543
+ lines.push("Notes:");
14544
+ for (const note of plan.notes) lines.push("- " + note);
14545
+ }
14427
14546
  return {
14428
14547
  text: lines.join("\n"),
14429
14548
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -14538,7 +14657,7 @@ var statusTool = {
14538
14657
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
14539
14658
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
14540
14659
  `Fingerprint: ${manifest.fingerprint}`,
14541
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
14660
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
14542
14661
  ];
14543
14662
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
14544
14663
  if (!versionMatches) {
@@ -14689,6 +14808,16 @@ var generateTool = {
14689
14808
  minimum: 500,
14690
14809
  description: "Fit the snapshot into this token budget, highest value first."
14691
14810
  },
14811
+ only: {
14812
+ type: "array",
14813
+ items: { type: "string" },
14814
+ description: "Globs to include: replaces the config allow-list for this run."
14815
+ },
14816
+ ignore: {
14817
+ type: "array",
14818
+ items: { type: "string" },
14819
+ description: "Globs to exclude, added to the config deny-list for this run."
14820
+ },
14692
14821
  ...SCOPE_PROPERTIES
14693
14822
  },
14694
14823
  additionalProperties: false
@@ -14717,7 +14846,9 @@ var generateTool = {
14717
14846
  ...args.tokenTree === true ? { tokenTree: true } : {},
14718
14847
  ...args.stripComments === true ? { stripComments: true } : {},
14719
14848
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
14720
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
14849
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
14850
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
14851
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
14721
14852
  };
14722
14853
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
14723
14854
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -14761,6 +14892,20 @@ var generateTool = {
14761
14892
  };
14762
14893
  }
14763
14894
  };
14895
+ function configAsGenerated(workspace, manifest) {
14896
+ const recorded = manifest.config;
14897
+ return {
14898
+ ...workspace.config,
14899
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
14900
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
14901
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
14902
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
14903
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
14904
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
14905
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
14906
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
14907
+ };
14908
+ }
14764
14909
  var validateTool = {
14765
14910
  name: "snapshot_validate",
14766
14911
  title: "Validate the snapshot",
@@ -14782,9 +14927,11 @@ var validateTool = {
14782
14927
  const prepared = await prepare(args, context, workspaceOverrides(args));
14783
14928
  if (!prepared.ok) return prepared.outcome;
14784
14929
  const workspace = prepared.workspace;
14930
+ const read = readManifest3(workspace);
14931
+ if (!read.ok) return failure(read.message);
14785
14932
  let result;
14786
14933
  try {
14787
- result = validateSnapshot(workspace.config);
14934
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
14788
14935
  } catch (error) {
14789
14936
  return failure(error instanceof Error ? error.message : String(error));
14790
14937
  }
@@ -15148,6 +15295,12 @@ var readTool = {
15148
15295
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
15149
15296
  );
15150
15297
  }
15298
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
15299
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
15300
+ }
15301
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
15302
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
15303
+ }
15151
15304
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
15152
15305
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
15153
15306
  const window = windowText(section.body, fromLine, lineCount);
@@ -15597,6 +15750,8 @@ var COMMAND_OPTION_SCOPE = {
15597
15750
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
15598
15751
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
15599
15752
  // list, so removing them narrows the two together.
15753
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
15754
+ update: ["format", "help"],
15600
15755
  report: [
15601
15756
  "cwd",
15602
15757
  "out-dir",
@@ -15958,6 +16113,13 @@ function buildAgentContract() {
15958
16113
  positionals: [],
15959
16114
  exits: [0]
15960
16115
  },
16116
+ {
16117
+ name: "update",
16118
+ aliases: [],
16119
+ 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.",
16120
+ positionals: [],
16121
+ exits: [0, 1, 2]
16122
+ },
15961
16123
  {
15962
16124
  name: "skill",
15963
16125
  aliases: [],
@@ -16253,14 +16415,14 @@ function buildAgentContract() {
16253
16415
  type: "boolean",
16254
16416
  default: false,
16255
16417
  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."
16418
+ 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
16419
  },
16258
16420
  {
16259
16421
  flag: "--include-logs",
16260
16422
  type: "string",
16261
16423
  default: "unset",
16262
16424
  appliesTo: optionAppliesTo("include-logs"),
16263
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
16425
+ 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
16426
  },
16265
16427
  {
16266
16428
  flag: "--token-tree",
@@ -17254,6 +17416,18 @@ function createMcpServer(options) {
17254
17416
  if (!isJsonObject(rawArguments)) {
17255
17417
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
17256
17418
  }
17419
+ const missing = (prompt.arguments ?? []).filter((argument) => {
17420
+ if (argument.required !== true) return false;
17421
+ const value = rawArguments[argument.name];
17422
+ return typeof value !== "string" || value.trim() === "";
17423
+ });
17424
+ if (missing.length > 0) {
17425
+ return errorResponse(
17426
+ id,
17427
+ ERROR_CODES.invalidParams,
17428
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
17429
+ );
17430
+ }
17257
17431
  const built = prompt.build(rawArguments);
17258
17432
  const messages = built.messages.map((message) => ({
17259
17433
  role: message.role,
@@ -17727,20 +17901,20 @@ var SERVE_PAGE = `<!doctype html>
17727
17901
  <header><b>codebase-snapshot</b><span>a snapshot an agent can trust</span></header>
17728
17902
  <main>
17729
17903
  <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">
17904
+ <input id="source" aria-label="repository path or URL" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
17905
+ <select id="mode" aria-label="What to generate" title="What to generate">
17732
17906
  <option value="full">whole repository</option>
17733
17907
  <option value="slice">a slice for a question</option>
17734
17908
  <option value="budget">fit a token budget</option>
17735
17909
  </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>
17910
+ <input id="question" aria-label="Question for the slice" placeholder="the question (slice mode)" spellcheck="false" hidden>
17911
+ <input id="budget" type="number" min="500" step="500" value="30000" aria-label="Token budget" title="token budget" hidden>
17738
17912
  <button id="run" type="submit">Generate</button>
17739
17913
  <button id="download" type="button" disabled>Download .zip</button>
17740
17914
  </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>
17915
+ <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
17916
  <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>
17917
+ <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
17918
  </div>
17745
17919
  <div class="row">
17746
17920
  <section><h2>Brief <span id="fingerprint"></span> <span id="health"></span></h2><pre id="brief">No snapshot loaded.</pre></section>
@@ -18035,9 +18209,14 @@ async function startWebServer(options) {
18035
18209
  send(400, { error: "not a directory: " + target });
18036
18210
  return;
18037
18211
  }
18212
+ const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
18213
+ if (loaded.errors.length > 0) {
18214
+ send(400, { error: loaded.errors.join("; ") });
18215
+ return;
18216
+ }
18038
18217
  const started = Date.now();
18039
18218
  try {
18040
- const manifest = generateSnapshot({ cwd: target }, {
18219
+ const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
18041
18220
  ...provenance === void 0 ? {} : { source: provenance },
18042
18221
  ...mode === "slice" ? { slice: { question } } : {},
18043
18222
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
@@ -18177,8 +18356,8 @@ import * as path23 from "path";
18177
18356
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
18178
18357
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
18179
18358
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
18180
- var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
18181
- var REQUEST_TIMEOUT_MS = 1200;
18359
+ var FAILURE_INTERVAL_MS = 5 * 60 * 1e3;
18360
+ var REQUEST_TIMEOUT_MS = 2500;
18182
18361
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
18183
18362
  const normalise = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
18184
18363
  const script = normalise(scriptPath);
@@ -18242,7 +18421,7 @@ function shouldCheck(argv, env) {
18242
18421
  if (env.CI !== void 0 && env.CI !== "" && env.CI !== "false" && env.CI !== "0") return false;
18243
18422
  const args = argv.map((argument) => argument.toLowerCase());
18244
18423
  if (args.includes("--no-update-check")) return false;
18245
- for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
18424
+ for (const skip of ["mcp", "describe", "skill", "update", "--version", "-v", "--help", "-h"]) {
18246
18425
  if (args.includes(skip)) return false;
18247
18426
  }
18248
18427
  let format = null;
@@ -18338,13 +18517,19 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
18338
18517
  });
18339
18518
  }
18340
18519
  async function checkForUpdate(options) {
18520
+ const latest = await resolveLatest(options);
18521
+ if (!latest) return null;
18522
+ return isNewer(latest, options.current) ? { current: options.current, latest } : null;
18523
+ }
18524
+ async function resolveLatest(options) {
18341
18525
  if (options.enabled === false) return null;
18342
18526
  const now = options.now ?? (() => Date.now());
18343
18527
  const fetchLatest = options.fetchLatest ?? fetchLatestVersion;
18528
+ const latestUrl = options.latestUrl ?? PACKAGE_LATEST_URL;
18344
18529
  let latest = null;
18345
18530
  try {
18346
18531
  const cached = readCache(options.cacheFile);
18347
- let needsFetch = cached === null;
18532
+ let needsFetch = cached === null || options.force === true;
18348
18533
  if (cached) {
18349
18534
  const age = now() - cached.checkedAt;
18350
18535
  if (cached.latest === null) {
@@ -18356,15 +18541,14 @@ async function checkForUpdate(options) {
18356
18541
  }
18357
18542
  }
18358
18543
  if (needsFetch) {
18359
- const fetched = await fetchLatest(PACKAGE_LATEST_URL, REQUEST_TIMEOUT_MS);
18544
+ const fetched = await fetchLatest(latestUrl, REQUEST_TIMEOUT_MS);
18360
18545
  writeCache(options.cacheFile, { checkedAt: now(), latest: fetched });
18361
- latest = fetched;
18546
+ latest = fetched ?? latest;
18362
18547
  }
18363
18548
  } catch {
18364
18549
  return null;
18365
18550
  }
18366
- if (!latest) return null;
18367
- return isNewer(latest, options.current) ? { current: options.current, latest } : null;
18551
+ return latest;
18368
18552
  }
18369
18553
  function formatUpdateNotice(notice, kind) {
18370
18554
  return `\u2191 codebase-snapshot ${notice.latest} is available \u2014 you have ${notice.current}.
@@ -20119,6 +20303,11 @@ function generateSnapshot(configInput, options) {
20119
20303
  detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
20120
20304
  files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
20121
20305
  };
20306
+ if (plan.files.length === 0) {
20307
+ warnings.push(
20308
+ "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.")
20309
+ );
20310
+ }
20122
20311
  }
20123
20312
  let budgetBlock;
20124
20313
  if (options?.budgetTokens !== void 0) {
@@ -20210,6 +20399,11 @@ function generateSnapshot(configInput, options) {
20210
20399
  warnings.push("No file fits --budget-tokens " + budget + "; the snapshot is empty.");
20211
20400
  }
20212
20401
  }
20402
+ if (config.include.length > 0 && files.length === 0) {
20403
+ warnings.push(
20404
+ "No file matched the include allow-list (" + config.include.length + " pattern(s): " + config.include.join(", ") + "), so the snapshot is empty."
20405
+ );
20406
+ }
20213
20407
  if (changedScope !== null || options?.deltaBase !== void 0) {
20214
20408
  const detail = changedScope !== null ? `not ${changedScope.detail}` : "identical to the base snapshot given with --delta";
20215
20409
  for (const relativePath of unchangedPaths) {
@@ -20348,6 +20542,12 @@ function generateSnapshot(configInput, options) {
20348
20542
  maxMonolithBytes: config.maxMonolithBytes ?? null,
20349
20543
  includeSensitiveFiles: config.includeSensitiveFiles,
20350
20544
  ...config.stripComments === true ? { stripComments: true } : {},
20545
+ // The other three settings the digest covers and the manifest did not record: without them a
20546
+ // validator (or `snapshot_review`) had no way to reconstruct the run, so a snapshot taken
20547
+ // with `--remove-empty-lines`, `--pack` or `--include-logs 3` looked stale forever.
20548
+ ...config.removeEmptyLines === true ? { removeEmptyLines: true } : {},
20549
+ ...config.pack === null ? {} : { pack: config.pack },
20550
+ logCount: config.logCount,
20351
20551
  // The destination the instructions were written for. Not part of `digest`: the payload is
20352
20552
  // identical whatever this says, and a new delivery preference must not make an existing
20353
20553
  // snapshot fail `validate` as configuration drift.
@@ -20491,6 +20691,18 @@ function generateSnapshot(configInput, options) {
20491
20691
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
20492
20692
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20493
20693
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
20694
+ if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20695
+ manifest.warnings.push(
20696
+ "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
20697
+ );
20698
+ manifest.totals.warningCount = manifest.warnings.length;
20699
+ }
20700
+ if (artifacts.log && logReport === null && !isGitRepository(config.cwd)) {
20701
+ manifest.warnings.push(
20702
+ "--include-logs was requested, but the generated directory is not a git repository; reports/log.md was not written."
20703
+ );
20704
+ manifest.totals.warningCount = manifest.warnings.length;
20705
+ }
20494
20706
  if (logReport !== null) manifest.artifacts.log = artifactRecord(logReport.text);
20495
20707
  const tokenTree = artifacts.tokenTree ? generateTokenTree(manifest) : null;
20496
20708
  if (tokenTree !== null) manifest.artifacts.tokenTree = artifactRecord(tokenTree.text);
@@ -20540,17 +20752,19 @@ function generateSnapshot(configInput, options) {
20540
20752
  if (wantsXml) manifest.warnings.push(`full-codebase.xml skipped: ${reason}`);
20541
20753
  }
20542
20754
  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
- );
20755
+ if (markdown !== null) {
20756
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
20757
+ if (config.maxMonolithBytes === null || markdownBytes <= config.maxMonolithBytes) {
20758
+ monolithMarkdown = markdown;
20759
+ manifest.artifacts.fullMarkdown = {
20760
+ byteSize: markdownBytes,
20761
+ sha256: sha256Hex2(markdown)
20762
+ };
20763
+ } else {
20764
+ manifest.warnings.push(
20765
+ `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20766
+ );
20767
+ }
20554
20768
  }
20555
20769
  if (wantsXml && !definitelyTooLarge) {
20556
20770
  const xml = generateMonolithXml(manifest, fullFiles);
@@ -20566,14 +20780,16 @@ function generateSnapshot(configInput, options) {
20566
20780
  }
20567
20781
  manifest.totals.warningCount = manifest.warnings.length;
20568
20782
  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
- );
20783
+ if (json !== null) {
20784
+ const jsonBytes = Buffer.byteLength(json, "utf8");
20785
+ if (config.maxMonolithBytes === null || jsonBytes <= config.maxMonolithBytes) {
20786
+ monolithJson = json;
20787
+ manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20788
+ } else {
20789
+ manifest.warnings.push(
20790
+ `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20791
+ );
20792
+ }
20577
20793
  }
20578
20794
  manifest.totals.warningCount = manifest.warnings.length;
20579
20795
  }
@@ -20919,6 +21135,7 @@ async function startHttpTransport(options) {
20919
21135
  noteRequest(request);
20920
21136
  const send = (status, body, extra = {}) => {
20921
21137
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
21138
+ if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
20922
21139
  response.writeHead(status, {
20923
21140
  "content-type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json",
20924
21141
  "content-length": Buffer.byteLength(text2, "utf8"),
@@ -20930,7 +21147,6 @@ async function startHttpTransport(options) {
20930
21147
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
20931
21148
  const allowed = allowedOrigin(origin);
20932
21149
  if (origin !== void 0 && allowed === null) {
20933
- metrics.refused += 1;
20934
21150
  send(403, { error: "origin not allowed" });
20935
21151
  return;
20936
21152
  }
@@ -20968,7 +21184,7 @@ async function startHttpTransport(options) {
20968
21184
  "# HELP snapshot_requests_total HTTP requests received.",
20969
21185
  "# TYPE snapshot_requests_total counter",
20970
21186
  "snapshot_requests_total " + metrics.requests,
20971
- "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
21187
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch (4xx other than 429).",
20972
21188
  "# TYPE snapshot_requests_refused_total counter",
20973
21189
  "snapshot_requests_refused_total " + metrics.refused,
20974
21190
  "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
@@ -21170,6 +21386,7 @@ var COMMAND_ALIASES = /* @__PURE__ */ new Map([
21170
21386
  ["describe", "describe"],
21171
21387
  ["skill", "skill"],
21172
21388
  ["mcp", "mcp"],
21389
+ ["update", "update"],
21173
21390
  ["serve", "serve"]
21174
21391
  ]);
21175
21392
  var COMMAND_ARITY = {
@@ -21184,6 +21401,7 @@ var COMMAND_ARITY = {
21184
21401
  describe: 0,
21185
21402
  skill: 0,
21186
21403
  mcp: 0,
21404
+ update: 0,
21187
21405
  serve: 0
21188
21406
  };
21189
21407
  var CLI_OPTIONS = {
@@ -21279,6 +21497,7 @@ Commands:
21279
21497
  explain <path> Show how one path would be treated: layer, kind, part, skips
21280
21498
  diff <a> <b> Compare two snapshots (directories or manifest.json files)
21281
21499
  describe Print the machine-readable contract (--format json for agents)
21500
+ update Ask the registry whether a newer release exists (exit 1 if one does)
21282
21501
  skill Print the bundled agent skill; --install writes it into the repo
21283
21502
  mcp Serve this repository to an MCP client (stdio, or --http for the web)
21284
21503
  serve Open a browser UI: generate, preview, download a zip; MCP at /mcp
@@ -22121,6 +22340,37 @@ async function firstRun(invocation) {
22121
22340
  );
22122
22341
  return await runSetupCommand(invocation, { interactive: plan.interactive });
22123
22342
  }
22343
+ async function runUpdateCommand(invocation) {
22344
+ const current = GENERATOR_VERSION;
22345
+ const latestUrl = process.env.CODEBASE_SNAPSHOT_REGISTRY_URL;
22346
+ const latest = await resolveLatest({
22347
+ current,
22348
+ cacheFile: cacheFilePath(),
22349
+ force: true,
22350
+ ...latestUrl === void 0 || latestUrl === "" ? {} : { latestUrl }
22351
+ });
22352
+ if (latest === null) {
22353
+ emit(invocation.format, { current, latest: null, updateAvailable: false }, () => {
22354
+ info(
22355
+ "Could not reach the npm registry, so the installed version could not be compared. Nothing was changed; try again when the network is available."
22356
+ );
22357
+ });
22358
+ return 2;
22359
+ }
22360
+ const kind = installKind();
22361
+ const updateAvailable = isNewer(latest, current);
22362
+ const command = updateCommand(kind);
22363
+ emit(invocation.format, { current, latest, updateAvailable, command }, () => {
22364
+ if (updateAvailable) {
22365
+ info(formatUpdateNotice({ current, latest }, kind));
22366
+ } else {
22367
+ info(
22368
+ `You are on codebase-snapshot ${current}, and the registry publishes ${latest}. No update is available.`
22369
+ );
22370
+ }
22371
+ });
22372
+ return updateAvailable ? 1 : 0;
22373
+ }
22124
22374
  function runSkillCommand(invocation) {
22125
22375
  if (!invocation.install) {
22126
22376
  if (invocation.format === "json") {
@@ -22262,6 +22512,9 @@ ${USAGE}
22262
22512
  if (invocation.command === "skill") {
22263
22513
  return runSkillCommand(invocation);
22264
22514
  }
22515
+ if (invocation.command === "update") {
22516
+ return runUpdateCommand(invocation);
22517
+ }
22265
22518
  if (invocation.command === "serve") {
22266
22519
  const server = await startWebServer({
22267
22520
  cwd: path27.resolve(invocation.cwd),
@@ -22679,8 +22932,9 @@ ${USAGE}
22679
22932
  }
22680
22933
  const started = performance.now();
22681
22934
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
22935
+ const headerGit = getGitInfo(resolved.cwd, resolved.branch);
22682
22936
  info(
22683
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
22937
+ ` Branch: ${resolved.branch}${headerGit.branchFromGit ? "" : " (fallback)"} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
22684
22938
  );
22685
22939
  try {
22686
22940
  let deltaBase;