codebase-snapshot 0.19.0 → 0.20.2

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