codebase-snapshot 0.20.0 → 0.20.3

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