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/cli.cjs CHANGED
@@ -554,7 +554,7 @@ var JS_PRESETS = [
554
554
  ...commonKinds()
555
555
  ],
556
556
  exclude: [".nuxt", ".output"],
557
- recommendedBudget: "200k"
557
+ recommendedBudget: "300k"
558
558
  },
559
559
  {
560
560
  name: "sveltekit",
@@ -575,7 +575,7 @@ var JS_PRESETS = [
575
575
  ...commonKinds()
576
576
  ],
577
577
  exclude: [".svelte-kit", ".vercel"],
578
- recommendedBudget: "200k"
578
+ recommendedBudget: "300k"
579
579
  },
580
580
  {
581
581
  name: "remix",
@@ -589,7 +589,7 @@ var JS_PRESETS = [
589
589
  ],
590
590
  kinds: [kindOf("route", "routes/"), ...commonKinds()],
591
591
  exclude: [".cache", "public/build"],
592
- recommendedBudget: "200k"
592
+ recommendedBudget: "300k"
593
593
  },
594
594
  {
595
595
  name: "astro",
@@ -604,7 +604,7 @@ var JS_PRESETS = [
604
604
  ],
605
605
  kinds: [suffixKind("page", ".astro"), kindOf("layout", "layouts/"), ...commonKinds()],
606
606
  exclude: [".astro", "dist"],
607
- recommendedBudget: "150k"
607
+ recommendedBudget: "300k"
608
608
  },
609
609
  {
610
610
  name: "angular",
@@ -628,7 +628,7 @@ var JS_PRESETS = [
628
628
  ...commonKinds()
629
629
  ],
630
630
  exclude: [".angular", "dist"],
631
- recommendedBudget: "200k"
631
+ recommendedBudget: "300k"
632
632
  },
633
633
  {
634
634
  name: "solid",
@@ -641,7 +641,7 @@ var JS_PRESETS = [
641
641
  ],
642
642
  kinds: [kindOf("route", "routes/"), ...commonKinds()],
643
643
  exclude: [".solid", "dist"],
644
- recommendedBudget: "120k"
644
+ recommendedBudget: "300k"
645
645
  },
646
646
  {
647
647
  name: "vue-vite",
@@ -674,7 +674,7 @@ var JS_PRESETS = [
674
674
  ...commonKinds()
675
675
  ],
676
676
  exclude: [".vite", "dist"],
677
- recommendedBudget: "120k"
677
+ recommendedBudget: "300k"
678
678
  },
679
679
  {
680
680
  name: "react-vite",
@@ -688,7 +688,7 @@ var JS_PRESETS = [
688
688
  layers: VITE_LAYERS,
689
689
  kinds: VITE_KINDS,
690
690
  exclude: [".vite", "dist"],
691
- recommendedBudget: "120k"
691
+ recommendedBudget: "300k"
692
692
  },
693
693
  {
694
694
  name: "nest",
@@ -714,7 +714,7 @@ var JS_PRESETS = [
714
714
  ...commonKinds()
715
715
  ],
716
716
  exclude: ["dist", "node_modules"],
717
- recommendedBudget: "200k"
717
+ recommendedBudget: "300k"
718
718
  },
719
719
  {
720
720
  name: "node-express",
@@ -723,7 +723,7 @@ var JS_PRESETS = [
723
723
  layers: NODE_LAYERS,
724
724
  kinds: NODE_KINDS,
725
725
  exclude: ["dist"],
726
- recommendedBudget: "200k"
726
+ recommendedBudget: "300k"
727
727
  },
728
728
  {
729
729
  name: "node-lib",
@@ -739,7 +739,7 @@ var JS_PRESETS = [
739
739
  ],
740
740
  kinds: [suffixKind("type", ".d.ts"), ...commonKinds()],
741
741
  exclude: ["dist"],
742
- recommendedBudget: "120k"
742
+ recommendedBudget: "300k"
743
743
  }
744
744
  ];
745
745
 
@@ -770,7 +770,7 @@ var LANGUAGE_PRESETS = [
770
770
  ...commonKinds()
771
771
  ],
772
772
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs", "staticfiles", "media"],
773
- recommendedBudget: "150k"
773
+ recommendedBudget: "300k"
774
774
  },
775
775
  {
776
776
  name: "python-fastapi",
@@ -793,7 +793,7 @@ var LANGUAGE_PRESETS = [
793
793
  ...commonKinds()
794
794
  ],
795
795
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs"],
796
- recommendedBudget: "150k"
796
+ recommendedBudget: "300k"
797
797
  },
798
798
  {
799
799
  name: "python-lib",
@@ -807,7 +807,7 @@ var LANGUAGE_PRESETS = [
807
807
  ],
808
808
  kinds: [suffixKind("module", ".py"), ...commonKinds()],
809
809
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs"],
810
- recommendedBudget: "120k"
810
+ recommendedBudget: "300k"
811
811
  },
