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