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.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { O as OutputFormat, D as DiscoveryMode, R as ResolvedSnapshotConfig } from './types-KbJvBjmV.cjs';
1
+ import { O as OutputFormat, D as DiscoveryMode, R as ResolvedSnapshotConfig } from './types-Z471HW65.cjs';
2
2
 
3
3
  /**
4
4
  * The machine-readable description of this tool.
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { O as OutputFormat, D as DiscoveryMode, R as ResolvedSnapshotConfig } from './types-KbJvBjmV.js';
1
+ import { O as OutputFormat, D as DiscoveryMode, R as ResolvedSnapshotConfig } from './types-Z471HW65.js';
2
2
 
3
3
  /**
4
4
  * The machine-readable description of this tool.
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
- import { buildAgentContract, runStdioServer, COMMAND_OPTION_SCOPE, commandsForOption, SKILL_NAME, renderSkill, renderContractText } from './chunk-XAW5GY6X.js';
2
- export { buildAgentContract } from './chunk-XAW5GY6X.js';
3
- import { shouldCheck, checkForUpdate, GENERATOR_VERSION, cacheFilePath, formatUpdateNotice, installKind, loadConfigFileDetailed, resolveConfig, validateSnapshot, describeManifestShapeProblem, explainPath, compareManifests, loadManifest, renderDiffText, generateSnapshot, formatNumber, isDiscoveryMode, ARTIFACT_NAMES, getPreset, unknownPresetMessage, GENERATOR_NAME, runInit, installPreCommitHook, PromptCancelled, findConfigFile, planFirstRun, isEffectivelyEmpty, isInteractive, defaultIO, hasPriorSnapshot, DEFAULT_ANSWERS, firstRunMessage, parseByteSize, stripJsonComments, gitignorePath, appendGitignoreEntries, runWithStdoutCapture, escapeControls, MIN_MAX_PART_TOKENS, MIN_MAX_PART_BYTES, renderExplainText } from './chunk-ZXWAVHSZ.js';
1
+ import { buildAgentContract, runStdioServer, COMMAND_OPTION_SCOPE, commandsForOption, SKILL_NAME, renderSkill, renderContractText } from './chunk-4H7MSW64.js';
2
+ export { buildAgentContract } from './chunk-4H7MSW64.js';
3
+ import { shouldCheck, checkForUpdate, GENERATOR_VERSION, cacheFilePath, formatUpdateNotice, installKind, loadConfigFileDetailed, resolveConfig, validateSnapshot, describeManifestShapeProblem, explainPath, compareManifests, loadManifest, renderDiffText, generateSnapshot, formatNumber, isDiscoveryMode, ARTIFACT_NAMES, getPreset, unknownPresetMessage, GENERATOR_NAME, runInit, installPreCommitHook, PromptCancelled, findConfigFile, planFirstRun, isEffectivelyEmpty, isInteractive, defaultIO, hasPriorSnapshot, DEFAULT_ANSWERS, firstRunMessage, parseByteSize, stripJsonComments, gitignorePath, appendGitignoreEntries, runWithStdoutCapture, escapeControls, MIN_MAX_PART_TOKENS, MIN_MAX_PART_BYTES, renderExplainText } from './chunk-EP7OCPUM.js';
4
4
  import { spawnSync } from 'child_process';
5
5
  import * as fs from 'fs';
6
6
  import * as path2 from 'path';
@@ -640,6 +640,17 @@ async function runInitCommand(invocation) {
640
640
  return fail(invocation.format, err.message);
641
641
  }
642
642
  }
643
+ function generatorOrigin(cwd) {
644
+ try {
645
+ const pkg = JSON.parse(fs.readFileSync(path2.join(cwd, "package.json"), "utf8"));
646
+ const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
647
+ if (typeof spec === "string") return `project dependency ${spec}`;
648
+ } catch {
649
+ }
650
+ const entry = process.argv[1] ?? "";
651
+ if (entry.includes("_npx") || entry.includes(`${path2.sep}npx${path2.sep}`)) return "via npx";
652
+ return "global or direct install";
653
+ }
643
654
  function detectPackageManager(cwd) {
644
655
  const has = (name) => fs.existsSync(path2.join(cwd, name));
645
656
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
@@ -787,9 +798,14 @@ async function runSetupCommand(invocation, options = {}) {
787
798
  info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
788
799
  }
789
800
  }
801
+ const hasManifest = fs.existsSync(path2.join(invocation.cwd, "package.json"));
790
802
  let install = null;
791
803
  if (invocation.noInstall) {
792
804
  if (invocation.format !== "json") info(" Skipped the install (--no-install)");
805
+ } else if (!hasManifest) {
806
+ if (invocation.format !== "json") {
807
+ info(" Skipped the install: no package.json here, so there is no dependency to add.");
808
+ }
793
809
  } else {
794
810
  if (invocation.format !== "json") info("\u23F3 Installing dependencies\u2026");
795
811
  install = installDependencies(invocation.cwd);
@@ -1142,7 +1158,7 @@ ${USAGE}
1142
1158
  const started = performance.now();
1143
1159
  info(`\u{1F4F8} ${invocation.dryRun ? "Planning snapshot (dry run)" : "Generating snapshot"} for: ${resolved.cwd}`);
1144
1160
  info(
1145
- ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB`
1161
+ ` Branch: ${resolved.branch} | Part budget: ${(resolved.maxPartBytes / 1024).toFixed(0)} KB | Generator: ${GENERATOR_VERSION} (${generatorOrigin(resolved.cwd)})`
1146
1162
  );
1147
1163
  try {
1148
1164
  const manifest = generateSnapshot(resolved, { dryRun: invocation.dryRun });
@@ -1160,12 +1176,31 @@ ${USAGE}
1160
1176
  ` - Redacted: ${manifest.totals.redactedLines} line(s) \u2014 a real run lists them in ` + displayOutPath(resolved.cwd, resolved.outDir, "reports/audit.md")
1161
1177
  );
1162
1178
  }
1179
+ const incomplete = manifest.incomplete ?? [];
1180
+ if (incomplete.length > 0) {
1181
+ const byReason = /* @__PURE__ */ new Map();
1182
+ for (const record of incomplete) {
1183
+ byReason.set(record.reason, (byReason.get(record.reason) ?? 0) + 1);
1184
+ }
1185
+ const detail = [...byReason.entries()].map(([reason, count]) => `${count} ${reason}`).join(", ");
1186
+ info(` - Incomplete: ${incomplete.length} file(s) \u2014 ${detail}; see manifest.json incomplete[]`);
1187
+ }
1163
1188
  info(` - Integrity: ${manifest.validation.status}`);