812
812
  {
813
813
  name: "go",
@@ -831,7 +831,7 @@ var LANGUAGE_PRESETS = [
831
831
  ...commonKinds()
832
832
  ],
833
833
  exclude: ["vendor", "testdata"],
834
- recommendedBudget: "200k"
834
+ recommendedBudget: "300k"
835
835
  },
836
836
  {
837
837
  name: "rust",
@@ -847,7 +847,7 @@ var LANGUAGE_PRESETS = [
847
847
  ],
848
848
  kinds: [suffixKind("module", ".rs"), suffixKind("test", "_test.rs"), ...commonKinds()],
849
849
  exclude: ["target"],
850
- recommendedBudget: "200k"
850
+ recommendedBudget: "300k"
851
851
  },
852
852
  {
853
853
  name: "java-spring",
@@ -870,7 +870,7 @@ var LANGUAGE_PRESETS = [
870
870
  ...commonKinds()
871
871
  ],
872
872
  exclude: [".gradle", "out", "target"],
873
- recommendedBudget: "200k"
873
+ recommendedBudget: "300k"
874
874
  },
875
875
  {
876
876
  name: "dotnet",
@@ -893,7 +893,7 @@ var LANGUAGE_PRESETS = [
893
893
  ...commonKinds()
894
894
  ],
895
895
  exclude: ["bin", "obj", ".vs"],
896
- recommendedBudget: "200k"
896
+ recommendedBudget: "300k"
897
897
  },
898
898
  {
899
899
  name: "php-laravel",
@@ -919,7 +919,7 @@ var LANGUAGE_PRESETS = [
919
919
  ...commonKinds()
920
920
  ],
921
921
  exclude: ["vendor", "storage", "bootstrap/cache", "public/build"],
922
- recommendedBudget: "150k"
922
+ recommendedBudget: "300k"
923
923
  },
924
924
  {
925
925
  name: "ruby-rails",
@@ -944,7 +944,7 @@ var LANGUAGE_PRESETS = [
944
944
  ...commonKinds()
945
945
  ],
946
946
  exclude: [".bundle", "log", "tmp", "vendor/bundle", "public/assets"],
947
- recommendedBudget: "150k"
947
+ recommendedBudget: "300k"
948
948
  }
949
949
  ];
950
950
 
@@ -1006,7 +1006,7 @@ var SHAPE_PRESETS = [
1006
1006
  ],
1007
1007
  kinds: commonKinds(),
1008
1008
  exclude: [".turbo", ".nx"],
1009
- recommendedBudget: "200k"
1009
+ recommendedBudget: "300k"
1010
1010
  },
1011
1011
  {
1012
1012
  name: "infra",
@@ -1024,7 +1024,7 @@ var SHAPE_PRESETS = [
1024
1024
  ...commonKinds()
1025
1025
  ],
1026
1026
  exclude: [".terraform", ".terragrunt-cache"],
1027
- recommendedBudget: "100k"
1027
+ recommendedBudget: "300k"
1028
1028
  },
1029
1029
  {
1030
1030
  name: "docs",
@@ -1041,7 +1041,7 @@ var SHAPE_PRESETS = [
1041
1041
  ],
1042
1042
  kinds: commonKinds(),
1043
1043
  exclude: [".docusaurus", ".vitepress/dist", "site"],
1044
- recommendedBudget: "100k"
1044
+ recommendedBudget: "300k"
1045
1045
  },
1046
1046
  {
1047
1047
  name: "generic",
@@ -1053,7 +1053,7 @@ var SHAPE_PRESETS = [
1053
1053
  layers: DEFAULT_LAYERS,
1054
1054
  kinds: DEFAULT_KINDS,
1055
1055
  exclude: [],
1056
- recommendedBudget: "120k"
1056
+ recommendedBudget: "300k"
1057
1057
  }
1058
1058
  ];
1059
1059
 
@@ -2179,7 +2179,7 @@ function applySpans(line, spans) {
2179
2179
 
2180
2180
  // src/version.ts
2181
2181
  var GENERATOR_NAME = "codebase-snapshot";
2182
- var GENERATOR_VERSION = "0.9.18";
2182
+ var GENERATOR_VERSION = "0.10.1";
2183
2183
  var SCHEMA_VERSION = "3.0.0";
2184
2184
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2185
2185
  function isOurGeneratorName(name) {
@@ -3505,6 +3505,16 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3505
3505
  }
3506
3506
  return { config: null, file: null, warnings, errors };
3507
3507
  }
