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.
package/dist/index.cjs CHANGED
@@ -3923,7 +3923,7 @@ function applySpansKeepingQuotes(line, spans) {
3923
3923
 
3924
3924
  // src/version.ts
3925
3925
  var GENERATOR_NAME = "codebase-snapshot";
3926
- var GENERATOR_VERSION = "0.10.2";
3926
+ var GENERATOR_VERSION = "0.11.0";
3927
3927
  var SCHEMA_VERSION = "3.0.0";
3928
3928
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
3929
3929
  function isOurGeneratorName(name) {
@@ -4371,6 +4371,23 @@ function defaultIgnoreReason(relativePath, toolDirNames = DEFAULT_TOOL_DIR_NAMES
4371
4371
  }
4372
4372
  return null;
4373
4373
  }
4374
+ function recentCommitSubjects(cwd, limit = 10) {
4375
+ try {
4376
+ const stdout = childProcess__namespace.execFileSync(
4377
+ "git",
4378
+ ["log", "-n", String(limit), "--pretty=%s", "--no-color"],
4379
+ {
4380
+ cwd,
4381
+ stdio: ["ignore", "pipe", "ignore"],
4382
+ encoding: "utf8",
4383
+ maxBuffer: GIT_OUTPUT_LIMIT
4384
+ }
4385
+ );
4386
+ return stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
4387
+ } catch {
4388
+ return [];
4389
+ }
4390
+ }
4374
4391
  function listIgnoredPaths(cwd) {
4375
4392
  try {
4376
4393
  const stdout = childProcess__namespace.execFileSync(
@@ -4895,6 +4912,10 @@ function normalizeResolvedConfig(config) {
4895
4912
  return markResolvedConfig({
4896
4913
  ...config,
4897
4914
  discovery,
4915
+ // A spread copy built before the field existed carries no value; the default applies, and it
4916
+ // is re-validated because the number reaches a rendered artifact.
4917
+ attachmentSlots: resolveAttachmentSlots(config.attachmentSlots),
4918
+ maxParts: resolveMaxParts(config.maxParts),
4898
4919
  includeMonolith: artifacts.monolith,
4899
4920
  secretRules: compileSecretRules(config.secretRules),
4900
4921
  artifacts,
@@ -4963,6 +4984,7 @@ function describeValue2(value) {
4963
4984
  var isThenable = (value) => typeof value.then === "function";
4964
4985
  var CONFIG_KEY_NAMES = [
4965
4986
  "artifacts",
4987
+ "attachmentSlots",
4966
4988
  "branch",
4967
4989
  "budgets",
4968
4990
  "changedSince",
@@ -4980,6 +5002,7 @@ var CONFIG_KEY_NAMES = [
4980
5002
  "layersMode",
4981
5003
  "maxMonolithBytes",
4982
5004
  "maxPartBytes",
5005
+ "maxParts",
4983
5006
  "maxPartTokens",
4984
5007
  "outDir",
4985
5008
  "preset",
@@ -5185,6 +5208,7 @@ var MIN_MAX_PART_BYTES = 4096;
5185
5208
  var MIN_MAX_PART_TOKENS = MIN_MAX_PART_BYTES / 4;
5186
5209
  var ARTIFACT_NAMES = [
5187
5210
  "readme",
5211
+ "prompt",
5188
5212
  "manifest",
5189
5213
  "parts",
5190
5214
  "navigation",
@@ -5194,6 +5218,7 @@ var ARTIFACT_NAMES = [
5194
5218
  ];
5195
5219
  var DEFAULT_ARTIFACTS = {
5196
5220
  readme: true,
5221
+ prompt: true,
5197
5222
  manifest: true,
5198
5223
  parts: true,
5199
5224
  navigation: true,
@@ -5254,6 +5279,25 @@ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride,
5254
5279
  }
5255
5280
  return artifacts;
5256
5281
  }
5282
+ var DEFAULT_ATTACHMENT_SLOTS = 10;
5283
+ function resolveAttachmentSlots(value) {
5284
+ if (value === void 0 || value === null) return DEFAULT_ATTACHMENT_SLOTS;
5285
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
5286
+ throw new Error(
5287
+ "attachmentSlots must be a whole number, with 0 meaning no limit (received " + describeValue2(value) + ")."
5288
+ );
5289
+ }
5290
+ return value;
5291
+ }
5292
+ function resolveMaxParts(value) {
5293
+ if (value === void 0 || value === null) return null;
5294
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
5295
+ throw new Error(
5296
+ "maxParts must be a whole number of parts, or null to disable it (received " + describeValue2(value) + ")."
5297
+ );
5298
+ }
5299
+ return value;
5300
+ }
5257
5301
  function strictPositiveInteger(value, fallback, label) {
5258
5302
  if (value === void 0) return fallback;
5259
5303
  if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
@@ -5632,6 +5676,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
5632
5676
  "maxMonolithBytes"
5633
5677
  ),
5634
5678
  includeSensitiveFiles,
5679
+ attachmentSlots: resolveAttachmentSlots(
5680
+ cliOptions?.attachmentSlots ?? userConfig?.attachmentSlots
5681
+ ),
5682
+ maxParts: resolveMaxParts(cliOptions?.maxParts ?? userConfig?.maxParts),
5635
5683
  ...changedSince === void 0 ? {} : { changedSince },
5636
5684
  ...staged ? { staged } : {},
5637
5685
  ...withDependents ? { withDependents } : {},
@@ -5714,6 +5762,9 @@ function configDigest(config) {
5714
5762
  includeMonolith: config.includeMonolith,
5715
5763
  maxMonolithBytes: config.maxMonolithBytes ?? null,
5716
5764
  includeSensitiveFiles: config.includeSensitiveFiles,
5765
+ // Only when the experimental mode is on: `null` is the off switch, and writing it into the
5766
+ // material would change the digest of every snapshot taken before the setting existed.
5767
+ ...config.maxParts === null ? {} : { maxParts: config.maxParts },
5717
5768
  artifacts: config.artifacts,
5718
5769
  include: config.include,
5719
5770
  excludePatterns: config.excludePatterns,
@@ -6673,10 +6724,420 @@ function generateNavigation(manifest) {
6673
6724
  return lines.join("\n");
6674
6725
  }
6675
6726
 
6727
+ // src/generator/prompt.ts
6728
+ var MAX_PART_ROWS = 16;
6729
+ var MAX_LAYER_ROWS = 8;
6730
+ var MAX_INCOMPLETE_ROWS = 50;
6731
+ var MAX_CENTRAL_FILES = 5;
6732
+ var MAX_ENTRY_POINTS = 4;
6733
+ var MAX_LARGEST_FILES = 3;
6734
+ var partWord = (count) => count === 1 ? "part" : "parts";
6735
+ var UNLIMITED_SLOTS = 0;
6736
+ var ENTRY_POINT = /(^|\/)(index|cli|main|bin|server|app|mod)\.[cm]?[jt]sx?$/;
6737
+ var TEST_PATH = /(^|\/)(tests?|__tests__)\//;
6738
+ var TEST_FILE = /\.(test|spec)\.[^.]+$/;
6739
+ function generatePrompt(manifest, artifacts, attachmentSlots = DEFAULT_ATTACHMENT_SLOTS, history = []) {
6740
+ const wrote = (name) => artifacts?.[name] !== false;
6741
+ const code = (value) => inlineCode(escapeControls(value));
6742
+ const lines = [
6743
+ "# PROMPT.md",
6744
+ "",
6745
+ "The brief and the apparatus for this snapshot. Paste this file first, then the parts it names.",
6746
+ "",
6747
+ "It is generated rather than written once: the system map, the omissions, the fingerprint and",
6748
+ "the history below are read from `manifest.json` and this repository, so they describe this run.",
6749
+ "Regenerate it after the code moves.",
6750
+ "",
6751
+ "---",
6752
+ "",
6753
+ "```text",
6754
+ "You are working on a codebase you cannot clone, run or grep. Everything you know about it comes",
6755
+ "from the snapshot that follows this instruction. Where these notes and the snapshot disagree,",
6756
+ "the snapshot is what exists.",
6757
+ "",
6758
+ "## The job",
6759
+ "",
6760
+ "Find what is still wrong or will break. How you read the code is yours to decide - by",
6761
+ "subsystem, by data flow, by the invariants you derive yourself. What you owe in return is an",
6762
+ "honest account of what you covered and what you did not.",
6763
+ "",
6764
+ 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,",
6765
+ 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.",
6766
+ 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.",
6767
+ "",
6768
+ "If the task at the end asks for something narrower - explain a file, review a change, answer a",
6769
+ "question - that task wins. The standard and the coverage duty below still apply to it.",
6770
+ ""
6771
+ ];
6772
+ lines.push(...haveSection(wrote), "");
6773
+ lines.push(...systemSection(manifest, code), "");
6774
+ lines.push(...historySection(history), "");
6775
+ lines.push(...barSection(), "");
6776
+ lines.push(...coverageSection(manifest, code, wrote("audit")), "");
6777
+ lines.push(...answerSection(), "");
6778
+ lines.push(...calibrationSection(), "");
6779
+ lines.push(...snapshotSection(manifest, code), "");
6780
+ lines.push(...deliverySection(manifest, wrote("parts"), attachmentSlots));
6781
+ lines.push(
6782
+ "## Your task",
6783
+ "",
6784
+ "<replace with the question, the area to review, or the subsystem to audit>",
6785
+ "```"
6786
+ );
6787
+ lines.push(
6788
+ "",
6789
+ "---",
6790
+ "",
6791
+ "## Why this file exists",
6792
+ "",
6793
+ "Parts on their own are a dump: the model receives text, has no idea what was left out of it,",
6794
+ "and fills the gap by invention. A brief on its own is a wish list: it cannot say which files",
6795
+ "are present, which are partial or which part holds what. This file is both halves, and the",
6796
+ "facts in it move with the snapshot.",
6797
+ "",
6798
+ "## Keeping it true",
6799
+ "",
6800
+ "- It is one of the artifacts recorded in `manifest.json` under `artifacts.prompt`, so deleting",
6801
+ " or editing `PROMPT.md` makes `snapshot validate` fail.",
6802
+ "- `--skip-artifacts prompt`, or `artifacts: { prompt: false }` in the config, turns it off.",
6803
+ "- The history section disappears when git cannot be read, rather than being invented.",
6804
+ "- If the code moves, regenerate. A brief naming the previous run parts is worse than no",
6805
+ " brief, because it reads as current.",
6806
+ ""
6807
+ );
6808
+ return lines.join("\n");
6809
+ }
6810
+ function haveSection(wrote) {
6811
+ const out = ["## What you have", ""];
6812
+ const bullets = [];
6813
+ if (wrote("readme")) {
6814
+ bullets.push("- `README.md` - orientation: metrics, the part table, and the fingerprint.");
6815
+ }
6816
+ if (wrote("manifest")) {
6817
+ bullets.push(
6818
+ "- `manifest.json` - the index. Per file: `relativePath`, `layer`, `kind`, `language`,",
6819
+ " `part`, `sha256`, `inclusionMode`, `truncationReason`, `omittedRanges`. It also carries",
6820
+ " every excluded path under `skipped[]` with its reason, and `incomplete[]`, which names",
6821
+ " every included file whose emitted body is not the whole file."
6822
+ );
6823
+ }
6824
+ if (wrote("navigation")) {
6825
+ bullets.push("- `reports/navigation.md` - file to part. Locate here before you read anything.");
6826
+ }
6827
+ if (wrote("projectTree")) {
6828
+ bullets.push("- `reports/project-tree.md` - the directory shape of what was included.");
6829
+ }
6830
+ if (wrote("audit")) {
6831
+ bullets.push(
6832
+ "- `reports/audit.md` - secret findings, the files whose lines were redacted, large files,",
6833
+ " parse diagnostics and the git state the snapshot was taken from."
6834
+ );
6835
+ }
6836
+ if (wrote("parts")) {
6837
+ bullets.push(
6838
+ "- `parts/part-NNN.md` - the code itself, split to a fixed byte budget. Each part states its",
6839
+ " own number, the files it contains, and the fingerprint it was built from."
6840
+ );
6841
+ }
6842
+ if (wrote("monolith")) {
6843
+ bullets.push(
6844
+ "- `full-codebase.json` and `full-codebase.md` - the entire payload in one file each.",
6845
+ " Where they are present, they supersede the parts: nothing was left out of them."
6846
+ );
6847
+ }
6848
+ if (bullets.length === 0) {
6849
+ bullets.push(
6850
+ "- Nothing but this brief: every code artifact was disabled for this run. Ask for a snapshot",
6851
+ " generated with the artifacts you need, and do not answer from memory."
6852
+ );
6853
+ }
6854
+ out.push(...bullets);
6855
+ return out;
6856
+ }
6857
+ function systemSection(manifest, code) {
6858
+ const out = ["## The system", ""];
6859
+ const layers = Object.entries(manifest.layers).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
6860
+ if (layers.length > 0) {
6861
+ const shown = layers.slice(0, MAX_LAYER_ROWS).map(([name, count]) => code(name) + " " + formatNumber(count));
6862
+ const rest = layers.length > MAX_LAYER_ROWS ? ", and " + formatNumber(layers.length - MAX_LAYER_ROWS) + " more" : "";
6863
+ out.push("- Layers, by file count: " + shown.join(", ") + rest + ".");
6864
+ }
6865
+ const central = manifest.indexes.imports.centralFiles;
6866
+ if (central.length > 0) {
6867
+ const shown = central.slice(0, MAX_CENTRAL_FILES).map((entry) => code(entry.path) + " (" + formatNumber(entry.importedByCount) + ")").join(", ");
6868
+ out.push(
6869
+ "- Load-bearing modules, by how many files import them: " + shown + ".",
6870
+ " A change here reaches the most call sites; read it before judging anything that uses it."
6871
+ );
6872
+ }
6873
+ 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);
6874
+ out.push(
6875
+ 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"
6876
+ );
6877
+ if (entryPoints.length === 0) out.push(" starts, and the call graph in `manifest.json` is the map.");
6878
+ const routes = manifest.indexes.routes.length;
6879
+ const handlers = manifest.indexes.handlers.length;
6880
+ const components = manifest.indexes.components.length;
6881
+ const routesShown = manifest.indexes.routes.slice(0, 4).map((route) => code(route.path));
6882
+ const componentsShown = manifest.indexes.components.slice(0, 4).map((entry) => code(entry.path));
6883
+ if (routes + handlers + components === 0) {
6884
+ out.push(
6885
+ "- No routes, handlers or UI components were recorded: this snapshot indexes no HTTP or",
6886
+ " component surface. Do not go looking for one, and do not infer one from a file name."
6887
+ );
6888
+ } else {
6889
+ const parts = [];
6890
+ if (routes > 0) parts.push(formatNumber(routes) + " route(s), e.g. " + routesShown.join(", "));
6891
+ if (handlers > 0) parts.push(formatNumber(handlers) + " handler(s)");
6892
+ if (components > 0) parts.push(formatNumber(components) + " component(s), e.g. " + componentsShown.join(", "));
6893
+ out.push("- Surfaces the index found: " + parts.join("; ") + ".");
6894
+ }
6895
+ const largest = [...manifest.files].sort((a, b) => b.includedBytes - a.includedBytes).slice(0, MAX_LARGEST_FILES);
6896
+ if (largest.length > 0) {
6897
+ out.push(
6898
+ "- Largest files: " + largest.map((file) => code(file.relativePath) + " (" + formatNumber(Math.round(file.includedBytes / 1024)) + " KB)").join(", ") + "."
6899
+ );
6900
+ }
6901
+ const tests = manifest.files.filter(
6902
+ (file) => TEST_PATH.test(file.relativePath) || TEST_FILE.test(file.relativePath)
6903
+ );
6904
+ if (tests.length > 0) {
6905
+ const testBytes = tests.reduce((total, file) => total + file.includedBytes, 0);
6906
+ const allBytes = manifest.files.reduce((total, file) => total + file.includedBytes, 0);
6907
+ const share = allBytes === 0 ? 0 : Math.round(testBytes / allBytes * 100);
6908
+ out.push(
6909
+ "- Tests: " + formatNumber(tests.length) + " file(s), " + share + "% of the included bytes.",
6910
+ " They are evidence of intent, not of behaviour: a fixture can encode a payload shape the",
6911
+ " real system never sends."
6912
+ );
6913
+ }
6914
+ return out;
6915
+ }
6916
+ function historySection(history) {
6917
+ const out = ["## What came before", ""];
6918
+ if (history.length === 0) {
6919
+ out.push(
6920
+ "No history was readable: this is not a git checkout, or git could not be run. Nothing about",
6921
+ "what came before can be claimed from here, and that is not evidence that the code is new."
6922
+ );
6923
+ return out;
6924
+ }
6925
+ out.push(
6926
+ "Commit subjects, newest first. They are claims by whoever wrote them, not evidence - the code",
6927
+ "beside them is the evidence. If one of these fixes looks incomplete, quote the lines and say",
6928
+ "which call site it missed.",
6929
+ ""
6930
+ );
6931
+ for (const subject of history) out.push("- " + subject);
6932
+ return out;
6933
+ }
6934
+ function barSection() {
6935
+ return [
6936
+ "## The bar",
6937
+ "",
6938
+ "A finding is a concrete way the code breaks or lies, supported by quoted lines: the path and",
6939
+ "line, the input or state that reaches it, what happens next, and why the guard that appears to",
6940
+ "stop it does not. A comment is not behaviour. A passing test is evidence of intent, not of",
6941
+ "behaviour.",
6942
+ "",
6943
+ "- No style, naming, formatting, add-types, add-tests, consider-X or speculative rewrites.",
6944
+ "- Never invent a finding to fill a section. A clean surface is proven by quoting the guard",
6945
+ " that makes it clean.",
6946
+ "- Mark confidence, and name the check - a test, a run, an input - that would settle anything",
6947
+ " you cannot decide by reading.",
6948
+ "- Separate what the code does from what the deployment or configuration does. Both are",
6949
+ " findings; they have different owners and different fixes."
6950
+ ];
6951
+ }
6952
+ function coverageSection(manifest, code, auditWritten) {
6953
+ const out = ["## Coverage", ""];
6954
+ const reasons = /* @__PURE__ */ new Map();
6955
+ for (const record of manifest.skipped) {
6956
+ reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
6957
+ }
6958
+ const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
6959
+ out.push(
6960
+ "- " + 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 + ")" : "") + ".",
6961
+ " `manifest.skipped[]` names each one and why. An absent path is not a clean path."
6962
+ );
6963
+ out.push(...incompleteSection(manifest, code));
6964
+ out.push(...redactionSection(manifest, auditWritten));
6965
+ out.push(
6966
+ "- Everything unseen is unread, never clean. If you were given only some of the parts, say",
6967
+ " which ones are missing before you answer. A file the index names but the parts do not carry",
6968
+ " is an input defect, not a code finding - report it as one."
6969
+ );
6970
+ return out;
6971
+ }
6972
+ function answerSection() {
6973
+ return [
6974
+ "## What a useful answer contains",
6975
+ "",
6976
+ "- An opening line, filled from This snapshot below:",
6977
+ "",
6978
+ " snapshot <fingerprint> generated <generatedAt>",
6979
+ "",
6980
+ "- What you read and what you did not, named by path or by part.",
6981
+ "- Findings ordered by consequence, each with the lines quoted.",
6982
+ "- The checks or attacks that failed, and the line or guard that blocked them. A failed attack",
6983
+ " is how anyone knows an invariant is real rather than asserted.",
6984
+ "- What you retracted after re-reading.",
6985
+ "- What only a run, a test or a host can settle, and the check that would settle each.",
6986
+ "- One paragraph on the failure you would bet on next.",
6987
+ "- A closing line: Needed but not received: <paths>, or none. That line is not decoration -",
6988
+ " an invented function is indistinguishable from a real one, and this is where you name",
6989
+ " the gap you filled by asking instead of guessing."
6990
+ ];
6991
+ }
6992
+ function calibrationSection() {
6993
+ return [
6994
+ "## Calibration",
6995
+ "",
6996
+ "The findings that matter here do not crash. They look like:",
6997
+ "",
6998
+ "- a guard applied at one call site and not its twin - the route checks, the timer does not;",
6999
+ "- a budget shorter than the work it guards, so the caller gives up while the work continues;",
7000
+ "- a success flag that means the call returned, consumed as the change happened;",
7001
+ "- a document that describes a different run than the one beside it;",
7002
+ "- a default that fabricates a number when the measurement failed.",
7003
+ "",
7004
+ "None of these throw. All are invisible in a summary."
7005
+ ];
7006
+ }
7007
+ function snapshotSection(manifest, code) {
7008
+ const out = ["## This snapshot", ""];
7009
+ out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
7010
+ out.push(
7011
+ "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
7012
+ );
7013
+ out.push(
7014
+ manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
7015
+ );
7016
+ out.push(
7017
+ "- Validation: `manifest.validation.status` was " + code(manifest.validation.status) + " at generation time.",
7018
+ " That describes the run, not now: if the tree may have moved since, the snapshot is a",
7019
+ " claim that needs re-checking, not a fact."
7020
+ );
7021
+ if (manifest.parts.length > 0) {
7022
+ out.push(
7023
+ "- Parts: " + formatNumber(manifest.parts.length) + " at a " + formatNumber(Math.round(manifest.budgets.maxPartBytes / 1024)) + " KB ceiling" + (manifest.parts.length === 1 ? ":" : " each:")
7024
+ );
7025
+ for (const part of manifest.parts.slice(0, MAX_PART_ROWS)) {
7026
+ out.push(" - " + code(part.filename) + " - " + formatNumber(part.fileCount) + " file(s)");
7027
+ }
7028
+ if (manifest.parts.length > MAX_PART_ROWS) {
7029
+ out.push(
7030
+ " - and " + formatNumber(manifest.parts.length - MAX_PART_ROWS) + " more, tabled in `README.md`"
7031
+ );
7032
+ }
7033
+ }
7034
+ return out;
7035
+ }
7036
+ function incompleteSection(manifest, code) {
7037
+ const out = [];
7038
+ const list2 = manifest.incomplete;
7039
+ if (list2.length === 0) {
7040
+ out.push("- Partial files: none. Every included file is present in full.");
7041
+ return out;
7042
+ }
7043
+ out.push(
7044
+ "- Partial files: " + formatNumber(list2.length) + ". These are present only in part, and the",
7045
+ " missing lines are named, not implied:"
7046
+ );
7047
+ for (const entry of list2.slice(0, MAX_INCOMPLETE_ROWS)) {
7048
+ const ranges = entry.omittedRanges.map(([start, end]) => start === end ? String(start) : start + "-" + end).join(", ");
7049
+ out.push(
7050
+ " - " + code(entry.relativePath) + " in " + code(entry.part) + " - " + entry.reason + ", lines " + ranges + " (" + formatNumber(entry.omittedLines) + " of " + formatNumber(entry.lines) + " missing)"
7051
+ );
7052
+ }
7053
+ if (list2.length > MAX_INCOMPLETE_ROWS) {
7054
+ out.push(
7055
+ " - and " + formatNumber(list2.length - MAX_INCOMPLETE_ROWS) + " more, all named in `manifest.json` under `incomplete[]`"
7056
+ );
7057
+ }
7058
+ return out;
7059
+ }
7060
+ function redactionSection(manifest, auditWritten) {
7061
+ const redacted = manifest.totals.redactedLines;
7062
+ if (redacted === 0) {
7063
+ return ["- Redacted: no line matched a secret rule."];
7064
+ }
7065
+ 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.";
7066
+ return [
7067
+ "- Redacted: " + formatNumber(redacted) + " line(s) had values masked before you received them.",
7068
+ " A masked span is a deliberate redaction, not an empty value.",
7069
+ " " + where
7070
+ ];
7071
+ }
7072
+ function deliverySection(manifest, partsWritten, slots) {
7073
+ if (!partsWritten || manifest.parts.length === 0) return [];
7074
+ const parts = manifest.parts.length;
7075
+ const wholeSet = parts + 5;
7076
+ const unlimited = slots <= UNLIMITED_SLOTS;
7077
+ const out = ["## Attaching this", ""];
7078
+ out.push(
7079
+ "Paste this file as text: instructions cost no attachment slot. Attach the files it names.",
7080
+ "",
7081
+ "- Every part opens with `# Codebase Snapshot Part NNN of MMM` and repeats the fingerprint",
7082
+ " above, so check both before relying on one. A part you were not given is not an empty part."
7083
+ );
7084
+ if (unlimited) {
7085
+ out.push(
7086
+ "- No attachment limit is configured, so every file can travel: " + parts + " " + partWord(parts) + " plus `manifest.json`, `README.md` and the three reports (" + wholeSet + " files)."
7087
+ );
7088
+ } else if (wholeSet <= slots) {
7089
+ out.push(
7090
+ "- A " + slots + "-file destination carries the whole set: " + parts + " " + partWord(parts) + " plus `manifest.json`, `README.md` and the three reports - " + wholeSet + " of " + slots + "."
7091
+ );
7092
+ } else if (parts + 1 <= slots) {
7093
+ out.push(
7094
+ "- A " + slots + "-file destination carries " + parts + " " + partWord(parts) + " and",
7095
+ " `manifest.json` (" + (parts + 1) + " of " + slots + "); `README.md` and",
7096
+ " `reports/` stay behind - the brief above carries what they add."
7097
+ );
7098
+ } else if (parts <= slots) {
7099
+ out.push(
7100
+ 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",
7101
+ " `reports/` stay behind. The brief above carries what they add."
7102
+ );
7103
+ if (parts > 1) {
7104
+ out.push(
7105
+ " Either raise `--max-part-bytes` to merge the parts, or set `--max-parts " + slots + "` and let the parts grow to the count instead."
7106
+ );
7107
+ }
7108
+ } else {
7109
+ out.push(
7110
+ "- The " + parts + " parts do not fit a " + slots + "-file destination: at most " + slots + " can be attached.",
7111
+ " Choose by task - `reports/navigation.md` maps a file to its part - and name the parts",
7112
+ " you left out, or regenerate with `--max-part-bytes " + suggestBudgetBytes(manifest, slots) + "` for about " + (slots - 1) + " parts. `--max-parts " + slots + "` grows the parts until",
7113
+ " they fit instead, and says so when they end up larger than maxPartBytes."
7114
+ );
7115
+ }
7116
+ out.push(
7117
+ "- If you were given only some of them, say which parts are missing before you answer, and",
7118
+ " name the files you needed. Do not infer the contents of a part you did not receive.",
7119
+ ""
7120
+ );
7121
+ return out;
7122
+ }
7123
+ function suggestBudgetBytes(manifest, slots) {
7124
+ const total = manifest.parts.reduce((sum, part) => sum + part.byteSize, 0);
7125
+ const target = Math.max(1, slots - 1);
7126
+ const estimated = Math.ceil(total / target * 1.15);
7127
+ const rounded = Math.ceil(estimated / 16384) * 16384;
7128
+ const budget = Math.max(rounded, manifest.budgets.maxPartBytes);
7129
+ return Math.round(budget / 1024) + "k";
7130
+ }
7131
+
6676
7132
  // src/generator/readme.ts
6677
7133
  function generateReadme(manifest, artifacts) {
6678
7134
  const wrote = (name) => artifacts?.[name] !== false;
6679
7135
  const reportLinks = [];
7136
+ if (wrote("prompt")) {
7137
+ reportLinks.push(
7138
+ "- [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."
7139
+ );
7140
+ }
6680
7141
  if (wrote("navigation")) {
6681
7142
  reportLinks.push(
6682
7143
  "- [reports/navigation.md](reports/navigation.md) \u2014 Comprehensive file directory mapping files to chunk files."
@@ -6746,6 +7207,11 @@ function generateReadme(manifest, artifacts) {
6746
7207
  lines.push("", "## Snapshot Parts", "", "No parts were written for this run.");
6747
7208
  }
6748
7209
  const readOrder = [];
7210
+ if (wrote("prompt")) {
7211
+ readOrder.push(
7212
+ "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
7213
+ );
7214
+ }
6749
7215
  if (wrote("navigation") || wrote("projectTree")) {
6750
7216
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
6751
7217
  readOrder.push(`1. Read ${first} first to locate target features or files.`);
@@ -8043,7 +8509,8 @@ function validateSnapshot(configInput) {
8043
8509
  );
8044
8510
  }
8045
8511
  }
8046
- if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
8512
+ const ceilingDerivedByMaxParts = (manifest.config?.maxParts ?? null) !== null;
8513
+ if (!ceilingDerivedByMaxParts && manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
8047
8514
  totalsMismatches.push(
8048
8515
  `budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
8049
8516
  );
@@ -8072,6 +8539,7 @@ function validateSnapshot(configInput) {
8072
8539
  }
8073
8540
  const declaredArtifacts = [
8074
8541
  ["README.md", manifest.artifacts?.readme],
8542
+ ["PROMPT.md", manifest.artifacts?.prompt],
8075
8543
  ["reports/navigation.md", manifest.artifacts?.navigation],
8076
8544
  ["reports/project-tree.md", manifest.artifacts?.projectTree],
8077
8545
  ["reports/audit.md", manifest.artifacts?.audit],
@@ -8984,6 +9452,7 @@ var DEFAULT_ANSWERS = {
8984
9452
  excludePatterns: [],
8985
9453
  artifacts: {
8986
9454
  readme: true,
9455
+ prompt: true,
8987
9456
  manifest: true,
8988
9457
  parts: true,
8989
9458
  navigation: true,
@@ -9100,6 +9569,7 @@ function renderConfig(answers) {
9100
9569
  // \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
9101
9570
  artifacts: {
9102
9571
  readme: ${artifacts.readme}, // README.md
9572
+ prompt: ${artifacts.prompt}, // PROMPT.md \u2014 the instruction sheet a model is given
9103
9573
  manifest: ${artifacts.manifest}, // manifest.json \u2014 required by validate and report
9104
9574
  parts: ${artifacts.parts}, // parts/part-XXX.md
9105
9575
  navigation: ${artifacts.navigation}, // reports/navigation.md
@@ -9115,6 +9585,11 @@ function renderConfig(answers) {
9115
9585
  includeMonolith: ${artifacts.monolith},
9116
9586
 
9117
9587
  // \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
9588
+ // Files your destination accepts in one message, used by PROMPT.md to plan the delivery.
9589
+ // attachmentSlots: 10,
9590
+ // Experimental: grow the per-part budget until the snapshot fits this many parts, instead of
9591
+ // adding a part as the code grows. The plan in PROMPT.md becomes a fixed-length attachment list.
9592
+ // maxParts: 10,
9118
9593
  // afterGenerate: (manifest) => { /* write your own artifact */ }
9119
9594
  hooks: {},
9120
9595
  };
@@ -9805,6 +10280,7 @@ async function runInit(options) {
9805
10280
  let lastScope = "all";
9806
10281
  const artifactChoices = [
9807
10282
  { value: "readme", label: "README.md", hint: "orientation page" },
10283
+ { value: "prompt", label: "PROMPT.md", hint: "instruction sheet for the model" },
9808
10284
  { value: "manifest", label: "manifest.json", hint: "required by validate and report" },
9809
10285
  { value: "parts", label: "parts/", hint: "the code payload" },
9810
10286
  { value: "navigation", label: "reports/navigation.md", hint: "file \u2192 part index" },
@@ -11351,7 +11827,55 @@ function runAfterGenerate(config, manifest) {
11351
11827
  return Promise.resolve(returned).finally(releaseRedirect);
11352
11828
  }
11353
11829
  function partitionByBudget(files, config, fingerprint) {
11354
- const budgetFor = (file) => config.budgets.byLayer[file.layer] ?? config.budgets.default;
11830
+ const configured = {
11831
+ parts: partitionWithBudgets(files, config.budgets, fingerprint),
11832
+ budgets: config.budgets,
11833
+ maxPartBytes: config.maxPartBytes,
11834
+ warnings: []
11835
+ };
11836
+ const limit = config.maxParts;
11837
+ if (limit === null || !config.artifacts.parts || configured.parts.length <= limit) return configured;
11838
+ const totalBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11839
+ let target = Math.max(config.budgets.default, Math.ceil(totalBytes * 1.15 / limit));
11840
+ const seen = [];
11841
+ let low = config.budgets.default;
11842
+ let fitting = null;
11843
+ for (let pass = 0; pass < 6; pass += 1) {
11844
+ const parts2 = partitionWithBudgets(files, scaleBudgets(config.budgets, target), fingerprint);
11845
+ if (parts2.length <= limit) {
11846
+ fitting = { target, parts: parts2 };
11847
+ break;
11848
+ }
11849
+ seen.push(parts2.length);
11850
+ low = target;
11851
+ target = Math.ceil(target * 1.3);
11852
+ }
11853
+ if (fitting === null) {
11854
+ throw new Error(
11855
+ `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.`
11856
+ );
11857
+ }
11858
+ for (let step = 0; step < 3 && fitting.target - low > 8192; step += 1) {
11859
+ const middle = Math.round((low + fitting.target) / 2);
11860
+ const parts2 = partitionWithBudgets(files, scaleBudgets(config.budgets, middle), fingerprint);
11861
+ if (parts2.length <= limit) fitting = { target: middle, parts: parts2 };
11862
+ else low = middle;
11863
+ }
11864
+ const { target: chosen, parts } = fitting;
11865
+ const budgets = scaleBudgets(config.budgets, chosen);
11866
+ const maxPartBytes = Math.max(config.maxPartBytes, chosen);
11867
+ const warnings = [
11868
+ `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).`
11869
+ ];
11870
+ if (maxPartBytes > config.maxPartBytes) {
11871
+ warnings.push(
11872
+ `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.`
11873
+ );
11874
+ }
11875
+ return { parts, budgets, maxPartBytes, warnings };
11876
+ }
11877
+ function partitionWithBudgets(files, budgets, fingerprint) {
11878
+ const budgetFor = (file) => budgets.byLayer[file.layer] ?? budgets.default;
11355
11879
  const buckets = /* @__PURE__ */ new Map();
11356
11880
  for (const file of files) {
11357
11881
  const budget = budgetFor(file);
@@ -11368,6 +11892,18 @@ function partitionByBudget(files, config, fingerprint) {
11368
11892
  fingerprint
11369
11893
  );
11370
11894
  }
11895
+ function scaleBudgets(budgets, targetDefault) {
11896
+ const factor = targetDefault / budgets.default;
11897
+ return {
11898
+ default: Math.max(budgets.default, Math.round(targetDefault)),
11899
+ byLayer: Object.fromEntries(
11900
+ Object.entries(budgets.byLayer).map(([name, bytes]) => [
11901
+ name,
11902
+ Math.max(bytes, Math.round(bytes * factor))
11903
+ ])
11904
+ )
11905
+ };
11906
+ }
11371
11907
  function generateSnapshot(configInput, options) {
11372
11908
  assertUsableConfigInput(configInput);
11373
11909
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
@@ -11696,7 +12232,8 @@ function generateSnapshot(configInput, options) {
11696
12232
  );
11697
12233
  }
11698
12234
  }
11699
- const parts = partitionByBudget(files, config, fingerprint);
12235
+ const partitioned = partitionByBudget(files, config, fingerprint);
12236
+ const parts = partitioned.parts;
11700
12237
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11701
12238
  const incomplete = files.flatMap((file) => {
11702
12239
  if (file.truncationReason === void 0) return [];
@@ -11733,7 +12270,10 @@ function generateSnapshot(configInput, options) {
11733
12270
  // the README and the audit report.
11734
12271
  git: { ...gitInfo, branch: maskPathText(gitInfo.branch, config.secretRules) },
11735
12272
  budgets: {
11736
- maxPartBytes: config.maxPartBytes,
12273
+ // The ceiling the parts actually honour. It equals the configured one unless `maxParts`
12274
+ // grew it; `config.maxPartBytes` below keeps the configured value, because that is what
12275
+ // `validate` compares against the config on disk.
12276
+ maxPartBytes: partitioned.maxPartBytes,
11737
12277
  largeFileBytes: config.largeFileBytes
11738
12278
  },
11739
12279
  config: {
@@ -11751,6 +12291,14 @@ function generateSnapshot(configInput, options) {
11751
12291
  // invisible in the manifest that is supposed to describe the run.
11752
12292
  maxMonolithBytes: config.maxMonolithBytes ?? null,
11753
12293
  includeSensitiveFiles: config.includeSensitiveFiles,
12294
+ // The destination the instructions were written for. Not part of `digest`: the payload is
12295
+ // identical whatever this says, and a new delivery preference must not make an existing
12296
+ // snapshot fail `validate` as configuration drift.
12297
+ attachmentSlots: config.attachmentSlots,
12298
+ // The part-count ceiling the run enforced. Recorded because it decided the part sizes, and
12299
+ // omitted from `digest` when it is off so an existing snapshot does not start reporting
12300
+ // configuration drift.
12301
+ maxParts: config.maxParts ?? null,
11754
12302
  discovery: config.discovery ?? "auto",
11755
12303
  // A changed-files scope decides which files are in the snapshot, so the manifest that
11756
12304
  // describes the run has to name it.
@@ -11821,6 +12369,10 @@ function generateSnapshot(configInput, options) {
11821
12369
  incomplete,
11822
12370
  warnings
11823
12371
  };
12372
+ if (partitioned.warnings.length > 0) {
12373
+ manifest.warnings.push(...partitioned.warnings);
12374
+ manifest.totals.warningCount = manifest.warnings.length;
12375
+ }
11824
12376
  manifest.totals.redactedLines = secretFindings.length;
11825
12377
  manifest.totals.warningCount = manifest.warnings.length;
11826
12378
  if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
@@ -11877,6 +12429,15 @@ function generateSnapshot(configInput, options) {
11877
12429
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
11878
12430
  const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
11879
12431
  if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
12432
+ const promptText = artifacts.prompt ? generatePrompt(
12433
+ manifest,
12434
+ artifacts,
12435
+ config.attachmentSlots,
12436
+ // Commit subjects are user input and reach an artifact, so they go through the same
12437
+ // masking as every other name the run reproduces.
12438
+ recentCommitSubjects(config.cwd).map((subject) => maskPathText(subject, config.secretRules))
12439
+ ) : null;
12440
+ if (promptText !== null) manifest.artifacts.prompt = artifactRecord(promptText);
11880
12441
  if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
11881
12442
  let monolithJson = null;
11882
12443
  let monolithMarkdown = null;
@@ -12014,6 +12575,9 @@ function generateSnapshot(configInput, options) {
12014
12575
  if (readmeText !== null) {
12015
12576
  writeArtifact(stagingDir, "README.md", readmeText);
12016
12577
  }
12578
+ if (promptText !== null) {
12579
+ writeArtifact(stagingDir, "PROMPT.md", promptText);
12580
+ }
12017
12581
  if (artifacts.manifest) {
12018
12582
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
12019
12583
  }