1164
1189
  for (const error of manifest.validation.errors.slice(0, 10)) info(` - ${error}`);
1165
1190
  } else {
1166
1191
  info(`
1167
1192
  \u2705 Snapshot generated in ${elapsed}s:`);
1168
- info(` - Tracked files: ${manifest.counts.totalFiles}`);
1193
+ const skipCounts = /* @__PURE__ */ new Map();
1194
+ for (const record of manifest.skipped) {
1195
+ skipCounts.set(record.reason, (skipCounts.get(record.reason) ?? 0) + 1);
1196
+ }
1197
+ const skipBreakdown = [...skipCounts.entries()].sort((left, right) => right[1] - left[1]).map(([reason, count]) => `${reason} ${formatNumber(count)}`);
1198
+ const shownReasons = skipBreakdown.slice(0, 3);
1199
+ const reasons = skipBreakdown.length > shownReasons.length ? `${shownReasons.join(", ")}, +${skipBreakdown.length - shownReasons.length} more` : shownReasons.join(", ");
1200
+ const candidates = manifest.counts.totalFiles + manifest.counts.skippedCount;
1201
+ info(
1202
+ 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")}`
1203
+ );
1169
1204
  info(` - Total lines: ${formatNumber(manifest.counts.totalLines)}`);
1170
1205
  info(
1171
1206
  ` - Total size: ${(manifest.counts.totalSizeBytes / (1024 * 1024)).toFixed(2)} MB`
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.18";
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
  "",
@@ -8871,7 +8893,9 @@ function renderConfig(answers) {
8871
8893
  // The same ceiling expressed in tokens; it narrows maxPartBytes rather than
8872
8894
  // replacing it. null = not set. Minimum 1024.
8873
8895
  maxPartTokens: ${answers.maxPartTokens === null ? "null" : String(answers.maxPartTokens)},
8874
- // 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.
8875
8899
  largeFileBytes: ${size(answers.largeFileBytes)},
8876
8900
  previewHeadLines: 80,
8877
8901
  previewTailLines: 40,
@@ -9556,6 +9580,9 @@ async function runInit(options) {
9556
9580
  let reason = detected.reason;
9557
9581
  let fallback = detected.fallback;
9558
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);
9559
9586
  const answers = {
9560
9587
  preset: detected.presetName,
9561
9588
  // The repository's own branch, read the same way the generator reads it.
@@ -9569,7 +9596,13 @@ async function runInit(options) {
9569
9596
  // what the run used is drift the next `validate` reports, and `setup` is the one command
9570
9597
  // that is supposed to leave a project in a consistent state.
9571
9598
  maxPartTokens: options.maxPartTokens ?? DEFAULT_ANSWERS.maxPartTokens,
9572
- 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
+ ),
9573
9606
  maxMonolithBytes: options.maxMonolithBytes ?? DEFAULT_ANSWERS.maxMonolithBytes,
9574
9607
  discovery: options.discovery ?? DEFAULT_ANSWERS.discovery,
9575
9608
  skeleton: options.skeleton ?? DEFAULT_ANSWERS.skeleton,
@@ -10098,6 +10131,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10098
10131
  const oversizeForSummary = Buffer.byteLength(rawContent, "utf8") > SUMMARY_MAX_SOURCE_BYTES2;
10099
10132
  let finalContent = redacted;
10100
10133
  let isPreviewTruncated = false;
10134
+ let truncationReason;
10135
+ let omittedRanges = [];
10101
10136
  let includedLines = lineCount;
10102
10137
  let inclusionMode = "full";
10103
10138
  if (config.skeleton === true && isSkeletonizable(relativePath) && !oversizeForSummary) {
@@ -10114,6 +10149,10 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10114
10149
  isPreviewTruncated = preview.isTruncated;
10115
10150
  includedLines = preview.includedLines;
10116
10151
  inclusionMode = isPreviewTruncated ? "preview" : "full";
10152
+ if (isPreviewTruncated) {
10153
+ truncationReason = "large-file-budget";
10154
+ omittedRanges = preview.omittedRanges;
10155
+ }
10117
10156
  }
10118
10157
  let summary;
10119
10158
  let summaryQuality;
@@ -10148,6 +10187,8 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
10148
10187
  finalContent,
10149
10188
  inclusionMode,
10150
10189
  isPreviewTruncated,
10190
+ truncationReason,
10191
+ omittedRanges,
10151
10192
  includedLines,
10152
10193
  isLarge,
10153
10194
  summary,
@@ -10257,8 +10298,30 @@ function buildIndexes(files, tsconfigPaths) {
10257
10298
  }))
10258
10299
  };
10259
10300
  }
