codebase-snapshot 0.9.17 → 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/index.cjs CHANGED
@@ -2255,7 +2255,7 @@ var JS_PRESETS = [
2255
2255
  ...commonKinds()
2256
2256
  ],
2257
2257
  exclude: [".nuxt", ".output"],
2258
- recommendedBudget: "200k"
2258
+ recommendedBudget: "300k"
2259
2259
  },
2260
2260
  {
2261
2261
  name: "sveltekit",
@@ -2276,7 +2276,7 @@ var JS_PRESETS = [
2276
2276
  ...commonKinds()
2277
2277
  ],
2278
2278
  exclude: [".svelte-kit", ".vercel"],
2279
- recommendedBudget: "200k"
2279
+ recommendedBudget: "300k"
2280
2280
  },
2281
2281
  {
2282
2282
  name: "remix",
@@ -2290,7 +2290,7 @@ var JS_PRESETS = [
2290
2290
  ],
2291
2291
  kinds: [kindOf("route", "routes/"), ...commonKinds()],
2292
2292
  exclude: [".cache", "public/build"],
2293
- recommendedBudget: "200k"
2293
+ recommendedBudget: "300k"
2294
2294
  },
2295
2295
  {
2296
2296
  name: "astro",
@@ -2305,7 +2305,7 @@ var JS_PRESETS = [
2305
2305
  ],
2306
2306
  kinds: [suffixKind("page", ".astro"), kindOf("layout", "layouts/"), ...commonKinds()],
2307
2307
  exclude: [".astro", "dist"],
2308
- recommendedBudget: "150k"
2308
+ recommendedBudget: "300k"
2309
2309
  },
2310
2310
  {
2311
2311
  name: "angular",
@@ -2329,7 +2329,7 @@ var JS_PRESETS = [
2329
2329
  ...commonKinds()
2330
2330
  ],
2331
2331
  exclude: [".angular", "dist"],
2332
- recommendedBudget: "200k"
2332
+ recommendedBudget: "300k"
2333
2333
  },
2334
2334
  {
2335
2335
  name: "solid",
@@ -2342,7 +2342,7 @@ var JS_PRESETS = [
2342
2342
  ],
2343
2343
  kinds: [kindOf("route", "routes/"), ...commonKinds()],
2344
2344
  exclude: [".solid", "dist"],
2345
- recommendedBudget: "120k"
2345
+ recommendedBudget: "300k"
2346
2346
  },
2347
2347
  {
2348
2348
  name: "vue-vite",
@@ -2375,7 +2375,7 @@ var JS_PRESETS = [
2375
2375
  ...commonKinds()
2376
2376
  ],
2377
2377
  exclude: [".vite", "dist"],
2378
- recommendedBudget: "120k"
2378
+ recommendedBudget: "300k"
2379
2379
  },
2380
2380
  {
2381
2381
  name: "react-vite",
@@ -2389,7 +2389,7 @@ var JS_PRESETS = [
2389
2389
  layers: VITE_LAYERS,
2390
2390
  kinds: VITE_KINDS,
2391
2391
  exclude: [".vite", "dist"],
2392
- recommendedBudget: "120k"
2392
+ recommendedBudget: "300k"
2393
2393
  },
2394
2394
  {
2395
2395
  name: "nest",
@@ -2415,7 +2415,7 @@ var JS_PRESETS = [
2415
2415
  ...commonKinds()
2416
2416
  ],
2417
2417
  exclude: ["dist", "node_modules"],
2418
- recommendedBudget: "200k"
2418
+ recommendedBudget: "300k"
2419
2419
  },
2420
2420
  {
2421
2421
  name: "node-express",
@@ -2424,7 +2424,7 @@ var JS_PRESETS = [
2424
2424
  layers: NODE_LAYERS,
2425
2425
  kinds: NODE_KINDS,
2426
2426
  exclude: ["dist"],
2427
- recommendedBudget: "200k"
2427
+ recommendedBudget: "300k"
2428
2428
  },
2429
2429
  {
2430
2430
  name: "node-lib",
@@ -2440,7 +2440,7 @@ var JS_PRESETS = [
2440
2440
  ],
2441
2441
  kinds: [suffixKind("type", ".d.ts"), ...commonKinds()],
2442
2442
  exclude: ["dist"],
2443
- recommendedBudget: "120k"
2443
+ recommendedBudget: "300k"
2444
2444
  }
2445
2445
  ];
2446
2446
 
@@ -2471,7 +2471,7 @@ var LANGUAGE_PRESETS = [
2471
2471
  ...commonKinds()
2472
2472
  ],
2473
2473
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs", "staticfiles", "media"],
2474
- recommendedBudget: "150k"
2474
+ recommendedBudget: "300k"
2475
2475
  },
