codebase-snapshot 0.20.0 → 0.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -2199,7 +2199,7 @@ function applySpansKeepingQuotes(line, spans) {
2199
2199
 
2200
2200
  // src/version.ts
2201
2201
  var GENERATOR_NAME = "codebase-snapshot";
2202
- var GENERATOR_VERSION = "0.20.0";
2202
+ var GENERATOR_VERSION = "0.20.2";
2203
2203
  var SCHEMA_VERSION = "3.0.0";
2204
2204
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2205
2205
  function isOurGeneratorName(name) {
@@ -10181,7 +10181,10 @@ function generateMonolithJson(manifest, filesWithContent) {
10181
10181
  ...manifest,
10182
10182
  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."
10183
10183
  };
10184
- return JSON.stringify({ manifest: embedded, files: filesWithContent }, null, 2);
10184
+ const files = filesWithContent.map(
10185
+ (file) => file.content === void 0 ? file : { ...file, content: file.content.replace(/\r\n|\r/g, "\n") }
10186
+ );
10187
+ return JSON.stringify({ manifest: embedded, files }, null, 2);
10185
10188
  }
10186
10189
  function xmlAttribute(value) {
10187
10190
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -12185,6 +12188,135 @@ function staleAgainstRepository(manifest, repoDir) {
12185
12188
  if (head === recorded) return null;
12186
12189
  return "HEAD is " + head.slice(0, 8) + " but the snapshot was generated at " + recorded.slice(0, 8) + "; regenerate before trusting it.";
12187
12190
  }
12191
+ function summaryClaims(summary) {
12192
+ if ("imports" in summary) {
12193
+ const fields = [
12194
+ ["imports", summary.imports],
12195
+ ["reExports", summary.reExports],
12196
+ ["exports", summary.exports],
12197
+ ["functions", summary.functions],
12198
+ ["classes", summary.classes],
12199
+ ["interfaces", summary.interfaces],
12200
+ ["types", summary.types],
12201
+ ["enums", summary.enums],
12202
+ ["variables", summary.variables],
12203
+ ["reactComponents", summary.reactComponents],
12204
+ ["hooks", summary.hooks],
12205
+ ["routeHandlers", summary.routeHandlers]
12206
+ ];
12207
+ const claims = [];
12208
+ for (const [field, values] of fields) {
12209
+ for (const value of values) {
12210
+ if (typeof value !== "string" || value === "") continue;
12211
+ if (field === "routeHandlers" && value.includes(" ")) {
12212
+ const route = value.slice(value.indexOf(" ") + 1).trim();
12213
+ if (route !== "") claims.push({ field, value: route });
12214
+ continue;
12215
+ }
12216
+ claims.push({ field, value });
12217
+ }
12218
+ }
12219
+ return claims;
12220
+ }
12221
+ if ("keys" in summary) {
12222
+ return [...summary.keys, ...summary.sampleKeys].map((key) => ({
12223
+ field: "keys",
12224
+ value: '"' + key + '"'
12225
+ }));
12226
+ }
12227
+ return summary.headings.map((heading) => ({ field: "headings", value: heading }));
12228
+ }
12229
+ function reportNumber(text2, label) {
12230
+ const match = new RegExp("\\*\\*" + escapeRegExp(label) + ":\\*\\* `([0-9][0-9,]*)`").exec(text2);
12231
+ return match === null ? null : Number(match[1].replace(/,/g, ""));
12232
+ }
12233
+ function reportMib(text2, label) {
12234
+ const match = new RegExp(
12235
+ "\\*\\*" + escapeRegExp(label) + ":\\*\\* `([0-9]+(?:\\.[0-9]+)?) MiB`"
12236
+ ).exec(text2);
12237
+ return match === null ? null : Number(match[1]);
12238
+ }
12239
+ function maskCompatible(sourceLine, bodyLine) {
12240
+ const normalised = bodyLine.split(PEM_REDACTION_MARKER).join(REDACTION_MARKER);
12241
+ let cursor = 0;
12242
+ for (const piece of normalised.split(REDACTION_MARKER)) {
12243
+ if (piece === "") continue;
12244
+ const at = sourceLine.indexOf(piece, cursor);
12245
+ if (at === -1) return false;
12246
+ cursor = at + piece.length;
12247
+ }
12248
+ return true;
12249
+ }
12250
+ function firstBodyMismatch(expected, actual) {
12251
+ const sourceLines = expected.split("\n");
12252
+ const bodyLines = actual.split("\n");
12253
+ const shared = Math.min(sourceLines.length, bodyLines.length);
12254
+ for (let index = 0; index < shared; index += 1) {
12255
+ if (sourceLines[index] === bodyLines[index]) continue;
12256
+ if (!bodyLines[index].includes(REDACTION_MARKER) && !bodyLines[index].includes(PEM_REDACTION_MARKER)) {
12257
+ return index + 1;
12258
+ }
12259
+ if (!maskCompatible(sourceLines[index], bodyLines[index])) return index + 1;
12260
+ }
12261
+ return sourceLines.length === bodyLines.length ? null : shared + 1;
12262
+ }
12263
+ function decodeXmlAttribute(value) {
12264
+ return value.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
12265
+ }
12266
+ function jsonPackBodies(text2) {
12267
+ try {
12268
+ const parsed = JSON.parse(text2);
12269
+ if (!Array.isArray(parsed?.files)) return null;
12270
+ const bodies = /* @__PURE__ */ new Map();
12271
+ for (const entry of parsed.files) {
12272
+ if (typeof entry?.relativePath !== "string" || typeof entry.content !== "string") continue;
12273
+ bodies.set(entry.relativePath, entry.content);
12274
+ }
12275
+ return bodies;
12276
+ } catch {
12277
+ return null;
12278
+ }
12279
+ }
12280
+ function xmlPackBodies(text2) {
12281
+ const bodies = /* @__PURE__ */ new Map();
12282
+ const filePattern = / <file path="([^"]*)"[^>]*>\n([\s\S]*?)\n <\/file>/g;
12283
+ for (const match of text2.matchAll(filePattern)) {
12284
+ const content = [...match[2].matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)].map((part) => part[1]).join("");
12285
+ bodies.set(decodeXmlAttribute(match[1]), content);
12286
+ }
12287
+ return bodies.size === 0 ? null : bodies;
12288
+ }
12289
+ function markdownPackBodies(text2) {
12290
+ const bodies = /* @__PURE__ */ new Map();
12291
+ const lines = text2.split("\n");
12292
+ let index = 0;
12293
+ while (index < lines.length) {
12294
+ if (!lines[index].startsWith("## File: ")) {
12295
+ index += 1;
12296
+ continue;
12297
+ }
12298
+ const filePath = lines[index].slice("## File: ".length).trim();
12299
+ let cursor = index + 1;
12300
+ while (cursor < lines.length && !/^`{3,}/.test(lines[cursor])) {
12301
+ if (lines[cursor].startsWith("## File: ")) break;
12302
+ cursor += 1;
12303
+ }
12304
+ const fence = /^(`{3,})/.exec(lines[cursor] ?? "");
12305
+ if (fence === null) {
12306
+ index = cursor + 1;
12307
+ continue;
12308
+ }
12309
+ const body = [];
12310
+ let bodyLine = cursor + 1;
12311
+ while (bodyLine < lines.length && lines[bodyLine] !== fence[1]) {
12312
+ body.push(lines[bodyLine]);
12313
+ bodyLine += 1;
12314
+ }
12315
+ bodies.set(filePath, body.join("\n"));
12316
+ index = bodyLine + 1;
12317
+ }
12318
+ return bodies.size === 0 ? null : bodies;
12319
+ }
12188
12320
  function auditSnapshot(options) {
12189
12321
  const snapshotDir = path16.resolve(options.snapshotDir);
12190
12322
  const repoDir = path16.resolve(options.repoDir);
@@ -12391,6 +12523,272 @@ function auditSnapshot(options) {
12391
12523
  bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
12392
12524
  )
12393
12525
  );