3508
+ function largeFileBytesFor(maxPartBytes, cliOptions, userConfig) {
3509
+ const requested = cliOptions?.largeFileBytes ?? userConfig?.largeFileBytes;
3510
+ const value = boundedBytes(requested, maxPartBytes, 1, "largeFileBytes");
3511
+ if (value > maxPartBytes) {
3512
+ throw new Error(
3513
+ `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.`
3514
+ );
3515
+ }
3516
+ return value;
3517
+ }
3508
3518
  var MIN_MAX_PART_BYTES = 4096;
3509
3519
  var MIN_MAX_PART_TOKENS = MIN_MAX_PART_BYTES / 4;
3510
3520
  var ARTIFACT_NAMES = [
@@ -3947,7 +3957,7 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
3947
3957
  tmpDir,
3948
3958
  maxPartBytes: resolvedMaxPartBytes,
3949
3959
  ...maxPartTokens === void 0 ? {} : { maxPartTokens },
3950
- largeFileBytes: boundedBytes(cliOptions?.largeFileBytes ?? userConfig?.largeFileBytes, 200 * 1024, 1, "largeFileBytes"),
3960
+ largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
3951
3961
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
3952
3962
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
3953
3963
  includeMonolith: artifacts.monolith,
@@ -7000,7 +7010,8 @@ function truncatePreview(content, headLines, tailLines) {
7000
7010
  content: normalised,
7001
7011
  isTruncated: false,
7002
7012
  originalLines: total,
7003
- includedLines: total
7013
+ includedLines: total,
7014
+ omittedRanges: []
7004
7015
  };
7005
7016
  }
7006
7017
  const window = normalised.endsWith("\n") ? lines.slice(0, -1) : lines;
@@ -7012,13 +7023,16 @@ function truncatePreview(content, headLines, tailLines) {
7012
7023
  `... [${omitted} lines omitted: file exceeds large file size budget] ...`,
7013
7024
  ...tail
7014
7025
  ].join("\n");
7026
+ const firstOmitted = head.length + 1;
7027
+ const lastOmitted = total - tail.length;
7015
7028
  return {
7016
7029
  content: result,
7017
7030
  isTruncated: true,
7018
7031
  originalLines: total,
7019
7032
  // Head + notice + tail is exactly what is emitted; counting the slice is
7020
7033
  // wrong when the source ended with a newline (the trailing "" issue above).
7021
- includedLines: head.length + tail.length + 1
7034
+ includedLines: head.length + tail.length + 1,
7035
+ omittedRanges: lastOmitted >= firstOmitted ? [[firstOmitted, lastOmitted]] : []
7022
7036
  };
7023
7037
  }