2476
2476
  {
2477
2477
  name: "python-fastapi",
@@ -2494,7 +2494,7 @@ var LANGUAGE_PRESETS = [
2494
2494
  ...commonKinds()
2495
2495
  ],
2496
2496
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs"],
2497
- recommendedBudget: "150k"
2497
+ recommendedBudget: "300k"
2498
2498
  },
2499
2499
  {
2500
2500
  name: "python-lib",
@@ -2508,7 +2508,7 @@ var LANGUAGE_PRESETS = [
2508
2508
  ],
2509
2509
  kinds: [suffixKind("module", ".py"), ...commonKinds()],
2510
2510
  exclude: ["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".tox", ".eggs"],
2511
- recommendedBudget: "120k"
2511
+ recommendedBudget: "300k"
2512
2512
  },
2513
2513
  {
2514
2514
  name: "go",
@@ -2532,7 +2532,7 @@ var LANGUAGE_PRESETS = [
2532
2532
  ...commonKinds()
2533
2533
  ],
2534
2534
  exclude: ["vendor", "testdata"],
2535
- recommendedBudget: "200k"
2535
+ recommendedBudget: "300k"
2536
2536
  },
2537
2537
  {
2538
2538
  name: "rust",
@@ -2548,7 +2548,7 @@ var LANGUAGE_PRESETS = [
2548
2548
  ],
2549
2549
  kinds: [suffixKind("module", ".rs"), suffixKind("test", "_test.rs"), ...commonKinds()],
2550
2550
  exclude: ["target"],
2551
- recommendedBudget: "200k"
2551
+ recommendedBudget: "300k"
2552
2552
  },
2553
2553
  {
2554
2554
  name: "java-spring",
@@ -2571,7 +2571,7 @@ var LANGUAGE_PRESETS = [
2571
2571
  ...commonKinds()
2572
2572
  ],
2573
2573
  exclude: [".gradle", "out", "target"],
2574
- recommendedBudget: "200k"
2574
+ recommendedBudget: "300k"
2575
2575
  },
2576
2576
  {
2577
2577
  name: "dotnet",
@@ -2594,7 +2594,7 @@ var LANGUAGE_PRESETS = [
2594
2594
  ...commonKinds()
2595
2595
  ],
2596
2596
  exclude: ["bin", "obj", ".vs"],
2597
- recommendedBudget: "200k"
2597
+ recommendedBudget: "300k"
2598
2598
  },
2599
2599
  {
2600
2600
  name: "php-laravel",
@@ -2620,7 +2620,7 @@ var LANGUAGE_PRESETS = [
2620
2620
  ...commonKinds()
2621
2621
  ],
2622
2622
  exclude: ["vendor", "storage", "bootstrap/cache", "public/build"],
2623
- recommendedBudget: "150k"
2623
+ recommendedBudget: "300k"
2624
2624
  },
2625
2625
  {
2626
2626
  name: "ruby-rails",
@@ -2645,7 +2645,7 @@ var LANGUAGE_PRESETS = [
2645
2645
  ...commonKinds()
2646
2646
  ],
2647
2647
  exclude: [".bundle", "log", "tmp", "vendor/bundle", "public/assets"],
2648
- recommendedBudget: "150k"
2648
+ recommendedBudget: "300k"
2649
2649
  }
2650
2650
  ];
2651
2651
 
@@ -2707,7 +2707,7 @@ var SHAPE_PRESETS = [
2707
2707
  ],
2708
2708
  kinds: commonKinds(),
2709
2709
  exclude: [".turbo", ".nx"],
2710
- recommendedBudget: "200k"
2710
+ recommendedBudget: "300k"
2711
2711
  },
2712
2712
  {
2713
2713
  name: "infra",
@@ -2725,7 +2725,7 @@ var SHAPE_PRESETS = [
2725
2725
  ...commonKinds()
2726
2726
  ],
2727
2727
  exclude: [".terraform", ".terragrunt-cache"],
2728
- recommendedBudget: "100k"
2728
+ recommendedBudget: "300k"
2729
2729
  },
2730
2730
  {
2731
2731
  name: "docs",
@@ -2742,7 +2742,7 @@ var SHAPE_PRESETS = [
2742
2742
  ],
2743
2743
  kinds: commonKinds(),
2744
2744
  exclude: [".docusaurus", ".vitepress/dist", "site"],
2745
- recommendedBudget: "100k"
2745
+ recommendedBudget: "300k"
2746
2746
  },
2747
2747
  {
2748
2748
  name: "generic",
@@ -2754,7 +2754,7 @@ var SHAPE_PRESETS = [
2754
2754
  layers: DEFAULT_LAYERS,
2755
2755
  kinds: DEFAULT_KINDS,
2756
2756
  exclude: [],
2757
- recommendedBudget: "120k"
2757
+ recommendedBudget: "300k"
2758
2758
  }
2759
2759
  ];
2760
2760
 
