codebase-snapshot 0.10.1 → 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/cli.cjs CHANGED
@@ -196,8 +196,8 @@ function workspacePackageDirs(cwd, patterns) {
196
196
  function scanWorkspacePackages(cwd, patterns) {
197
197
  const files = /* @__PURE__ */ new Set();
198
198
  const dependencies = /* @__PURE__ */ new Set();
199
- for (const relative14 of workspacePackageDirs(cwd, patterns)) {
200
- const full = path16__namespace.join(cwd, relative14);
199
+ for (const relative15 of workspacePackageDirs(cwd, patterns)) {
200
+ const full = path16__namespace.join(cwd, relative15);
201
201
  try {
202
202
  for (const entry of fs15__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
203
203
  } catch {
@@ -1316,6 +1316,24 @@ var DEFAULT_SECRET_PATTERNS = [
1316
1316
  ),
1317
1317
  valueGroup: 2
1318
1318
  },
1319
+ {
1320
+ // A quoted assignment whose closing quote is **not on this line**.
1321
+ //
1322
+ // The rule above requires `\1`, so an unterminated literal never matched it and the
1323
+ // credential reached the artefact in clear with no finding at all. That is the shape a
1324
+ // truncated file, a hand-edited `.env` and a string that continues on the next line all
1325
+ // produce, and it was the only branch of the redaction pass that was silent.
1326
+ //
1327
+ // The value runs to the end of the line on purpose — there is no delimiter to stop at — and
1328
+ // a later quote of the same kind disables the rule (`(?!\1)`), so a balanced literal is
1329
+ // never matched here: `password: "abc" and "def"` belongs to the rule above.
1330
+ rule: "credential-assignment-unterminated",
1331
+ pattern: new RegExp(
1332
+ `(?:${QUOTED_CREDENTIAL_KEY}|${NOT_AFTER_QUOTE}(?<!id[-_])${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}(["'\`])((?:(?!\\1)[^\\\\\\n]|\\\\.){1,512})$`,
1333
+ "i"
1334
+ ),
1335
+ valueGroup: 2
1336
+ },
1319
1337
  {
1320
1338
  // `pass` and `credentials` are ambiguous on their own, so they
1321
1339
  // are accepted only against a quoted value long enough to be a credential.
@@ -1875,10 +1893,8 @@ function scanAndRedactSecrets(content, rules, filePath) {
1875
1893
  }
1876
1894
  if (spans.length > 0) {
1877
1895
  const maskedLine = applySpans(line, spans);
1878
- if (!quotesAreBalanced(line) || quotesAreBalanced(maskedLine)) {
1879
- recordFinding(lineNumber, matchedRules);
1880
- segments[index] = maskedLine;
1881
- }
1896
+ recordFinding(lineNumber, matchedRules);
1897
+ segments[index] = !quotesAreBalanced(line) || quotesAreBalanced(maskedLine) ? maskedLine : applySpansKeepingQuotes(line, spans);
1882
1898
  }
1883
1899
  }
1884
1900
  if (index + 1 < segments.length) lineNumber += 1;
@@ -2156,6 +2172,17 @@ function isDeclaredBinding(line, matchIndex, filePath) {
2156
2172
  return DECLARATION_KEYWORDS.test(line.slice(from, runStart));
2157
2173
  }
2158
2174
  function applySpans(line, spans) {
2175
+ let out = "";
2176
+ let cursor = 0;
2177
+ for (const span of mergedSpans(line, spans)) {
2178
+ out += line.slice(cursor, span.start);
2179
+ out += REDACTION_MARKER;
2180
+ cursor = span.end;
2181
+ }
2182
+ out += line.slice(cursor);
2183
+ return out;
2184
+ }
2185
+ function mergedSpans(line, spans) {
2159
2186
  const ordered = [...spans].sort((a, b) => a.start - b.start || a.end - b.end);
2160
2187
  const merged = [];
2161
2188
  for (const span of ordered) {
@@ -2166,11 +2193,25 @@ function applySpans(line, spans) {
2166
2193
  if (last && start <= last.end) last.end = Math.max(last.end, end);
2167
2194
  else merged.push({ start, end });
2168
2195
  }
2196
+ return merged;
2197
+ }
2198
+ function applySpansKeepingQuotes(line, spans) {
2169
2199
  let out = "";
2170
2200
  let cursor = 0;
2171
- for (const span of merged) {
2201
+ for (const span of mergedSpans(line, spans)) {
2172
2202
  out += line.slice(cursor, span.start);
2173
- out += REDACTION_MARKER;
2203
+ let run = false;
2204
+ for (let index = span.start; index < span.end; index += 1) {
2205
+ const char = line[index];
2206
+ if (char === '"' || char === "'" || char === "`" || char === "\\") {
2207
+ if (run) out += REDACTION_MARKER;
2208
+ run = false;
2209
+ out += char;
2210
+ continue;
2211
+ }
2212
+ run = true;
2213
+ }
2214
+ if (run) out += REDACTION_MARKER;
2174
2215
  cursor = span.end;
2175
2216
  }
2176
2217
  out += line.slice(cursor);
@@ -2179,7 +2220,7 @@ function applySpans(line, spans) {
2179
2220
 
2180
2221
  // src/version.ts
2181
2222
  var GENERATOR_NAME = "codebase-snapshot";
2182
- var GENERATOR_VERSION = "0.10.1";
2223
+ var GENERATOR_VERSION = "0.11.0";
2183
2224
  var SCHEMA_VERSION = "3.0.0";
2184
2225
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2185
2226
  function isOurGeneratorName(name) {
@@ -2211,8 +2252,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
2211
2252
  };
2212
2253
  }
2213
2254
  function isInside(root, candidate) {
2214
- const relative14 = path16__namespace.relative(root, candidate);
2215
- return relative14 === "" || !relative14.startsWith(`..${path16__namespace.sep}`) && relative14 !== ".." && !path16__namespace.isAbsolute(relative14);
2255
+ const relative15 = path16__namespace.relative(root, candidate);
2256
+ return relative15 === "" || !relative15.startsWith(`..${path16__namespace.sep}`) && relative15 !== ".." && !path16__namespace.isAbsolute(relative15);
2216
2257
  }
2217
2258
  var GIT_OUTPUT_LIMIT = 68157440;
2218
2259
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -2627,6 +2668,23 @@ function defaultIgnoreReason(relativePath, toolDirNames = DEFAULT_TOOL_DIR_NAMES
2627
2668
  }
2628
2669
  return null;
2629
2670
  }
2671
+ function recentCommitSubjects(cwd, limit = 10) {
2672
+ try {
2673
+ const stdout = childProcess__namespace.execFileSync(
2674
+ "git",
2675
+ ["log", "-n", String(limit), "--pretty=%s", "--no-color"],
2676
+ {
2677
+ cwd,
2678
+ stdio: ["ignore", "pipe", "ignore"],
2679
+ encoding: "utf8",
2680
+ maxBuffer: GIT_OUTPUT_LIMIT
2681
+ }
2682
+ );
2683
+ return stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
2684
+ } catch {
2685
+ return [];
2686
+ }
2687
+ }
2630
2688
  function listIgnoredPaths(cwd) {
2631
2689
  try {
2632
2690
  const stdout = childProcess__namespace.execFileSync(
@@ -3063,6 +3121,178 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3063
3121
  return results;
3064
3122
  }
3065
3123
 
3124
+ // src/ast/structured.ts
3125
+ function stripJsonComments(content) {
3126
+ const text2 = content.replace(/^\uFEFF/, "");
3127
+ const withoutComments = stripComments(text2);
3128
+ return stripTrailingCommas(withoutComments);
3129
+ }
3130
+ function stripComments(text2) {
3131
+ let out = "";
3132
+ let inString = false;
3133
+ let escaped = false;
3134
+ for (let index = 0; index < text2.length; index += 1) {
3135
+ const char = text2[index];
3136
+ if (inString) {
3137
+ out += char;
3138
+ if (escaped) escaped = false;
3139
+ else if (char === "\\") escaped = true;
3140
+ else if (char === '"') inString = false;
3141
+ continue;
3142
+ }
3143
+ if (char === '"') {
3144
+ inString = true;
3145
+ out += char;
3146
+ continue;
3147
+ }
3148
+ if (char === "/" && text2[index + 1] === "/") {
3149
+ while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
3150
+ index -= 1;
3151
+ continue;
3152
+ }
3153
+ if (char === "/" && text2[index + 1] === "*") {
3154
+ index += 2;
3155
+ while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
3156
+ if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
3157
+ index += 1;
3158
+ }
3159
+ index += 1;
3160
+ continue;
3161
+ }
3162
+ out += char;
3163
+ }
3164
+ return out;
3165
+ }
3166
+ function stripTrailingCommas(text2) {
3167
+ let out = "";
3168
+ let inString = false;
3169
+ let escaped = false;
3170
+ for (let index = 0; index < text2.length; index += 1) {
3171
+ const char = text2[index];
3172
+ if (inString) {
3173
+ out += char;
3174
+ if (escaped) escaped = false;
3175
+ else if (char === "\\") escaped = true;
3176
+ else if (char === '"') inString = false;
3177
+ continue;
3178
+ }
3179
+ if (char === '"') {
3180
+ inString = true;
3181
+ out += char;
3182
+ continue;
3183
+ }
3184
+ if (char === ",") {
3185
+ let next = index + 1;
3186
+ while (next < text2.length && /\s/.test(text2[next])) next += 1;
3187
+ if (text2[next] === "}" || text2[next] === "]") continue;
3188
+ }
3189
+ out += char;
3190
+ }
3191
+ return out;
3192
+ }
3193
+ function summarizeJson(content) {
3194
+ try {
3195
+ const parsed = JSON.parse(stripJsonComments(content));
3196
+ if (Array.isArray(parsed)) {
3197
+ const sample = parsed[0];
3198
+ const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
3199
+ return {
3200
+ shape: "array",
3201
+ itemCount: parsed.length,
3202
+ keys: [],
3203
+ sampleKeys
3204
+ };
3205
+ }
3206
+ if (parsed && typeof parsed === "object") {
3207
+ const keys = Object.keys(parsed).sort();
3208
+ return {
3209
+ shape: "object",
3210
+ itemCount: keys.length,
3211
+ keys: keys.slice(0, 30),
3212
+ sampleKeys: []
3213
+ };
3214
+ }
3215
+ return {
3216
+ shape: typeof parsed,
3217
+ itemCount: null,
3218
+ keys: [],
3219
+ sampleKeys: []
3220
+ };
3221
+ } catch {
3222
+ return {
3223
+ shape: "invalid-json",
3224
+ itemCount: null,
3225
+ keys: [],
3226
+ sampleKeys: []
3227
+ };
3228
+ }
3229
+ }
3230
+ function frontMatterEnd(lines) {
3231
+ if (lines.length < 3 || lines[0].trim() !== "---") return 0;
3232
+ for (let index = 1; index < lines.length; index += 1) {
3233
+ const line = lines[index];
3234
+ const candidate = line.trim();
3235
+ if (candidate === "---" || candidate === "...") {
3236
+ return index > 1 ? index : 0;
3237
+ }
3238
+ if (candidate === "") continue;
3239
+ if (/^#(\s|$)/.test(candidate)) continue;
3240
+ if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
3241
+ if (/^#{1,6}\s+\S/.test(candidate)) return 0;
3242
+ const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
3243
+ const isListItem = /^-(?:(\s|$))/.test(candidate);
3244
+ const isIndented = /^[ \t]/.test(line);
3245
+ if (!isYamlMapping && !isListItem && !isIndented) return 0;
3246
+ }
3247
+ return 0;
3248
+ }
3249
+ function summarizeMarkdown(content) {
3250
+ const headings = [];
3251
+ const frontmatterKeys = [];
3252
+ const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
3253
+ let inFrontmatter = false;
3254
+ let fence = null;
3255
+ const frontMatterEndLine = frontMatterEnd(lines);
3256
+ for (let index = 0; index < lines.length; index++) {
3257
+ const line = lines[index];
3258
+ if (index === 0 && frontMatterEndLine > 0) {
3259
+ inFrontmatter = true;
3260
+ continue;
3261
+ }
3262
+ if (inFrontmatter) {
3263
+ const trimmedFrontmatter = line.trim();
3264
+ if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
3265
+ inFrontmatter = false;
3266
+ continue;
3267
+ }
3268
+ const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
3269
+ if (match) frontmatterKeys.push(match[1]);
3270
+ continue;
3271
+ }
3272
+ const trimmed = line.trim();
3273
+ const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
3274
+ if (fenceMatch) {
3275
+ const run = fenceMatch[1];
3276
+ const rest = fenceMatch[2].trim();
3277
+ if (fence === null) {
3278
+ fence = { marker: run[0], length: run.length };
3279
+ } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
3280
+ fence = null;
3281
+ }
3282
+ continue;
3283
+ }
3284
+ if (fence !== null) continue;
3285
+ const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
3286
+ if (headingMatch) {
3287
+ headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
3288
+ }
3289
+ }
3290
+ return {
3291
+ headings: headings.slice(0, 40),
3292
+ frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
3293
+ };
3294
+ }
3295
+
3066
3296
  // src/tokenize.ts
3067
3297
  var WORD_RUN = /[A-Za-z0-9_]+/g;
3068
3298
  var SINGLE_TOKEN = /[^\sA-Za-z0-9_]/g;
@@ -3173,6 +3403,10 @@ function normalizeResolvedConfig(config) {
3173
3403
  return markResolvedConfig({
3174
3404
  ...config,
3175
3405
  discovery,
3406
+ // A spread copy built before the field existed carries no value; the default applies, and it
3407
+ // is re-validated because the number reaches a rendered artifact.
3408
+ attachmentSlots: resolveAttachmentSlots(config.attachmentSlots),
3409
+ maxParts: resolveMaxParts(config.maxParts),
3176
3410
  includeMonolith: artifacts.monolith,
3177
3411
  secretRules: compileSecretRules(config.secretRules),
3178
3412
  artifacts,
@@ -3219,70 +3453,6 @@ function supportsTypeScriptImports() {
3219
3453
  if (!Number.isFinite(major)) return false;
3220
3454
  return major > 22 || major === 22 && minor >= 6;
3221
3455
  }
3222
- function stripJsonComments(raw) {
3223
- const text2 = raw.replace(/^\uFEFF/, "");
3224
- let out = "";
3225
- let inString = false;
3226
- let escaped = false;
3227
- for (let index = 0; index < text2.length; index += 1) {
3228
- const char = text2[index];
3229
- if (inString) {
3230
- out += char;
3231
- if (escaped) escaped = false;
3232
- else if (char === "\\") escaped = true;
3233
- else if (char === '"') inString = false;
3234
- continue;
3235
- }
3236
- if (char === '"') {
3237
- inString = true;
3238
- out += char;
3239
- continue;
3240
- }
3241
- if (char === "/" && text2[index + 1] === "/") {
3242
- while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
3243
- index -= 1;
3244
- continue;
3245
- }
3246
- if (char === "/" && text2[index + 1] === "*") {
3247
- index += 2;
3248
- while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
3249
- if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
3250
- index += 1;
3251
- }
3252
- index += 1;
3253
- continue;
3254
- }
3255
- out += char;
3256
- }
3257
- return stripTrailingCommas(out);
3258
- }
3259
- function stripTrailingCommas(text2) {
3260
- let out = "";
3261
- let inString = false;
3262
- let escaped = false;
3263
- for (let index = 0; index < text2.length; index += 1) {
3264
- const char = text2[index];
3265
- if (inString) {
3266
- out += char;
3267
- if (escaped) escaped = false;
3268
- else if (char === "\\") escaped = true;
3269
- else if (char === '"') inString = false;
3270
- continue;
3271
- }
3272
- if (char === '"') {
3273
- inString = true;
3274
- out += char;
3275
- continue;
3276
- }
3277
- if (char === ",") {
3278
- let next = index + 1;
3279
- while (next < text2.length && /\s/.test(text2[next])) next += 1;
3280
- if (text2[next] === "}" || text2[next] === "]") continue;
3281
- }
3282
- out += char;
3283
- }
3284
- return out;
3285
- }
3286
3456
  function parseJsonish(raw, file) {
3287
3457
  try {
3288
3458
  return JSON.parse(stripJsonComments(raw));
@@ -3303,8 +3473,9 @@ function describeValue2(value) {
3303
3473
  return `${typeof value} (${String(value)})`;
3304
3474
  }
3305
3475
  var isThenable = (value) => typeof value.then === "function";
3306
- var CONFIG_KEYS = /* @__PURE__ */ new Set([
3476
+ var CONFIG_KEY_NAMES = [
3307
3477
  "artifacts",
3478
+ "attachmentSlots",
3308
3479
  "branch",
3309
3480
  "budgets",
3310
3481
  "changedSince",
@@ -3322,6 +3493,7 @@ var CONFIG_KEYS = /* @__PURE__ */ new Set([
3322
3493
  "layersMode",
3323
3494
  "maxMonolithBytes",
3324
3495
  "maxPartBytes",
3496
+ "maxParts",
3325
3497
  "maxPartTokens",
3326
3498
  "outDir",
3327
3499
  "preset",
@@ -3334,7 +3506,8 @@ var CONFIG_KEYS = /* @__PURE__ */ new Set([
3334
3506
  "skeleton",
3335
3507
  "tmpDir",
3336
3508
  "withDependents"
3337
- ]);
3509
+ ];
3510
+ var CONFIG_KEYS = new Set(CONFIG_KEY_NAMES);
3338
3511
  function assertKnownConfigKeys(value, file) {
3339
3512
  const unknownKeys = Object.keys(value).filter((key) => !CONFIG_KEYS.has(key));
3340
3513
  if (unknownKeys.length === 0) return;
@@ -3519,6 +3692,7 @@ var MIN_MAX_PART_BYTES = 4096;
3519
3692
  var MIN_MAX_PART_TOKENS = MIN_MAX_PART_BYTES / 4;
3520
3693
  var ARTIFACT_NAMES = [
3521
3694
  "readme",
3695
+ "prompt",
3522
3696
  "manifest",
3523
3697
  "parts",
3524
3698
  "navigation",
@@ -3528,6 +3702,7 @@ var ARTIFACT_NAMES = [
3528
3702
  ];
3529
3703
  var DEFAULT_ARTIFACTS = {
3530
3704
  readme: true,
3705
+ prompt: true,
3531
3706
  manifest: true,
3532
3707
  parts: true,
3533
3708
  navigation: true,
@@ -3588,6 +3763,25 @@ function resolveArtifacts(requested, skipped, includeMonolith, monolithOverride,
3588
3763
  }
3589
3764
  return artifacts;
3590
3765
  }
3766
+ var DEFAULT_ATTACHMENT_SLOTS = 10;
3767
+ function resolveAttachmentSlots(value) {
3768
+ if (value === void 0 || value === null) return DEFAULT_ATTACHMENT_SLOTS;
3769
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
3770
+ throw new Error(
3771
+ "attachmentSlots must be a whole number, with 0 meaning no limit (received " + describeValue2(value) + ")."
3772
+ );
3773
+ }
3774
+ return value;
3775
+ }
3776
+ function resolveMaxParts(value) {
3777
+ if (value === void 0 || value === null) return null;
3778
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
3779
+ throw new Error(
3780
+ "maxParts must be a whole number of parts, or null to disable it (received " + describeValue2(value) + ")."
3781
+ );
3782
+ }
3783
+ return value;
3784
+ }
3591
3785
  function strictPositiveInteger(value, fallback, label) {
3592
3786
  if (value === void 0) return fallback;
3593
3787
  if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
@@ -3681,11 +3875,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
3681
3875
  const patterns = [];
3682
3876
  for (const dir of [outDir, tmpDir]) {
3683
3877
  const absolute = path16__namespace.resolve(cwd, dir);
3684
- const relative14 = path16__namespace.relative(cwd, absolute);
3685
- if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
3878
+ const relative15 = path16__namespace.relative(cwd, absolute);
3879
+ if (!relative15 || relative15 === ".." || relative15.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative15)) {
3686
3880
  continue;
3687
3881
  }
3688
- patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
3882
+ patterns.push(`${relative15.replace(/\\/g, "/")}/**`);
3689
3883
  }
3690
3884
  return patterns;
3691
3885
  }
@@ -3966,6 +4160,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
3966
4160
  "maxMonolithBytes"
3967
4161
  ),
3968
4162
  includeSensitiveFiles,
4163
+ attachmentSlots: resolveAttachmentSlots(
4164
+ cliOptions?.attachmentSlots ?? userConfig?.attachmentSlots
4165
+ ),
4166
+ maxParts: resolveMaxParts(cliOptions?.maxParts ?? userConfig?.maxParts),
3969
4167
  ...changedSince === void 0 ? {} : { changedSince },
3970
4168
  ...staged ? { staged } : {},
3971
4169
  ...withDependents ? { withDependents } : {},
@@ -4048,6 +4246,9 @@ function configDigest(config) {
4048
4246
  includeMonolith: config.includeMonolith,
4049
4247
  maxMonolithBytes: config.maxMonolithBytes ?? null,
4050
4248
  includeSensitiveFiles: config.includeSensitiveFiles,
4249
+ // Only when the experimental mode is on: `null` is the off switch, and writing it into the
4250
+ // material would change the digest of every snapshot taken before the setting existed.
4251
+ ...config.maxParts === null ? {} : { maxParts: config.maxParts },
4051
4252
  artifacts: config.artifacts,
4052
4253
  include: config.include,
4053
4254
  excludePatterns: config.excludePatterns,
@@ -4252,8 +4453,8 @@ function tsconfigPathsFor(cwd) {
4252
4453
  return value;
4253
4454
  }
4254
4455
  function repositoryRelative(cwd, target) {
4255
- const relative14 = path16__namespace.relative(cwd, target).replace(/\\/g, "/");
4256
- return relative14.length === 0 || !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14) ? relative14 : null;
4456
+ const relative15 = path16__namespace.relative(cwd, target).replace(/\\/g, "/");
4457
+ return relative15.length === 0 || !relative15.startsWith("..") && !path16__namespace.isAbsolute(relative15) ? relative15 : null;
4257
4458
  }
4258
4459
  function rememberFirst(map, key, value) {
4259
4460
  if (!map.has(key)) map.set(key, value);
@@ -4651,6 +4852,8 @@ function summarizeTypeScriptSource(relativePath, content) {
4651
4852
  if (cjsExports.length > 0) {
4652
4853
  summary.exportsKind = summary.exports.length > 0 ? "mixed" : "cjs";
4653
4854
  summary.exports.push(...cjsExports);
4855
+ } else if (summary.exports.length > 0) {
4856
+ summary.exportsKind = "esm";
4654
4857
  }
4655
4858
  const dedupeSorted2 = (values) => Array.from(new Set(values)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
4656
4859
  summary.directives = dedupeSorted2(summary.directives);
@@ -5215,9 +5418,9 @@ var rubyProfile = {
5215
5418
  eachLine(content, (line) => {
5216
5419
  const trimmed = line.trim();
5217
5420
  if (!trimmed || trimmed.startsWith("#")) return;
5218
- const relative14 = REQUIRE_RELATIVE.exec(trimmed);
5219
- if (relative14) {
5220
- summary.imports.push(`./${relative14[1]}`);
5421
+ const relative15 = REQUIRE_RELATIVE.exec(trimmed);
5422
+ if (relative15) {
5423
+ summary.imports.push(`./${relative15[1]}`);
5221
5424
  return;
5222
5425
  }
5223
5426
  const required = REQUIRE.exec(trimmed);
@@ -5879,6 +6082,16 @@ function wouldNowBeIncluded(cwd, relativePath) {
5879
6082
  return false;
5880
6083
  }
5881
6084
  }
6085
+ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
6086
+ "large-file-budget",
6087
+ "part-budget",
6088
+ "section-metadata"
6089
+ ]);
6090
+ function isConfinedRelative(value) {
6091
+ if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
6092
+ if (path16__namespace.isAbsolute(value)) return false;
6093
+ return !value.split("/").includes("..");
6094
+ }
5882
6095
  function describeManifestShapeProblem(value) {
5883
6096
  if (!value || typeof value !== "object" || Array.isArray(value)) return "not a JSON object";
5884
6097
  const candidate = value;
@@ -5944,6 +6157,68 @@ function describeManifestShapeProblem(value) {
5944
6157
  if (!candidate.kinds || typeof candidate.kinds !== "object" || Array.isArray(candidate.kinds)) {
5945
6158
  return 'missing "kinds" object';
5946
6159
  }
6160
+ const incompleteCount = counts.incompleteCount;
6161
+ if (typeof incompleteCount !== "number" || !Number.isSafeInteger(incompleteCount) || incompleteCount < 0) {
6162
+ return "missing numeric `counts.incompleteCount`";
6163
+ }
6164
+ const incomplete = candidate.incomplete;
6165
+ if (!Array.isArray(incomplete)) return 'missing "incomplete" array';
6166
+ if (incompleteCount !== incomplete.length) {
6167
+ return "`counts.incompleteCount` does not match the length of `incomplete`";
6168
+ }
6169
+ for (const entry of incomplete) {
6170
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
6171
+ return 'an "incomplete" entry is not an object';
6172
+ }
6173
+ const fields = entry;
6174
+ const relativePath = fields.relativePath;
6175
+ if (typeof relativePath !== "string" || relativePath.length === 0) {
6176
+ return 'an "incomplete" entry has no "relativePath"';
6177
+ }
6178
+ if (!isConfinedRelative(relativePath)) {
6179
+ return 'an "incomplete" entry "relativePath" must stay inside the repository';
6180
+ }
6181
+ if (typeof fields.part !== "string" || fields.part.trim() === "") {
6182
+ return 'an "incomplete" entry has no "part"';
6183
+ }
6184
+ if (typeof fields.reason !== "string" || !TRUNCATION_REASONS.has(fields.reason)) {
6185
+ return 'an "incomplete" entry has an unknown "reason"';
6186
+ }
6187
+ for (const key of ["omittedLines", "includedLines", "lines"]) {
6188
+ const value2 = fields[key];
6189
+ if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) {
6190
+ return `an "incomplete" entry "${key}" must be a non-negative integer`;
6191
+ }
6192
+ }
6193
+ const lines = fields.lines;
6194
+ if (fields.includedLines > lines) {
6195
+ return 'an "incomplete" entry "includedLines" exceeds its "lines"';
6196
+ }
6197
+ const ranges = fields.omittedRanges;
6198
+ if (!Array.isArray(ranges)) return 'an "incomplete" entry has no "omittedRanges" array';
6199
+ let previousEnd = 0;
6200
+ let omitted = 0;
6201
+ for (const range of ranges) {
6202
+ if (!Array.isArray(range) || range.length !== 2) {
6203
+ return 'an "incomplete" entry "omittedRanges" must hold [from, to] pairs';
6204
+ }
6205
+ const [from, to] = range;
6206
+ if (typeof from !== "number" || typeof to !== "number" || !Number.isSafeInteger(from) || !Number.isSafeInteger(to)) {
6207
+ return 'an "incomplete" entry "omittedRanges" must hold integer pairs';
6208
+ }
6209
+ if (from < 1 || to < from || to > lines) {
6210
+ return `an "incomplete" entry records an omitted range ${from}-${to}, outside 1-${lines}`;
6211
+ }
6212
+ if (from <= previousEnd) {
6213
+ return 'an "incomplete" entry "omittedRanges" must be sorted and non-overlapping';
6214
+ }
6215
+ previousEnd = to;
6216
+ omitted += to - from + 1;
6217
+ }
6218
+ if (omitted !== fields.omittedLines) {
6219
+ return "`omittedLines` does not match the ranges it records";
6220
+ }
6221
+ }
5947
6222
  }
5948
6223
  if (!Array.isArray(candidate.files)) return 'missing "files" array';
5949
6224
  for (const entry of candidate.files) {
@@ -6057,11 +6332,57 @@ function validateSnapshot(configInput) {
6057
6332
  );
6058
6333
  }
6059
6334
  const manifestFileMap = /* @__PURE__ */ new Map();
6335
+ const manifestFilesByPath = /* @__PURE__ */ new Map();
6060
6336
  for (const file of manifest.files) {
6061
6337
  if (file && typeof file.relativePath === "string") {
6062
6338
  manifestFileMap.set(file.relativePath, file.hashSha256);
6339
+ manifestFilesByPath.set(file.relativePath, file);
6063
6340
  }
6064
6341
  }
6342
+ const incompleteRecords = manifest.incomplete ?? [];
6343
+ const incompleteness = /* @__PURE__ */ new Map();
6344
+ for (const record of incompleteRecords) {
6345
+ incompleteness.set(record.relativePath, record);
6346
+ const label = maskedPath(record.relativePath, config.secretRules);
6347
+ const file = manifestFilesByPath.get(record.relativePath);
6348
+ if (file === void 0) {
6349
+ drift.partIssues.push({
6350
+ part: "(manifest)",
6351
+ issue: `${label} is in incomplete[] but not in files[]`
6352
+ });
6353
+ continue;
6354
+ }
6355
+ if (file.part !== record.part) {
6356
+ drift.partIssues.push({
6357
+ part: "(manifest)",
6358
+ issue: `${label} is recorded in part ${String(record.part)} in incomplete[] and part ${String(file.part)} in files[]`
6359
+ });
6360
+ }
6361
+ if (file.truncationReason !== record.reason) {
6362
+ drift.partIssues.push({
6363
+ part: "(manifest)",
6364
+ issue: `${label} records truncationReason ${String(file.truncationReason)} in files[] and reason ${String(record.reason)} in incomplete[]`
6365
+ });
6366
+ }
6367
+ const recordedRanges = file.omittedRanges ?? [];
6368
+ const rangesAgree = recordedRanges.length === record.omittedRanges.length && recordedRanges.every(
6369
+ ([from, to], index) => record.omittedRanges[index][0] === from && record.omittedRanges[index][1] === to
6370
+ );
6371
+ if (!rangesAgree || file.includedLines !== record.includedLines || file.lines !== record.lines) {
6372
+ drift.partIssues.push({
6373
+ part: "(manifest)",
6374
+ issue: `${label} records different omission numbers in files[] and incomplete[]`
6375
+ });
6376
+ }
6377
+ }
6378
+ for (const file of manifest.files) {
6379
+ if (file.truncationReason === void 0) continue;
6380
+ if (incompleteness.has(file.relativePath)) continue;
6381
+ drift.partIssues.push({
6382
+ part: "(manifest)",
6383
+ issue: `${maskedPath(file.relativePath, config.secretRules)} records a truncationReason but is missing from incomplete[]`
6384
+ });
6385
+ }
6065
6386
  const skippedReasons = /* @__PURE__ */ new Map();
6066
6387
  for (const entry of manifest.skipped) {
6067
6388
  if (entry && typeof entry.path === "string" && typeof entry.reason === "string") {
@@ -6118,7 +6439,7 @@ function validateSnapshot(configInput) {
6118
6439
  // snapshot was reported as drifting.
6119
6440
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6120
6441
  (directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
6121
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
6442
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
6122
6443
  });
6123
6444
  for (const diskFile of collection.files) {
6124
6445
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -6519,7 +6840,8 @@ function validateSnapshot(configInput) {
6519
6840
  );
6520
6841
  }
6521
6842
  }
6522
- if (manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
6843
+ const ceilingDerivedByMaxParts = (manifest.config?.maxParts ?? null) !== null;
6844
+ if (!ceilingDerivedByMaxParts && manifest.budgets && manifest.budgets.maxPartBytes !== config.maxPartBytes) {
6523
6845
  totalsMismatches.push(
6524
6846
  `budgets.maxPartBytes: manifest ${manifest.budgets.maxPartBytes} vs current ${config.maxPartBytes}`
6525
6847
  );
@@ -6548,6 +6870,7 @@ function validateSnapshot(configInput) {
6548
6870
  }
6549
6871
  const declaredArtifacts = [
6550
6872
  ["README.md", manifest.artifacts?.readme],
6873
+ ["PROMPT.md", manifest.artifacts?.prompt],
6551
6874
  ["reports/navigation.md", manifest.artifacts?.navigation],
6552
6875
  ["reports/project-tree.md", manifest.artifacts?.projectTree],
6553
6876
  ["reports/audit.md", manifest.artifacts?.audit],
@@ -6574,8 +6897,8 @@ function validateSnapshot(configInput) {
6574
6897
  const target = match[1].split("#")[0];
6575
6898
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
6576
6899
  const resolved = path16__namespace.resolve(snapshotDir, "reports", target);
6577
- const relative14 = path16__namespace.relative(snapshotDir, resolved);
6578
- if (relative14.startsWith("..") || path16__namespace.isAbsolute(relative14) || !fs15__namespace.existsSync(resolved)) {
6900
+ const relative15 = path16__namespace.relative(snapshotDir, resolved);
6901
+ if (relative15.startsWith("..") || path16__namespace.isAbsolute(relative15) || !fs15__namespace.existsSync(resolved)) {
6579
6902
  drift.partIssues.push({
6580
6903
  part: key,
6581
6904
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -6671,19 +6994,19 @@ function side(manifest) {
6671
6994
  function shortDigest(value) {
6672
6995
  return value === null ? "not recorded" : `${value.slice(0, 12)}\u2026`;
6673
6996
  }
6674
- function describeLayerChanges(before, after) {
6997
+ function describeLayerChanges(before, after, secretRules) {
6675
6998
  const names = Array.from(/* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])).sort();
6676
6999
  const changes = [];
6677
7000
  for (const name of names) {
6678
7001
  const was = before[name] ?? 0;
6679
7002
  const now = after[name] ?? 0;
6680
7003
  if (was === now) continue;
6681
- const label = findSecretInPath(name)?.masked ?? name;
7004
+ const label = findSecretInPath(name, secretRules)?.masked ?? name;
6682
7005
  changes.push(`layer "${label}": ${was} file(s) \u2192 ${now} file(s)`);
6683
7006
  }
6684
7007
  return changes;
6685
7008
  }
6686
- function describePartChanges(before, after) {
7009
+ function describePartChanges(before, after, secretRules) {
6687
7010
  const index = (parts) => {
6688
7011
  const map = /* @__PURE__ */ new Map();
6689
7012
  for (const part of parts) {
@@ -6693,7 +7016,7 @@ function describePartChanges(before, after) {
6693
7016
  };
6694
7017
  const left = index(before);
6695
7018
  const right = index(after);
6696
- const label = (filename) => findSecretInPath(filename)?.masked ?? filename;
7019
+ const label = (filename) => findSecretInPath(filename, secretRules)?.masked ?? filename;
6697
7020
  const changes = [];
6698
7021
  for (const [filename, part] of right) {
6699
7022
  const previous = left.get(filename);
@@ -6721,7 +7044,15 @@ function describePartChanges(before, after) {
6721
7044
  }
6722
7045
  return changes;
6723
7046
  }
6724
- function describePayloadDiff(before, after, sourceFilesIdentical) {
7047
+ function maskLayerNames(layers, secretRules) {
7048
+ return Object.fromEntries(
7049
+ Object.entries(layers ?? {}).map(([name, count]) => [
7050
+ findSecretInPath(name, secretRules)?.masked ?? name,
7051
+ count
7052
+ ])
7053
+ );
7054
+ }
7055
+ function describePayloadDiff(before, after, sourceFilesIdentical, secretRules) {
6725
7056
  const generatorBefore = before.generator?.version ?? "unknown";
6726
7057
  const generatorAfter = after.generator?.version ?? "unknown";
6727
7058
  const digestBefore = typeof before.config?.digest === "string" ? before.config.digest : null;
@@ -6734,35 +7065,43 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
6734
7065
  const configurationDiffers = generatorDiffers || digestDiffers || schemaDiffers;
6735
7066
  const fingerprintDiffers = before.fingerprint !== after.fingerprint;
6736
7067
  const partsDiffer = before.counts.partsCount !== after.counts.partsCount;
6737
- const partChanges = describePartChanges(before.parts ?? [], after.parts ?? []);
6738
- const layerChanges = describeLayerChanges(before.layers ?? {}, after.layers ?? {});
7068
+ const partChanges = describePartChanges(before.parts ?? [], after.parts ?? [], secretRules);
7069
+ const layerChanges = describeLayerChanges(before.layers ?? {}, after.layers ?? {}, secretRules);
6739
7070
  const reasons = [];
7071
+ const codes = [];
6740
7072
  if (schemaDiffers) {
7073
+ codes.push("schema-version");
6741
7074
  reasons.push(
6742
7075
  `schema version ${schemaBefore} \u2192 ${schemaAfter} (the two manifests describe different formats)`
6743
7076
  );
6744
7077
  }
6745
7078
  if (digestDiffers) {
7079
+ codes.push("config-digest");
6746
7080
  reasons.push(
6747
7081
  `configuration digest ${shortDigest(digestBefore)} \u2192 ${shortDigest(digestAfter)} (budgets, preview thresholds, redaction rules and artifact selection all count)`
6748
7082
  );
6749
7083
  } else if (digestBefore === null || digestAfter === null) {
6750
7084
  const missing = digestBefore === null && digestAfter !== null ? "before" : digestAfter === null && digestBefore !== null ? "after" : "both";
7085
+ codes.push("config-digest-missing");
6751
7086
  reasons.push(
6752
7087
  `configuration digest not recorded on the ${missing} side (manifest written before 4.0.5); compared the content fingerprint and part count instead`
6753
7088
  );
6754
7089
  }
6755
7090
  if (generatorDiffers) {
7091
+ codes.push("generator");
6756
7092
  reasons.push(`generator ${generatorBefore} \u2192 ${generatorAfter}`);
6757
7093
  }
6758
7094
  if (fingerprintDiffers && (sourceFilesIdentical || configurationDiffers)) {
7095
+ codes.push("fingerprint");
6759
7096
  reasons.push(
6760
7097
  `content fingerprint ${shortDigest(before.fingerprint)} \u2192 ${shortDigest(after.fingerprint)}` + (sourceFilesIdentical ? " (same source files, packed or configured differently)" : "")
6761
7098
  );
6762
7099
  }
6763
7100
  if (partsDiffer) {
7101
+ codes.push("parts-count");
6764
7102
  reasons.push(`${before.counts.partsCount} part(s) \u2192 ${after.counts.partsCount} part(s)`);
6765
7103
  }
7104
+ for (let index = 0; index < layerChanges.length; index += 1) codes.push("layer-changed");
6766
7105
  reasons.push(...layerChanges);
6767
7106
  return {
6768
7107
  sourceFilesIdentical,
@@ -6774,8 +7113,12 @@ function describePayloadDiff(before, after, sourceFilesIdentical) {
6774
7113
  partsCount: { before: before.counts.partsCount, after: after.counts.partsCount },
6775
7114
  schemaVersion: { before: schemaBefore, after: schemaAfter },
6776
7115
  partsManifest: { differs: partChanges.length > 0, changes: partChanges },
6777
- layers: { before: { ...before.layers ?? {} }, after: { ...after.layers ?? {} } },
6778
- reasons
7116
+ // The layer maps are printed and serialized, so a layer named after a project token leaks the
7117
+ // token here even though every reason line above is masked. Found while testing the rules
7118
+ // parameter: masking the prose and not the data it describes is the same bug one layer down.
7119
+ layers: { before: maskLayerNames(before.layers, secretRules), after: maskLayerNames(after.layers, secretRules) },
7120
+ reasons,
7121
+ codes
6779
7122
  };
6780
7123
  }
6781
7124
  function hashMap(manifest) {
@@ -6814,10 +7157,10 @@ function comparableProblem(value) {
6814
7157
  function assertUsableManifest(value, label) {
6815
7158
  const problem = comparableProblem(value);
6816
7159
  if (problem) {
6817
- throw new Error(`The ${label} manifest is not a snapshot manifest this tool wrote: ${problem}.`);
7160
+ throw new Error(`The ${label} manifest is not a snapshot manifest: ${problem}.`);
6818
7161
  }
6819
7162
  }
6820
- function compareManifests(before, after) {
7163
+ function compareManifests(before, after, secretRules) {
6821
7164
  assertUsableManifest(before, "before");
6822
7165
  assertUsableManifest(after, "after");
6823
7166
  const left = hashMap(before);
@@ -6837,8 +7180,8 @@ function compareManifests(before, after) {
6837
7180
  }
6838
7181
  const sort = (values) => values.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
6839
7182
  const sourceFilesIdentical = added.length === 0 && removed.length === 0 && changed.length === 0;
6840
- const payload = describePayloadDiff(before, after, sourceFilesIdentical);
6841
- const mask = (values) => values.map((value) => findSecretInPath(value)?.masked ?? value);
7183
+ const payload = describePayloadDiff(before, after, sourceFilesIdentical, secretRules);
7184
+ const mask = (values) => values.map((value) => findSecretInPath(value, secretRules)?.masked ?? value);
6842
7185
  return {
6843
7186
  before: side(before),
6844
7187
  after: side(after),
@@ -6872,7 +7215,7 @@ function loadManifest(target) {
6872
7215
  const problem = describeManifestShapeProblem(parsed);
6873
7216
  if (problem) {
6874
7217
  throw new Error(
6875
- `${manifestPath} is not a usable snapshot manifest: ${problem}. Point diff at a manifest.json written by \`generate\` (or at the directory that holds it).`
7218
+ `${manifestPath} is not a snapshot manifest: ${problem}. Point diff at a manifest.json written by \`generate\` (or at the directory that holds it).`
6876
7219
  );
6877
7220
  }
6878
7221
  return parsed;
@@ -7139,23 +7482,23 @@ function describeMatcher(matcher) {
7139
7482
  function normalizeTarget(cwd, target) {
7140
7483
  const resolvedCwd = path16__namespace.resolve(cwd);
7141
7484
  const absolute = path16__namespace.resolve(resolvedCwd, target);
7142
- const relative14 = path16__namespace.relative(resolvedCwd, absolute);
7143
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
7485
+ const relative15 = path16__namespace.relative(resolvedCwd, absolute);
7486
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative15)) {
7144
7487
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7145
7488
  }
7146
- return { relative: relative14.split(path16__namespace.sep).join("/"), outsideRoot: false };
7489
+ return { relative: relative15.split(path16__namespace.sep).join("/"), outsideRoot: false };
7147
7490
  }
7148
7491
  function findRuleMatch(rules, relativePath) {
7149
7492
  return rules.find(
7150
7493
  (rule) => matchRule(relativePath, rule.match)
7151
7494
  );
7152
7495
  }
7153
- function findRecordedAncestor(skipped, relative14, maskedPath2) {
7496
+ function findRecordedAncestor(skipped, relative15, maskedPath2) {
7154
7497
  let nearest;
7155
7498
  for (const record of skipped) {
7156
7499
  const ancestorPath = record.path;
7157
7500
  if (ancestorPath.length === 0) continue;
7158
- const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7501
+ const isAncestor = relative15.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7159
7502
  if (!isAncestor) continue;
7160
7503
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
7161
7504
  }
@@ -7171,8 +7514,8 @@ function readManifest2(config) {
7171
7514
  }
7172
7515
  function explainPath(config, target) {
7173
7516
  const normalized = normalizeTarget(config.cwd, target);
7174
- const relative14 = normalized.relative;
7175
- const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
7517
+ const relative15 = normalized.relative;
7518
+ const maskedPath2 = findSecretInPath(relative15, config.secretRules)?.masked ?? relative15;
7176
7519
  if (normalized.outsideRoot) {
7177
7520
  return {
7178
7521
  path: maskedPath2,
@@ -7182,7 +7525,7 @@ function explainPath(config, target) {
7182
7525
  detail: "path resolves outside the configured repository root and was not inspected"
7183
7526
  };
7184
7527
  }
7185
- const absolute = path16__namespace.join(config.cwd, relative14);
7528
+ const absolute = path16__namespace.join(config.cwd, relative15);
7186
7529
  const result = {
7187
7530
  path: maskedPath2,
7188
7531
  exists: fs15__namespace.existsSync(absolute),
@@ -7200,11 +7543,11 @@ function explainPath(config, target) {
7200
7543
  // that is only missing because the walker dropped the tool's own output directory.
7201
7544
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7202
7545
  (directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
7203
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
7546
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
7204
7547
  });
7205
- if (!collection.files.includes(relative14)) {
7548
+ if (!collection.files.includes(relative15)) {
7206
7549
  const record = collection.skipped.find(
7207
- (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
7550
+ (entry2) => entry2.path === relative15 || entry2.path === maskedPath2
7208
7551
  );
7209
7552
  if (record) {
7210
7553
  result.reason = record.reason;
@@ -7213,7 +7556,7 @@ function explainPath(config, target) {
7213
7556
  result.reason = "missing";
7214
7557
  result.detail = "no such file or directory, relative to the configured cwd";
7215
7558
  } else {
7216
- const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
7559
+ const ancestor = findRecordedAncestor(collection.skipped, relative15, maskedPath2);
7217
7560
  if (ancestor) {
7218
7561
  result.reason = ancestor.reason;
7219
7562
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -7233,11 +7576,11 @@ function explainPath(config, target) {
7233
7576
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
7234
7577
  ...config.staged === true ? { staged: true } : {}
7235
7578
  });
7236
- inScope = scope.paths.has(relative14);
7579
+ inScope = scope.paths.has(relative15);
7237
7580
  if (!inScope && config.withDependents === true) {
7238
7581
  inScope = importsChangedFile(
7239
- relative14,
7240
- importsOfFile(relative14, absolute),
7582
+ relative15,
7583
+ importsOfFile(relative15, absolute),
7241
7584
  scope.paths,
7242
7585
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
7243
7586
  );
@@ -7295,12 +7638,12 @@ function explainPath(config, target) {
7295
7638
  result.bytes = buffer.length;
7296
7639
  result.lines = countLines(text2);
7297
7640
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
7298
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
7641
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative15);
7299
7642
  result.secretCount = findings.length;
7300
7643
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
7301
7644
  let inclusionMode = "full";
7302
- if (config.skeleton === true && isSkeletonizable(relative14)) {
7303
- const skeleton = skeletonizeTypeScript(text2, relative14);
7645
+ if (config.skeleton === true && isSkeletonizable(relative15)) {
7646
+ const skeleton = skeletonizeTypeScript(text2, relative15);
7304
7647
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
7305
7648
  }
7306
7649
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -7309,15 +7652,15 @@ function explainPath(config, target) {
7309
7652
  }
7310
7653
  result.inclusionMode = inclusionMode;
7311
7654
  }
7312
- result.layer = classifyLayer(relative14, config.layers);
7313
- result.kind = classifyKind(relative14, config.kinds);
7314
- result.language = detectLanguage(relative14);
7315
- const layerRule = findRuleMatch(config.layers, relative14);
7655
+ result.layer = classifyLayer(relative15, config.layers);
7656
+ result.kind = classifyKind(relative15, config.kinds);
7657
+ result.language = detectLanguage(relative15);
7658
+ const layerRule = findRuleMatch(config.layers, relative15);
7316
7659
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
7317
- const kindRule = findRuleMatch(config.kinds, relative14);
7660
+ const kindRule = findRuleMatch(config.kinds, relative15);
7318
7661
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
7319
7662
  const manifest = readManifest2(config);
7320
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
7663
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative15) : void 0;
7321
7664
  result.part = entry?.part ?? null;
7322
7665
  return result;
7323
7666
  }
@@ -7342,190 +7685,18 @@ function renderExplainText(result) {
7342
7685
  "part",
7343
7686
  result.part ?? "(not in the last snapshot; run generate)"
7344
7687
  )
7345
- );
7346
- if (result.inclusionMode) lines.push(row("inclusion", result.inclusionMode));
7347
- if (result.encoding) lines.push(row("encoding", result.encoding));
7348
- lines.push(
7349
- row(
7350
- "secrets",
7351
- result.secretCount ? `${result.secretCount} finding(s): ${Array.from(
7352
- new Set((result.secrets ?? []).flatMap((secret) => secret.rules))
7353
- ).join(", ")}` : "none"
7354
- )
7355
- );
7356
- return lines.join("\n");
7357
- }
7358
-
7359
- // src/ast/structured.ts
7360
- function stripJsonComments2(content) {
7361
- const text2 = content.replace(/^\uFEFF/, "");
7362
- const withoutComments = stripComments(text2);
7363
- return stripTrailingCommas2(withoutComments);
7364
- }
7365
- function stripComments(text2) {
7366
- let out = "";
7367
- let inString = false;
7368
- let escaped = false;
7369
- for (let index = 0; index < text2.length; index += 1) {
7370
- const char = text2[index];
7371
- if (inString) {
7372
- out += char;
7373
- if (escaped) escaped = false;
7374
- else if (char === "\\") escaped = true;
7375
- else if (char === '"') inString = false;
7376
- continue;
7377
- }
7378
- if (char === '"') {
7379
- inString = true;
7380
- out += char;
7381
- continue;
7382
- }
7383
- if (char === "/" && text2[index + 1] === "/") {
7384
- while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
7385
- index -= 1;
7386
- continue;
7387
- }
7388
- if (char === "/" && text2[index + 1] === "*") {
7389
- index += 2;
7390
- while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
7391
- if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
7392
- index += 1;
7393
- }
7394
- index += 1;
7395
- continue;
7396
- }
7397
- out += char;
7398
- }
7399
- return out;
7400
- }
7401
- function stripTrailingCommas2(text2) {
7402
- let out = "";
7403
- let inString = false;
7404
- let escaped = false;
7405
- for (let index = 0; index < text2.length; index += 1) {
7406
- const char = text2[index];
7407
- if (inString) {
7408
- out += char;
7409
- if (escaped) escaped = false;
7410
- else if (char === "\\") escaped = true;
7411
- else if (char === '"') inString = false;
7412
- continue;
7413
- }
7414
- if (char === '"') {
7415
- inString = true;
7416
- out += char;
7417
- continue;
7418
- }
7419
- if (char === ",") {
7420
- let next = index + 1;
7421
- while (next < text2.length && /\s/.test(text2[next])) next += 1;
7422
- if (text2[next] === "}" || text2[next] === "]") continue;
7423
- }
7424
- out += char;
7425
- }
7426
- return out;
7427
- }
7428
- function summarizeJson(content) {
7429
- try {
7430
- const parsed = JSON.parse(stripJsonComments2(content));
7431
- if (Array.isArray(parsed)) {
7432
- const sample = parsed[0];
7433
- const sampleKeys = sample && typeof sample === "object" && !Array.isArray(sample) ? Object.keys(sample).slice(0, 10).sort() : [];
7434
- return {
7435
- shape: "array",
7436
- itemCount: parsed.length,
7437
- keys: [],
7438
- sampleKeys
7439
- };
7440
- }
7441
- if (parsed && typeof parsed === "object") {
7442
- const keys = Object.keys(parsed).sort();
7443
- return {
7444
- shape: "object",
7445
- itemCount: keys.length,
7446
- keys: keys.slice(0, 30),
7447
- sampleKeys: []
7448
- };
7449
- }
7450
- return {
7451
- shape: typeof parsed,
7452
- itemCount: null,
7453
- keys: [],
7454
- sampleKeys: []
7455
- };
7456
- } catch {
7457
- return {
7458
- shape: "invalid-json",
7459
- itemCount: null,
7460
- keys: [],
7461
- sampleKeys: []
7462
- };
7463
- }
7464
- }
7465
- function frontMatterEnd(lines) {
7466
- if (lines.length < 3 || lines[0].trim() !== "---") return 0;
7467
- for (let index = 1; index < lines.length; index += 1) {
7468
- const line = lines[index];
7469
- const candidate = line.trim();
7470
- if (candidate === "---" || candidate === "...") {
7471
- return index > 1 ? index : 0;
7472
- }
7473
- if (candidate === "") continue;
7474
- if (/^#(\s|$)/.test(candidate)) continue;
7475
- if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
7476
- if (/^#{1,6}\s+\S/.test(candidate)) return 0;
7477
- const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
7478
- const isListItem = /^-(?:(\s|$))/.test(candidate);
7479
- const isIndented = /^[ \t]/.test(line);
7480
- if (!isYamlMapping && !isListItem && !isIndented) return 0;
7481
- }
7482
- return 0;
7483
- }
7484
- function summarizeMarkdown(content) {
7485
- const headings = [];
7486
- const frontmatterKeys = [];
7487
- const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
7488
- let inFrontmatter = false;
7489
- let fence = null;
7490
- const frontMatterEndLine = frontMatterEnd(lines);
7491
- for (let index = 0; index < lines.length; index++) {
7492
- const line = lines[index];
7493
- if (index === 0 && frontMatterEndLine > 0) {
7494
- inFrontmatter = true;
7495
- continue;
7496
- }
7497
- if (inFrontmatter) {
7498
- const trimmedFrontmatter = line.trim();
7499
- if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
7500
- inFrontmatter = false;
7501
- continue;
7502
- }
7503
- const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
7504
- if (match) frontmatterKeys.push(match[1]);
7505
- continue;
7506
- }
7507
- const trimmed = line.trim();
7508
- const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
7509
- if (fenceMatch) {
7510
- const run = fenceMatch[1];
7511
- const rest = fenceMatch[2].trim();
7512
- if (fence === null) {
7513
- fence = { marker: run[0], length: run.length };
7514
- } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
7515
- fence = null;
7516
- }
7517
- continue;
7518
- }
7519
- if (fence !== null) continue;
7520
- const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
7521
- if (headingMatch) {
7522
- headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
7523
- }
7524
- }
7525
- return {
7526
- headings: headings.slice(0, 40),
7527
- frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
7528
- };
7688
+ );
7689
+ if (result.inclusionMode) lines.push(row("inclusion", result.inclusionMode));
7690
+ if (result.encoding) lines.push(row("encoding", result.encoding));
7691
+ lines.push(
7692
+ row(
7693
+ "secrets",
7694
+ result.secretCount ? `${result.secretCount} finding(s): ${Array.from(
7695
+ new Set((result.secrets ?? []).flatMap((secret) => secret.rules))
7696
+ ).join(", ")}` : "none"
7697
+ )
7698
+ );
7699
+ return lines.join("\n");
7529
7700
  }
7530
7701
  function decodeGitignore(buffer) {
7531
7702
  const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
@@ -7628,6 +7799,7 @@ var DEFAULT_ANSWERS = {
7628
7799
  sarif: false,
7629
7800
  artifacts: {
7630
7801
  readme: true,
7802
+ prompt: true,
7631
7803
  manifest: true,
7632
7804
  parts: true,
7633
7805
  navigation: true,
@@ -7736,10 +7908,15 @@ function renderConfig(answers) {
7736
7908
  // Set true to drop the built-in rules above and keep only customPatterns.
7737
7909
  disableDefaultPatterns: false,
7738
7910
  },
7911
+ // The library spelling of the same list, accepted here too so a config file can
7912
+ // express what a caller passes in code: an array of { rule, pattern } or a bare
7913
+ // RegExp. Use \`secrets.customPatterns\` above unless you are porting code.
7914
+ // secretRules: [],
7739
7915
 
7740
7916
  // \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
7741
7917
  artifacts: {
7742
7918
  readme: ${artifacts.readme}, // README.md
7919
+ prompt: ${artifacts.prompt}, // PROMPT.md \u2014 the instruction sheet a model is given
7743
7920
  manifest: ${artifacts.manifest}, // manifest.json \u2014 required by validate and report
7744
7921
  parts: ${artifacts.parts}, // parts/part-XXX.md
7745
7922
  navigation: ${artifacts.navigation}, // reports/navigation.md
@@ -7755,6 +7932,11 @@ function renderConfig(answers) {
7755
7932
  includeMonolith: ${artifacts.monolith},
7756
7933
 
7757
7934
  // \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
7935
+ // Files your destination accepts in one message, used by PROMPT.md to plan the delivery.
7936
+ // attachmentSlots: 10,
7937
+ // Experimental: grow the per-part budget until the snapshot fits this many parts, instead of
7938
+ // adding a part as the code grows. The plan in PROMPT.md becomes a fixed-length attachment list.
7939
+ // maxParts: 10,
7758
7940
  // afterGenerate: (manifest) => { /* write your own artifact */ }
7759
7941
  hooks: {},
7760
7942
  };
@@ -7923,7 +8105,7 @@ function keyReader(input) {
7923
8105
  next() {
7924
8106
  const queued = queue.shift();
7925
8107
  if (queued) return Promise.resolve(queued);
7926
- return new Promise((resolve11) => waiters.push(resolve11));
8108
+ return new Promise((resolve12) => waiters.push(resolve12));
7927
8109
  },
7928
8110
  close() {
7929
8111
  input.off("keypress", onKey);
@@ -8141,7 +8323,7 @@ var CONFIG_CANDIDATES = [
8141
8323
  ".snapshotrc"
8142
8324
  ];
8143
8325
  function parsePackageJson(raw) {
8144
- const parsed = JSON.parse(stripJsonComments2(raw));
8326
+ const parsed = JSON.parse(stripJsonComments(raw));
8145
8327
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
8146
8328
  throw new Error("package.json is not a JSON object");
8147
8329
  }
@@ -8352,7 +8534,18 @@ function updatePackageJson(cwd, notes) {
8352
8534
  writeFileOrExplain(packagePath, serializePackageJson(raw, parsed));
8353
8535
  return { scripts: added, dependency };
8354
8536
  }
8355
- var GITIGNORE_ENTRIES = ["/snapshot/", "/snapshot.tmp/"];
8537
+ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
8538
+ const entries = [];
8539
+ for (const directory of [outDir, tmpDir]) {
8540
+ if (directory === null) continue;
8541
+ const relative15 = path16__namespace.relative(cwd, path16__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
8542
+ if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path16__namespace.isAbsolute(relative15)) {
8543
+ continue;
8544
+ }
8545
+ entries.push(`/${relative15}/`);
8546
+ }
8547
+ return [...new Set(entries)];
8548
+ }
8356
8549
  function resolvePresetChoice(detectedName, presetName) {
8357
8550
  return {
8358
8551
  value: presetName,
@@ -8434,6 +8627,7 @@ async function runInit(options) {
8434
8627
  let lastScope = "all";
8435
8628
  const artifactChoices = [
8436
8629
  { value: "readme", label: "README.md", hint: "orientation page" },
8630
+ { value: "prompt", label: "PROMPT.md", hint: "instruction sheet for the model" },
8437
8631
  { value: "manifest", label: "manifest.json", hint: "required by validate and report" },
8438
8632
  { value: "parts", label: "parts/", hint: "the code payload" },
8439
8633
  { value: "navigation", label: "reports/navigation.md", hint: "file \u2192 part index" },
@@ -8645,7 +8839,10 @@ async function runInit(options) {
8645
8839
  }
8646
8840
  if (!reused) writeFileOrExplain(configPath, configText);
8647
8841
  const { scripts, dependency } = updatePackageJson(options.cwd, notes);
8648
- const ignore = appendGitignoreEntries(options.cwd, GITIGNORE_ENTRIES);
8842
+ const ignore = appendGitignoreEntries(
8843
+ options.cwd,
8844
+ gitignoreEntriesFor(options.cwd, answers.outDir, options.tmpDir ?? (reused ? null : "snapshot.tmp"))
8845
+ );
8649
8846
  if (ignore.note !== null) notes.push(ignore.note);
8650
8847
  return {
8651
8848
  configPath,
@@ -8663,10 +8860,10 @@ async function runInit(options) {
8663
8860
  };
8664
8861
  }
8665
8862
  function describeTarget(cwd) {
8666
- const relative14 = path16__namespace.relative(process.cwd(), cwd);
8667
- if (relative14 === "") return "this directory";
8668
- if (relative14.startsWith("..") || path16__namespace.isAbsolute(relative14)) return cwd;
8669
- return relative14;
8863
+ const relative15 = path16__namespace.relative(process.cwd(), cwd);
8864
+ if (relative15 === "") return "this directory";
8865
+ if (relative15.startsWith("..") || path16__namespace.isAbsolute(relative15)) return cwd;
8866
+ return relative15;
8670
8867
  }
8671
8868
  function firstRunMessage(reason, cwd) {
8672
8869
  const where = describeTarget(cwd);
@@ -8861,7 +9058,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
8861
9058
  );
8862
9059
  for (const file of affected) {
8863
9060
  const status = file.isPreviewTruncated ? "Truncated" : "Full";
8864
- const cutBy = file.truncationReason === "part-budget" ? "maxPartBytes" : "largeFileBytes";
9061
+ const cutBy = file.truncationReason === "part-budget" ? "part budget (maxPartBytes)" : "large-file budget (largeFileBytes)";
8865
9062
  lines.push(
8866
9063
  `| ${code(file.relativePath)} | ${file.sizeBytes} | ${file.lines} | ${file.includedBytes} | ${file.includedLines} | ${status} | ${cutBy} |`
8867
9064
  );
@@ -8974,11 +9171,11 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
8974
9171
  codebaseSnapshotFinding: `${findingPath}#L${line}#${finding.rules.join("+")}`
8975
9172
  }
8976
9173
  };
8977
- }).sort(
8978
- (a, b) => a.locations[0].physicalLocation.artifactLocation.uri.localeCompare(
8979
- b.locations[0].physicalLocation.artifactLocation.uri
8980
- ) || a.locations[0].physicalLocation.region.startLine - b.locations[0].physicalLocation.region.startLine
8981
- );
9174
+ }).sort((a, b) => {
9175
+ const left = a.locations[0].physicalLocation.artifactLocation.uri;
9176
+ const right = b.locations[0].physicalLocation.artifactLocation.uri;
9177
+ return (left < right ? -1 : left > right ? 1 : 0) || a.locations[0].physicalLocation.region.startLine - b.locations[0].physicalLocation.region.startLine;
9178
+ });
8982
9179
  const log = {
8983
9180
  $schema: SARIF_SCHEMA,
8984
9181
  version: SARIF_VERSION,
@@ -9007,6 +9204,7 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
9007
9204
  }
9008
9205
  var HEADER_RESERVE_BYTES = 2048 + Buffer.byteLength(UNTRUSTED_CONTENT_NOTICE, "utf8") + 8;
9009
9206
  var MIN_SECTION_BUDGET_BYTES = 512;
9207
+ var MIN_PART_BUDGET_BYTES = MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES;
9010
9208
  var MAX_SPLIT_PASSES = 64;
9011
9209
  var BUDGET_MARKER_RESERVE = 96;
9012
9210
  function insertTokenLine(markdown, tokens) {
@@ -9045,10 +9243,17 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
9045
9243
  const groups = [];
9046
9244
  for (const bucket of buckets) {
9047
9245
  if (bucket.files.length === 0) continue;
9048
- const budget = Math.max(
9049
- MIN_SECTION_BUDGET_BYTES + HEADER_RESERVE_BYTES,
9050
- bucket.budgetBytes
9051
- );
9246
+ if (!Number.isFinite(bucket.budgetBytes)) {
9247
+ throw new Error(
9248
+ `A part budget must be a finite number of bytes; received ${String(bucket.budgetBytes)}.`
9249
+ );
9250
+ }
9251
+ if (bucket.budgetBytes < MIN_PART_BUDGET_BYTES) {
9252
+ throw new Error(
9253
+ `A part budget of ${bucket.budgetBytes} B is below the ${MIN_PART_BUDGET_BYTES} B minimum: the header every part must carry is larger than that, so the budget could not be honoured. Use a budget of at least 4096 B.`
9254
+ );
9255
+ }
9256
+ const budget = bucket.budgetBytes;
9052
9257
  const sectionBudget = budget - HEADER_RESERVE_BYTES;
9053
9258
  const prepared = bucket.files.map((file) => prepareSection(file, sectionBudget, budget));
9054
9259
  for (const sections of greedyGroups(prepared, budget)) groups.push({ sections, budget });
@@ -9516,10 +9721,420 @@ function generateNavigation(manifest) {
9516
9721
  return lines.join("\n");
9517
9722
  }
9518
9723
 
9724
+ // src/generator/prompt.ts
9725
+ var MAX_PART_ROWS = 16;
9726
+ var MAX_LAYER_ROWS = 8;
9727
+ var MAX_INCOMPLETE_ROWS = 50;
9728
+ var MAX_CENTRAL_FILES = 5;
9729
+ var MAX_ENTRY_POINTS = 4;
9730
+ var MAX_LARGEST_FILES = 3;
9731
+ var partWord = (count) => count === 1 ? "part" : "parts";
9732
+ var UNLIMITED_SLOTS = 0;
9733
+ var ENTRY_POINT = /(^|\/)(index|cli|main|bin|server|app|mod)\.[cm]?[jt]sx?$/;
9734
+ var TEST_PATH = /(^|\/)(tests?|__tests__)\//;
9735
+ var TEST_FILE = /\.(test|spec)\.[^.]+$/;
9736
+ function generatePrompt(manifest, artifacts, attachmentSlots = DEFAULT_ATTACHMENT_SLOTS, history = []) {
9737
+ const wrote = (name) => artifacts?.[name] !== false;
9738
+ const code = (value) => inlineCode(escapeControls(value));
9739
+ const lines = [
9740
+ "# PROMPT.md",
9741
+ "",
9742
+ "The brief and the apparatus for this snapshot. Paste this file first, then the parts it names.",
9743
+ "",
9744
+ "It is generated rather than written once: the system map, the omissions, the fingerprint and",
9745
+ "the history below are read from `manifest.json` and this repository, so they describe this run.",
9746
+ "Regenerate it after the code moves.",
9747
+ "",
9748
+ "---",
9749
+ "",
9750
+ "```text",
9751
+ "You are working on a codebase you cannot clone, run or grep. Everything you know about it comes",
9752
+ "from the snapshot that follows this instruction. Where these notes and the snapshot disagree,",
9753
+ "the snapshot is what exists.",
9754
+ "",
9755
+ "## The job",
9756
+ "",
9757
+ "Find what is still wrong or will break. How you read the code is yours to decide - by",
9758
+ "subsystem, by data flow, by the invariants you derive yourself. What you owe in return is an",
9759
+ "honest account of what you covered and what you did not.",
9760
+ "",
9761
+ 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,",
9762
+ 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.",
9763
+ 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.",
9764
+ "",
9765
+ "If the task at the end asks for something narrower - explain a file, review a change, answer a",
9766
+ "question - that task wins. The standard and the coverage duty below still apply to it.",
9767
+ ""
9768
+ ];
9769
+ lines.push(...haveSection(wrote), "");
9770
+ lines.push(...systemSection(manifest, code), "");
9771
+ lines.push(...historySection(history), "");
9772
+ lines.push(...barSection(), "");
9773
+ lines.push(...coverageSection(manifest, code, wrote("audit")), "");
9774
+ lines.push(...answerSection(), "");
9775
+ lines.push(...calibrationSection(), "");
9776
+ lines.push(...snapshotSection(manifest, code), "");
9777
+ lines.push(...deliverySection(manifest, wrote("parts"), attachmentSlots));
9778
+ lines.push(
9779
+ "## Your task",
9780
+ "",
9781
+ "<replace with the question, the area to review, or the subsystem to audit>",
9782
+ "```"
9783
+ );
9784
+ lines.push(
9785
+ "",
9786
+ "---",
9787
+ "",
9788
+ "## Why this file exists",
9789
+ "",
9790
+ "Parts on their own are a dump: the model receives text, has no idea what was left out of it,",
9791
+ "and fills the gap by invention. A brief on its own is a wish list: it cannot say which files",
9792
+ "are present, which are partial or which part holds what. This file is both halves, and the",
9793
+ "facts in it move with the snapshot.",
9794
+ "",
9795
+ "## Keeping it true",
9796
+ "",
9797
+ "- It is one of the artifacts recorded in `manifest.json` under `artifacts.prompt`, so deleting",
9798
+ " or editing `PROMPT.md` makes `snapshot validate` fail.",
9799
+ "- `--skip-artifacts prompt`, or `artifacts: { prompt: false }` in the config, turns it off.",
9800
+ "- The history section disappears when git cannot be read, rather than being invented.",
9801
+ "- If the code moves, regenerate. A brief naming the previous run parts is worse than no",
9802
+ " brief, because it reads as current.",
9803
+ ""
9804
+ );
9805
+ return lines.join("\n");
9806
+ }
9807
+ function haveSection(wrote) {
9808
+ const out = ["## What you have", ""];
9809
+ const bullets = [];
9810
+ if (wrote("readme")) {
9811
+ bullets.push("- `README.md` - orientation: metrics, the part table, and the fingerprint.");
9812
+ }
9813
+ if (wrote("manifest")) {
9814
+ bullets.push(
9815
+ "- `manifest.json` - the index. Per file: `relativePath`, `layer`, `kind`, `language`,",
9816
+ " `part`, `sha256`, `inclusionMode`, `truncationReason`, `omittedRanges`. It also carries",
9817
+ " every excluded path under `skipped[]` with its reason, and `incomplete[]`, which names",
9818
+ " every included file whose emitted body is not the whole file."
9819
+ );
9820
+ }
9821
+ if (wrote("navigation")) {
9822
+ bullets.push("- `reports/navigation.md` - file to part. Locate here before you read anything.");
9823
+ }
9824
+ if (wrote("projectTree")) {
9825
+ bullets.push("- `reports/project-tree.md` - the directory shape of what was included.");
9826
+ }
9827
+ if (wrote("audit")) {
9828
+ bullets.push(
9829
+ "- `reports/audit.md` - secret findings, the files whose lines were redacted, large files,",
9830
+ " parse diagnostics and the git state the snapshot was taken from."
9831
+ );
9832
+ }
9833
+ if (wrote("parts")) {
9834
+ bullets.push(
9835
+ "- `parts/part-NNN.md` - the code itself, split to a fixed byte budget. Each part states its",
9836
+ " own number, the files it contains, and the fingerprint it was built from."
9837
+ );
9838
+ }
9839
+ if (wrote("monolith")) {
9840
+ bullets.push(
9841
+ "- `full-codebase.json` and `full-codebase.md` - the entire payload in one file each.",
9842
+ " Where they are present, they supersede the parts: nothing was left out of them."
9843
+ );
9844
+ }
9845
+ if (bullets.length === 0) {
9846
+ bullets.push(
9847
+ "- Nothing but this brief: every code artifact was disabled for this run. Ask for a snapshot",
9848
+ " generated with the artifacts you need, and do not answer from memory."
9849
+ );
9850
+ }
9851
+ out.push(...bullets);
9852
+ return out;
9853
+ }
9854
+ function systemSection(manifest, code) {
9855
+ const out = ["## The system", ""];
9856
+ const layers = Object.entries(manifest.layers).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
9857
+ if (layers.length > 0) {
9858
+ const shown = layers.slice(0, MAX_LAYER_ROWS).map(([name, count]) => code(name) + " " + formatNumber(count));
9859
+ const rest = layers.length > MAX_LAYER_ROWS ? ", and " + formatNumber(layers.length - MAX_LAYER_ROWS) + " more" : "";
9860
+ out.push("- Layers, by file count: " + shown.join(", ") + rest + ".");
9861
+ }
9862
+ const central = manifest.indexes.imports.centralFiles;
9863
+ if (central.length > 0) {
9864
+ const shown = central.slice(0, MAX_CENTRAL_FILES).map((entry) => code(entry.path) + " (" + formatNumber(entry.importedByCount) + ")").join(", ");
9865
+ out.push(
9866
+ "- Load-bearing modules, by how many files import them: " + shown + ".",
9867
+ " A change here reaches the most call sites; read it before judging anything that uses it."
9868
+ );
9869
+ }
9870
+ const entryPoints = manifest.files.map((file) => file.relativePath).filter((path22) => ENTRY_POINT.test(path22)).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length).slice(0, MAX_ENTRY_POINTS);
9871
+ out.push(
9872
+ 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"
9873
+ );
9874
+ if (entryPoints.length === 0) out.push(" starts, and the call graph in `manifest.json` is the map.");
9875
+ const routes = manifest.indexes.routes.length;
9876
+ const handlers = manifest.indexes.handlers.length;
9877
+ const components = manifest.indexes.components.length;
9878
+ const routesShown = manifest.indexes.routes.slice(0, 4).map((route) => code(route.path));
9879
+ const componentsShown = manifest.indexes.components.slice(0, 4).map((entry) => code(entry.path));
9880
+ if (routes + handlers + components === 0) {
9881
+ out.push(
9882
+ "- No routes, handlers or UI components were recorded: this snapshot indexes no HTTP or",
9883
+ " component surface. Do not go looking for one, and do not infer one from a file name."
9884
+ );
9885
+ } else {
9886
+ const parts = [];
9887
+ if (routes > 0) parts.push(formatNumber(routes) + " route(s), e.g. " + routesShown.join(", "));
9888
+ if (handlers > 0) parts.push(formatNumber(handlers) + " handler(s)");
9889
+ if (components > 0) parts.push(formatNumber(components) + " component(s), e.g. " + componentsShown.join(", "));
9890
+ out.push("- Surfaces the index found: " + parts.join("; ") + ".");
9891
+ }
9892
+ const largest = [...manifest.files].sort((a, b) => b.includedBytes - a.includedBytes).slice(0, MAX_LARGEST_FILES);
9893
+ if (largest.length > 0) {
9894
+ out.push(
9895
+ "- Largest files: " + largest.map((file) => code(file.relativePath) + " (" + formatNumber(Math.round(file.includedBytes / 1024)) + " KB)").join(", ") + "."
9896
+ );
9897
+ }
9898
+ const tests = manifest.files.filter(
9899
+ (file) => TEST_PATH.test(file.relativePath) || TEST_FILE.test(file.relativePath)
9900
+ );
9901
+ if (tests.length > 0) {
9902
+ const testBytes = tests.reduce((total, file) => total + file.includedBytes, 0);
9903
+ const allBytes = manifest.files.reduce((total, file) => total + file.includedBytes, 0);
9904
+ const share = allBytes === 0 ? 0 : Math.round(testBytes / allBytes * 100);
9905
+ out.push(
9906
+ "- Tests: " + formatNumber(tests.length) + " file(s), " + share + "% of the included bytes.",
9907
+ " They are evidence of intent, not of behaviour: a fixture can encode a payload shape the",
9908
+ " real system never sends."
9909
+ );
9910
+ }
9911
+ return out;
9912
+ }
9913
+ function historySection(history) {
9914
+ const out = ["## What came before", ""];
9915
+ if (history.length === 0) {
9916
+ out.push(
9917
+ "No history was readable: this is not a git checkout, or git could not be run. Nothing about",
9918
+ "what came before can be claimed from here, and that is not evidence that the code is new."
9919
+ );
9920
+ return out;
9921
+ }
9922
+ out.push(
9923
+ "Commit subjects, newest first. They are claims by whoever wrote them, not evidence - the code",
9924
+ "beside them is the evidence. If one of these fixes looks incomplete, quote the lines and say",
9925
+ "which call site it missed.",
9926
+ ""
9927
+ );
9928
+ for (const subject of history) out.push("- " + subject);
9929
+ return out;
9930
+ }
9931
+ function barSection() {
9932
+ return [
9933
+ "## The bar",
9934
+ "",
9935
+ "A finding is a concrete way the code breaks or lies, supported by quoted lines: the path and",
9936
+ "line, the input or state that reaches it, what happens next, and why the guard that appears to",
9937
+ "stop it does not. A comment is not behaviour. A passing test is evidence of intent, not of",
9938
+ "behaviour.",
9939
+ "",
9940
+ "- No style, naming, formatting, add-types, add-tests, consider-X or speculative rewrites.",
9941
+ "- Never invent a finding to fill a section. A clean surface is proven by quoting the guard",
9942
+ " that makes it clean.",
9943
+ "- Mark confidence, and name the check - a test, a run, an input - that would settle anything",
9944
+ " you cannot decide by reading.",
9945
+ "- Separate what the code does from what the deployment or configuration does. Both are",
9946
+ " findings; they have different owners and different fixes."
9947
+ ];
9948
+ }
9949
+ function coverageSection(manifest, code, auditWritten) {
9950
+ const out = ["## Coverage", ""];
9951
+ const reasons = /* @__PURE__ */ new Map();
9952
+ for (const record of manifest.skipped) {
9953
+ reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
9954
+ }
9955
+ const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
9956
+ out.push(
9957
+ "- " + 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 + ")" : "") + ".",
9958
+ " `manifest.skipped[]` names each one and why. An absent path is not a clean path."
9959
+ );
9960
+ out.push(...incompleteSection(manifest, code));
9961
+ out.push(...redactionSection(manifest, auditWritten));
9962
+ out.push(
9963
+ "- Everything unseen is unread, never clean. If you were given only some of the parts, say",
9964
+ " which ones are missing before you answer. A file the index names but the parts do not carry",
9965
+ " is an input defect, not a code finding - report it as one."
9966
+ );
9967
+ return out;
9968
+ }
9969
+ function answerSection() {
9970
+ return [
9971
+ "## What a useful answer contains",
9972
+ "",
9973
+ "- An opening line, filled from This snapshot below:",
9974
+ "",
9975
+ " snapshot <fingerprint> generated <generatedAt>",
9976
+ "",
9977
+ "- What you read and what you did not, named by path or by part.",
9978
+ "- Findings ordered by consequence, each with the lines quoted.",
9979
+ "- The checks or attacks that failed, and the line or guard that blocked them. A failed attack",
9980
+ " is how anyone knows an invariant is real rather than asserted.",
9981
+ "- What you retracted after re-reading.",
9982
+ "- What only a run, a test or a host can settle, and the check that would settle each.",
9983
+ "- One paragraph on the failure you would bet on next.",
9984
+ "- A closing line: Needed but not received: <paths>, or none. That line is not decoration -",
9985
+ " an invented function is indistinguishable from a real one, and this is where you name",
9986
+ " the gap you filled by asking instead of guessing."
9987
+ ];
9988
+ }
9989
+ function calibrationSection() {
9990
+ return [
9991
+ "## Calibration",
9992
+ "",
9993
+ "The findings that matter here do not crash. They look like:",
9994
+ "",
9995
+ "- a guard applied at one call site and not its twin - the route checks, the timer does not;",
9996
+ "- a budget shorter than the work it guards, so the caller gives up while the work continues;",
9997
+ "- a success flag that means the call returned, consumed as the change happened;",
9998
+ "- a document that describes a different run than the one beside it;",
9999
+ "- a default that fabricates a number when the measurement failed.",
10000
+ "",
10001
+ "None of these throw. All are invisible in a summary."
10002
+ ];
10003
+ }
10004
+ function snapshotSection(manifest, code) {
10005
+ const out = ["## This snapshot", ""];
10006
+ out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
10007
+ out.push(
10008
+ "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
10009
+ );
10010
+ out.push(
10011
+ manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
10012
+ );
10013
+ out.push(
10014
+ "- Validation: `manifest.validation.status` was " + code(manifest.validation.status) + " at generation time.",
10015
+ " That describes the run, not now: if the tree may have moved since, the snapshot is a",
10016
+ " claim that needs re-checking, not a fact."
10017
+ );
10018
+ if (manifest.parts.length > 0) {
10019
+ out.push(
10020
+ "- Parts: " + formatNumber(manifest.parts.length) + " at a " + formatNumber(Math.round(manifest.budgets.maxPartBytes / 1024)) + " KB ceiling" + (manifest.parts.length === 1 ? ":" : " each:")
10021
+ );
10022
+ for (const part of manifest.parts.slice(0, MAX_PART_ROWS)) {
10023
+ out.push(" - " + code(part.filename) + " - " + formatNumber(part.fileCount) + " file(s)");
10024
+ }
10025
+ if (manifest.parts.length > MAX_PART_ROWS) {
10026
+ out.push(
10027
+ " - and " + formatNumber(manifest.parts.length - MAX_PART_ROWS) + " more, tabled in `README.md`"
10028
+ );
10029
+ }
10030
+ }
10031
+ return out;
10032
+ }
10033
+ function incompleteSection(manifest, code) {
10034
+ const out = [];
10035
+ const list2 = manifest.incomplete;
10036
+ if (list2.length === 0) {
10037
+ out.push("- Partial files: none. Every included file is present in full.");
10038
+ return out;
10039
+ }
10040
+ out.push(
10041
+ "- Partial files: " + formatNumber(list2.length) + ". These are present only in part, and the",
10042
+ " missing lines are named, not implied:"
10043
+ );
10044
+ for (const entry of list2.slice(0, MAX_INCOMPLETE_ROWS)) {
10045
+ const ranges = entry.omittedRanges.map(([start, end]) => start === end ? String(start) : start + "-" + end).join(", ");
10046
+ out.push(
10047
+ " - " + code(entry.relativePath) + " in " + code(entry.part) + " - " + entry.reason + ", lines " + ranges + " (" + formatNumber(entry.omittedLines) + " of " + formatNumber(entry.lines) + " missing)"
10048
+ );
10049
+ }
10050
+ if (list2.length > MAX_INCOMPLETE_ROWS) {
10051
+ out.push(
10052
+ " - and " + formatNumber(list2.length - MAX_INCOMPLETE_ROWS) + " more, all named in `manifest.json` under `incomplete[]`"
10053
+ );
10054
+ }
10055
+ return out;
10056
+ }
10057
+ function redactionSection(manifest, auditWritten) {
10058
+ const redacted = manifest.totals.redactedLines;
10059
+ if (redacted === 0) {
10060
+ return ["- Redacted: no line matched a secret rule."];
10061
+ }
10062
+ 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.";
10063
+ return [
10064
+ "- Redacted: " + formatNumber(redacted) + " line(s) had values masked before you received them.",
10065
+ " A masked span is a deliberate redaction, not an empty value.",
10066
+ " " + where
10067
+ ];
10068
+ }
10069
+ function deliverySection(manifest, partsWritten, slots) {
10070
+ if (!partsWritten || manifest.parts.length === 0) return [];
10071
+ const parts = manifest.parts.length;
10072
+ const wholeSet = parts + 5;
10073
+ const unlimited = slots <= UNLIMITED_SLOTS;
10074
+ const out = ["## Attaching this", ""];
10075
+ out.push(
10076
+ "Paste this file as text: instructions cost no attachment slot. Attach the files it names.",
10077
+ "",
10078
+ "- Every part opens with `# Codebase Snapshot Part NNN of MMM` and repeats the fingerprint",
10079
+ " above, so check both before relying on one. A part you were not given is not an empty part."
10080
+ );
10081
+ if (unlimited) {
10082
+ out.push(
10083
+ "- No attachment limit is configured, so every file can travel: " + parts + " " + partWord(parts) + " plus `manifest.json`, `README.md` and the three reports (" + wholeSet + " files)."
10084
+ );
10085
+ } else if (wholeSet <= slots) {
10086
+ out.push(
10087
+ "- A " + slots + "-file destination carries the whole set: " + parts + " " + partWord(parts) + " plus `manifest.json`, `README.md` and the three reports - " + wholeSet + " of " + slots + "."
10088
+ );
10089
+ } else if (parts + 1 <= slots) {
10090
+ out.push(
10091
+ "- A " + slots + "-file destination carries " + parts + " " + partWord(parts) + " and",
10092
+ " `manifest.json` (" + (parts + 1) + " of " + slots + "); `README.md` and",
10093
+ " `reports/` stay behind - the brief above carries what they add."
10094
+ );
10095
+ } else if (parts <= slots) {
10096
+ out.push(
10097
+ 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",
10098
+ " `reports/` stay behind. The brief above carries what they add."
10099
+ );
10100
+ if (parts > 1) {
10101
+ out.push(
10102
+ " Either raise `--max-part-bytes` to merge the parts, or set `--max-parts " + slots + "` and let the parts grow to the count instead."
10103
+ );
10104
+ }
10105
+ } else {
10106
+ out.push(
10107
+ "- The " + parts + " parts do not fit a " + slots + "-file destination: at most " + slots + " can be attached.",
10108
+ " Choose by task - `reports/navigation.md` maps a file to its part - and name the parts",
10109
+ " you left out, or regenerate with `--max-part-bytes " + suggestBudgetBytes(manifest, slots) + "` for about " + (slots - 1) + " parts. `--max-parts " + slots + "` grows the parts until",
10110
+ " they fit instead, and says so when they end up larger than maxPartBytes."
10111
+ );
10112
+ }
10113
+ out.push(
10114
+ "- If you were given only some of them, say which parts are missing before you answer, and",
10115
+ " name the files you needed. Do not infer the contents of a part you did not receive.",
10116
+ ""
10117
+ );
10118
+ return out;
10119
+ }
10120
+ function suggestBudgetBytes(manifest, slots) {
10121
+ const total = manifest.parts.reduce((sum, part) => sum + part.byteSize, 0);
10122
+ const target = Math.max(1, slots - 1);
10123
+ const estimated = Math.ceil(total / target * 1.15);
10124
+ const rounded = Math.ceil(estimated / 16384) * 16384;
10125
+ const budget = Math.max(rounded, manifest.budgets.maxPartBytes);
10126
+ return Math.round(budget / 1024) + "k";
10127
+ }
10128
+
9519
10129
  // src/generator/readme.ts
9520
10130
  function generateReadme(manifest, artifacts) {
9521
10131
  const wrote = (name) => artifacts?.[name] !== false;
9522
10132
  const reportLinks = [];
10133
+ if (wrote("prompt")) {
10134
+ reportLinks.push(
10135
+ "- [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."
10136
+ );
10137
+ }
9523
10138
  if (wrote("navigation")) {
9524
10139
  reportLinks.push(
9525
10140
  "- [reports/navigation.md](reports/navigation.md) \u2014 Comprehensive file directory mapping files to chunk files."
@@ -9589,6 +10204,11 @@ function generateReadme(manifest, artifacts) {
9589
10204
  lines.push("", "## Snapshot Parts", "", "No parts were written for this run.");
9590
10205
  }
9591
10206
  const readOrder = [];
10207
+ if (wrote("prompt")) {
10208
+ readOrder.push(
10209
+ "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
10210
+ );
10211
+ }
9592
10212
  if (wrote("navigation") || wrote("projectTree")) {
9593
10213
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
9594
10214
  readOrder.push(`1. Read ${first} first to locate target features or files.`);
@@ -9677,6 +10297,22 @@ function generateProjectTree(filePaths) {
9677
10297
  const fence = fenceForText(lines.join("\n"), 3);
9678
10298
  return ["# Project Tree", "", `${fence}text`, ...lines, fence, ""].join("\n");
9679
10299
  }
10300
+ function treeTruncationWarnings(treeText) {
10301
+ const warnings = [];
10302
+ const depth = /\[tree truncated at (\d+) levels\]/.exec(treeText);
10303
+ if (depth) {
10304
+ warnings.push(
10305
+ `reports/project-tree.md was truncated at the ${depth[1]}-level depth cap: deeper directories are not listed there.`
10306
+ );
10307
+ }
10308
+ const lines = /\[tree truncated at (\d+) lines\]/.exec(treeText);
10309
+ if (lines) {
10310
+ warnings.push(
10311
+ `reports/project-tree.md was truncated at the ${lines[1]}-line cap: the rest of the tree is not listed there.`
10312
+ );
10313
+ }
10314
+ return warnings;
10315
+ }
9680
10316
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
9681
10317
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
9682
10318
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
@@ -9789,14 +10425,14 @@ function writeCache(file, entry) {
9789
10425
  }
9790
10426
  }
9791
10427
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
9792
- return new Promise((resolve11) => {
10428
+ return new Promise((resolve12) => {
9793
10429
  let settled = false;
9794
10430
  let request = null;
9795
10431
  const finish = (value) => {
9796
10432
  if (settled) return;
9797
10433
  settled = true;
9798
10434
  clearTimeout(deadline);
9799
- resolve11(value);
10435
+ resolve12(value);
9800
10436
  };
9801
10437
  const deadline = setTimeout(() => {
9802
10438
  request?.destroy();
@@ -9937,8 +10573,8 @@ function gitDirectory(cwd) {
9937
10573
  }
9938
10574
  }
9939
10575
  function isInside2(parent, child) {
9940
- const relative14 = path16__namespace.relative(parent, child);
9941
- return relative14 === "" || !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14);
10576
+ const relative15 = path16__namespace.relative(parent, child);
10577
+ return relative15 === "" || !relative15.startsWith("..") && !path16__namespace.isAbsolute(relative15);
9942
10578
  }
9943
10579
  function isRegisteredWorktree(gitDir, cwd) {
9944
10580
  try {
@@ -10052,7 +10688,20 @@ const { parentPort, workerData } = require("node:worker_threads");
10052
10688
  // so the run is the documented MCP run rather than the CLI run with one setting removed.
10053
10689
  const base = loaded.config ? { ...loaded.config, hooks: {} } : null;
10054
10690
  const config = mod.resolveConfig(base, workerData.cliOptions, workerData.cwd);
10055
- const manifest = mod.generateSnapshot(config);
10691
+ const manifest = mod.generateSnapshot(config, { dryRun: workerData.dryRun === true });
10692
+ const skipCounts = new Map();
10693
+ for (const record of manifest.skipped) {
10694
+ skipCounts.set(record.reason, (skipCounts.get(record.reason) || 0) + 1);
10695
+ }
10696
+ const skipReasons = Array.from(skipCounts.entries())
10697
+ .sort(function (a, b) {
10698
+ if (b[1] !== a[1]) return b[1] - a[1];
10699
+ return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
10700
+ })
10701
+ .slice(0, 8)
10702
+ .map(function (entry) {
10703
+ return { reason: entry[0], count: entry[1] };
10704
+ });
10056
10705
  parentPort.postMessage({
10057
10706
  ok: true,
10058
10707
  summary: {
@@ -10061,7 +10710,11 @@ const { parentPort, workerData } = require("node:worker_threads");
10061
10710
  skippedCount: manifest.counts.skippedCount,
10062
10711
  partsCount: manifest.counts.partsCount,
10063
10712
  parts: manifest.parts.map((part) => ({ filename: part.filename, byteSize: part.byteSize })),
10713
+ totalSizeBytes: manifest.counts.totalSizeBytes,
10064
10714
  totalContentBytes: manifest.totals.totalContentBytes,
10715
+ preset: manifest.config.preset,
10716
+ layers: manifest.layers,
10717
+ skipReasons: skipReasons,
10065
10718
  warnings: manifest.warnings,
10066
10719
  },
10067
10720
  });
@@ -10073,15 +10726,15 @@ const { parentPort, workerData } = require("node:worker_threads");
10073
10726
  }
10074
10727
  })();
10075
10728
  `;
10076
- function generateInWorker(cwd, cliOptions) {
10077
- return new Promise((resolve11) => {
10729
+ function generateInWorker(cwd, cliOptions, options = {}) {
10730
+ return new Promise((resolve12) => {
10078
10731
  let settled = false;
10079
10732
  let worker = null;
10080
10733
  const finish = (result) => {
10081
10734
  if (settled) return;
10082
10735
  settled = true;
10083
10736
  if (worker !== null) void worker.terminate();
10084
- resolve11(result);
10737
+ resolve12(result);
10085
10738
  };
10086
10739
  const isCjs = typeof __dirname !== "undefined";
10087
10740
  const directory = isCjs ? __dirname : path16__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
@@ -10091,7 +10744,8 @@ function generateInWorker(cwd, cliOptions) {
10091
10744
  workerData: {
10092
10745
  entryUrl: workerEntry(directory, isCjs).url,
10093
10746
  cwd,
10094
- cliOptions
10747
+ cliOptions,
10748
+ dryRun: options.dryRun === true
10095
10749
  }
10096
10750
  });
10097
10751
  } catch (error) {
@@ -10276,16 +10930,29 @@ function retain(items, keep) {
10276
10930
  }
10277
10931
  items.length = write;
10278
10932
  }
10279
- function buildIndexes(files, tsconfigPaths) {
10933
+ function buildIndexes(files, tsconfigPaths, skippedSummaryImports = /* @__PURE__ */ new Map()) {
10280
10934
  const resolver = buildImportResolver(files, { tsconfig: tsconfigPaths });
10281
10935
  const importerCounts = /* @__PURE__ */ new Map();
10282
- const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => {
10283
- const summary = file.summary;
10284
- return {
10285
- path: file.relativePath,
10286
- imports: summary.imports,
10287
- exports: summary.exports
10288
- };
10936
+ const byFile = files.flatMap((file) => {
10937
+ if (isSourceSummary(file.summary)) {
10938
+ return [
10939
+ {
10940
+ path: file.relativePath,
10941
+ imports: file.summary.imports,
10942
+ exports: file.summary.exports
10943
+ }
10944
+ ];
10945
+ }
10946
+ const imports = skippedSummaryImports.get(file.relativePath);
10947
+ if (imports === void 0) return [];
10948
+ return [
10949
+ {
10950
+ path: file.relativePath,
10951
+ imports,
10952
+ exports: [],
10953
+ exportsOmitted: true
10954
+ }
10955
+ ];
10289
10956
  });
10290
10957
  for (const entry of byFile) {
10291
10958
  for (const specifier of entry.imports) {
@@ -10405,6 +11072,9 @@ function resolveSafeOutputDirs(config) {
10405
11072
  return { outDir, tmpDir };
10406
11073
  }
10407
11074
  var IGNORABLE_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
11075
+ function isIgnorableEntry(entry) {
11076
+ return IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1));
11077
+ }
10408
11078
  var RUN_DIR_PREFIX = "run-";
10409
11079
  var STALE_RUN_MS = 60 * 60 * 1e3;
10410
11080
  function maskSummaryStrings(value, secretRules) {
@@ -10447,9 +11117,9 @@ function listEntries(dir) {
10447
11117
  return;
10448
11118
  }
10449
11119
  for (const child of children) {
10450
- const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
10451
- entries.push(relative14);
10452
- if (child.isDirectory()) walk(path16__namespace.join(absolute, child.name), relative14);
11120
+ const relative15 = prefix === "" ? child.name : `${prefix}/${child.name}`;
11121
+ entries.push(relative15);
11122
+ if (child.isDirectory()) walk(path16__namespace.join(absolute, child.name), relative15);
10453
11123
  }
10454
11124
  };
10455
11125
  walk(dir, "");
@@ -10460,7 +11130,7 @@ function markerInventory(dir, written) {
10460
11130
  const files = [];
10461
11131
  for (const entry of entries) {
10462
11132
  if (entry === OWNERSHIP_MARKER) continue;
10463
- if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
11133
+ if (isIgnorableEntry(entry)) continue;
10464
11134
  const full = path16__namespace.join(dir, ...entry.split("/"));
10465
11135
  let stats;
10466
11136
  try {
@@ -10749,7 +11419,7 @@ function assessSnapshotDirectory(dir) {
10749
11419
  }
10750
11420
  const entries = listEntries(dir);
10751
11421
  const foreignEntries = entries.filter(
10752
- (entry) => !recorded.has(entry) && !IGNORABLE_ENTRIES.has(entry)
11422
+ (entry) => !recorded.has(entry) && !isIgnorableEntry(entry)
10753
11423
  );
10754
11424
  if (foreignEntries.length > 0) {
10755
11425
  return { owned: false, problem: null, foreignEntries, marker: marker2 };
@@ -11205,7 +11875,55 @@ function runAfterGenerate(config, manifest) {
11205
11875
  return Promise.resolve(returned).finally(releaseRedirect);
11206
11876
  }
11207
11877
  function partitionByBudget(files, config, fingerprint) {
11208
- const budgetFor = (file) => config.budgets.byLayer[file.layer] ?? config.budgets.default;
11878
+ const configured = {
11879
+ parts: partitionWithBudgets(files, config.budgets, fingerprint),
11880
+ budgets: config.budgets,
11881
+ maxPartBytes: config.maxPartBytes,
11882
+ warnings: []
11883
+ };
11884
+ const limit = config.maxParts;
11885
+ if (limit === null || !config.artifacts.parts || configured.parts.length <= limit) return configured;
11886
+ const totalBytes = files.reduce((total, file) => total + file.includedBytes, 0);
11887
+ let target = Math.max(config.budgets.default, Math.ceil(totalBytes * 1.15 / limit));
11888
+ const seen = [];
11889
+ let low = config.budgets.default;
11890
+ let fitting = null;
11891
+ for (let pass = 0; pass < 6; pass += 1) {
11892
+ const parts2 = partitionWithBudgets(files, scaleBudgets(config.budgets, target), fingerprint);
11893
+ if (parts2.length <= limit) {
11894
+ fitting = { target, parts: parts2 };
11895
+ break;
11896
+ }
11897
+ seen.push(parts2.length);
11898
+ low = target;
11899
+ target = Math.ceil(target * 1.3);
11900
+ }
11901
+ if (fitting === null) {
11902
+ throw new Error(
11903
+ `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.`
11904
+ );
11905
+ }
11906
+ for (let step = 0; step < 3 && fitting.target - low > 8192; step += 1) {
11907
+ const middle = Math.round((low + fitting.target) / 2);
11908
+ const parts2 = partitionWithBudgets(files, scaleBudgets(config.budgets, middle), fingerprint);
11909
+ if (parts2.length <= limit) fitting = { target: middle, parts: parts2 };
11910
+ else low = middle;
11911
+ }
11912
+ const { target: chosen, parts } = fitting;
11913
+ const budgets = scaleBudgets(config.budgets, chosen);
11914
+ const maxPartBytes = Math.max(config.maxPartBytes, chosen);
11915
+ const warnings = [
11916
+ `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).`
11917
+ ];
11918
+ if (maxPartBytes > config.maxPartBytes) {
11919
+ warnings.push(
11920
+ `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.`
11921
+ );
11922
+ }
11923
+ return { parts, budgets, maxPartBytes, warnings };
11924
+ }
11925
+ function partitionWithBudgets(files, budgets, fingerprint) {
11926
+ const budgetFor = (file) => budgets.byLayer[file.layer] ?? budgets.default;
11209
11927
  const buckets = /* @__PURE__ */ new Map();
11210
11928
  for (const file of files) {
11211
11929
  const budget = budgetFor(file);
@@ -11222,6 +11940,18 @@ function partitionByBudget(files, config, fingerprint) {
11222
11940
  fingerprint
11223
11941
  );
11224
11942
  }
11943
+ function scaleBudgets(budgets, targetDefault) {
11944
+ const factor = targetDefault / budgets.default;
11945
+ return {
11946
+ default: Math.max(budgets.default, Math.round(targetDefault)),
11947
+ byLayer: Object.fromEntries(
11948
+ Object.entries(budgets.byLayer).map(([name, bytes]) => [
11949
+ name,
11950
+ Math.max(bytes, Math.round(bytes * factor))
11951
+ ])
11952
+ )
11953
+ };
11954
+ }
11225
11955
  function generateSnapshot(configInput, options) {
11226
11956
  assertUsableConfigInput(configInput);
11227
11957
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
@@ -11245,7 +11975,7 @@ function generateSnapshot(configInput, options) {
11245
11975
  // output — but only at these exact paths, not at every directory that shares the name.
11246
11976
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11247
11977
  (directory) => path16__namespace.relative(config.cwd, path16__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
11248
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
11978
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith("..")),
11249
11979
  // A staged path can be absent from the working tree while its index blob exists. Discovery
11250
11980
  // lists the working tree, so those paths would never reach the scan at all.
11251
11981
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -11550,7 +12280,8 @@ function generateSnapshot(configInput, options) {
11550
12280
  );
11551
12281
  }
11552
12282
  }
11553
- const parts = partitionByBudget(files, config, fingerprint);
12283
+ const partitioned = partitionByBudget(files, config, fingerprint);
12284
+ const parts = partitioned.parts;
11554
12285
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
11555
12286
  const incomplete = files.flatMap((file) => {
11556
12287
  if (file.truncationReason === void 0) return [];
@@ -11587,7 +12318,10 @@ function generateSnapshot(configInput, options) {
11587
12318
  // the README and the audit report.
11588
12319
  git: { ...gitInfo, branch: maskPathText(gitInfo.branch, config.secretRules) },
11589
12320
  budgets: {
11590
- maxPartBytes: config.maxPartBytes,
12321
+ // The ceiling the parts actually honour. It equals the configured one unless `maxParts`
12322
+ // grew it; `config.maxPartBytes` below keeps the configured value, because that is what
12323
+ // `validate` compares against the config on disk.
12324
+ maxPartBytes: partitioned.maxPartBytes,
11591
12325
  largeFileBytes: config.largeFileBytes
11592
12326
  },
11593
12327
  config: {
@@ -11605,6 +12339,14 @@ function generateSnapshot(configInput, options) {
11605
12339
  // invisible in the manifest that is supposed to describe the run.
11606
12340
  maxMonolithBytes: config.maxMonolithBytes ?? null,
11607
12341
  includeSensitiveFiles: config.includeSensitiveFiles,
12342
+ // The destination the instructions were written for. Not part of `digest`: the payload is
12343
+ // identical whatever this says, and a new delivery preference must not make an existing
12344
+ // snapshot fail `validate` as configuration drift.
12345
+ attachmentSlots: config.attachmentSlots,
12346
+ // The part-count ceiling the run enforced. Recorded because it decided the part sizes, and
12347
+ // omitted from `digest` when it is off so an existing snapshot does not start reporting
12348
+ // configuration drift.
12349
+ maxParts: config.maxParts ?? null,
11608
12350
  discovery: config.discovery ?? "auto",
11609
12351
  // A changed-files scope decides which files are in the snapshot, so the manifest that
11610
12352
  // describes the run has to name it.
@@ -11665,7 +12407,7 @@ function generateSnapshot(configInput, options) {
11665
12407
  },
11666
12408
  layers: layerCounts,
11667
12409
  kinds: kindCounts,
11668
- indexes: buildIndexes(files, tsconfigPathsFor(config.cwd)),
12410
+ indexes: buildIndexes(files, tsconfigPathsFor(config.cwd), skippedSummaryImports),
11669
12411
  parts: parts.map((part) => part.metadata),
11670
12412
  files: files.map((file) => {
11671
12413
  const { content: _content, ...rest } = file;
@@ -11675,6 +12417,10 @@ function generateSnapshot(configInput, options) {
11675
12417
  incomplete,
11676
12418
  warnings
11677
12419
  };
12420
+ if (partitioned.warnings.length > 0) {
12421
+ manifest.warnings.push(...partitioned.warnings);
12422
+ manifest.totals.warningCount = manifest.warnings.length;
12423
+ }
11678
12424
  manifest.totals.redactedLines = secretFindings.length;
11679
12425
  manifest.totals.warningCount = manifest.warnings.length;
11680
12426
  if (files.some((file) => file.isPreviewTruncated) && config.largeFileBytes < config.maxPartBytes) {
@@ -11707,11 +12453,9 @@ function generateSnapshot(configInput, options) {
11707
12453
  let projectTree = null;
11708
12454
  if (config.artifacts.projectTree) {
11709
12455
  projectTree = generateProjectTree(files.map((file) => file.relativePath));
11710
- const depthMarker = /\[tree truncated at (\d+) levels\]/.exec(projectTree);
11711
- if (depthMarker) {
11712
- manifest.warnings.push(
11713
- `reports/project-tree.md was truncated at the ${depthMarker[1]}-level depth cap: deeper directories are not listed there.`
11714
- );
12456
+ const truncations = treeTruncationWarnings(projectTree);
12457
+ if (truncations.length > 0) {
12458
+ manifest.warnings.push(...truncations);
11715
12459
  manifest.totals.warningCount = manifest.warnings.length;
11716
12460
  }
11717
12461
  }
@@ -11733,13 +12477,22 @@ function generateSnapshot(configInput, options) {
11733
12477
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
11734
12478
  const readmeText = artifacts.readme ? generateReadme(manifest, artifacts) : null;
11735
12479
  if (readmeText !== null) manifest.artifacts.readme = artifactRecord(readmeText);
12480
+ const promptText = artifacts.prompt ? generatePrompt(
12481
+ manifest,
12482
+ artifacts,
12483
+ config.attachmentSlots,
12484
+ // Commit subjects are user input and reach an artifact, so they go through the same
12485
+ // masking as every other name the run reproduces.
12486
+ recentCommitSubjects(config.cwd).map((subject) => maskPathText(subject, config.secretRules))
12487
+ ) : null;
12488
+ if (promptText !== null) manifest.artifacts.prompt = artifactRecord(promptText);
11736
12489
  if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
11737
12490
  let monolithJson = null;
11738
12491
  let monolithMarkdown = null;
11739
12492
  if (config.includeMonolith) {
11740
12493
  const fullFiles = files.map((file) => {
11741
12494
  const content = fullContents.get(file.relativePath) ?? "";
11742
- return {
12495
+ const entry = {
11743
12496
  ...file,
11744
12497
  content,
11745
12498
  inclusionMode: "full",
@@ -11747,6 +12500,9 @@ function generateSnapshot(configInput, options) {
11747
12500
  includedBytes: Buffer.byteLength(content, "utf8"),
11748
12501
  includedLines: countLines(content)
11749
12502
  };
12503
+ delete entry.truncationReason;
12504
+ delete entry.omittedRanges;
12505
+ return entry;
11750
12506
  });
11751
12507
  const bodyBytes = fullFiles.reduce((total, file) => total + file.includedBytes, 0);
11752
12508
  const definitelyTooLarge = config.maxMonolithBytes !== null && bodyBytes > config.maxMonolithBytes;
@@ -11867,6 +12623,9 @@ function generateSnapshot(configInput, options) {
11867
12623
  if (readmeText !== null) {
11868
12624
  writeArtifact(stagingDir, "README.md", readmeText);
11869
12625
  }
12626
+ if (promptText !== null) {
12627
+ writeArtifact(stagingDir, "PROMPT.md", promptText);
12628
+ }
11870
12629
  if (artifacts.manifest) {
11871
12630
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
11872
12631
  }
@@ -12174,8 +12933,8 @@ function partPathFor(workspace, filename) {
12174
12933
  if (filename.length === 0 || filename.includes("\0")) return null;
12175
12934
  const partsDir = path16__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
12176
12935
  const resolved = path16__namespace.resolve(partsDir, filename);
12177
- const relative14 = path16__namespace.relative(partsDir, resolved);
12178
- if (relative14.length === 0 || relative14.includes(path16__namespace.sep) || relative14.includes("/") || relative14.includes("\\") || path16__namespace.isAbsolute(relative14)) {
12936
+ const relative15 = path16__namespace.relative(partsDir, resolved);
12937
+ if (relative15.length === 0 || relative15.includes(path16__namespace.sep) || relative15.includes("/") || relative15.includes("\\") || path16__namespace.isAbsolute(relative15)) {
12179
12938
  return null;
12180
12939
  }
12181
12940
  let stats;
@@ -12344,11 +13103,11 @@ function toRelativePath(root, value) {
12344
13103
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12345
13104
  const resolvedRoot = path16__namespace.resolve(root);
12346
13105
  const absolute = path16__namespace.resolve(resolvedRoot, cleaned);
12347
- const relative14 = path16__namespace.relative(resolvedRoot, absolute);
12348
- if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative14)) {
13106
+ const relative15 = path16__namespace.relative(resolvedRoot, absolute);
13107
+ if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path16__namespace.sep}`) || path16__namespace.isAbsolute(relative15)) {
12349
13108
  return null;
12350
13109
  }
12351
- return relative14.split(path16__namespace.sep).join("/");
13110
+ return relative15.split(path16__namespace.sep).join("/");
12352
13111
  }
12353
13112
  function symbolsOf(entry) {
12354
13113
  const summary = entry.summary;
@@ -12506,45 +13265,38 @@ var planTool = {
12506
13265
  const prepared = await prepare(args, context, workspaceOverrides(args));
12507
13266
  if (!prepared.ok) return prepared.outcome;
12508
13267
  const workspace = prepared.workspace;
12509
- let manifest;
12510
- try {
12511
- manifest = generateSnapshot(workspace.config, { dryRun: true });
12512
- } catch (error) {
12513
- return failure(error instanceof Error ? error.message : String(error));
12514
- }
12515
- const reasons = /* @__PURE__ */ new Map();
12516
- for (const record of manifest.skipped) {
12517
- reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
12518
- }
12519
- const topReasons = [...reasons.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 8).map(([reason, count]) => ({ reason, count }));
13268
+ const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
13269
+ if (!result.ok) return failure(result.message);
13270
+ const summary = result.summary;
13271
+ const topReasons = summary.skipReasons;
12520
13272
  const lines = [
12521
13273
  "Dry run \u2014 nothing was written.",
12522
- `Preset: ${manifest.config.preset}`,
12523
- `Would include ${plural(manifest.counts.totalFiles, "file")} in ${plural(manifest.counts.partsCount, "part")} (${formatBytes(manifest.counts.totalSizeBytes)} of source, ${formatBytes(manifest.totals.totalContentBytes)} emitted).`,
12524
- `Would skip ${plural(manifest.counts.skippedCount, "file")}.`
13274
+ `Preset: ${summary.preset}`,
13275
+ `Would include ${plural(summary.totalFiles, "file")} in ${plural(summary.partsCount, "part")} (${formatBytes(summary.totalSizeBytes)} of source, ${formatBytes(summary.totalContentBytes)} emitted).`,
13276
+ `Would skip ${plural(summary.skippedCount, "file")}.`
12525
13277
  ];
12526
13278
  if (topReasons.length > 0) {
12527
13279
  lines.push("Top skip reasons:");
12528
13280
  for (const entry of topReasons) lines.push(` - ${entry.reason} (${entry.count})`);
12529
13281
  }
12530
- if (manifest.warnings.length > 0) {
12531
- lines.push(`Warnings (${manifest.warnings.length}):`);
12532
- for (const warning of manifest.warnings.slice(0, 5)) lines.push(` - ${warning}`);
13282
+ if (summary.warnings.length > 0) {
13283
+ lines.push(`Warnings (${summary.warnings.length}):`);
13284
+ for (const warning of summary.warnings.slice(0, 5)) lines.push(` - ${warning}`);
12533
13285
  }
12534
13286
  return {
12535
13287
  text: lines.join("\n"),
12536
13288
  structured: {
12537
- files: manifest.counts.totalFiles,
12538
- skipped: manifest.counts.skippedCount,
12539
- parts: manifest.counts.partsCount,
12540
- sourceBytes: manifest.counts.totalSizeBytes,
12541
- emittedBytes: manifest.totals.totalContentBytes,
12542
- preset: manifest.config.preset,
12543
- maxPartBytes: manifest.budgets.maxPartBytes,
12544
- layers: manifest.layers,
13289
+ files: summary.totalFiles,
13290
+ skipped: summary.skippedCount,
13291
+ parts: summary.partsCount,
13292
+ sourceBytes: summary.totalSizeBytes,
13293
+ emittedBytes: summary.totalContentBytes,
13294
+ preset: summary.preset,
13295
+ maxPartBytes: workspace.config.maxPartBytes,
13296
+ layers: summary.layers,
12545
13297
  skipReasons: topReasons,
12546
- warnings: manifest.warnings.slice(0, 5),
12547
- warningCount: manifest.warnings.length
13298
+ warnings: summary.warnings.slice(0, 5),
13299
+ warningCount: summary.warnings.length
12548
13300
  }
12549
13301
  };
12550
13302
  }
@@ -13290,6 +14042,7 @@ var VALIDATE_OPTIONS = [
13290
14042
  "max-part-tokens",
13291
14043
  "large-file-bytes",
13292
14044
  "max-monolith-bytes",
14045
+ "max-parts",
13293
14046
  "include-monolith",
13294
14047
  "include-sensitive-files",
13295
14048
  "skip-artifacts",
@@ -13315,6 +14068,8 @@ var COMMAND_OPTION_SCOPE = {
13315
14068
  "max-part-tokens",
13316
14069
  "large-file-bytes",
13317
14070
  "max-monolith-bytes",
14071
+ "attachment-slots",
14072
+ "max-parts",
13318
14073
  "include-monolith",
13319
14074
  "include-sensitive-files",
13320
14075
  "skip-artifacts",
@@ -13460,6 +14215,7 @@ var PACKAGE_NAME = "codebase-snapshot";
13460
14215
  var MAJOR_VERSION = GENERATOR_VERSION.split(".")[0];
13461
14216
  var ARTIFACT_SUMMARY = {
13462
14217
  readme: "README.md describing the snapshot at the output root.",
14218
+ prompt: "PROMPT.md: the instruction sheet to paste with the snapshot, rendered from its manifest.",
13463
14219
  manifest: "manifest.json: machine-readable index of every file, part, hash and config.",
13464
14220
  parts: "parts/*.md: the packed, budget-limited markdown parts that carry the code.",
13465
14221
  navigation: "reports/navigation.md: links between parts and layers.",
@@ -13469,6 +14225,7 @@ var ARTIFACT_SUMMARY = {
13469
14225
  };
13470
14226
  var ARTIFACT_DEFAULTS = {
13471
14227
  readme: true,
14228
+ prompt: true,
13472
14229
  manifest: true,
13473
14230
  parts: true,
13474
14231
  navigation: true,
@@ -13609,9 +14366,9 @@ function buildAgentContract() {
13609
14366
  {
13610
14367
  step: 6,
13611
14368
  id: "consume",
13612
- run: "read ./snapshot/parts/*.md, then ./snapshot/manifest.json, then ./snapshot/reports/audit.md",
14369
+ run: "read ./snapshot/PROMPT.md first, then ./snapshot/parts/*.md, ./snapshot/manifest.json and ./snapshot/reports/audit.md",
13613
14370
  expect: "the code, the index of what was included, and the risk findings",
13614
- notes: "manifest.json.files[] lists every included file with layer, kind, language, part and summary. manifest.skipped[] explains every file that was left out and why; manifest.incomplete[] lists every included file that is not present in full, with its missing line ranges."
14371
+ notes: "manifest.json.files[] lists every included file with layer, kind, language, part and summary. manifest.skipped[] explains every file that was left out and why; manifest.incomplete[] lists every included file that is not present in full, with its missing line ranges. PROMPT.md is the instruction sheet for whoever reads the snapshot; it is rendered from the manifest, so it names this run's omissions rather than describing snapshots in general."
13615
14372
  }
13616
14373
  ],
13617
14374
  commands: [
@@ -13748,6 +14505,20 @@ function buildAgentContract() {
13748
14505
  appliesTo: optionAppliesTo("discovery"),
13749
14506
  summary: "How files are discovered: auto (git when usable), git (require git), walk (read .gitignore files directly, including nested ones; the escape hatch for a .git that cannot be listed)."
13750
14507
  },
14508
+ {
14509
+ flag: "--attachment-slots",
14510
+ type: "number",
14511
+ default: "10",
14512
+ appliesTo: optionAppliesTo("attachment-slots"),
14513
+ summary: "Files the destination accepts in one message (0 = no limit). PROMPT.md plans the delivery against it: which parts to attach, what to leave behind, and the part budget that would merge them. It does not change the payload."
14514
+ },
14515
+ {
14516
+ flag: "--max-parts",
14517
+ type: "number",
14518
+ default: "unset",
14519
+ appliesTo: optionAppliesTo("max-parts"),
14520
+ summary: "Experimental: grow the per-part budget until the snapshot has at most this many parts. The budget it settles on is recorded in manifest.budgets.maxPartBytes and may exceed maxPartBytes; a warning says so."
14521
+ },
13751
14522
  {
13752
14523
  flag: "--skip-artifacts",
13753
14524
  type: "string",
@@ -13961,6 +14732,8 @@ function buildAgentContract() {
13961
14732
  { key: "includeSensitiveFiles", type: "boolean", default: false, summary: "Emit .env / *.pem / credential files." },
13962
14733
  { key: "include", type: "string[]", default: "[]", summary: "Allow-list of globs; empty means everything." },
13963
14734
  { key: "excludePatterns", type: "string[]", default: "[]", summary: "Extra exclude globs." },
14735
+ { key: "maxParts", type: "number | null", default: null, summary: "Experimental: the most parts a snapshot may have. The per-part budget grows to fit, up to the run's own needs; the effective ceiling is recorded in manifest.budgets.maxPartBytes and may exceed maxPartBytes." },
14736
+ { key: "attachmentSlots", type: "number", default: 10, summary: "Files the destination accepts in one message (0 = no limit); PROMPT.md plans the delivery to fit. It does not change the payload, and it is not part of the config digest." },
13964
14737
  { key: "discovery", type: '"auto" | "git" | "walk"', default: "auto", summary: "How files are discovered; `walk` scans the tree and reads .gitignore directly when a .git directory cannot be listed." },
13965
14738
  { key: "artifacts", type: "object", default: "all on except monolith", summary: "Per-artifact opt-out." },
13966
14739
  { key: "budgets", type: "object", default: "{ default, byLayer }", summary: "Per-layer byte budgets." },
@@ -13968,12 +14741,14 @@ function buildAgentContract() {
13968
14741
  { key: "layers", type: "array", default: "preset layers", summary: "Custom layer rules (glob or RegExp)." },
13969
14742
  { key: "kinds", type: "array", default: "preset kinds", summary: "Custom kind rules." },
13970
14743
  { key: "secrets", type: "object", default: "{}", summary: "Custom secret patterns, or disable the defaults." },
14744
+ { key: "secretRules", type: "array", default: "[]", summary: "Full secret-rule list: the library spelling of secrets.customPatterns. The built-ins are prepended unless secrets.disableDefaultPatterns is set." },
13971
14745
  { key: "hooks", type: "object", default: "{}", summary: "afterGenerate(manifest) runs after a successful generate." }
13972
14746
  ]
13973
14747
  },
13974
14748
  output: {
13975
14749
  layout: [
13976
14750
  "<outDir>/README.md",
14751
+ "<outDir>/PROMPT.md",
13977
14752
  "<outDir>/manifest.json",
13978
14753
  "<outDir>/parts/part-NNN.md",
13979
14754
  "<outDir>/reports/project-tree.md",
@@ -13984,7 +14759,10 @@ function buildAgentContract() {
13984
14759
  notes: [
13985
14760
  "Parts are ordered and budget-limited; a file that cannot fit one part is emitted as a head/tail preview, and every file not present in full is listed in manifest.json incomplete[] with the missing line ranges.",
13986
14761
  "manifest.json.files[] carries relativePath, layer, kind, language, part, inclusionMode, truncationReason, omittedRanges and hash; manifest.json.incomplete[] lists every file not present in full; `summary` is conditional \u2014 it is absent for languages with no structural summary, and `summaryOmitted: true` marks a summary dropped to fit the part budget; encoding appears when the file was not plain UTF-8.",
14762
+ "indexes.imports.byFile includes previewed files (their import specifiers are still extracted); such an entry carries `exportsOmitted: true` instead of pretending it exports nothing.",
14763
+ "validate re-checks manifest.incomplete[] against files[] and refuses a manifest whose two statements of what is missing disagree.",
13987
14764
  "manifest.skipped[] carries the path and the exact reason it was excluded.",
14765
+ "PROMPT.md is rendered from the manifest of the run that wrote it \u2014 its parts, partial files, skip tallies and fingerprint are that run's \u2014 and manifest.artifacts.prompt records its digest, so an edited prompt fails validate.",
13988
14766
  `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
13989
14767
  ]
13990
14768
  },
@@ -14155,6 +14933,10 @@ do not assume the repository is broken.
14155
14933
  - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
14156
14934
  state. Read this before you quote code back to a user.
14157
14935
  - \`snapshot/reports/project-tree.md\` and \`navigation.md\` \u2014 structure and cross-links.
14936
+ - \`snapshot/PROMPT.md\` \u2014 the instruction sheet to hand to the model that receives the
14937
+ snapshot: paste it with the parts. It is rendered from this run's manifest and names the
14938
+ parts, the partial files and the fingerprint, so do not rewrite it by hand \u2014 \`validate\`
14939
+ fails when it was edited.
14158
14940
 
14159
14941
  ## Project types
14160
14942
 
@@ -14977,11 +15759,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
14977
15759
  function createWriter(output) {
14978
15760
  return {
14979
15761
  write(value) {
14980
- return new Promise((resolve11, reject) => {
15762
+ return new Promise((resolve12, reject) => {
14981
15763
  output.write(`${JSON.stringify(value)}
14982
15764
  `, (error) => {
14983
15765
  if (error) reject(error);
14984
- else resolve11();
15766
+ else resolve12();
14985
15767
  });
14986
15768
  });
14987
15769
  }
@@ -15118,8 +15900,8 @@ async function runStdioServer(options) {
15118
15900
  let inFlight = 0;
15119
15901
  let inputEnded = false;
15120
15902
  let resolveDone = () => void 0;
15121
- const finished = new Promise((resolve11) => {
15122
- resolveDone = resolve11;
15903
+ const finished = new Promise((resolve12) => {
15904
+ resolveDone = resolve12;
15123
15905
  });
15124
15906
  const finishIfIdle = () => {
15125
15907
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -15216,6 +15998,8 @@ var CLI_OPTIONS = {
15216
15998
  "max-part-bytes": { type: "string" },
15217
15999
  "large-file-bytes": { type: "string" },
15218
16000
  "max-monolith-bytes": { type: "string" },
16001
+ "attachment-slots": { type: "string" },
16002
+ "max-parts": { type: "string" },
15219
16003
  "include-monolith": { type: "boolean" },
15220
16004
  "include-sensitive-files": { type: "boolean" },
15221
16005
  "skip-artifacts": { type: "string" },
@@ -15290,6 +16074,10 @@ Options:
15290
16074
  --skeleton Emit TypeScript signatures instead of bodies
15291
16075
  --sarif Also write reports/audit.sarif for GitHub Code Scanning
15292
16076
  --include-sensitive-files Emit .env / *.pem / .npmrc / credential files
16077
+ --attachment-slots <n> Files the destination takes in one message (default: 10,
16078
+ 0 = no limit); PROMPT.md plans the delivery to fit
16079
+ --max-parts <n> Experimental: grow the part budget until the snapshot has at
16080
+ most n parts, instead of adding parts as the code grows
15293
16081
  --skip-artifacts <names> Comma-separated artifacts to omit
15294
16082
  (readme, manifest, parts, navigation,
15295
16083
  projectTree, audit, monolith)
@@ -15360,6 +16148,20 @@ function parseByteOption(raw, optionName, minimum, unit = "byte count") {
15360
16148
  }
15361
16149
  return value;
15362
16150
  }
16151
+ function parseCountOption(raw, optionName, minimum = 0) {
16152
+ if (raw === void 0) return void 0;
16153
+ const trimmed = raw.trim();
16154
+ if (!/^\d+$/.test(trimmed) || !Number.isSafeInteger(Number(trimmed))) {
16155
+ throw new UsageError(
16156
+ `--${optionName} expects a whole number such as 10 or 20, received "${raw}".`
16157
+ );
16158
+ }
16159
+ const value = Number(trimmed);
16160
+ if (value < minimum) {
16161
+ throw new UsageError(`--${optionName} must be at least ${minimum}, received "${raw}".`);
16162
+ }
16163
+ return value;
16164
+ }
15363
16165
  function parseArtifactList(raw, flag) {
15364
16166
  const names = raw.split(",").map((name) => name.trim()).filter(Boolean);
15365
16167
  if (names.length === 0) {
@@ -15601,6 +16403,11 @@ function parseCliArgs(argv) {
15601
16403
  "max-monolith-bytes",
15602
16404
  1
15603
16405
  ),
16406
+ attachmentSlots: parseCountOption(
16407
+ values["attachment-slots"],
16408
+ "attachment-slots"
16409
+ ),
16410
+ maxParts: parseCountOption(values["max-parts"], "max-parts", 1),
15604
16411
  skipArtifacts,
15605
16412
  onlyArtifacts,
15606
16413
  discovery: isDiscoveryMode(rawDiscovery) ? rawDiscovery : void 0,
@@ -15655,8 +16462,8 @@ function splitList(value) {
15655
16462
  }
15656
16463
  function displayOutPath(cwd, outDir, ...segments) {
15657
16464
  const absolute = path16__namespace.resolve(cwd, outDir, ...segments);
15658
- const relative14 = path16__namespace.relative(cwd, absolute);
15659
- if (relative14 && !relative14.startsWith("..") && !path16__namespace.isAbsolute(relative14)) return relative14;
16465
+ const relative15 = path16__namespace.relative(cwd, absolute);
16466
+ if (relative15 && !relative15.startsWith("..") && !path16__namespace.isAbsolute(relative15)) return relative15;
15660
16467
  return absolute;
15661
16468
  }
15662
16469
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -15664,7 +16471,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
15664
16471
  if (!hasScript) {
15665
16472
  try {
15666
16473
  const parsed = JSON.parse(
15667
- stripJsonComments2(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"))
16474
+ stripJsonComments(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"))
15668
16475
  );
15669
16476
  hasScript = typeof parsed.scripts?.snapshot === "string";
15670
16477
  } catch {
@@ -15731,7 +16538,9 @@ async function runInitCommand(invocation) {
15731
16538
  }
15732
16539
  function generatorOrigin(cwd) {
15733
16540
  try {
15734
- const pkg = JSON.parse(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"));
16541
+ const pkg = JSON.parse(
16542
+ stripJsonComments(fs15__namespace.readFileSync(path16__namespace.join(cwd, "package.json"), "utf8"))
16543
+ );
15735
16544
  const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
15736
16545
  if (typeof spec === "string") return `project dependency ${spec}`;
15737
16546
  } catch {
@@ -15924,6 +16733,12 @@ async function runSetupCommand(invocation, options = {}) {
15924
16733
  if (invocation.maxPartTokens !== void 0) {
15925
16734
  generateArgs.push("--max-part-tokens", String(invocation.maxPartTokens));
15926
16735
  }
16736
+ if (invocation.attachmentSlots !== void 0) {
16737
+ generateArgs.push("--attachment-slots", String(invocation.attachmentSlots));
16738
+ }
16739
+ if (invocation.maxParts !== void 0) {
16740
+ generateArgs.push("--max-parts", String(invocation.maxParts));
16741
+ }
15927
16742
  if (invocation.skeleton === true) generateArgs.push("--skeleton");
15928
16743
  if (invocation.sarif === true) generateArgs.push("--sarif");
15929
16744
  if (invocation.noUpdateCheck) generateArgs.push("--no-update-check");
@@ -16028,6 +16843,8 @@ function runSkillCommand(invocation) {
16028
16843
  function renderValidateText(result) {
16029
16844
  if (result.valid) {
16030
16845
  info("\u2705 Snapshot is valid and up to date with disk.");
16846
+ } else if (result.errors.length === 1 && result.errors[0].includes(" is not a snapshot manifest: ")) {
16847
+ warn(`\u274C ${result.errors[0]}`);
16031
16848
  } else {
16032
16849
  warn("\u274C Snapshot validation failed:");
16033
16850
  for (const error of result.errors) warn(` - ${error}`);
@@ -16164,6 +16981,8 @@ ${USAGE}
16164
16981
  maxPartTokens: invocation.maxPartTokens,
16165
16982
  largeFileBytes: invocation.largeFileBytes,
16166
16983
  maxMonolithBytes: invocation.maxMonolithBytes,
16984
+ attachmentSlots: invocation.attachmentSlots,
16985
+ maxParts: invocation.maxParts,
16167
16986
  skipArtifacts: invocation.skipArtifacts,
16168
16987
  // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
16169
16988
  // suppression cannot switch an artifact *on*, so a config that had turned one of the
@@ -16233,7 +17052,11 @@ ${USAGE}
16233
17052
  if (invocation.command === "diff") {
16234
17053
  try {
16235
17054
  const [beforePath, afterPath] = invocation.args;
16236
- const diff = compareManifests(loadManifest(beforePath), loadManifest(afterPath));
17055
+ const diff = compareManifests(
17056
+ loadManifest(beforePath),
17057
+ loadManifest(afterPath),
17058
+ resolved.secretRules
17059
+ );
16237
17060
  emit(invocation.format, diff, () => info(renderDiffText(diff)));
16238
17061
  return 0;
16239
17062
  } catch (err) {
@@ -16288,7 +17111,7 @@ ${USAGE}
16288
17111
  const reasons = skipBreakdown.length > shownReasons.length ? `${shownReasons.join(", ")}, +${skipBreakdown.length - shownReasons.length} more` : shownReasons.join(", ");
16289
17112
  const candidates = manifest.counts.totalFiles + manifest.counts.skippedCount;
16290
17113
  info(
16291
- 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")}`
17114
+ manifest.counts.skippedCount === 0 ? ` - Tracked files: ${formatNumber(manifest.counts.totalFiles)}` : ` - Tracked files: ${formatNumber(manifest.counts.totalFiles)} included of ${formatNumber(candidates)} paths found \u2014 ${formatNumber(manifest.counts.skippedCount)} skipped (${reasons}); every one is listed in ${displayOutPath(resolved.cwd, resolved.outDir, "reports/audit.md")}`
16292
17115
  );
16293
17116
  info(` - Total lines: ${formatNumber(manifest.counts.totalLines)}`);
16294
17117
  info(
@@ -16332,7 +17155,16 @@ ${USAGE}
16332
17155
  );
16333
17156
  }
16334
17157
  }
16335
- if (reports.length === 0 && !artifacts.parts && !artifacts.manifest && !artifacts.monolith) {
17158
+ const orientation = [
17159
+ artifacts.readme ? "README.md" : null,
17160
+ artifacts.prompt ? "PROMPT.md" : null
17161
+ ].filter((name) => name !== null);
17162
+ if (orientation.length > 0) {
17163
+ info(
17164
+ ` - Orientation: ${orientation.map((name) => displayOutPath(resolved.cwd, resolved.outDir, name)).join(", ")}`
17165
+ );
17166
+ }
17167
+ if (reports.length === 0 && !artifacts.parts && !artifacts.manifest && !artifacts.monolith && orientation.length === 0) {
16336
17168
  info(` - Artifacts: all disabled (only the ownership marker was written)`);
16337
17169
  }
16338
17170
  info(` - Fingerprint: ${manifest.fingerprint}`);
@@ -16388,8 +17220,8 @@ function comparablePath(value) {
16388
17220
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
16389
17221
  }
16390
17222
  function isSameOrInside(parent, candidate) {
16391
- const relative14 = path16__namespace.relative(parent, candidate);
16392
- return relative14 === "" || relative14 !== ".." && !relative14.startsWith(`..${path16__namespace.sep}`) && !path16__namespace.isAbsolute(relative14);
17223
+ const relative15 = path16__namespace.relative(parent, candidate);
17224
+ return relative15 === "" || relative15 !== ".." && !relative15.startsWith(`..${path16__namespace.sep}`) && !path16__namespace.isAbsolute(relative15);
16393
17225
  }
16394
17226
  function isGeneratedWatchPath(candidate, paths) {
16395
17227
  const absolute = comparablePath(path16__namespace.resolve(paths.cwd, candidate));
@@ -16476,6 +17308,8 @@ async function runWatchLoop(invocation, resolved, options) {
16476
17308
  maxPartTokens: invocation.maxPartTokens,
16477
17309
  largeFileBytes: invocation.largeFileBytes,
16478
17310
  maxMonolithBytes: invocation.maxMonolithBytes,
17311
+ attachmentSlots: invocation.attachmentSlots,
17312
+ maxParts: invocation.maxParts,
16479
17313
  skipArtifacts: invocation.skipArtifacts,
16480
17314
  onlyArtifacts: invocation.onlyArtifacts,
16481
17315
  discovery: invocation.discovery,
@@ -16534,12 +17368,12 @@ async function runWatchLoop(invocation, resolved, options) {
16534
17368
  info(`\u26A0 Watch error: ${err.message}`);
16535
17369
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
16536
17370
  });
16537
- await new Promise((resolve11) => {
17371
+ await new Promise((resolve12) => {
16538
17372
  const stop = () => {
16539
17373
  stopped = true;
16540
17374
  if (timer) clearTimeout(timer);
16541
17375
  watcher.close();
16542
- resolve11();
17376
+ resolve12();
16543
17377
  };
16544
17378
  process.once("SIGINT", stop);
16545
17379
  process.once("SIGTERM", stop);
@@ -16576,6 +17410,7 @@ exports.isGeneratedWatchPath = isGeneratedWatchPath;
16576
17410
  exports.main = main;
16577
17411
  exports.parseByteOption = parseByteOption;
16578
17412
  exports.parseCliArgs = parseCliArgs;
17413
+ exports.parseCountOption = parseCountOption;
16579
17414
  exports.parsePositiveInteger = parsePositiveInteger;
16580
17415
  exports.watchPathsFor = watchPathsFor;
16581
17416
  exports.watchSupportProblem = watchSupportProblem;