@ankurhalder/codebase-snapshot 2.1.1 → 3.0.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
@@ -2109,11 +2109,12 @@ var PRESET_NAMES = [
2109
2109
  "java-spring \xB7 dotnet \xB7 php-laravel \xB7 ruby-rails",
2110
2110
  "monorepo \xB7 docs \xB7 infra \xB7 generic"
2111
2111
  ];
2112
+ var CONFIG_HEADER = `// Generated by codebase-snapshot. A plain object on purpose: this file must load
2113
+ // even when the package itself is only run through npx.
2114
+ `;
2112
2115
  function renderConfig(answers) {
2113
2116
  const { artifacts } = answers;
2114
- return `import { defineConfig } from "@ankurhalder/codebase-snapshot";
2115
-
2116
- export default defineConfig({
2117
+ return `${CONFIG_HEADER}export default {
2117
2118
  // \u2500\u2500 Project \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\u2500
2118
2119
  // Which project shape to use. Detected from the repo when omitted.
2119
2120
  // ${PRESET_NAMES.join("\n // ")}
@@ -2182,7 +2183,7 @@ export default defineConfig({
2182
2183
  // \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
2183
2184
  // afterGenerate: (manifest) => { /* write your own artifact */ }
2184
2185
  hooks: {},
2185
- });
2186
+ };
2186
2187
  `;
2187
2188
  }
2188
2189
  function renderMinimalConfig(answers) {
@@ -2210,16 +2211,12 @@ ${entries},
2210
2211
  },`);
2211
2212
  }