@@ -3880,7 +3880,7 @@ function applySpans(line, spans) {
3880
3880
 
3881
3881
  // src/version.ts
3882
3882
  var GENERATOR_NAME = "codebase-snapshot";
3883
- var GENERATOR_VERSION = "0.9.17";
3883
+ var GENERATOR_VERSION = "0.10.0";
3884
3884
  var SCHEMA_VERSION = "3.0.0";
3885
3885
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
3886
3886
  function isOurGeneratorName(name) {
@@ -5191,6 +5191,16 @@ async function loadConfigFile(cwd) {
5191
5191
  }
5192
5192
  return loaded.config;
5193
5193
  }
5194
+ function largeFileBytesFor(maxPartBytes, cliOptions, userConfig) {
5195
+ const requested = cliOptions?.largeFileBytes ?? userConfig?.largeFileBytes;
5196
+ const value = boundedBytes(requested, maxPartBytes, 1, "largeFileBytes");
5197
+ if (value > maxPartBytes) {
5198
+ throw new Error(
5199
+ `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.`
5200
+ );
5201
+ }
5202
+ return value;
5203
+ }
5194
5204
  var MIN_MAX_PART_BYTES = 4096;
5195
5205
  var MIN_MAX_PART_TOKENS = MIN_MAX_PART_BYTES / 4;
5196
5206
  var ARTIFACT_NAMES = [
@@ -5633,7 +5643,7 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
5633
5643
  tmpDir,
5634
5644
  maxPartBytes: resolvedMaxPartBytes,
5635
5645
  ...maxPartTokens === void 0 ? {} : { maxPartTokens },
5636
- largeFileBytes: boundedBytes(cliOptions?.largeFileBytes ?? userConfig?.largeFileBytes, 200 * 1024, 1, "largeFileBytes"),
5646
+ largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
5637
5647
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
5638
5648
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
5639
5649
  includeMonolith: artifacts.monolith,
@@ -5896,7 +5906,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
5896
5906
  );
5897
5907
  for (const file of affected) {
5898
5908
  const status = file.isPreviewTruncated ? "Truncated" : "Full";
5899
- const cutBy = file.isLarge ? "largeFileBytes" : "maxPartBytes";
5909
+ const cutBy = file.truncationReason === "part-budget" ? "maxPartBytes" : "largeFileBytes";
5900
5910
  lines.push(
5901
5911
  `| ${code(file.relativePath)} | ${file.sizeBytes} | ${file.lines} | ${file.includedBytes} | ${file.includedLines} | ${status} | ${cutBy} |`
5902
5912
  );
@@ -6075,7 +6085,8 @@ function truncatePreview(content, headLines, tailLines) {
6075
6085
  content: normalised,
6076
6086
  isTruncated: false,
6077
6087
  originalLines: total,
6078
- includedLines: total
6088
+ includedLines: total,
6089
+ omittedRanges: []
6079
6090
  };
6080
6091
  }
6081
6092
  const window = normalised.endsWith("\n") ? lines.slice(0, -1) : lines;
@@ -6087,13 +6098,16 @@ function truncatePreview(content, headLines, tailLines) {
6087
6098
  `... [${omitted} lines omitted: file exceeds large file size budget] ...`,
6088
6099
  ...tail
6089
6100
  ].join("\n");
6101
+ const firstOmitted = head.length + 1;
6102
+ const lastOmitted = total - tail.length;
6090
6103
  return {
6091
6104
  content: result,
6092
6105
  isTruncated: true,
6093
6106
  originalLines: total,
6094
6107
  // Head + notice + tail is exactly what is emitted; counting the slice is
6095
6108
  // wrong when the source ended with a newline (the trailing "" issue above).
6096
- includedLines: head.length + tail.length + 1
6109
+ includedLines: head.length + tail.length + 1,
6110
+ omittedRanges: lastOmitted >= firstOmitted ? [[firstOmitted, lastOmitted]] : []
6097
6111
  };
6098
6112
  }
6099
6113
 
@@ -6193,7 +6207,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
6193
6207
  section.file.originalLines
6194
6208
  );
6195
6209
  if (shrunk.isTruncated) {
6196
- applyTruncatedContent(section.file, shrunk.content);
6210
+ applyTruncatedContent(section.file, shrunk.content, "part-budget");
6197
6211
  section.text = renderFileSection(section.file);
6198
6212
  section.byteSize = Buffer.byteLength(section.text, "utf8");
6199
6213
  assemblies.delete(group);
@@ -6329,7 +6343,7 @@ function prepareSection(file, sectionBudget, partBudget) {
6329
6343
  file.originalLines
6330
6344
  );
6331
6345
  if (!truncated.isTruncated) return;
6332
- applyTruncatedContent(file, truncated.content);
6346
+ applyTruncatedContent(file, truncated.content, "part-budget");
6333
6347
  text2 = renderFileSection(file);
6334
6348
  byteSize = Buffer.byteLength(text2, "utf8");
6335
6349
  };