12526
+ const fileByPath = new Map(manifest.files.map((file) => [file.relativePath, file]));
12527
+ const partTexts = /* @__PURE__ */ new Map();
12528
+ const partSections = /* @__PURE__ */ new Map();
12529
+ const bodyByPath = /* @__PURE__ */ new Map();
12530
+ const anchorToPath = new Map(
12531
+ manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
12532
+ );
12533
+ for (const part of manifest.parts) {
12534
+ const partText = readText2(path16.join(snapshotDir, "parts", part.filename));
12535
+ if (partText === null) continue;
12536
+ const sections = parsePartSections(partText);
12537
+ partTexts.set(part.filename, partText);
12538
+ partSections.set(part.filename, sections);
12539
+ for (const section of sections) {
12540
+ if (section.anchor === null) continue;
12541
+ const relativePath = anchorToPath.get(section.anchor);
12542
+ if (relativePath !== void 0) bodyByPath.set(relativePath, section.body);
12543
+ }
12544
+ }
12545
+ const summaryProblems = [];
12546
+ let claimsChecked = 0;
12547
+ let summarisedFiles = 0;
12548
+ for (const file of manifest.files) {
12549
+ if (file.summary === void 0) continue;
12550
+ if (file.inclusionMode === "preview" || file.emptyLinesRemoved === true) continue;
12551
+ const body = bodyByPath.get(file.relativePath);
12552
+ if (body === void 0) continue;
12553
+ summarisedFiles += 1;
12554
+ for (const claim of summaryClaims(file.summary)) {
12555
+ if (claim.value.includes(REDACTION_MARKER)) continue;
12556
+ claimsChecked += 1;
12557
+ if (!body.includes(claim.value)) {
12558
+ summaryProblems.push(file.relativePath + " (" + claim.field + ")");
12559
+ }
12560
+ }
12561
+ }
12562
+ checks.push(
12563
+ summarisedFiles === 0 ? check(
12564
+ "summary.truth",
12565
+ "Every summary claim appears in the body",
12566
+ "critical",
12567
+ "skip",
12568
+ "No summarised file could be compared with a body."
12569
+ ) : summaryProblems.length === 0 ? check(
12570
+ "summary.truth",
12571
+ "Every summary claim appears in the body",
12572
+ "critical",
12573
+ "pass",
12574
+ claimsChecked + " claim(s) across " + summarisedFiles + " file(s) are present in the parts."
12575
+ ) : check(
12576
+ "summary.truth",
12577
+ "Every summary claim appears in the body",
12578
+ "critical",
12579
+ "fail",
12580
+ summaryProblems.length + " claim(s) name something the body does not contain: " + sample(summaryProblems)
12581
+ )
12582
+ );
12583
+ const reportProblems = [];
12584
+ let reportClaims = 0;
12585
+ const compareNumber = (label, actual, expected) => {
12586
+ if (actual === null) return;
12587
+ reportClaims += 1;
12588
+ if (actual !== expected) {
12589
+ reportProblems.push(label + " says " + actual + ", the manifest says " + expected);
12590
+ }
12591
+ };
12592
+ const compareMib = (label, actual, bytes) => {
12593
+ if (actual === null) return;
12594
+ reportClaims += 1;
12595
+ const expected = Number((bytes / (1024 * 1024)).toFixed(2));
12596
+ if (Math.abs(actual - expected) > 0.011) {
12597
+ reportProblems.push(label + " says " + actual + " MiB, the manifest says " + expected);
12598
+ }
12599
+ };
12600
+ if (manifest.artifacts?.readme != null) {
12601
+ const text2 = readText2(path16.join(snapshotDir, "README.md"));
12602
+ if (text2 === null) {
12603
+ reportProblems.push("README.md is recorded but unreadable");
12604
+ } else {
12605
+ compareNumber("README total files", reportNumber(text2, "Total Tracked Files"), manifest.counts.totalFiles);
12606
+ compareNumber("README source lines", reportNumber(text2, "Source Lines"), manifest.counts.totalLines);
12607
+ compareNumber(
12608
+ "README emitted lines",
12609
+ reportNumber(text2, "Emitted Lines"),
12610
+ manifest.totals.emittedLines ?? manifest.counts.totalLines
12611
+ );
12612
+ const partsWritten = manifest.config.artifacts?.parts !== false;
12613
+ compareNumber("README part count", reportNumber(text2, "Part Count"), partsWritten ? manifest.counts.partsCount : 0);
12614
+ compareMib("README total size", reportMib(text2, "Total Size"), manifest.counts.totalSizeBytes);
12615
+ compareMib("README emitted content", reportMib(text2, "Emitted Content"), manifest.totals.totalContentBytes);
12616
+ const rows = [...text2.matchAll(/^\| \[([^\]]+)\]\(parts\/([^)]+)\) \| (\d+) \| ([0-9.]+) KB \|/gm)];
12617
+ if (rows.length > 0) {
12618
+ reportClaims += rows.length;
12619
+ if (rows.length !== manifest.parts.length) {
12620
+ reportProblems.push("README tables " + rows.length + " part(s), the manifest holds " + manifest.parts.length);
12621
+ }
12622
+ for (const row of rows) {
12623
+ const part = manifest.parts.find((candidate) => candidate.filename === row[2]);
12624
+ if (part === void 0) {
12625
+ reportProblems.push("README names " + row[2] + ", which the manifest does not hold");
12626
+ continue;
12627
+ }
12628
+ if (Number(row[3]) !== part.fileCount) {
12629
+ reportProblems.push("README " + row[2] + " says " + row[3] + " file(s), the manifest says " + part.fileCount);
12630
+ }
12631
+ const stated = Number(row[4]);
12632
+ const expected = Number((part.byteSize / 1024).toFixed(1));
12633
+ if (Math.abs(stated - expected) > 0.11) {
12634
+ reportProblems.push("README " + row[2] + " says " + stated + " KB, the manifest says " + expected);
12635
+ }
12636
+ }
12637
+ }
12638
+ }
12639
+ }
12640
+ if (manifest.artifacts?.prompt != null) {
12641
+ const text2 = readText2(path16.join(snapshotDir, "PROMPT.md"));
12642
+ if (text2 === null) {
12643
+ reportProblems.push("PROMPT.md is recorded but unreadable");
12644
+ } else {
12645
+ const fingerprint = /^- Fingerprint: \x60([0-9a-f]{12,64})\x60/m.exec(text2);
12646
+ if (fingerprint !== null) {
12647
+ reportClaims += 1;
12648
+ if (fingerprint[1] !== manifest.fingerprint) reportProblems.push("PROMPT names a different fingerprint");
12649
+ }
12650
+ const generated = /^- Generated: \x60([^\x60]+)\x60 from branch \x60([^\x60]+)\x60 at commit \x60([0-9a-f]+)\x60/m.exec(text2);
12651
+ if (generated !== null) {
12652
+ reportClaims += 3;
12653
+ if (generated[1] !== manifest.generatedAt) reportProblems.push("PROMPT names a different generation time");
12654
+ if (generated[2] !== manifest.git.branch) reportProblems.push("PROMPT names a different branch");
12655
+ if (!manifest.git.commit.startsWith(generated[3])) reportProblems.push("PROMPT names a different commit");
12656
+ }
12657
+ const validation = /^- Validation: the generation-time check was \x60([^\x60]+)\x60/m.exec(text2);
12658
+ if (validation !== null) {
12659
+ reportClaims += 1;
12660
+ if (validation[1] !== manifest.validation.status) reportProblems.push("PROMPT quotes a different validation status");
12661
+ }
12662
+ const partsLine = /^- Parts: ([\d,]+) at a ([\d,]+) KB ceiling/m.exec(text2);
12663
+ if (partsLine !== null) {
12664
+ reportClaims += 2;
12665
+ if (Number(partsLine[1].replace(/,/g, "")) !== manifest.parts.length) {
12666
+ reportProblems.push("PROMPT says " + partsLine[1] + " part(s), the manifest holds " + manifest.parts.length);
12667
+ }
12668
+ const ceiling = Math.round(manifest.budgets.maxPartBytes / 1024);
12669
+ if (Number(partsLine[2].replace(/,/g, "")) !== ceiling) {
12670
+ reportProblems.push("PROMPT says a " + partsLine[2] + " KB ceiling, the manifest says " + ceiling);
12671
+ }
12672
+ }
12673
+ for (const row of text2.matchAll(/^ - \x60([^\x60]+)\x60 - ([\d,]+) file\(s\)$/gm)) {
12674
+ reportClaims += 1;
12675
+ const part = manifest.parts.find((candidate) => candidate.filename === row[1]);
12676
+ if (part === void 0) {
12677
+ reportProblems.push("PROMPT names " + row[1] + ", which the manifest does not hold");
12678
+ } else if (Number(row[2].replace(/,/g, "")) !== part.fileCount) {
12679
+ reportProblems.push("PROMPT " + row[1] + " says " + row[2] + " file(s), the manifest says " + part.fileCount);
12680
+ }
12681
+ }
12682
+ const coverage = /^- ([\d,]+) paths were found; ([\d,]+) (?:is|are) in the parts and ([\d,]+) (?:was|were) skipped/m.exec(text2);
12683
+ if (coverage !== null) {
12684
+ reportClaims += 3;
12685
+ if (Number(coverage[1].replace(/,/g, "")) !== manifest.totals.candidateFiles) {
12686
+ reportProblems.push("PROMPT says " + coverage[1] + " paths were found, the manifest says " + manifest.totals.candidateFiles);
12687
+ }
12688
+ if (Number(coverage[2].replace(/,/g, "")) !== manifest.totals.includedFiles) {
12689
+ reportProblems.push("PROMPT says " + coverage[2] + " are in the parts, the manifest says " + manifest.totals.includedFiles);
12690
+ }
12691
+ if (Number(coverage[3].replace(/,/g, "")) !== manifest.counts.skippedCount) {
12692
+ reportProblems.push("PROMPT says " + coverage[3] + " were skipped, the manifest says " + manifest.counts.skippedCount);
12693
+ }
12694
+ }
12695
+ const partial = /^- Partial files: (none|[\d,]+)\./m.exec(text2);
12696
+ if (partial !== null) {
12697
+ reportClaims += 1;
12698
+ const stated = partial[1] === "none" ? 0 : Number(partial[1].replace(/,/g, ""));
12699
+ if (stated !== manifest.incomplete.length) {
12700
+ reportProblems.push("PROMPT says " + partial[1] + " partial file(s), the manifest holds " + manifest.incomplete.length);
12701
+ }
12702
+ }
12703
+ if (text2.includes("- Redacted: no line matched a secret rule.")) {
12704
+ reportClaims += 1;
12705
+ if (manifest.totals.redactedLines !== 0) {
12706
+ reportProblems.push("PROMPT says nothing was redacted, the manifest says " + manifest.totals.redactedLines);
12707
+ }
12708
+ } else {
12709
+ const redacted = /^- Redacted: ([\d,]+) line\(s\) had values masked/m.exec(text2);
12710
+ if (redacted !== null) {
12711
+ reportClaims += 1;
12712
+ if (Number(redacted[1].replace(/,/g, "")) !== manifest.totals.redactedLines) {
12713
+ reportProblems.push("PROMPT says " + redacted[1] + " redacted line(s), the manifest says " + manifest.totals.redactedLines);
12714
+ }
12715
+ }
12716
+ }
12717
+ const layersLine = /^- Layers, by file count: (.+)$/m.exec(text2);
12718
+ if (layersLine !== null) {
12719
+ for (const layer2 of layersLine[1].matchAll(/\x60([^\x60]+)\x60 ([\d,]+)/g)) {
12720
+ reportClaims += 1;
12721
+ const expected = manifest.layers[layer2[1]] ?? 0;
12722
+ if (Number(layer2[2].replace(/,/g, "")) !== expected) {
12723
+ reportProblems.push("PROMPT layer " + layer2[1] + " says " + layer2[2] + ", the manifest says " + expected);
12724
+ }
12725
+ }
12726
+ }
12727
+ }
12728
+ }
12729
+ checks.push(
12730
+ reportProblems.length > 0 ? check(
12731
+ "report.truth",
12732
+ "The reports quote this run, not another",
12733
+ "critical",
12734
+ "fail",
12735
+ reportProblems.length + " disagreement(s): " + sample(reportProblems)
12736
+ ) : reportClaims === 0 ? check(
12737
+ "report.truth",
12738
+ "The reports quote this run, not another",
12739
+ "critical",
12740
+ "skip",
12741
+ "No report in the current shape could be compared with the manifest."
12742
+ ) : check(
12743
+ "report.truth",
12744
+ "The reports quote this run, not another",
12745
+ "critical",
12746
+ "pass",
12747
+ reportClaims + " figure(s) in README.md and PROMPT.md agree with the manifest."
12748
+ )
12749
+ );
12750
+ const indexProblems = [];
12751
+ const indexedPaths = /* @__PURE__ */ new Set();
12752
+ const checkIndexed = (kind, relativePath, part) => {
12753
+ const file = fileByPath.get(relativePath);
12754
+ if (file === void 0) {
12755
+ indexProblems.push(kind + " names " + relativePath + ", which is not in files[]");
12756
+ return;
12757
+ }
12758
+ if (part !== void 0 && file.part !== part) {
12759
+ indexProblems.push(kind + " puts " + relativePath + " in " + part + ", the manifest says " + file.part);
12760
+ }
12761
+ };
12762
+ for (const route of manifest.indexes.routes) checkIndexed("routes", route.path, route.part);
12763
+ for (const component of manifest.indexes.components) checkIndexed("components", component.path, component.part);
12764
+ for (const handler of manifest.indexes.handlers) checkIndexed("handlers", handler.path, handler.part);
12765
+ for (const directive of manifest.indexes.directives) checkIndexed("directives", directive.path);
12766
+ for (const entry of manifest.indexes.imports.byFile) {
12767
+ checkIndexed("imports.byFile", entry.path);
12768
+ if (indexedPaths.has(entry.path)) indexProblems.push("imports.byFile lists " + entry.path + " twice");
12769
+ indexedPaths.add(entry.path);
12770
+ }
12771
+ for (const entry of manifest.indexes.imports.centralFiles) {
12772
+ checkIndexed("centralFiles", entry.path);
12773
+ if (entry.importedByCount < 1) {
12774
+ indexProblems.push("centralFiles says " + entry.path + " has " + entry.importedByCount + " importer(s)");
12775
+ }
12776
+ }
12777
+ checks.push(
12778
+ indexProblems.length === 0 ? check(
12779
+ "indexes.consistent",
12780
+ "Every index entry names a file in the snapshot",
12781
+ "critical",
12782
+ "pass",
12783
+ 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."
12784
+ ) : check(
12785
+ "indexes.consistent",
12786
+ "Every index entry names a file in the snapshot",
12787
+ "critical",
12788
+ "fail",
12789
+ indexProblems.length + " index problem(s): " + sample(indexProblems)
12790
+ )
12791
+ );
12394
12792
  const packReaders = [
12395
12793
  {
12396
12794
  key: "fullJson",
@@ -12467,9 +12865,8 @@ function auditSnapshot(options) {
12467
12865
  const bodyProblems = [];
12468
12866
  let bodiesChecked = 0;
12469
12867
  for (const part of manifest.parts) {
12470
- const partText = readText2(path16.join(snapshotDir, "parts", part.filename));
12471
- if (partText === null) continue;
12472
- const sections = parsePartSections(partText);
12868
+ const sections = partSections.get(part.filename);
12869
+ if (sections === void 0) continue;
12473
12870
  for (const file of manifest.files) {
12474
12871
  if (file.part !== part.filename) continue;
12475
12872
  const section = findSection(sections, file.relativePath);
@@ -12477,6 +12874,7 @@ function auditSnapshot(options) {
12477
12874
  bodyProblems.push(file.relativePath + " has no section in " + part.filename);
12478
12875
  continue;
12479
12876
  }
12877
+ bodyByPath.set(file.relativePath, section.body);
12480
12878
  bodiesChecked += 1;
12481
12879
  const bytes = Buffer.byteLength(section.body, "utf8");
12482
12880
  const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
@@ -12502,6 +12900,198 @@ function auditSnapshot(options) {
12502
12900
  bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
12503
12901
  )
12504
12902
  );
12903
+ const structureProblems = [];
12904
+ let sectionsChecked = 0;
12905
+ for (const part of manifest.parts) {
12906
+ const text2 = partTexts.get(part.filename);
12907
+ const sections = partSections.get(part.filename);
12908
+ if (text2 === void 0 || sections === void 0) continue;
12909
+ const header = /^# Codebase Snapshot Part (\d+) of (\d+)$/m.exec(text2);
12910
+ if (header !== null) {
12911
+ if (Number(header[1]) !== part.index) {
12912
+ structureProblems.push(part.filename + " says part " + header[1] + ", the manifest says " + part.index);
12913
+ }
12914
+ if (Number(header[2]) !== manifest.parts.length) {
12915
+ structureProblems.push(part.filename + " says " + header[2] + " parts, the manifest holds " + manifest.parts.length);
12916
+ }
12917
+ }
12918
+ const filesLine = /^- Files: (\d+)$/m.exec(text2);
12919
+ if (filesLine !== null && Number(filesLine[1]) !== part.fileCount) {
12920
+ structureProblems.push(part.filename + " says " + filesLine[1] + " file(s), the manifest says " + part.fileCount);
12921
+ }
12922
+ const fingerprintLine = /^- Content Fingerprint: (\S+)$/m.exec(text2);
12923
+ if (fingerprintLine !== null && fingerprintLine[1] !== manifest.fingerprint) {
12924
+ structureProblems.push(part.filename + " names a different content fingerprint");
12925
+ }
12926
+ const tokenLine = /^- Estimated Tokens: ~([0-9,]+)$/m.exec(text2);
12927
+ if (tokenLine !== null && Number(tokenLine[1].replace(/,/g, "")) !== part.estimatedTokens) {
12928
+ structureProblems.push(part.filename + " says " + tokenLine[1] + " tokens, the manifest says " + part.estimatedTokens);
12929
+ }
12930
+ if (sections.length !== part.fileCount) {
12931
+ structureProblems.push(part.filename + " holds " + sections.length + " section(s), the manifest says " + part.fileCount);
12932
+ }
12933
+ const expectedAnchors = new Set(part.includedFiles.map((entry) => anchorForPath(entry.relativePath)));
12934
+ for (const section of sections) {
12935
+ if (section.anchor === null || !expectedAnchors.has(section.anchor)) {
12936
+ structureProblems.push(part.filename + " holds a section for " + section.path + ", which the manifest does not list");
12937
+ }
12938
+ }
12939
+ const expectedOrder = part.includedFiles.map((entry) => anchorForPath(entry.relativePath)).join("\n");
12940
+ const actualOrder = sections.map((section) => section.anchor).filter((anchor) => anchor !== null).join("\n");
12941
+ if (actualOrder !== expectedOrder) {
12942
+ structureProblems.push(part.filename + " orders its sections differently than the manifest");
12943
+ }
12944
+ for (const entry of part.includedFiles) {
12945
+ const file = fileByPath.get(entry.relativePath);
12946
+ if (file === void 0) continue;
12947
+ const section = findSection(sections, entry.relativePath);
12948
+ if (section === null) {
12949
+ structureProblems.push(entry.relativePath + " has no section in " + part.filename);
12950
+ continue;
12951
+ }
12952
+ sectionsChecked += 1;
12953
+ if (section.path !== displayPath(entry.relativePath)) {
12954
+ structureProblems.push(entry.relativePath + " is headed " + section.path);
12955
+ }
12956
+ if (section.inclusion !== null && section.inclusion !== file.inclusionMode) {
12957
+ structureProblems.push(entry.relativePath + " declares " + section.inclusion + ", the manifest says " + file.inclusionMode);
12958
+ }
12959
+ if (section.includedLines !== null && section.includedLines !== file.includedLines) {
12960
+ structureProblems.push(entry.relativePath + " declares " + section.includedLines + " line(s), the manifest says " + file.includedLines);
12961
+ }
12962
+ }
12963
+ }
12964
+ checks.push(
12965
+ structureProblems.length === 0 ? check(
12966
+ "markdown.structure",
12967
+ "Every section sits where the manifest says",
12968
+ "critical",
12969
+ "pass",
12970
+ sectionsChecked + " section(s) in " + manifest.parts.length + " part(s) match their heading, metadata and order."
12971
+ ) : check(
12972
+ "markdown.structure",
12973
+ "Every section sits where the manifest says",
12974
+ "critical",
12975
+ "fail",
12976
+ structureProblems.length + " structural problem(s): " + sample(structureProblems)
12977
+ )
12978
+ );
12979
+ const packCandidates = [
12980
+ { key: "fullJson", file: "full-codebase.json", label: "JSON", read: jsonPackBodies },
12981
+ { key: "fullXml", file: "full-codebase.xml", label: "XML", read: xmlPackBodies },
12982
+ { key: "fullMarkdown", file: "full-codebase.md", label: "markdown", read: markdownPackBodies }
12983
+ ];
12984
+ const packsWanted = packCandidates.filter((pack) => manifest.artifacts?.[pack.key] != null);
12985
+ if (packsWanted.length > 0) {
12986
+ const renderedPaths = new Map(
12987
+ manifest.files.map((file) => [escapeControls(file.relativePath), file.relativePath])
12988
+ );
12989
+ const packProblems = [];
12990
+ let packBodies = 0;
12991
+ let packSkipped = 0;
12992
+ for (const pack of packsWanted) {
12993
+ const text2 = readText2(path16.join(snapshotDir, pack.file));
12994
+ if (text2 === null) continue;
12995
+ const bodies = pack.read(text2);
12996
+ if (bodies === null) {
12997
+ packProblems.push(pack.file + " could not be read as a file pack");
12998
+ continue;
12999
+ }
13000
+ for (const [entryPath, body] of bodies) {
13001
+ const relativePath = pack.key === "fullMarkdown" ? renderedPaths.get(entryPath) ?? entryPath : entryPath;
13002
+ const file = fileByPath.get(relativePath);
13003
+ if (file === void 0) continue;
13004
+ if (file.inclusionMode === "preview" || file.inclusionMode === "signatures") {
13005
+ packSkipped += 1;
13006
+ continue;
13007
+ }
13008
+ const partBody = bodyByPath.get(relativePath);
13009
+ if (partBody === void 0) continue;
13010
+ packBodies += 1;
13011
+ const normalised = pack.key === "fullMarkdown" ? body : emittedBody(body);
13012
+ if (normalised !== partBody) {
13013
+ packProblems.push(pack.file + ": " + relativePath + " holds a different body");
13014
+ }
13015
+ }
13016
+ }
13017
+ checks.push(
13018
+ packProblems.length === 0 ? check(
13019
+ "packs.bodies",
13020
+ "Every pack body is the body the parts carry",
13021
+ "critical",
13022
+ "pass",
13023
+ packBodies + " full body/bodies match across " + packsWanted.length + " pack(s)" + (packSkipped > 0 ? "; " + packSkipped + " preview/signature body(s) are whole-file by design." : ".")
13024
+ ) : check(
13025
+ "packs.bodies",
13026
+ "Every pack body is the body the parts carry",
13027
+ "critical",
13028
+ "fail",
13029
+ packProblems.length + " body/bodies differ: " + sample(packProblems)
13030
+ )
13031
+ );
13032
+ }
13033
+ if (options.deep !== true) {
13034
+ checks.push(
13035
+ check(
13036
+ "fidelity.bodies",
13037
+ "Every full body replays from the source bytes",
13038
+ "critical",
13039
+ "skip",
13040
+ "Run health --deep to replay each full body against the file on disk."
13041
+ )
13042
+ );
13043
+ } else {
13044
+ const replayProblems = [];
13045
+ let replayed = 0;
13046
+ let unreplayable = 0;
13047
+ for (const file of manifest.files) {
13048
+ if (file.inclusionMode !== "full" || file.emptyLinesRemoved === true) {
13049
+ unreplayable += 1;
13050
+ continue;
13051
+ }
13052
+ const body = bodyByPath.get(file.relativePath);
13053
+ if (body === void 0) {
13054
+ unreplayable += 1;
13055
+ continue;
13056
+ }
13057
+ const bytes = readBytes(path16.join(repoDir, file.relativePath));
13058
+ if (bytes === null || sha256(bytes) !== file.hashSha256) {
13059
+ unreplayable += 1;
13060
+ continue;
13061
+ }
13062
+ const decoded = decodeText(bytes);
13063
+ if (decoded.binary) {
13064
+ replayProblems.push(file.relativePath + " is binary on disk");
13065
+ continue;
13066
+ }
13067
+ const expected = emittedBody(decoded.text);
13068
+ if (expected === body) {
13069
+ replayed += 1;
13070
+ continue;
13071
+ }
13072
+ const line = firstBodyMismatch(expected, body);
13073
+ if (line === null) {
13074
+ replayed += 1;
13075
+ continue;
13076
+ }
13077
+ replayProblems.push(file.relativePath + " line " + line + " is not the source line");
13078
+ }
13079
+ checks.push(
13080
+ replayProblems.length === 0 ? check(
13081
+ "fidelity.bodies",
13082
+ "Every full body replays from the source bytes",
13083
+ "critical",
13084
+ "pass",
13085
+ replayed + " full body/bodies replayed byte-for-byte (redaction allowed); " + unreplayable + " not replayable by design or because the file moved."
13086
+ ) : check(
13087
+ "fidelity.bodies",
13088
+ "Every full body replays from the source bytes",
13089
+ "critical",
13090
+ "fail",
13091
+ replayProblems.length + " body/bodies disagree with the source: " + sample(replayProblems)
13092
+ )
13093
+ );
13094
+ }
12505
13095
  const indexParent = path16.dirname(snapshotDir);
12506
13096
  const indexPath = path16.join(indexParent, "WORKSPACE.json");
12507
13097
  if (fs16.existsSync(indexPath)) {
@@ -12665,9 +13255,13 @@ function auditSnapshot(options) {
12665
13255
  )
12666
13256
  );
12667
13257
  let recomputed = 0;
13258
+ const partTokens = /* @__PURE__ */ new Map();
12668
13259
  for (const part of manifest.parts) {
12669
- const text2 = readText2(path16.join(snapshotDir, "parts", part.filename));
12670
- if (text2 !== null) recomputed += estimateTokens(text2);
13260
+ const text2 = partTexts.get(part.filename);
13261
+ if (text2 === void 0) continue;
13262
+ const tokens = estimateTokens(text2);
13263
+ partTokens.set(part.filename, tokens);
13264
+ recomputed += tokens;
12671
13265
  }
12672
13266
  const recorded = manifest.totals.estimatedTokens ?? null;
12673
13267
  checks.push(
@@ -12691,6 +13285,22 @@ function auditSnapshot(options) {
12691
13285
  "Recorded " + recorded + ", recomputed " + recomputed + ": the manifest no longer describes these parts."
12692
13286
  )
12693
13287
  );
13288
+ const partSizes = [...partTokens.values()];
13289
+ const largestPart = partSizes.length === 0 ? 0 : Math.max(...partSizes);
13290
+ const largestFile = manifest.files.reduce((largest, file) => {
13291
+ const body = bodyByPath.get(file.relativePath);
13292
+ return body === void 0 ? largest : Math.max(largest, estimateTokens(body));
13293
+ }, 0);
13294
+ const fits = (window) => partSizes.filter((tokens) => tokens <= window).length;
13295
+ checks.push(
13296
+ check(
13297
+ "tokens.fit",
13298
+ "The parts fit a context window",
13299
+ "warning",
13300
+ largestPart > 2e5 || largestFile > 2e5 ? "warn" : "pass",
13301
+ 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."
13302
+ )
13303
+ );
12694
13304
  const overBudget = manifest.parts.filter(
12695
13305
  (part) => part.byteSize > manifest.budgets.maxPartBytes
12696
13306
  );
@@ -14561,6 +15171,10 @@ var healthTool = {
14561
15171
  minimum: 1024,
14562
15172
  description: "Cap on the text the secret and host-path scans read (default 8 MB)."
14563
15173
  },
15174
+ deep: {
15175
+ type: "boolean",
15176
+ description: "Replay every full body against the source on disk. Slower, and catches a generator that wrote the wrong bytes."
15177
+ },
14564
15178
  root: ROOT_PROPERTY,
14565
15179
  outDir: OUT_DIR_PROPERTY
14566
15180
  },
@@ -14582,7 +15196,8 @@ var healthTool = {
14582
15196
  const report2 = auditSnapshot({
14583
15197
  snapshotDir: path19.resolve(workspace.root, workspace.config.outDir),
14584
15198
  repoDir: workspace.root,
14585
- ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {}
15199
+ ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
15200
+ ...args.deep === true ? { deep: true } : {}
14586
15201
  });
14587
15202
  const lines = [
14588
15203
  "Health: " + report2.score + "/100 (" + report2.counts.pass + " passed, " + report2.counts.warn + " warning(s), " + report2.counts.fail + " failed)",
@@ -15743,7 +16358,7 @@ var COMMAND_OPTION_SCOPE = {
15743
16358
  ],
15744
16359
  // The health audit resolves the config only to find the output directory; --strict decides the
15745
16360
  // exit code, and every other setting would be a promise the command does not keep.
15746
- health: ["cwd", "out-dir", "format", "strict", "all-members", "no-update-check", "help"],
16361
+ health: ["cwd", "out-dir", "format", "strict", "all-members", "deep", "no-update-check", "help"],
15747
16362
  validate: VALIDATE_OPTIONS,
15748
16363
  // `report` reads `manifest.json` and prints what is there; a generation setting would change
15749
16364
  // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
@@ -16067,7 +16682,7 @@ function buildAgentContract() {
16067
16682
  {
16068
16683
  name: "health",
16069
16684
  aliases: [],
16070
- 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.",
16685
+ 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.",
16071
16686
  positionals: [],
16072
16687
  exits: [0, 1, 2]
16073
16688
  },
@@ -16438,6 +17053,13 @@ function buildAgentContract() {
16438
17053
  appliesTo: optionAppliesTo("strict"),
16439
17054
  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."
16440
17055
  },
17056
+ {
17057
+ flag: "--deep",
17058
+ type: "boolean",
17059
+ default: false,
17060
+ appliesTo: optionAppliesTo("deep"),
17061
+ 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."
17062
+ },
16441
17063
  {
16442
17064
  flag: "--changed-since",
16443
17065
  type: "string",
@@ -21468,6 +22090,7 @@ var CLI_OPTIONS = {
21468
22090
  only: { type: "string" },
21469
22091
  ignore: { type: "string" },
21470
22092
  "all-members": { type: "boolean" },
22093
+ deep: { type: "boolean" },
21471
22094
  help: { type: "boolean", short: "h" },
21472
22095
  version: { type: "boolean", short: "v" }
21473
22096
  };
@@ -21575,6 +22198,11 @@ Options:
21575
22198
  --install-hook As for init
21576
22199
  --preset / --include / --exclude / --force As for init
21577
22200
 
22201
+ health only:
22202
+ --strict Treat warnings as failures (exit 2 on a critical failure)
22203
+ --all-members Audit every snapshot a --workspace run wrote
22204
+ --deep Replay every full body against the source on disk
22205
+
21578
22206
  skill only:
21579
22207
  --install Write the skill into the repository instead of printing
21580
22208
  --target <name> claude | cursor | all (default: all)
@@ -21919,6 +22547,7 @@ function parseCliArgs(argv) {
21919
22547
  only: values.only === void 0 ? void 0 : String(values.only).split(",").map((item) => item.trim()).filter(Boolean),
21920
22548
  ignore: values.ignore === void 0 ? void 0 : String(values.ignore).split(",").map((item) => item.trim()).filter(Boolean),
21921
22549
  allMembers: values["all-members"] === true ? true : void 0,
22550
+ deep: values.deep === true ? true : void 0,
21922
22551
  budgetTokens: values["budget-tokens"] === void 0 ? void 0 : parsePositiveInteger(values["budget-tokens"], "budget-tokens", 500),
21923
22552
  delta: values.delta === void 0 ? void 0 : String(values.delta),
21924
22553
  slice: values.slice === void 0 ? void 0 : String(values.slice),
@@ -22734,7 +23363,11 @@ ${USAGE}
22734
23363
  return 0;
22735
23364
  }
22736
23365
  const snapshotDir = path27.resolve(resolved.cwd, resolved.outDir);
22737
- const report2 = auditSnapshot({ snapshotDir, repoDir: resolved.cwd });
23366
+ const report2 = auditSnapshot({
23367
+ snapshotDir,
23368
+ repoDir: resolved.cwd,
23369
+ ...invocation.deep === true ? { deep: true } : {}
23370
+ });
22738
23371
  emit(invocation.format, report2, () => renderHealthText(report2));
22739
23372
  if (report2.counts.fail > 0) return invocation.strict === true ? 2 : 1;
22740
23373
  if (invocation.strict === true && report2.counts.warn > 0) return 1;