2212
2213
  if (lines.length === 0) {
2213
- return `import { defineConfig } from "@ankurhalder/codebase-snapshot";
2214
-
2215
- export default defineConfig({});
2214
+ return `${CONFIG_HEADER}export default {};
2216
2215
  `;
2217
2216
  }
2218
- return `import { defineConfig } from "@ankurhalder/codebase-snapshot";
2219
-
2220
- export default defineConfig({
2217
+ return `${CONFIG_HEADER}export default {
2221
2218
  ${lines.join("\n")}
2222
- });
2219
+ };
2223
2220
  `;
2224
2221
  }
2225
2222
  var PromptCancelled = class extends Error {
@@ -2480,6 +2477,17 @@ var CONFIG_CANDIDATES = [
2480
2477
  ".snapshotrc.json",
2481
2478
  ".snapshotrc"
2482
2479
  ];
2480
+ function chooseConfigFileName(cwd) {
2481
+ if (!supportsTypeScriptImports()) return "snapshot.config.mjs";
2482
+ const pkgPath = path10__namespace.join(cwd, "package.json");
2483
+ if (!fs9__namespace.existsSync(pkgPath)) return "snapshot.config.mjs";
2484
+ try {
2485
+ const parsed = JSON.parse(fs9__namespace.readFileSync(pkgPath, "utf8"));
2486
+ return parsed.type === "module" ? "snapshot.config.ts" : "snapshot.config.mjs";
2487
+ } catch {
2488
+ return "snapshot.config.mjs";
2489
+ }
2490
+ }
2483
2491
  var SIZE_CHOICES = [
2484
2492
  { value: "60k", label: "Small", hint: "60 KB \xB7 ~15k tokens \xB7 tight context windows" },
2485
2493
  { value: "120k", label: "Medium", hint: "120 KB \xB7 ~30k tokens \xB7 recommended" },
@@ -2685,7 +2693,7 @@ async function runInit(options) {
2685
2693
  if (!proceed) throw new PromptCancelled();
2686
2694
  }
2687
2695
  const configText = options.minimal ? renderMinimalConfig(answers) : renderConfig(answers);
2688
- const configName = supportsTypeScriptImports() ? "snapshot.config.ts" : "snapshot.config.mjs";
2696
+ const configName = chooseConfigFileName(options.cwd);
2689
2697
  const configPath = path10__namespace.join(options.cwd, configName);
2690
2698
  if (options.dryRun) {
2691
2699
  return {
@@ -2943,9 +2951,9 @@ var JAVA_METHOD = /^\s+(?:public|private|protected)\s+(?:static\s+)?(?:final\s+)
2943
2951
  var jvmProfile = {
2944
2952
  id: "jvm",
2945
2953
  extensions: [".java", ".kt", ".kts", ".scala"],
2946
- summarize(path12, content) {
2954
+ summarize(path13, content) {
2947
2955
  const summary = emptySummary();
2948
- const lower = path12.toLowerCase();
2956
+ const lower = path13.toLowerCase();
2949
2957
  const isJava = lower.endsWith(".java");
2950
2958
  const isKotlin = lower.endsWith(".kt") || lower.endsWith(".kts");
2951
2959
  eachLine(content, (line) => {
@@ -3366,16 +3374,16 @@ function summarizeTypeScriptSource(relativePath, content) {
3366
3374
  // src/ast/profiles/sfc.ts
3367
3375
  var SCRIPT_BLOCK = /<script[^>]*>([\s\S]*?)<\/script>/gi;
3368
3376
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
3369
- function componentName(path12) {
3370
- const base = path12.split("/").pop() ?? path12;
3377
+ function componentName(path13) {
3378
+ const base = path13.split("/").pop() ?? path13;
3371
3379
  return base.replace(/\.[^.]+$/, "");
3372
3380
  }
3373
3381
  var sfcProfile = {
3374
3382
  id: "sfc",
3375
3383
  extensions: [".vue", ".svelte", ".astro"],
3376
- summarize(path12, content) {
3384
+ summarize(path13, content) {
3377
3385
  let script = "";
3378
- if (path12.toLowerCase().endsWith(".astro")) {
3386
+ if (path13.toLowerCase().endsWith(".astro")) {
3379
3387
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
3380
3388
  if (frontmatter) script += `${frontmatter[1]}
3381
3389
  `;
@@ -3384,7 +3392,7 @@ var sfcProfile = {
3384
3392
  script += `${match[1]}
3385
3393
  `;
3386
3394
  }
3387
- const name = componentName(path12);
3395
+ const name = componentName(path13);
3388
3396
  if (!script.trim()) {
3389
3397
  const summary2 = emptySummary();
3390
3398
  if (name) {
@@ -3418,15 +3426,15 @@ for (const profile of LANGUAGE_PROFILES) {
3418
3426
  BY_EXTENSION.set(extension.toLowerCase(), profile);
3419
3427
  }
3420
3428
  }
3421
- function profileForPath(path12) {
3422
- const lower = path12.toLowerCase();
3429
+ function profileForPath(path13) {
3430
+ const lower = path13.toLowerCase();
3423
3431
  const dot = lower.lastIndexOf(".");
3424
3432
  if (dot === -1) return null;
3425
3433
  return BY_EXTENSION.get(lower.slice(dot)) ?? null;
3426
3434
  }
3427
- function summarizeWithProfile(path12, content) {
3428
- const profile = profileForPath(path12);
3429
- return profile ? profile.summarize(path12, content) : null;
3435
+ function summarizeWithProfile(path13, content) {
3436
+ const profile = profileForPath(path13);
3437
+ return profile ? profile.summarize(path13, content) : null;
3430
3438
  }
3431
3439
 
3432
3440
  // src/ast/structured.ts
@@ -4547,7 +4555,7 @@ function validateSnapshot(configInput) {
4547
4555
 
4548
4556
  // src/index.ts
4549
4557
  var GENERATOR_NAME = "@ankurhalder/codebase-snapshot";
4550
- var GENERATOR_VERSION = "2.1.1";
4558
+ var GENERATOR_VERSION = "3.0.0";
4551
4559
  var SCHEMA_VERSION = "3.0.0";
4552
4560
  function sha256Hex2(input) {
4553
4561
  return crypto__namespace.createHash("sha256").update(input).digest("hex");
@@ -5120,6 +5128,631 @@ function generateSnapshot(configInput, options) {
5120
5128
  return manifest;
5121
5129
  }
5122
5130
 
5131
+ // src/agent/contract.ts
5132
+ var CONTRACT_VERSION = "1.0.0";
5133
+ var PACKAGE_NAME = "@ankurhalder/codebase-snapshot";
5134
+ var ARTIFACT_SUMMARY = {
5135
+ readme: "README.md describing the snapshot at the output root.",
5136
+ manifest: "manifest.json: machine-readable index of every file, part, hash and config.",
5137
+ parts: "parts/*.md: the packed, budget-limited markdown parts that carry the code.",
5138
+ navigation: "reports/navigation.md: links between parts and layers.",
5139
+ projectTree: "reports/project-tree.md: the directory tree of included files.",
5140
+ audit: "reports/audit.md: secret findings, large files, parse diagnostics, git state.",
5141
+ monolith: "full-codebase.json and full-codebase.md: the whole repository in one file (off by default)."
5142
+ };
5143
+ var ARTIFACT_DEFAULTS = {
5144
+ readme: true,
5145
+ manifest: true,
5146
+ parts: true,
5147
+ navigation: true,
5148
+ projectTree: true,
5149
+ audit: true,
5150
+ monolith: false
5151
+ };
5152
+ function renderContractText(contract) {
5153
+ const lines = [];
5154
+ lines.push(`${contract.package} v${contract.version}`);
5155
+ lines.push(contract.summary);
5156
+ lines.push("");
5157
+ lines.push(`Node : ${contract.requires.node}`);
5158
+ lines.push(`Schema : ${contract.schemaVersion} (contract ${contract.contractVersion})`);
5159
+ lines.push(`One-shot : ${contract.invocation.oneShot} <command>`);
5160
+ lines.push(`Installed : ${contract.invocation.installed} <command>`);
5161
+ lines.push("");
5162
+ lines.push("Workflow:");
5163
+ for (const step of contract.workflow) {
5164
+ lines.push(` ${step.step}. ${step.id}`);
5165
+ lines.push(` run : ${step.run}`);
5166
+ lines.push(` expect : ${step.expect}`);
5167
+ if (step.notes) lines.push(` note : ${step.notes}`);
5168
+ }
5169
+ lines.push("");
5170
+ lines.push("Commands:");
5171
+ for (const command of contract.commands) {
5172
+ const args = command.positionals.length > 0 ? ` ${command.positionals.join(" ")}` : "";
5173
+ lines.push(` ${(command.name + args).padEnd(26)} ${command.summary}`);
5174
+ }
5175
+ lines.push("");
5176
+ lines.push("Exit codes:");
5177
+ for (const [code, meaning] of Object.entries(contract.exitCodes)) {
5178
+ lines.push(` ${code} ${meaning}`);
5179
+ }
5180
+ lines.push("");
5181
+ lines.push(`Presets (${contract.presets.length}): ${contract.presets.map((p) => p.name).join(", ")}`);
5182
+ lines.push("");
5183
+ lines.push("Artifacts:");
5184
+ for (const artifact of contract.artifacts) {
5185
+ lines.push(` ${artifact.name.padEnd(12)} ${artifact.default ? "on " : "off"} ${artifact.summary}`);
5186
+ }
5187
+ lines.push("");
5188
+ lines.push("Options:");
5189
+ for (const option of contract.options) {
5190
+ const fallback = option.default === void 0 ? "" : ` [${JSON.stringify(option.default)}]`;
5191
+ lines.push(` ${option.flag.padEnd(24)} ${option.appliesTo.padEnd(32)}${fallback}`);
5192
+ lines.push(` ${"".padEnd(24)} ${option.summary}`);
5193
+ }
5194
+ lines.push("");
5195
+ lines.push("Safety:");
5196
+ for (const note of contract.safety) lines.push(` - ${note}`);
5197
+ lines.push("");
5198
+ lines.push("Troubleshooting:");
5199
+ for (const item of contract.troubleshooting) {
5200
+ lines.push(` ${item.symptom}`);
5201
+ lines.push(` cause: ${item.cause}`);
5202
+ lines.push(` fix : ${item.fix}`);
5203
+ }
5204
+ lines.push("");
5205
+ lines.push("This is the human rendering. Agents should use: describe --format json");
5206
+ return lines.join("\n");
5207
+ }
5208
+ function buildAgentContract() {
5209
+ return {
5210
+ generator: GENERATOR_NAME,
5211
+ package: PACKAGE_NAME,
5212
+ version: GENERATOR_VERSION,
5213
+ schemaVersion: SCHEMA_VERSION,
5214
+ contractVersion: CONTRACT_VERSION,
5215
+ summary: "Turns a repository into an LLM-ready snapshot: code packed into size-budgeted markdown parts, plus a manifest, a project tree, navigation and a secret audit. Auto-detects the project shape (framework, language, monorepo, docs, infra).",
5216
+ requires: { node: ">=18.0.0", dependencies: ["typescript"] },
5217
+ invocation: {
5218
+ oneShot: `npx ${PACKAGE_NAME}@latest`,
5219
+ installed: "npx codebase-snapshot",
5220
+ bins: ["codebase-snapshot"],
5221
+ notes: [
5222
+ `The bare package name also works: npx ${PACKAGE_NAME} <command>.`,
5223
+ "Pin @latest (or @2) when you need the exact same version on every machine.",
5224
+ "This package exposes exactly one executable on purpose: npm cannot infer which one to run for a scoped package that ships several.",
5225
+ "Human progress goes to stderr. With --format json the payload on stdout is pure JSON."
5226
+ ]
5227
+ },
5228
+ workflow: [
5229
+ {
5230
+ step: 1,
5231
+ id: "verify",
5232
+ run: `npx ${PACKAGE_NAME}@latest --version`,
5233
+ expect: "prints v2.x.x on stdout and exits 0",
5234
+ notes: "If it prints nothing, clear the npm cache and retry, or use `npx -p <pkg> codebase-snapshot`."
5235
+ },
5236
+ {
5237
+ step: 2,
5238
+ id: "understand",
5239
+ run: `npx ${PACKAGE_NAME}@latest describe --format json`,
5240
+ expect: "the full contract as JSON: commands, options, presets, exit codes",
5241
+ notes: "Read this before acting if you have no prior knowledge of the tool."
5242
+ },
5243
+ {
5244
+ step: 3,
5245
+ id: "configure",
5246
+ run: `npx ${PACKAGE_NAME}@latest init --yes`,
5247
+ expect: "writes snapshot.config.ts listing every setting at its current value",
5248
+ notes: "Non-interactive. The detected preset is chosen automatically; override with --preset <name>. Skip this step to run on built-in defaults."
5249
+ },
5250
+ {
5251
+ step: 4,
5252
+ id: "generate",
5253
+ run: `npx ${PACKAGE_NAME}@latest generate`,
5254
+ expect: "exit 0, and ./snapshot/ written with parts, reports and manifest.json"
5255
+ },
5256
+ {
5257
+ step: 5,
5258
+ id: "verify-output",
5259
+ run: `npx ${PACKAGE_NAME}@latest validate`,
5260
+ expect: "exit 0 means the snapshot matches the files on disk",
5261
+ notes: "Exit 1 means drift or a damaged snapshot; re-run generate."
5262
+ },
5263
+ {
5264
+ step: 6,
5265
+ id: "consume",
5266
+ run: "read ./snapshot/parts/*.md, then ./snapshot/manifest.json, then ./snapshot/reports/audit.md",
5267
+ expect: "the code, the index of what was included, and the risk findings",
5268
+ 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."
5269
+ }
5270
+ ],
5271
+ commands: [
5272
+ {
5273
+ name: "generate",
5274
+ aliases: ["default"],
5275
+ summary: "Write the snapshot. This is the command you normally want.",
5276
+ positionals: [],
5277
+ exits: [0, 1]
5278
+ },
5279
+ {
5280
+ name: "validate",
5281
+ aliases: ["check"],
5282
+ summary: "Compare the snapshot on disk with the repository; exit 1 on drift.",
5283
+ positionals: [],
5284
+ exits: [0, 1]
5285
+ },
5286
+ {
5287
+ name: "report",
5288
+ aliases: [],
5289
+ summary: "Print snapshot health, layer metrics and the secret audit.",
5290
+ positionals: [],
5291
+ exits: [0, 1]
5292
+ },
5293
+ {
5294
+ name: "init",
5295
+ aliases: [],
5296
+ summary: "Write a commented snapshot.config.ts (interactive, or --yes for CI).",
5297
+ positionals: [],
5298
+ exits: [0, 1, 2]
5299
+ },
5300
+ {
5301
+ name: "explain",
5302
+ aliases: [],
5303
+ summary: "Explain how one path would be treated: layer, kind, part, skip reason.",
5304
+ positionals: ["<path>"],
5305
+ exits: [0, 1]
5306
+ },
5307
+ {
5308
+ name: "diff",
5309
+ aliases: [],
5310
+ summary: "Compare two snapshots (directories or manifest.json files).",
5311
+ positionals: ["<before>", "<after>"],
5312
+ exits: [0, 1]
5313
+ },
5314
+ {
5315
+ name: "describe",
5316
+ aliases: [],
5317
+ summary: "Print this contract. --format json for machines, text for humans.",
5318
+ positionals: [],
5319
+ exits: [0]
5320
+ },
5321
+ {
5322
+ name: "skill",
5323
+ aliases: [],
5324
+ summary: "Print the agent skill, or --install it into the repository (AGENTS.md, .claude/skills, .cursor/rules).",
5325
+ positionals: [],
5326
+ exits: [0, 1, 2]
5327
+ }
5328
+ ],
5329
+ exitCodes: {
5330
+ "0": "success (and validate: no drift)",
5331
+ "1": "drift detected, or generation refused/failed (nothing was written)",
5332
+ "2": "usage error: unknown flag/command, bad value, wrong argument count"
5333
+ },
5334
+ options: [
5335
+ {
5336
+ flag: "--out-dir",
5337
+ type: "string",
5338
+ default: "snapshot",
5339
+ appliesTo: "generate/validate/report/explain",
5340
+ summary: "Where the snapshot is written. Must not be the repo root or a directory the tool did not create."
5341
+ },
5342
+ {
5343
+ flag: "--max-part-bytes",
5344
+ type: "string",
5345
+ default: 307200,
5346
+ appliesTo: "generate/validate/report",
5347
+ summary: 'Byte budget per markdown part. Accepts "120k" / "1.5mb". Minimum 4096.'
5348
+ },
5349
+ {
5350
+ flag: "--large-file-bytes",
5351
+ type: "string",
5352
+ default: 204800,
5353
+ appliesTo: "generate/validate/report",
5354
+ summary: "Above this size a file gets a head/tail preview instead of the full body."
5355
+ },
5356
+ {
5357
+ flag: "--max-monolith-bytes",
5358
+ type: "string",
5359
+ default: "unset",
5360
+ appliesTo: "generate",
5361
+ summary: "Skip the monolith artifacts when they would exceed this size."
5362
+ },
5363
+ {
5364
+ flag: "--include-monolith",
5365
+ type: "boolean",
5366
+ default: false,
5367
+ appliesTo: "generate",
5368
+ summary: "Also write full-codebase.json and full-codebase.md."
5369
+ },
5370
+ {
5371
+ flag: "--include-sensitive-files",
5372
+ type: "boolean",
5373
+ default: false,
5374
+ appliesTo: "generate/validate/report",
5375
+ summary: "Also emit .env / *.pem / .npmrc style files. Off by default; they are recorded as skipped."
5376
+ },
5377
+ {
5378
+ flag: "--skip-artifacts",
5379
+ type: "string",
5380
+ default: "unset",
5381
+ appliesTo: "generate",
5382
+ summary: "Comma-separated artifacts to omit (readme, manifest, parts, navigation, projectTree, audit, monolith)."
5383
+ },
5384
+ {
5385
+ flag: "--only-artifacts",
5386
+ type: "string",
5387
+ default: "unset",
5388
+ appliesTo: "generate",
5389
+ summary: "Write only these artifacts. Cannot be combined with --skip-artifacts."
5390
+ },
5391
+ {
5392
+ flag: "--format",
5393
+ type: "string",
5394
+ default: "text",
5395
+ appliesTo: "all commands",
5396
+ summary: 'Output format: "text" or "json". JSON goes to stdout, progress to stderr.'
5397
+ },
5398
+ {
5399
+ flag: "--cwd",
5400
+ type: "string",
5401
+ default: "process.cwd()",
5402
+ appliesTo: "all commands",
5403
+ summary: "Repository to operate on. Must be an existing directory."
5404
+ },
5405
+ {
5406
+ flag: "--dry-run",
5407
+ type: "boolean",
5408
+ default: false,
5409
+ appliesTo: "generate",
5410
+ summary: "Compute everything and print the result without writing."
5411
+ },
5412
+ {
5413
+ flag: "--watch",
5414
+ type: "boolean",
5415
+ default: false,
5416
+ appliesTo: "generate",
5417
+ summary: "Regenerate on every change until interrupted."
5418
+ },
5419
+ {
5420
+ flag: "--preset",
5421
+ type: "string",
5422
+ default: "detected",
5423
+ appliesTo: "init",
5424
+ summary: "Force a project preset instead of detecting one. Unknown names are a usage error."
5425
+ },
5426
+ {
5427
+ flag: "--include",
5428
+ type: "string",
5429
+ default: "unset",
5430
+ appliesTo: "init",
5431
+ summary: "Comma-separated allow-list of globs to record in the generated config."
5432
+ },
5433
+ {
5434
+ flag: "--exclude",
5435
+ type: "string",
5436
+ default: "unset",
5437
+ appliesTo: "init",
5438
+ summary: "Comma-separated globs to record in the generated config."
5439
+ },
5440
+ {
5441
+ flag: "--yes",
5442
+ type: "boolean",
5443
+ default: false,
5444
+ appliesTo: "init",
5445
+ summary: "Accept every default without prompting. Required in a non-TTY."
5446
+ },
5447
+ {
5448
+ flag: "--minimal",
5449
+ type: "boolean",
5450
+ default: false,
5451
+ appliesTo: "init",
5452
+ summary: "Write only the settings that differ from the defaults."
5453
+ },
5454
+ {
5455
+ flag: "--force",
5456
+ type: "boolean",
5457
+ default: false,
5458
+ appliesTo: "init",
5459
+ summary: "Overwrite an existing config file."
5460
+ },
5461
+ {
5462
+ flag: "--install",
5463
+ type: "boolean",
5464
+ default: false,
5465
+ appliesTo: "skill",
5466
+ summary: "Write the skill into the repository instead of printing it."
5467
+ },
5468
+ {
5469
+ flag: "--target",
5470
+ type: "string",
5471
+ default: "all",
5472
+ appliesTo: "skill",
5473
+ summary: 'Where to install: "claude", "agents", "cursor" or "all".'
5474
+ }
5475
+ ],
5476
+ presets: PRESETS.map((preset) => ({
5477
+ name: preset.name,
5478
+ priority: preset.priority,
5479
+ recommendedBudget: preset.recommendedBudget ?? "300k",
5480
+ excludes: preset.exclude ? [...preset.exclude] : []
5481
+ })),
5482
+ artifacts: ARTIFACT_NAMES.map((name) => ({
5483
+ name,
5484
+ default: ARTIFACT_DEFAULTS[name] ?? true,
5485
+ summary: ARTIFACT_SUMMARY[name] ?? name
5486
+ })),
5487
+ config: {
5488
+ fileNames: [
5489
+ "snapshot.config.ts",
5490
+ "snapshot.config.js",
5491
+ "snapshot.config.mjs",
5492
+ "snapshot.config.cjs",
5493
+ "snapshot.config.json",
5494
+ ".snapshotrc",
5495
+ ".snapshotrc.json",
5496
+ 'package.json \u2192 "snapshot" key'
5497
+ ],
5498
+ settings: [
5499
+ { key: "outDir", type: "string", default: "snapshot", summary: "Snapshot output directory." },
5500
+ { key: "tmpDir", type: "string", default: "snapshot.tmp", summary: "Scratch directory used for the atomic swap." },
5501
+ { key: "branch", type: "string", default: "main", summary: "Branch recorded when git cannot report one." },
5502
+ { key: "preset", type: "string", default: "detected", summary: "Force a preset. Unknown names are an error." },
5503
+ { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
5504
+ { key: "largeFileBytes", type: "number | string", default: 204800, summary: "Preview threshold for large files." },
5505
+ { key: "previewHeadLines", type: "number", default: 80, summary: "Lines kept from the head of a large file." },
5506
+ { key: "previewTailLines", type: "number", default: 40, summary: "Lines kept from the tail of a large file." },
5507
+ { key: "includeMonolith", type: "boolean", default: false, summary: "Also write the single-file monolith." },
5508
+ { key: "maxMonolithBytes", type: "number | string | null", default: null, summary: "Skip the monolith above this size." },
5509
+ { key: "includeSensitiveFiles", type: "boolean", default: false, summary: "Emit .env / *.pem / credential files." },
5510
+ { key: "include", type: "string[]", default: "[]", summary: "Allow-list of globs; empty means everything." },
5511
+ { key: "excludePatterns", type: "string[]", default: "[]", summary: "Extra exclude globs." },
5512
+ { key: "artifacts", type: "object", default: "all on except monolith", summary: "Per-artifact opt-out." },
5513
+ { key: "budgets", type: "object", default: "{ default, byLayer }", summary: "Per-layer byte budgets." },
5514
+ { key: "layersMode", type: '"merge" | "replace"', default: "merge", summary: "Whether custom layers extend or replace the preset's." },
5515
+ { key: "layers", type: "array", default: "preset layers", summary: "Custom layer rules (glob or RegExp)." },
5516
+ { key: "kinds", type: "array", default: "preset kinds", summary: "Custom kind rules." },
5517
+ { key: "secrets", type: "object", default: "{}", summary: "Custom secret patterns, or disable the defaults." },
5518
+ { key: "hooks", type: "object", default: "{}", summary: "afterGenerate(manifest) runs after a successful generate." }
5519
+ ]
5520
+ },
5521
+ output: {
5522
+ layout: [
5523
+ "<outDir>/README.md",
5524
+ "<outDir>/manifest.json",
5525
+ "<outDir>/parts/part-NNN.md",
5526
+ "<outDir>/reports/project-tree.md",
5527
+ "<outDir>/reports/navigation.md",
5528
+ "<outDir>/reports/audit.md",
5529
+ "<outDir>/.codebase-snapshot (ownership marker, always written)"
5530
+ ],
5531
+ notes: [
5532
+ "Parts are ordered and budget-limited; a single file larger than the budget becomes a head/tail preview.",
5533
+ "manifest.json.files[] carries relativePath, layer, kind, language, part, inclusionMode, hash and a structural summary.",
5534
+ "manifest.skipped[] carries the path and the exact reason it was excluded.",
5535
+ `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
5536
+ ]
5537
+ },
5538
+ safety: [
5539
+ "Sensitive files (.env, *.pem, .npmrc, .ssh/, .tfstate) are excluded by default and listed in manifest.skipped[].",
5540
+ "Secret-shaped strings in ordinary source files are redacted in the emitted parts.",
5541
+ "The tool refuses to replace an outDir that it did not create, so a mistyped outDir cannot delete source code.",
5542
+ "Nothing is ever written above the repository root; --out-dir may not be the root or an ancestor."
5543
+ ],
5544
+ troubleshooting: [
5545
+ {
5546
+ symptom: "Command prints nothing and exits 0",
5547
+ cause: "The executable was not found: an offline or partially populated npm cache, or an npm proxy serving an incomplete manifest.",
5548
+ fix: `Clear the npx cache (npm cache clean --force), then run npx ${PACKAGE_NAME}@latest <command>.`
5549
+ },
5550
+ {
5551
+ symptom: "Exit 1 with 'Refusing to replace outDir'",
5552
+ cause: "The outDir exists and contains files this tool did not write.",
5553
+ fix: "Choose a new/empty --out-dir, or delete the existing directory yourself."
5554
+ },
5555
+ {
5556
+ symptom: "Exit 1 with 'The config file could not be read'",
5557
+ cause: "snapshot.config.* exists but does not parse.",
5558
+ fix: "Fix the syntax, or delete the config to use the defaults."
5559
+ },
5560
+ {
5561
+ symptom: "Exit 1 from validate",
5562
+ cause: "The snapshot no longer matches the files on disk.",
5563
+ fix: "Re-run generate."
5564
+ },
5565
+ {
5566
+ symptom: "A directory you expected is missing from the snapshot",
5567
+ cause: "It is excluded by the preset, by default ignores, or by your own globs.",
5568
+ fix: "Run `explain <path>`; manifest.skipped[] also records the reason for every file."
5569
+ }
5570
+ ]
5571
+ };
5572
+ }
5573
+
5574
+ // src/agent/skill.ts
5575
+ var PACKAGE_NAME2 = "@ankurhalder/codebase-snapshot";
5576
+ var SKILL_NAME = "codebase-snapshot";
5577
+ var AGENTS_MARKER_START = "<!-- codebase-snapshot:skill:start -->";
5578
+ var AGENTS_MARKER_END = "<!-- codebase-snapshot:skill:end -->";
5579
+ function renderSkill() {
5580
+ return `---
5581
+ name: ${SKILL_NAME}
5582
+ description: Create an LLM-ready snapshot of a repository (size-budgeted markdown parts, a JSON manifest, project tree, navigation and a secret audit) when a whole codebase has to be read, summarized or handed to a model that cannot clone it. Use when asked to snapshot a codebase, prepare repository context, or analyze a project's structure.
5583
+ version: ${GENERATOR_VERSION}
5584
+ ---
5585
+
5586
+ # codebase-snapshot
5587
+
5588
+ Turns a repository into an LLM-ready snapshot under \`./snapshot/\`: code packed into
5589
+ size-budgeted markdown parts, plus a manifest that indexes every file, a project tree, a
5590
+ navigation index and a secret audit.
5591
+
5592
+ Use it when you need to understand a whole repository, or produce repository context for
5593
+ another model, and reading files one by one would not fit in context.
5594
+
5595
+ ## Before you start
5596
+
5597
+ This tool is a Node CLI. It needs **Node.js 18 or newer**. You do not need to install it
5598
+ globally, and you do not need to clone anything.
5599
+
5600
+ **Pin the tag** \u2014 \`npx ${PACKAGE_NAME2}@latest <command>\` \u2014 when you need the same version on
5601
+ every machine. The bare package name works too: this package ships exactly one executable,
5602
+ which is what lets npm pick it. If a command exits 0 printing nothing, the executable was
5603
+ not resolved \u2014 clear the npm cache and retry; do not assume the repository is broken.
5604
+
5605
+ ## Step by step
5606
+
5607
+ 1. **Verify the tool.** Run \`npx ${PACKAGE_NAME2}@latest --version\`. Expect \`v${GENERATOR_VERSION}\` or
5608
+ newer on stdout. Empty output means you hit the bare-spec problem above.
5609
+
5610
+ 2. **Read the contract, not the prose.** Run
5611
+ \`npx ${PACKAGE_NAME2}@latest describe --format json\`. It returns the full machine
5612
+ contract: every command, every option with its default, the exit-code meanings, the
5613
+ 25 project presets, the artifact list, the config settings and a troubleshooting
5614
+ table. Read it before you make decisions; do not guess option names.
5615
+
5616
+ 3. **Look before you leap (optional but cheap).** To see how a specific file or directory
5617
+ would be treated, run \`npx ${PACKAGE_NAME2}@latest explain <path>\`. It reports the
5618
+ layer, kind, language, target part, and the exact reason a path would be skipped.
5619
+ \`--format json\` if you want to parse it.
5620
+
5621
+ 4. **Configure (recommended).** Run \`npx ${PACKAGE_NAME2}@latest init --yes\`. It detects
5622
+ the project shape, then writes \`snapshot.config.ts\` listing **every** setting at its
5623
+ current value, commented. Pass \`--preset <name>\` only if detection is wrong; the
5624
+ preset names are in the contract. This step is optional: without a config the tool
5625
+ runs on the same defaults.
5626
+
5627
+ 5. **Generate.** Run \`npx ${PACKAGE_NAME2}@latest generate\`. Expect exit 0 and a
5628
+ \`./snapshot/\` directory. If you need a different location use \`--out-dir <path>\`; if
5629
+ you need smaller or larger parts use \`--max-part-bytes 120k\`.
5630
+
5631
+ 6. **Verify.** Run \`npx ${PACKAGE_NAME2}@latest validate\`. Exit 0 means the snapshot
5632
+ matches the files on disk. Exit 1 means drift \u2014 re-run step 5.
5633
+
5634
+ 7. **Read the output in this order:**
5635
+ - \`snapshot/parts/part-*.md\` \u2014 the code itself, each file tagged with its layer, kind,
5636
+ language and a structural summary (imports, exports, classes, functions).
5637
+ - \`snapshot/manifest.json\` \u2014 the index. \`files[]\` has \`relativePath\`, \`layer\`,
5638
+ \`kind\`, \`language\`, \`part\`, \`inclusionMode\`, \`hashSha256\` and \`summary\`.
5639
+ \`skipped[]\` records every excluded file **and why**. Prefer querying this over
5640
+ re-reading the parts.
5641
+ - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
5642
+ state. Read this before you quote code back to a user.
5643
+ - \`snapshot/reports/project-tree.md\` and \`navigation.md\` \u2014 structure and cross-links.
5644
+
5645
+ ## Project types
5646
+
5647
+ Detection is automatic and covers Next.js, Nuxt, SvelteKit, Remix, Astro, Angular, Solid,
5648
+ Vue+React with Vite, Nest, Express/Fastify/Koa, any Node library, monorepos, Django,
5649
+ FastAPI/Flask, plain Python, Go, Rust, Java/Spring, .NET, PHP/Laravel, Ruby/Rails,
5650
+ Terraform/Docker infra, docs-only repositories, and a generic fallback. It sets sensible
5651
+ layers, kinds, ecosystem ignore patterns and a recommended part budget. For non-TypeScript
5652
+ languages it extracts imports, exports, classes and functions structurally; Vue, Svelte and
5653
+ Astro script blocks go through the real TypeScript compiler. You do not need to configure
5654
+ any of this to get a good first snapshot.
5655
+
5656
+ ## Things that will surprise you
5657
+
5658
+ - **Sensitive files are excluded by default** (\`.env\`, \`*.pem\`, \`.npmrc\`, \`.ssh/\`,
5659
+ \`.tfstate\`) and are listed in \`manifest.skipped[]\`. Add \`--include-sensitive-files\` only
5660
+ if the user asks for them explicitly.
5661
+ - **Secret-shaped strings inside normal source files are redacted** in the emitted parts.
5662
+ If the user needs the raw value, say so rather than working around it.
5663
+ - **The output directory is owned by the tool.** It is replaced atomically, and the tool
5664
+ refuses to replace a directory it did not create. Never point \`--out-dir\` at source
5665
+ code; if you see \`Refusing to replace outDir\`, choose a new directory rather than
5666
+ deleting anything.
5667
+ - **Exit 2 is a usage error**, not a failure of the repository. Re-read the contract
5668
+ before retrying.
5669
+ - **\`--format json\` keeps stdout pure.** Progress goes to stderr, so \`stdout\` is safe to
5670
+ pipe into a JSON parser.
5671
+
5672
+ ## Making this available to other agents
5673
+
5674
+ Run \`npx ${PACKAGE_NAME2}@latest skill --install\`. It writes this skill into the
5675
+ repository in the places agents look for it by default: an \`AGENTS.md\` section,
5676
+ \`.claude/skills/${SKILL_NAME}/SKILL.md\`, and \`.cursor/rules/${SKILL_NAME}.mdc\`. The command
5677
+ is idempotent and only replaces its own marked section.
5678
+ `;
5679
+ }
5680
+
5681
+ // src/agent/install-skill.ts
5682
+ var SKILL_TARGETS = ["claude", "agents", "cursor", "all"];
5683
+ function targetPath(cwd, target) {
5684
+ switch (target) {
5685
+ case "claude":
5686
+ return path10__namespace.join(cwd, ".claude", "skills", SKILL_NAME, "SKILL.md");
5687
+ case "cursor":
5688
+ return path10__namespace.join(cwd, ".cursor", "rules", `${SKILL_NAME}.mdc`);
5689
+ case "agents":
5690
+ return path10__namespace.join(cwd, "AGENTS.md");
5691
+ }
5692
+ }
5693
+ function writeIfChanged(target, filePath, content) {
5694
+ const existing = fs9__namespace.existsSync(filePath) ? fs9__namespace.readFileSync(filePath, "utf8") : null;
5695
+ if (existing === content) return { target, path: filePath, action: "unchanged" };
5696
+ fs9__namespace.mkdirSync(path10__namespace.dirname(filePath), { recursive: true });
5697
+ fs9__namespace.writeFileSync(filePath, content, "utf8");
5698
+ return { target, path: filePath, action: existing === null ? "created" : "updated" };
5699
+ }
5700
+ function agentsBlock(skill) {
5701
+ return [
5702
+ AGENTS_MARKER_START,
5703
+ "",
5704
+ `## ${SKILL_NAME} (${"@ankurhalder/codebase-snapshot"})`,
5705
+ "",
5706
+ // Drop the YAML frontmatter: inside AGENTS.md it is noise, and the heading
5707
+ // above already names the skill.
5708
+ skill.replace(/^---[\s\S]*?---\r?\n/, "").trim(),
5709
+ "",
5710
+ AGENTS_MARKER_END,
5711
+ ""
5712
+ ].join("\n");
5713
+ }
5714
+ function mergeAgentsFile(cwd, skill) {
5715
+ const filePath = targetPath(cwd, "agents");
5716
+ const block = agentsBlock(skill);
5717
+ const existing = fs9__namespace.existsSync(filePath) ? fs9__namespace.readFileSync(filePath, "utf8") : null;
5718
+ let next;
5719
+ if (existing === null) {
5720
+ next = `# AGENTS.md
5721
+
5722
+ ${block}`;
5723
+ } else if (existing.includes(AGENTS_MARKER_START) && existing.includes(AGENTS_MARKER_END)) {
5724
+ const start = existing.indexOf(AGENTS_MARKER_START);
5725
+ const end = existing.indexOf(AGENTS_MARKER_END) + AGENTS_MARKER_END.length;
5726
+ next = `${existing.slice(0, start)}${block.trimEnd()}${existing.slice(end)}`;
5727
+ } else {
5728
+ next = `${existing.trimEnd()}
5729
+
5730
+ ${block}`;
5731
+ }
5732
+ const action = existing === null ? "created" : existing === next ? "unchanged" : "updated";
5733
+ if (action !== "unchanged") {
5734
+ fs9__namespace.mkdirSync(path10__namespace.dirname(filePath), { recursive: true });
5735
+ fs9__namespace.writeFileSync(filePath, next, "utf8");
5736
+ }
5737
+ return { target: "agents", path: filePath, action };
5738
+ }
5739
+ function installSkill(cwd, target = "all") {
5740
+ const skill = renderSkill();
5741
+ const written = [];
5742
+ const wanted = target === "all" ? ["agents", "claude", "cursor"] : [target];
5743
+ for (const item of wanted) {
5744
+ if (item === "agents") {
5745
+ written.push(mergeAgentsFile(cwd, skill));
5746
+ continue;
5747
+ }
5748
+ written.push(writeIfChanged(item, targetPath(cwd, item), skill));
5749
+ }
5750
+ return { cwd, written };
5751
+ }
5752
+ function isSkillTarget(value) {
5753
+ return SKILL_TARGETS.includes(value);
5754
+ }
5755
+
5123
5756
  // src/cli.ts
5124
5757
  var VERSION = GENERATOR_VERSION;
5125
5758
  var COMMAND_ALIASES = /* @__PURE__ */ new Map([
@@ -5129,7 +5762,9 @@ var COMMAND_ALIASES = /* @__PURE__ */ new Map([
5129
5762
  ["report", "report"],
5130
5763
  ["init", "init"],
5131
5764
  ["explain", "explain"],
5132
- ["diff", "diff"]
5765
+ ["diff", "diff"],
5766
+ ["describe", "describe"],
5767
+ ["skill", "skill"]
5133
5768
  ]);
5134
5769
  var COMMAND_ARITY = {
5135
5770
  generate: 0,
@@ -5137,7 +5772,9 @@ var COMMAND_ARITY = {
5137
5772
  report: 0,
5138
5773
  init: 0,
5139
5774
  explain: 1,
5140
- diff: 2
5775
+ diff: 2,
5776
+ describe: 0,
5777
+ skill: 0
5141
5778
  };
5142
5779
  var CLI_OPTIONS = {
5143
5780
  cwd: { type: "string" },
@@ -5159,6 +5796,8 @@ var CLI_OPTIONS = {
5159
5796
  yes: { type: "boolean" },
5160
5797
  minimal: { type: "boolean" },
5161
5798
  force: { type: "boolean" },
5799
+ install: { type: "boolean" },
5800
+ target: { type: "string" },
5162
5801
  help: { type: "boolean", short: "h" },
5163
5802
  version: { type: "boolean", short: "v" }
5164
5803
  };
@@ -5170,7 +5809,6 @@ Production-grade LLM codebase snapshot generator, auditor, and AST partitioner
5170
5809
 
5171
5810
  Usage:
5172
5811
  codebase-snapshot [command] [options]
5173
- snap [command] [options]
5174
5812
 
5175
5813
  Commands:
5176
5814
  generate (default) Generate a complete partitioned codebase snapshot
@@ -5179,6 +5817,8 @@ Commands:
5179
5817
  report Print codebase health, layer metrics, and secret audit
5180
5818
  explain <path> Show how one path would be treated: layer, kind, part, skips
5181
5819
  diff <a> <b> Compare two snapshots (directories or manifest.json files)
5820
+ describe Print the machine-readable contract (--format json for agents)
5821
+ skill Print the bundled agent skill; --install writes it into the repo
5182
5822
 
5183
5823
  Options:
5184
5824
  --cwd <path> Target repository directory (default: current directory)
@@ -5204,11 +5844,17 @@ Options:
5204
5844
  --minimal Write only the settings that differ from defaults
5205
5845
  --yes Accept every default without prompting
5206
5846
  --force Overwrite an existing config
5847
+
5848
+ skill only:
5849
+ --install Write the skill into the repository instead of printing
5850
+ --target <name> claude | agents | cursor | all (default: all)
5851
+
5207
5852
  -h, --help Display this help message
5208
5853
  -v, --version Display version
5209
5854
 
5210
5855
  All options also accept the --option=value form.
5211
5856
  Human-readable progress is written to stderr; payloads (--format json) go to stdout.
5857
+ Agents with no prior knowledge of this tool should start with: describe --format json
5212
5858
  `.trim();
5213
5859
  function parsePositiveInteger(raw, optionName, minimum) {
5214
5860
  if (raw === void 0) return void 0;
@@ -5361,7 +6007,7 @@ function parseCliArgs(argv) {
5361
6007
  if (values.force === true) initOnly.push("--force");
5362
6008
  if (initOnly.length > 0) {
5363
6009
  throw new UsageError(
5364
- `${initOnly.join(", ")} ${initOnly.length === 1 ? "is" : "are"} only valid with \`init\`. To scope \`${command}\`, set include/excludePatterns/preset in snapshot.config.ts (or run \`snap init\` to generate one).`
6010
+ `${initOnly.join(", ")} ${initOnly.length === 1 ? "is" : "are"} only valid with \`init\`. To scope \`${command}\`, set include/excludePatterns/preset in snapshot.config.ts (or run \`codebase-snapshot init\` to generate one).`
5365
6011
  );
5366
6012
  }
5367
6013
  }
@@ -5369,6 +6015,14 @@ function parseCliArgs(argv) {
5369
6015
  const requested = String(values.preset);
5370
6016
  if (!getPreset(requested)) throw new UsageError(unknownPresetMessage(requested));
5371
6017
  }
6018
+ if (command !== "skill" && (values.install !== void 0 || values.target !== void 0)) {
6019
+ throw new UsageError("--install and --target are only valid with `skill`.");
6020
+ }
6021
+ if (values.target !== void 0 && !isSkillTarget(String(values.target))) {
6022
+ throw new UsageError(
6023
+ `--target must be one of: ${SKILL_TARGETS.join(", ")} (received "${String(values.target)}").`
6024
+ );
6025
+ }
5372
6026
  return {
5373
6027
  command,
5374
6028
  args,
@@ -5382,6 +6036,8 @@ function parseCliArgs(argv) {
5382
6036
  yes: values.yes === true,
5383
6037
  minimal: values.minimal === true,
5384
6038
  force: values.force === true,
6039
+ install: values.install === true,
6040
+ target: values.target === void 0 ? void 0 : String(values.target),
5385
6041
  cwd: values.cwd === void 0 ? process.cwd() : path10__namespace.resolve(String(values.cwd)),
5386
6042
  outDir: values["out-dir"] === void 0 ? void 0 : String(values["out-dir"]),
5387
6043
  includeMonolith: values["include-monolith"] === true ? true : void 0,
@@ -5472,6 +6128,9 @@ async function runInitCommand(invocation) {
5472
6128
  for (const note of result.notes) info(` \u26A0 ${note}`);
5473
6129
  info("");
5474
6130
  info(" Next: npm run snapshot");
6131
+ info(
6132
+ ` Tip: \`${GENERATOR_NAME} skill --install\` makes this repo discoverable by AI agents.`
6133
+ );
5475
6134
  return 0;
5476
6135
  } catch (err) {
5477
6136
  if (err instanceof PromptCancelled) {
@@ -5482,6 +6141,31 @@ async function runInitCommand(invocation) {
5482
6141
  return 1;
5483
6142
  }
5484
6143
  }
6144
+ function runSkillCommand(invocation) {
6145
+ if (!invocation.install) {
6146
+ process.stdout.write(renderSkill());
6147
+ return 0;
6148
+ }
6149
+ try {
6150
+ const result = installSkill(invocation.cwd, invocation.target);
6151
+ if (invocation.format === "json") {
6152
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
6153
+ `);
6154
+ return 0;
6155
+ }
6156
+ info(`\u2705 Agent skill installed (${SKILL_NAME}):`);
6157
+ for (const item of result.written) {
6158
+ const shown = path10__namespace.relative(invocation.cwd, item.path) || item.path;
6159
+ info(` - ${item.action.padEnd(9)} ${shown}`);
6160
+ }
6161
+ info("");
6162
+ info(" Agents that read AGENTS.md, .claude/skills or .cursor/rules will pick this up automatically.");
6163
+ return 0;
6164
+ } catch (err) {
6165
+ warn(`\u274C Could not install the skill: ${err.message}`);
6166
+ return 1;
6167
+ }
6168
+ }
5485
6169
  function renderValidateText(result) {
5486
6170
  if (result.valid) {
5487
6171
  info("\u2705 Snapshot is valid and up to date with disk.");
@@ -5527,6 +6211,14 @@ ${USAGE}
5527
6211
  if (invocation.command === "init") {
5528
6212
  return await runInitCommand(invocation);
5529
6213
  }
6214
+ if (invocation.command === "describe") {
6215
+ const contract = buildAgentContract();
6216
+ emit(invocation.format, contract, () => info(renderContractText(contract)));
6217
+ return 0;
6218
+ }
6219
+ if (invocation.command === "skill") {
6220
+ return runSkillCommand(invocation);
6221
+ }
5530
6222
  const loaded = await loadConfigFileDetailed(invocation.cwd);
5531
6223
  for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
5532
6224
  if (loaded.errors.length > 0) {