@@ -6337,14 +6351,16 @@ function prepareSection(file, sectionBudget, partBudget) {
6337
6351
  if (byteSize > sectionBudget && file.summary) {
6338
6352
  file.summary = void 0;
6339
6353
  file.summaryOmitted = true;
6354
+ file.summaryOmittedReason = "part-budget";
6340
6355
  text2 = renderFileSection(file);
6341
6356
  byteSize = Buffer.byteLength(text2, "utf8");
6342
6357
  shrinkBody();
6343
6358
  }
6344
6359
  if (byteSize > sectionBudget) {
6345
- applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE);
6360
+ applyTruncatedContent(file, SECTION_TRUNCATION_NOTICE, "section-metadata");
6346
6361
  file.summary = void 0;
6347
6362
  file.summaryOmitted = true;
6363
+ file.summaryOmittedReason = "part-budget";
6348
6364
  text2 = renderFileSection(file);
6349
6365
  byteSize = Buffer.byteLength(text2, "utf8");
6350
6366
  if (byteSize > sectionBudget) {
@@ -6393,10 +6409,14 @@ function fenceIsOpen(text2, fence) {
6393
6409
  }
6394
6410
  return open;
6395
6411
  }
6396
- function applyTruncatedContent(file, content) {
6412
+ var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
6413
+ function applyTruncatedContent(file, content, reason) {
6414
+ const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
6397
6415
  file.content = content;
6398
6416
  file.isPreviewTruncated = true;
6399
6417
  file.inclusionMode = "preview";
6418
+ file.truncationReason = reason;
6419
+ file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
6400
6420
  file.includedBytes = Buffer.byteLength(content, "utf8");
6401
6421
  file.includedLines = countLines(content);
6402
6422
  }
@@ -6543,7 +6563,9 @@ function renderFileSection(file) {
6543
6563
  compactMetadata(file),
6544
6564
  ...file.summaryQuality ? [`- Summary Quality: ${file.summaryQuality}`] : [],
6545
6565
  ...renderSummary(file.summary, file.inclusionMode),
6546
- ...file.summaryOmitted ? ["- Summary: (omitted: exceeds the part budget)"] : [],
6566
+ ...file.summaryOmitted ? [
6567
+ 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)"
6568
+ ] : [],
6547
6569
  "",
6548
6570
  file.inclusionMode === "preview" ? "#### Bounded Preview" : "#### Content",
6549
6571
  "",
@@ -8040,6 +8062,7 @@ function validateSnapshot(configInput) {
8040
8062
  }
8041
8063
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
8042
8064
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
8065
+ var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
8043
8066
  var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
8044
8067
  var REQUEST_TIMEOUT_MS = 1200;
8045
8068
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
@@ -8214,7 +8237,8 @@ async function checkForUpdate(options) {
8214
8237
  needsFetch = age >= FAILURE_INTERVAL_MS;
8215
8238
  } else {
8216
8239
  latest = cached.latest;
8217
- needsFetch = age >= CHECK_INTERVAL_MS;
8240
+ const interval = isNewer(cached.latest, options.current) ? CHECK_INTERVAL_MS : UP_TO_DATE_INTERVAL_MS;
8241
+ needsFetch = age >= interval;
8218
8242
  }
8219
8243
  }
8220
8244
  if (needsFetch) {
@@ -8869,7 +8893,9 @@ function renderConfig(answers) {
8869
8893
  // The same ceiling expressed in tokens; it narrows maxPartBytes rather than
8870
8894
  // replacing it. null = not set. Minimum 1024.
8871
8895
  maxPartTokens: ${answers.maxPartTokens === null ? "null" : String(answers.maxPartTokens)},
8872
- // Files above this size get a head/tail preview instead of the full body.
8896
+ // Files above this size get a head/tail preview instead of the full body. It may not
8897
+ // exceed maxPartBytes: a file between the two could not fit a part, and cutting it to fit
8898
+ // while the manifest called it a preview is exactly what this ceiling pair must prevent.
8873
8899
  largeFileBytes: ${size(answers.largeFileBytes)},
8874
8900
  previewHeadLines: 80,
8875
8901
  previewTailLines: 40,
@@ -9554,6 +9580,9 @@ async function runInit(options) {
9554
9580
  let reason = detected.reason;
9555
9581
  let fallback = detected.fallback;
9556
9582
  const notes = [];
9583
+ const budgetBytes = parseByteSize(options.maxPartBytes ?? detected.recommendedBudget ?? DEFAULT_ANSWERS.maxPartBytes) ?? 307200;
9584
+ const tokenBudgetBytes = options.maxPartTokens === void 0 || options.maxPartTokens === null ? void 0 : options.maxPartTokens * 4;
9585
+ const effectiveBudgetBytes = tokenBudgetBytes === void 0 ? budgetBytes : Math.min(budgetBytes, tokenBudgetBytes);
9557
9586
  const answers = {
9558
9587
  preset: detected.presetName,
9559
9588
  // The repository's own branch, read the same way the generator reads it.
@@ -9567,7 +9596,13 @@ async function runInit(options) {
9567
9596
  // what the run used is drift the next `validate` reports, and `setup` is the one command
9568
9597
  // that is supposed to leave a project in a consistent state.
9569
9598
  maxPartTokens: options.maxPartTokens ?? DEFAULT_ANSWERS.maxPartTokens,
9570
- largeFileBytes: options.largeFileBytes ?? DEFAULT_ANSWERS.largeFileBytes,
9599
+ largeFileBytes: options.largeFileBytes ?? // A threshold above the part budget is a configuration error (a file between the two
9600
+ // cannot fit, so it is cut while the manifest calls it a preview). Writing the old fixed
9601
+ // 200 KB beside `--max-part-tokens 32k` made the setup's own output fail its own validate.
9602
+ Math.min(
9603
+ parseByteSize(DEFAULT_ANSWERS.largeFileBytes) ?? effectiveBudgetBytes,
9604
+ effectiveBudgetBytes
9605
+ ),
9571
9606
  maxMonolithBytes: options.maxMonolithBytes ?? DEFAULT_ANSWERS.maxMonolithBytes,
9572
9607
  discovery: options.discovery ?? DEFAULT_ANSWERS.discovery,
9573
9608
  skeleton: options.skeleton ?? DEFAULT_ANSWERS.skeleton,
@@ -10096,6 +10131,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10096
10131
  const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
10097
10132
  let finalContent = redacted;
10098
10133
  let isPreviewTruncated = false;
10134
+ let truncationReason;
10135
+ let omittedRanges = [];
10099
10136
  let includedLines = lineCount;
10100
10137
  let inclusionMode = "full";
10101
10138
  if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
@@ -10112,6 +10149,10 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10112
10149
  isPreviewTruncated = preview.isTruncated;
10113
10150
  includedLines = preview.includedLines;
10114
10151
  inclusionMode = isPreviewTruncated ? "preview" : "full";
10152
+ if (isPreviewTruncated) {
10153
+ truncationReason = "large-file-budget";
10154
+ omittedRanges = preview.omittedRanges;
10155
+ }
10115
10156
  }
10116
10157
  let summary;
10117
10158
  let summaryQuality;
@@ -10146,6 +10187,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10146
10187
  finalContent,
10147
10188
  inclusionMode,
10148
10189
  isPreviewTruncated,
10190
+ truncationReason,
10191
+ omittedRanges,
10149
10192
  includedLines,
10150
10193
  isLarge,
10151
10194
  summary,
@@ -10255,8 +10298,30 @@ function buildIndexes(files, tsconfigPaths) {
10255
10298
  }))
10256
10299
  };
10257
10300
  }
10258
- function verifyInMemory(files, parts) {
10301
+ function verifyInMemory(files, parts, unaccounted) {
10259
10302
  const errors = [];
10303
+ if (unaccounted.length > 0) {
10304
+ const shown = unaccounted.slice(0, 5).join(", ");
10305
+ errors.push(
10306
+ `${unaccounted.length} scanned file(s) appear in neither files[] nor skipped[]${unaccounted.length > 5 ? ` (first five: ${shown})` : `: ${shown}`}.`
10307
+ );
10308
+ }
10309
+ for (const file of files) {
10310
+ if (file.isPreviewTruncated && file.truncationReason === void 0) {
10311
+ errors.push(`${file.relativePath} is truncated but records no truncationReason.`);
10312
+ }
10313
+ const ranges = file.omittedRanges ?? [];
10314
+ if (file.truncationReason !== void 0 && ranges.length === 0) {
10315
+ errors.push(`${file.relativePath} is truncated but records no omittedRanges.`);
10316
+ }
10317
+ for (const [from, to] of ranges) {
10318
+ if (from < 1 || to < from || to > file.lines) {
10319
+ errors.push(
10320
+ `${file.relativePath} records omitted range ${from}-${to}, outside 1-${file.lines}.`
10321
+ );
10322
+ }
10323
+ }
10324
+ }
10260
10325
  const partNames = new Set(parts.map((part) => part.filename));
10261
10326
  for (const file of files) {
10262
10327
  if (!file.part || !partNames.has(file.part)) {
@@ -11007,7 +11072,20 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11007
11072
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
11008
11073
  const hadPrevious = fs15__namespace.existsSync(outDir);
11009
11074
  if (hadPrevious) beforeSwap?.();
11010
- if (hadPrevious) fs15__namespace.renameSync(outDir, backupDir);
11075
+ let movedAside = false;
11076
+ if (hadPrevious) {
11077
+ try {
11078
+ fs15__namespace.renameSync(outDir, backupDir);
11079
+ movedAside = true;
11080
+ } catch (err) {
11081
+ if (!isLockError(err)) throw err;
11082
+ fs15__namespace.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
11083
+ process.stderr.write(
11084
+ `\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.
11085
+ `
11086
+ );
11087
+ }
11088
+ }
11011
11089
  try {
11012
11090
  try {
11013
11091
  fs15__namespace.renameSync(stagingDir, outDir);
@@ -11027,9 +11105,14 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11027
11105
  }
11028
11106
  }
11029
11107
  } catch (err) {
11030
- if (hadPrevious && fs15__namespace.existsSync(backupDir)) {
11108
+ if (hadPrevious && movedAside && fs15__namespace.existsSync(backupDir)) {
11031
11109
  if (fs15__namespace.existsSync(outDir)) fs15__namespace.rmSync(outDir, { recursive: true, force: true });
11032
11110
  fs15__namespace.renameSync(backupDir, outDir);
11111
+ } else if (hadPrevious && !movedAside) {
11112
+ process.stderr.write(
11113
+ `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
11114
+ `
11115
+ );
11033
11116
  }
11034
11117
  throw err;
11035
11118
  }
@@ -11044,6 +11127,10 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11044
11127
  }
11045
11128
  }
11046
11129
  }
11130
+ function isLockError(err) {
11131
+ const code = err.code;
11132
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
11133
+ }
11047
11134
  function sleepSync(milliseconds) {
11048
11135
  const buffer = new Int32Array(new SharedArrayBuffer(4));
11049
11136
  Atomics.wait(buffer, 0, 0, milliseconds);
@@ -11147,10 +11234,6 @@ function generateSnapshot(configInput, options) {
11147
11234
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
11148
11235
  const secretFindings = [];
11149
11236
  const warnings = [];
11150
- const budgetOrderCutsFiles = () => {
11151
- if (config.maxPartBytes >= config.largeFileBytes) return false;
11152
- return files.some((file) => file.isPreviewTruncated && !file.isLarge);
11153
- };
11154
11237
  const encodingNotes = [];
11155
11238
  const fileWarnings = [];
11156
11239
  const oversizeSummaryPaths = [];
@@ -11312,11 +11395,16 @@ function generateSnapshot(configInput, options) {
11312
11395
  inclusionMode: derivation.inclusionMode,
11313
11396
  isLarge: derivation.isLarge,
11314
11397
  isPreviewTruncated: derivation.isPreviewTruncated,
11398
+ ...derivation.truncationReason === void 0 ? {} : { truncationReason: derivation.truncationReason },
11399
+ ...derivation.omittedRanges.length === 0 ? {} : { omittedRanges: derivation.omittedRanges },
11315
11400
  originalLines: lineCount,
11316
11401
  includedLines: derivation.includedLines,
11317
11402
  includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
11318
11403
  summary: derivation.summary,
11319
11404
  summaryQuality: derivation.summaryQuality,
11405
+ // A summary skipped for size is not an absent summary: record it the same way the
11406
+ // partitioner records one it had to drop, so a reader can tell the two apart.
11407
+ ...derivation.summarySkip === null ? {} : { summaryOmitted: true, summaryOmittedReason: derivation.summarySkip },
11320
11408
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
11321
11409
  content: derivation.finalContent
11322
11410
  });
@@ -11436,7 +11524,28 @@ function generateSnapshot(configInput, options) {
11436
11524
  }
11437
11525
  const parts = partitionByBudget(files, config, fingerprint);
11438
11526
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11439
- const validationErrors = verifyInMemory(files, parts);
11527
+ const incomplete = files.flatMap((file) => {
11528
+ if (file.truncationReason === void 0) return [];
11529
+ const ranges = file.omittedRanges ?? [];
11530
+ const omittedLines = ranges.reduce((total, [from, to]) => total + (to - from + 1), 0);
11531
+ return [
11532
+ {
11533
+ relativePath: file.relativePath,
11534
+ part: file.part,
11535
+ reason: file.truncationReason,
11536
+ omittedRanges: ranges,
11537
+ omittedLines,
11538
+ includedLines: file.includedLines,
11539
+ lines: file.lines
11540
+ }
11541
+ ];
11542
+ });
11543
+ const accounted = /* @__PURE__ */ new Set([
11544
+ ...files.map((file) => maskPathText(file.relativePath, config.secretRules)),
11545
+ ...skipped.map((record) => record.path)
11546
+ ]);
11547
+ const unaccounted = candidateFiles.map((candidate) => maskPathText(candidate, config.secretRules)).filter((candidate) => !accounted.has(candidate));
11548
+ const validationErrors = verifyInMemory(files, parts, unaccounted);
11440
11549
  const totalContentBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11441
11550
  const maskName = (value) => maskPathText(value, config.secretRules);
11442
11551
  const manifest = {
@@ -11497,7 +11606,8 @@ function generateSnapshot(configInput, options) {
11497
11606
  partsCount: parts.length,
11498
11607
  skippedCount: skipped.length,
11499
11608
  largeFileCount,
11500
- truncatedPreviewCount
11609
+ truncatedPreviewCount,
11610
+ incompleteCount: incomplete.length
11501
11611
  },
11502
11612
  totals: {
11503
11613
  candidateFiles: files.length + skipped.length,
@@ -11534,19 +11644,14 @@ function generateSnapshot(configInput, options) {
11534
11644
  return rest;
11535
11645
  }),
11536
11646
  skipped: maskSkipRecords(skipped, config.secretRules),
11647
+ incomplete,
11537
11648
  warnings
11538
11649
  };
11539
11650
  manifest.totals.redactedLines = secretFindings.length;
11540
11651
  manifest.totals.warningCount = manifest.warnings.length;
11541
- if (budgetOrderCutsFiles()) {
11542
- manifest.warnings.push(
11543
- `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.`
11544
- );
11545
- manifest.totals.warningCount = manifest.warnings.length;
11546
- }
11547
- if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
11652
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
11548
11653
  manifest.warnings.push(
11549
- `${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.`
11654
+ `${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.`
11550
11655
  );
11551
11656
  manifest.totals.warningCount = manifest.warnings.length;
11552
11657
  }
@@ -11840,6 +11945,7 @@ exports.PromptBack = PromptBack;
11840
11945
  exports.PromptCancelled = PromptCancelled;
11841
11946
  exports.REQUEST_TIMEOUT_MS = REQUEST_TIMEOUT_MS;
11842
11947
  exports.SCHEMA_VERSION = SCHEMA_VERSION;
11948
+ exports.UP_TO_DATE_INTERVAL_MS = UP_TO_DATE_INTERVAL_MS;
11843
11949
  exports.anchorForPath = anchorForPath;
11844
11950
  exports.appendGitignoreEntries = appendGitignoreEntries;
11845
11951
  exports.assertReplaceable = assertReplaceable;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SecretRule, D as DiscoveryMode, a as SkipRecord, J as JsonSummary, M as MarkdownSummary, b as SourceSummary, K as KindRule, L as LayerRule, R as ResolvedSnapshotConfig, c as SnapshotConfig, B as ByteSize, C as CliOptions, P as PartMetadata, F as FileEntry, T as TextEncoding, d as SecretFinding, V as ValidationResult, e as Manifest, A as ArtifactSelection } from './types-KbJvBjmV.cjs';
2
- export { f as BudgetConfig, H as HooksConfig, I as InclusionMode, g as ManifestArtifact, h as ManifestConfigSnapshot, i as ManifestIndexes, j as ManifestTotals, k as Mode, O as OutputFormat, l as PartFileEntry, m as ResolvedArtifacts, n as ResolvedBudgets, o as SecretRuleInput, p as SkipReason, q as SummaryQuality, r as ValidationDrift } from './types-KbJvBjmV.cjs';
1
+ import { S as SecretRule, D as DiscoveryMode, a as SkipRecord, J as JsonSummary, M as MarkdownSummary, b as SourceSummary, K as KindRule, L as LayerRule, R as ResolvedSnapshotConfig, c as SnapshotConfig, B as ByteSize, C as CliOptions, P as PartMetadata, F as FileEntry, T as TextEncoding, d as SecretFinding, V as ValidationResult, e as Manifest, A as ArtifactSelection } from './types-Z471HW65.cjs';
2
+ export { f as BudgetConfig, H as HooksConfig, I as InclusionMode, g as IncompleteFile, h as ManifestArtifact, i as ManifestConfigSnapshot, j as ManifestIndexes, k as ManifestTotals, l as Mode, O as OutputFormat, m as PartFileEntry, n as ResolvedArtifacts, o as ResolvedBudgets, p as SecretRuleInput, q as SkipReason, r as SummaryQuality, s as TruncationReason, t as ValidationDrift } from './types-Z471HW65.cjs';
3
3
  export { w as workerEntry } from './generate-worker-D_mUjgXw.cjs';
4
4
 
5
5
  interface GitInfo {
@@ -337,6 +337,14 @@ interface PreviewResult {
337
337
  isTruncated: boolean;
338
338
  originalLines: number;
339
339
  includedLines: number;
340
+ /**
341
+ * 1-based, inclusive source line ranges the preview does not contain.
342
+ *
343
+ * Empty when nothing was dropped. A head/tail preview drops exactly one contiguous run, so a
344
+ * reader can say which lines are missing instead of inferring it from a sentence in the middle
345
+ * of a part.
346
+ */
347
+ omittedRanges: Array<[number, number]>;
340
348
  }
341
349
  /**
342
350
  * Line count with one consistent convention: a trailing newline does not start
@@ -520,7 +528,7 @@ declare function validateSnapshot(configInput: ResolvedSnapshotConfig | Snapshot
520
528
  * `package.json` carries the same version; `npm run verify` compares the two.
521
529
  */
522
530
  declare const GENERATOR_NAME = "codebase-snapshot";
523
- declare const GENERATOR_VERSION = "0.9.17";
531
+ declare const GENERATOR_VERSION = "0.10.0";
524
532
  /**
525
533
  * The manifest and ownership-marker schema this build writes and understands.
526
534
  *
@@ -532,8 +540,16 @@ declare const SCHEMA_VERSION = "3.0.0";
532
540
 
533
541
  /** The one endpoint this package will ever request. */
534
542
  declare const PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
535
- /** A result younger than this is trusted without asking again. */
543
+ /** A result naming a newer release is trusted for a day: the upgrade command cannot change. */
536
544
  declare const CHECK_INTERVAL_MS: number;
545
+ /**
546
+ * How long "you are already current" is trusted.
547
+ *
548
+ * That is the only answer a new release can invalidate. Re-asking it hourly means an active run
549
+ * notices a release within the hour, while a cached upgrade keeps the daily interval: the notice
550
+ * is already known and a second request would buy nothing.
551
+ */
552
+ declare const UP_TO_DATE_INTERVAL_MS: number;
537
553
  /**
538
554
  * How long a *failed* check is remembered.
539
555
  *
@@ -1296,4 +1312,4 @@ declare function generateSnapshot(configInput?: SnapshotConfig | ResolvedSnapsho
1296
1312
  /** Promise-returning wrapper for consumers that prefer an async call site. */
1297
1313
  declare function generateSnapshotAsync(configInput?: SnapshotConfig | ResolvedSnapshotConfig | null, options?: GenerateOptions): Promise<Manifest>;
1298
1314
 
1299
- export { ARTIFACT_NAMES, ArtifactSelection, ByteSize, CHECK_INTERVAL_MS, CONFIG_KEYS, type ChangedScope, type ChangedScopeRequest, CliOptions, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, DiscoveryMode, type ExplainResult, FAILURE_INTERVAL_MS, FileEntry, type FirstRunFacts, type FirstRunPlan, type FirstRunRefusal, GENERATOR_NAME, GENERATOR_VERSION, type GenerateOptions, HOOK_MARKER, type HeuristicResult, type HookInstallResult, type ImportCandidate, type ImportResolver, type InitDependency, type InitOptions, type InitResult, type InstallKind, JsonSummary, KindRule, LANGUAGE_PROFILES, type LanguageProfile, LayerRule, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, Manifest, type ManifestDiff, MarkdownSummary, PACKAGE_LATEST_URL, PRESETS, PartMetadata, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, ResolvedSnapshotConfig, SCHEMA_VERSION, SecretFinding, SecretRule, SkipRecord, SnapshotConfig, SourceSummary, TextEncoding, type UpdateCheckOptions, type UpdateNotice, ValidationResult, type WizardAnswers, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defineConfig, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findSecretInPath, firstRunMessage, formatTokens, formatUpdateNotice, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, tsconfigPathsFor, updateCommand, validateSnapshot, wrapLines };
1315
+ export { ARTIFACT_NAMES, ArtifactSelection, ByteSize, CHECK_INTERVAL_MS, CONFIG_KEYS, type ChangedScope, type ChangedScopeRequest, CliOptions, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, DiscoveryMode, type ExplainResult, FAILURE_INTERVAL_MS, FileEntry, type FirstRunFacts, type FirstRunPlan, type FirstRunRefusal, GENERATOR_NAME, GENERATOR_VERSION, type GenerateOptions, HOOK_MARKER, type HeuristicResult, type HookInstallResult, type ImportCandidate, type ImportResolver, type InitDependency, type InitOptions, type InitResult, type InstallKind, JsonSummary, KindRule, LANGUAGE_PROFILES, type LanguageProfile, LayerRule, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, Manifest, type ManifestDiff, MarkdownSummary, PACKAGE_LATEST_URL, PRESETS, PartMetadata, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, ResolvedSnapshotConfig, SCHEMA_VERSION, SecretFinding, SecretRule, SkipRecord, SnapshotConfig, SourceSummary, TextEncoding, UP_TO_DATE_INTERVAL_MS, type UpdateCheckOptions, type UpdateNotice, ValidationResult, type WizardAnswers, anchorForPath, appendGitignoreEntries, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, decodeText, defineConfig, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findSecretInPath, firstRunMessage, formatTokens, formatUpdateNotice, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isEffectivelyEmpty, isInteractive, isNewer, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, truncatePreview, truncateToBytes, tsconfigPathsFor, updateCommand, validateSnapshot, wrapLines };