10260
- function verifyInMemory(files, parts) {
10301
+ function verifyInMemory(files, parts, unaccounted) {
10261
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
+ }
10262
10325
  const partNames = new Set(parts.map((part) => part.filename));
10263
10326
  for (const file of files) {
10264
10327
  if (!file.part || !partNames.has(file.part)) {
@@ -11009,7 +11072,20 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11009
11072
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
11010
11073
  const hadPrevious = fs15__namespace.existsSync(outDir);
11011
11074
  if (hadPrevious) beforeSwap?.();
11012
- 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
+ }
11013
11089
  try {
11014
11090
  try {
11015
11091
  fs15__namespace.renameSync(stagingDir, outDir);
@@ -11029,9 +11105,14 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11029
11105
  }
11030
11106
  }
11031
11107
  } catch (err) {
11032
- if (hadPrevious && fs15__namespace.existsSync(backupDir)) {
11108
+ if (hadPrevious && movedAside && fs15__namespace.existsSync(backupDir)) {
11033
11109
  if (fs15__namespace.existsSync(outDir)) fs15__namespace.rmSync(outDir, { recursive: true, force: true });
11034
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
+ );
11035
11116
  }
11036
11117
  throw err;
11037
11118
  }
@@ -11046,6 +11127,10 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
11046
11127
  }
