codebase-snapshot 0.20.0 → 0.20.3

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/mcp.cjs CHANGED
@@ -2556,7 +2556,7 @@ function applySpansKeepingQuotes(line, spans) {
2556
2556
 
2557
2557
  // src/version.ts
2558
2558
  var GENERATOR_NAME = "codebase-snapshot";
2559
- var GENERATOR_VERSION = "0.20.0";
2559
+ var GENERATOR_VERSION = "0.20.3";
2560
2560
  var SCHEMA_VERSION = "3.0.0";
2561
2561
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2562
2562
  function isOurGeneratorName(name) {
@@ -6087,6 +6087,10 @@ function capValue(value, max) {
6087
6087
  return `${value.slice(0, half)}\u2026${value.slice(value.length - half)}`;
6088
6088
  }
6089
6089
  var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
6090
+ function emittedBody(content) {
6091
+ const normalised = content.replace(/\r\n|\r/g, "\n");
6092
+ return normalised.endsWith("\n") ? normalised.slice(0, -1) : normalised;
6093
+ }
6090
6094
  function anchorForPath(filePath) {
6091
6095
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
6092
6096
  const digest = crypto2__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
@@ -8288,13 +8292,14 @@ function secretTokens(text) {
8288
8292
  }
8289
8293
  return [...tokens];
8290
8294
  }
8291
- function artifactTextContains(snapshotDir, token) {
8295
+ function readArtifactTexts(snapshotDir) {
8296
+ const texts = [];
8292
8297
  for (const relative9 of walk(snapshotDir)) {
8293
8298
  if (!TEXT_ARTIFACT.test(relative9)) continue;
8294
8299
  const text = readText(path5__namespace.join(snapshotDir, relative9));
8295
- if (text !== null && text.includes(token)) return true;
8300
+ if (text !== null) texts.push(text);
8296
8301
  }
8297
- return false;
8302
+ return texts;
8298
8303
  }
8299
8304
  function findHostPaths(snapshotDir, repoDir) {
8300
8305
  const patterns = [
@@ -8335,6 +8340,135 @@ function staleAgainstRepository(manifest, repoDir) {
8335
8340
  if (head === recorded) return null;
8336
8341
  return "HEAD is " + head.slice(0, 8) + " but the snapshot was generated at " + recorded.slice(0, 8) + "; regenerate before trusting it.";
8337
8342
  }
8343
+ function summaryClaims(summary) {
8344
+ if ("imports" in summary) {
8345
+ const fields = [
8346
+ ["imports", summary.imports],
8347
+ ["reExports", summary.reExports],
8348
+ ["exports", summary.exports],
8349
+ ["functions", summary.functions],
8350
+ ["classes", summary.classes],
8351
+ ["interfaces", summary.interfaces],
8352
+ ["types", summary.types],
8353
+ ["enums", summary.enums],
8354
+ ["variables", summary.variables],
8355
+ ["reactComponents", summary.reactComponents],
8356
+ ["hooks", summary.hooks],
8357
+ ["routeHandlers", summary.routeHandlers]
8358
+ ];
8359
+ const claims = [];
8360
+ for (const [field, values] of fields) {
8361
+ for (const value of values) {
8362
+ if (typeof value !== "string" || value === "") continue;
8363
+ if (field === "routeHandlers" && value.includes(" ")) {
8364
+ const route = value.slice(value.indexOf(" ") + 1).trim();
8365
+ if (route !== "") claims.push({ field, value: route });
8366
+ continue;
8367
+ }
8368
+ claims.push({ field, value });
8369
+ }
8370
+ }
8371
+ return claims;
8372
+ }
8373
+ if ("keys" in summary) {
8374
+ return [...summary.keys, ...summary.sampleKeys].map((key) => ({
8375
+ field: "keys",
8376
+ value: '"' + key + '"'
8377
+ }));
8378
+ }
8379
+ return summary.headings.map((heading) => ({ field: "headings", value: heading }));
8380
+ }
8381
+ function reportNumber(text, label) {
8382
+ const match = new RegExp("\\*\\*" + escapeRegExp(label) + ":\\*\\* `([0-9][0-9,]*)`").exec(text);
8383
+ return match === null ? null : Number(match[1].replace(/,/g, ""));
8384
+ }
8385
+ function reportMib(text, label) {
8386
+ const match = new RegExp(
8387
+ "\\*\\*" + escapeRegExp(label) + ":\\*\\* `([0-9]+(?:\\.[0-9]+)?) MiB`"
8388
+ ).exec(text);
8389
+ return match === null ? null : Number(match[1]);
8390
+ }
8391
+ function maskCompatible(sourceLine, bodyLine) {
8392
+ const normalised = bodyLine.split(PEM_REDACTION_MARKER).join(REDACTION_MARKER);
8393
+ let cursor = 0;
8394
+ for (const piece of normalised.split(REDACTION_MARKER)) {
8395
+ if (piece === "") continue;
8396
+ const at = sourceLine.indexOf(piece, cursor);
8397
+ if (at === -1) return false;
8398
+ cursor = at + piece.length;
8399
+ }
8400
+ return true;
8401
+ }
8402
+ function firstBodyMismatch(expected, actual) {
8403
+ const sourceLines = expected.split("\n");
8404
+ const bodyLines = actual.split("\n");
8405
+ const shared = Math.min(sourceLines.length, bodyLines.length);
8406
+ for (let index = 0; index < shared; index += 1) {
8407
+ if (sourceLines[index] === bodyLines[index]) continue;
8408
+ if (!bodyLines[index].includes(REDACTION_MARKER) && !bodyLines[index].includes(PEM_REDACTION_MARKER)) {
8409
+ return index + 1;
8410
+ }
8411
+ if (!maskCompatible(sourceLines[index], bodyLines[index])) return index + 1;
8412
+ }
8413
+ return sourceLines.length === bodyLines.length ? null : shared + 1;
8414
+ }
8415
+ function decodeXmlAttribute(value) {
8416
+ return value.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
8417
+ }
8418
+ function jsonPackBodies(text) {
8419
+ try {
8420
+ const parsed = JSON.parse(text);
8421
+ if (!Array.isArray(parsed?.files)) return null;
8422
+ const bodies = /* @__PURE__ */ new Map();
8423
+ for (const entry of parsed.files) {
8424
+ if (typeof entry?.relativePath !== "string" || typeof entry.content !== "string") continue;
8425
+ bodies.set(entry.relativePath, entry.content);
8426
+ }
8427
+ return bodies;
8428
+ } catch {
8429
+ return null;
8430
+ }
8431
+ }
8432
+ function xmlPackBodies(text) {
8433
+ const bodies = /* @__PURE__ */ new Map();
8434
+ const filePattern = / <file path="([^"]*)"[^>]*>\n([\s\S]*?)\n <\/file>/g;
8435
+ for (const match of text.matchAll(filePattern)) {
8436
+ const content = [...match[2].matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)].map((part) => part[1]).join("");
8437
+ bodies.set(decodeXmlAttribute(match[1]), content);
8438
+ }
8439
+ return bodies.size === 0 ? null : bodies;
8440
+ }
8441
+ function markdownPackBodies(text) {
8442
+ const bodies = /* @__PURE__ */ new Map();
8443
+ const lines = text.split("\n");
8444
+ let index = 0;
8445
+ while (index < lines.length) {
8446
+ if (!lines[index].startsWith("## File: ")) {
8447
+ index += 1;
8448
+ continue;
8449
+ }
8450
+ const filePath = lines[index].slice("## File: ".length).trim();
8451
+ let cursor = index + 1;
8452
+ while (cursor < lines.length && !/^`{3,}/.test(lines[cursor])) {
8453
+ if (lines[cursor].startsWith("## File: ")) break;
8454
+ cursor += 1;
8455
+ }
8456
+ const fence = /^(`{3,})/.exec(lines[cursor] ?? "");
8457
+ if (fence === null) {
8458
+ index = cursor + 1;
8459
+ continue;
8460
+ }
8461
+ const body = [];
8462
+ let bodyLine = cursor + 1;
8463
+ while (bodyLine < lines.length && lines[bodyLine] !== fence[1]) {
8464
+ body.push(lines[bodyLine]);
8465
+ bodyLine += 1;
8466
+ }
8467
+ bodies.set(filePath, body.join("\n"));
8468
+ index = bodyLine + 1;
8469
+ }
8470
+ return bodies.size === 0 ? null : bodies;
8471
+ }
8338
8472
  function auditSnapshot(options) {
8339
8473
  const snapshotDir = path5__namespace.resolve(options.snapshotDir);
8340
8474
  const repoDir = path5__namespace.resolve(options.repoDir);
@@ -8541,6 +8675,272 @@ function auditSnapshot(options) {
8541
8675
  bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
8542
8676
  )
8543
8677
  );
8678
+ const fileByPath = new Map(manifest.files.map((file) => [file.relativePath, file]));
8679
+ const partTexts = /* @__PURE__ */ new Map();
8680
+ const partSections = /* @__PURE__ */ new Map();
8681
+ const bodyByPath = /* @__PURE__ */ new Map();
8682
+ const anchorToPath = new Map(
8683
+ manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
8684
+ );
8685
+ for (const part of manifest.parts) {
8686
+ const partText = readText(path5__namespace.join(snapshotDir, "parts", part.filename));
8687
+ if (partText === null) continue;
8688
+ const sections = parsePartSections(partText);
8689
+ partTexts.set(part.filename, partText);
8690
+ partSections.set(part.filename, sections);
8691
+ for (const section of sections) {
8692
+ if (section.anchor === null) continue;
8693
+ const relativePath = anchorToPath.get(section.anchor);
8694
+ if (relativePath !== void 0) bodyByPath.set(relativePath, section.body);
8695
+ }
8696
+ }
8697
+ const summaryProblems = [];
8698
+ let claimsChecked = 0;
8699
+ let summarisedFiles = 0;
8700
+ for (const file of manifest.files) {
8701
+ if (file.summary === void 0) continue;
8702
+ if (file.inclusionMode === "preview" || file.emptyLinesRemoved === true) continue;
8703
+ const body = bodyByPath.get(file.relativePath);
8704
+ if (body === void 0) continue;
8705
+ summarisedFiles += 1;
8706
+ for (const claim of summaryClaims(file.summary)) {
8707
+ if (claim.value.includes(REDACTION_MARKER)) continue;
8708
+ claimsChecked += 1;
8709
+ if (!body.includes(claim.value)) {
8710
+ summaryProblems.push(file.relativePath + " (" + claim.field + ")");
8711
+ }
8712
+ }
8713
+ }
8714
+ checks.push(
8715
+ summarisedFiles === 0 ? check(
8716
+ "summary.truth",
8717
+ "Every summary claim appears in the body",
8718
+ "critical",
8719
+ "skip",
8720
+ "No summarised file could be compared with a body."
8721
+ ) : summaryProblems.length === 0 ? check(
8722
+ "summary.truth",
8723
+ "Every summary claim appears in the body",
8724
+ "critical",
8725
+ "pass",
8726
+ claimsChecked + " claim(s) across " + summarisedFiles + " file(s) are present in the parts."
8727
+ ) : check(
8728
+ "summary.truth",
8729
+ "Every summary claim appears in the body",
8730
+ "critical",
8731
+ "fail",
8732
+ summaryProblems.length + " claim(s) name something the body does not contain: " + sample(summaryProblems)
8733
+ )
8734
+ );
8735
+ const reportProblems = [];
8736
+ let reportClaims = 0;
8737
+ const compareNumber = (label, actual, expected) => {
8738
+ if (actual === null) return;
8739
+ reportClaims += 1;
8740
+ if (actual !== expected) {
8741
+ reportProblems.push(label + " says " + actual + ", the manifest says " + expected);
8742
+ }
8743
+ };
8744
+ const compareMib = (label, actual, bytes) => {
8745
+ if (actual === null) return;
8746
+ reportClaims += 1;
8747
+ const expected = Number((bytes / (1024 * 1024)).toFixed(2));
8748
+ if (Math.abs(actual - expected) > 0.011) {
8749
+ reportProblems.push(label + " says " + actual + " MiB, the manifest says " + expected);
8750
+ }
8751
+ };
8752
+ if (manifest.artifacts?.readme != null) {
8753
+ const text = readText(path5__namespace.join(snapshotDir, "README.md"));
8754
+ if (text === null) {
8755
+ reportProblems.push("README.md is recorded but unreadable");
8756
+ } else {
8757
+ compareNumber("README total files", reportNumber(text, "Total Tracked Files"), manifest.counts.totalFiles);
8758
+ compareNumber("README source lines", reportNumber(text, "Source Lines"), manifest.counts.totalLines);
8759
+ compareNumber(
8760
+ "README emitted lines",
8761
+ reportNumber(text, "Emitted Lines"),
8762
+ manifest.totals.emittedLines ?? manifest.counts.totalLines
8763
+ );
8764
+ const partsWritten = manifest.config.artifacts?.parts !== false;
8765
+ compareNumber("README part count", reportNumber(text, "Part Count"), partsWritten ? manifest.counts.partsCount : 0);
8766
+ compareMib("README total size", reportMib(text, "Total Size"), manifest.counts.totalSizeBytes);
8767
+ compareMib("README emitted content", reportMib(text, "Emitted Content"), manifest.totals.totalContentBytes);
8768
+ const rows = [...text.matchAll(/^\| \[([^\]]+)\]\(parts\/([^)]+)\) \| (\d+) \| ([0-9.]+) KB \|/gm)];
8769
+ if (rows.length > 0) {
8770
+ reportClaims += rows.length;
8771
+ if (rows.length !== manifest.parts.length) {
8772
+ reportProblems.push("README tables " + rows.length + " part(s), the manifest holds " + manifest.parts.length);
8773
+ }
8774
+ for (const row of rows) {
8775
+ const part = manifest.parts.find((candidate) => candidate.filename === row[2]);
8776
+ if (part === void 0) {
8777
+ reportProblems.push("README names " + row[2] + ", which the manifest does not hold");
8778
+ continue;
8779
+ }
8780
+ if (Number(row[3]) !== part.fileCount) {
8781
+ reportProblems.push("README " + row[2] + " says " + row[3] + " file(s), the manifest says " + part.fileCount);
8782
+ }
8783
+ const stated = Number(row[4]);
8784
+ const expected = Number((part.byteSize / 1024).toFixed(1));
8785
+ if (Math.abs(stated - expected) > 0.11) {
8786
+ reportProblems.push("README " + row[2] + " says " + stated + " KB, the manifest says " + expected);
8787
+ }
8788
+ }
8789
+ }
8790
+ }
8791
+ }
8792
+ if (manifest.artifacts?.prompt != null) {
8793
+ const text = readText(path5__namespace.join(snapshotDir, "PROMPT.md"));
8794
+ if (text === null) {
8795
+ reportProblems.push("PROMPT.md is recorded but unreadable");
8796
+ } else {
8797
+ const fingerprint = /^- Fingerprint: \x60([0-9a-f]{12,64})\x60/m.exec(text);
8798
+ if (fingerprint !== null) {
8799
+ reportClaims += 1;
8800
+ if (fingerprint[1] !== manifest.fingerprint) reportProblems.push("PROMPT names a different fingerprint");
8801
+ }
8802
+ const generated = /^- Generated: \x60([^\x60]+)\x60 from branch \x60([^\x60]+)\x60 at commit \x60([0-9a-f]+)\x60/m.exec(text);
8803
+ if (generated !== null) {
8804
+ reportClaims += 3;
8805
+ if (generated[1] !== manifest.generatedAt) reportProblems.push("PROMPT names a different generation time");
8806
+ if (generated[2] !== manifest.git.branch) reportProblems.push("PROMPT names a different branch");
8807
+ if (!manifest.git.commit.startsWith(generated[3])) reportProblems.push("PROMPT names a different commit");
8808
+ }
8809
+ const validation = /^- Validation: the generation-time check was \x60([^\x60]+)\x60/m.exec(text);
8810
+ if (validation !== null) {
8811
+ reportClaims += 1;
8812
+ if (validation[1] !== manifest.validation.status) reportProblems.push("PROMPT quotes a different validation status");
8813
+ }
8814
+ const partsLine = /^- Parts: ([\d,]+) at a ([\d,]+) KB ceiling/m.exec(text);
8815
+ if (partsLine !== null) {
8816
+ reportClaims += 2;
8817
+ if (Number(partsLine[1].replace(/,/g, "")) !== manifest.parts.length) {
8818
+ reportProblems.push("PROMPT says " + partsLine[1] + " part(s), the manifest holds " + manifest.parts.length);
8819
+ }
8820
+ const ceiling = Math.round(manifest.budgets.maxPartBytes / 1024);
8821
+ if (Number(partsLine[2].replace(/,/g, "")) !== ceiling) {
8822
+ reportProblems.push("PROMPT says a " + partsLine[2] + " KB ceiling, the manifest says " + ceiling);
8823
+ }
8824
+ }
8825
+ for (const row of text.matchAll(/^ - \x60([^\x60]+)\x60 - ([\d,]+) file\(s\)$/gm)) {
8826
+ reportClaims += 1;
8827
+ const part = manifest.parts.find((candidate) => candidate.filename === row[1]);
8828
+ if (part === void 0) {
8829
+ reportProblems.push("PROMPT names " + row[1] + ", which the manifest does not hold");
8830
+ } else if (Number(row[2].replace(/,/g, "")) !== part.fileCount) {
8831
+ reportProblems.push("PROMPT " + row[1] + " says " + row[2] + " file(s), the manifest says " + part.fileCount);
8832
+ }
8833
+ }
8834
+ const coverage = /^- ([\d,]+) paths were found; ([\d,]+) (?:is|are) in the parts and ([\d,]+) (?:was|were) skipped/m.exec(text);
8835
+ if (coverage !== null) {
8836
+ reportClaims += 3;
8837
+ if (Number(coverage[1].replace(/,/g, "")) !== manifest.totals.candidateFiles) {
8838
+ reportProblems.push("PROMPT says " + coverage[1] + " paths were found, the manifest says " + manifest.totals.candidateFiles);
8839
+ }
8840
+ if (Number(coverage[2].replace(/,/g, "")) !== manifest.totals.includedFiles) {
8841
+ reportProblems.push("PROMPT says " + coverage[2] + " are in the parts, the manifest says " + manifest.totals.includedFiles);
8842
+ }
8843
+ if (Number(coverage[3].replace(/,/g, "")) !== manifest.counts.skippedCount) {
8844
+ reportProblems.push("PROMPT says " + coverage[3] + " were skipped, the manifest says " + manifest.counts.skippedCount);
8845
+ }
8846
+ }
8847
+ const partial = /^- Partial files: (none|[\d,]+)\./m.exec(text);
8848
+ if (partial !== null) {
8849
+ reportClaims += 1;
8850
+ const stated = partial[1] === "none" ? 0 : Number(partial[1].replace(/,/g, ""));
8851
+ if (stated !== manifest.incomplete.length) {
8852
+ reportProblems.push("PROMPT says " + partial[1] + " partial file(s), the manifest holds " + manifest.incomplete.length);
8853
+ }
8854
+ }
8855
+ if (text.includes("- Redacted: no line matched a secret rule.")) {
8856
+ reportClaims += 1;
8857
+ if (manifest.totals.redactedLines !== 0) {
8858
+ reportProblems.push("PROMPT says nothing was redacted, the manifest says " + manifest.totals.redactedLines);
8859
+ }
8860
+ } else {
8861
+ const redacted = /^- Redacted: ([\d,]+) line\(s\) had values masked/m.exec(text);
8862
+ if (redacted !== null) {
8863
+ reportClaims += 1;
8864
+ if (Number(redacted[1].replace(/,/g, "")) !== manifest.totals.redactedLines) {
8865
+ reportProblems.push("PROMPT says " + redacted[1] + " redacted line(s), the manifest says " + manifest.totals.redactedLines);
8866
+ }
8867
+ }
8868
+ }
8869
+ const layersLine = /^- Layers, by file count: (.+)$/m.exec(text);
8870
+ if (layersLine !== null) {
8871
+ for (const layer2 of layersLine[1].matchAll(/\x60([^\x60]+)\x60 ([\d,]+)/g)) {
8872
+ reportClaims += 1;
8873
+ const expected = manifest.layers[layer2[1]] ?? 0;
8874
+ if (Number(layer2[2].replace(/,/g, "")) !== expected) {
8875
+ reportProblems.push("PROMPT layer " + layer2[1] + " says " + layer2[2] + ", the manifest says " + expected);
8876
+ }
8877
+ }
8878
+ }
8879
+ }
8880
+ }
8881
+ checks.push(
8882
+ reportProblems.length > 0 ? check(
8883
+ "report.truth",
8884
+ "The reports quote this run, not another",
8885
+ "critical",
8886
+ "fail",
8887
+ reportProblems.length + " disagreement(s): " + sample(reportProblems)
8888
+ ) : reportClaims === 0 ? check(
8889
+ "report.truth",
8890
+ "The reports quote this run, not another",
8891
+ "critical",
8892
+ "skip",
8893
+ "No report in the current shape could be compared with the manifest."
8894
+ ) : check(
8895
+ "report.truth",
8896
+ "The reports quote this run, not another",
8897
+ "critical",
8898
+ "pass",
8899
+ reportClaims + " figure(s) in README.md and PROMPT.md agree with the manifest."
8900
+ )
8901
+ );
8902
+ const indexProblems = [];
8903
+ const indexedPaths = /* @__PURE__ */ new Set();
8904
+ const checkIndexed = (kind, relativePath, part) => {
8905
+ const file = fileByPath.get(relativePath);
8906
+ if (file === void 0) {
8907
+ indexProblems.push(kind + " names " + relativePath + ", which is not in files[]");
8908
+ return;
8909
+ }
8910
+ if (part !== void 0 && file.part !== part) {
8911
+ indexProblems.push(kind + " puts " + relativePath + " in " + part + ", the manifest says " + file.part);
8912
+ }
8913
+ };
8914
+ for (const route of manifest.indexes.routes) checkIndexed("routes", route.path, route.part);
8915
+ for (const component of manifest.indexes.components) checkIndexed("components", component.path, component.part);
8916
+ for (const handler of manifest.indexes.handlers) checkIndexed("handlers", handler.path, handler.part);
8917
+ for (const directive of manifest.indexes.directives) checkIndexed("directives", directive.path);
8918
+ for (const entry of manifest.indexes.imports.byFile) {
8919
+ checkIndexed("imports.byFile", entry.path);
8920
+ if (indexedPaths.has(entry.path)) indexProblems.push("imports.byFile lists " + entry.path + " twice");
8921
+ indexedPaths.add(entry.path);
8922
+ }
8923
+ for (const entry of manifest.indexes.imports.centralFiles) {
8924
+ checkIndexed("centralFiles", entry.path);
8925
+ if (entry.importedByCount < 1) {
8926
+ indexProblems.push("centralFiles says " + entry.path + " has " + entry.importedByCount + " importer(s)");
8927
+ }
8928
+ }
8929
+ checks.push(
8930
+ indexProblems.length === 0 ? check(
8931
+ "indexes.consistent",
8932
+ "Every index entry names a file in the snapshot",
8933
+ "critical",
8934
+ "pass",
8935
+ manifest.indexes.imports.byFile.length + " import edge(s) and " + (manifest.indexes.routes.length + manifest.indexes.components.length + manifest.indexes.handlers.length) + " route/component/handler entry(s) resolve."
8936
+ ) : check(
8937
+ "indexes.consistent",
8938
+ "Every index entry names a file in the snapshot",
8939
+ "critical",
8940
+ "fail",
8941
+ indexProblems.length + " index problem(s): " + sample(indexProblems)
8942
+ )
8943
+ );
8544
8944
  const packReaders = [
8545
8945
  {
8546
8946
  key: "fullJson",
@@ -8617,9 +9017,8 @@ function auditSnapshot(options) {
8617
9017
  const bodyProblems = [];
8618
9018
  let bodiesChecked = 0;
8619
9019
  for (const part of manifest.parts) {
8620
- const partText = readText(path5__namespace.join(snapshotDir, "parts", part.filename));
8621
- if (partText === null) continue;
8622
- const sections = parsePartSections(partText);
9020
+ const sections = partSections.get(part.filename);
9021
+ if (sections === void 0) continue;
8623
9022
  for (const file of manifest.files) {
8624
9023
  if (file.part !== part.filename) continue;
8625
9024
  const section = findSection(sections, file.relativePath);
@@ -8627,6 +9026,7 @@ function auditSnapshot(options) {
8627
9026
  bodyProblems.push(file.relativePath + " has no section in " + part.filename);
8628
9027
  continue;
8629
9028
  }
9029
+ bodyByPath.set(file.relativePath, section.body);
8630
9030
  bodiesChecked += 1;
8631
9031
  const bytes = Buffer.byteLength(section.body, "utf8");
8632
9032
  const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
@@ -8652,6 +9052,198 @@ function auditSnapshot(options) {
8652
9052
  bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
8653
9053
  )
8654
9054
  );
9055
+ const structureProblems = [];
9056
+ let sectionsChecked = 0;
9057
+ for (const part of manifest.parts) {
9058
+ const text = partTexts.get(part.filename);
9059
+ const sections = partSections.get(part.filename);
9060
+ if (text === void 0 || sections === void 0) continue;
9061
+ const header = /^# Codebase Snapshot Part (\d+) of (\d+)$/m.exec(text);
9062
+ if (header !== null) {
9063
+ if (Number(header[1]) !== part.index) {
9064
+ structureProblems.push(part.filename + " says part " + header[1] + ", the manifest says " + part.index);
9065
+ }
9066
+ if (Number(header[2]) !== manifest.parts.length) {
9067
+ structureProblems.push(part.filename + " says " + header[2] + " parts, the manifest holds " + manifest.parts.length);
9068
+ }
9069
+ }
9070
+ const filesLine = /^- Files: (\d+)$/m.exec(text);
9071
+ if (filesLine !== null && Number(filesLine[1]) !== part.fileCount) {
9072
+ structureProblems.push(part.filename + " says " + filesLine[1] + " file(s), the manifest says " + part.fileCount);
9073
+ }
9074
+ const fingerprintLine = /^- Content Fingerprint: (\S+)$/m.exec(text);
9075
+ if (fingerprintLine !== null && fingerprintLine[1] !== manifest.fingerprint) {
9076
+ structureProblems.push(part.filename + " names a different content fingerprint");
9077
+ }
9078
+ const tokenLine = /^- Estimated Tokens: ~([0-9,]+)$/m.exec(text);
9079
+ if (tokenLine !== null && Number(tokenLine[1].replace(/,/g, "")) !== part.estimatedTokens) {
9080
+ structureProblems.push(part.filename + " says " + tokenLine[1] + " tokens, the manifest says " + part.estimatedTokens);
9081
+ }
9082
+ if (sections.length !== part.fileCount) {
9083
+ structureProblems.push(part.filename + " holds " + sections.length + " section(s), the manifest says " + part.fileCount);
9084
+ }
9085
+ const expectedAnchors = new Set(part.includedFiles.map((entry) => anchorForPath(entry.relativePath)));
9086
+ for (const section of sections) {
9087
+ if (section.anchor === null || !expectedAnchors.has(section.anchor)) {
9088
+ structureProblems.push(part.filename + " holds a section for " + section.path + ", which the manifest does not list");
9089
+ }
9090
+ }
9091
+ const expectedOrder = part.includedFiles.map((entry) => anchorForPath(entry.relativePath)).join("\n");
9092
+ const actualOrder = sections.map((section) => section.anchor).filter((anchor) => anchor !== null).join("\n");
9093
+ if (actualOrder !== expectedOrder) {
9094
+ structureProblems.push(part.filename + " orders its sections differently than the manifest");
9095
+ }
9096
+ for (const entry of part.includedFiles) {
9097
+ const file = fileByPath.get(entry.relativePath);
9098
+ if (file === void 0) continue;
9099
+ const section = findSection(sections, entry.relativePath);
9100
+ if (section === null) {
9101
+ structureProblems.push(entry.relativePath + " has no section in " + part.filename);
9102
+ continue;
9103
+ }
9104
+ sectionsChecked += 1;
9105
+ if (section.path !== displayPath(entry.relativePath)) {
9106
+ structureProblems.push(entry.relativePath + " is headed " + section.path);
9107
+ }
9108
+ if (section.inclusion !== null && section.inclusion !== file.inclusionMode) {
9109
+ structureProblems.push(entry.relativePath + " declares " + section.inclusion + ", the manifest says " + file.inclusionMode);
9110
+ }
9111
+ if (section.includedLines !== null && section.includedLines !== file.includedLines) {
9112
+ structureProblems.push(entry.relativePath + " declares " + section.includedLines + " line(s), the manifest says " + file.includedLines);
9113
+ }
9114
+ }
9115
+ }
9116
+ checks.push(
9117
+ structureProblems.length === 0 ? check(
9118
+ "markdown.structure",
9119
+ "Every section sits where the manifest says",
9120
+ "critical",
9121
+ "pass",
9122
+ sectionsChecked + " section(s) in " + manifest.parts.length + " part(s) match their heading, metadata and order."
9123
+ ) : check(
9124
+ "markdown.structure",
9125
+ "Every section sits where the manifest says",
9126
+ "critical",
9127
+ "fail",
9128
+ structureProblems.length + " structural problem(s): " + sample(structureProblems)
9129
+ )
9130
+ );
9131
+ const packCandidates = [
9132
+ { key: "fullJson", file: "full-codebase.json", label: "JSON", read: jsonPackBodies },
9133
+ { key: "fullXml", file: "full-codebase.xml", label: "XML", read: xmlPackBodies },
9134
+ { key: "fullMarkdown", file: "full-codebase.md", label: "markdown", read: markdownPackBodies }
9135
+ ];
9136
+ const packsWanted = packCandidates.filter((pack) => manifest.artifacts?.[pack.key] != null);
9137
+ if (packsWanted.length > 0) {
9138
+ const renderedPaths = new Map(
9139
+ manifest.files.map((file) => [escapeControls(file.relativePath), file.relativePath])
9140
+ );
9141
+ const packProblems = [];
9142
+ let packBodies = 0;
9143
+ let packSkipped = 0;
9144
+ for (const pack of packsWanted) {
9145
+ const text = readText(path5__namespace.join(snapshotDir, pack.file));
9146
+ if (text === null) continue;
9147
+ const bodies = pack.read(text);
9148
+ if (bodies === null) {
9149
+ packProblems.push(pack.file + " could not be read as a file pack");
9150
+ continue;
9151
+ }
9152
+ for (const [entryPath, body] of bodies) {
9153
+ const relativePath = pack.key === "fullMarkdown" ? renderedPaths.get(entryPath) ?? entryPath : entryPath;
9154
+ const file = fileByPath.get(relativePath);
9155
+ if (file === void 0) continue;
9156
+ if (file.inclusionMode === "preview" || file.inclusionMode === "signatures") {
9157
+ packSkipped += 1;
9158
+ continue;
9159
+ }
9160
+ const partBody = bodyByPath.get(relativePath);
9161
+ if (partBody === void 0) continue;
9162
+ packBodies += 1;
9163
+ const normalised = pack.key === "fullMarkdown" ? body : emittedBody(body);
9164
+ if (normalised !== partBody) {
9165
+ packProblems.push(pack.file + ": " + relativePath + " holds a different body");
9166
+ }
9167
+ }
9168
+ }
9169
+ checks.push(
9170
+ packProblems.length === 0 ? check(
9171
+ "packs.bodies",
9172
+ "Every pack body is the body the parts carry",
9173
+ "critical",
9174
+ "pass",
9175
+ packBodies + " full body/bodies match across " + packsWanted.length + " pack(s)" + (packSkipped > 0 ? "; " + packSkipped + " preview/signature body(s) are whole-file by design." : ".")
9176
+ ) : check(
9177
+ "packs.bodies",
9178
+ "Every pack body is the body the parts carry",
9179
+ "critical",
9180
+ "fail",
9181
+ packProblems.length + " body/bodies differ: " + sample(packProblems)
9182
+ )
9183
+ );
9184
+ }
9185
+ if (options.deep !== true) {
9186
+ checks.push(
9187
+ check(
9188
+ "fidelity.bodies",
9189
+ "Every full body replays from the source bytes",
9190
+ "critical",
9191
+ "skip",
9192
+ "Run health --deep to replay each full body against the file on disk."
9193
+ )
9194
+ );
9195
+ } else {
9196
+ const replayProblems = [];
9197
+ let replayed = 0;
9198
+ let unreplayable = 0;
9199
+ for (const file of manifest.files) {
9200
+ if (file.inclusionMode !== "full" || file.emptyLinesRemoved === true) {
9201
+ unreplayable += 1;
9202
+ continue;
9203
+ }
9204
+ const body = bodyByPath.get(file.relativePath);
9205
+ if (body === void 0) {
9206
+ unreplayable += 1;
9207
+ continue;
9208
+ }
9209
+ const bytes = readBytes(path5__namespace.join(repoDir, file.relativePath));
9210
+ if (bytes === null || sha256(bytes) !== file.hashSha256) {
9211
+ unreplayable += 1;
9212
+ continue;
9213
+ }
9214
+ const decoded = decodeText(bytes);
9215
+ if (decoded.binary) {
9216
+ replayProblems.push(file.relativePath + " is binary on disk");
9217
+ continue;
9218
+ }
9219
+ const expected = emittedBody(decoded.text);
9220
+ if (expected === body) {
9221
+ replayed += 1;
9222
+ continue;
9223
+ }
9224
+ const line = firstBodyMismatch(expected, body);
9225
+ if (line === null) {
9226
+ replayed += 1;
9227
+ continue;
9228
+ }
9229
+ replayProblems.push(file.relativePath + " line " + line + " is not the source line");
9230
+ }
9231
+ checks.push(
9232
+ replayProblems.length === 0 ? check(
9233
+ "fidelity.bodies",
9234
+ "Every full body replays from the source bytes",
9235
+ "critical",
9236
+ "pass",
9237
+ replayed + " full body/bodies replayed byte-for-byte (redaction allowed); " + unreplayable + " not replayable by design or because the file moved."
9238
+ ) : check(
9239
+ "fidelity.bodies",
9240
+ "Every full body replays from the source bytes",
9241
+ "critical",
9242
+ "fail",
9243
+ replayProblems.length + " body/bodies disagree with the source: " + sample(replayProblems)
9244
+ )
9245
+ );
9246
+ }
8655
9247
  const indexParent = path5__namespace.dirname(snapshotDir);
8656
9248
  const indexPath = path5__namespace.join(indexParent, "WORKSPACE.json");
8657
9249
  if (fs2__namespace.existsSync(indexPath)) {
@@ -8774,13 +9366,15 @@ function auditSnapshot(options) {
8774
9366
  );
8775
9367
  const leakedFrom = [];
8776
9368
  let compared = 0;
9369
+ const artifactTexts = readArtifactTexts(snapshotDir);
9370
+ const artifactContains = (token) => artifactTexts.some((text) => text.includes(token));
8777
9371
  for (const record of skippedSensitive.slice(0, 40)) {
8778
9372
  if (record.path.includes("[REDACTED") || compared > 400) continue;
8779
9373
  const text = readText(path5__namespace.join(repoDir, record.path));
8780
9374
  if (text === null) continue;
8781
9375
  for (const token of secretTokens(text)) {
8782
9376
  compared += 1;
8783
- if (artifactTextContains(snapshotDir, token)) leakedFrom.push(record.path);
9377
+ if (artifactContains(token)) leakedFrom.push(record.path);
8784
9378
  }
8785
9379
  }
8786
9380
  checks.push(
@@ -8815,9 +9409,13 @@ function auditSnapshot(options) {
8815
9409
  )
8816
9410
  );
8817
9411
  let recomputed = 0;
9412
+ const partTokens = /* @__PURE__ */ new Map();
8818
9413
  for (const part of manifest.parts) {
8819
- const text = readText(path5__namespace.join(snapshotDir, "parts", part.filename));
8820
- if (text !== null) recomputed += estimateTokens(text);
9414
+ const text = partTexts.get(part.filename);
9415
+ if (text === void 0) continue;
9416
+ const tokens = estimateTokens(text);
9417
+ partTokens.set(part.filename, tokens);
9418
+ recomputed += tokens;
8821
9419
  }
8822
9420
  const recorded = manifest.totals.estimatedTokens ?? null;
8823
9421
  checks.push(
@@ -8841,6 +9439,22 @@ function auditSnapshot(options) {
8841
9439
  "Recorded " + recorded + ", recomputed " + recomputed + ": the manifest no longer describes these parts."
8842
9440
  )
8843
9441
  );
9442
+ const partSizes = [...partTokens.values()];
9443
+ const largestPart = partSizes.length === 0 ? 0 : Math.max(...partSizes);
9444
+ const largestFile = manifest.files.reduce((largest, file) => {
9445
+ const body = bodyByPath.get(file.relativePath);
9446
+ return body === void 0 ? largest : Math.max(largest, estimateTokens(body));
9447
+ }, 0);
9448
+ const fits = (window) => partSizes.filter((tokens) => tokens <= window).length;
9449
+ checks.push(
9450
+ check(
9451
+ "tokens.fit",
9452
+ "The parts fit a context window",
9453
+ "warning",
9454
+ largestPart > 2e5 || largestFile > 2e5 ? "warn" : "pass",
9455
+ manifest.parts.length + " part(s); largest about " + largestPart + " tokens, " + fits(32e3) + " fit 32k, " + fits(128e3) + " fit 128k, " + fits(2e5) + " fit 200k; largest single file about " + largestFile + " tokens."
9456
+ )
9457
+ );
8844
9458
  const overBudget = manifest.parts.filter(
8845
9459
  (part) => part.byteSize > manifest.budgets.maxPartBytes
8846
9460
  );
@@ -10937,6 +11551,10 @@ var healthTool = {
10937
11551
  minimum: 1024,
10938
11552
  description: "Cap on the text the secret and host-path scans read (default 8 MB)."
10939
11553
  },
11554
+ deep: {
11555
+ type: "boolean",
11556
+ description: "Replay every full body against the source on disk. Slower, and catches a generator that wrote the wrong bytes."
11557
+ },
10940
11558
  root: ROOT_PROPERTY,
10941
11559
  outDir: OUT_DIR_PROPERTY
10942
11560
  },
@@ -10958,7 +11576,8 @@ var healthTool = {
10958
11576
  const report2 = auditSnapshot({
10959
11577
  snapshotDir: path5__namespace.resolve(workspace.root, workspace.config.outDir),
10960
11578
  repoDir: workspace.root,
10961
- ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {}
11579
+ ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
11580
+ ...args.deep === true ? { deep: true } : {}
10962
11581
  });
10963
11582
  const lines = [
10964
11583
  "Health: " + report2.score + "/100 (" + report2.counts.pass + " passed, " + report2.counts.warn + " warning(s), " + report2.counts.fail + " failed)",
@@ -12088,7 +12707,7 @@ var COMMAND_OPTION_SCOPE = {
12088
12707
  ],
12089
12708
  // The health audit resolves the config only to find the output directory; --strict decides the
12090
12709
  // exit code, and every other setting would be a promise the command does not keep.
12091
- health: ["cwd", "out-dir", "format", "strict", "all-members", "no-update-check", "help"],
12710
+ health: ["cwd", "out-dir", "format", "strict", "all-members", "deep", "no-update-check", "help"],
12092
12711
  validate: VALIDATE_OPTIONS,
12093
12712
  // `report` reads `manifest.json` and prints what is there; a generation setting would change
12094
12713
  // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
@@ -12343,7 +12962,7 @@ function buildAgentContract() {
12343
12962
  {
12344
12963
  name: "health",
12345
12964
  aliases: [],
12346
- summary: "Audit a generated snapshot against the repository it describes: manifest shape, part hashes, artifact claims, unmasked secrets in any artifact, values from excluded sensitive files, host paths, the recorded token count and freshness. Exits 0 clean, 1 when a check fails, 2 with --strict when a critical check fails.",
12965
+ summary: "Audit a generated snapshot against the repository it describes: manifest shape, part hashes, artifact claims, summary and report truthfulness, pack bodies, unmasked secrets in any artifact, values from excluded sensitive files, host paths, the recorded token count and freshness; --deep also replays every full body from the source. Exits 0 clean, 1 when a check fails, 2 with --strict when a critical check fails.",
12347
12966
  positionals: [],
12348
12967
  exits: [0, 1, 2]
12349
12968
  },
@@ -12714,6 +13333,13 @@ function buildAgentContract() {
12714
13333
  appliesTo: optionAppliesTo("strict"),
12715
13334
  summary: "health only: exit 2 when a critical check fails, and 1 when a warning is the only thing left. Without it a critical check exits 1 and warnings exit 0."
12716
13335
  },
13336
+ {
13337
+ flag: "--deep",
13338
+ type: "boolean",
13339
+ default: false,
13340
+ appliesTo: optionAppliesTo("deep"),
13341
+ summary: "health only: replay every full body from the source bytes on disk and compare it with the part. The only allowed difference is a redaction marker. Costs one full read of the tree."
13342
+ },
12717
13343
  {
12718
13344
  flag: "--changed-since",
12719
13345
  type: "string",