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/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.0";
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 = {
@@ -7666,7 +7680,9 @@ function renderConfig(answers) {
7666
7680
  // The same ceiling expressed in tokens; it narrows maxPartBytes rather than
7667
7681
  // replacing it. null = not set. Minimum 1024.
7668
7682
  maxPartTokens: ${answers.maxPartTokens === null ? "null" : String(answers.maxPartTokens)},
7669
- // Files above this size get a head/tail preview instead of the full body.
7683
+ // Files above this size get a head/tail preview instead of the full body. It may not
7684
+ // exceed maxPartBytes: a file between the two could not fit a part, and cutting it to fit
7685
+ // while the manifest called it a preview is exactly what this ceiling pair must prevent.
7670
7686
  largeFileBytes: ${size(answers.largeFileBytes)},
7671
7687
  previewHeadLines: 80,
7672
7688
  previewTailLines: 40,
@@ -8351,6 +8367,9 @@ async function runInit(options) {
8351
8367
  let reason = detected.reason;
8352
8368
  let fallback = detected.fallback;
8353
8369
  const notes = [];
8370
+ const budgetBytes = parseByteSize(options.maxPartBytes ?? detected.recommendedBudget ?? DEFAULT_ANSWERS.maxPartBytes) ?? 307200;
8371
+ const tokenBudgetBytes = options.maxPartTokens === void 0 || options.maxPartTokens === null ? void 0 : options.maxPartTokens * 4;
8372
+ const effectiveBudgetBytes = tokenBudgetBytes === void 0 ? budgetBytes : Math.min(budgetBytes, tokenBudgetBytes);
8354
8373
  const answers = {
8355
8374
  preset: detected.presetName,
8356
8375
  // The repository's own branch, read the same way the generator reads it.
@@ -8364,7 +8383,13 @@ async function runInit(options) {
8364
8383
  // what the run used is drift the next `validate` reports, and `setup` is the one command
8365
8384
  // that is supposed to leave a project in a consistent state.
8366
8385
  maxPartTokens: options.maxPartTokens ?? DEFAULT_ANSWERS.maxPartTokens,
8367
- largeFileBytes: options.largeFileBytes ?? DEFAULT_ANSWERS.largeFileBytes,
8386
+ largeFileBytes: options.largeFileBytes ?? // A threshold above the part budget is a configuration error (a file between the two
8387
+ // cannot fit, so it is cut while the manifest calls it a preview). Writing the old fixed
8388
+ // 200 KB beside `--max-part-tokens 32k` made the setup's own output fail its own validate.
8389
+ Math.min(
8390
+ parseByteSize(DEFAULT_ANSWERS.largeFileBytes) ?? effectiveBudgetBytes,
8391
+ effectiveBudgetBytes
8392
+ ),
8368
8393
  maxMonolithBytes: options.maxMonolithBytes ?? DEFAULT_ANSWERS.maxMonolithBytes,
8369
8394
  discovery: options.discovery ?? DEFAULT_ANSWERS.discovery,
8370
8395
  skeleton: options.skeleton ?? DEFAULT_ANSWERS.skeleton,
@@ -8839,7 +8864,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
8839
8864
  );
8840
8865
  for (const file of affected) {
8841
8866
  const status = file.isPreviewTruncated ? "Truncated" : "Full";
8842
- const cutBy = file.isLarge ? "largeFileBytes" : "maxPartBytes";
8867
+ const cutBy = file.truncationReason === "part-budget" ? "maxPartBytes" : "largeFileBytes";
8843
8868
  lines.push(
8844
8869
  `| ${code(file.relativePath)} | ${file.sizeBytes} | ${file.lines} | ${file.includedBytes} | ${file.includedLines} | ${status} | ${cutBy} |`
8845
8870
  );
@@ -9078,7 +9103,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
9078
9103
  section.file.originalLines
9079
9104
  );
9080
9105
  if (shrunk.isTruncated) {
9081
- applyTruncatedContent(section.file, shrunk.content);
9106
+ applyTruncatedContent(section.file, shrunk.content, "part-budget");
9082
9107
  section.text = renderFileSection(section.file);
9083
9108
  section.byteSize = Buffer.byteLength(section.text, "utf8");
9084
9109
  assemblies.delete(group);
@@ -9152,7 +9177,7 @@ function prepareSection(file, sectionBudget, partBudget) {
9152
9177
  file.originalLines
9153
9178
  );
9154
9179
  if (!truncated.isTruncated) return;
9155
- applyTruncatedContent(file, truncated.content);
9180
+ applyTruncatedContent(file, truncated.content, "part-budget");
9156
9181
  text2 = renderFileSection(file);
9157
9182
  byteSize = Buffer.byteLength(text2, "utf8");
9158
9183
  };
@@ -9160,14 +9185,16 @@ function prepareSection(file, sectionBudget, partBudget) {
9160
9185
  if (byteSize > sectionBudget && file.summary) {
9161
9186
  file.summary = void 0;
9162
9187
  file.summaryOmitted = true;
9188
+ file.summaryOmittedReason = "part-budget";
9163
9189
  text2 = renderFileSection(file);
9164
9190
  byteSize = Buffer.byteLength(text2, "utf8");
9165
9191
  shrinkBody();
9166
9192
  }
9167
9193
  if (byteSize > sectionBudget) {
9168
- applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
9194
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE, "section-metadata");
9169
9195
  file.summary = void 0;
9170
9196
  file.summaryOmitted = true;
9197
+ file.summaryOmittedReason = "part-budget";
9171
9198
  text2 = renderFileSection(file);
9172
9199
  byteSize = Buffer.byteLength(text2, "utf8");
9173
9200
  if (byteSize > sectionBudget) {
@@ -9216,10 +9243,14 @@ function fenceIsOpen(text2, fence) {
9216
9243
  }
9217
9244
  return open;
9218
9245
  }
9219
- function applyTruncatedContent(file, content) {
9246
+ var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
9247
+ function applyTruncatedContent(file, content, reason) {
9248
+ const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
9220
9249
  file.content = content;
9221
9250
  file.isPreviewTruncated = true;
9222
9251
  file.inclusionMode = "preview";
9252
+ file.truncationReason = reason;
9253
+ file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
9223
9254
  file.includedBytes = Buffer.byteLength(content, "utf8");
9224
9255
  file.includedLines = countLines(content);
9225
9256
  }
@@ -9366,7 +9397,9 @@ function renderFileSection(file) {
9366
9397
  compactMetadata(file),
9367
9398
  ...file.summaryQuality ? [`- Summary Quality: ${file.summaryQuality}`] : [],
9368
9399
  ...renderSummary(file.summary, file.inclusionMode),
9369
- ...file.summaryOmitted ? ["- Summary: (omitted: exceeds the part budget)"] : [],
9400
+ ...file.summaryOmitted ? [
9401
+ 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)"
9402
+ ] : [],
9370
9403
  "",
9371
9404
  file.inclusionMode === "preview" ? "#### Bounded Preview" : "#### Content",
9372
9405
  "",
@@ -10129,6 +10162,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10129
10162
  const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
10130
10163
  let finalContent = redacted;
10131
10164
  let isPreviewTruncated = false;
10165
+ let truncationReason;
10166
+ let omittedRanges = [];
10132
10167
  let includedLines = lineCount;
10133
10168
  let inclusionMode = "full";
10134
10169
  if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
@@ -10145,6 +10180,10 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10145
10180
  isPreviewTruncated = preview.isTruncated;
10146
10181
  includedLines = preview.includedLines;
10147
10182
  inclusionMode = isPreviewTruncated ? "preview" : "full";
10183
+ if (isPreviewTruncated) {
10184
+ truncationReason = "large-file-budget";
10185
+ omittedRanges = preview.omittedRanges;
10186
+ }
10148
10187
  }
10149
10188
  let summary;
10150
10189
  let summaryQuality;
@@ -10179,6 +10218,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10179
10218
  finalContent,
10180
10219
  inclusionMode,
10181
10220
  isPreviewTruncated,
10221
+ truncationReason,
10222
+ omittedRanges,
10182
10223
  includedLines,
10183
10224
  isLarge,
10184
10225
  summary,
@@ -10288,8 +10329,30 @@ function buildIndexes(files, tsconfigPaths) {
10288
10329
  }))
10289
10330
  };
10290
10331
  }
10291
- function verifyInMemory(files, parts) {
10332
+ function verifyInMemory(files, parts, unaccounted) {
10292
10333
  const errors = [];
10334
+ if (unaccounted.length > 0) {
10335
+ const shown = unaccounted.slice(0, 5).join(", ");
10336
+ errors.push(
10337
+ `${unaccounted.length} scanned file(s) appear in neither files[] nor skipped[]${unaccounted.length > 5 ? ` (first five: ${shown})` : `: ${shown}`}.`
10338
+ );
10339
+ }
10340
+ for (const file of files) {
10341
+ if (file.isPreviewTruncated && file.truncationReason === void 0) {
10342
+ errors.push(`${file.relativePath} is truncated but records no truncationReason.`);
10343
+ }
10344
+ const ranges = file.omittedRanges ?? [];
10345
+ if (file.truncationReason !== void 0 && ranges.length === 0) {
10346
+ errors.push(`${file.relativePath} is truncated but records no omittedRanges.`);
10347
+ }
10348
+ for (const [from, to] of ranges) {
10349
+ if (from < 1 || to < from || to > file.lines) {
10350
+ errors.push(
10351
+ `${file.relativePath} records omitted range ${from}-${to}, outside 1-${file.lines}.`
10352
+ );
10353
+ }
10354
+ }
10355
+ }
10293
10356
  const partNames = new Set(parts.map((part) => part.filename));
10294
10357
  for (const file of files) {
10295
10358
  if (!file.part || !partNames.has(file.part)) {
@@ -11040,7 +11103,20 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11040
11103
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
11041
11104
  const hadPrevious = fs15__namespace.existsSync(outDir);
11042
11105
  if (hadPrevious) beforeSwap?.();
11043
- if (hadPrevious) fs15__namespace.renameSync(outDir, backupDir);
11106
+ let movedAside = false;
11107
+ if (hadPrevious) {
11108
+ try {
11109
+ fs15__namespace.renameSync(outDir, backupDir);
11110
+ movedAside = true;
11111
+ } catch (err) {
11112
+ if (!isLockError(err)) throw err;
11113
+ fs15__namespace.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
11114
+ process.stderr.write(
11115
+ `\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.
11116
+ `
11117
+ );
11118
+ }
11119
+ }
11044
11120
  try {
11045
11121
  try {
11046
11122
  fs15__namespace.renameSync(stagingDir, outDir);
@@ -11060,9 +11136,14 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11060
11136
  }
11061
11137
  }
11062
11138
  } catch (err) {
11063
- if (hadPrevious && fs15__namespace.existsSync(backupDir)) {
11139
+ if (hadPrevious && movedAside && fs15__namespace.existsSync(backupDir)) {
11064
11140
  if (fs15__namespace.existsSync(outDir)) fs15__namespace.rmSync(outDir, { recursive: true, force: true });
11065
11141
  fs15__namespace.renameSync(backupDir, outDir);
11142
+ } else if (hadPrevious && !movedAside) {
11143
+ process.stderr.write(
11144
+ `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
11145
+ `
11146
+ );
11066
11147
  }
11067
11148
  throw err;
11068
11149
  }
@@ -11077,6 +11158,10 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11077
11158
  }
11078
11159
  }
11079
11160
  }
11161
+ function isLockError(err) {
11162
+ const code = err.code;
11163
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
11164
+ }
11080
11165
  function sleepSync(milliseconds) {
11081
11166
  const buffer = new Int32Array(new SharedArrayBuffer(4));
11082
11167
  Atomics.wait(buffer, 0, 0, milliseconds);
@@ -11180,10 +11265,6 @@ function generateSnapshot(configInput, options) {
11180
11265
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
11181
11266
  const secretFindings = [];
11182
11267
  const warnings = [];
11183
- const budgetOrderCutsFiles = () => {
11184
- if (config.maxPartBytes >= config.largeFileBytes) return false;
11185
- return files.some((file) => file.isPreviewTruncated && !file.isLarge);
11186
- };
11187
11268
  const encodingNotes = [];
11188
11269
  const fileWarnings = [];
11189
11270
  const oversizeSummaryPaths = [];
@@ -11345,11 +11426,16 @@ function generateSnapshot(configInput, options) {
11345
11426
  inclusionMode: derivation.inclusionMode,
11346
11427
  isLarge: derivation.isLarge,
11347
11428
  isPreviewTruncated: derivation.isPreviewTruncated,
11429
+ ...derivation.truncationReason === void 0 ? {} : { truncationReason: derivation.truncationReason },
11430
+ ...derivation.omittedRanges.length === 0 ? {} : { omittedRanges: derivation.omittedRanges },
11348
11431
  originalLines: lineCount,
11349
11432
  includedLines: derivation.includedLines,
11350
11433
  includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
11351
11434
  summary: derivation.summary,
11352
11435
  summaryQuality: derivation.summaryQuality,
11436
+ // A summary skipped for size is not an absent summary: record it the same way the
11437
+ // partitioner records one it had to drop, so a reader can tell the two apart.
11438
+ ...derivation.summarySkip === null ? {} : { summaryOmitted: true, summaryOmittedReason: derivation.summarySkip },
11353
11439
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
11354
11440
  content: derivation.finalContent
11355
11441
  });
@@ -11469,7 +11555,28 @@ function generateSnapshot(configInput, options) {
11469
11555
  }
11470
11556
  const parts = partitionByBudget(files, config, fingerprint);
11471
11557
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11472
- const validationErrors = verifyInMemory(files, parts);
11558
+ const incomplete = files.flatMap((file) => {
11559
+ if (file.truncationReason === void 0) return [];
11560
+ const ranges = file.omittedRanges ?? [];
11561
+ const omittedLines = ranges.reduce((total, [from, to]) => total + (to - from + 1), 0);
11562
+ return [
11563
+ {
11564
+ relativePath: file.relativePath,
11565
+ part: file.part,
11566
+ reason: file.truncationReason,
11567
+ omittedRanges: ranges,
11568
+ omittedLines,
11569
+ includedLines: file.includedLines,
11570
+ lines: file.lines
11571
+ }
11572
+ ];
11573
+ });
11574
+ const accounted = /* @__PURE__ */ new Set([
11575
+ ...files.map((file) => maskPathText(file.relativePath, config.secretRules)),
11576
+ ...skipped.map((record) => record.path)
11577
+ ]);
11578
+ const unaccounted = candidateFiles.map((candidate) => maskPathText(candidate, config.secretRules)).filter((candidate) => !accounted.has(candidate));
11579
+ const validationErrors = verifyInMemory(files, parts, unaccounted);
11473
11580
  const totalContentBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11474
11581
  const maskName = (value) => maskPathText(value, config.secretRules);
11475
11582
  const manifest = {
@@ -11530,7 +11637,8 @@ function generateSnapshot(configInput, options) {
11530
11637
  partsCount: parts.length,
11531
11638
  skippedCount: skipped.length,
11532
11639
  largeFileCount,
11533
- truncatedPreviewCount
11640
+ truncatedPreviewCount,
11641
+ incompleteCount: incomplete.length
11534
11642
  },
11535
11643
  totals: {
11536
11644
  candidateFiles: files.length + skipped.length,
@@ -11567,19 +11675,14 @@ function generateSnapshot(configInput, options) {
11567
11675
  return rest;
11568
11676
  }),
11569
11677
  skipped: maskSkipRecords(skipped, config.secretRules),
11678
+ incomplete,
11570
11679
  warnings
11571
11680
  };
11572
11681
  manifest.totals.redactedLines = secretFindings.length;
11573
11682
  manifest.totals.warningCount = manifest.warnings.length;
11574
- if (budgetOrderCutsFiles()) {
11683
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
11575
11684
  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.`
11685
+ `${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
11686
  );
11584
11687
  manifest.totals.warningCount = manifest.warnings.length;
11585
11688
  }
@@ -12947,6 +13050,9 @@ var readTool = {
12947
13050
  structured: {
12948
13051
  path: entry.relativePath,
12949
13052
  part: entry.part,
13053
+ // The window itself: a caller that wants to measure or re-send what it received should
13054
+ // not have to strip the header and the paging note back off `text`.
13055
+ body,
12950
13056
  layer: entry.layer,
12951
13057
  kind: entry.kind,
12952
13058
  language: entry.language,
@@ -13613,9 +13719,9 @@ function buildAgentContract() {
13613
13719
  {
13614
13720
  flag: "--large-file-bytes",
13615
13721
  type: "string",
13616
- default: 204800,
13722
+ default: 307200,
13617
13723
  appliesTo: optionAppliesTo("large-file-bytes"),
13618
- summary: "Above this size a file gets a head/tail preview instead of the full body."
13724
+ 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
13725
  },
13620
13726
  {
13621
13727
  flag: "--max-monolith-bytes",
@@ -13850,7 +13956,7 @@ function buildAgentContract() {
13850
13956
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
13851
13957
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
13852
13958
  { 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." },
13959
+ { key: "largeFileBytes", type: "number | string", default: 307200, summary: "Preview threshold for large files; defaults to maxPartBytes and may not exceed it." },
13854
13960
  { key: "previewHeadLines", type: "number", default: 80, summary: "Lines kept from the head of a large file." },
13855
13961
  { key: "previewTailLines", type: "number", default: 40, summary: "Lines kept from the tail of a large file." },
13856
13962
  { key: "includeMonolith", type: "boolean", default: false, summary: "Also write the single-file monolith." },
@@ -13879,8 +13985,8 @@ function buildAgentContract() {
13879
13985
  "<outDir>/.codebase-snapshot (ownership marker, always written)"
13880
13986
  ],
13881
13987
  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.",
13988
+ "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.",
13989
+ "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
13990
  "manifest.skipped[] carries the path and the exact reason it was excluded.",
13885
13991
  `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
13886
13992
  ]
@@ -14042,10 +14148,12 @@ do not assume the repository is broken.
14042
14148
  \`kind\`, \`language\`, \`part\`, \`inclusionMode\`, \`hashSha256\` and the structural
14043
14149
  \`summary\`, plus \`encoding\` when the file was not plain UTF-8. \`summary\` is
14044
14150
  **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
14151
+ \`summaryOmitted: true\` marks one dropped for size, and the reason in \`summaryOmittedReason\` says which rule \u2014 never assume it
14046
14152
  exists. The per-file \`hashSha256\` is only here and in the manifest; it is not printed
14047
14153
  into the parts.
14048
- \`skipped[]\` records every excluded file **and why**. Prefer querying this over
14154
+ \`skipped[]\` records every excluded file **and why**. The top-level \`incomplete[]\` records every included
14155
+ file whose body is not the whole file, with its reason and omittedRanges: ask that list,
14156
+ not the footer of a part, when the question is whether anything was lost. Prefer querying this over
14049
14157
  re-reading the parts.
14050
14158
  - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
14051
14159
  state. Read this before you quote code back to a user.
@@ -15624,6 +15732,17 @@ async function runInitCommand(invocation) {
15624
15732
  return fail(invocation.format, err.message);
15625
15733
  }
15626
15734
  }
15735
+ function generatorOrigin(cwd) {
15736
+ try {
15737
+ const pkg = JSON.parse(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
15738
+ const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
15739
+ if (typeof spec === "string") return `project dependency ${spec}`;
15740
+ } catch {
15741
+ }
15742
+ const entry = process.argv[1] ?? "";
15743
+ if (entry.includes("_npx") || entry.includes(`${path16__namespace.sep}npx${path16__namespace.sep}`)) return "via npx";
15744
+ return "global or direct install";
15745
+ }
15627
15746
  function detectPackageManager(cwd) {
15628
15747
  const has = (name) => fs15__namespace.existsSync(path16__namespace.join(cwd, name));
15629
15748
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
@@ -15771,9 +15890,14 @@ async function runSetupCommand(invocation, options = {}) {
15771
15890
  info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
15772
15891
  }
15773
15892
  }
15893
+ const hasManifest = fs15__namespace.existsSync(path16__namespace.join(invocation.cwd, "package.json"));
15774
15894
  let install = null;
15775
15895
  if (invocation.noInstall) {
15776
15896
  if (invocation.format !== "json") info(" Skipped the install (--no-install)");
15897
+ } else if (!hasManifest) {
15898
+ if (invocation.format !== "json") {
15899
+ info(" Skipped the install: no package.json here, so there is no dependency to add.");
15900
+ }
15777
15901
  } else {
15778
15902
  if (invocation.format !== "json") info("\u23F3 Installing dependencies\u2026");
15779
15903
  install = installDependencies(invocation.cwd);
@@ -16126,7 +16250,7 @@ ${USAGE}
16126
16250
  const started = performance.now();
16127
16251
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
16128
16252
  info(
16129
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB`
16253
+ ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
16130
16254
  );
16131
16255
  try {
16132
16256
  const manifest = generateSnapshot(resolved, { dryRun: invocation.dryRun });
@@ -16144,12 +16268,31 @@ ${USAGE}
16144
16268
  ` - Redacted: ${manifest.totals.redactedLines} line(s) \u2014 a real run lists them in ` + displayOutPath(resolved.cwd, resolved.outDir, "reports/audit.md")
16145
16269
  );
16146
16270
  }
16271
+ const incomplete = manifest.incomplete ?? [];
16272
+ if (incomplete.length > 0) {
16273
+ const byReason = /* @__PURE__ */ new Map();
16274
+ for (const record of incomplete) {
16275
+ byReason.set(record.reason, (byReason.get(record.reason) ?? 0) + 1);
16276
+ }
16277
+ const detail = [...byReason.entries()].map(([reason, count]) => `${count} ${reason}`).join(", ");
16278
+ info(` - Incomplete: ${incomplete.length} file(s) \u2014 ${detail}; see manifest.json incomplete[]`);
16279
+ }
16147
16280
  info(` - Integrity: ${manifest.validation.status}`);
16148
16281
  for (const error of manifest.validation.errors.slice(0, 10)) info(` - ${error}`);
16149
16282
  } else {
16150
16283
  info(`
16151
16284
  \u2705 Snapshot generated in ${elapsed}s:`);
16152
- info(` - Tracked files: ${manifest.counts.totalFiles}`);
16285
+ const skipCounts = /* @__PURE__ */ new Map();
16286
+ for (const record of manifest.skipped) {
16287
+ skipCounts.set(record.reason, (skipCounts.get(record.reason) ?? 0) + 1);
16288
+ }
16289
+ const skipBreakdown = [...skipCounts.entries()].sort((left, right) => right[1] - left[1]).map(([reason, count]) => `${reason} ${formatNumber(count)}`);
16290
+ const shownReasons = skipBreakdown.slice(0, 3);
16291
+ const reasons = skipBreakdown.length > shownReasons.length ? `${shownReasons.join(", ")}, +${skipBreakdown.length - shownReasons.length} more` : shownReasons.join(", ");
16292
+ const candidates = manifest.counts.totalFiles + manifest.counts.skippedCount;
16293
+ info(
16294
+ 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")}`
16295
+ );
16153
16296
  info(` - Total lines: ${formatNumber(manifest.counts.totalLines)}`);
16154
16297
  info(
16155
16298
  ` - Total size: ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB`