codebase-snapshot 0.9.18 → 0.10.1

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
@@ -525,7 +525,7 @@ var JS_PRESETS = [
525
525
  ...commonKinds()
526
526
  ],
527
527
  exclude: [".nuxt", ".output"],
528
- recommendedBudget: "200k"
528
+ recommendedBudget: "300k"
529
529
  },
530
530
  {
531
531
  name: "sveltekit",
@@ -546,7 +546,7 @@ var JS_PRESETS = [
546
546
  ...commonKinds()
547
547
  ],
548
548
  exclude: [".svelte-kit", ".vercel"],
549
- recommendedBudget: "200k"
549
+ recommendedBudget: "300k"
550
550
  },
551
551
  {
552
552
  name: "remix",
@@ -560,7 +560,7 @@ var JS_PRESETS = [
560
560
  ],
561
561
  kinds: [kindOf("route", "routes/"), ...commonKinds()],
562
562
  exclude: [".cache", "public/build"],
563
- recommendedBudget: "200k"
563
+ recommendedBudget: "300k"
564
564
  },
565
565
  {
566
566
  name: "astro",
@@ -575,7 +575,7 @@ var JS_PRESETS = [
575
575
  ],
576
576
  kinds: [suffixKind("page", ".astro"), kindOf("layout", "layouts/"), ...commonKinds()],
577
577
  exclude: [".astro", "dist"],
578
- recommendedBudget: "150k"
578
+ recommendedBudget: "300k"
579
579
  },
580
580
  {
581
581
  name: "angular",
@@ -599,7 +599,7 @@ var JS_PRESETS = [
599
599
  ...commonKinds()
600
600
  ],
601
601
  exclude: [".angular", "dist"],
602
- recommendedBudget: "200k"
602
+ recommendedBudget: "300k"
603
603
  },
604
604
  {
605
605
  name: "solid",
@@ -612,7 +612,7 @@ var JS_PRESETS = [
612
612
  ],
613
613
  kinds: [kindOf("route", "routes/"), ...commonKinds()],
614
614
  exclude: [".solid", "dist"],
615
- recommendedBudget: "120k"
615
+ recommendedBudget: "300k"
616
616
  },
617
617
  {
618
618
  name: "vue-vite",
@@ -645,7 +645,7 @@ var JS_PRESETS = [
645
645
  ...commonKinds()
646
646
  ],
647
647
  exclude: [".vite", "dist"],
648
- recommendedBudget: "120k"
648
+ recommendedBudget: "300k"
649
649
  },
650
650
  {
651
651
  name: "react-vite",
@@ -659,7 +659,7 @@ var JS_PRESETS = [
659
659
  layers: VITE_LAYERS,
660
660
  kinds: VITE_KINDS,
661
661
  exclude: [".vite", "dist"],
662
- recommendedBudget: "120k"
662
+ recommendedBudget: "300k"
663
663
  },
664
664
  {
665
665
  name: "nest",
@@ -685,7 +685,7 @@ var JS_PRESETS = [
685
685
  ...commonKinds()
686
686
  ],
687
687
  exclude: ["dist", "node_modules"],
688
- recommendedBudget: "200k"
688
+ recommendedBudget: "300k"
689
689
  },
690
690
  {
691
691
  name: "node-express",
@@ -694,7 +694,7 @@ var JS_PRESETS = [
694
694
  layers: NODE_LAYERS,
695
695
  kinds: NODE_KINDS,
696
696
  exclude: ["dist"],
697
- recommendedBudget: "200k"
697
+ recommendedBudget: "300k"
698
698
  },
699
699
  {
700
700
  name: "node-lib",
@@ -710,7 +710,7 @@ var JS_PRESETS = [
710
710
  ],
711
711
  kinds: [suffixKind("type", ".d.ts"), ...commonKinds()],
712
712
  exclude: ["dist"],
713
- recommendedBudget: "120k"
713
+ recommendedBudget: "300k"
714
714
  }
715
715
  ];
716
716
 
@@ -741,7 +741,7 @@ var LANGUAGE_PRESETS = [
741
741
  ...commonKinds()
742
742
  ],
743
743
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs", "staticfiles", "media"],
744
- recommendedBudget: "150k"
744
+ recommendedBudget: "300k"
745
745
  },
746
746
  {
747
747
  name: "python-fastapi",
@@ -764,7 +764,7 @@ var LANGUAGE_PRESETS = [
764
764
  ...commonKinds()
765
765
  ],
766
766
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs"],
767
- recommendedBudget: "150k"
767
+ recommendedBudget: "300k"
768
768
  },
769
769
  {
770
770
  name: "python-lib",
@@ -778,7 +778,7 @@ var LANGUAGE_PRESETS = [
778
778
  ],
779
779
  kinds: [suffixKind("module", ".py"), ...commonKinds()],
780
780
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs"],
781
- recommendedBudget: "120k"
781
+ recommendedBudget: "300k"
782
782
  },
783
783
  {
784
784
  name: "go",
@@ -802,7 +802,7 @@ var LANGUAGE_PRESETS = [
802
802
  ...commonKinds()
803
803
  ],
804
804
  exclude: ["vendor", "testdata"],
805
- recommendedBudget: "200k"
805
+ recommendedBudget: "300k"
806
806
  },
807
807
  {
808
808
  name: "rust",
@@ -818,7 +818,7 @@ var LANGUAGE_PRESETS = [
818
818
  ],
819
819
  kinds: [suffixKind("module", ".rs"), suffixKind("test", "_test.rs"), ...commonKinds()],
820
820
  exclude: ["target"],
821
- recommendedBudget: "200k"
821
+ recommendedBudget: "300k"
822
822
  },
823
823
  {
824
824
  name: "java-spring",
@@ -841,7 +841,7 @@ var LANGUAGE_PRESETS = [
841
841
  ...commonKinds()
842
842
  ],
843
843
  exclude: [".gradle", "out", "target"],
844
- recommendedBudget: "200k"
844
+ recommendedBudget: "300k"
845
845
  },
846
846
  {
847
847
  name: "dotnet",
@@ -864,7 +864,7 @@ var LANGUAGE_PRESETS = [
864
864
  ...commonKinds()
865
865
  ],
866
866
  exclude: ["bin", "obj", ".vs"],
867
- recommendedBudget: "200k"
867
+ recommendedBudget: "300k"
868
868
  },
869
869
  {
870
870
  name: "php-laravel",
@@ -890,7 +890,7 @@ var LANGUAGE_PRESETS = [
890
890
  ...commonKinds()
891
891
  ],
892
892
  exclude: ["vendor", "storage", "bootstrap/cache", "public/build"],
893
- recommendedBudget: "150k"
893
+ recommendedBudget: "300k"
894
894
  },
895
895
  {
896
896
  name: "ruby-rails",
@@ -915,7 +915,7 @@ var LANGUAGE_PRESETS = [
915
915
  ...commonKinds()
916
916
  ],
917
917
  exclude: [".bundle", "log", "tmp", "vendor/bundle", "public/assets"],
918
- recommendedBudget: "150k"
918
+ recommendedBudget: "300k"
919
919
  }
920
920
  ];
921
921
 
@@ -977,7 +977,7 @@ var SHAPE_PRESETS = [
977
977
  ],
978
978
  kinds: commonKinds(),
979
979
  exclude: [".turbo", ".nx"],
980
- recommendedBudget: "200k"
980
+ recommendedBudget: "300k"
981
981
  },
982
982
  {
983
983
  name: "infra",
@@ -995,7 +995,7 @@ var SHAPE_PRESETS = [
995
995
  ...commonKinds()
996
996
  ],
997
997
  exclude: [".terraform", ".terragrunt-cache"],
998
- recommendedBudget: "100k"
998
+ recommendedBudget: "300k"
999
999
  },
1000
1000
  {
1001
1001
  name: "docs",
@@ -1012,7 +1012,7 @@ var SHAPE_PRESETS = [
1012
1012
  ],
1013
1013
  kinds: commonKinds(),
1014
1014
  exclude: [".docusaurus", ".vitepress/dist", "site"],
1015
- recommendedBudget: "100k"
1015
+ recommendedBudget: "300k"
1016
1016
  },
1017
1017
  {
1018
1018
  name: "generic",
@@ -1024,7 +1024,7 @@ var SHAPE_PRESETS = [
1024
1024
  layers: DEFAULT_LAYERS,
1025
1025
  kinds: DEFAULT_KINDS,
1026
1026
  exclude: [],
1027
- recommendedBudget: "120k"
1027
+ recommendedBudget: "300k"
1028
1028
  }
1029
1029
  ];
1030
1030
 
@@ -2150,7 +2150,7 @@ function applySpans(line, spans) {
2150
2150
 
2151
2151
  // src/version.ts
2152
2152
  var GENERATOR_NAME = "codebase-snapshot";
2153
- var GENERATOR_VERSION = "0.9.18";
2153
+ var GENERATOR_VERSION = "0.10.1";
2154
2154
  var SCHEMA_VERSION = "3.0.0";
2155
2155
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2156
2156
  function isOurGeneratorName(name) {
@@ -3488,6 +3488,16 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3488
3488
  }
3489
3489
  return { config: null, file: null, warnings, errors };
3490
3490
  }
3491
+ function largeFileBytesFor(maxPartBytes, cliOptions, userConfig) {
3492
+ const requested = cliOptions?.largeFileBytes ?? userConfig?.largeFileBytes;
3493
+ const value = boundedBytes(requested, maxPartBytes, 1, "largeFileBytes");
3494
+ if (value > maxPartBytes) {
3495
+ throw new Error(
3496
+ `largeFileBytes (${describeBytes(value)}) is larger than maxPartBytes (${describeBytes(maxPartBytes)}). A file between the two cannot fit a part, so it would be cut to fit while the manifest called it complete. Raise maxPartBytes to at least largeFileBytes, or lower largeFileBytes.`
3497
+ );
3498
+ }
3499
+ return value;
3500
+ }
3491
3501
  var MIN_MAX_PART_BYTES = 4096;
3492
3502
  var MIN_MAX_PART_TOKENS = MIN_MAX_PART_BYTES / 4;
3493
3503
  var ARTIFACT_NAMES = [
@@ -3930,7 +3940,7 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
3930
3940
  tmpDir,
3931
3941
  maxPartBytes: resolvedMaxPartBytes,
3932
3942
  ...maxPartTokens === void 0 ? {} : { maxPartTokens },
3933
- largeFileBytes: boundedBytes(cliOptions?.largeFileBytes ?? userConfig?.largeFileBytes, 200 * 1024, 1, "largeFileBytes"),
3943
+ largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
3934
3944
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
3935
3945
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
3936
3946
  includeMonolith: artifacts.monolith,
@@ -7008,7 +7018,8 @@ function truncatePreview(content, headLines, tailLines) {
7008
7018
  content: normalised,
7009
7019
  isTruncated: false,
7010
7020
  originalLines: total,
7011
- includedLines: total
7021
+ includedLines: total,
7022
+ omittedRanges: []
7012
7023
  };
7013
7024
  }
7014
7025
  const window = normalised.endsWith("\n") ? lines.slice(0, -1) : lines;
@@ -7020,13 +7031,16 @@ function truncatePreview(content, headLines, tailLines) {
7020
7031
  `... [${omitted} lines omitted: file exceeds large file size budget] ...`,
7021
7032
  ...tail
7022
7033
  ].join("\n");
7034
+ const firstOmitted = head.length + 1;
7035
+ const lastOmitted = total - tail.length;
7023
7036
  return {
7024
7037
  content: result,
7025
7038
  isTruncated: true,
7026
7039
  originalLines: total,
7027
7040
  // Head + notice + tail is exactly what is emitted; counting the slice is
7028
7041
  // wrong when the source ended with a newline (the trailing "" issue above).
7029
- includedLines: head.length + tail.length + 1
7042
+ includedLines: head.length + tail.length + 1,
7043
+ omittedRanges: lastOmitted >= firstOmitted ? [[firstOmitted, lastOmitted]] : []
7030
7044
  };
7031
7045
  }
7032
7046
 
@@ -7629,7 +7643,7 @@ var DEFAULT_ANSWERS = {
7629
7643
  branch: "main",
7630
7644
  maxPartBytes: "300k",
7631
7645
  maxPartTokens: null,
7632
- largeFileBytes: "200k",
7646
+ largeFileBytes: "300k",
7633
7647
  maxMonolithBytes: null,
7634
7648
  discovery: "auto",
7635
7649
  skeleton: false,
@@ -7689,7 +7703,9 @@ function renderConfig(answers) {
7689
7703
  // The same ceiling expressed in tokens; it narrows maxPartBytes rather than
7690
7704
  // replacing it. null = not set. Minimum 1024.
7691
7705
  maxPartTokens: ${answers.maxPartTokens === null ? "null" : String(answers.maxPartTokens)},
7692
- // Files above this size get a head/tail preview instead of the full body.
7706
+ // Files above this size get a head/tail preview instead of the full body. It may not
7707
+ // exceed maxPartBytes: a file between the two could not fit a part, and cutting it to fit
7708
+ // while the manifest called it a preview is exactly what this ceiling pair must prevent.
7693
7709
  largeFileBytes: ${size(answers.largeFileBytes)},
7694
7710
  previewHeadLines: 80,
7695
7711
  previewTailLines: 40,
@@ -8377,6 +8393,9 @@ async function runInit(options) {
8377
8393
  let reason = detected.reason;
8378
8394
  let fallback = detected.fallback;
8379
8395
  const notes = [];
8396
+ const budgetBytes = parseByteSize(options.maxPartBytes ?? detected.recommendedBudget ?? DEFAULT_ANSWERS.maxPartBytes) ?? 307200;
8397
+ const tokenBudgetBytes = options.maxPartTokens === void 0 || options.maxPartTokens === null ? void 0 : options.maxPartTokens * 4;
8398
+ const effectiveBudgetBytes = tokenBudgetBytes === void 0 ? budgetBytes : Math.min(budgetBytes, tokenBudgetBytes);
8380
8399
  const answers = {
8381
8400
  preset: detected.presetName,
8382
8401
  // The repository's own branch, read the same way the generator reads it.
@@ -8390,7 +8409,11 @@ async function runInit(options) {
8390
8409
  // what the run used is drift the next `validate` reports, and `setup` is the one command
8391
8410
  // that is supposed to leave a project in a consistent state.
8392
8411
  maxPartTokens: options.maxPartTokens ?? DEFAULT_ANSWERS.maxPartTokens,
8393
- largeFileBytes: options.largeFileBytes ?? DEFAULT_ANSWERS.largeFileBytes,
8412
+ // Follows the budget unless the caller named one. A threshold above the part budget is a
8413
+ // config error (a file between the two cannot fit a part, so it is cut while the manifest
8414
+ // calls it a preview); a fixed 200 KB beside `--max-part-tokens 32k` made setup's own output
8415
+ // fail its own validate, and a fixed 200 KB under a 300 KB budget previewed files that fit.
8416
+ largeFileBytes: options.largeFileBytes ?? effectiveBudgetBytes,
8394
8417
  maxMonolithBytes: options.maxMonolithBytes ?? DEFAULT_ANSWERS.maxMonolithBytes,
8395
8418
  discovery: options.discovery ?? DEFAULT_ANSWERS.discovery,
8396
8419
  skeleton: options.skeleton ?? DEFAULT_ANSWERS.skeleton,
@@ -8881,7 +8904,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
8881
8904
  );
8882
8905
  for (const file of affected) {
8883
8906
  const status = file.isPreviewTruncated ? "Truncated" : "Full";
8884
- const cutBy = file.isLarge ? "largeFileBytes" : "maxPartBytes";
8907
+ const cutBy = file.truncationReason === "part-budget" ? "maxPartBytes" : "largeFileBytes";
8885
8908
  lines.push(
8886
8909
  `| ${code(file.relativePath)} | ${file.sizeBytes} | ${file.lines} | ${file.includedBytes} | ${file.includedLines} | ${status} | ${cutBy} |`
8887
8910
  );
@@ -9126,7 +9149,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
9126
9149
  section.file.originalLines
9127
9150
  );
9128
9151
  if (shrunk.isTruncated) {
9129
- applyTruncatedContent(section.file, shrunk.content);
9152
+ applyTruncatedContent(section.file, shrunk.content, "part-budget");
9130
9153
  section.text = renderFileSection(section.file);
9131
9154
  section.byteSize = Buffer.byteLength(section.text, "utf8");
9132
9155
  assemblies.delete(group);
@@ -9200,7 +9223,7 @@ function prepareSection(file, sectionBudget, partBudget) {
9200
9223
  file.originalLines
9201
9224
  );
9202
9225
  if (!truncated.isTruncated) return;
9203
- applyTruncatedContent(file, truncated.content);
9226
+ applyTruncatedContent(file, truncated.content, "part-budget");
9204
9227
  text2 = renderFileSection(file);
9205
9228
  byteSize = Buffer.byteLength(text2, "utf8");
9206
9229
  };
@@ -9208,14 +9231,16 @@ function prepareSection(file, sectionBudget, partBudget) {
9208
9231
  if (byteSize > sectionBudget && file.summary) {
9209
9232
  file.summary = void 0;
9210
9233
  file.summaryOmitted = true;
9234
+ file.summaryOmittedReason = "part-budget";
9211
9235
  text2 = renderFileSection(file);
9212
9236
  byteSize = Buffer.byteLength(text2, "utf8");
9213
9237
  shrinkBody();
9214
9238
  }
9215
9239
  if (byteSize > sectionBudget) {
9216
- applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
9240
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE, "section-metadata");
9217
9241
  file.summary = void 0;
9218
9242
  file.summaryOmitted = true;
9243
+ file.summaryOmittedReason = "part-budget";
9219
9244
  text2 = renderFileSection(file);
9220
9245
  byteSize = Buffer.byteLength(text2, "utf8");
9221
9246
  if (byteSize > sectionBudget) {
@@ -9264,10 +9289,14 @@ function fenceIsOpen(text2, fence) {
9264
9289
  }
9265
9290
  return open;
9266
9291
  }
9267
- function applyTruncatedContent(file, content) {
9292
+ var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
9293
+ function applyTruncatedContent(file, content, reason) {
9294
+ const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
9268
9295
  file.content = content;
9269
9296
  file.isPreviewTruncated = true;
9270
9297
  file.inclusionMode = "preview";
9298
+ file.truncationReason = reason;
9299
+ file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
9271
9300
  file.includedBytes = Buffer.byteLength(content, "utf8");
9272
9301
  file.includedLines = countLines(content);
9273
9302
  }
@@ -9414,7 +9443,9 @@ function renderFileSection(file) {
9414
9443
  compactMetadata(file),
9415
9444
  ...file.summaryQuality ? [`- Summary Quality: ${file.summaryQuality}`] : [],
9416
9445
  ...renderSummary(file.summary, file.inclusionMode),
9417
- ...file.summaryOmitted ? ["- Summary: (omitted: exceeds the part budget)"] : [],
9446
+ ...file.summaryOmitted ? [
9447
+ file.summaryOmittedReason === "preview" ? "- Summary: (omitted: the file is a head/tail preview)" : file.summaryOmittedReason === "oversize" ? "- Summary: (omitted: the file is too large to parse)" : "- Summary: (omitted: exceeds the part budget)"
9448
+ ] : [],
9418
9449
  "",
9419
9450
  file.inclusionMode === "preview" ? "#### Bounded Preview" : "#### Content",
9420
9451
  "",
@@ -10194,6 +10225,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10194
10225
  const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
10195
10226
  let finalContent = redacted;
10196
10227
  let isPreviewTruncated = false;
10228
+ let truncationReason;
10229
+ let omittedRanges = [];
10197
10230
  let includedLines = lineCount;
10198
10231
  let inclusionMode = "full";
10199
10232
  if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
@@ -10210,6 +10243,10 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10210
10243
  isPreviewTruncated = preview.isTruncated;
10211
10244
  includedLines = preview.includedLines;
10212
10245
  inclusionMode = isPreviewTruncated ? "preview" : "full";
10246
+ if (isPreviewTruncated) {
10247
+ truncationReason = "large-file-budget";
10248
+ omittedRanges = preview.omittedRanges;
10249
+ }
10213
10250
  }
10214
10251
  let summary;
10215
10252
  let summaryQuality;
@@ -10244,6 +10281,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10244
10281
  finalContent,
10245
10282
  inclusionMode,
10246
10283
  isPreviewTruncated,
10284
+ truncationReason,
10285
+ omittedRanges,
10247
10286
  includedLines,
10248
10287
  isLarge,
10249
10288
  summary,
@@ -10354,8 +10393,30 @@ function buildIndexes(files, tsconfigPaths) {
10354
10393
  }))
10355
10394
  };
10356
10395
  }
10357
- function verifyInMemory(files, parts) {
10396
+ function verifyInMemory(files, parts, unaccounted) {
10358
10397
  const errors = [];
10398
+ if (unaccounted.length > 0) {
10399
+ const shown = unaccounted.slice(0, 5).join(", ");
10400
+ errors.push(
10401
+ `${unaccounted.length} scanned file(s) appear in neither files[] nor skipped[]${unaccounted.length > 5 ? ` (first five: ${shown})` : `: ${shown}`}.`
10402
+ );
10403
+ }
10404
+ for (const file of files) {
10405
+ if (file.isPreviewTruncated && file.truncationReason === void 0) {
10406
+ errors.push(`${file.relativePath} is truncated but records no truncationReason.`);
10407
+ }
10408
+ const ranges = file.omittedRanges ?? [];
10409
+ if (file.truncationReason !== void 0 && ranges.length === 0) {
10410
+ errors.push(`${file.relativePath} is truncated but records no omittedRanges.`);
10411
+ }
10412
+ for (const [from, to] of ranges) {
10413
+ if (from < 1 || to < from || to > file.lines) {
10414
+ errors.push(
10415
+ `${file.relativePath} records omitted range ${from}-${to}, outside 1-${file.lines}.`
10416
+ );
10417
+ }
10418
+ }
10419
+ }
10359
10420
  const partNames = new Set(parts.map((part) => part.filename));
10360
10421
  for (const file of files) {
10361
10422
  if (!file.part || !partNames.has(file.part)) {
@@ -11106,7 +11167,20 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11106
11167
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
11107
11168
  const hadPrevious = fs15.existsSync(outDir);
11108
11169
  if (hadPrevious) beforeSwap?.();
11109
- if (hadPrevious) fs15.renameSync(outDir, backupDir);
11170
+ let movedAside = false;
11171
+ if (hadPrevious) {
11172
+ try {
11173
+ fs15.renameSync(outDir, backupDir);
11174
+ movedAside = true;
11175
+ } catch (err) {
11176
+ if (!isLockError(err)) throw err;
11177
+ fs15.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
11178
+ process.stderr.write(
11179
+ `\u26A0 ${outDir} could not be moved aside (${err.message}), so it was replaced in place. Close anything holding the old snapshot open to avoid this next time.
11180
+ `
11181
+ );
11182
+ }
11183
+ }
11110
11184
  try {
11111
11185
  try {
11112
11186
  fs15.renameSync(stagingDir, outDir);
@@ -11126,9 +11200,14 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11126
11200
  }
11127
11201
  }
11128
11202
  } catch (err) {
11129
- if (hadPrevious && fs15.existsSync(backupDir)) {
11203
+ if (hadPrevious && movedAside && fs15.existsSync(backupDir)) {
11130
11204
  if (fs15.existsSync(outDir)) fs15.rmSync(outDir, { recursive: true, force: true });
11131
11205
  fs15.renameSync(backupDir, outDir);
11206
+ } else if (hadPrevious && !movedAside) {
11207
+ process.stderr.write(
11208
+ `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
11209
+ `
11210
+ );
11132
11211
  }
11133
11212
  throw err;
11134
11213
  }
@@ -11143,6 +11222,10 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11143
11222
  }
11144
11223
  }
11145
11224
  }
11225
+ function isLockError(err) {
11226
+ const code = err.code;
11227
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
11228
+ }
11146
11229
  function sleepSync(milliseconds) {
11147
11230
  const buffer = new Int32Array(new SharedArrayBuffer(4));
11148
11231
  Atomics.wait(buffer, 0, 0, milliseconds);
@@ -11246,10 +11329,6 @@ function generateSnapshot(configInput, options) {
11246
11329
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
11247
11330
  const secretFindings = [];
11248
11331
  const warnings = [];
11249
- const budgetOrderCutsFiles = () => {
11250
- if (config.maxPartBytes >= config.largeFileBytes) return false;
11251
- return files.some((file) => file.isPreviewTruncated && !file.isLarge);
11252
- };
11253
11332
  const encodingNotes = [];
11254
11333
  const fileWarnings = [];
11255
11334
  const oversizeSummaryPaths = [];
@@ -11411,11 +11490,16 @@ function generateSnapshot(configInput, options) {
11411
11490
  inclusionMode: derivation.inclusionMode,
11412
11491
  isLarge: derivation.isLarge,
11413
11492
  isPreviewTruncated: derivation.isPreviewTruncated,
11493
+ ...derivation.truncationReason === void 0 ? {} : { truncationReason: derivation.truncationReason },
11494
+ ...derivation.omittedRanges.length === 0 ? {} : { omittedRanges: derivation.omittedRanges },
11414
11495
  originalLines: lineCount,
11415
11496
  includedLines: derivation.includedLines,
11416
11497
  includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
11417
11498
  summary: derivation.summary,
11418
11499
  summaryQuality: derivation.summaryQuality,
11500
+ // A summary skipped for size is not an absent summary: record it the same way the
11501
+ // partitioner records one it had to drop, so a reader can tell the two apart.
11502
+ ...derivation.summarySkip === null ? {} : { summaryOmitted: true, summaryOmittedReason: derivation.summarySkip },
11419
11503
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
11420
11504
  content: derivation.finalContent
11421
11505
  });
@@ -11535,7 +11619,28 @@ function generateSnapshot(configInput, options) {
11535
11619
  }
11536
11620
  const parts = partitionByBudget(files, config, fingerprint);
11537
11621
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11538
- const validationErrors = verifyInMemory(files, parts);
11622
+ const incomplete = files.flatMap((file) => {
11623
+ if (file.truncationReason === void 0) return [];
11624
+ const ranges = file.omittedRanges ?? [];
11625
+ const omittedLines = ranges.reduce((total, [from, to]) => total + (to - from + 1), 0);
11626
+ return [
11627
+ {
11628
+ relativePath: file.relativePath,
11629
+ part: file.part,
11630
+ reason: file.truncationReason,
11631
+ omittedRanges: ranges,
11632
+ omittedLines,
11633
+ includedLines: file.includedLines,
11634
+ lines: file.lines
11635
+ }
11636
+ ];
11637
+ });
11638
+ const accounted = /* @__PURE__ */ new Set([
11639
+ ...files.map((file) => maskPathText(file.relativePath, config.secretRules)),
11640
+ ...skipped.map((record) => record.path)
11641
+ ]);
11642
+ const unaccounted = candidateFiles.map((candidate) => maskPathText(candidate, config.secretRules)).filter((candidate) => !accounted.has(candidate));
11643
+ const validationErrors = verifyInMemory(files, parts, unaccounted);
11539
11644
  const totalContentBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11540
11645
  const maskName = (value) => maskPathText(value, config.secretRules);
11541
11646
  const manifest = {
@@ -11596,7 +11701,8 @@ function generateSnapshot(configInput, options) {
11596
11701
  partsCount: parts.length,
11597
11702
  skippedCount: skipped.length,
11598
11703
  largeFileCount,
11599
- truncatedPreviewCount
11704
+ truncatedPreviewCount,
11705
+ incompleteCount: incomplete.length
11600
11706
  },
11601
11707
  totals: {
11602
11708
  candidateFiles: files.length + skipped.length,
@@ -11633,19 +11739,14 @@ function generateSnapshot(configInput, options) {
11633
11739
  return rest;
11634
11740
  }),
11635
11741
  skipped: maskSkipRecords(skipped, config.secretRules),
11742
+ incomplete,
11636
11743
  warnings
11637
11744
  };
11638
11745
  manifest.totals.redactedLines = secretFindings.length;
11639
11746
  manifest.totals.warningCount = manifest.warnings.length;
11640
- if (budgetOrderCutsFiles()) {
11747
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
11641
11748
  manifest.warnings.push(
11642
- `maxPartBytes (${config.maxPartBytes} B) is below largeFileBytes (${config.largeFileBytes} B), so files cut by the part budget are not marked as large previews. Increase maxPartBytes or lower largeFileBytes.`
11643
- );
11644
- manifest.totals.warningCount = manifest.warnings.length;
11645
- }
11646
- if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
11647
- manifest.warnings.push(
11648
- `${files.filter((file) => file.isPreviewTruncated).length} file(s) were previewed because largeFileBytes (${config.largeFileBytes} B) is not above maxPartBytes (${config.maxPartBytes} B). Raise largeFileBytes if a whole file is wanted.`
11749
+ `${files.filter((file) => file.isPreviewTruncated).length} file(s) were previewed because largeFileBytes (${config.largeFileBytes} B) is below maxPartBytes (${config.maxPartBytes} B). Raise largeFileBytes if a whole file is wanted.`
11649
11750
  );
11650
11751
  manifest.totals.warningCount = manifest.warnings.length;
11651
11752
  }
@@ -13021,6 +13122,9 @@ var readTool = {
13021
13122
  structured: {
13022
13123
  path: entry.relativePath,
13023
13124
  part: entry.part,
13125
+ // The window itself: a caller that wants to measure or re-send what it received should
13126
+ // not have to strip the header and the paging note back off `text`.
13127
+ body,
13024
13128
  layer: entry.layer,
13025
13129
  kind: entry.kind,
13026
13130
  language: entry.language,
@@ -13586,7 +13690,7 @@ function buildAgentContract() {
13586
13690
  id: "consume",
13587
13691
  run: "read ./snapshot/parts/*.md, then ./snapshot/manifest.json, then ./snapshot/reports/audit.md",
13588
13692
  expect: "the code, the index of what was included, and the risk findings",
13589
- notes: "manifest.json.files[] lists every included file with layer, kind, language, part and summary. manifest.skipped[] explains every file that was left out and why."
13693
+ notes: "manifest.json.files[] lists every included file with layer, kind, language, part and summary. manifest.skipped[] explains every file that was left out and why; manifest.incomplete[] lists every included file that is not present in full, with its missing line ranges."
13590
13694
  }
13591
13695
  ],
13592
13696
  commands: [
@@ -13691,9 +13795,9 @@ function buildAgentContract() {
13691
13795
  {
13692
13796
  flag: "--large-file-bytes",
13693
13797
  type: "string",
13694
- default: 204800,
13798
+ default: 307200,
13695
13799
  appliesTo: optionAppliesTo("large-file-bytes"),
13696
- summary: "Above this size a file gets a head/tail preview instead of the full body."
13800
+ summary: "Above this size a file gets a head/tail preview instead of the full body. It defaults to maxPartBytes and may not exceed it: a file between the two could not fit a part."
13697
13801
  },
13698
13802
  {
13699
13803
  flag: "--max-monolith-bytes",
@@ -13928,7 +14032,7 @@ function buildAgentContract() {
13928
14032
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
13929
14033
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
13930
14034
  { key: "withDependents", type: "boolean", default: false, summary: "With a changed-files scope, also include one hop of importers." },
13931
- { key: "largeFileBytes", type: "number | string", default: 204800, summary: "Preview threshold for large files." },
14035
+ { key: "largeFileBytes", type: "number | string", default: 307200, summary: "Preview threshold for large files; defaults to maxPartBytes and may not exceed it." },
13932
14036
  { key: "previewHeadLines", type: "number", default: 80, summary: "Lines kept from the head of a large file." },
13933
14037
  { key: "previewTailLines", type: "number", default: 40, summary: "Lines kept from the tail of a large file." },
13934
14038
  { key: "includeMonolith", type: "boolean", default: false, summary: "Also write the single-file monolith." },
@@ -13957,8 +14061,8 @@ function buildAgentContract() {
13957
14061
  "<outDir>/.codebase-snapshot (ownership marker, always written)"
13958
14062
  ],
13959
14063
  notes: [
13960
- "Parts are ordered and budget-limited; a single file larger than the budget becomes a head/tail preview.",
13961
- "manifest.json.files[] carries relativePath, layer, kind, language, part, inclusionMode and hash; `summary` is conditional \u2014 it is absent for languages with no structural summary, and `summaryOmitted: true` marks a summary dropped to fit the part budget; encoding appears when the file was not plain UTF-8.",
14064
+ "Parts are ordered and budget-limited; a file that cannot fit one part is emitted as a head/tail preview, and every file not present in full is listed in manifest.json incomplete[] with the missing line ranges.",
14065
+ "manifest.json.files[] carries relativePath, layer, kind, language, part, inclusionMode, truncationReason, omittedRanges and hash; manifest.json.incomplete[] lists every file not present in full; `summary` is conditional \u2014 it is absent for languages with no structural summary, and `summaryOmitted: true` marks a summary dropped to fit the part budget; encoding appears when the file was not plain UTF-8.",
13962
14066
  "manifest.skipped[] carries the path and the exact reason it was excluded.",
13963
14067
  `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
13964
14068
  ]
@@ -14124,10 +14228,12 @@ do not assume the repository is broken.
14124
14228
  \`kind\`, \`language\`, \`part\`, \`inclusionMode\`, \`hashSha256\` and the structural
14125
14229
  \`summary\`, plus \`encoding\` when the file was not plain UTF-8. \`summary\` is
14126
14230
  **optional**: it is absent for languages with no structural summary, and
14127
- \`summaryOmitted: true\` marks one dropped to fit the part budget \u2014 never assume it
14231
+ \`summaryOmitted: true\` marks one dropped for size, and the reason in \`summaryOmittedReason\` says which rule \u2014 never assume it
14128
14232
  exists. The per-file \`hashSha256\` is only here and in the manifest; it is not printed
14129
14233
  into the parts.
14130
- \`skipped[]\` records every excluded file **and why**. Prefer querying this over
14234
+ \`skipped[]\` records every excluded file **and why**. The top-level \`incomplete[]\` records every included
14235
+ file whose body is not the whole file, with its reason and omittedRanges: ask that list,
14236
+ not the footer of a part, when the question is whether anything was lost. Prefer querying this over
14131
14237
  re-reading the parts.
14132
14238
  - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
14133
14239
  state. Read this before you quote code back to a user.
@@ -15266,7 +15372,7 @@ Options:
15266
15372
  --max-part-bytes <n> Maximum byte budget per markdown part (default: 307200).
15267
15373
  Accepts units: 120k, 1.5mb
15268
15374
  --max-part-tokens <n> Per-part budget in tokens; narrows --max-part-bytes
15269
- --large-file-bytes <n> Threshold for head/tail truncation (default: 204800)
15375
+ --large-file-bytes <n> Preview threshold (default: the part budget; never above it)
15270
15376
  --changed-since <ref> Only files changed since this git ref, plus untracked ones
15271
15377
  --staged Only files staged for the next commit
15272
15378
  --with-dependents With the two above: also include their importers
@@ -15700,6 +15806,17 @@ async function runInitCommand(invocation) {
15700
15806
  return fail(invocation.format, err.message);
15701
15807
  }
15702
15808
  }
15809
+ function generatorOrigin(cwd) {
15810
+ try {
15811
+ const pkg = JSON.parse(fs20.readFileSync(path21.join(cwd, "package.json"), "utf8"));
15812
+ const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
15813
+ if (typeof spec === "string") return `project dependency ${spec}`;
15814
+ } catch {
15815
+ }
15816
+ const entry = process.argv[1] ?? "";
15817
+ if (entry.includes("_npx") || entry.includes(`${path21.sep}npx${path21.sep}`)) return "via npx";
15818
+ return "global or direct install";
15819
+ }
15703
15820
  function detectPackageManager(cwd) {
15704
15821
  const has = (name) => fs20.existsSync(path21.join(cwd, name));
15705
15822
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
@@ -15847,9 +15964,14 @@ async function runSetupCommand(invocation, options = {}) {
15847
15964
  info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
15848
15965
  }
15849
15966
  }
15967
+ const hasManifest = fs20.existsSync(path21.join(invocation.cwd, "package.json"));
15850
15968
  let install = null;
15851
15969
  if (invocation.noInstall) {
15852
15970
  if (invocation.format !== "json") info(" Skipped the install (--no-install)");
15971
+ } else if (!hasManifest) {
15972
+ if (invocation.format !== "json") {
15973
+ info(" Skipped the install: no package.json here, so there is no dependency to add.");
15974
+ }
15853
15975
  } else {
15854
15976
  if (invocation.format !== "json") info("\u23F3 Installing dependencies\u2026");
15855
15977
  install = installDependencies(invocation.cwd);
@@ -16202,7 +16324,7 @@ ${USAGE}
16202
16324
  const started = performance.now();
16203
16325
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
16204
16326
  info(
16205
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB`
16327
+ ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
16206
16328
  );
16207
16329
  try {
16208
16330
  const manifest = generateSnapshot(resolved, { dryRun: invocation.dryRun });
@@ -16220,12 +16342,31 @@ ${USAGE}
16220
16342
  ` - Redacted: ${manifest.totals.redactedLines} line(s) \u2014 a real run lists them in ` + displayOutPath(resolved.cwd, resolved.outDir, "reports/audit.md")
16221
16343
  );
16222
16344
  }
16345
+ const incomplete = manifest.incomplete ?? [];
16346
+ if (incomplete.length > 0) {
16347
+ const byReason = /* @__PURE__ */ new Map();
16348
+ for (const record of incomplete) {
16349
+ byReason.set(record.reason, (byReason.get(record.reason) ?? 0) + 1);
16350
+ }
16351
+ const detail = [...byReason.entries()].map(([reason, count]) => `${count} ${reason}`).join(", ");
16352
+ info(` - Incomplete: ${incomplete.length} file(s) \u2014 ${detail}; see manifest.json incomplete[]`);
16353
+ }
16223
16354
  info(` - Integrity: ${manifest.validation.status}`);
16224
16355
  for (const error of manifest.validation.errors.slice(0, 10)) info(` - ${error}`);
16225
16356
  } else {
16226
16357
  info(`
16227
16358
  \u2705 Snapshot generated in ${elapsed}s:`);
16228
- info(` - Tracked files: ${manifest.counts.totalFiles}`);
16359
+ const skipCounts = /* @__PURE__ */ new Map();
16360
+ for (const record of manifest.skipped) {
16361
+ skipCounts.set(record.reason, (skipCounts.get(record.reason) ?? 0) + 1);
16362
+ }
16363
+ const skipBreakdown = [...skipCounts.entries()].sort((left, right) => right[1] - left[1]).map(([reason, count]) => `${reason} ${formatNumber(count)}`);
16364
+ const shownReasons = skipBreakdown.slice(0, 3);
16365
+ const reasons = skipBreakdown.length > shownReasons.length ? `${shownReasons.join(", ")}, +${skipBreakdown.length - shownReasons.length} more` : shownReasons.join(", ");
16366
+ const candidates = manifest.counts.totalFiles + manifest.counts.skippedCount;
16367
+ info(
16368
+ manifest.counts.skippedCount === 0 ? ` - Tracked files: ${formatNumber(manifest.counts.totalFiles)}` : ` - Tracked files: ${formatNumber(manifest.counts.totalFiles)} included of ${formatNumber(candidates)} found \u2014 ${formatNumber(manifest.counts.skippedCount)} skipped (${reasons}); every one is listed in ${displayOutPath(resolved.cwd, resolved.outDir, "reports/audit.md")}`
16369
+ );
16229
16370
  info(` - Total lines: ${formatNumber(manifest.counts.totalLines)}`);
16230
16371
  info(
16231
16372
  ` - Total size: ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB`