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.
@@ -4002,7 +4002,7 @@ function applySpansKeepingQuotes(line, spans) {
4002
4002
 
4003
4003
  // src/version.ts
4004
4004
  var GENERATOR_NAME = "codebase-snapshot";
4005
- var GENERATOR_VERSION = "0.20.0";
4005
+ var GENERATOR_VERSION = "0.20.2";
4006
4006
  var SCHEMA_VERSION = "3.0.0";
4007
4007
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4008
4008
  function isOurGeneratorName(name) {
@@ -6878,7 +6878,10 @@ function generateMonolithJson(manifest, filesWithContent) {
6878
6878
  ...manifest,
6879
6879
  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."
6880
6880
  };
6881
- return JSON.stringify({ manifest: embedded, files: filesWithContent }, null, 2);
6881
+ const files = filesWithContent.map(
6882
+ (file) => file.content === void 0 ? file : { ...file, content: file.content.replace(/\r\n|\r/g, "\n") }
6883
+ );
6884
+ return JSON.stringify({ manifest: embedded, files }, null, 2);
6882
6885
  }
6883
6886
  function xmlAttribute(value) {
6884
6887
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -10348,6 +10351,135 @@ function staleAgainstRepository(manifest, repoDir) {
10348
10351
  if (head === recorded) return null;
10349
10352
  return "HEAD is " + head.slice(0, 8) + " but the snapshot was generated at " + recorded.slice(0, 8) + "; regenerate before trusting it.";
10350
10353
  }
10354
+ function summaryClaims(summary) {
10355
+ if ("imports" in summary) {
10356
+ const fields = [
10357
+ ["imports", summary.imports],
10358
+ ["reExports", summary.reExports],
10359
+ ["exports", summary.exports],
10360
+ ["functions", summary.functions],
10361
+ ["classes", summary.classes],
10362
+ ["interfaces", summary.interfaces],
10363
+ ["types", summary.types],
10364
+ ["enums", summary.enums],
10365
+ ["variables", summary.variables],
10366
+ ["reactComponents", summary.reactComponents],
10367
+ ["hooks", summary.hooks],
10368
+ ["routeHandlers", summary.routeHandlers]
10369
+ ];
10370
+ const claims = [];
10371
+ for (const [field, values] of fields) {
10372
+ for (const value of values) {
10373
+ if (typeof value !== "string" || value === "") continue;
10374
+ if (field === "routeHandlers" && value.includes(" ")) {
10375
+ const route = value.slice(value.indexOf(" ") + 1).trim();
10376
+ if (route !== "") claims.push({ field, value: route });
10377
+ continue;
10378
+ }
10379
+ claims.push({ field, value });
10380
+ }
10381
+ }
10382
+ return claims;
10383
+ }
10384
+ if ("keys" in summary) {
10385
+ return [...summary.keys, ...summary.sampleKeys].map((key) => ({
10386
+ field: "keys",
10387
+ value: '"' + key + '"'
10388
+ }));
10389
+ }
10390
+ return summary.headings.map((heading) => ({ field: "headings", value: heading }));
10391
+ }
10392
+ function reportNumber(text2, label) {
10393
+ const match = new RegExp("\\*\\*" + escapeRegExp(label) + ":\\*\\* `([0-9][0-9,]*)`").exec(text2);
10394
+ return match === null ? null : Number(match[1].replace(/,/g, ""));
10395
+ }
10396
+ function reportMib(text2, label) {
10397
+ const match = new RegExp(
10398
+ "\\*\\*" + escapeRegExp(label) + ":\\*\\* `([0-9]+(?:\\.[0-9]+)?) MiB`"
10399
+ ).exec(text2);
10400
+ return match === null ? null : Number(match[1]);
10401
+ }
10402
+ function maskCompatible(sourceLine, bodyLine) {
10403
+ const normalised = bodyLine.split(PEM_REDACTION_MARKER).join(REDACTION_MARKER);
10404
+ let cursor = 0;
10405
+ for (const piece of normalised.split(REDACTION_MARKER)) {
10406
+ if (piece === "") continue;
10407
+ const at = sourceLine.indexOf(piece, cursor);
10408
+ if (at === -1) return false;
10409
+ cursor = at + piece.length;
10410
+ }
10411
+ return true;
10412
+ }
10413
+ function firstBodyMismatch(expected, actual) {
10414
+ const sourceLines = expected.split("\n");
10415
+ const bodyLines = actual.split("\n");
10416
+ const shared = Math.min(sourceLines.length, bodyLines.length);
10417
+ for (let index = 0; index < shared; index += 1) {
10418
+ if (sourceLines[index] === bodyLines[index]) continue;
10419
+ if (!bodyLines[index].includes(REDACTION_MARKER) && !bodyLines[index].includes(PEM_REDACTION_MARKER)) {
10420
+ return index + 1;
10421
+ }
10422
+ if (!maskCompatible(sourceLines[index], bodyLines[index])) return index + 1;
10423
+ }
10424
+ return sourceLines.length === bodyLines.length ? null : shared + 1;
10425
+ }
10426
+ function decodeXmlAttribute(value) {
10427
+ return value.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
10428
+ }
10429
+ function jsonPackBodies(text2) {
10430
+ try {
10431
+ const parsed = JSON.parse(text2);
10432
+ if (!Array.isArray(parsed?.files)) return null;
10433
+ const bodies = /* @__PURE__ */ new Map();
10434
+ for (const entry of parsed.files) {
10435
+ if (typeof entry?.relativePath !== "string" || typeof entry.content !== "string") continue;
10436
+ bodies.set(entry.relativePath, entry.content);
10437
+ }
10438
+ return bodies;
10439
+ } catch {
10440
+ return null;
10441
+ }
10442
+ }
10443
+ function xmlPackBodies(text2) {
10444
+ const bodies = /* @__PURE__ */ new Map();
10445
+ const filePattern = / <file path="([^"]*)"[^>]*>\n([\s\S]*?)\n <\/file>/g;
10446
+ for (const match of text2.matchAll(filePattern)) {
10447
+ const content = [...match[2].matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)].map((part) => part[1]).join("");
10448
+ bodies.set(decodeXmlAttribute(match[1]), content);
10449
+ }
10450
+ return bodies.size === 0 ? null : bodies;
10451
+ }
10452
+ function markdownPackBodies(text2) {
10453
+ const bodies = /* @__PURE__ */ new Map();
10454
+ const lines = text2.split("\n");
10455
+ let index = 0;
10456
+ while (index < lines.length) {
10457
+ if (!lines[index].startsWith("## File: ")) {
10458
+ index += 1;
10459
+ continue;
10460
+ }
10461
+ const filePath = lines[index].slice("## File: ".length).trim();
10462
+ let cursor = index + 1;
10463
+ while (cursor < lines.length && !/^`{3,}/.test(lines[cursor])) {
10464
+ if (lines[cursor].startsWith("## File: ")) break;
10465
+ cursor += 1;
10466
+ }
10467
+ const fence = /^(`{3,})/.exec(lines[cursor] ?? "");
10468
+ if (fence === null) {
10469
+ index = cursor + 1;
10470
+ continue;
10471
+ }
10472
+ const body = [];
10473
+ let bodyLine = cursor + 1;
10474
+ while (bodyLine < lines.length && lines[bodyLine] !== fence[1]) {
10475
+ body.push(lines[bodyLine]);
10476
+ bodyLine += 1;
10477
+ }
10478
+ bodies.set(filePath, body.join("\n"));
10479
+ index = bodyLine + 1;
10480
+ }
10481
+ return bodies.size === 0 ? null : bodies;
10482
+ }
10351
10483
  function auditSnapshot(options) {
10352
10484
  const snapshotDir = path25.resolve(options.snapshotDir);
10353
10485
  const repoDir = path25.resolve(options.repoDir);
@@ -10554,6 +10686,272 @@ function auditSnapshot(options) {
10554
10686
  bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
10555
10687
  )
10556
10688
  );
10689
+ const fileByPath = new Map(manifest.files.map((file) => [file.relativePath, file]));
10690
+ const partTexts = /* @__PURE__ */ new Map();
10691
+ const partSections = /* @__PURE__ */ new Map();
10692
+ const bodyByPath = /* @__PURE__ */ new Map();
10693
+ const anchorToPath = new Map(
10694
+ manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
10695
+ );
10696
+ for (const part of manifest.parts) {
10697
+ const partText = readText2(path25.join(snapshotDir, "parts", part.filename));
10698
+ if (partText === null) continue;
10699
+ const sections = parsePartSections(partText);
10700
+ partTexts.set(part.filename, partText);
10701
+ partSections.set(part.filename, sections);
10702
+ for (const section of sections) {
10703
+ if (section.anchor === null) continue;
10704
+ const relativePath = anchorToPath.get(section.anchor);
10705
+ if (relativePath !== void 0) bodyByPath.set(relativePath, section.body);
10706
+ }
10707
+ }
10708
+ const summaryProblems = [];
10709
+ let claimsChecked = 0;
10710
+ let summarisedFiles = 0;
10711
+ for (const file of manifest.files) {
10712
+ if (file.summary === void 0) continue;
10713
+ if (file.inclusionMode === "preview" || file.emptyLinesRemoved === true) continue;
10714
+ const body = bodyByPath.get(file.relativePath);
10715
+ if (body === void 0) continue;
10716
+ summarisedFiles += 1;
10717
+ for (const claim of summaryClaims(file.summary)) {
10718
+ if (claim.value.includes(REDACTION_MARKER)) continue;
10719
+ claimsChecked += 1;
10720
+ if (!body.includes(claim.value)) {
10721
+ summaryProblems.push(file.relativePath + " (" + claim.field + ")");
10722
+ }
10723
+ }
10724
+ }
10725
+ checks.push(
10726
+ summarisedFiles === 0 ? check(
10727
+ "summary.truth",
10728
+ "Every summary claim appears in the body",
10729
+ "critical",
10730
+ "skip",
10731
+ "No summarised file could be compared with a body."
10732
+ ) : summaryProblems.length === 0 ? check(
10733
+ "summary.truth",
10734
+ "Every summary claim appears in the body",
10735
+ "critical",
10736
+ "pass",
10737
+ claimsChecked + " claim(s) across " + summarisedFiles + " file(s) are present in the parts."
10738
+ ) : check(
10739
+ "summary.truth",
10740
+ "Every summary claim appears in the body",
10741
+ "critical",
10742
+ "fail",
10743
+ summaryProblems.length + " claim(s) name something the body does not contain: " + sample(summaryProblems)
10744
+ )
10745
+ );
10746
+ const reportProblems = [];
10747
+ let reportClaims = 0;
10748
+ const compareNumber = (label, actual, expected) => {
10749
+ if (actual === null) return;
10750
+ reportClaims += 1;
10751
+ if (actual !== expected) {
10752
+ reportProblems.push(label + " says " + actual + ", the manifest says " + expected);
10753
+ }
10754
+ };
10755
+ const compareMib = (label, actual, bytes) => {
10756
+ if (actual === null) return;
10757
+ reportClaims += 1;
10758
+ const expected = Number((bytes / (1024 * 1024)).toFixed(2));
10759
+ if (Math.abs(actual - expected) > 0.011) {
10760
+ reportProblems.push(label + " says " + actual + " MiB, the manifest says " + expected);
10761
+ }
10762
+ };
10763
+ if (manifest.artifacts?.readme != null) {
10764
+ const text2 = readText2(path25.join(snapshotDir, "README.md"));
10765
+ if (text2 === null) {
10766
+ reportProblems.push("README.md is recorded but unreadable");
10767
+ } else {
10768
+ compareNumber("README total files", reportNumber(text2, "Total Tracked Files"), manifest.counts.totalFiles);
10769
+ compareNumber("README source lines", reportNumber(text2, "Source Lines"), manifest.counts.totalLines);
10770
+ compareNumber(
10771
+ "README emitted lines",
10772
+ reportNumber(text2, "Emitted Lines"),
10773
+ manifest.totals.emittedLines ?? manifest.counts.totalLines
10774
+ );
10775
+ const partsWritten = manifest.config.artifacts?.parts !== false;
10776
+ compareNumber("README part count", reportNumber(text2, "Part Count"), partsWritten ? manifest.counts.partsCount : 0);
10777
+ compareMib("README total size", reportMib(text2, "Total Size"), manifest.counts.totalSizeBytes);
10778
+ compareMib("README emitted content", reportMib(text2, "Emitted Content"), manifest.totals.totalContentBytes);
10779
+ const rows = [...text2.matchAll(/^\| \[([^\]]+)\]\(parts\/([^)]+)\) \| (\d+) \| ([0-9.]+) KB \|/gm)];
10780
+ if (rows.length > 0) {
10781
+ reportClaims += rows.length;
10782
+ if (rows.length !== manifest.parts.length) {
10783
+ reportProblems.push("README tables " + rows.length + " part(s), the manifest holds " + manifest.parts.length);
10784
+ }
10785
+ for (const row of rows) {
10786
+ const part = manifest.parts.find((candidate) => candidate.filename === row[2]);
10787
+ if (part === void 0) {
10788
+ reportProblems.push("README names " + row[2] + ", which the manifest does not hold");
10789
+ continue;
10790
+ }
10791
+ if (Number(row[3]) !== part.fileCount) {
10792
+ reportProblems.push("README " + row[2] + " says " + row[3] + " file(s), the manifest says " + part.fileCount);
10793
+ }
10794
+ const stated = Number(row[4]);
10795
+ const expected = Number((part.byteSize / 1024).toFixed(1));
10796
+ if (Math.abs(stated - expected) > 0.11) {
10797
+ reportProblems.push("README " + row[2] + " says " + stated + " KB, the manifest says " + expected);
10798
+ }
10799
+ }
10800
+ }
10801
+ }
10802
+ }
10803
+ if (manifest.artifacts?.prompt != null) {
10804
+ const text2 = readText2(path25.join(snapshotDir, "PROMPT.md"));
10805
+ if (text2 === null) {
10806
+ reportProblems.push("PROMPT.md is recorded but unreadable");
10807
+ } else {
10808
+ const fingerprint = /^- Fingerprint: \x60([0-9a-f]{12,64})\x60/m.exec(text2);
10809
+ if (fingerprint !== null) {
10810
+ reportClaims += 1;
10811
+ if (fingerprint[1] !== manifest.fingerprint) reportProblems.push("PROMPT names a different fingerprint");
10812
+ }
10813
+ const generated = /^- Generated: \x60([^\x60]+)\x60 from branch \x60([^\x60]+)\x60 at commit \x60([0-9a-f]+)\x60/m.exec(text2);
10814
+ if (generated !== null) {
10815
+ reportClaims += 3;
10816
+ if (generated[1] !== manifest.generatedAt) reportProblems.push("PROMPT names a different generation time");
10817
+ if (generated[2] !== manifest.git.branch) reportProblems.push("PROMPT names a different branch");
10818
+ if (!manifest.git.commit.startsWith(generated[3])) reportProblems.push("PROMPT names a different commit");
10819
+ }
10820
+ const validation = /^- Validation: the generation-time check was \x60([^\x60]+)\x60/m.exec(text2);
10821
+ if (validation !== null) {
10822
+ reportClaims += 1;
10823
+ if (validation[1] !== manifest.validation.status) reportProblems.push("PROMPT quotes a different validation status");
10824
+ }
10825
+ const partsLine = /^- Parts: ([\d,]+) at a ([\d,]+) KB ceiling/m.exec(text2);
10826
+ if (partsLine !== null) {
10827
+ reportClaims += 2;
10828
+ if (Number(partsLine[1].replace(/,/g, "")) !== manifest.parts.length) {
10829
+ reportProblems.push("PROMPT says " + partsLine[1] + " part(s), the manifest holds " + manifest.parts.length);
10830
+ }
10831
+ const ceiling = Math.round(manifest.budgets.maxPartBytes / 1024);
10832
+ if (Number(partsLine[2].replace(/,/g, "")) !== ceiling) {
10833
+ reportProblems.push("PROMPT says a " + partsLine[2] + " KB ceiling, the manifest says " + ceiling);
10834
+ }
10835
+ }
10836
+ for (const row of text2.matchAll(/^ - \x60([^\x60]+)\x60 - ([\d,]+) file\(s\)$/gm)) {
10837
+ reportClaims += 1;
10838
+ const part = manifest.parts.find((candidate) => candidate.filename === row[1]);
10839
+ if (part === void 0) {
10840
+ reportProblems.push("PROMPT names " + row[1] + ", which the manifest does not hold");
10841
+ } else if (Number(row[2].replace(/,/g, "")) !== part.fileCount) {
10842
+ reportProblems.push("PROMPT " + row[1] + " says " + row[2] + " file(s), the manifest says " + part.fileCount);
10843
+ }
10844
+ }
10845
+ const coverage = /^- ([\d,]+) paths were found; ([\d,]+) (?:is|are) in the parts and ([\d,]+) (?:was|were) skipped/m.exec(text2);
10846
+ if (coverage !== null) {
10847
+ reportClaims += 3;
10848
+ if (Number(coverage[1].replace(/,/g, "")) !== manifest.totals.candidateFiles) {
10849
+ reportProblems.push("PROMPT says " + coverage[1] + " paths were found, the manifest says " + manifest.totals.candidateFiles);
10850
+ }
10851
+ if (Number(coverage[2].replace(/,/g, "")) !== manifest.totals.includedFiles) {
10852
+ reportProblems.push("PROMPT says " + coverage[2] + " are in the parts, the manifest says " + manifest.totals.includedFiles);
10853
+ }
10854
+ if (Number(coverage[3].replace(/,/g, "")) !== manifest.counts.skippedCount) {
10855
+ reportProblems.push("PROMPT says " + coverage[3] + " were skipped, the manifest says " + manifest.counts.skippedCount);
10856
+ }
10857
+ }
10858
+ const partial = /^- Partial files: (none|[\d,]+)\./m.exec(text2);
10859
+ if (partial !== null) {
10860
+ reportClaims += 1;
10861
+ const stated = partial[1] === "none" ? 0 : Number(partial[1].replace(/,/g, ""));
10862
+ if (stated !== manifest.incomplete.length) {
10863
+ reportProblems.push("PROMPT says " + partial[1] + " partial file(s), the manifest holds " + manifest.incomplete.length);
10864
+ }
10865
+ }
10866
+ if (text2.includes("- Redacted: no line matched a secret rule.")) {
10867
+ reportClaims += 1;
10868
+ if (manifest.totals.redactedLines !== 0) {
10869
+ reportProblems.push("PROMPT says nothing was redacted, the manifest says " + manifest.totals.redactedLines);
10870
+ }
10871
+ } else {
10872
+ const redacted = /^- Redacted: ([\d,]+) line\(s\) had values masked/m.exec(text2);
10873
+ if (redacted !== null) {
10874
+ reportClaims += 1;
10875
+ if (Number(redacted[1].replace(/,/g, "")) !== manifest.totals.redactedLines) {
10876
+ reportProblems.push("PROMPT says " + redacted[1] + " redacted line(s), the manifest says " + manifest.totals.redactedLines);
10877
+ }
10878
+ }
10879
+ }
10880
+ const layersLine = /^- Layers, by file count: (.+)$/m.exec(text2);
10881
+ if (layersLine !== null) {
10882
+ for (const layer2 of layersLine[1].matchAll(/\x60([^\x60]+)\x60 ([\d,]+)/g)) {
10883
+ reportClaims += 1;
10884
+ const expected = manifest.layers[layer2[1]] ?? 0;
10885
+ if (Number(layer2[2].replace(/,/g, "")) !== expected) {
10886
+ reportProblems.push("PROMPT layer " + layer2[1] + " says " + layer2[2] + ", the manifest says " + expected);
10887
+ }
10888
+ }
10889
+ }
10890
+ }
10891
+ }
10892
+ checks.push(
10893
+ reportProblems.length > 0 ? check(
10894
+ "report.truth",
10895
+ "The reports quote this run, not another",
10896
+ "critical",
10897
+ "fail",
10898
+ reportProblems.length + " disagreement(s): " + sample(reportProblems)
10899
+ ) : reportClaims === 0 ? check(
10900
+ "report.truth",
10901
+ "The reports quote this run, not another",
10902
+ "critical",
10903
+ "skip",
10904
+ "No report in the current shape could be compared with the manifest."
10905
+ ) : check(
10906
+ "report.truth",
10907
+ "The reports quote this run, not another",
10908
+ "critical",
10909
+ "pass",
10910
+ reportClaims + " figure(s) in README.md and PROMPT.md agree with the manifest."
10911
+ )
10912
+ );
10913
+ const indexProblems = [];
10914
+ const indexedPaths = /* @__PURE__ */ new Set();
10915
+ const checkIndexed = (kind, relativePath, part) => {
10916
+ const file = fileByPath.get(relativePath);
10917
+ if (file === void 0) {
10918
+ indexProblems.push(kind + " names " + relativePath + ", which is not in files[]");
10919
+ return;
10920
+ }
10921
+ if (part !== void 0 && file.part !== part) {
10922
+ indexProblems.push(kind + " puts " + relativePath + " in " + part + ", the manifest says " + file.part);
10923
+ }
10924
+ };
10925
+ for (const route of manifest.indexes.routes) checkIndexed("routes", route.path, route.part);
10926
+ for (const component of manifest.indexes.components) checkIndexed("components", component.path, component.part);
10927
+ for (const handler of manifest.indexes.handlers) checkIndexed("handlers", handler.path, handler.part);
10928
+ for (const directive of manifest.indexes.directives) checkIndexed("directives", directive.path);
10929
+ for (const entry of manifest.indexes.imports.byFile) {
10930
+ checkIndexed("imports.byFile", entry.path);
10931
+ if (indexedPaths.has(entry.path)) indexProblems.push("imports.byFile lists " + entry.path + " twice");
10932
+ indexedPaths.add(entry.path);
10933
+ }
10934
+ for (const entry of manifest.indexes.imports.centralFiles) {
10935
+ checkIndexed("centralFiles", entry.path);
10936
+ if (entry.importedByCount < 1) {
10937
+ indexProblems.push("centralFiles says " + entry.path + " has " + entry.importedByCount + " importer(s)");
10938
+ }
10939
+ }
10940
+ checks.push(
10941
+ indexProblems.length === 0 ? check(
10942
+ "indexes.consistent",
10943
+ "Every index entry names a file in the snapshot",
10944
+ "critical",
10945
+ "pass",
10946
+ 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."
10947
+ ) : check(
10948
+ "indexes.consistent",
10949
+ "Every index entry names a file in the snapshot",
10950
+ "critical",
10951
+ "fail",
10952
+ indexProblems.length + " index problem(s): " + sample(indexProblems)
10953
+ )
10954
+ );
10557
10955
  const packReaders = [
10558
10956
  {
10559
10957
  key: "fullJson",
@@ -10630,9 +11028,8 @@ function auditSnapshot(options) {
10630
11028
  const bodyProblems = [];
10631
11029
  let bodiesChecked = 0;
10632
11030
  for (const part of manifest.parts) {
10633
- const partText = readText2(path25.join(snapshotDir, "parts", part.filename));
10634
- if (partText === null) continue;
10635
- const sections = parsePartSections(partText);
11031
+ const sections = partSections.get(part.filename);
11032
+ if (sections === void 0) continue;
10636
11033
  for (const file of manifest.files) {
10637
11034
  if (file.part !== part.filename) continue;
10638
11035
  const section = findSection(sections, file.relativePath);
@@ -10640,6 +11037,7 @@ function auditSnapshot(options) {
10640
11037
  bodyProblems.push(file.relativePath + " has no section in " + part.filename);
10641
11038
  continue;
10642
11039
  }
11040
+ bodyByPath.set(file.relativePath, section.body);
10643
11041
  bodiesChecked += 1;
10644
11042
  const bytes = Buffer.byteLength(section.body, "utf8");
10645
11043
  const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
@@ -10665,6 +11063,198 @@ function auditSnapshot(options) {
10665
11063
  bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
10666
11064
  )
10667
11065
  );
11066
+ const structureProblems = [];
11067
+ let sectionsChecked = 0;
11068
+ for (const part of manifest.parts) {
11069
+ const text2 = partTexts.get(part.filename);
11070
+ const sections = partSections.get(part.filename);
11071
+ if (text2 === void 0 || sections === void 0) continue;
11072
+ const header = /^# Codebase Snapshot Part (\d+) of (\d+)$/m.exec(text2);
11073
+ if (header !== null) {
11074
+ if (Number(header[1]) !== part.index) {
11075
+ structureProblems.push(part.filename + " says part " + header[1] + ", the manifest says " + part.index);
11076
+ }
11077
+ if (Number(header[2]) !== manifest.parts.length) {
11078
+ structureProblems.push(part.filename + " says " + header[2] + " parts, the manifest holds " + manifest.parts.length);
11079
+ }
11080
+ }
11081
+ const filesLine = /^- Files: (\d+)$/m.exec(text2);
11082
+ if (filesLine !== null && Number(filesLine[1]) !== part.fileCount) {
11083
+ structureProblems.push(part.filename + " says " + filesLine[1] + " file(s), the manifest says " + part.fileCount);
11084
+ }
11085
+ const fingerprintLine = /^- Content Fingerprint: (\S+)$/m.exec(text2);
11086
+ if (fingerprintLine !== null && fingerprintLine[1] !== manifest.fingerprint) {
11087
+ structureProblems.push(part.filename + " names a different content fingerprint");
11088
+ }
11089
+ const tokenLine = /^- Estimated Tokens: ~([0-9,]+)$/m.exec(text2);
11090
+ if (tokenLine !== null && Number(tokenLine[1].replace(/,/g, "")) !== part.estimatedTokens) {
11091
+ structureProblems.push(part.filename + " says " + tokenLine[1] + " tokens, the manifest says " + part.estimatedTokens);
11092
+ }
11093
+ if (sections.length !== part.fileCount) {
11094
+ structureProblems.push(part.filename + " holds " + sections.length + " section(s), the manifest says " + part.fileCount);
11095
+ }
11096
+ const expectedAnchors = new Set(part.includedFiles.map((entry) => anchorForPath(entry.relativePath)));
11097
+ for (const section of sections) {
11098
+ if (section.anchor === null || !expectedAnchors.has(section.anchor)) {
11099
+ structureProblems.push(part.filename + " holds a section for " + section.path + ", which the manifest does not list");
11100
+ }
11101
+ }
11102
+ const expectedOrder = part.includedFiles.map((entry) => anchorForPath(entry.relativePath)).join("\n");
11103
+ const actualOrder = sections.map((section) => section.anchor).filter((anchor) => anchor !== null).join("\n");
11104
+ if (actualOrder !== expectedOrder) {
11105
+ structureProblems.push(part.filename + " orders its sections differently than the manifest");
11106
+ }
11107
+ for (const entry of part.includedFiles) {
11108
+ const file = fileByPath.get(entry.relativePath);
11109
+ if (file === void 0) continue;
11110
+ const section = findSection(sections, entry.relativePath);
11111
+ if (section === null) {
11112
+ structureProblems.push(entry.relativePath + " has no section in " + part.filename);
11113
+ continue;
11114
+ }
11115
+ sectionsChecked += 1;
11116
+ if (section.path !== displayPath(entry.relativePath)) {
11117
+ structureProblems.push(entry.relativePath + " is headed " + section.path);
11118
+ }
11119
+ if (section.inclusion !== null && section.inclusion !== file.inclusionMode) {
11120
+ structureProblems.push(entry.relativePath + " declares " + section.inclusion + ", the manifest says " + file.inclusionMode);
11121
+ }
11122
+ if (section.includedLines !== null && section.includedLines !== file.includedLines) {
11123
+ structureProblems.push(entry.relativePath + " declares " + section.includedLines + " line(s), the manifest says " + file.includedLines);
11124
+ }
11125
+ }
11126
+ }
11127
+ checks.push(
11128
+ structureProblems.length === 0 ? check(
11129
+ "markdown.structure",
11130
+ "Every section sits where the manifest says",
11131
+ "critical",
11132
+ "pass",
11133
+ sectionsChecked + " section(s) in " + manifest.parts.length + " part(s) match their heading, metadata and order."
11134
+ ) : check(
11135
+ "markdown.structure",
11136
+ "Every section sits where the manifest says",
11137
+ "critical",
11138
+ "fail",
11139
+ structureProblems.length + " structural problem(s): " + sample(structureProblems)
11140
+ )
11141
+ );
11142
+ const packCandidates = [
11143
+ { key: "fullJson", file: "full-codebase.json", label: "JSON", read: jsonPackBodies },
11144
+ { key: "fullXml", file: "full-codebase.xml", label: "XML", read: xmlPackBodies },
11145
+ { key: "fullMarkdown", file: "full-codebase.md", label: "markdown", read: markdownPackBodies }
11146
+ ];
11147
+ const packsWanted = packCandidates.filter((pack) => manifest.artifacts?.[pack.key] != null);
11148
+ if (packsWanted.length > 0) {
11149
+ const renderedPaths = new Map(
11150
+ manifest.files.map((file) => [escapeControls(file.relativePath), file.relativePath])
11151
+ );
11152
+ const packProblems = [];
11153
+ let packBodies = 0;
11154
+ let packSkipped = 0;
11155
+ for (const pack of packsWanted) {
11156
+ const text2 = readText2(path25.join(snapshotDir, pack.file));
11157
+ if (text2 === null) continue;
11158
+ const bodies = pack.read(text2);
11159
+ if (bodies === null) {
11160
+ packProblems.push(pack.file + " could not be read as a file pack");
11161
+ continue;
11162
+ }
11163
+ for (const [entryPath, body] of bodies) {
11164
+ const relativePath = pack.key === "fullMarkdown" ? renderedPaths.get(entryPath) ?? entryPath : entryPath;
11165
+ const file = fileByPath.get(relativePath);
11166
+ if (file === void 0) continue;
11167
+ if (file.inclusionMode === "preview" || file.inclusionMode === "signatures") {
11168
+ packSkipped += 1;
11169
+ continue;
11170
+ }
11171
+ const partBody = bodyByPath.get(relativePath);
11172
+ if (partBody === void 0) continue;
11173
+ packBodies += 1;
11174
+ const normalised = pack.key === "fullMarkdown" ? body : emittedBody(body);
11175
+ if (normalised !== partBody) {
11176
+ packProblems.push(pack.file + ": " + relativePath + " holds a different body");
11177
+ }
11178
+ }
11179
+ }
11180
+ checks.push(
11181
+ packProblems.length === 0 ? check(
11182
+ "packs.bodies",
11183
+ "Every pack body is the body the parts carry",
11184
+ "critical",
11185
+ "pass",
11186
+ packBodies + " full body/bodies match across " + packsWanted.length + " pack(s)" + (packSkipped > 0 ? "; " + packSkipped + " preview/signature body(s) are whole-file by design." : ".")
11187
+ ) : check(
11188
+ "packs.bodies",
11189
+ "Every pack body is the body the parts carry",
11190
+ "critical",
11191
+ "fail",
11192
+ packProblems.length + " body/bodies differ: " + sample(packProblems)
11193
+ )
11194
+ );
11195
+ }
11196
+ if (options.deep !== true) {
11197
+ checks.push(
11198
+ check(
11199
+ "fidelity.bodies",
11200
+ "Every full body replays from the source bytes",
11201
+ "critical",
11202
+ "skip",
11203
+ "Run health --deep to replay each full body against the file on disk."
11204
+ )
11205
+ );
11206
+ } else {
11207
+ const replayProblems = [];
11208
+ let replayed = 0;
11209
+ let unreplayable = 0;
11210
+ for (const file of manifest.files) {
11211
+ if (file.inclusionMode !== "full" || file.emptyLinesRemoved === true) {
11212
+ unreplayable += 1;
11213
+ continue;
11214
+ }
11215
+ const body = bodyByPath.get(file.relativePath);
11216
+ if (body === void 0) {
11217
+ unreplayable += 1;
11218
+ continue;
11219
+ }
11220
+ const bytes = readBytes(path25.join(repoDir, file.relativePath));
11221
+ if (bytes === null || sha256(bytes) !== file.hashSha256) {
11222
+ unreplayable += 1;
11223
+ continue;
11224
+ }
11225
+ const decoded = decodeText(bytes);
11226
+ if (decoded.binary) {
11227
+ replayProblems.push(file.relativePath + " is binary on disk");
11228
+ continue;
11229
+ }
11230
+ const expected = emittedBody(decoded.text);
11231
+ if (expected === body) {
11232
+ replayed += 1;
11233
+ continue;
11234
+ }
11235
+ const line = firstBodyMismatch(expected, body);
11236
+ if (line === null) {
11237
+ replayed += 1;
11238
+ continue;
11239
+ }
11240
+ replayProblems.push(file.relativePath + " line " + line + " is not the source line");
11241
+ }
11242
+ checks.push(
11243
+ replayProblems.length === 0 ? check(
11244
+ "fidelity.bodies",
11245
+ "Every full body replays from the source bytes",
11246
+ "critical",
11247
+ "pass",
11248
+ replayed + " full body/bodies replayed byte-for-byte (redaction allowed); " + unreplayable + " not replayable by design or because the file moved."
11249
+ ) : check(
11250
+ "fidelity.bodies",
11251
+ "Every full body replays from the source bytes",
11252
+ "critical",
11253
+ "fail",
11254
+ replayProblems.length + " body/bodies disagree with the source: " + sample(replayProblems)
11255
+ )
11256
+ );
11257
+ }
10668
11258
  const indexParent = path25.dirname(snapshotDir);
10669
11259
  const indexPath = path25.join(indexParent, "WORKSPACE.json");
10670
11260
  if (fs24.existsSync(indexPath)) {
@@ -10828,9 +11418,13 @@ function auditSnapshot(options) {
10828
11418
  )
10829
11419
  );
10830
11420
  let recomputed = 0;
11421
+ const partTokens = /* @__PURE__ */ new Map();
10831
11422
  for (const part of manifest.parts) {
10832
- const text2 = readText2(path25.join(snapshotDir, "parts", part.filename));
10833
- if (text2 !== null) recomputed += estimateTokens(text2);
11423
+ const text2 = partTexts.get(part.filename);
11424
+ if (text2 === void 0) continue;
11425
+ const tokens = estimateTokens(text2);
11426
+ partTokens.set(part.filename, tokens);
11427
+ recomputed += tokens;
10834
11428
  }
10835
11429
  const recorded = manifest.totals.estimatedTokens ?? null;
10836
11430
  checks.push(
@@ -10854,6 +11448,22 @@ function auditSnapshot(options) {
10854
11448
  "Recorded " + recorded + ", recomputed " + recomputed + ": the manifest no longer describes these parts."
10855
11449
  )
10856
11450
  );
11451
+ const partSizes = [...partTokens.values()];
11452
+ const largestPart = partSizes.length === 0 ? 0 : Math.max(...partSizes);
11453
+ const largestFile = manifest.files.reduce((largest, file) => {
11454
+ const body = bodyByPath.get(file.relativePath);
11455
+ return body === void 0 ? largest : Math.max(largest, estimateTokens(body));
11456
+ }, 0);
11457
+ const fits = (window) => partSizes.filter((tokens) => tokens <= window).length;
11458
+ checks.push(
11459
+ check(
11460
+ "tokens.fit",
11461
+ "The parts fit a context window",
11462
+ "warning",
11463
+ largestPart > 2e5 || largestFile > 2e5 ? "warn" : "pass",
11464
+ 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."
11465
+ )
11466
+ );
10857
11467
  const overBudget = manifest.parts.filter(
10858
11468
  (part) => part.byteSize > manifest.budgets.maxPartBytes
10859
11469
  );
@@ -12950,6 +13560,10 @@ var healthTool = {
12950
13560
  minimum: 1024,
12951
13561
  description: "Cap on the text the secret and host-path scans read (default 8 MB)."
12952
13562
  },
13563
+ deep: {
13564
+ type: "boolean",
13565
+ description: "Replay every full body against the source on disk. Slower, and catches a generator that wrote the wrong bytes."
13566
+ },
12953
13567
  root: ROOT_PROPERTY,
12954
13568
  outDir: OUT_DIR_PROPERTY
12955
13569
  },
@@ -12971,7 +13585,8 @@ var healthTool = {
12971
13585
  const report2 = auditSnapshot({
12972
13586
  snapshotDir: path25.resolve(workspace.root, workspace.config.outDir),
12973
13587
  repoDir: workspace.root,
12974
- ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {}
13588
+ ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
13589
+ ...args.deep === true ? { deep: true } : {}
12975
13590
  });
12976
13591
  const lines = [
12977
13592
  "Health: " + report2.score + "/100 (" + report2.counts.pass + " passed, " + report2.counts.warn + " warning(s), " + report2.counts.fail + " failed)",
@@ -14132,7 +14747,7 @@ var COMMAND_OPTION_SCOPE = {
14132
14747
  ],
14133
14748
  // The health audit resolves the config only to find the output directory; --strict decides the
14134
14749
  // exit code, and every other setting would be a promise the command does not keep.
14135
- health: ["cwd", "out-dir", "format", "strict", "all-members", "no-update-check", "help"],
14750
+ health: ["cwd", "out-dir", "format", "strict", "all-members", "deep", "no-update-check", "help"],
14136
14751
  validate: VALIDATE_OPTIONS,
14137
14752
  // `report` reads `manifest.json` and prints what is there; a generation setting would change
14138
14753
  // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
@@ -14456,7 +15071,7 @@ function buildAgentContract() {
14456
15071
  {
14457
15072
  name: "health",
14458
15073
  aliases: [],
14459
- 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.",
15074
+ 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.",
14460
15075
  positionals: [],
14461
15076
  exits: [0, 1, 2]
14462
15077
  },
@@ -14827,6 +15442,13 @@ function buildAgentContract() {
14827
15442
  appliesTo: optionAppliesTo("strict"),
14828
15443
  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."
14829
15444
  },
15445
+ {
15446
+ flag: "--deep",
15447
+ type: "boolean",
15448
+ default: false,
15449
+ appliesTo: optionAppliesTo("deep"),
15450
+ 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."
15451
+ },
14830
15452
  {
14831
15453
  flag: "--changed-since",
14832
15454
  type: "string",