7024
7038
  var LANGUAGE_BY_EXTENSION = {
@@ -7608,7 +7622,6 @@ function gitignorePath(cwd, filePath) {
7608
7622
  var DEFAULT_ANSWERS = {
7609
7623
  maxPartBytes: "300k",
7610
7624
  maxPartTokens: null,
7611
- largeFileBytes: "200k",
7612
7625
  maxMonolithBytes: null,
7613
7626
  discovery: "auto",
7614
7627
  skeleton: false,
@@ -7666,7 +7679,9 @@ function renderConfig(answers) {
7666
7679
  // The same ceiling expressed in tokens; it narrows maxPartBytes rather than
7667
7680
  // replacing it. null = not set. Minimum 1024.
7668
7681
  maxPartTokens: ${answers.maxPartTokens === null ? "null" : String(answers.maxPartTokens)},
7669
- // Files above this size get a head/tail preview instead of the full body.
7682
+ // Files above this size get a head/tail preview instead of the full body. It may not
7683
+ // exceed maxPartBytes: a file between the two could not fit a part, and cutting it to fit
7684
+ // while the manifest called it a preview is exactly what this ceiling pair must prevent.
7670
7685
  largeFileBytes: ${size(answers.largeFileBytes)},
7671
7686
  previewHeadLines: 80,
7672
7687
  previewTailLines: 40,
@@ -8351,6 +8366,9 @@ async function runInit(options) {
8351
8366
  let reason = detected.reason;
8352
8367
  let fallback = detected.fallback;
8353
8368
  const notes = [];
8369
+ const budgetBytes = parseByteSize(options.maxPartBytes ?? detected.recommendedBudget ?? DEFAULT_ANSWERS.maxPartBytes) ?? 307200;
8370
+ const tokenBudgetBytes = options.maxPartTokens === void 0 || options.maxPartTokens === null ? void 0 : options.maxPartTokens * 4;
8371
+ const effectiveBudgetBytes = tokenBudgetBytes === void 0 ? budgetBytes : Math.min(budgetBytes, tokenBudgetBytes);
8354
8372
  const answers = {
8355
8373
  preset: detected.presetName,
8356
8374
  // The repository's own branch, read the same way the generator reads it.
@@ -8364,7 +8382,11 @@ async function runInit(options) {
8364
8382
  // what the run used is drift the next `validate` reports, and `setup` is the one command
8365
8383
  // that is supposed to leave a project in a consistent state.
8366
8384
  maxPartTokens: options.maxPartTokens ?? DEFAULT_ANSWERS.maxPartTokens,
8367
- largeFileBytes: options.largeFileBytes ?? DEFAULT_ANSWERS.largeFileBytes,
8385
+ // Follows the budget unless the caller named one. A threshold above the part budget is a
8386
+ // config error (a file between the two cannot fit a part, so it is cut while the manifest
8387
+ // calls it a preview); a fixed 200 KB beside `--max-part-tokens 32k` made setup's own output
8388
+ // fail its own validate, and a fixed 200 KB under a 300 KB budget previewed files that fit.
8389
+ largeFileBytes: options.largeFileBytes ?? effectiveBudgetBytes,
8368
8390
  maxMonolithBytes: options.maxMonolithBytes ?? DEFAULT_ANSWERS.maxMonolithBytes,
8369
8391
  discovery: options.discovery ?? DEFAULT_ANSWERS.discovery,
8370
8392
  skeleton: options.skeleton ?? DEFAULT_ANSWERS.skeleton,
@@ -8839,7 +8861,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
8839
8861
  );
8840
8862
  for (const file of affected) {
8841
8863
  const status = file.isPreviewTruncated ? "Truncated" : "Full";
8842
- const cutBy = file.isLarge ? "largeFileBytes" : "maxPartBytes";
8864
+ const cutBy = file.truncationReason === "part-budget" ? "maxPartBytes" : "largeFileBytes";
8843
8865
  lines.push(
8844
8866
  `| ${code(file.relativePath)} | ${file.sizeBytes} | ${file.lines} | ${file.includedBytes} | ${file.includedLines} | ${status} | ${cutBy} |`
8845
8867
  );
@@ -9078,7 +9100,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
9078
9100
  section.file.originalLines
9079
9101
  );
9080
9102
  if (shrunk.isTruncated) {
9081
- applyTruncatedContent(section.file, shrunk.content);
9103
+ applyTruncatedContent(section.file, shrunk.content, "part-budget");
9082
9104
  section.text = renderFileSection(section.file);
9083
9105
  section.byteSize = Buffer.byteLength(section.text, "utf8");
9084
9106
  assemblies.delete(group);
@@ -9152,7 +9174,7 @@ function prepareSection(file, sectionBudget, partBudget) {
9152
9174
  file.originalLines
9153
9175
  );
9154
9176
  if (!truncated.isTruncated) return;
9155
- applyTruncatedContent(file, truncated.content);
9177
+ applyTruncatedContent(file, truncated.content, "part-budget");
9156
9178
  text2 = renderFileSection(file);
9157
9179
  byteSize = Buffer.byteLength(text2, "utf8");
9158
9180
  };
@@ -9160,14 +9182,16 @@ function prepareSection(file, sectionBudget, partBudget) {
9160
9182
  if (byteSize > sectionBudget && file.summary) {
9161
9183
  file.summary = void 0;
9162
9184
  file.summaryOmitted = true;
9185
+ file.summaryOmittedReason = "part-budget";
9163
9186
  text2 = renderFileSection(file);
9164
9187
  byteSize = Buffer.byteLength(text2, "utf8");
9165
9188
  shrinkBody();
9166
9189
  }
9167
9190
  if (byteSize > sectionBudget) {
9168
- applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
9191
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE, "section-metadata");
9169
9192
  file.summary = void 0;
9170
9193
  file.summaryOmitted = true;
9194
+ file.summaryOmittedReason = "part-budget";
9171
9195
  text2 = renderFileSection(file);
9172
9196
  byteSize = Buffer.byteLength(text2, "utf8");
9173
9197
  if (byteSize > sectionBudget) {
@@ -9216,10 +9240,14 @@ function fenceIsOpen(text2, fence) {
9216
9240
  }
9217
9241
  return open;
9218
9242
  }
9219
- function applyTruncatedContent(file, content) {
9243
+ var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
9244
+ function applyTruncatedContent(file, content, reason) {
9245
+ const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
9220
9246
  file.content = content;
9221
9247
  file.isPreviewTruncated = true;
9222
9248
  file.inclusionMode = "preview";
9249
+ file.truncationReason = reason;
9250
+ file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
9223
9251
  file.includedBytes = Buffer.byteLength(content, "utf8");
9224
9252
  file.includedLines = countLines(content);
9225
9253
  }
@@ -9366,7 +9394,9 @@ function renderFileSection(file) {
9366
9394
  compactMetadata(file),
9367
9395
  ...file.summaryQuality ? [`- Summary Quality: ${file.summaryQuality}`] : [],
9368
9396
  ...renderSummary(file.summary, file.inclusionMode),
9369
- ...file.summaryOmitted ? ["- Summary: (omitted: exceeds the part budget)"] : [],
9397
+ ...file.summaryOmitted ? [
9398
+ 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)"
9399
+ ] : [],
9370
9400
  "",
9371
9401
  file.inclusionMode === "preview" ? "#### Bounded Preview" : "#### Content",
9372
9402
  "",
@@ -10129,6 +10159,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10129
10159
  const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
10130
10160
  let finalContent = redacted;
10131
10161
  let isPreviewTruncated = false;
10162
+ let truncationReason;
10163
+ let omittedRanges = [];
10132
10164
  let includedLines = lineCount;
10133
10165
  let inclusionMode = "full";
10134
10166
  if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
@@ -10145,6 +10177,10 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10145
10177
  isPreviewTruncated = preview.isTruncated;
10146
10178
  includedLines = preview.includedLines;
10147
10179
  inclusionMode = isPreviewTruncated ? "preview" : "full";
10180
+ if (isPreviewTruncated) {
10181
+ truncationReason = "large-file-budget";
10182
+ omittedRanges = preview.omittedRanges;
10183
+ }
10148
10184
  }
10149
10185
  let summary;
10150
10186
  let summaryQuality;
@@ -10179,6 +10215,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10179
10215
  finalContent,
10180
10216
  inclusionMode,
10181
10217
  isPreviewTruncated,
10218
+ truncationReason,
10219
+ omittedRanges,
10182
10220
  includedLines,
10183
10221
  isLarge,
10184
10222
  summary,
@@ -10288,8 +10326,30 @@ function buildIndexes(files, tsconfigPaths) {
10288
10326
  }))
10289
10327
  };
10290
10328
  }
10291
- function verifyInMemory(files, parts) {
10329
+ function verifyInMemory(files, parts, unaccounted) {
10292
10330
  const errors = [];
10331
+ if (unaccounted.length > 0) {
10332
+ const shown = unaccounted.slice(0, 5).join(", ");
10333
+ errors.push(
10334
+ `${unaccounted.length} scanned file(s) appear in neither files[] nor skipped[]${unaccounted.length > 5 ? ` (first five: ${shown})` : `: ${shown}`}.`
10335
+ );
10336
+ }
10337
+ for (const file of files) {
10338
+ if (file.isPreviewTruncated && file.truncationReason === void 0) {
10339
+ errors.push(`${file.relativePath} is truncated but records no truncationReason.`);
10340
+ }
10341
+ const ranges = file.omittedRanges ?? [];
10342
+ if (file.truncationReason !== void 0 && ranges.length === 0) {
10343
+ errors.push(`${file.relativePath} is truncated but records no omittedRanges.`);
10344
+ }
10345
+ for (const [from, to] of ranges) {
10346
+ if (from < 1 || to < from || to > file.lines) {
10347
+ errors.push(
10348
+ `${file.relativePath} records omitted range ${from}-${to}, outside 1-${file.lines}.`
10349
+ );
10350
+ }
10351
+ }
10352
+ }
10293
10353
  const partNames = new Set(parts.map((part) => part.filename));
10294
10354
  for (const file of files) {
10295
10355
  if (!file.part || !partNames.has(file.part)) {
@@ -11040,7 +11100,20 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11040
11100
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
11041
11101
  const hadPrevious = fs15__namespace.existsSync(outDir);
11042
11102
  if (hadPrevious) beforeSwap?.();
11043
- if (hadPrevious) fs15__namespace.renameSync(outDir, backupDir);
11103
+ let movedAside = false;
11104
+ if (hadPrevious) {
11105
+ try {
11106
+ fs15__namespace.renameSync(outDir, backupDir);
11107
+ movedAside = true;
11108
+ } catch (err) {
11109
+ if (!isLockError(err)) throw err;
11110
+ fs15__namespace.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
11111
+ process.stderr.write(
11112
+ `\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.
11113
+ `
11114
+ );
11115
+ }
11116
+ }
11044
11117
  try {
11045
11118
  try {
11046
11119
  fs15__namespace.renameSync(stagingDir, outDir);
@@ -11060,9 +11133,14 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11060
11133
  }
11061
11134
  }
11062
11135
  } catch (err) {
11063
- if (hadPrevious && fs15__namespace.existsSync(backupDir)) {
11136
+ if (hadPrevious && movedAside && fs15__namespace.existsSync(backupDir)) {
11064
11137
  if (fs15__namespace.existsSync(outDir)) fs15__namespace.rmSync(outDir, { recursive: true, force: true });
11065
11138
  fs15__namespace.renameSync(backupDir, outDir);
11139
+ } else if (hadPrevious && !movedAside) {
11140
+ process.stderr.write(
11141
+ `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
11142
+ `
11143
+ );
11066
11144
  }
11067
11145
  throw err;
11068
11146
  }
@@ -11077,6 +11155,10 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11077
11155
  }
11078
11156
  }
11079
11157
  }
11158
+ function isLockError(err) {
11159
+ const code = err.code;
11160
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
11161
+ }
11080
11162
  function sleepSync(milliseconds) {
11081
11163
  const buffer = new Int32Array(new SharedArrayBuffer(4));
11082
11164
  Atomics.wait(buffer, 0, 0, milliseconds);
@@ -11180,10 +11262,6 @@ function generateSnapshot(configInput, options) {
11180
11262
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
11181
11263
  const secretFindings = [];
11182
11264
  const warnings = [];
11183
- const budgetOrderCutsFiles = () => {
11184
- if (config.maxPartBytes >= config.largeFileBytes) return false;
11185
- return files.some((file) => file.isPreviewTruncated && !file.isLarge);
11186
- };
11187
11265
  const encodingNotes = [];
11188
11266
  const fileWarnings = [];
11189
11267
  const oversizeSummaryPaths = [];
@@ -11345,11 +11423,16 @@ function generateSnapshot(configInput, options) {
11345
11423
  inclusionMode: derivation.inclusionMode,
11346
11424
  isLarge: derivation.isLarge,
11347
11425
  isPreviewTruncated: derivation.isPreviewTruncated,
11426
+ ...derivation.truncationReason === void 0 ? {} : { truncationReason: derivation.truncationReason },
11427
+ ...derivation.omittedRanges.length === 0 ? {} : { omittedRanges: derivation.omittedRanges },
11348
11428
  originalLines: lineCount,
11349
11429
  includedLines: derivation.includedLines,
11350
11430
  includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
11351
11431
  summary: derivation.summary,
11352
11432
  summaryQuality: derivation.summaryQuality,
11433
+ // A summary skipped for size is not an absent summary: record it the same way the
11434
+ // partitioner records one it had to drop, so a reader can tell the two apart.
11435
+ ...derivation.summarySkip === null ? {} : { summaryOmitted: true, summaryOmittedReason: derivation.summarySkip },
11353
11436
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
11354
11437
  content: derivation.finalContent
11355
11438
  });
@@ -11469,7 +11552,28 @@ function generateSnapshot(configInput, options) {
11469
11552
  }
11470
11553
  const parts = partitionByBudget(files, config, fingerprint);
11471
11554
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11472
- const validationErrors = verifyInMemory(files, parts);
11555
+ const incomplete = files.flatMap((file) => {
11556
+ if (file.truncationReason === void 0) return [];
11557
+ const ranges = file.omittedRanges ?? [];
11558
+ const omittedLines = ranges.reduce((total, [from, to]) => total + (to - from + 1), 0);
11559
+ return [
11560
+ {
11561
+ relativePath: file.relativePath,
11562
+ part: file.part,
11563
+ reason: file.truncationReason,
11564
+ omittedRanges: ranges,
11565
+ omittedLines,
11566
+ includedLines: file.includedLines,
11567
+ lines: file.lines
11568
+ }
11569
+ ];
11570
+ });
11571
+ const accounted = /* @__PURE__ */ new Set([
11572
+ ...files.map((file) => maskPathText(file.relativePath, config.secretRules)),
11573
+ ...skipped.map((record) => record.path)
11574
+ ]);
11575
+ const unaccounted = candidateFiles.map((candidate) => maskPathText(candidate, config.secretRules)).filter((candidate) => !accounted.has(candidate));
11576
+ const validationErrors = verifyInMemory(files, parts, unaccounted);
11473
11577
  const totalContentBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11474
11578
  const maskName = (value) => maskPathText(value, config.secretRules);
11475
11579
  const manifest = {
@@ -11530,7 +11634,8 @@ function generateSnapshot(configInput, options) {
11530
11634
  partsCount: parts.length,
11531
11635
  skippedCount: skipped.length,
11532
11636
  largeFileCount,
11533
- truncatedPreviewCount
11637
+ truncatedPreviewCount,
11638
+ incompleteCount: incomplete.length
11534
11639
  },
11535
11640
  totals: {
11536
11641
  candidateFiles: files.length + skipped.length,
@@ -11567,19 +11672,14 @@ function generateSnapshot(configInput, options) {
11567
11672
  return rest;
11568
11673
  }),
11569
11674
  skipped: maskSkipRecords(skipped, config.secretRules),
11675
+ incomplete,
11570
11676
  warnings
11571
11677
  };
11572
11678
  manifest.totals.redactedLines = secretFindings.length;
11573
11679
  manifest.totals.warningCount = manifest.warnings.length;
11574
- if (budgetOrderCutsFiles()) {
11680
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
11575
11681
  manifest.warnings.push(
11576
- `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.`
11577
- );
11578
- manifest.totals.warningCount = manifest.warnings.length;
11579
- }
11580
- if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
11581
- manifest.warnings.push(
11582
- `${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.`
11682
+ `${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.`
11583
11683
  );
11584
11684
  manifest.totals.warningCount = manifest.warnings.length;
11585
11685
  }
@@ -12947,6 +13047,9 @@ var readTool = {
12947
13047
  structured: {
12948
13048
  path: entry.relativePath,
12949
13049
  part: entry.part,
13050
+ // The window itself: a caller that wants to measure or re-send what it received should
13051
+ // not have to strip the header and the paging note back off `text`.
13052
+ body,
12950
13053
  layer: entry.layer,
12951
13054
  kind: entry.kind,
12952
13055
  language: entry.language,
@@ -13508,7 +13611,7 @@ function buildAgentContract() {
13508
13611
  id: "consume",
13509
13612
  run: "read ./snapshot/parts/*.md, then ./snapshot/manifest.json, then ./snapshot/reports/audit.md",
13510
13613
  expect: "the code, the index of what was included, and the risk findings",
13511
- 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."
13614
+ 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."
13512
13615
  }
13513
13616
  ],
13514
13617
  commands: [
@@ -13613,9 +13716,9 @@ function buildAgentContract() {
13613
13716
  {
13614
13717
  flag: "--large-file-bytes",
13615
13718
  type: "string",
13616
- default: 204800,
13719
+ default: 307200,
13617
13720
  appliesTo: optionAppliesTo("large-file-bytes"),
13618
- summary: "Above this size a file gets a head/tail preview instead of the full body."
13721
+ 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."
13619
13722
  },
13620
13723
  {
13621
13724
  flag: "--max-monolith-bytes",
@@ -13850,7 +13953,7 @@ function buildAgentContract() {
13850
13953
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
13851
13954
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
13852
13955
  { key: "withDependents", type: "boolean", default: false, summary: "With a changed-files scope, also include one hop of importers." },
13853
- { key: "largeFileBytes", type: "number | string", default: 204800, summary: "Preview threshold for large files." },
13956
+ { key: "largeFileBytes", type: "number | string", default: 307200, summary: "Preview threshold for large files; defaults to maxPartBytes and may not exceed it." },
13854
13957
  { key: "previewHeadLines", type: "number", default: 80, summary: "Lines kept from the head of a large file." },
13855
13958
  { key: "previewTailLines", type: "number", default: 40, summary: "Lines kept from the tail of a large file." },
13856
13959
  { key: "includeMonolith", type: "boolean", default: false, summary: "Also write the single-file monolith." },
@@ -13879,8 +13982,8 @@ function buildAgentContract() {
13879
13982
  "<outDir>/.codebase-snapshot (ownership marker, always written)"
13880
13983
  ],
13881
13984
  notes: [
13882
- "Parts are ordered and budget-limited; a single file larger than the budget becomes a head/tail preview.",
13883
- "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.",
13985
+ "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.",
13986
+ "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.",
13884
13987
  "manifest.skipped[] carries the path and the exact reason it was excluded.",
13885
13988
  `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
13886
13989
  ]
@@ -14042,10 +14145,12 @@ do not assume the repository is broken.
14042
14145
  \`kind\`, \`language\`, \`part\`, \`inclusionMode\`, \`hashSha256\` and the structural
14043
14146
  \`summary\`, plus \`encoding\` when the file was not plain UTF-8. \`summary\` is
14044
14147
  **optional**: it is absent for languages with no structural summary, and
14045
- \`summaryOmitted: true\` marks one dropped to fit the part budget \u2014 never assume it
14148
+ \`summaryOmitted: true\` marks one dropped for size, and the reason in \`summaryOmittedReason\` says which rule \u2014 never assume it
14046
14149
  exists. The per-file \`hashSha256\` is only here and in the manifest; it is not printed
14047
14150
  into the parts.
14048
- \`skipped[]\` records every excluded file **and why**. Prefer querying this over
14151
+ \`skipped[]\` records every excluded file **and why**. The top-level \`incomplete[]\` records every included
14152
+ file whose body is not the whole file, with its reason and omittedRanges: ask that list,
14153
+ not the footer of a part, when the question is whether anything was lost. Prefer querying this over
14049
14154
  re-reading the parts.
14050
14155
  - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
14051
14156
  state. Read this before you quote code back to a user.
@@ -15178,7 +15283,7 @@ Options:
15178
15283
  --max-part-bytes <n> Maximum byte budget per markdown part (default: 307200).
15179
15284
  Accepts units: 120k, 1.5mb
15180
15285
  --max-part-tokens <n> Per-part budget in tokens; narrows --max-part-bytes
15181
- --large-file-bytes <n> Threshold for head/tail truncation (default: 204800)
15286
+ --large-file-bytes <n> Preview threshold (default: the part budget; never above it)
15182
15287
  --changed-since <ref> Only files changed since this git ref, plus untracked ones
15183
15288
  --staged Only files staged for the next commit
15184
15289
  --with-dependents With the two above: also include their importers
@@ -15624,6 +15729,17 @@ async function runInitCommand(invocation) {
15624
15729
  return fail(invocation.format, err.message);
15625
15730
  }
15626
15731
  }
15732
+ function generatorOrigin(cwd) {
15733
+ try {
15734
+ const pkg = JSON.parse(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
15735
+ const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
15736
+ if (typeof spec === "string") return `project dependency ${spec}`;
15737
+ } catch {
15738
+ }
15739
+ const entry = process.argv[1] ?? "";
15740
+ if (entry.includes("_npx") || entry.includes(`${path16__namespace.sep}npx${path16__namespace.sep}`)) return "via npx";
15741
+ return "global or direct install";
15742
+ }
15627
15743
  function detectPackageManager(cwd) {
15628
15744
  const has = (name) => fs15__namespace.existsSync(path16__namespace.join(cwd, name));
15629
15745
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
@@ -15771,9 +15887,14 @@ async function runSetupCommand(invocation, options = {}) {
15771
15887
  info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
15772
15888
  }
15773
15889
  }
15890
+ const hasManifest = fs15__namespace.existsSync(path16__namespace.join(invocation.cwd, "package.json"));
15774
15891
  let install = null;
15775
15892
  if (invocation.noInstall) {
15776
15893
  if (invocation.format !== "json") info(" Skipped the install (--no-install)");
15894
+ } else if (!hasManifest) {
15895
+ if (invocation.format !== "json") {
15896
+ info(" Skipped the install: no package.json here, so there is no dependency to add.");
15897
+ }
15777
15898
  } else {
15778
15899
  if (invocation.format !== "json") info("\u23F3 Installing dependencies\u2026");
15779
15900
  install = installDependencies(invocation.cwd);
@@ -16126,7 +16247,7 @@ ${USAGE}
16126
16247
  const started = performance.now();
16127
16248
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
16128
16249
  info(
16129
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB`
16250
+ ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
16130
16251
  );
16131
16252
  try {
16132
16253
  const manifest = generateSnapshot(resolved, { dryRun: invocation.dryRun });
@@ -16144,12 +16265,31 @@ ${USAGE}
16144
16265
  ` - Redacted: ${manifest.totals.redactedLines} line(s) \u2014 a real run lists them in ` + displayOutPath(resolved.cwd, resolved.outDir, "reports/audit.md")
16145
16266
  );
16146
16267
  }
16268
+ const incomplete = manifest.incomplete ?? [];
16269
+ if (incomplete.length > 0) {
16270
+ const byReason = /* @__PURE__ */ new Map();
16271
+ for (const record of incomplete) {
16272
+ byReason.set(record.reason, (byReason.get(record.reason) ?? 0) + 1);
16273
+ }
16274
+ const detail = [...byReason.entries()].map(([reason, count]) => `${count} ${reason}`).join(", ");
16275
+ info(` - Incomplete: ${incomplete.length} file(s) \u2014 ${detail}; see manifest.json incomplete[]`);
16276
+ }
16147
16277
  info(` - Integrity: ${manifest.validation.status}`);
16148
16278
  for (const error of manifest.validation.errors.slice(0, 10)) info(` - ${error}`);
16149
16279
  } else {
16150
16280
  info(`
16151
16281
  \u2705 Snapshot generated in ${elapsed}s:`);
16152
- info(` - Tracked files: ${manifest.counts.totalFiles}`);
16282
+ const skipCounts = /* @__PURE__ */ new Map();
16283
+ for (const record of manifest.skipped) {
16284
+ skipCounts.set(record.reason, (skipCounts.get(record.reason) ?? 0) + 1);
16285
+ }
16286
+ const skipBreakdown = [...skipCounts.entries()].sort((left, right) => right[1] - left[1]).map(([reason, count]) => `${reason} ${formatNumber(count)}`);
16287
+ const shownReasons = skipBreakdown.slice(0, 3);
16288
+ const reasons = skipBreakdown.length > shownReasons.length ? `${shownReasons.join(", ")}, +${skipBreakdown.length - shownReasons.length} more` : shownReasons.join(", ");
16289
+ const candidates = manifest.counts.totalFiles + manifest.counts.skippedCount;
16290
+ info(
16291
+ 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")}`
16292
+ );
16153
16293
  info(` - Total lines: ${formatNumber(manifest.counts.totalLines)}`);
16154
16294
  info(
16155
16295
  ` - Total size: ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB`