codebase-snapshot 0.9.18 → 0.10.0

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.0";
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
 
@@ -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,13 @@ 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
+ largeFileBytes: options.largeFileBytes ?? // A threshold above the part budget is a configuration error (a file between the two
8413
+ // cannot fit, so it is cut while the manifest calls it a preview). Writing the old fixed
8414
+ // 200 KB beside `--max-part-tokens 32k` made the setup's own output fail its own validate.
8415
+ Math.min(
8416
+ parseByteSize(DEFAULT_ANSWERS.largeFileBytes) ?? effectiveBudgetBytes,
8417
+ effectiveBudgetBytes
8418
+ ),
8394
8419
  maxMonolithBytes: options.maxMonolithBytes ?? DEFAULT_ANSWERS.maxMonolithBytes,
8395
8420
  discovery: options.discovery ?? DEFAULT_ANSWERS.discovery,
8396
8421
  skeleton: options.skeleton ?? DEFAULT_ANSWERS.skeleton,
@@ -8881,7 +8906,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
8881
8906
  );
8882
8907
  for (const file of affected) {
8883
8908
  const status = file.isPreviewTruncated ? "Truncated" : "Full";
8884
- const cutBy = file.isLarge ? "largeFileBytes" : "maxPartBytes";
8909
+ const cutBy = file.truncationReason === "part-budget" ? "maxPartBytes" : "largeFileBytes";
8885
8910
  lines.push(
8886
8911
  `| ${code(file.relativePath)} | ${file.sizeBytes} | ${file.lines} | ${file.includedBytes} | ${file.includedLines} | ${status} | ${cutBy} |`
8887
8912
  );
@@ -9126,7 +9151,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
9126
9151
  section.file.originalLines
9127
9152
  );
9128
9153
  if (shrunk.isTruncated) {
9129
- applyTruncatedContent(section.file, shrunk.content);
9154
+ applyTruncatedContent(section.file, shrunk.content, "part-budget");
9130
9155
  section.text = renderFileSection(section.file);
9131
9156
  section.byteSize = Buffer.byteLength(section.text, "utf8");
9132
9157
  assemblies.delete(group);
@@ -9200,7 +9225,7 @@ function prepareSection(file, sectionBudget, partBudget) {
9200
9225
  file.originalLines
9201
9226
  );
9202
9227
  if (!truncated.isTruncated) return;
9203
- applyTruncatedContent(file, truncated.content);
9228
+ applyTruncatedContent(file, truncated.content, "part-budget");
9204
9229
  text2 = renderFileSection(file);
9205
9230
  byteSize = Buffer.byteLength(text2, "utf8");
9206
9231
  };
@@ -9208,14 +9233,16 @@ function prepareSection(file, sectionBudget, partBudget) {
9208
9233
  if (byteSize > sectionBudget && file.summary) {
9209
9234
  file.summary = void 0;
9210
9235
  file.summaryOmitted = true;
9236
+ file.summaryOmittedReason = "part-budget";
9211
9237
  text2 = renderFileSection(file);
9212
9238
  byteSize = Buffer.byteLength(text2, "utf8");
9213
9239
  shrinkBody();
9214
9240
  }
9215
9241
  if (byteSize > sectionBudget) {
9216
- applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
9242
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE, "section-metadata");
9217
9243
  file.summary = void 0;
9218
9244
  file.summaryOmitted = true;
9245
+ file.summaryOmittedReason = "part-budget";
9219
9246
  text2 = renderFileSection(file);
9220
9247
  byteSize = Buffer.byteLength(text2, "utf8");
9221
9248
  if (byteSize > sectionBudget) {
@@ -9264,10 +9291,14 @@ function fenceIsOpen(text2, fence) {
9264
9291
  }
9265
9292
  return open;
9266
9293
  }
9267
- function applyTruncatedContent(file, content) {
9294
+ var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
9295
+ function applyTruncatedContent(file, content, reason) {
9296
+ const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
9268
9297
  file.content = content;
9269
9298
  file.isPreviewTruncated = true;
9270
9299
  file.inclusionMode = "preview";
9300
+ file.truncationReason = reason;
9301
+ file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
9271
9302
  file.includedBytes = Buffer.byteLength(content, "utf8");
9272
9303
  file.includedLines = countLines(content);
9273
9304
  }
@@ -9414,7 +9445,9 @@ function renderFileSection(file) {
9414
9445
  compactMetadata(file),
9415
9446
  ...file.summaryQuality ? [`- Summary Quality: ${file.summaryQuality}`] : [],
9416
9447
  ...renderSummary(file.summary, file.inclusionMode),
9417
- ...file.summaryOmitted ? ["- Summary: (omitted: exceeds the part budget)"] : [],
9448
+ ...file.summaryOmitted ? [
9449
+ 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)"
9450
+ ] : [],
9418
9451
  "",
9419
9452
  file.inclusionMode === "preview" ? "#### Bounded Preview" : "#### Content",
9420
9453
  "",
@@ -10194,6 +10227,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10194
10227
  const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
10195
10228
  let finalContent = redacted;
10196
10229
  let isPreviewTruncated = false;
10230
+ let truncationReason;
10231
+ let omittedRanges = [];
10197
10232
  let includedLines = lineCount;
10198
10233
  let inclusionMode = "full";
10199
10234
  if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
@@ -10210,6 +10245,10 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10210
10245
  isPreviewTruncated = preview.isTruncated;
10211
10246
  includedLines = preview.includedLines;
10212
10247
  inclusionMode = isPreviewTruncated ? "preview" : "full";
10248
+ if (isPreviewTruncated) {
10249
+ truncationReason = "large-file-budget";
10250
+ omittedRanges = preview.omittedRanges;
10251
+ }
10213
10252
  }
10214
10253
  let summary;
10215
10254
  let summaryQuality;
@@ -10244,6 +10283,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10244
10283
  finalContent,
10245
10284
  inclusionMode,
10246
10285
  isPreviewTruncated,
10286
+ truncationReason,
10287
+ omittedRanges,
10247
10288
  includedLines,
10248
10289
  isLarge,
10249
10290
  summary,
@@ -10354,8 +10395,30 @@ function buildIndexes(files, tsconfigPaths) {
10354
10395
  }))
10355
10396
  };
10356
10397
  }
10357
- function verifyInMemory(files, parts) {
10398
+ function verifyInMemory(files, parts, unaccounted) {
10358
10399
  const errors = [];
10400
+ if (unaccounted.length > 0) {
10401
+ const shown = unaccounted.slice(0, 5).join(", ");
10402
+ errors.push(
10403
+ `${unaccounted.length} scanned file(s) appear in neither files[] nor skipped[]${unaccounted.length > 5 ? ` (first five: ${shown})` : `: ${shown}`}.`
10404
+ );
10405
+ }
10406
+ for (const file of files) {
10407
+ if (file.isPreviewTruncated && file.truncationReason === void 0) {
10408
+ errors.push(`${file.relativePath} is truncated but records no truncationReason.`);
10409
+ }
10410
+ const ranges = file.omittedRanges ?? [];
10411
+ if (file.truncationReason !== void 0 && ranges.length === 0) {
10412
+ errors.push(`${file.relativePath} is truncated but records no omittedRanges.`);
10413
+ }
10414
+ for (const [from, to] of ranges) {
10415
+ if (from < 1 || to < from || to > file.lines) {
10416
+ errors.push(
10417
+ `${file.relativePath} records omitted range ${from}-${to}, outside 1-${file.lines}.`
10418
+ );
10419
+ }
10420
+ }
10421
+ }
10359
10422
  const partNames = new Set(parts.map((part) => part.filename));
10360
10423
  for (const file of files) {
10361
10424
  if (!file.part || !partNames.has(file.part)) {
@@ -11106,7 +11169,20 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11106
11169
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
11107
11170
  const hadPrevious = fs15.existsSync(outDir);
11108
11171
  if (hadPrevious) beforeSwap?.();
11109
- if (hadPrevious) fs15.renameSync(outDir, backupDir);
11172
+ let movedAside = false;
11173
+ if (hadPrevious) {
11174
+ try {
11175
+ fs15.renameSync(outDir, backupDir);
11176
+ movedAside = true;
11177
+ } catch (err) {
11178
+ if (!isLockError(err)) throw err;
11179
+ fs15.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
11180
+ process.stderr.write(
11181
+ `\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.
11182
+ `
11183
+ );
11184
+ }
11185
+ }
11110
11186
  try {
11111
11187
  try {
11112
11188
  fs15.renameSync(stagingDir, outDir);
@@ -11126,9 +11202,14 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11126
11202
  }
11127
11203
  }
11128
11204
  } catch (err) {
11129
- if (hadPrevious && fs15.existsSync(backupDir)) {
11205
+ if (hadPrevious && movedAside && fs15.existsSync(backupDir)) {
11130
11206
  if (fs15.existsSync(outDir)) fs15.rmSync(outDir, { recursive: true, force: true });
11131
11207
  fs15.renameSync(backupDir, outDir);
11208
+ } else if (hadPrevious && !movedAside) {
11209
+ process.stderr.write(
11210
+ `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
11211
+ `
11212
+ );
11132
11213
  }
11133
11214
  throw err;
11134
11215
  }
@@ -11143,6 +11224,10 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11143
11224
  }
11144
11225
  }
11145
11226
  }
11227
+ function isLockError(err) {
11228
+ const code = err.code;
11229
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
11230
+ }
11146
11231
  function sleepSync(milliseconds) {
11147
11232
  const buffer = new Int32Array(new SharedArrayBuffer(4));
11148
11233
  Atomics.wait(buffer, 0, 0, milliseconds);
@@ -11246,10 +11331,6 @@ function generateSnapshot(configInput, options) {
11246
11331
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
11247
11332
  const secretFindings = [];
11248
11333
  const warnings = [];
11249
- const budgetOrderCutsFiles = () => {
11250
- if (config.maxPartBytes >= config.largeFileBytes) return false;
11251
- return files.some((file) => file.isPreviewTruncated && !file.isLarge);
11252
- };
11253
11334
  const encodingNotes = [];
11254
11335
  const fileWarnings = [];
11255
11336
  const oversizeSummaryPaths = [];
@@ -11411,11 +11492,16 @@ function generateSnapshot(configInput, options) {
11411
11492
  inclusionMode: derivation.inclusionMode,
11412
11493
  isLarge: derivation.isLarge,
11413
11494
  isPreviewTruncated: derivation.isPreviewTruncated,
11495
+ ...derivation.truncationReason === void 0 ? {} : { truncationReason: derivation.truncationReason },
11496
+ ...derivation.omittedRanges.length === 0 ? {} : { omittedRanges: derivation.omittedRanges },
11414
11497
  originalLines: lineCount,
11415
11498
  includedLines: derivation.includedLines,
11416
11499
  includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
11417
11500
  summary: derivation.summary,
11418
11501
  summaryQuality: derivation.summaryQuality,
11502
+ // A summary skipped for size is not an absent summary: record it the same way the
11503
+ // partitioner records one it had to drop, so a reader can tell the two apart.
11504
+ ...derivation.summarySkip === null ? {} : { summaryOmitted: true, summaryOmittedReason: derivation.summarySkip },
11419
11505
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
11420
11506
  content: derivation.finalContent
11421
11507
  });
@@ -11535,7 +11621,28 @@ function generateSnapshot(configInput, options) {
11535
11621
  }
11536
11622
  const parts = partitionByBudget(files, config, fingerprint);
11537
11623
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11538
- const validationErrors = verifyInMemory(files, parts);
11624
+ const incomplete = files.flatMap((file) => {
11625
+ if (file.truncationReason === void 0) return [];
11626
+ const ranges = file.omittedRanges ?? [];
11627
+ const omittedLines = ranges.reduce((total, [from, to]) => total + (to - from + 1), 0);
11628
+ return [
11629
+ {
11630
+ relativePath: file.relativePath,
11631
+ part: file.part,
11632
+ reason: file.truncationReason,
11633
+ omittedRanges: ranges,
11634
+ omittedLines,
11635
+ includedLines: file.includedLines,
11636
+ lines: file.lines
11637
+ }
11638
+ ];
11639
+ });
11640
+ const accounted = /* @__PURE__ */ new Set([
11641
+ ...files.map((file) => maskPathText(file.relativePath, config.secretRules)),
11642
+ ...skipped.map((record) => record.path)
11643
+ ]);
11644
+ const unaccounted = candidateFiles.map((candidate) => maskPathText(candidate, config.secretRules)).filter((candidate) => !accounted.has(candidate));
11645
+ const validationErrors = verifyInMemory(files, parts, unaccounted);
11539
11646
  const totalContentBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11540
11647
  const maskName = (value) => maskPathText(value, config.secretRules);
11541
11648
  const manifest = {
@@ -11596,7 +11703,8 @@ function generateSnapshot(configInput, options) {
11596
11703
  partsCount: parts.length,
11597
11704
  skippedCount: skipped.length,
11598
11705
  largeFileCount,
11599
- truncatedPreviewCount
11706
+ truncatedPreviewCount,
11707
+ incompleteCount: incomplete.length
11600
11708
  },
11601
11709
  totals: {
11602
11710
  candidateFiles: files.length + skipped.length,
@@ -11633,19 +11741,14 @@ function generateSnapshot(configInput, options) {
11633
11741
  return rest;
11634
11742
  }),
11635
11743
  skipped: maskSkipRecords(skipped, config.secretRules),
11744
+ incomplete,
11636
11745
  warnings
11637
11746
  };
11638
11747
  manifest.totals.redactedLines = secretFindings.length;
11639
11748
  manifest.totals.warningCount = manifest.warnings.length;
11640
- if (budgetOrderCutsFiles()) {
11749
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
11641
11750
  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.`
11751
+ `${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
11752
  );
11650
11753
  manifest.totals.warningCount = manifest.warnings.length;
11651
11754
  }
@@ -13021,6 +13124,9 @@ var readTool = {
13021
13124
  structured: {
13022
13125
  path: entry.relativePath,
13023
13126
  part: entry.part,
13127
+ // The window itself: a caller that wants to measure or re-send what it received should
13128
+ // not have to strip the header and the paging note back off `text`.
13129
+ body,
13024
13130
  layer: entry.layer,
13025
13131
  kind: entry.kind,
13026
13132
  language: entry.language,
@@ -13691,9 +13797,9 @@ function buildAgentContract() {
13691
13797
  {
13692
13798
  flag: "--large-file-bytes",
13693
13799
  type: "string",
13694
- default: 204800,
13800
+ default: 307200,
13695
13801
  appliesTo: optionAppliesTo("large-file-bytes"),
13696
- summary: "Above this size a file gets a head/tail preview instead of the full body."
13802
+ 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
13803
  },
13698
13804
  {
13699
13805
  flag: "--max-monolith-bytes",
@@ -13928,7 +14034,7 @@ function buildAgentContract() {
13928
14034
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
13929
14035
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
13930
14036
  { 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." },
14037
+ { key: "largeFileBytes", type: "number | string", default: 307200, summary: "Preview threshold for large files; defaults to maxPartBytes and may not exceed it." },
13932
14038
  { key: "previewHeadLines", type: "number", default: 80, summary: "Lines kept from the head of a large file." },
13933
14039
  { key: "previewTailLines", type: "number", default: 40, summary: "Lines kept from the tail of a large file." },
13934
14040
  { key: "includeMonolith", type: "boolean", default: false, summary: "Also write the single-file monolith." },
@@ -13957,8 +14063,8 @@ function buildAgentContract() {
13957
14063
  "<outDir>/.codebase-snapshot (ownership marker, always written)"
13958
14064
  ],
13959
14065
  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.",
14066
+ "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.",
14067
+ "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
14068
  "manifest.skipped[] carries the path and the exact reason it was excluded.",
13963
14069
  `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
13964
14070
  ]
@@ -14124,10 +14230,12 @@ do not assume the repository is broken.
14124
14230
  \`kind\`, \`language\`, \`part\`, \`inclusionMode\`, \`hashSha256\` and the structural
14125
14231
  \`summary\`, plus \`encoding\` when the file was not plain UTF-8. \`summary\` is
14126
14232
  **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
14233
+ \`summaryOmitted: true\` marks one dropped for size, and the reason in \`summaryOmittedReason\` says which rule \u2014 never assume it
14128
14234
  exists. The per-file \`hashSha256\` is only here and in the manifest; it is not printed
14129
14235
  into the parts.
14130
- \`skipped[]\` records every excluded file **and why**. Prefer querying this over
14236
+ \`skipped[]\` records every excluded file **and why**. The top-level \`incomplete[]\` records every included
14237
+ file whose body is not the whole file, with its reason and omittedRanges: ask that list,
14238
+ not the footer of a part, when the question is whether anything was lost. Prefer querying this over
14131
14239
  re-reading the parts.
14132
14240
  - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
14133
14241
  state. Read this before you quote code back to a user.
@@ -15700,6 +15808,17 @@ async function runInitCommand(invocation) {
15700
15808
  return fail(invocation.format, err.message);
15701
15809
  }
15702
15810
  }
15811
+ function generatorOrigin(cwd) {
15812
+ try {
15813
+ const pkg = JSON.parse(fs20.readFileSync(path21.join(cwd, "package.json"), "utf8"));
15814
+ const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
15815
+ if (typeof spec === "string") return `project dependency ${spec}`;
15816
+ } catch {
15817
+ }
15818
+ const entry = process.argv[1] ?? "";
15819
+ if (entry.includes("_npx") || entry.includes(`${path21.sep}npx${path21.sep}`)) return "via npx";
15820
+ return "global or direct install";
15821
+ }
15703
15822
  function detectPackageManager(cwd) {
15704
15823
  const has = (name) => fs20.existsSync(path21.join(cwd, name));
15705
15824
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
@@ -15847,9 +15966,14 @@ async function runSetupCommand(invocation, options = {}) {
15847
15966
  info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
15848
15967
  }
15849
15968
  }
15969
+ const hasManifest = fs20.existsSync(path21.join(invocation.cwd, "package.json"));
15850
15970
  let install = null;
15851
15971
  if (invocation.noInstall) {
15852
15972
  if (invocation.format !== "json") info(" Skipped the install (--no-install)");
15973
+ } else if (!hasManifest) {
15974
+ if (invocation.format !== "json") {
15975
+ info(" Skipped the install: no package.json here, so there is no dependency to add.");
15976
+ }
15853
15977
  } else {
15854
15978
  if (invocation.format !== "json") info("\u23F3 Installing dependencies\u2026");
15855
15979
  install = installDependencies(invocation.cwd);
@@ -16202,7 +16326,7 @@ ${USAGE}
16202
16326
  const started = performance.now();
16203
16327
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
16204
16328
  info(
16205
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB`
16329
+ ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
16206
16330
  );
16207
16331
  try {
16208
16332
  const manifest = generateSnapshot(resolved, { dryRun: invocation.dryRun });
@@ -16220,12 +16344,31 @@ ${USAGE}
16220
16344
  ` - Redacted: ${manifest.totals.redactedLines} line(s) \u2014 a real run lists them in ` + displayOutPath(resolved.cwd, resolved.outDir, "reports/audit.md")
16221
16345
  );
16222
16346
  }
16347
+ const incomplete = manifest.incomplete ?? [];
16348
+ if (incomplete.length > 0) {
16349
+ const byReason = /* @__PURE__ */ new Map();
16350
+ for (const record of incomplete) {
16351
+ byReason.set(record.reason, (byReason.get(record.reason) ?? 0) + 1);
16352
+ }
16353
+ const detail = [...byReason.entries()].map(([reason, count]) => `${count} ${reason}`).join(", ");
16354
+ info(` - Incomplete: ${incomplete.length} file(s) \u2014 ${detail}; see manifest.json incomplete[]`);
16355
+ }
16223
16356
  info(` - Integrity: ${manifest.validation.status}`);
16224
16357
  for (const error of manifest.validation.errors.slice(0, 10)) info(` - ${error}`);
16225
16358
  } else {
16226
16359
  info(`
16227
16360
  \u2705 Snapshot generated in ${elapsed}s:`);
16228
- info(` - Tracked files: ${manifest.counts.totalFiles}`);
16361
+ const skipCounts = /* @__PURE__ */ new Map();
16362
+ for (const record of manifest.skipped) {
16363
+ skipCounts.set(record.reason, (skipCounts.get(record.reason) ?? 0) + 1);
16364
+ }
16365
+ const skipBreakdown = [...skipCounts.entries()].sort((left, right) => right[1] - left[1]).map(([reason, count]) => `${reason} ${formatNumber(count)}`);
16366
+ const shownReasons = skipBreakdown.slice(0, 3);
16367
+ const reasons = skipBreakdown.length > shownReasons.length ? `${shownReasons.join(", ")}, +${skipBreakdown.length - shownReasons.length} more` : shownReasons.join(", ");
16368
+ const candidates = manifest.counts.totalFiles + manifest.counts.skippedCount;
16369
+ info(
16370
+ 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")}`
16371
+ );
16229
16372
  info(` - Total lines: ${formatNumber(manifest.counts.totalLines)}`);
16230
16373
  info(
16231
16374
  ` - Total size: ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB`