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/index.cjs CHANGED
@@ -4020,7 +4020,7 @@ function applySpansKeepingQuotes(line, spans) {
4020
4020
 
4021
4021
  // src/version.ts
4022
4022
  var GENERATOR_NAME = "codebase-snapshot";
4023
- var GENERATOR_VERSION = "0.20.0";
4023
+ var GENERATOR_VERSION = "0.20.3";
4024
4024
  var SCHEMA_VERSION = "3.0.0";
4025
4025
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4026
4026
  function isOurGeneratorName(name) {
@@ -6874,7 +6874,10 @@ function generateMonolithJson(manifest, filesWithContent) {
6874
6874
  ...manifest,
6875
6875
  selfReference: "This manifest is embedded in full-codebase.json, which cannot record its own digest. manifest.json holds the byteSize and sha256 of this file."
6876
6876
  };
6877
- return JSON.stringify({ manifest: embedded, files: filesWithContent }, null, 2);
6877
+ const files = filesWithContent.map(
6878
+ (file) => file.content === void 0 ? file : { ...file, content: file.content.replace(/\r\n|\r/g, "\n") }
6879
+ );
6880
+ return JSON.stringify({ manifest: embedded, files }, null, 2);
6878
6881
  }
6879
6882
  function xmlAttribute(value) {
6880
6883
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -10257,13 +10260,14 @@ function secretTokens(text2) {
10257
10260
  }
10258
10261
  return [...tokens];
10259
10262
  }
10260
- function artifactTextContains(snapshotDir, token) {
10263
+ function readArtifactTexts(snapshotDir) {
10264
+ const texts = [];
10261
10265
  for (const relative13 of walk(snapshotDir)) {
10262
10266
  if (!TEXT_ARTIFACT.test(relative13)) continue;
10263
10267
  const text2 = readText2(path25__namespace.join(snapshotDir, relative13));
10264
- if (text2 !== null && text2.includes(token)) return true;
10268
+ if (text2 !== null) texts.push(text2);
10265
10269
  }
10266
- return false;
10270
+ return texts;
10267
10271
  }
10268
10272
  function findHostPaths(snapshotDir, repoDir) {
10269
10273
  const patterns = [
@@ -10304,6 +10308,135 @@ function staleAgainstRepository(manifest, repoDir) {
10304
10308
  if (head === recorded) return null;
10305
10309
  return "HEAD is " + head.slice(0, 8) + " but the snapshot was generated at " + recorded.slice(0, 8) + "; regenerate before trusting it.";
10306
10310
  }
10311
+ function summaryClaims(summary) {
10312
+ if ("imports" in summary) {
10313
+ const fields = [
10314
+ ["imports", summary.imports],
10315
+ ["reExports", summary.reExports],
10316
+ ["exports", summary.exports],
10317
+ ["functions", summary.functions],
10318
+ ["classes", summary.classes],
10319
+ ["interfaces", summary.interfaces],
10320
+ ["types", summary.types],
10321
+ ["enums", summary.enums],
10322
+ ["variables", summary.variables],
10323
+ ["reactComponents", summary.reactComponents],
10324
+ ["hooks", summary.hooks],
10325
+ ["routeHandlers", summary.routeHandlers]
10326
+ ];
10327
+ const claims = [];
10328
+ for (const [field, values] of fields) {
10329
+ for (const value of values) {
10330
+ if (typeof value !== "string" || value === "") continue;
10331
+ if (field === "routeHandlers" && value.includes(" ")) {
10332
+ const route = value.slice(value.indexOf(" ") + 1).trim();
10333
+ if (route !== "") claims.push({ field, value: route });
10334
+ continue;
10335
+ }
10336
+ claims.push({ field, value });
10337
+ }
10338
+ }
10339
+ return claims;
10340
+ }
10341
+ if ("keys" in summary) {
10342
+ return [...summary.keys, ...summary.sampleKeys].map((key) => ({
10343
+ field: "keys",
10344
+ value: '"' + key + '"'
10345
+ }));
10346
+ }
10347
+ return summary.headings.map((heading) => ({ field: "headings", value: heading }));
10348
+ }
10349
+ function reportNumber(text2, label) {
10350
+ const match = new RegExp("\\*\\*" + escapeRegExp(label) + ":\\*\\* `([0-9][0-9,]*)`").exec(text2);
10351
+ return match === null ? null : Number(match[1].replace(/,/g, ""));
10352
+ }
10353
+ function reportMib(text2, label) {
10354
+ const match = new RegExp(
10355
+ "\\*\\*" + escapeRegExp(label) + ":\\*\\* `([0-9]+(?:\\.[0-9]+)?) MiB`"
10356
+ ).exec(text2);
10357
+ return match === null ? null : Number(match[1]);
10358
+ }
10359
+ function maskCompatible(sourceLine, bodyLine) {
10360
+ const normalised = bodyLine.split(PEM_REDACTION_MARKER).join(REDACTION_MARKER);
10361
+ let cursor = 0;
10362
+ for (const piece of normalised.split(REDACTION_MARKER)) {
10363
+ if (piece === "") continue;
10364
+ const at = sourceLine.indexOf(piece, cursor);
10365
+ if (at === -1) return false;
10366
+ cursor = at + piece.length;
10367
+ }
10368
+ return true;
10369
+ }
10370
+ function firstBodyMismatch(expected, actual) {
10371
+ const sourceLines = expected.split("\n");
10372
+ const bodyLines = actual.split("\n");
10373
+ const shared = Math.min(sourceLines.length, bodyLines.length);
10374
+ for (let index = 0; index < shared; index += 1) {
10375
+ if (sourceLines[index] === bodyLines[index]) continue;
10376
+ if (!bodyLines[index].includes(REDACTION_MARKER) && !bodyLines[index].includes(PEM_REDACTION_MARKER)) {
10377
+ return index + 1;
10378
+ }
10379
+ if (!maskCompatible(sourceLines[index], bodyLines[index])) return index + 1;
10380
+ }
10381
+ return sourceLines.length === bodyLines.length ? null : shared + 1;
10382
+ }
10383
+ function decodeXmlAttribute(value) {
10384
+ return value.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
10385
+ }
10386
+ function jsonPackBodies(text2) {
10387
+ try {
10388
+ const parsed = JSON.parse(text2);
10389
+ if (!Array.isArray(parsed?.files)) return null;
10390
+ const bodies = /* @__PURE__ */ new Map();
10391
+ for (const entry of parsed.files) {
10392
+ if (typeof entry?.relativePath !== "string" || typeof entry.content !== "string") continue;
10393
+ bodies.set(entry.relativePath, entry.content);
10394
+ }
10395
+ return bodies;
10396
+ } catch {
10397
+ return null;
10398
+ }
10399
+ }
10400
+ function xmlPackBodies(text2) {
10401
+ const bodies = /* @__PURE__ */ new Map();
10402
+ const filePattern = / <file path="([^"]*)"[^>]*>\n([\s\S]*?)\n <\/file>/g;
10403
+ for (const match of text2.matchAll(filePattern)) {
10404
+ const content = [...match[2].matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)].map((part) => part[1]).join("");
10405
+ bodies.set(decodeXmlAttribute(match[1]), content);
10406
+ }
10407
+ return bodies.size === 0 ? null : bodies;
10408
+ }
10409
+ function markdownPackBodies(text2) {
10410
+ const bodies = /* @__PURE__ */ new Map();
10411
+ const lines = text2.split("\n");
10412
+ let index = 0;
10413
+ while (index < lines.length) {
10414
+ if (!lines[index].startsWith("## File: ")) {
10415
+ index += 1;
10416
+ continue;
10417
+ }
10418
+ const filePath = lines[index].slice("## File: ".length).trim();
10419
+ let cursor = index + 1;
10420
+ while (cursor < lines.length && !/^`{3,}/.test(lines[cursor])) {
10421
+ if (lines[cursor].startsWith("## File: ")) break;
10422
+ cursor += 1;
10423
+ }
10424
+ const fence = /^(`{3,})/.exec(lines[cursor] ?? "");
10425
+ if (fence === null) {
10426
+ index = cursor + 1;
10427
+ continue;
10428
+ }
10429
+ const body = [];
10430
+ let bodyLine = cursor + 1;
10431
+ while (bodyLine < lines.length && lines[bodyLine] !== fence[1]) {
10432
+ body.push(lines[bodyLine]);
10433
+ bodyLine += 1;
10434
+ }
10435
+ bodies.set(filePath, body.join("\n"));
10436
+ index = bodyLine + 1;
10437
+ }
10438
+ return bodies.size === 0 ? null : bodies;
10439
+ }
10307
10440
  function auditSnapshot(options) {
10308
10441
  const snapshotDir = path25__namespace.resolve(options.snapshotDir);
10309
10442
  const repoDir = path25__namespace.resolve(options.repoDir);
@@ -10510,6 +10643,272 @@ function auditSnapshot(options) {
10510
10643
  bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
10511
10644
  )
10512
10645
  );
10646
+ const fileByPath = new Map(manifest.files.map((file) => [file.relativePath, file]));
10647
+ const partTexts = /* @__PURE__ */ new Map();
10648
+ const partSections = /* @__PURE__ */ new Map();
10649
+ const bodyByPath = /* @__PURE__ */ new Map();
10650
+ const anchorToPath = new Map(
10651
+ manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
10652
+ );
10653
+ for (const part of manifest.parts) {
10654
+ const partText = readText2(path25__namespace.join(snapshotDir, "parts", part.filename));
10655
+ if (partText === null) continue;
10656
+ const sections = parsePartSections(partText);
10657
+ partTexts.set(part.filename, partText);
10658
+ partSections.set(part.filename, sections);
10659
+ for (const section of sections) {
10660
+ if (section.anchor === null) continue;
10661
+ const relativePath = anchorToPath.get(section.anchor);
10662
+ if (relativePath !== void 0) bodyByPath.set(relativePath, section.body);
10663
+ }
10664
+ }
10665
+ const summaryProblems = [];
10666
+ let claimsChecked = 0;
10667
+ let summarisedFiles = 0;
10668
+ for (const file of manifest.files) {
10669
+ if (file.summary === void 0) continue;
10670
+ if (file.inclusionMode === "preview" || file.emptyLinesRemoved === true) continue;
10671
+ const body = bodyByPath.get(file.relativePath);
10672
+ if (body === void 0) continue;
10673
+ summarisedFiles += 1;
10674
+ for (const claim of summaryClaims(file.summary)) {
10675
+ if (claim.value.includes(REDACTION_MARKER)) continue;
10676
+ claimsChecked += 1;
10677
+ if (!body.includes(claim.value)) {
10678
+ summaryProblems.push(file.relativePath + " (" + claim.field + ")");
10679
+ }
10680
+ }
10681
+ }
10682
+ checks.push(
10683
+ summarisedFiles === 0 ? check(
10684
+ "summary.truth",
10685
+ "Every summary claim appears in the body",
10686
+ "critical",
10687
+ "skip",
10688
+ "No summarised file could be compared with a body."
10689
+ ) : summaryProblems.length === 0 ? check(
10690
+ "summary.truth",
10691
+ "Every summary claim appears in the body",
10692
+ "critical",
10693
+ "pass",
10694
+ claimsChecked + " claim(s) across " + summarisedFiles + " file(s) are present in the parts."
10695
+ ) : check(
10696
+ "summary.truth",
10697
+ "Every summary claim appears in the body",
10698
+ "critical",
10699
+ "fail",
10700
+ summaryProblems.length + " claim(s) name something the body does not contain: " + sample(summaryProblems)
10701
+ )
10702
+ );
10703
+ const reportProblems = [];
10704
+ let reportClaims = 0;
10705
+ const compareNumber = (label, actual, expected) => {
10706
+ if (actual === null) return;
10707
+ reportClaims += 1;
10708
+ if (actual !== expected) {
10709
+ reportProblems.push(label + " says " + actual + ", the manifest says " + expected);
10710
+ }
10711
+ };
10712
+ const compareMib = (label, actual, bytes) => {
10713
+ if (actual === null) return;
10714
+ reportClaims += 1;
10715
+ const expected = Number((bytes / (1024 * 1024)).toFixed(2));
10716
+ if (Math.abs(actual - expected) > 0.011) {
10717
+ reportProblems.push(label + " says " + actual + " MiB, the manifest says " + expected);
10718
+ }
10719
+ };
10720
+ if (manifest.artifacts?.readme != null) {
10721
+ const text2 = readText2(path25__namespace.join(snapshotDir, "README.md"));
10722
+ if (text2 === null) {
10723
+ reportProblems.push("README.md is recorded but unreadable");
10724
+ } else {
10725
+ compareNumber("README total files", reportNumber(text2, "Total Tracked Files"), manifest.counts.totalFiles);
10726
+ compareNumber("README source lines", reportNumber(text2, "Source Lines"), manifest.counts.totalLines);
10727
+ compareNumber(
10728
+ "README emitted lines",
10729
+ reportNumber(text2, "Emitted Lines"),
10730
+ manifest.totals.emittedLines ?? manifest.counts.totalLines
10731
+ );
10732
+ const partsWritten = manifest.config.artifacts?.parts !== false;
10733
+ compareNumber("README part count", reportNumber(text2, "Part Count"), partsWritten ? manifest.counts.partsCount : 0);
10734
+ compareMib("README total size", reportMib(text2, "Total Size"), manifest.counts.totalSizeBytes);
10735
+ compareMib("README emitted content", reportMib(text2, "Emitted Content"), manifest.totals.totalContentBytes);
10736
+ const rows = [...text2.matchAll(/^\| \[([^\]]+)\]\(parts\/([^)]+)\) \| (\d+) \| ([0-9.]+) KB \|/gm)];
10737
+ if (rows.length > 0) {
10738
+ reportClaims += rows.length;
10739
+ if (rows.length !== manifest.parts.length) {
10740
+ reportProblems.push("README tables " + rows.length + " part(s), the manifest holds " + manifest.parts.length);
10741
+ }
10742
+ for (const row of rows) {
10743
+ const part = manifest.parts.find((candidate) => candidate.filename === row[2]);
10744
+ if (part === void 0) {
10745
+ reportProblems.push("README names " + row[2] + ", which the manifest does not hold");
10746
+ continue;
10747
+ }
10748
+ if (Number(row[3]) !== part.fileCount) {
10749
+ reportProblems.push("README " + row[2] + " says " + row[3] + " file(s), the manifest says " + part.fileCount);
10750
+ }
10751
+ const stated = Number(row[4]);
10752
+ const expected = Number((part.byteSize / 1024).toFixed(1));
10753
+ if (Math.abs(stated - expected) > 0.11) {
10754
+ reportProblems.push("README " + row[2] + " says " + stated + " KB, the manifest says " + expected);
10755
+ }
10756
+ }
10757
+ }
10758
+ }
10759
+ }
10760
+ if (manifest.artifacts?.prompt != null) {
10761
+ const text2 = readText2(path25__namespace.join(snapshotDir, "PROMPT.md"));
10762
+ if (text2 === null) {
10763
+ reportProblems.push("PROMPT.md is recorded but unreadable");
10764
+ } else {
10765
+ const fingerprint = /^- Fingerprint: \x60([0-9a-f]{12,64})\x60/m.exec(text2);
10766
+ if (fingerprint !== null) {
10767
+ reportClaims += 1;
10768
+ if (fingerprint[1] !== manifest.fingerprint) reportProblems.push("PROMPT names a different fingerprint");
10769
+ }
10770
+ const generated = /^- Generated: \x60([^\x60]+)\x60 from branch \x60([^\x60]+)\x60 at commit \x60([0-9a-f]+)\x60/m.exec(text2);
10771
+ if (generated !== null) {
10772
+ reportClaims += 3;
10773
+ if (generated[1] !== manifest.generatedAt) reportProblems.push("PROMPT names a different generation time");
10774
+ if (generated[2] !== manifest.git.branch) reportProblems.push("PROMPT names a different branch");
10775
+ if (!manifest.git.commit.startsWith(generated[3])) reportProblems.push("PROMPT names a different commit");
10776
+ }
10777
+ const validation = /^- Validation: the generation-time check was \x60([^\x60]+)\x60/m.exec(text2);
10778
+ if (validation !== null) {
10779
+ reportClaims += 1;
10780
+ if (validation[1] !== manifest.validation.status) reportProblems.push("PROMPT quotes a different validation status");
10781
+ }
10782
+ const partsLine = /^- Parts: ([\d,]+) at a ([\d,]+) KB ceiling/m.exec(text2);
10783
+ if (partsLine !== null) {
10784
+ reportClaims += 2;
10785
+ if (Number(partsLine[1].replace(/,/g, "")) !== manifest.parts.length) {
10786
+ reportProblems.push("PROMPT says " + partsLine[1] + " part(s), the manifest holds " + manifest.parts.length);
10787
+ }
10788
+ const ceiling = Math.round(manifest.budgets.maxPartBytes / 1024);
10789
+ if (Number(partsLine[2].replace(/,/g, "")) !== ceiling) {
10790
+ reportProblems.push("PROMPT says a " + partsLine[2] + " KB ceiling, the manifest says " + ceiling);
10791
+ }
10792
+ }
10793
+ for (const row of text2.matchAll(/^ - \x60([^\x60]+)\x60 - ([\d,]+) file\(s\)$/gm)) {
10794
+ reportClaims += 1;
10795
+ const part = manifest.parts.find((candidate) => candidate.filename === row[1]);
10796
+ if (part === void 0) {
10797
+ reportProblems.push("PROMPT names " + row[1] + ", which the manifest does not hold");
10798
+ } else if (Number(row[2].replace(/,/g, "")) !== part.fileCount) {
10799
+ reportProblems.push("PROMPT " + row[1] + " says " + row[2] + " file(s), the manifest says " + part.fileCount);
10800
+ }
10801
+ }
10802
+ const coverage = /^- ([\d,]+) paths were found; ([\d,]+) (?:is|are) in the parts and ([\d,]+) (?:was|were) skipped/m.exec(text2);
10803
+ if (coverage !== null) {
10804
+ reportClaims += 3;
10805
+ if (Number(coverage[1].replace(/,/g, "")) !== manifest.totals.candidateFiles) {
10806
+ reportProblems.push("PROMPT says " + coverage[1] + " paths were found, the manifest says " + manifest.totals.candidateFiles);
10807
+ }
10808
+ if (Number(coverage[2].replace(/,/g, "")) !== manifest.totals.includedFiles) {
10809
+ reportProblems.push("PROMPT says " + coverage[2] + " are in the parts, the manifest says " + manifest.totals.includedFiles);
10810
+ }
10811
+ if (Number(coverage[3].replace(/,/g, "")) !== manifest.counts.skippedCount) {
10812
+ reportProblems.push("PROMPT says " + coverage[3] + " were skipped, the manifest says " + manifest.counts.skippedCount);
10813
+ }
10814
+ }
10815
+ const partial = /^- Partial files: (none|[\d,]+)\./m.exec(text2);
10816
+ if (partial !== null) {
10817
+ reportClaims += 1;
10818
+ const stated = partial[1] === "none" ? 0 : Number(partial[1].replace(/,/g, ""));
10819
+ if (stated !== manifest.incomplete.length) {
10820
+ reportProblems.push("PROMPT says " + partial[1] + " partial file(s), the manifest holds " + manifest.incomplete.length);
10821
+ }
10822
+ }
10823
+ if (text2.includes("- Redacted: no line matched a secret rule.")) {
10824
+ reportClaims += 1;
10825
+ if (manifest.totals.redactedLines !== 0) {
10826
+ reportProblems.push("PROMPT says nothing was redacted, the manifest says " + manifest.totals.redactedLines);
10827
+ }
10828
+ } else {
10829
+ const redacted = /^- Redacted: ([\d,]+) line\(s\) had values masked/m.exec(text2);
10830
+ if (redacted !== null) {
10831
+ reportClaims += 1;
10832
+ if (Number(redacted[1].replace(/,/g, "")) !== manifest.totals.redactedLines) {
10833
+ reportProblems.push("PROMPT says " + redacted[1] + " redacted line(s), the manifest says " + manifest.totals.redactedLines);
10834
+ }
10835
+ }
10836
+ }
10837
+ const layersLine = /^- Layers, by file count: (.+)$/m.exec(text2);
10838
+ if (layersLine !== null) {
10839
+ for (const layer2 of layersLine[1].matchAll(/\x60([^\x60]+)\x60 ([\d,]+)/g)) {
10840
+ reportClaims += 1;
10841
+ const expected = manifest.layers[layer2[1]] ?? 0;
10842
+ if (Number(layer2[2].replace(/,/g, "")) !== expected) {
10843
+ reportProblems.push("PROMPT layer " + layer2[1] + " says " + layer2[2] + ", the manifest says " + expected);
10844
+ }
10845
+ }
10846
+ }
10847
+ }
10848
+ }
10849
+ checks.push(
10850
+ reportProblems.length > 0 ? check(
10851
+ "report.truth",
10852
+ "The reports quote this run, not another",
10853
+ "critical",
10854
+ "fail",
10855
+ reportProblems.length + " disagreement(s): " + sample(reportProblems)
10856
+ ) : reportClaims === 0 ? check(
10857
+ "report.truth",
10858
+ "The reports quote this run, not another",
10859
+ "critical",
10860
+ "skip",
10861
+ "No report in the current shape could be compared with the manifest."
10862
+ ) : check(
10863
+ "report.truth",
10864
+ "The reports quote this run, not another",
10865
+ "critical",
10866
+ "pass",
10867
+ reportClaims + " figure(s) in README.md and PROMPT.md agree with the manifest."
10868
+ )
10869
+ );
10870
+ const indexProblems = [];
10871
+ const indexedPaths = /* @__PURE__ */ new Set();
10872
+ const checkIndexed = (kind, relativePath, part) => {
10873
+ const file = fileByPath.get(relativePath);
10874
+ if (file === void 0) {
10875
+ indexProblems.push(kind + " names " + relativePath + ", which is not in files[]");
10876
+ return;
10877
+ }
10878
+ if (part !== void 0 && file.part !== part) {
10879
+ indexProblems.push(kind + " puts " + relativePath + " in " + part + ", the manifest says " + file.part);
10880
+ }
10881
+ };
10882
+ for (const route of manifest.indexes.routes) checkIndexed("routes", route.path, route.part);
10883
+ for (const component of manifest.indexes.components) checkIndexed("components", component.path, component.part);
10884
+ for (const handler of manifest.indexes.handlers) checkIndexed("handlers", handler.path, handler.part);
10885
+ for (const directive of manifest.indexes.directives) checkIndexed("directives", directive.path);
10886
+ for (const entry of manifest.indexes.imports.byFile) {
10887
+ checkIndexed("imports.byFile", entry.path);
10888
+ if (indexedPaths.has(entry.path)) indexProblems.push("imports.byFile lists " + entry.path + " twice");
10889
+ indexedPaths.add(entry.path);
10890
+ }
10891
+ for (const entry of manifest.indexes.imports.centralFiles) {
10892
+ checkIndexed("centralFiles", entry.path);
10893
+ if (entry.importedByCount < 1) {
10894
+ indexProblems.push("centralFiles says " + entry.path + " has " + entry.importedByCount + " importer(s)");
10895
+ }
10896
+ }
10897
+ checks.push(
10898
+ indexProblems.length === 0 ? check(
10899
+ "indexes.consistent",
10900
+ "Every index entry names a file in the snapshot",
10901
+ "critical",
10902
+ "pass",
10903
+ 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."
10904
+ ) : check(
10905
+ "indexes.consistent",
10906
+ "Every index entry names a file in the snapshot",
10907
+ "critical",
10908
+ "fail",
10909
+ indexProblems.length + " index problem(s): " + sample(indexProblems)
10910
+ )
10911
+ );
10513
10912
  const packReaders = [
10514
10913
  {
10515
10914
  key: "fullJson",
@@ -10586,9 +10985,8 @@ function auditSnapshot(options) {
10586
10985
  const bodyProblems = [];
10587
10986
  let bodiesChecked = 0;
10588
10987
  for (const part of manifest.parts) {
10589
- const partText = readText2(path25__namespace.join(snapshotDir, "parts", part.filename));
10590
- if (partText === null) continue;
10591
- const sections = parsePartSections(partText);
10988
+ const sections = partSections.get(part.filename);
10989
+ if (sections === void 0) continue;
10592
10990
  for (const file of manifest.files) {
10593
10991
  if (file.part !== part.filename) continue;
10594
10992
  const section = findSection(sections, file.relativePath);
@@ -10596,6 +10994,7 @@ function auditSnapshot(options) {
10596
10994
  bodyProblems.push(file.relativePath + " has no section in " + part.filename);
10597
10995
  continue;
10598
10996
  }
10997
+ bodyByPath.set(file.relativePath, section.body);
10599
10998
  bodiesChecked += 1;
10600
10999
  const bytes = Buffer.byteLength(section.body, "utf8");
10601
11000
  const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
@@ -10621,6 +11020,198 @@ function auditSnapshot(options) {
10621
11020
  bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
10622
11021
  )
10623
11022
  );
11023
+ const structureProblems = [];
11024
+ let sectionsChecked = 0;
11025
+ for (const part of manifest.parts) {
11026
+ const text2 = partTexts.get(part.filename);
11027
+ const sections = partSections.get(part.filename);
11028
+ if (text2 === void 0 || sections === void 0) continue;
11029
+ const header = /^# Codebase Snapshot Part (\d+) of (\d+)$/m.exec(text2);
11030
+ if (header !== null) {
11031
+ if (Number(header[1]) !== part.index) {
11032
+ structureProblems.push(part.filename + " says part " + header[1] + ", the manifest says " + part.index);
11033
+ }
11034
+ if (Number(header[2]) !== manifest.parts.length) {
11035
+ structureProblems.push(part.filename + " says " + header[2] + " parts, the manifest holds " + manifest.parts.length);
11036
+ }
11037
+ }
11038
+ const filesLine = /^- Files: (\d+)$/m.exec(text2);
11039
+ if (filesLine !== null && Number(filesLine[1]) !== part.fileCount) {
11040
+ structureProblems.push(part.filename + " says " + filesLine[1] + " file(s), the manifest says " + part.fileCount);
11041
+ }
11042
+ const fingerprintLine = /^- Content Fingerprint: (\S+)$/m.exec(text2);
11043
+ if (fingerprintLine !== null && fingerprintLine[1] !== manifest.fingerprint) {
11044
+ structureProblems.push(part.filename + " names a different content fingerprint");
11045
+ }
11046
+ const tokenLine = /^- Estimated Tokens: ~([0-9,]+)$/m.exec(text2);
11047
+ if (tokenLine !== null && Number(tokenLine[1].replace(/,/g, "")) !== part.estimatedTokens) {
11048
+ structureProblems.push(part.filename + " says " + tokenLine[1] + " tokens, the manifest says " + part.estimatedTokens);
11049
+ }
11050
+ if (sections.length !== part.fileCount) {
11051
+ structureProblems.push(part.filename + " holds " + sections.length + " section(s), the manifest says " + part.fileCount);
11052
+ }
11053
+ const expectedAnchors = new Set(part.includedFiles.map((entry) => anchorForPath(entry.relativePath)));
11054
+ for (const section of sections) {
11055
+ if (section.anchor === null || !expectedAnchors.has(section.anchor)) {
11056
+ structureProblems.push(part.filename + " holds a section for " + section.path + ", which the manifest does not list");
11057
+ }
11058
+ }
11059
+ const expectedOrder = part.includedFiles.map((entry) => anchorForPath(entry.relativePath)).join("\n");
11060
+ const actualOrder = sections.map((section) => section.anchor).filter((anchor) => anchor !== null).join("\n");
11061
+ if (actualOrder !== expectedOrder) {
11062
+ structureProblems.push(part.filename + " orders its sections differently than the manifest");
11063
+ }
11064
+ for (const entry of part.includedFiles) {
11065
+ const file = fileByPath.get(entry.relativePath);
11066
+ if (file === void 0) continue;
11067
+ const section = findSection(sections, entry.relativePath);
11068
+ if (section === null) {
11069
+ structureProblems.push(entry.relativePath + " has no section in " + part.filename);
11070
+ continue;
11071
+ }
11072
+ sectionsChecked += 1;
11073
+ if (section.path !== displayPath(entry.relativePath)) {
11074
+ structureProblems.push(entry.relativePath + " is headed " + section.path);
11075
+ }
11076
+ if (section.inclusion !== null && section.inclusion !== file.inclusionMode) {
11077
+ structureProblems.push(entry.relativePath + " declares " + section.inclusion + ", the manifest says " + file.inclusionMode);
11078
+ }
11079
+ if (section.includedLines !== null && section.includedLines !== file.includedLines) {
11080
+ structureProblems.push(entry.relativePath + " declares " + section.includedLines + " line(s), the manifest says " + file.includedLines);
11081
+ }
11082
+ }
11083
+ }
11084
+ checks.push(
11085
+ structureProblems.length === 0 ? check(
11086
+ "markdown.structure",
11087
+ "Every section sits where the manifest says",
11088
+ "critical",
11089
+ "pass",
11090
+ sectionsChecked + " section(s) in " + manifest.parts.length + " part(s) match their heading, metadata and order."
11091
+ ) : check(
11092
+ "markdown.structure",
11093
+ "Every section sits where the manifest says",
11094
+ "critical",
11095
+ "fail",
11096
+ structureProblems.length + " structural problem(s): " + sample(structureProblems)
11097
+ )
11098
+ );
11099
+ const packCandidates = [
11100
+ { key: "fullJson", file: "full-codebase.json", label: "JSON", read: jsonPackBodies },
11101
+ { key: "fullXml", file: "full-codebase.xml", label: "XML", read: xmlPackBodies },
11102
+ { key: "fullMarkdown", file: "full-codebase.md", label: "markdown", read: markdownPackBodies }
11103
+ ];
11104
+ const packsWanted = packCandidates.filter((pack) => manifest.artifacts?.[pack.key] != null);
11105
+ if (packsWanted.length > 0) {
11106
+ const renderedPaths = new Map(
11107
+ manifest.files.map((file) => [escapeControls(file.relativePath), file.relativePath])
11108
+ );
11109
+ const packProblems = [];
11110
+ let packBodies = 0;
11111
+ let packSkipped = 0;
11112
+ for (const pack of packsWanted) {
11113
+ const text2 = readText2(path25__namespace.join(snapshotDir, pack.file));
11114
+ if (text2 === null) continue;
11115
+ const bodies = pack.read(text2);
11116
+ if (bodies === null) {
11117
+ packProblems.push(pack.file + " could not be read as a file pack");
11118
+ continue;
11119
+ }
11120
+ for (const [entryPath, body] of bodies) {
11121
+ const relativePath = pack.key === "fullMarkdown" ? renderedPaths.get(entryPath) ?? entryPath : entryPath;
11122
+ const file = fileByPath.get(relativePath);
11123
+ if (file === void 0) continue;
11124
+ if (file.inclusionMode === "preview" || file.inclusionMode === "signatures") {
11125
+ packSkipped += 1;
11126
+ continue;
11127
+ }
11128
+ const partBody = bodyByPath.get(relativePath);
11129
+ if (partBody === void 0) continue;
11130
+ packBodies += 1;
11131
+ const normalised = pack.key === "fullMarkdown" ? body : emittedBody(body);
11132
+ if (normalised !== partBody) {
11133
+ packProblems.push(pack.file + ": " + relativePath + " holds a different body");
11134
+ }
11135
+ }
11136
+ }
11137
+ checks.push(
11138
+ packProblems.length === 0 ? check(
11139
+ "packs.bodies",
11140
+ "Every pack body is the body the parts carry",
11141
+ "critical",
11142
+ "pass",
11143
+ packBodies + " full body/bodies match across " + packsWanted.length + " pack(s)" + (packSkipped > 0 ? "; " + packSkipped + " preview/signature body(s) are whole-file by design." : ".")
11144
+ ) : check(
11145
+ "packs.bodies",
11146
+ "Every pack body is the body the parts carry",
11147
+ "critical",
11148
+ "fail",
11149
+ packProblems.length + " body/bodies differ: " + sample(packProblems)
11150
+ )
11151
+ );
11152
+ }
11153
+ if (options.deep !== true) {
11154
+ checks.push(
11155
+ check(
11156
+ "fidelity.bodies",
11157
+ "Every full body replays from the source bytes",
11158
+ "critical",
11159
+ "skip",
11160
+ "Run health --deep to replay each full body against the file on disk."
11161
+ )
11162
+ );
11163
+ } else {
11164
+ const replayProblems = [];
11165
+ let replayed = 0;
11166
+ let unreplayable = 0;
11167
+ for (const file of manifest.files) {
11168
+ if (file.inclusionMode !== "full" || file.emptyLinesRemoved === true) {
11169
+ unreplayable += 1;
11170
+ continue;
11171
+ }
11172
+ const body = bodyByPath.get(file.relativePath);
11173
+ if (body === void 0) {
11174
+ unreplayable += 1;
11175
+ continue;
11176
+ }
11177
+ const bytes = readBytes(path25__namespace.join(repoDir, file.relativePath));
11178
+ if (bytes === null || sha256(bytes) !== file.hashSha256) {
11179
+ unreplayable += 1;
11180
+ continue;
11181
+ }
11182
+ const decoded = decodeText(bytes);
11183
+ if (decoded.binary) {
11184
+ replayProblems.push(file.relativePath + " is binary on disk");
11185
+ continue;
11186
+ }
11187
+ const expected = emittedBody(decoded.text);
11188
+ if (expected === body) {
11189
+ replayed += 1;
11190
+ continue;
11191
+ }
11192
+ const line = firstBodyMismatch(expected, body);
11193
+ if (line === null) {
11194
+ replayed += 1;
11195
+ continue;
11196
+ }
11197
+ replayProblems.push(file.relativePath + " line " + line + " is not the source line");
11198
+ }
11199
+ checks.push(
11200
+ replayProblems.length === 0 ? check(
11201
+ "fidelity.bodies",
11202
+ "Every full body replays from the source bytes",
11203
+ "critical",
11204
+ "pass",
11205
+ replayed + " full body/bodies replayed byte-for-byte (redaction allowed); " + unreplayable + " not replayable by design or because the file moved."
11206
+ ) : check(
11207
+ "fidelity.bodies",
11208
+ "Every full body replays from the source bytes",
11209
+ "critical",
11210
+ "fail",
11211
+ replayProblems.length + " body/bodies disagree with the source: " + sample(replayProblems)
11212
+ )
11213
+ );
11214
+ }
10624
11215
  const indexParent = path25__namespace.dirname(snapshotDir);
10625
11216
  const indexPath = path25__namespace.join(indexParent, "WORKSPACE.json");
10626
11217
  if (fs24__namespace.existsSync(indexPath)) {
@@ -10743,13 +11334,15 @@ function auditSnapshot(options) {
10743
11334
  );
10744
11335
  const leakedFrom = [];
10745
11336
  let compared = 0;
11337
+ const artifactTexts = readArtifactTexts(snapshotDir);
11338
+ const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
10746
11339
  for (const record of skippedSensitive.slice(0, 40)) {
10747
11340
  if (record.path.includes("[REDACTED") || compared > 400) continue;
10748
11341
  const text2 = readText2(path25__namespace.join(repoDir, record.path));
10749
11342
  if (text2 === null) continue;
10750
11343
  for (const token of secretTokens(text2)) {
10751
11344
  compared += 1;
10752
- if (artifactTextContains(snapshotDir, token)) leakedFrom.push(record.path);
11345
+ if (artifactContains(token)) leakedFrom.push(record.path);
10753
11346
  }
10754
11347
  }
10755
11348
  checks.push(
@@ -10784,9 +11377,13 @@ function auditSnapshot(options) {
10784
11377
  )
10785
11378
  );
10786
11379
  let recomputed = 0;
11380
+ const partTokens = /* @__PURE__ */ new Map();
10787
11381
  for (const part of manifest.parts) {
10788
- const text2 = readText2(path25__namespace.join(snapshotDir, "parts", part.filename));
10789
- if (text2 !== null) recomputed += estimateTokens(text2);
11382
+ const text2 = partTexts.get(part.filename);
11383
+ if (text2 === void 0) continue;
11384
+ const tokens = estimateTokens(text2);
11385
+ partTokens.set(part.filename, tokens);
11386
+ recomputed += tokens;
10790
11387
  }
10791
11388
  const recorded = manifest.totals.estimatedTokens ?? null;
10792
11389
  checks.push(
@@ -10810,6 +11407,22 @@ function auditSnapshot(options) {
10810
11407
  "Recorded " + recorded + ", recomputed " + recomputed + ": the manifest no longer describes these parts."
10811
11408
  )
10812
11409
  );
11410
+ const partSizes = [...partTokens.values()];
11411
+ const largestPart = partSizes.length === 0 ? 0 : Math.max(...partSizes);
11412
+ const largestFile = manifest.files.reduce((largest, file) => {
11413
+ const body = bodyByPath.get(file.relativePath);
11414
+ return body === void 0 ? largest : Math.max(largest, estimateTokens(body));
11415
+ }, 0);
11416
+ const fits = (window) => partSizes.filter((tokens) => tokens <= window).length;
11417
+ checks.push(
11418
+ check(
11419
+ "tokens.fit",
11420
+ "The parts fit a context window",
11421
+ "warning",
11422
+ largestPart > 2e5 || largestFile > 2e5 ? "warn" : "pass",
11423
+ 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."
11424
+ )
11425
+ );
10813
11426
  const overBudget = manifest.parts.filter(
10814
11427
  (part) => part.byteSize > manifest.budgets.maxPartBytes
10815
11428
  );
@@ -12906,6 +13519,10 @@ var healthTool = {
12906
13519
  minimum: 1024,
12907
13520
  description: "Cap on the text the secret and host-path scans read (default 8 MB)."
12908
13521
  },
13522
+ deep: {
13523
+ type: "boolean",
13524
+ description: "Replay every full body against the source on disk. Slower, and catches a generator that wrote the wrong bytes."
13525
+ },
12909
13526
  root: ROOT_PROPERTY,
12910
13527
  outDir: OUT_DIR_PROPERTY
12911
13528
  },
@@ -12927,7 +13544,8 @@ var healthTool = {
12927
13544
  const report2 = auditSnapshot({
12928
13545
  snapshotDir: path25__namespace.resolve(workspace.root, workspace.config.outDir),
12929
13546
  repoDir: workspace.root,
12930
- ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {}
13547
+ ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
13548
+ ...args.deep === true ? { deep: true } : {}
12931
13549
  });
12932
13550
  const lines = [
12933
13551
  "Health: " + report2.score + "/100 (" + report2.counts.pass + " passed, " + report2.counts.warn + " warning(s), " + report2.counts.fail + " failed)",
@@ -14088,7 +14706,7 @@ var COMMAND_OPTION_SCOPE = {
14088
14706
  ],
14089
14707
  // The health audit resolves the config only to find the output directory; --strict decides the
14090
14708
  // exit code, and every other setting would be a promise the command does not keep.
14091
- health: ["cwd", "out-dir", "format", "strict", "all-members", "no-update-check", "help"],
14709
+ health: ["cwd", "out-dir", "format", "strict", "all-members", "deep", "no-update-check", "help"],
14092
14710
  validate: VALIDATE_OPTIONS,
14093
14711
  // `report` reads `manifest.json` and prints what is there; a generation setting would change
14094
14712
  // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
@@ -14343,7 +14961,7 @@ function buildAgentContract() {
14343
14961
  {
14344
14962
  name: "health",
14345
14963
  aliases: [],
14346
- 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.",
14964
+ 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.",
14347
14965
  positionals: [],
14348
14966
  exits: [0, 1, 2]
14349
14967
  },
@@ -14714,6 +15332,13 @@ function buildAgentContract() {
14714
15332
  appliesTo: optionAppliesTo("strict"),
14715
15333
  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."
14716
15334
  },
15335
+ {
15336
+ flag: "--deep",
15337
+ type: "boolean",
15338
+ default: false,
15339
+ appliesTo: optionAppliesTo("deep"),
15340
+ 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."
15341
+ },
14717
15342
  {
14718
15343
  flag: "--changed-since",
14719
15344
  type: "string",