codebase-snapshot 0.10.2 → 0.11.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.
@@ -3906,7 +3906,7 @@ function applySpansKeepingQuotes(line, spans) {
3906
3906
 
3907
3907
  // src/version.ts
3908
3908
  var GENERATOR_NAME = "codebase-snapshot";
3909
- var GENERATOR_VERSION = "0.10.2";
3909
+ var GENERATOR_VERSION = "0.11.0";
3910
3910
  var SCHEMA_VERSION = "3.0.0";
3911
3911
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
3912
3912
  function isOurGeneratorName(name) {
@@ -4354,6 +4354,23 @@ function defaultIgnoreReason(relativePath, toolDirNames = DEFAULT_TOOL_DIR_NAMES
4354
4354
  }
4355
4355
  return null;
4356
4356
  }
4357
+ function recentCommitSubjects(cwd, limit = 10) {
4358
+ try {
4359
+ const stdout = childProcess.execFileSync(
4360
+ "git",
4361
+ ["log", "-n", String(limit), "--pretty=%s", "--no-color"],
4362
+ {
4363
+ cwd,
4364
+ stdio: ["ignore", "pipe", "ignore"],
4365
+ encoding: "utf8",
4366
+ maxBuffer: GIT_OUTPUT_LIMIT
4367
+ }
4368
+ );
4369
+ return stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
4370
+ } catch {
4371
+ return [];
4372
+ }
4373
+ }
4357
4374
  function listIgnoredPaths(cwd) {
4358
4375
  try {
4359
4376
  const stdout = childProcess.execFileSync(
@@ -4900,6 +4917,10 @@ function normalizeResolvedConfig(config) {
4900
4917
  return markResolvedConfig({
4901
4918
  ...config,
4902
4919
  discovery,
4920
+ // A spread copy built before the field existed carries no value; the default applies, and it
4921
+ // is re-validated because the number reaches a rendered artifact.
4922
+ attachmentSlots: resolveAttachmentSlots(config.attachmentSlots),
4923
+ maxParts: resolveMaxParts(config.maxParts),
4903
4924
  includeMonolith: artifacts.monolith,
4904
4925
  secretRules: compileSecretRules(config.secretRules),
4905
4926
  artifacts,
@@ -4968,6 +4989,7 @@ function describeValue2(value) {
4968
4989
  var isThenable = (value) => typeof value.then === "function";
4969
4990
  var CONFIG_KEY_NAMES = [
4970
4991
  "artifacts",
4992
+ "attachmentSlots",
4971
4993
  "branch",
4972
4994
  "budgets",
4973
4995
  "changedSince",
@@ -4985,6 +5007,7 @@ var CONFIG_KEY_NAMES = [
4985
5007
  "layersMode",
4986
5008
  "maxMonolithBytes",
4987
5009
  "maxPartBytes",
5010
+ "maxParts",
4988
5011
  "maxPartTokens",
4989
5012
  "outDir",
4990
5013
  "preset",
@@ -5190,6 +5213,7 @@ var MIN_MAX_PART_BYTES = 4096;
5190
5213
  var MIN_MAX_PART_TOKENS = MIN_MAX_PART_BYTES / 4;
5191
5214
  var ARTIFACT_NAMES = [
5192
5215
  "readme",
5216
+ "prompt",
5193
5217
  "manifest",
5194
5218
  "parts",
5195
5219
  "navigation",
@@ -5199,6 +5223,7 @@ var ARTIFACT_NAMES = [
5199
5223
  ];
5200
5224
  var DEFAULT_ARTIFACTS = {
5201
5225
  readme: true,
5226
+ prompt: true,
5202
5227
  manifest: true,
5203
5228
  parts: true,
5204
5229
  navigation: true,
@@ -5259,6 +5284,25 @@ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride,
5259
5284
  }
5260
5285
  return artifacts;
5261
5286
  }
5287
+ var DEFAULT_ATTACHMENT_SLOTS = 10;
5288
+ function resolveAttachmentSlots(value) {
5289
+ if (value === void 0 || value === null) return DEFAULT_ATTACHMENT_SLOTS;
5290
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
5291
+ throw new Error(
5292
+ "attachmentSlots must be a whole number, with 0 meaning no limit (received " + describeValue2(value) + ")."
5293
+ );
5294
+ }
5295
+ return value;
5296
+ }
5297
+ function resolveMaxParts(value) {
5298
+ if (value === void 0 || value === null) return null;
5299
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
5300
+ throw new Error(
5301
+ "maxParts must be a whole number of parts, or null to disable it (received " + describeValue2(value) + ")."
5302
+ );
5303
+ }
5304
+ return value;
5305
+ }
5262
5306
  function strictPositiveInteger(value, fallback, label) {
5263
5307
  if (value === void 0) return fallback;
5264
5308
  if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
@@ -5637,6 +5681,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
5637
5681
  "maxMonolithBytes"
5638
5682
  ),
5639
5683
  includeSensitiveFiles,
5684
+ attachmentSlots: resolveAttachmentSlots(
5685
+ cliOptions?.attachmentSlots ?? userConfig?.attachmentSlots
5686
+ ),
5687
+ maxParts: resolveMaxParts(cliOptions?.maxParts ?? userConfig?.maxParts),
5640
5688
  ...changedSince === void 0 ? {} : { changedSince },
5641
5689
  ...staged ? { staged } : {},
5642
5690
  ...withDependents ? { withDependents } : {},
@@ -5719,6 +5767,9 @@ function configDigest(config) {
5719
5767
  includeMonolith: config.includeMonolith,
5720
5768
  maxMonolithBytes: config.maxMonolithBytes ?? null,
5721
5769
  includeSensitiveFiles: config.includeSensitiveFiles,
5770
+ // Only when the experimental mode is on: `null` is the off switch, and writing it into the
5771
+ // material would change the digest of every snapshot taken before the setting existed.
5772
+ ...config.maxParts === null ? {} : { maxParts: config.maxParts },
5722
5773
  artifacts: config.artifacts,
5723
5774
  include: config.include,
5724
5775
  excludePatterns: config.excludePatterns,
@@ -6678,10 +6729,420 @@ function generateNavigation(manifest) {
6678
6729
  return lines.join("\n");
6679
6730
  }
6680
6731
 
6732
+ // src/generator/prompt.ts
6733
+ var MAX_PART_ROWS = 16;
6734
+ var MAX_LAYER_ROWS = 8;
6735
+ var MAX_INCOMPLETE_ROWS = 50;
6736
+ var MAX_CENTRAL_FILES = 5;
6737
+ var MAX_ENTRY_POINTS = 4;
6738
+ var MAX_LARGEST_FILES = 3;
6739
+ var partWord = (count) => count === 1 ? "part" : "parts";
6740
+ var UNLIMITED_SLOTS = 0;
6741
+ var ENTRY_POINT = /(^|\/)(index|cli|main|bin|server|app|mod)\.[cm]?[jt]sx?$/;
6742
+ var TEST_PATH = /(^|\/)(tests?|__tests__)\//;
6743
+ var TEST_FILE = /\.(test|spec)\.[^.]+$/;
6744
+ function generatePrompt(manifest, artifacts, attachmentSlots = DEFAULT_ATTACHMENT_SLOTS, history = []) {
6745
+ const wrote = (name) => artifacts?.[name] !== false;
6746
+ const code = (value) => inlineCode(escapeControls(value));
6747
+ const lines = [
6748
+ "# PROMPT.md",
6749
+ "",
6750
+ "The brief and the apparatus for this snapshot. Paste this file first, then the parts it names.",
6751
+ "",
6752
+ "It is generated rather than written once: the system map, the omissions, the fingerprint and",
6753
+ "the history below are read from `manifest.json` and this repository, so they describe this run.",
6754
+ "Regenerate it after the code moves.",
6755
+ "",
6756
+ "---",
6757
+ "",
6758
+ "```text",
6759
+ "You are working on a codebase you cannot clone, run or grep. Everything you know about it comes",
6760
+ "from the snapshot that follows this instruction. Where these notes and the snapshot disagree,",
6761
+ "the snapshot is what exists.",
6762
+ "",
6763
+ "## The job",
6764
+ "",
6765
+ "Find what is still wrong or will break. How you read the code is yours to decide - by",
6766
+ "subsystem, by data flow, by the invariants you derive yourself. What you owe in return is an",
6767
+ "honest account of what you covered and what you did not.",
6768
+ "",
6769
+ history.length > 0 ? "Another pass of the same findings is worth nothing. This repository carries a record of" : "Another pass of the same findings is worth nothing, but no earlier round is readable here,",
6770
+ history.length > 0 ? "what was already fixed, below. Verify that those fixes hold instead of rediscovering them," : "so you cannot tell what has already been tried. Do not assume this is the first attempt.",
6771
+ history.length > 0 ? "and treat a variant of one at a different call site as a new finding." : "Every finding you report has to stand on the code alone.",
6772
+ "",
6773
+ "If the task at the end asks for something narrower - explain a file, review a change, answer a",
6774
+ "question - that task wins. The standard and the coverage duty below still apply to it.",
6775
+ ""
6776
+ ];
6777
+ lines.push(...haveSection(wrote), "");
6778
+ lines.push(...systemSection(manifest, code), "");
6779
+ lines.push(...historySection(history), "");
6780
+ lines.push(...barSection(), "");
6781
+ lines.push(...coverageSection(manifest, code, wrote("audit")), "");
6782
+ lines.push(...answerSection(), "");
6783
+ lines.push(...calibrationSection(), "");
6784
+ lines.push(...snapshotSection(manifest, code), "");
6785
+ lines.push(...deliverySection(manifest, wrote("parts"), attachmentSlots));
6786
+ lines.push(
6787
+ "## Your task",
6788
+ "",
6789
+ "<replace with the question, the area to review, or the subsystem to audit>",
6790
+ "```"
6791
+ );
6792
+ lines.push(
6793
+ "",
6794
+ "---",
6795
+ "",
6796
+ "## Why this file exists",
6797
+ "",
6798
+ "Parts on their own are a dump: the model receives text, has no idea what was left out of it,",
6799
+ "and fills the gap by invention. A brief on its own is a wish list: it cannot say which files",
6800
+ "are present, which are partial or which part holds what. This file is both halves, and the",
6801
+ "facts in it move with the snapshot.",
6802
+ "",
6803
+ "## Keeping it true",
6804
+ "",
6805
+ "- It is one of the artifacts recorded in `manifest.json` under `artifacts.prompt`, so deleting",
6806
+ " or editing `PROMPT.md` makes `snapshot validate` fail.",
6807
+ "- `--skip-artifacts prompt`, or `artifacts: { prompt: false }` in the config, turns it off.",
6808
+ "- The history section disappears when git cannot be read, rather than being invented.",
6809
+ "- If the code moves, regenerate. A brief naming the previous run parts is worse than no",
6810
+ " brief, because it reads as current.",
6811
+ ""
6812
+ );
6813
+ return lines.join("\n");
6814
+ }
6815
+ function haveSection(wrote) {
6816
+ const out = ["## What you have", ""];
6817
+ const bullets = [];
6818
+ if (wrote("readme")) {
6819
+ bullets.push("- `README.md` - orientation: metrics, the part table, and the fingerprint.");
6820
+ }
6821
+ if (wrote("manifest")) {
6822
+ bullets.push(
6823
+ "- `manifest.json` - the index. Per file: `relativePath`, `layer`, `kind`, `language`,",
6824
+ " `part`, `sha256`, `inclusionMode`, `truncationReason`, `omittedRanges`. It also carries",
6825
+ " every excluded path under `skipped[]` with its reason, and `incomplete[]`, which names",
6826
+ " every included file whose emitted body is not the whole file."
6827
+ );
6828
+ }
6829
+ if (wrote("navigation")) {
6830
+ bullets.push("- `reports/navigation.md` - file to part. Locate here before you read anything.");
6831
+ }
6832
+ if (wrote("projectTree")) {
6833
+ bullets.push("- `reports/project-tree.md` - the directory shape of what was included.");
6834
+ }
6835
+ if (wrote("audit")) {
6836
+ bullets.push(
6837
+ "- `reports/audit.md` - secret findings, the files whose lines were redacted, large files,",
6838
+ " parse diagnostics and the git state the snapshot was taken from."
6839
+ );
6840
+ }
6841
+ if (wrote("parts")) {
6842
+ bullets.push(
6843
+ "- `parts/part-NNN.md` - the code itself, split to a fixed byte budget. Each part states its",
6844
+ " own number, the files it contains, and the fingerprint it was built from."
6845
+ );
6846
+ }
6847
+ if (wrote("monolith")) {
6848
+ bullets.push(
6849
+ "- `full-codebase.json` and `full-codebase.md` - the entire payload in one file each.",
6850
+ " Where they are present, they supersede the parts: nothing was left out of them."
6851
+ );
6852
+ }
6853
+ if (bullets.length === 0) {
6854
+ bullets.push(
6855
+ "- Nothing but this brief: every code artifact was disabled for this run. Ask for a snapshot",
6856
+ " generated with the artifacts you need, and do not answer from memory."
6857
+ );
6858
+ }
6859
+ out.push(...bullets);
6860
+ return out;
6861
+ }
6862
+ function systemSection(manifest, code) {
6863
+ const out = ["## The system", ""];
6864
+ const layers = Object.entries(manifest.layers).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
6865
+ if (layers.length > 0) {
6866
+ const shown = layers.slice(0, MAX_LAYER_ROWS).map(([name, count]) => code(name) + " " + formatNumber(count));
6867
+ const rest = layers.length > MAX_LAYER_ROWS ? ", and " + formatNumber(layers.length - MAX_LAYER_ROWS) + " more" : "";
6868
+ out.push("- Layers, by file count: " + shown.join(", ") + rest + ".");
6869
+ }
6870
+ const central = manifest.indexes.imports.centralFiles;
6871
+ if (central.length > 0) {
6872
+ const shown = central.slice(0, MAX_CENTRAL_FILES).map((entry) => code(entry.path) + " (" + formatNumber(entry.importedByCount) + ")").join(", ");
6873
+ out.push(
6874
+ "- Load-bearing modules, by how many files import them: " + shown + ".",
6875
+ " A change here reaches the most call sites; read it before judging anything that uses it."
6876
+ );
6877
+ }
6878
+ const entryPoints = manifest.files.map((file) => file.relativePath).filter((path17) => ENTRY_POINT.test(path17)).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length).slice(0, MAX_ENTRY_POINTS);
6879
+ out.push(
6880
+ entryPoints.length > 0 ? "- Entry points by convention: " + entryPoints.map(code).join(", ") + "." : "- No entry point was identifiable by name. The largest files below are where execution"
6881
+ );
6882
+ if (entryPoints.length === 0) out.push(" starts, and the call graph in `manifest.json` is the map.");
6883
+ const routes = manifest.indexes.routes.length;
6884
+ const handlers = manifest.indexes.handlers.length;
6885
+ const components = manifest.indexes.components.length;
6886
+ const routesShown = manifest.indexes.routes.slice(0, 4).map((route) => code(route.path));
6887
+ const componentsShown = manifest.indexes.components.slice(0, 4).map((entry) => code(entry.path));
6888
+ if (routes + handlers + components === 0) {
6889
+ out.push(
6890
+ "- No routes, handlers or UI components were recorded: this snapshot indexes no HTTP or",
6891
+ " component surface. Do not go looking for one, and do not infer one from a file name."
6892
+ );
6893
+ } else {
6894
+ const parts = [];
6895
+ if (routes > 0) parts.push(formatNumber(routes) + " route(s), e.g. " + routesShown.join(", "));
6896
+ if (handlers > 0) parts.push(formatNumber(handlers) + " handler(s)");
6897
+ if (components > 0) parts.push(formatNumber(components) + " component(s), e.g. " + componentsShown.join(", "));
6898
+ out.push("- Surfaces the index found: " + parts.join("; ") + ".");
6899
+ }
6900
+ const largest = [...manifest.files].sort((a, b) => b.includedBytes - a.includedBytes).slice(0, MAX_LARGEST_FILES);
6901
+ if (largest.length > 0) {
6902
+ out.push(
6903
+ "- Largest files: " + largest.map((file) => code(file.relativePath) + " (" + formatNumber(Math.round(file.includedBytes / 1024)) + " KB)").join(", ") + "."
6904
+ );
6905
+ }
6906
+ const tests = manifest.files.filter(
6907
+ (file) => TEST_PATH.test(file.relativePath) || TEST_FILE.test(file.relativePath)
6908
+ );
6909
+ if (tests.length > 0) {
6910
+ const testBytes = tests.reduce((total, file) => total + file.includedBytes, 0);
6911
+ const allBytes = manifest.files.reduce((total, file) => total + file.includedBytes, 0);
6912
+ const share = allBytes === 0 ? 0 : Math.round(testBytes / allBytes * 100);
6913
+ out.push(
6914
+ "- Tests: " + formatNumber(tests.length) + " file(s), " + share + "% of the included bytes.",
6915
+ " They are evidence of intent, not of behaviour: a fixture can encode a payload shape the",
6916
+ " real system never sends."
6917
+ );
6918
+ }
6919
+ return out;
6920
+ }
6921
+ function historySection(history) {
6922
+ const out = ["## What came before", ""];
6923
+ if (history.length === 0) {
6924
+ out.push(
6925
+ "No history was readable: this is not a git checkout, or git could not be run. Nothing about",
6926
+ "what came before can be claimed from here, and that is not evidence that the code is new."
6927
+ );
6928
+ return out;
6929
+ }
6930
+ out.push(
6931
+ "Commit subjects, newest first. They are claims by whoever wrote them, not evidence - the code",
6932
+ "beside them is the evidence. If one of these fixes looks incomplete, quote the lines and say",
6933
+ "which call site it missed.",
6934
+ ""
6935
+ );
6936
+ for (const subject of history) out.push("- " + subject);
6937
+ return out;
6938
+ }
6939
+ function barSection() {
6940
+ return [
6941
+ "## The bar",
6942
+ "",
6943
+ "A finding is a concrete way the code breaks or lies, supported by quoted lines: the path and",
6944
+ "line, the input or state that reaches it, what happens next, and why the guard that appears to",
6945
+ "stop it does not. A comment is not behaviour. A passing test is evidence of intent, not of",
6946
+ "behaviour.",
6947
+ "",
6948
+ "- No style, naming, formatting, add-types, add-tests, consider-X or speculative rewrites.",
6949
+ "- Never invent a finding to fill a section. A clean surface is proven by quoting the guard",
6950
+ " that makes it clean.",
6951
+ "- Mark confidence, and name the check - a test, a run, an input - that would settle anything",
6952
+ " you cannot decide by reading.",
6953
+ "- Separate what the code does from what the deployment or configuration does. Both are",
6954
+ " findings; they have different owners and different fixes."
6955
+ ];
6956
+ }
6957
+ function coverageSection(manifest, code, auditWritten) {
6958
+ const out = ["## Coverage", ""];
6959
+ const reasons = /* @__PURE__ */ new Map();
6960
+ for (const record of manifest.skipped) {
6961
+ reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
6962
+ }
6963
+ const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
6964
+ out.push(
6965
+ "- " + formatNumber(manifest.totals.candidateFiles) + " path(s) were found; " + formatNumber(manifest.totals.includedFiles) + " are in the parts and " + formatNumber(manifest.counts.skippedCount) + " were skipped" + (tally.length > 0 ? " (" + tally + ")" : "") + ".",
6966
+ " `manifest.skipped[]` names each one and why. An absent path is not a clean path."
6967
+ );
6968
+ out.push(...incompleteSection(manifest, code));
6969
+ out.push(...redactionSection(manifest, auditWritten));
6970
+ out.push(
6971
+ "- Everything unseen is unread, never clean. If you were given only some of the parts, say",
6972
+ " which ones are missing before you answer. A file the index names but the parts do not carry",
6973
+ " is an input defect, not a code finding - report it as one."
6974
+ );
6975
+ return out;
6976
+ }
6977
+ function answerSection() {
6978
+ return [
6979
+ "## What a useful answer contains",
6980
+ "",
6981
+ "- An opening line, filled from This snapshot below:",
6982
+ "",
6983
+ " snapshot <fingerprint> generated <generatedAt>",
6984
+ "",
6985
+ "- What you read and what you did not, named by path or by part.",
6986
+ "- Findings ordered by consequence, each with the lines quoted.",
6987
+ "- The checks or attacks that failed, and the line or guard that blocked them. A failed attack",
6988
+ " is how anyone knows an invariant is real rather than asserted.",
6989
+ "- What you retracted after re-reading.",
6990
+ "- What only a run, a test or a host can settle, and the check that would settle each.",
6991
+ "- One paragraph on the failure you would bet on next.",
6992
+ "- A closing line: Needed but not received: <paths>, or none. That line is not decoration -",
6993
+ " an invented function is indistinguishable from a real one, and this is where you name",
6994
+ " the gap you filled by asking instead of guessing."
6995
+ ];
6996
+ }
6997
+ function calibrationSection() {
6998
+ return [
6999
+ "## Calibration",
7000
+ "",
7001
+ "The findings that matter here do not crash. They look like:",
7002
+ "",
7003
+ "- a guard applied at one call site and not its twin - the route checks, the timer does not;",
7004
+ "- a budget shorter than the work it guards, so the caller gives up while the work continues;",
7005
+ "- a success flag that means the call returned, consumed as the change happened;",
7006
+ "- a document that describes a different run than the one beside it;",
7007
+ "- a default that fabricates a number when the measurement failed.",
7008
+ "",
7009
+ "None of these throw. All are invisible in a summary."
7010
+ ];
7011
+ }
7012
+ function snapshotSection(manifest, code) {
7013
+ const out = ["## This snapshot", ""];
7014
+ out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
7015
+ out.push(
7016
+ "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
7017
+ );
7018
+ out.push(
7019
+ manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
7020
+ );
7021
+ out.push(
7022
+ "- Validation: `manifest.validation.status` was " + code(manifest.validation.status) + " at generation time.",
7023
+ " That describes the run, not now: if the tree may have moved since, the snapshot is a",
7024
+ " claim that needs re-checking, not a fact."
7025
+ );
7026
+ if (manifest.parts.length > 0) {
7027
+ out.push(
7028
+ "- Parts: " + formatNumber(manifest.parts.length) + " at a " + formatNumber(Math.round(manifest.budgets.maxPartBytes / 1024)) + " KB ceiling" + (manifest.parts.length === 1 ? ":" : " each:")
7029
+ );
7030
+ for (const part of manifest.parts.slice(0, MAX_PART_ROWS)) {
7031
+ out.push(" - " + code(part.filename) + " - " + formatNumber(part.fileCount) + " file(s)");
7032
+ }
7033
+ if (manifest.parts.length > MAX_PART_ROWS) {
7034
+ out.push(
7035
+ " - and " + formatNumber(manifest.parts.length - MAX_PART_ROWS) + " more, tabled in `README.md`"
7036
+ );
7037
+ }
7038
+ }
7039
+ return out;
7040
+ }
7041
+ function incompleteSection(manifest, code) {
7042
+ const out = [];
7043
+ const list2 = manifest.incomplete;
7044
+ if (list2.length === 0) {
7045
+ out.push("- Partial files: none. Every included file is present in full.");
7046
+ return out;
7047
+ }
7048
+ out.push(
7049
+ "- Partial files: " + formatNumber(list2.length) + ". These are present only in part, and the",
7050
+ " missing lines are named, not implied:"
7051
+ );
7052
+ for (const entry of list2.slice(0, MAX_INCOMPLETE_ROWS)) {
7053
+ const ranges = entry.omittedRanges.map(([start, end]) => start === end ? String(start) : start + "-" + end).join(", ");
7054
+ out.push(
7055
+ " - " + code(entry.relativePath) + " in " + code(entry.part) + " - " + entry.reason + ", lines " + ranges + " (" + formatNumber(entry.omittedLines) + " of " + formatNumber(entry.lines) + " missing)"
7056
+ );
7057
+ }
7058
+ if (list2.length > MAX_INCOMPLETE_ROWS) {
7059
+ out.push(
7060
+ " - and " + formatNumber(list2.length - MAX_INCOMPLETE_ROWS) + " more, all named in `manifest.json` under `incomplete[]`"
7061
+ );
7062
+ }
7063
+ return out;
7064
+ }
7065
+ function redactionSection(manifest, auditWritten) {
7066
+ const redacted = manifest.totals.redactedLines;
7067
+ if (redacted === 0) {
7068
+ return ["- Redacted: no line matched a secret rule."];
7069
+ }
7070
+ const where = auditWritten ? "`reports/audit.md` names the files; the values are not recoverable from it." : "`reports/audit.md` was disabled for this run, so only the count is available.";
7071
+ return [
7072
+ "- Redacted: " + formatNumber(redacted) + " line(s) had values masked before you received them.",
7073
+ " A masked span is a deliberate redaction, not an empty value.",
7074
+ " " + where
7075
+ ];
7076
+ }
7077
+ function deliverySection(manifest, partsWritten, slots) {
7078
+ if (!partsWritten || manifest.parts.length === 0) return [];
7079
+ const parts = manifest.parts.length;
7080
+ const wholeSet = parts + 5;
7081
+ const unlimited = slots <= UNLIMITED_SLOTS;
7082
+ const out = ["## Attaching this", ""];
7083
+ out.push(
7084
+ "Paste this file as text: instructions cost no attachment slot. Attach the files it names.",
7085
+ "",
7086
+ "- Every part opens with `# Codebase Snapshot Part NNN of MMM` and repeats the fingerprint",
7087
+ " above, so check both before relying on one. A part you were not given is not an empty part."
7088
+ );
7089
+ if (unlimited) {
7090
+ out.push(
7091
+ "- No attachment limit is configured, so every file can travel: " + parts + " " + partWord(parts) + " plus `manifest.json`, `README.md` and the three reports (" + wholeSet + " files)."
7092
+ );
7093
+ } else if (wholeSet <= slots) {
7094
+ out.push(
7095
+ "- A " + slots + "-file destination carries the whole set: " + parts + " " + partWord(parts) + " plus `manifest.json`, `README.md` and the three reports - " + wholeSet + " of " + slots + "."
7096
+ );
7097
+ } else if (parts + 1 <= slots) {
7098
+ out.push(
7099
+ "- A " + slots + "-file destination carries " + parts + " " + partWord(parts) + " and",
7100
+ " `manifest.json` (" + (parts + 1) + " of " + slots + "); `README.md` and",
7101
+ " `reports/` stay behind - the brief above carries what they add."
7102
+ );
7103
+ } else if (parts <= slots) {
7104
+ out.push(
7105
+ parts === 1 ? "- The only part fills a " + slots + "-file destination, so `manifest.json` and" : "- The " + parts + " parts fill a " + slots + "-file destination, so `manifest.json` and",
7106
+ " `reports/` stay behind. The brief above carries what they add."
7107
+ );
7108
+ if (parts > 1) {
7109
+ out.push(
7110
+ " Either raise `--max-part-bytes` to merge the parts, or set `--max-parts " + slots + "` and let the parts grow to the count instead."
7111
+ );
7112
+ }
7113
+ } else {
7114
+ out.push(
7115
+ "- The " + parts + " parts do not fit a " + slots + "-file destination: at most " + slots + " can be attached.",
7116
+ " Choose by task - `reports/navigation.md` maps a file to its part - and name the parts",
7117
+ " you left out, or regenerate with `--max-part-bytes " + suggestBudgetBytes(manifest, slots) + "` for about " + (slots - 1) + " parts. `--max-parts " + slots + "` grows the parts until",
7118
+ " they fit instead, and says so when they end up larger than maxPartBytes."
7119
+ );
7120
+ }
7121
+ out.push(
7122
+ "- If you were given only some of them, say which parts are missing before you answer, and",
7123
+ " name the files you needed. Do not infer the contents of a part you did not receive.",
7124
+ ""
7125
+ );
7126
+ return out;
7127
+ }
7128
+ function suggestBudgetBytes(manifest, slots) {
7129
+ const total = manifest.parts.reduce((sum, part) => sum + part.byteSize, 0);
7130
+ const target = Math.max(1, slots - 1);
7131
+ const estimated = Math.ceil(total / target * 1.15);
7132
+ const rounded = Math.ceil(estimated / 16384) * 16384;
7133
+ const budget = Math.max(rounded, manifest.budgets.maxPartBytes);
7134
+ return Math.round(budget / 1024) + "k";
7135
+ }
7136
+
6681
7137
  // src/generator/readme.ts
6682
7138
  function generateReadme(manifest, artifacts) {
6683
7139
  const wrote = (name) => artifacts?.[name] !== false;
6684
7140
  const reportLinks = [];
7141
+ if (wrote("prompt")) {
7142
+ reportLinks.push(
7143
+ "- [PROMPT.md](PROMPT.md) \u2014 The instruction sheet to paste with this snapshot: what it contains, what it left out, and the rules for citing it."
7144
+ );
7145
+ }
6685
7146
  if (wrote("navigation")) {
6686
7147
  reportLinks.push(
6687
7148
  "- [reports/navigation.md](reports/navigation.md) \u2014 Comprehensive file directory mapping files to chunk files."
@@ -6751,6 +7212,11 @@ function generateReadme(manifest, artifacts) {
6751
7212
  lines.push("", "## Snapshot Parts", "", "No parts were written for this run.");
6752
7213
  }
6753
7214
  const readOrder = [];
7215
+ if (wrote("prompt")) {
7216
+ readOrder.push(
7217
+ "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
7218
+ );
7219
+ }
6754
7220
  if (wrote("navigation") || wrote("projectTree")) {
6755
7221
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
6756
7222
  readOrder.push(`1. Read ${first} first to locate target features or files.`);
@@ -8048,7 +8514,8 @@ function validateSnapshot(configInput) {
8048
8514
  );
8049
8515
  }
8050
8516
  }
8051
- if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
8517
+ const ceilingDerivedByMaxParts = (manifest.config?.maxParts ?? null) !== null;
8518
+ if (!ceilingDerivedByMaxParts && manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
8052
8519
  totalsMismatches.push(
8053
8520
  `budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
8054
8521
  );
@@ -8077,6 +8544,7 @@ function validateSnapshot(configInput) {
8077
8544
  }
8078
8545
  const declaredArtifacts = [
8079
8546
  ["README.md", manifest.artifacts?.readme],
8547
+ ["PROMPT.md", manifest.artifacts?.prompt],
8080
8548
  ["reports/navigation.md", manifest.artifacts?.navigation],
8081
8549
  ["reports/project-tree.md", manifest.artifacts?.projectTree],
8082
8550
  ["reports/audit.md", manifest.artifacts?.audit],
@@ -8989,6 +9457,7 @@ var DEFAULT_ANSWERS = {
8989
9457
  excludePatterns: [],
8990
9458
  artifacts: {
8991
9459
  readme: true,
9460
+ prompt: true,
8992
9461
  manifest: true,
8993
9462
  parts: true,
8994
9463
  navigation: true,
@@ -9105,6 +9574,7 @@ function renderConfig(answers) {
9105
9574
  // \u2500\u2500 Artifacts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
9106
9575
  artifacts: {
9107
9576
  readme: ${artifacts.readme}, // README.md
9577
+ prompt: ${artifacts.prompt}, // PROMPT.md \u2014 the instruction sheet a model is given
9108
9578
  manifest: ${artifacts.manifest}, // manifest.json \u2014 required by validate and report
9109
9579
  parts: ${artifacts.parts}, // parts/part-XXX.md
9110
9580
  navigation: ${artifacts.navigation}, // reports/navigation.md
@@ -9120,6 +9590,11 @@ function renderConfig(answers) {
9120
9590
  includeMonolith: ${artifacts.monolith},
9121
9591
 
9122
9592
  // \u2500\u2500 Advanced \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
9593
+ // Files your destination accepts in one message, used by PROMPT.md to plan the delivery.
9594
+ // attachmentSlots: 10,
9595
+ // Experimental: grow the per-part budget until the snapshot fits this many parts, instead of
9596
+ // adding a part as the code grows. The plan in PROMPT.md becomes a fixed-length attachment list.
9597
+ // maxParts: 10,
9123
9598
  // afterGenerate: (manifest) => { /* write your own artifact */ }
9124
9599
  hooks: {},
9125
9600
  };
@@ -9810,6 +10285,7 @@ async function runInit(options) {
9810
10285
  let lastScope = "all";
9811
10286
  const artifactChoices = [
9812
10287
  { value: "readme", label: "README.md", hint: "orientation page" },
10288
+ { value: "prompt", label: "PROMPT.md", hint: "instruction sheet for the model" },
9813
10289
  { value: "manifest", label: "manifest.json", hint: "required by validate and report" },
9814
10290
  { value: "parts", label: "parts/", hint: "the code payload" },
9815
10291
  { value: "navigation", label: "reports/navigation.md", hint: "file \u2192 part index" },
@@ -11449,7 +11925,55 @@ function runAfterGenerate(config, manifest) {
11449
11925
  return Promise.resolve(returned).finally(releaseRedirect);
11450
11926
  }
11451
11927
  function partitionByBudget(files, config, fingerprint) {
11452
- const budgetFor = (file) => config.budgets.byLayer[file.layer] ?? config.budgets.default;
11928
+ const configured = {
11929
+ parts: partitionWithBudgets(files, config.budgets, fingerprint),
11930
+ budgets: config.budgets,
11931
+ maxPartBytes: config.maxPartBytes,
11932
+ warnings: []
11933
+ };
11934
+ const limit = config.maxParts;
11935
+ if (limit === null || !config.artifacts.parts || configured.parts.length <= limit) return configured;
11936
+ const totalBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11937
+ let target = Math.max(config.budgets.default, Math.ceil(totalBytes * 1.15 / limit));
11938
+ const seen = [];
11939
+ let low = config.budgets.default;
11940
+ let fitting = null;
11941
+ for (let pass = 0; pass < 6; pass += 1) {
11942
+ const parts2 = partitionWithBudgets(files, scaleBudgets(config.budgets, target), fingerprint);
11943
+ if (parts2.length <= limit) {
11944
+ fitting = { target, parts: parts2 };
11945
+ break;
11946
+ }
11947
+ seen.push(parts2.length);
11948
+ low = target;
11949
+ target = Math.ceil(target * 1.3);
11950
+ }
11951
+ if (fitting === null) {
11952
+ throw new Error(
11953
+ `maxParts ${limit} could not be met: ${seen.join(", ")} part(s) at budgets up to ${formatNumber(target)} B. Raise maxParts, include fewer files, or drop the setting.`
11954
+ );
11955
+ }
11956
+ for (let step = 0; step < 3 && fitting.target - low > 8192; step += 1) {
11957
+ const middle = Math.round((low + fitting.target) / 2);
11958
+ const parts2 = partitionWithBudgets(files, scaleBudgets(config.budgets, middle), fingerprint);
11959
+ if (parts2.length <= limit) fitting = { target: middle, parts: parts2 };
11960
+ else low = middle;
11961
+ }
11962
+ const { target: chosen, parts } = fitting;
11963
+ const budgets = scaleBudgets(config.budgets, chosen);
11964
+ const maxPartBytes = Math.max(config.maxPartBytes, chosen);
11965
+ const warnings = [
11966
+ `maxParts ${limit}: the part budget grew from ${formatNumber(config.maxPartBytes)} B to ${formatNumber(maxPartBytes)} B, and the snapshot now has ${formatNumber(parts.length)} part(s).`
11967
+ ];
11968
+ if (maxPartBytes > config.maxPartBytes) {
11969
+ warnings.push(
11970
+ `maxParts ${limit}: parts are now above the configured maxPartBytes (${formatNumber(config.maxPartBytes)} B). A larger part is more tokens for the destination to take at once, and some destinations cap a single file.`
11971
+ );
11972
+ }
11973
+ return { parts, budgets, maxPartBytes, warnings };
11974
+ }
11975
+ function partitionWithBudgets(files, budgets, fingerprint) {
11976
+ const budgetFor = (file) => budgets.byLayer[file.layer] ?? budgets.default;
11453
11977
  const buckets = /* @__PURE__ */ new Map();
11454
11978
  for (const file of files) {
11455
11979
  const budget = budgetFor(file);
@@ -11466,6 +11990,18 @@ function partitionByBudget(files, config, fingerprint) {
11466
11990
  fingerprint
11467
11991
  );
11468
11992
  }
11993
+ function scaleBudgets(budgets, targetDefault) {
11994
+ const factor = targetDefault / budgets.default;
11995
+ return {
11996
+ default: Math.max(budgets.default, Math.round(targetDefault)),
11997
+ byLayer: Object.fromEntries(
11998
+ Object.entries(budgets.byLayer).map(([name, bytes]) => [
11999
+ name,
12000
+ Math.max(bytes, Math.round(bytes * factor))
12001
+ ])
12002
+ )
12003
+ };
12004
+ }
11469
12005
  function generateSnapshot(configInput, options) {
11470
12006
  assertUsableConfigInput(configInput);
11471
12007
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
@@ -11794,7 +12330,8 @@ function generateSnapshot(configInput, options) {
11794
12330
  );
11795
12331
  }
11796
12332
  }
11797
- const parts = partitionByBudget(files, config, fingerprint);
12333
+ const partitioned = partitionByBudget(files, config, fingerprint);
12334
+ const parts = partitioned.parts;
11798
12335
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11799
12336
  const incomplete = files.flatMap((file) => {
11800
12337
  if (file.truncationReason === void 0) return [];
@@ -11831,7 +12368,10 @@ function generateSnapshot(configInput, options) {
11831
12368
  // the README and the audit report.
11832
12369
  git: { ...gitInfo, branch: maskPathText(gitInfo.branch, config.secretRules) },
11833
12370
  budgets: {
11834
- maxPartBytes: config.maxPartBytes,
12371
+ // The ceiling the parts actually honour. It equals the configured one unless `maxParts`
12372
+ // grew it; `config.maxPartBytes` below keeps the configured value, because that is what
12373
+ // `validate` compares against the config on disk.
12374
+ maxPartBytes: partitioned.maxPartBytes,
11835
12375
  largeFileBytes: config.largeFileBytes
11836
12376
  },
11837
12377
  config: {
@@ -11849,6 +12389,14 @@ function generateSnapshot(configInput, options) {
11849
12389
  // invisible in the manifest that is supposed to describe the run.
11850
12390
  maxMonolithBytes: config.maxMonolithBytes ?? null,
11851
12391
  includeSensitiveFiles: config.includeSensitiveFiles,
12392
+ // The destination the instructions were written for. Not part of `digest`: the payload is
12393
+ // identical whatever this says, and a new delivery preference must not make an existing
12394
+ // snapshot fail `validate` as configuration drift.
12395
+ attachmentSlots: config.attachmentSlots,
12396
+ // The part-count ceiling the run enforced. Recorded because it decided the part sizes, and
12397
+ // omitted from `digest` when it is off so an existing snapshot does not start reporting
12398
+ // configuration drift.
12399
+ maxParts: config.maxParts ?? null,
11852
12400
  discovery: config.discovery ?? "auto",
11853
12401
  // A changed-files scope decides which files are in the snapshot, so the manifest that
11854
12402
  // describes the run has to name it.
@@ -11919,6 +12467,10 @@ function generateSnapshot(configInput, options) {
11919
12467
  incomplete,
11920
12468
  warnings
11921
12469
  };
12470
+ if (partitioned.warnings.length > 0) {
12471
+ manifest.warnings.push(...partitioned.warnings);
12472
+ manifest.totals.warningCount = manifest.warnings.length;
12473
+ }
11922
12474
  manifest.totals.redactedLines = secretFindings.length;
11923
12475
  manifest.totals.warningCount = manifest.warnings.length;
11924
12476
  if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
@@ -11975,6 +12527,15 @@ function generateSnapshot(configInput, options) {
11975
12527
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
11976
12528
  const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
11977
12529
  if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
12530
+ const promptText = artifacts.prompt ? generatePrompt(
12531
+ manifest,
12532
+ artifacts,
12533
+ config.attachmentSlots,
12534
+ // Commit subjects are user input and reach an artifact, so they go through the same
12535
+ // masking as every other name the run reproduces.
12536
+ recentCommitSubjects(config.cwd).map((subject) => maskPathText(subject, config.secretRules))
12537
+ ) : null;
12538
+ if (promptText !== null) manifest.artifacts.prompt = artifactRecord(promptText);
11978
12539
  if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
11979
12540
  let monolithJson = null;
11980
12541
  let monolithMarkdown = null;
@@ -12112,6 +12673,9 @@ function generateSnapshot(configInput, options) {
12112
12673
  if (readmeText !== null) {
12113
12674
  writeArtifact(stagingDir, "README.md", readmeText);
12114
12675
  }
12676
+ if (promptText !== null) {
12677
+ writeArtifact(stagingDir, "PROMPT.md", promptText);
12678
+ }
12115
12679
  if (artifacts.manifest) {
12116
12680
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
12117
12681
  }