codebase-snapshot 0.20.0 → 0.20.2

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