@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.js CHANGED
@@ -1,8 +1,634 @@
1
- import { parseByteSize, GENERATOR_VERSION, ARTIFACT_NAMES, getPreset, unknownPresetMessage, MIN_MAX_PART_BYTES, loadConfigFileDetailed, resolveConfig, validateSnapshot, explainPath, compareManifests, loadManifest, renderDiffText, generateSnapshot, GENERATOR_NAME, runInit, PromptCancelled, renderExplainText } from './chunk-SUOJL5EX.js';
1
+ import { parseByteSize, GENERATOR_VERSION, ARTIFACT_NAMES, getPreset, unknownPresetMessage, MIN_MAX_PART_BYTES, loadConfigFileDetailed, resolveConfig, validateSnapshot, explainPath, compareManifests, loadManifest, renderDiffText, generateSnapshot, GENERATOR_NAME, runInit, PromptCancelled, SCHEMA_VERSION, PRESETS, renderExplainText } from './chunk-5B4UVQLR.js';
2
2
  import * as fs from 'fs';
3
- import * as path from 'path';
3
+ import * as path2 from 'path';
4
4
  import { parseArgs } from 'util';
5
5
 
6
+ // src/agent/contract.ts
7
+ var CONTRACT_VERSION = "1.0.0";
8
+ var PACKAGE_NAME = "@ankurhalder/codebase-snapshot";
9
+ var ARTIFACT_SUMMARY = {
10
+ readme: "README.md describing the snapshot at the output root.",
11
+ manifest: "manifest.json: machine-readable index of every file, part, hash and config.",
12
+ parts: "parts/*.md: the packed, budget-limited markdown parts that carry the code.",
13
+ navigation: "reports/navigation.md: links between parts and layers.",
14
+ projectTree: "reports/project-tree.md: the directory tree of included files.",
15
+ audit: "reports/audit.md: secret findings, large files, parse diagnostics, git state.",
16
+ monolith: "full-codebase.json and full-codebase.md: the whole repository in one file (off by default)."
17
+ };
18
+ var ARTIFACT_DEFAULTS = {
19
+ readme: true,
20
+ manifest: true,
21
+ parts: true,
22
+ navigation: true,
23
+ projectTree: true,
24
+ audit: true,
25
+ monolith: false
26
+ };
27
+ function renderContractText(contract) {
28
+ const lines = [];
29
+ lines.push(`${contract.package} v${contract.version}`);
30
+ lines.push(contract.summary);
31
+ lines.push("");
32
+ lines.push(`Node : ${contract.requires.node}`);
33
+ lines.push(`Schema : ${contract.schemaVersion} (contract ${contract.contractVersion})`);
34
+ lines.push(`One-shot : ${contract.invocation.oneShot} <command>`);
35
+ lines.push(`Installed : ${contract.invocation.installed} <command>`);
36
+ lines.push("");
37
+ lines.push("Workflow:");
38
+ for (const step of contract.workflow) {
39
+ lines.push(` ${step.step}. ${step.id}`);
40
+ lines.push(` run : ${step.run}`);
41
+ lines.push(` expect : ${step.expect}`);
42
+ if (step.notes) lines.push(` note : ${step.notes}`);
43
+ }
44
+ lines.push("");
45
+ lines.push("Commands:");
46
+ for (const command of contract.commands) {
47
+ const args = command.positionals.length > 0 ? ` ${command.positionals.join(" ")}` : "";
48
+ lines.push(` ${(command.name + args).padEnd(26)} ${command.summary}`);
49
+ }
50
+ lines.push("");
51
+ lines.push("Exit codes:");
52
+ for (const [code, meaning] of Object.entries(contract.exitCodes)) {
53
+ lines.push(` ${code} ${meaning}`);
54
+ }
55
+ lines.push("");
56
+ lines.push(`Presets (${contract.presets.length}): ${contract.presets.map((p) => p.name).join(", ")}`);
57
+ lines.push("");
58
+ lines.push("Artifacts:");
59
+ for (const artifact of contract.artifacts) {
60
+ lines.push(` ${artifact.name.padEnd(12)} ${artifact.default ? "on " : "off"} ${artifact.summary}`);
61
+ }
62
+ lines.push("");
63
+ lines.push("Options:");
64
+ for (const option of contract.options) {
65
+ const fallback = option.default === void 0 ? "" : ` [${JSON.stringify(option.default)}]`;
66
+ lines.push(` ${option.flag.padEnd(24)} ${option.appliesTo.padEnd(32)}${fallback}`);
67
+ lines.push(` ${"".padEnd(24)} ${option.summary}`);
68
+ }
69
+ lines.push("");
70
+ lines.push("Safety:");
71
+ for (const note of contract.safety) lines.push(` - ${note}`);
72
+ lines.push("");
73
+ lines.push("Troubleshooting:");
74
+ for (const item of contract.troubleshooting) {
75
+ lines.push(` ${item.symptom}`);
76
+ lines.push(` cause: ${item.cause}`);
77
+ lines.push(` fix : ${item.fix}`);
78
+ }
79
+ lines.push("");
80
+ lines.push("This is the human rendering. Agents should use: describe --format json");
81
+ return lines.join("\n");
82
+ }
83
+ function buildAgentContract() {
84
+ return {
85
+ generator: GENERATOR_NAME,
86
+ package: PACKAGE_NAME,
87
+ version: GENERATOR_VERSION,
88
+ schemaVersion: SCHEMA_VERSION,
89
+ contractVersion: CONTRACT_VERSION,
90
+ 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).",
91
+ requires: { node: ">=18.0.0", dependencies: ["typescript"] },
92
+ invocation: {
93
+ oneShot: `npx ${PACKAGE_NAME}@latest`,
94
+ installed: "npx codebase-snapshot",
95
+ bins: ["codebase-snapshot"],
96
+ notes: [
97
+ `The bare package name also works: npx ${PACKAGE_NAME} <command>.`,
98
+ "Pin @latest (or @2) when you need the exact same version on every machine.",
99
+ "This package exposes exactly one executable on purpose: npm cannot infer which one to run for a scoped package that ships several.",
100
+ "Human progress goes to stderr. With --format json the payload on stdout is pure JSON."
101
+ ]
102
+ },
103
+ workflow: [
104
+ {
105
+ step: 1,
106
+ id: "verify",
107
+ run: `npx ${PACKAGE_NAME}@latest --version`,
108
+ expect: "prints v2.x.x on stdout and exits 0",
109
+ notes: "If it prints nothing, clear the npm cache and retry, or use `npx -p <pkg> codebase-snapshot`."
110
+ },
111
+ {
112
+ step: 2,
113
+ id: "understand",
114
+ run: `npx ${PACKAGE_NAME}@latest describe --format json`,
115
+ expect: "the full contract as JSON: commands, options, presets, exit codes",
116
+ notes: "Read this before acting if you have no prior knowledge of the tool."
117
+ },
118
+ {
119
+ step: 3,
120
+ id: "configure",
121
+ run: `npx ${PACKAGE_NAME}@latest init --yes`,
122
+ expect: "writes snapshot.config.ts listing every setting at its current value",
123
+ notes: "Non-interactive. The detected preset is chosen automatically; override with --preset <name>. Skip this step to run on built-in defaults."
124
+ },
125
+ {
126
+ step: 4,
127
+ id: "generate",
128
+ run: `npx ${PACKAGE_NAME}@latest generate`,
129
+ expect: "exit 0, and ./snapshot/ written with parts, reports and manifest.json"
130
+ },
131
+ {
132
+ step: 5,
133
+ id: "verify-output",
134
+ run: `npx ${PACKAGE_NAME}@latest validate`,
135
+ expect: "exit 0 means the snapshot matches the files on disk",
136
+ notes: "Exit 1 means drift or a damaged snapshot; re-run generate."
137
+ },
138
+ {
139
+ step: 6,
140
+ id: "consume",
141
+ run: "read ./snapshot/parts/*.md, then ./snapshot/manifest.json, then ./snapshot/reports/audit.md",
142
+ expect: "the code, the index of what was included, and the risk findings",
143
+ 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."
144
+ }
145
+ ],
146
+ commands: [
147
+ {
148
+ name: "generate",
149
+ aliases: ["default"],
150
+ summary: "Write the snapshot. This is the command you normally want.",
151
+ positionals: [],
152
+ exits: [0, 1]
153
+ },
154
+ {
155
+ name: "validate",
156
+ aliases: ["check"],
157
+ summary: "Compare the snapshot on disk with the repository; exit 1 on drift.",
158
+ positionals: [],
159
+ exits: [0, 1]
160
+ },
161
+ {
162
+ name: "report",
163
+ aliases: [],
164
+ summary: "Print snapshot health, layer metrics and the secret audit.",
165
+ positionals: [],
166
+ exits: [0, 1]
167
+ },
168
+ {
169
+ name: "init",
170
+ aliases: [],
171
+ summary: "Write a commented snapshot.config.ts (interactive, or --yes for CI).",
172
+ positionals: [],
173
+ exits: [0, 1, 2]
174
+ },
175
+ {
176
+ name: "explain",
177
+ aliases: [],
178
+ summary: "Explain how one path would be treated: layer, kind, part, skip reason.",
179
+ positionals: ["<path>"],
180
+ exits: [0, 1]
181
+ },
182
+ {
183
+ name: "diff",
184
+ aliases: [],
185
+ summary: "Compare two snapshots (directories or manifest.json files).",
186
+ positionals: ["<before>", "<after>"],
187
+ exits: [0, 1]
188
+ },
189
+ {
190
+ name: "describe",
191
+ aliases: [],
192
+ summary: "Print this contract. --format json for machines, text for humans.",
193
+ positionals: [],
194
+ exits: [0]
195
+ },
196
+ {
197
+ name: "skill",
198
+ aliases: [],
199
+ summary: "Print the agent skill, or --install it into the repository (AGENTS.md, .claude/skills, .cursor/rules).",
200
+ positionals: [],
201
+ exits: [0, 1, 2]
202
+ }
203
+ ],
204
+ exitCodes: {
205
+ "0": "success (and validate: no drift)",
206
+ "1": "drift detected, or generation refused/failed (nothing was written)",
207
+ "2": "usage error: unknown flag/command, bad value, wrong argument count"
208
+ },
209
+ options: [
210
+ {
211
+ flag: "--out-dir",
212
+ type: "string",
213
+ default: "snapshot",
214
+ appliesTo: "generate/validate/report/explain",
215
+ summary: "Where the snapshot is written. Must not be the repo root or a directory the tool did not create."
216
+ },
217
+ {
218
+ flag: "--max-part-bytes",
219
+ type: "string",
220
+ default: 307200,
221
+ appliesTo: "generate/validate/report",
222
+ summary: 'Byte budget per markdown part. Accepts "120k" / "1.5mb". Minimum 4096.'
223
+ },
224
+ {
225
+ flag: "--large-file-bytes",
226
+ type: "string",
227
+ default: 204800,
228
+ appliesTo: "generate/validate/report",
229
+ summary: "Above this size a file gets a head/tail preview instead of the full body."
230
+ },
231
+ {
232
+ flag: "--max-monolith-bytes",
233
+ type: "string",
234
+ default: "unset",
235
+ appliesTo: "generate",
236
+ summary: "Skip the monolith artifacts when they would exceed this size."
237
+ },
238
+ {
239
+ flag: "--include-monolith",
240
+ type: "boolean",
241
+ default: false,
242
+ appliesTo: "generate",
243
+ summary: "Also write full-codebase.json and full-codebase.md."
244
+ },
245
+ {
246
+ flag: "--include-sensitive-files",
247
+ type: "boolean",
248
+ default: false,
249
+ appliesTo: "generate/validate/report",
250
+ summary: "Also emit .env / *.pem / .npmrc style files. Off by default; they are recorded as skipped."
251
+ },
252
+ {
253
+ flag: "--skip-artifacts",
254
+ type: "string",
255
+ default: "unset",
256
+ appliesTo: "generate",
257
+ summary: "Comma-separated artifacts to omit (readme, manifest, parts, navigation, projectTree, audit, monolith)."
258
+ },
259
+ {
260
+ flag: "--only-artifacts",
261
+ type: "string",
262
+ default: "unset",
263
+ appliesTo: "generate",
264
+ summary: "Write only these artifacts. Cannot be combined with --skip-artifacts."
265
+ },
266
+ {
267
+ flag: "--format",
268
+ type: "string",
269
+ default: "text",
270
+ appliesTo: "all commands",
271
+ summary: 'Output format: "text" or "json". JSON goes to stdout, progress to stderr.'
272
+ },
273
+ {
274
+ flag: "--cwd",
275
+ type: "string",
276
+ default: "process.cwd()",
277
+ appliesTo: "all commands",
278
+ summary: "Repository to operate on. Must be an existing directory."
279
+ },
280
+ {
281
+ flag: "--dry-run",
282
+ type: "boolean",
283
+ default: false,
284
+ appliesTo: "generate",
285
+ summary: "Compute everything and print the result without writing."
286
+ },
287
+ {
288
+ flag: "--watch",
289
+ type: "boolean",
290
+ default: false,
291
+ appliesTo: "generate",
292
+ summary: "Regenerate on every change until interrupted."
293
+ },
294
+ {
295
+ flag: "--preset",
296
+ type: "string",
297
+ default: "detected",
298
+ appliesTo: "init",
299
+ summary: "Force a project preset instead of detecting one. Unknown names are a usage error."
300
+ },
301
+ {
302
+ flag: "--include",
303
+ type: "string",
304
+ default: "unset",
305
+ appliesTo: "init",
306
+ summary: "Comma-separated allow-list of globs to record in the generated config."
307
+ },
308
+ {
309
+ flag: "--exclude",
310
+ type: "string",
311
+ default: "unset",
312
+ appliesTo: "init",
313
+ summary: "Comma-separated globs to record in the generated config."
314
+ },
315
+ {
316
+ flag: "--yes",
317
+ type: "boolean",
318
+ default: false,
319
+ appliesTo: "init",
320
+ summary: "Accept every default without prompting. Required in a non-TTY."
321
+ },
322
+ {
323
+ flag: "--minimal",
324
+ type: "boolean",
325
+ default: false,
326
+ appliesTo: "init",
327
+ summary: "Write only the settings that differ from the defaults."
328
+ },
329
+ {
330
+ flag: "--force",
331
+ type: "boolean",
332
+ default: false,
333
+ appliesTo: "init",
334
+ summary: "Overwrite an existing config file."
335
+ },
336
+ {
337
+ flag: "--install",
338
+ type: "boolean",
339
+ default: false,
340
+ appliesTo: "skill",
341
+ summary: "Write the skill into the repository instead of printing it."
342
+ },
343
+ {
344
+ flag: "--target",
345
+ type: "string",
346
+ default: "all",
347
+ appliesTo: "skill",
348
+ summary: 'Where to install: "claude", "agents", "cursor" or "all".'
349
+ }
350
+ ],
351
+ presets: PRESETS.map((preset) => ({
352
+ name: preset.name,
353
+ priority: preset.priority,
354
+ recommendedBudget: preset.recommendedBudget ?? "300k",
355
+ excludes: preset.exclude ? [...preset.exclude] : []
356
+ })),
357
+ artifacts: ARTIFACT_NAMES.map((name) => ({
358
+ name,
359
+ default: ARTIFACT_DEFAULTS[name] ?? true,
360
+ summary: ARTIFACT_SUMMARY[name] ?? name
361
+ })),
362
+ config: {
363
+ fileNames: [
364
+ "snapshot.config.ts",
365
+ "snapshot.config.js",
366
+ "snapshot.config.mjs",
367
+ "snapshot.config.cjs",
368
+ "snapshot.config.json",
369
+ ".snapshotrc",
370
+ ".snapshotrc.json",
371
+ 'package.json \u2192 "snapshot" key'
372
+ ],
373
+ settings: [
374
+ { key: "outDir", type: "string", default: "snapshot", summary: "Snapshot output directory." },
375
+ { key: "tmpDir", type: "string", default: "snapshot.tmp", summary: "Scratch directory used for the atomic swap." },
376
+ { key: "branch", type: "string", default: "main", summary: "Branch recorded when git cannot report one." },
377
+ { key: "preset", type: "string", default: "detected", summary: "Force a preset. Unknown names are an error." },
378
+ { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
379
+ { key: "largeFileBytes", type: "number | string", default: 204800, summary: "Preview threshold for large files." },
380
+ { key: "previewHeadLines", type: "number", default: 80, summary: "Lines kept from the head of a large file." },
381
+ { key: "previewTailLines", type: "number", default: 40, summary: "Lines kept from the tail of a large file." },
382
+ { key: "includeMonolith", type: "boolean", default: false, summary: "Also write the single-file monolith." },
383
+ { key: "maxMonolithBytes", type: "number | string | null", default: null, summary: "Skip the monolith above this size." },
384
+ { key: "includeSensitiveFiles", type: "boolean", default: false, summary: "Emit .env / *.pem / credential files." },
385
+ { key: "include", type: "string[]", default: "[]", summary: "Allow-list of globs; empty means everything." },
386
+ { key: "excludePatterns", type: "string[]", default: "[]", summary: "Extra exclude globs." },
387
+ { key: "artifacts", type: "object", default: "all on except monolith", summary: "Per-artifact opt-out." },
388
+ { key: "budgets", type: "object", default: "{ default, byLayer }", summary: "Per-layer byte budgets." },
389
+ { key: "layersMode", type: '"merge" | "replace"', default: "merge", summary: "Whether custom layers extend or replace the preset's." },
390
+ { key: "layers", type: "array", default: "preset layers", summary: "Custom layer rules (glob or RegExp)." },
391
+ { key: "kinds", type: "array", default: "preset kinds", summary: "Custom kind rules." },
392
+ { key: "secrets", type: "object", default: "{}", summary: "Custom secret patterns, or disable the defaults." },
393
+ { key: "hooks", type: "object", default: "{}", summary: "afterGenerate(manifest) runs after a successful generate." }
394
+ ]
395
+ },
396
+ output: {
397
+ layout: [
398
+ "<outDir>/README.md",
399
+ "<outDir>/manifest.json",
400
+ "<outDir>/parts/part-NNN.md",
401
+ "<outDir>/reports/project-tree.md",
402
+ "<outDir>/reports/navigation.md",
403
+ "<outDir>/reports/audit.md",
404
+ "<outDir>/.codebase-snapshot (ownership marker, always written)"
405
+ ],
406
+ notes: [
407
+ "Parts are ordered and budget-limited; a single file larger than the budget becomes a head/tail preview.",
408
+ "manifest.json.files[] carries relativePath, layer, kind, language, part, inclusionMode, hash and a structural summary.",
409
+ "manifest.skipped[] carries the path and the exact reason it was excluded.",
410
+ `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
411
+ ]
412
+ },
413
+ safety: [
414
+ "Sensitive files (.env, *.pem, .npmrc, .ssh/, .tfstate) are excluded by default and listed in manifest.skipped[].",
415
+ "Secret-shaped strings in ordinary source files are redacted in the emitted parts.",
416
+ "The tool refuses to replace an outDir that it did not create, so a mistyped outDir cannot delete source code.",
417
+ "Nothing is ever written above the repository root; --out-dir may not be the root or an ancestor."
418
+ ],
419
+ troubleshooting: [
420
+ {
421
+ symptom: "Command prints nothing and exits 0",
422
+ cause: "The executable was not found: an offline or partially populated npm cache, or an npm proxy serving an incomplete manifest.",
423
+ fix: `Clear the npx cache (npm cache clean --force), then run npx ${PACKAGE_NAME}@latest <command>.`
424
+ },
425
+ {
426
+ symptom: "Exit 1 with 'Refusing to replace outDir'",
427
+ cause: "The outDir exists and contains files this tool did not write.",
428
+ fix: "Choose a new/empty --out-dir, or delete the existing directory yourself."
429
+ },
430
+ {
431
+ symptom: "Exit 1 with 'The config file could not be read'",
432
+ cause: "snapshot.config.* exists but does not parse.",
433
+ fix: "Fix the syntax, or delete the config to use the defaults."
434
+ },
435
+ {
436
+ symptom: "Exit 1 from validate",
437
+ cause: "The snapshot no longer matches the files on disk.",
438
+ fix: "Re-run generate."
439
+ },
440
+ {
441
+ symptom: "A directory you expected is missing from the snapshot",
442
+ cause: "It is excluded by the preset, by default ignores, or by your own globs.",
443
+ fix: "Run `explain <path>`; manifest.skipped[] also records the reason for every file."
444
+ }
445
+ ]
446
+ };
447
+ }
448
+
449
+ // src/agent/skill.ts
450
+ var PACKAGE_NAME2 = "@ankurhalder/codebase-snapshot";
451
+ var SKILL_NAME = "codebase-snapshot";
452
+ var AGENTS_MARKER_START = "<!-- codebase-snapshot:skill:start -->";
453
+ var AGENTS_MARKER_END = "<!-- codebase-snapshot:skill:end -->";
454
+ function renderSkill() {
455
+ return `---
456
+ name: ${SKILL_NAME}
457
+ 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.
458
+ version: ${GENERATOR_VERSION}
459
+ ---
460
+
461
+ # codebase-snapshot
462
+
463
+ Turns a repository into an LLM-ready snapshot under \`./snapshot/\`: code packed into
464
+ size-budgeted markdown parts, plus a manifest that indexes every file, a project tree, a
465
+ navigation index and a secret audit.
466
+
467
+ Use it when you need to understand a whole repository, or produce repository context for
468
+ another model, and reading files one by one would not fit in context.
469
+
470
+ ## Before you start
471
+
472
+ This tool is a Node CLI. It needs **Node.js 18 or newer**. You do not need to install it
473
+ globally, and you do not need to clone anything.
474
+
475
+ **Pin the tag** \u2014 \`npx ${PACKAGE_NAME2}@latest <command>\` \u2014 when you need the same version on
476
+ every machine. The bare package name works too: this package ships exactly one executable,
477
+ which is what lets npm pick it. If a command exits 0 printing nothing, the executable was
478
+ not resolved \u2014 clear the npm cache and retry; do not assume the repository is broken.
479
+
480
+ ## Step by step
481
+
482
+ 1. **Verify the tool.** Run \`npx ${PACKAGE_NAME2}@latest --version\`. Expect \`v${GENERATOR_VERSION}\` or
483
+ newer on stdout. Empty output means you hit the bare-spec problem above.
484
+
485
+ 2. **Read the contract, not the prose.** Run
486
+ \`npx ${PACKAGE_NAME2}@latest describe --format json\`. It returns the full machine
487
+ contract: every command, every option with its default, the exit-code meanings, the
488
+ 25 project presets, the artifact list, the config settings and a troubleshooting
489
+ table. Read it before you make decisions; do not guess option names.
490
+
491
+ 3. **Look before you leap (optional but cheap).** To see how a specific file or directory
492
+ would be treated, run \`npx ${PACKAGE_NAME2}@latest explain <path>\`. It reports the
493
+ layer, kind, language, target part, and the exact reason a path would be skipped.
494
+ \`--format json\` if you want to parse it.
495
+
496
+ 4. **Configure (recommended).** Run \`npx ${PACKAGE_NAME2}@latest init --yes\`. It detects
497
+ the project shape, then writes \`snapshot.config.ts\` listing **every** setting at its
498
+ current value, commented. Pass \`--preset <name>\` only if detection is wrong; the
499
+ preset names are in the contract. This step is optional: without a config the tool
500
+ runs on the same defaults.
501
+
502
+ 5. **Generate.** Run \`npx ${PACKAGE_NAME2}@latest generate\`. Expect exit 0 and a
503
+ \`./snapshot/\` directory. If you need a different location use \`--out-dir <path>\`; if
504
+ you need smaller or larger parts use \`--max-part-bytes 120k\`.
505
+
506
+ 6. **Verify.** Run \`npx ${PACKAGE_NAME2}@latest validate\`. Exit 0 means the snapshot
507
+ matches the files on disk. Exit 1 means drift \u2014 re-run step 5.
508
+
509
+ 7. **Read the output in this order:**
510
+ - \`snapshot/parts/part-*.md\` \u2014 the code itself, each file tagged with its layer, kind,
511
+ language and a structural summary (imports, exports, classes, functions).
512
+ - \`snapshot/manifest.json\` \u2014 the index. \`files[]\` has \`relativePath\`, \`layer\`,
513
+ \`kind\`, \`language\`, \`part\`, \`inclusionMode\`, \`hashSha256\` and \`summary\`.
514
+ \`skipped[]\` records every excluded file **and why**. Prefer querying this over
515
+ re-reading the parts.
516
+ - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
517
+ state. Read this before you quote code back to a user.
518
+ - \`snapshot/reports/project-tree.md\` and \`navigation.md\` \u2014 structure and cross-links.
519
+
520
+ ## Project types
521
+
522
+ Detection is automatic and covers Next.js, Nuxt, SvelteKit, Remix, Astro, Angular, Solid,
523
+ Vue+React with Vite, Nest, Express/Fastify/Koa, any Node library, monorepos, Django,
524
+ FastAPI/Flask, plain Python, Go, Rust, Java/Spring, .NET, PHP/Laravel, Ruby/Rails,
525
+ Terraform/Docker infra, docs-only repositories, and a generic fallback. It sets sensible
526
+ layers, kinds, ecosystem ignore patterns and a recommended part budget. For non-TypeScript
527
+ languages it extracts imports, exports, classes and functions structurally; Vue, Svelte and
528
+ Astro script blocks go through the real TypeScript compiler. You do not need to configure
529
+ any of this to get a good first snapshot.
530
+
531
+ ## Things that will surprise you
532
+
533
+ - **Sensitive files are excluded by default** (\`.env\`, \`*.pem\`, \`.npmrc\`, \`.ssh/\`,
534
+ \`.tfstate\`) and are listed in \`manifest.skipped[]\`. Add \`--include-sensitive-files\` only
535
+ if the user asks for them explicitly.
536
+ - **Secret-shaped strings inside normal source files are redacted** in the emitted parts.
537
+ If the user needs the raw value, say so rather than working around it.
538
+ - **The output directory is owned by the tool.** It is replaced atomically, and the tool
539
+ refuses to replace a directory it did not create. Never point \`--out-dir\` at source
540
+ code; if you see \`Refusing to replace outDir\`, choose a new directory rather than
541
+ deleting anything.
542
+ - **Exit 2 is a usage error**, not a failure of the repository. Re-read the contract
543
+ before retrying.
544
+ - **\`--format json\` keeps stdout pure.** Progress goes to stderr, so \`stdout\` is safe to
545
+ pipe into a JSON parser.
546
+
547
+ ## Making this available to other agents
548
+
549
+ Run \`npx ${PACKAGE_NAME2}@latest skill --install\`. It writes this skill into the
550
+ repository in the places agents look for it by default: an \`AGENTS.md\` section,
551
+ \`.claude/skills/${SKILL_NAME}/SKILL.md\`, and \`.cursor/rules/${SKILL_NAME}.mdc\`. The command
552
+ is idempotent and only replaces its own marked section.
553
+ `;
554
+ }
555
+
556
+ // src/agent/install-skill.ts
557
+ var SKILL_TARGETS = ["claude", "agents", "cursor", "all"];
558
+ function targetPath(cwd, target) {
559
+ switch (target) {
560
+ case "claude":
561
+ return path2.join(cwd, ".claude", "skills", SKILL_NAME, "SKILL.md");
562
+ case "cursor":
563
+ return path2.join(cwd, ".cursor", "rules", `${SKILL_NAME}.mdc`);
564
+ case "agents":
565
+ return path2.join(cwd, "AGENTS.md");
566
+ }
567
+ }
568
+ function writeIfChanged(target, filePath, content) {
569
+ const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8") : null;
570
+ if (existing === content) return { target, path: filePath, action: "unchanged" };
571
+ fs.mkdirSync(path2.dirname(filePath), { recursive: true });
572
+ fs.writeFileSync(filePath, content, "utf8");
573
+ return { target, path: filePath, action: existing === null ? "created" : "updated" };
574
+ }
575
+ function agentsBlock(skill) {
576
+ return [
577
+ AGENTS_MARKER_START,
578
+ "",
579
+ `## ${SKILL_NAME} (${"@ankurhalder/codebase-snapshot"})`,
580
+ "",
581
+ // Drop the YAML frontmatter: inside AGENTS.md it is noise, and the heading
582
+ // above already names the skill.
583
+ skill.replace(/^---[\s\S]*?---\r?\n/, "").trim(),
584
+ "",
585
+ AGENTS_MARKER_END,
586
+ ""
587
+ ].join("\n");
588
+ }
589
+ function mergeAgentsFile(cwd, skill) {
590
+ const filePath = targetPath(cwd, "agents");
591
+ const block = agentsBlock(skill);
592
+ const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8") : null;
593
+ let next;
594
+ if (existing === null) {
595
+ next = `# AGENTS.md
596
+
597
+ ${block}`;
598
+ } else if (existing.includes(AGENTS_MARKER_START) && existing.includes(AGENTS_MARKER_END)) {
599
+ const start = existing.indexOf(AGENTS_MARKER_START);
600
+ const end = existing.indexOf(AGENTS_MARKER_END) + AGENTS_MARKER_END.length;
601
+ next = `${existing.slice(0, start)}${block.trimEnd()}${existing.slice(end)}`;
602
+ } else {
603
+ next = `${existing.trimEnd()}
604
+
605
+ ${block}`;
606
+ }
607
+ const action = existing === null ? "created" : existing === next ? "unchanged" : "updated";
608
+ if (action !== "unchanged") {
609
+ fs.mkdirSync(path2.dirname(filePath), { recursive: true });
610
+ fs.writeFileSync(filePath, next, "utf8");
611
+ }
612
+ return { target: "agents", path: filePath, action };
613
+ }
614
+ function installSkill(cwd, target = "all") {
615
+ const skill = renderSkill();
616
+ const written = [];
617
+ const wanted = target === "all" ? ["agents", "claude", "cursor"] : [target];
618
+ for (const item of wanted) {
619
+ if (item === "agents") {
620
+ written.push(mergeAgentsFile(cwd, skill));
621
+ continue;
622
+ }
623
+ written.push(writeIfChanged(item, targetPath(cwd, item), skill));
624
+ }
625
+ return { cwd, written };
626
+ }
627
+ function isSkillTarget(value) {
628
+ return SKILL_TARGETS.includes(value);
629
+ }
630
+
631
+ // src/cli.ts
6
632
  var VERSION = GENERATOR_VERSION;
7
633
  var COMMAND_ALIASES = /* @__PURE__ */ new Map([
8
634
  ["generate", "generate"],
@@ -11,7 +637,9 @@ var COMMAND_ALIASES = /* @__PURE__ */ new Map([
11
637
  ["report", "report"],
12
638
  ["init", "init"],
13
639
  ["explain", "explain"],
14
- ["diff", "diff"]
640
+ ["diff", "diff"],
641
+ ["describe", "describe"],
642
+ ["skill", "skill"]
15
643
  ]);
16
644
  var COMMAND_ARITY = {
17
645
  generate: 0,
@@ -19,7 +647,9 @@ var COMMAND_ARITY = {
19
647
  report: 0,
20
648
  init: 0,
21
649
  explain: 1,
22
- diff: 2
650
+ diff: 2,
651
+ describe: 0,
652
+ skill: 0
23
653
  };
24
654
  var CLI_OPTIONS = {
25
655
  cwd: { type: "string" },
@@ -41,6 +671,8 @@ var CLI_OPTIONS = {
41
671
  yes: { type: "boolean" },
42
672
  minimal: { type: "boolean" },
43
673
  force: { type: "boolean" },
674
+ install: { type: "boolean" },
675
+ target: { type: "string" },
44
676
  help: { type: "boolean", short: "h" },
45
677
  version: { type: "boolean", short: "v" }
46
678
  };
@@ -52,7 +684,6 @@ Production-grade LLM codebase snapshot generator, auditor, and AST partitioner
52
684
 
53
685
  Usage:
54
686
  codebase-snapshot [command] [options]
55
- snap [command] [options]
56
687
 
57
688
  Commands:
58
689
  generate (default) Generate a complete partitioned codebase snapshot
@@ -61,6 +692,8 @@ Commands:
61
692
  report Print codebase health, layer metrics, and secret audit
62
693
  explain <path> Show how one path would be treated: layer, kind, part, skips
63
694
  diff <a> <b> Compare two snapshots (directories or manifest.json files)
695
+ describe Print the machine-readable contract (--format json for agents)
696
+ skill Print the bundled agent skill; --install writes it into the repo
64
697
 
65
698
  Options:
66
699
  --cwd <path> Target repository directory (default: current directory)
@@ -86,11 +719,17 @@ Options:
86
719
  --minimal Write only the settings that differ from defaults
87
720
  --yes Accept every default without prompting
88
721
  --force Overwrite an existing config
722
+
723
+ skill only:
724
+ --install Write the skill into the repository instead of printing
725
+ --target <name> claude | agents | cursor | all (default: all)
726
+
89
727
  -h, --help Display this help message
90
728
  -v, --version Display version
91
729
 
92
730
  All options also accept the --option=value form.
93
731
  Human-readable progress is written to stderr; payloads (--format json) go to stdout.
732
+ Agents with no prior knowledge of this tool should start with: describe --format json
94
733
  `.trim();
95
734
  function parsePositiveInteger(raw, optionName, minimum) {
96
735
  if (raw === void 0) return void 0;
@@ -243,7 +882,7 @@ function parseCliArgs(argv) {
243
882
  if (values.force === true) initOnly.push("--force");
244
883
  if (initOnly.length > 0) {
245
884
  throw new UsageError(
246
- `${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).`
885
+ `${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).`
247
886
  );
248
887
  }
249
888
  }
@@ -251,6 +890,14 @@ function parseCliArgs(argv) {
251
890
  const requested = String(values.preset);
252
891
  if (!getPreset(requested)) throw new UsageError(unknownPresetMessage(requested));
253
892
  }
893
+ if (command !== "skill" && (values.install !== void 0 || values.target !== void 0)) {
894
+ throw new UsageError("--install and --target are only valid with `skill`.");
895
+ }
896
+ if (values.target !== void 0 && !isSkillTarget(String(values.target))) {
897
+ throw new UsageError(
898
+ `--target must be one of: ${SKILL_TARGETS.join(", ")} (received "${String(values.target)}").`
899
+ );
900
+ }
254
901
  return {
255
902
  command,
256
903
  args,
@@ -264,7 +911,9 @@ function parseCliArgs(argv) {
264
911
  yes: values.yes === true,
265
912
  minimal: values.minimal === true,
266
913
  force: values.force === true,
267
- cwd: values.cwd === void 0 ? process.cwd() : path.resolve(String(values.cwd)),
914
+ install: values.install === true,
915
+ target: values.target === void 0 ? void 0 : String(values.target),
916
+ cwd: values.cwd === void 0 ? process.cwd() : path2.resolve(String(values.cwd)),
268
917
  outDir: values["out-dir"] === void 0 ? void 0 : String(values["out-dir"]),
269
918
  includeMonolith: values["include-monolith"] === true ? true : void 0,
270
919
  includeSensitiveFiles: values["include-sensitive-files"] === true ? true : void 0,
@@ -346,7 +995,7 @@ async function runInitCommand(invocation) {
346
995
  info(result.configText);
347
996
  return 0;
348
997
  }
349
- info(`\u2705 Created ${path.basename(result.configPath)} (preset: ${result.preset})`);
998
+ info(`\u2705 Created ${path2.basename(result.configPath)} (preset: ${result.preset})`);
350
999
  if (result.scripts.length > 0) info(` Added npm scripts: ${result.scripts.join(", ")}`);
351
1000
  if (result.gitignoreEntries.length > 0) {
352
1001
  info(` Added to .gitignore: ${result.gitignoreEntries.join(", ")}`);
@@ -354,6 +1003,9 @@ async function runInitCommand(invocation) {
354
1003
  for (const note of result.notes) info(` \u26A0 ${note}`);
355
1004
  info("");
356
1005
  info(" Next: npm run snapshot");
1006
+ info(
1007
+ ` Tip: \`${GENERATOR_NAME} skill --install\` makes this repo discoverable by AI agents.`
1008
+ );
357
1009
  return 0;
358
1010
  } catch (err) {
359
1011
  if (err instanceof PromptCancelled) {
@@ -364,6 +1016,31 @@ async function runInitCommand(invocation) {
364
1016
  return 1;
365
1017
  }
366
1018
  }
1019
+ function runSkillCommand(invocation) {
1020
+ if (!invocation.install) {
1021
+ process.stdout.write(renderSkill());
1022
+ return 0;
1023
+ }
1024
+ try {
1025
+ const result = installSkill(invocation.cwd, invocation.target);
1026
+ if (invocation.format === "json") {
1027
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
1028
+ `);
1029
+ return 0;
1030
+ }
1031
+ info(`\u2705 Agent skill installed (${SKILL_NAME}):`);
1032
+ for (const item of result.written) {
1033
+ const shown = path2.relative(invocation.cwd, item.path) || item.path;
1034
+ info(` - ${item.action.padEnd(9)} ${shown}`);
1035
+ }
1036
+ info("");
1037
+ info(" Agents that read AGENTS.md, .claude/skills or .cursor/rules will pick this up automatically.");
1038
+ return 0;
1039
+ } catch (err) {
1040
+ warn(`\u274C Could not install the skill: ${err.message}`);
1041
+ return 1;
1042
+ }
1043
+ }
367
1044
  function renderValidateText(result) {
368
1045
  if (result.valid) {
369
1046
  info("\u2705 Snapshot is valid and up to date with disk.");
@@ -409,13 +1086,21 @@ ${USAGE}
409
1086
  if (invocation.command === "init") {
410
1087
  return await runInitCommand(invocation);
411
1088
  }
1089
+ if (invocation.command === "describe") {
1090
+ const contract = buildAgentContract();
1091
+ emit(invocation.format, contract, () => info(renderContractText(contract)));
1092
+ return 0;
1093
+ }
1094
+ if (invocation.command === "skill") {
1095
+ return runSkillCommand(invocation);
1096
+ }
412
1097
  const loaded = await loadConfigFileDetailed(invocation.cwd);
413
1098
  for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
414
1099
  if (loaded.errors.length > 0) {
415
1100
  warn("\u274C The config file could not be read. Fix it, or delete it to use the defaults.");
416
1101
  return 1;
417
1102
  }
418
- if (loaded.file) info(`\u2699 Using config ${path.relative(process.cwd(), loaded.file) || loaded.file}`);
1103
+ if (loaded.file) info(`\u2699 Using config ${path2.relative(process.cwd(), loaded.file) || loaded.file}`);
419
1104
  const resolved = resolveConfig(
420
1105
  loaded.config,
421
1106
  {
@@ -439,7 +1124,7 @@ ${USAGE}
439
1124
  return result.valid ? 0 : 1;
440
1125
  }
441
1126
  if (invocation.command === "report") {
442
- const manifestPath = path.resolve(resolved.cwd, resolved.outDir, "manifest.json");
1127
+ const manifestPath = path2.resolve(resolved.cwd, resolved.outDir, "manifest.json");
443
1128
  if (!fs.existsSync(manifestPath)) {
444
1129
  warn(`\u274C Manifest not found at ${manifestPath}. Run generate first.`);
445
1130
  return 1;
@@ -564,10 +1249,10 @@ ${USAGE}
564
1249
  }
565
1250
  }
566
1251
  async function runWatchLoop(invocation, resolved) {
567
- const outDir = path.resolve(resolved.cwd, resolved.outDir);
568
- const tmpDir = path.resolve(resolved.cwd, resolved.tmpDir);
569
- const outName = path.basename(outDir).toLowerCase();
570
- const tmpName = path.basename(tmpDir).toLowerCase();
1252
+ const outDir = path2.resolve(resolved.cwd, resolved.outDir);
1253
+ const tmpDir = path2.resolve(resolved.cwd, resolved.tmpDir);
1254
+ const outName = path2.basename(outDir).toLowerCase();
1255
+ const tmpName = path2.basename(tmpDir).toLowerCase();
571
1256
  const isGenerated = (candidate) => candidate.toLowerCase().split(/[\\/]/).some(
572
1257
  (segment) => segment === outName || segment === tmpName || segment.startsWith(`${outName}.backup-`)
573
1258
  );
@@ -593,7 +1278,7 @@ async function runWatchLoop(invocation, resolved) {
593
1278
  let timer = null;
594
1279
  const watcher = fs.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
595
1280
  if (filename) {
596
- const changed = path.resolve(resolved.cwd, filename.toString());
1281
+ const changed = path2.resolve(resolved.cwd, filename.toString());
597
1282
  if (isGenerated(changed)) return;
598
1283
  }
599
1284
  if (timer) clearTimeout(timer);