11047
11128
  }
11048
11129
  }
11130
+ function isLockError(err) {
11131
+ const code = err.code;
11132
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
11133
+ }
11049
11134
  function sleepSync(milliseconds) {
11050
11135
  const buffer = new Int32Array(new SharedArrayBuffer(4));
11051
11136
  Atomics.wait(buffer, 0, 0, milliseconds);
@@ -11149,10 +11234,6 @@ function generateSnapshot(configInput, options) {
11149
11234
  const skipped = maskSkipRecords([...collection.skipped], config.secretRules);
11150
11235
  const secretFindings = [];
11151
11236
  const warnings = [];
11152
- const budgetOrderCutsFiles = () => {
11153
- if (config.maxPartBytes >= config.largeFileBytes) return false;
11154
- return files.some((file) => file.isPreviewTruncated && !file.isLarge);
11155
- };
11156
11237
  const encodingNotes = [];
11157
11238
  const fileWarnings = [];
11158
11239
  const oversizeSummaryPaths = [];
@@ -11314,11 +11395,16 @@ function generateSnapshot(configInput, options) {
11314
11395
  inclusionMode: derivation.inclusionMode,
11315
11396
  isLarge: derivation.isLarge,
11316
11397
  isPreviewTruncated: derivation.isPreviewTruncated,
11398
+ ...derivation.truncationReason === void 0 ? {} : { truncationReason: derivation.truncationReason },
11399
+ ...derivation.omittedRanges.length === 0 ? {} : { omittedRanges: derivation.omittedRanges },
11317
11400
  originalLines: lineCount,
11318
11401
  includedLines: derivation.includedLines,
11319
11402
  includedBytes: Buffer.byteLength(derivation.finalContent, "utf8"),
11320
11403
  summary: derivation.summary,
11321
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 },
11322
11408
  ...decoded.encoding === "utf-8" ? {} : { encoding: decoded.encoding },
11323
11409
  content: derivation.finalContent
11324
11410
  });
@@ -11438,7 +11524,28 @@ function generateSnapshot(configInput, options) {
11438
11524
  }
11439
11525
  const parts = partitionByBudget(files, config, fingerprint);
11440
11526
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11441
- 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);
11442
11549
  const totalContentBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11443
11550
  const maskName = (value) => maskPathText(value, config.secretRules);
11444
11551
  const manifest = {
@@ -11499,7 +11606,8 @@ function generateSnapshot(configInput, options) {
11499
11606
  partsCount: parts.length,
11500
11607
  skippedCount: skipped.length,
11501
11608
  largeFileCount,
11502
- truncatedPreviewCount
11609
+ truncatedPreviewCount,
11610
+ incompleteCount: incomplete.length
11503
11611
  },
11504
11612
  totals: {
11505
11613
  candidateFiles: files.length + skipped.length,
@@ -11536,19 +11644,14 @@ function generateSnapshot(configInput, options) {
11536
11644
  return rest;
11537
11645
  }),
11538
11646
  skipped: maskSkipRecords(skipped, config.secretRules),
11647
+ incomplete,
11539
11648
  warnings
11540
11649
  };
11541
11650
  manifest.totals.redactedLines = secretFindings.length;
11542
11651
  manifest.totals.warningCount = manifest.warnings.length;
11543
- if (budgetOrderCutsFiles()) {
11544
- manifest.warnings.push(
11545
- `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.`
11546
- );
11547
- manifest.totals.warningCount = manifest.warnings.length;
11548
- }
11549
- if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes <= config.maxPartBytes) {
11652
+ if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
11550
11653
  manifest.warnings.push(
11551
- `${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.`
11552
11655
  );
11553
11656
  manifest.totals.warningCount = manifest.warnings.length;
11554
11657
  }