codebase-snapshot 0.12.15 → 0.13.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +933 -3
  2. package/README.md +14 -3
  3. package/SECURITY.md +2 -2
  4. package/dist/bin.js +9884 -6034
  5. package/dist/{chunk-FZB2FTHF.js → chunk-BOJYZQFB.js} +7651 -747
  6. package/dist/chunk-NESEHOPU.js +266 -0
  7. package/dist/cli.cjs +9930 -6127
  8. package/dist/cli.d.cts +115 -2
  9. package/dist/cli.d.ts +115 -2
  10. package/dist/cli.js +389 -8
  11. package/dist/{generate-worker-BK4uJx7Z.d.cts → generate-worker-B79yGkQO.d.cts} +16 -0
  12. package/dist/{generate-worker-BK4uJx7Z.d.ts → generate-worker-B79yGkQO.d.ts} +16 -0
  13. package/dist/index.cjs +7389 -680
  14. package/dist/index.d.cts +145 -6
  15. package/dist/index.d.ts +145 -6
  16. package/dist/index.js +1 -1
  17. package/dist/mcp.cjs +3335 -1075
  18. package/dist/mcp.d.cts +86 -4
  19. package/dist/mcp.d.ts +86 -4
  20. package/dist/mcp.js +2 -2
  21. package/dist/{types-c0tLF2WC.d.cts → types-CbD8yQRZ.d.cts} +145 -1
  22. package/dist/{types-c0tLF2WC.d.ts → types-CbD8yQRZ.d.ts} +145 -1
  23. package/docs/agent.md +1 -1
  24. package/docs/benchmarks.md +80 -0
  25. package/docs/budget.md +59 -0
  26. package/docs/cli.md +41 -4
  27. package/docs/configuration.md +27 -0
  28. package/docs/delta.md +50 -0
  29. package/docs/deploy.md +75 -0
  30. package/docs/health.md +13 -0
  31. package/docs/mcp.md +112 -11
  32. package/docs/migration.md +68 -0
  33. package/docs/output.md +9 -3
  34. package/docs/remote.md +60 -0
  35. package/docs/security-review.md +117 -0
  36. package/docs/serve.md +66 -0
  37. package/docs/signing.md +61 -0
  38. package/docs/slice.md +57 -0
  39. package/docs/tools.md +161 -0
  40. package/docs/troubleshooting.md +63 -0
  41. package/docs/vs-repomix.md +1 -1
  42. package/docs/workspace.md +93 -0
  43. package/package.json +1 -1
  44. package/dist/chunk-EPAXW6QJ.js +0 -3749
@@ -1,3749 +0,0 @@
1
- import { GENERATOR_VERSION, describeManifestShapeProblem, compileSecretRules, DEFAULT_SECRET_PATTERNS, scanAndRedactSecrets, estimateTokens, anchorForPath, displayPath, MIN_MAX_PART_BYTES, SCHEMA_VERSION, GENERATOR_NAME, ARTIFACT_NAMES, PRESETS, generateInWorker, validateSnapshot, buildImportResolver, resolveSpecifier, truncateToBytes, explainPath, renderExplainText, loadConfigFileDetailed, parseByteSize, resolveConfig } from './chunk-FZB2FTHF.js';
2
- import * as fs2 from 'fs';
3
- import * as path2 from 'path';
4
- import { execFileSync } from 'child_process';
5
- import { createHash } from 'crypto';
6
-
7
- // src/mcp/protocol.ts
8
- var LEGACY_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18"];
9
- var MODERN_PROTOCOL_VERSIONS = ["2026-07-28"];
10
- var SUPPORTED_PROTOCOL_VERSIONS = [
11
- ...MODERN_PROTOCOL_VERSIONS,
12
- ...LEGACY_PROTOCOL_VERSIONS
13
- ];
14
- var DEFAULT_LEGACY_PROTOCOL_VERSION = LEGACY_PROTOCOL_VERSIONS[0];
15
- var ERROR_CODES = {
16
- parseError: -32700,
17
- invalidRequest: -32600,
18
- methodNotFound: -32601,
19
- invalidParams: -32602,
20
- internalError: -32603,
21
- /**
22
- * A resource whose complete text is larger than one read may return.
23
- *
24
- * `-32000` is JSON-RPC's range for implementation-defined server errors, which is what this is:
25
- * there is no standard code for "the document is too large", and answering with -32602 would tell
26
- * a client its request was malformed when it was not. The message names the size, the limit and
27
- * the tool to use instead, because a resource read that cannot return the whole resource must not
28
- * invent a partial one.
29
- */
30
- resourceTooLarge: -32e3,
31
- /**
32
- * A known resource that this snapshot does not contain.
33
- *
34
- * `-32002` is the MCP code for "resource not found". Answering `-32602` ("Unknown resource")
35
- * for `snapshot://prompt` in a snapshot generated with `--skip-artifacts prompt` told the
36
- * client its URI was wrong when the artifact had simply been left out.
37
- */
38
- resourceNotFound: -32002,
39
- /**
40
- * The server is at its concurrency limit.
41
- *
42
- * Implementation-defined range, like `resourceTooLarge`. A typed error rather than silent
43
- * queueing or a dropped request: the caller can retry, and knows why.
44
- */
45
- overloaded: -32001,
46
- unsupportedProtocolVersion: -32022
47
- };
48
- var METHOD = {
49
- initialize: "initialize",
50
- initialized: "notifications/initialized",
51
- discover: "server/discover",
52
- ping: "ping",
53
- toolsList: "tools/list",
54
- toolsCall: "tools/call",
55
- resourcesList: "resources/list",
56
- resourcesRead: "resources/read",
57
- resourceTemplatesList: "resources/templates/list",
58
- promptsList: "prompts/list",
59
- promptsGet: "prompts/get",
60
- cancelled: "notifications/cancelled"
61
- };
62
- var META_KEYS = {
63
- protocolVersion: "io.modelcontextprotocol/protocolVersion",
64
- clientCapabilities: "io.modelcontextprotocol/clientCapabilities",
65
- clientInfo: "io.modelcontextprotocol/clientInfo",
66
- serverInfo: "io.modelcontextprotocol/serverInfo"};
67
- function isJsonObject(value) {
68
- return typeof value === "object" && value !== null && !Array.isArray(value);
69
- }
70
- function serverInfoMeta(info) {
71
- const value = { name: info.name, version: info.version };
72
- if (info.title) value.title = info.title;
73
- return { [META_KEYS.serverInfo]: value };
74
- }
75
- function successResponse(id, result, modern, info) {
76
- if (!modern) return { jsonrpc: "2.0", id, result };
77
- const withMeta = {
78
- ...result,
79
- resultType: "complete",
80
- _meta: { ...isJsonObject(result._meta) ? result._meta : {}, ...serverInfoMeta(info) }
81
- };
82
- return { jsonrpc: "2.0", id, result: withMeta };
83
- }
84
- function errorResponse(id, code, message, data) {
85
- const error = { code, message };
86
- if (data !== void 0) error.data = data;
87
- return { jsonrpc: "2.0", id, error };
88
- }
89
-
90
- // src/mcp/era.ts
91
- function createSession() {
92
- return { era: null, protocolVersion: null, ready: false };
93
- }
94
- function isLegacyVersion(version) {
95
- return LEGACY_PROTOCOL_VERSIONS.includes(version);
96
- }
97
- function isModernVersion(version) {
98
- return MODERN_PROTOCOL_VERSIONS.includes(version);
99
- }
100
- function inspectModernMeta(params) {
101
- const raw = params?._meta;
102
- if (!isJsonObject(raw)) return { kind: "absent" };
103
- const version = raw[META_KEYS.protocolVersion];
104
- if (typeof version !== "string" || version.length === 0) {
105
- return { kind: "incomplete", missing: META_KEYS.protocolVersion };
106
- }
107
- const capabilities2 = raw[META_KEYS.clientCapabilities];
108
- if (!isJsonObject(capabilities2)) {
109
- return { kind: "incomplete", missing: META_KEYS.clientCapabilities };
110
- }
111
- const info = raw[META_KEYS.clientInfo];
112
- return {
113
- kind: "present",
114
- meta: {
115
- version,
116
- clientCapabilities: capabilities2,
117
- clientInfo: isJsonObject(info) ? info : null
118
- }
119
- };
120
- }
121
- function unsupportedVersionData(requested) {
122
- return { requested, supported: [...SUPPORTED_PROTOCOL_VERSIONS] };
123
- }
124
- function classifyRequest(method, params, session) {
125
- const inspection = inspectModernMeta(params);
126
- if (session.era === "modern") {
127
- if (inspection.kind === "absent") {
128
- return {
129
- kind: "error",
130
- code: ERROR_CODES.invalidRequest,
131
- message: `This request has no _meta. The modern era requires "${META_KEYS.protocolVersion}" and "${META_KEYS.clientCapabilities}" on every request.`
132
- };
133
- }
134
- if (inspection.kind === "incomplete") {
135
- return {
136
- kind: "error",
137
- code: ERROR_CODES.invalidParams,
138
- message: `The request _meta is missing the required key "${inspection.missing}".`
139
- };
140
- }
141
- if (!isModernVersion(inspection.meta.version)) {
142
- return {
143
- kind: "error",
144
- code: ERROR_CODES.unsupportedProtocolVersion,
145
- message: `Unsupported protocol version "${inspection.meta.version}".`,
146
- data: unsupportedVersionData(inspection.meta.version)
147
- };
148
- }
149
- return { kind: "era", era: "modern", version: inspection.meta.version };
150
- }
151
- if (session.era === "legacy") {
152
- return { kind: "era", era: "legacy", version: session.protocolVersion };
153
- }
154
- if (method === METHOD.initialize) {
155
- return { kind: "era", era: "legacy", version: null };
156
- }
157
- if (inspection.kind === "present") {
158
- if (!isModernVersion(inspection.meta.version)) {
159
- return {
160
- kind: "error",
161
- code: ERROR_CODES.unsupportedProtocolVersion,
162
- message: `Unsupported protocol version "${inspection.meta.version}".`,
163
- data: unsupportedVersionData(inspection.meta.version)
164
- };
165
- }
166
- return { kind: "era", era: "modern", version: inspection.meta.version };
167
- }
168
- if (inspection.kind === "incomplete") {
169
- return {
170
- kind: "error",
171
- code: ERROR_CODES.invalidParams,
172
- message: `The request _meta is missing the required key "${inspection.missing}".`
173
- };
174
- }
175
- if (method === METHOD.discover) {
176
- return { kind: "era", era: "modern", version: MODERN_PROTOCOL_VERSIONS[0] };
177
- }
178
- return { kind: "era", era: "legacy", version: null };
179
- }
180
- function negotiateLegacyVersion(requested) {
181
- if (typeof requested === "string" && isLegacyVersion(requested)) {
182
- return { version: requested, matched: true };
183
- }
184
- return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
185
- }
186
- var ARTIFACT_FILES = {
187
- readme: "README.md",
188
- prompt: "PROMPT.md",
189
- navigation: "reports/navigation.md",
190
- projectTree: "reports/project-tree.md",
191
- audit: "reports/audit.md",
192
- fullJson: "full-codebase.json",
193
- fullMarkdown: "full-codebase.md"
194
- };
195
- var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
196
- function sha256(buffer) {
197
- return createHash("sha256").update(buffer).digest("hex");
198
- }
199
- function readBytes(file) {
200
- try {
201
- return fs2.readFileSync(file);
202
- } catch {
203
- return null;
204
- }
205
- }
206
- function readText(file) {
207
- try {
208
- return fs2.readFileSync(file, "utf8");
209
- } catch {
210
- return null;
211
- }
212
- }
213
- function readJson(file) {
214
- const text = readText(file);
215
- if (text === null) return null;
216
- try {
217
- return JSON.parse(text);
218
- } catch {
219
- return null;
220
- }
221
- }
222
- function walk(dir, prefix = "") {
223
- let entries;
224
- try {
225
- entries = fs2.readdirSync(dir, { withFileTypes: true });
226
- } catch {
227
- return [];
228
- }
229
- const files = [];
230
- for (const entry of entries) {
231
- const relative3 = prefix === "" ? entry.name : prefix + "/" + entry.name;
232
- if (entry.isDirectory()) files.push(...walk(path2.join(dir, entry.name), relative3));
233
- else if (entry.isFile()) files.push(relative3);
234
- }
235
- return files;
236
- }
237
- function check(id, title, severity, status, detail) {
238
- return { id, title, severity, status, detail };
239
- }
240
- function scoreOf(checks) {
241
- let score = 100;
242
- for (const item of checks) {
243
- if (item.status === "fail") score -= 25;
244
- else if (item.status === "warn") score -= 5;
245
- }
246
- return Math.max(0, score);
247
- }
248
- function formatBytes(bytes) {
249
- if (bytes < 1024) return bytes + " B";
250
- if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KiB";
251
- return (bytes / (1024 * 1024)).toFixed(2) + " MiB";
252
- }
253
- function sample(items, limit = 3) {
254
- const shown = items.slice(0, limit).join(", ");
255
- return items.length > limit ? shown + " and " + (items.length - limit) + " more" : shown;
256
- }
257
- function escapeRegExp(value) {
258
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
259
- }
260
- function secretTokens(text) {
261
- const tokens = /* @__PURE__ */ new Set();
262
- for (const raw of text.split(/[\s"',;`]+/)) {
263
- const token = raw.trim();
264
- if (token.length < 12 || token.length > 200) continue;
265
- if (!/[0-9]/.test(token) && !(/[a-z]/.test(token) && /[A-Z]/.test(token))) continue;
266
- tokens.add(token);
267
- if (tokens.size >= 60) break;
268
- }
269
- return [...tokens];
270
- }
271
- function artifactTextContains(snapshotDir, token) {
272
- for (const relative3 of walk(snapshotDir)) {
273
- if (!TEXT_ARTIFACT.test(relative3)) continue;
274
- const text = readText(path2.join(snapshotDir, relative3));
275
- if (text !== null && text.includes(token)) return true;
276
- }
277
- return false;
278
- }
279
- function findHostPaths(snapshotDir, repoDir) {
280
- const patterns = [
281
- /\/home\/[A-Za-z0-9._-]+/g,
282
- /\/Users\/[A-Za-z0-9._-]+/g,
283
- /[A-Za-z]:\\Users\\[A-Za-z0-9._-]+/g
284
- ];
285
- const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
286
- const hits = /* @__PURE__ */ new Set();
287
- for (const relative3 of walk(snapshotDir)) {
288
- if (!TEXT_ARTIFACT.test(relative3)) continue;
289
- const text = readText(path2.join(snapshotDir, relative3));
290
- if (text === null) continue;
291
- for (const pattern of patterns) {
292
- for (const match of text.match(pattern) ?? []) hits.add(relative3 + ": " + match);
293
- }
294
- repoPattern.lastIndex = 0;
295
- if (repoPattern.test(text)) hits.add(relative3 + ": the repository absolute path");
296
- }
297
- return [...hits];
298
- }
299
- function staleAgainstRepository(manifest, repoDir) {
300
- const recorded = manifest.git.commit;
301
- if (recorded === "" || recorded === "unknown" || recorded === "none") return null;
302
- let head;
303
- try {
304
- head = execFileSync("git", ["rev-parse", "HEAD"], {
305
- cwd: repoDir,
306
- encoding: "utf8",
307
- stdio: ["ignore", "pipe", "ignore"]
308
- }).trim();
309
- } catch {
310
- return null;
311
- }
312
- if (head === recorded) return null;
313
- return "HEAD is " + head.slice(0, 8) + " but the snapshot was generated at " + recorded.slice(0, 8) + "; regenerate before trusting it.";
314
- }
315
- function auditSnapshot(options) {
316
- const snapshotDir = path2.resolve(options.snapshotDir);
317
- const repoDir = path2.resolve(options.repoDir);
318
- const checks = [];
319
- const manifestFile = path2.join(snapshotDir, "manifest.json");
320
- const raw = readJson(manifestFile);
321
- const problem = raw === null ? "the file is missing or is not valid JSON" : describeManifestShapeProblem(raw);
322
- if (raw === null || problem !== null) {
323
- checks.push(
324
- check(
325
- "manifest",
326
- "Manifest is present and well-formed",
327
- "critical",
328
- "fail",
329
- raw === null ? "No readable manifest at " + manifestFile + "." : "Not a snapshot manifest: " + problem
330
- )
331
- );
332
- return report(snapshotDir, repoDir, checks);
333
- }
334
- const manifest = raw;
335
- checks.push(
336
- check(
337
- "manifest",
338
- "Manifest is present and well-formed",
339
- "critical",
340
- "pass",
341
- "Schema " + manifest.schemaVersion + ", fingerprint " + manifest.fingerprint.slice(0, 12) + "."
342
- )
343
- );
344
- const partNames = new Set(manifest.parts.map((part) => part.filename));
345
- const missingParts = [];
346
- const mismatched = [];
347
- for (const part of manifest.parts) {
348
- const bytes = readBytes(path2.join(snapshotDir, "parts", part.filename));
349
- if (bytes === null) {
350
- missingParts.push(part.filename);
351
- continue;
352
- }
353
- if (bytes.length !== part.byteSize) {
354
- mismatched.push(part.filename + " (size " + bytes.length + " != " + part.byteSize + ")");
355
- } else if (sha256(bytes) !== part.sha256) {
356
- mismatched.push(part.filename + " (sha256)");
357
- }
358
- }
359
- checks.push(
360
- missingParts.length === 0 ? check(
361
- "parts.present",
362
- "Every part the manifest names is on disk",
363
- "critical",
364
- "pass",
365
- manifest.parts.length + " part(s) present."
366
- ) : check(
367
- "parts.present",
368
- "Every part the manifest names is on disk",
369
- "critical",
370
- "fail",
371
- missingParts.length + " missing: " + sample(missingParts)
372
- )
373
- );
374
- checks.push(
375
- mismatched.length === 0 ? check(
376
- "parts.hashes",
377
- "Every part matches its recorded size and hash",
378
- "critical",
379
- "pass",
380
- manifest.parts.length + " part(s) verified."
381
- ) : check(
382
- "parts.hashes",
383
- "Every part matches its recorded size and hash",
384
- "critical",
385
- "fail",
386
- mismatched.length + " altered: " + sample(mismatched)
387
- )
388
- );
389
- const unassigned = manifest.files.filter(
390
- (file) => file.part === null || !partNames.has(file.part)
391
- );
392
- const declared = manifest.parts.reduce((total, part) => total + part.fileCount, 0);
393
- checks.push(
394
- unassigned.length === 0 && declared === manifest.files.length ? check(
395
- "parts.accounting",
396
- "Every file is in exactly one part",
397
- "critical",
398
- "pass",
399
- manifest.files.length + " file(s) across " + manifest.parts.length + " part(s)."
400
- ) : check(
401
- "parts.accounting",
402
- "Every file is in exactly one part",
403
- "critical",
404
- "fail",
405
- unassigned.length + " file(s) point at no part; the parts declare " + declared + " of " + manifest.files.length + "."
406
- )
407
- );
408
- const artifacts = manifest.artifacts ?? {};
409
- const artifactProblems = [];
410
- let artifactCount = 0;
411
- for (const [key, value] of Object.entries(artifacts)) {
412
- if (value === null || value === void 0) continue;
413
- const relative3 = ARTIFACT_FILES[key];
414
- if (relative3 === void 0) continue;
415
- artifactCount += 1;
416
- const bytes = readBytes(path2.join(snapshotDir, relative3));
417
- if (bytes === null) artifactProblems.push(relative3 + " is missing");
418
- else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
419
- artifactProblems.push(relative3 + " changed");
420
- }
421
- }
422
- checks.push(
423
- artifactProblems.length === 0 ? check(
424
- "artifacts",
425
- "Every recorded artifact is present and unchanged",
426
- "critical",
427
- "pass",
428
- artifactCount + " artifact(s) verified."
429
- ) : check(
430
- "artifacts",
431
- "Every recorded artifact is present and unchanged",
432
- "critical",
433
- "fail",
434
- sample(artifactProblems)
435
- )
436
- );
437
- const known = /* @__PURE__ */ new Set([
438
- ".codebase-snapshot",
439
- "manifest.json",
440
- ...Object.values(ARTIFACT_FILES),
441
- ...manifest.parts.map((part) => "parts/" + part.filename)
442
- ]);
443
- const unexpected = walk(snapshotDir).filter((file) => !known.has(file));
444
- checks.push(
445
- unexpected.length === 0 ? check(
446
- "artifacts.extra",
447
- "Nothing unexpected in the snapshot directory",
448
- "warning",
449
- "pass",
450
- known.size + " expected path(s), no others."
451
- ) : check(
452
- "artifacts.extra",
453
- "Nothing unexpected in the snapshot directory",
454
- "warning",
455
- "warn",
456
- unexpected.length + " unexpected path(s): " + sample(unexpected)
457
- )
458
- );
459
- const rules = [...compileSecretRules(DEFAULT_SECRET_PATTERNS), ...options.secretRules ?? []];
460
- const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
461
- const leakHits = [];
462
- let scannedBytes = 0;
463
- for (const relative3 of walk(snapshotDir)) {
464
- if (!TEXT_ARTIFACT.test(relative3) || scannedBytes > scanBudget) continue;
465
- const text = readText(path2.join(snapshotDir, relative3));
466
- if (text === null) continue;
467
- scannedBytes += Buffer.byteLength(text, "utf8");
468
- const found = scanAndRedactSecrets(text, rules, relative3);
469
- if (found.findings.length > 0) {
470
- leakHits.push(relative3 + " (" + found.findings.length + " line(s))");
471
- }
472
- }
473
- checks.push(
474
- leakHits.length === 0 ? check(
475
- "secrets.artifacts",
476
- "No unmasked secret survives in an artifact",
477
- "critical",
478
- "pass",
479
- "Scanned " + formatBytes(scannedBytes) + " across the written artifacts."
480
- ) : check(
481
- "secrets.artifacts",
482
- "No unmasked secret survives in an artifact",
483
- "critical",
484
- "fail",
485
- leakHits.length + " artifact(s) contain a secret-shaped value: " + sample(leakHits)
486
- )
487
- );
488
- const skippedSensitive = manifest.skipped.filter(
489
- (record) => record.reason.startsWith("sensitive")
490
- );
491
- const leakedFrom = [];
492
- let compared = 0;
493
- for (const record of skippedSensitive.slice(0, 40)) {
494
- if (record.path.includes("[REDACTED") || compared > 400) continue;
495
- const text = readText(path2.join(repoDir, record.path));
496
- if (text === null) continue;
497
- for (const token of secretTokens(text)) {
498
- compared += 1;
499
- if (artifactTextContains(snapshotDir, token)) leakedFrom.push(record.path);
500
- }
501
- }
502
- checks.push(
503
- leakedFrom.length === 0 ? check(
504
- "secrets.skipped",
505
- "No value from an excluded sensitive file appears in an artifact",
506
- "critical",
507
- "pass",
508
- skippedSensitive.length + " sensitive path(s) excluded; " + compared + " value(s) compared."
509
- ) : check(
510
- "secrets.skipped",
511
- "No value from an excluded sensitive file appears in an artifact",
512
- "critical",
513
- "fail",
514
- "A value from " + sample([...new Set(leakedFrom)]) + " appears in the snapshot."
515
- )
516
- );
517
- const pii = findHostPaths(snapshotDir, repoDir);
518
- checks.push(
519
- pii.length === 0 ? check(
520
- "pii.paths",
521
- "No host path or machine identity leaks into the text",
522
- "warning",
523
- "pass",
524
- "No absolute home path or repository root found."
525
- ) : check(
526
- "pii.paths",
527
- "No host path or machine identity leaks into the text",
528
- "warning",
529
- "warn",
530
- pii.length + " hit(s): " + sample(pii)
531
- )
532
- );
533
- let recomputed = 0;
534
- for (const part of manifest.parts) {
535
- const text = readText(path2.join(snapshotDir, "parts", part.filename));
536
- if (text !== null) recomputed += estimateTokens(text);
537
- }
538
- const recorded = manifest.totals.estimatedTokens ?? null;
539
- checks.push(
540
- recorded === null ? check(
541
- "tokens.count",
542
- "The token estimate is recorded and plausible",
543
- "warning",
544
- "skip",
545
- "The manifest predates token accounting; recomputed " + recomputed + "."
546
- ) : Math.abs(recomputed - recorded) / Math.max(1, recorded) <= 0.25 ? check(
547
- "tokens.count",
548
- "The token estimate is recorded and plausible",
549
- "warning",
550
- "pass",
551
- "Recorded " + recorded + ", recomputed " + recomputed + "."
552
- ) : check(
553
- "tokens.count",
554
- "The token estimate is recorded and plausible",
555
- "warning",
556
- "warn",
557
- "Recorded " + recorded + ", recomputed " + recomputed + ": the manifest no longer describes these parts."
558
- )
559
- );
560
- const overBudget = manifest.parts.filter(
561
- (part) => part.byteSize > manifest.budgets.maxPartBytes
562
- );
563
- checks.push(
564
- overBudget.length === 0 ? check(
565
- "tokens.budget",
566
- "Every part honours the budget the manifest publishes",
567
- "warning",
568
- "pass",
569
- "Ceiling " + formatBytes(manifest.budgets.maxPartBytes) + "."
570
- ) : check(
571
- "tokens.budget",
572
- "Every part honours the budget the manifest publishes",
573
- "warning",
574
- "warn",
575
- overBudget.length + " part(s) exceed " + formatBytes(manifest.budgets.maxPartBytes) + ": " + sample(overBudget.map((part) => part.filename))
576
- )
577
- );
578
- const badSkips = manifest.skipped.filter((record) => !record.reason || !record.path);
579
- checks.push(
580
- badSkips.length === 0 && manifest.skipped.length === manifest.totals.skippedFiles ? check(
581
- "skips",
582
- "Every excluded path is recorded with a reason",
583
- "critical",
584
- "pass",
585
- manifest.skipped.length + " skip record(s)."
586
- ) : check(
587
- "skips",
588
- "Every excluded path is recorded with a reason",
589
- "critical",
590
- "fail",
591
- badSkips.length + " record(s) lack a path or reason; totals say " + manifest.totals.skippedFiles + "."
592
- )
593
- );
594
- const stale = staleAgainstRepository(manifest, repoDir);
595
- checks.push(
596
- stale === null ? check(
597
- "freshness",
598
- "The snapshot still describes the repository",
599
- "warning",
600
- "pass",
601
- "HEAD matches the recorded commit."
602
- ) : check("freshness", "The snapshot still describes the repository", "warning", "warn", stale)
603
- );
604
- return report(snapshotDir, repoDir, checks);
605
- }
606
- function report(snapshotDir, repoDir, checks) {
607
- const counts = { pass: 0, warn: 0, fail: 0, skip: 0 };
608
- for (const item of checks) counts[item.status] += 1;
609
- return {
610
- snapshotDir,
611
- repoDir,
612
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
613
- score: scoreOf(checks),
614
- checks,
615
- counts
616
- };
617
- }
618
-
619
- // src/mcp/part.ts
620
- var FILE_HEADING = "### FILE: ";
621
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
622
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
623
- var META_PREFIX = "- Meta: ";
624
- var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
625
- var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
626
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
627
- var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
628
- function readIncludedLines(fields) {
629
- const last = fields[fields.length - 1];
630
- if (last === void 0) return null;
631
- const counts = COMPACT_COUNTS.exec(last.trim());
632
- return counts === null ? null : Number(counts[1]);
633
- }
634
- function parsePartSections(partText) {
635
- const lines = partText.split("\n");
636
- const sections = [];
637
- let index = 0;
638
- while (index < lines.length) {
639
- if (!lines[index].startsWith(FILE_HEADING)) {
640
- index += 1;
641
- continue;
642
- }
643
- const heading = lines[index].slice(FILE_HEADING.length);
644
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
645
- let cursor = index + 1;
646
- let inclusion = null;
647
- let includedLines = null;
648
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
649
- const line = lines[cursor];
650
- if (line.startsWith(FILE_HEADING)) break;
651
- if (line.startsWith(META_PREFIX)) {
652
- const fields = line.slice(META_PREFIX.length).split("|");
653
- for (const field of fields) {
654
- const value = field.trim();
655
- if (INCLUSION_MODES.has(value)) inclusion = value;
656
- }
657
- includedLines = readIncludedLines(fields);
658
- } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
659
- inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
660
- } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
661
- const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
662
- includedLines = Number.isFinite(value) ? value : null;
663
- }
664
- cursor += 1;
665
- }
666
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
667
- index = cursor + 1;
668
- continue;
669
- }
670
- let fenceLine = cursor + 1;
671
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
672
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
673
- if (!fenceMatch) {
674
- index = cursor + 1;
675
- continue;
676
- }
677
- const fence = fenceMatch[1];
678
- const body = [];
679
- let bodyLine = fenceLine + 1;
680
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
681
- body.push(lines[bodyLine]);
682
- bodyLine += 1;
683
- }
684
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
685
- index = bodyLine + 1;
686
- }
687
- return sections;
688
- }
689
- function findSection(sections, relativePath) {
690
- const anchor = anchorForPath(relativePath);
691
- const byAnchor = sections.find((section) => section.anchor === anchor);
692
- if (byAnchor) return byAnchor;
693
- const rendered = displayPath(relativePath);
694
- const samePath = (section) => section.path === relativePath || section.path === rendered;
695
- const exact = sections.find(samePath);
696
- if (exact) return exact;
697
- const foldedPath = rendered.toLowerCase();
698
- const folded = sections.filter((section) => {
699
- const path5 = section.path.toLowerCase();
700
- return path5 === relativePath.toLowerCase() || path5 === foldedPath;
701
- });
702
- return folded.length === 1 ? folded[0] : null;
703
- }
704
- function windowText(body, fromLine, lineCount) {
705
- const lines = body.split("\n");
706
- const total = body.length === 0 ? 0 : lines.length;
707
- const requested = Math.max(1, Math.trunc(fromLine));
708
- const pastEnd = total > 0 && requested > total;
709
- const start = pastEnd ? requested : Math.min(requested, Math.max(1, total));
710
- const end = Math.min(total, start + Math.max(1, Math.trunc(lineCount)) - 1);
711
- const slice = pastEnd ? [] : lines.slice(start - 1, Math.max(start - 1, end));
712
- return {
713
- text: slice.join("\n"),
714
- fromLine: start,
715
- returnedLines: slice.length,
716
- totalLines: total,
717
- truncated: !pastEnd && end < total,
718
- nextFromLine: !pastEnd && end < total ? end + 1 : null,
719
- pastEnd
720
- };
721
- }
722
- function foldForComparison(value) {
723
- return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
724
- }
725
- function canonicalPath(value) {
726
- const absolute = path2.resolve(value);
727
- try {
728
- return fs2.realpathSync(absolute);
729
- } catch {
730
- return absolute;
731
- }
732
- }
733
- function isInside(parent, child) {
734
- const foldedParent = foldForComparison(parent);
735
- const foldedChild = foldForComparison(child);
736
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path2.sep}`);
737
- }
738
- function resolveThroughExistingAncestor(target) {
739
- let existing = target;
740
- const missing = [];
741
- while (!fs2.existsSync(existing)) {
742
- missing.unshift(path2.basename(existing));
743
- const parent = path2.dirname(existing);
744
- if (parent === existing) break;
745
- existing = parent;
746
- }
747
- const resolved = canonicalPath(existing);
748
- return missing.length === 0 ? resolved : path2.join(resolved, ...missing);
749
- }
750
- function resolveRoot(requested, context) {
751
- if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
752
- return { ok: false, message: '"root" must be a non-empty string when provided.' };
753
- }
754
- const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
755
- const absolute = path2.resolve(context.cwd, wanted);
756
- let stats;
757
- try {
758
- stats = fs2.statSync(absolute);
759
- } catch {
760
- return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
761
- }
762
- if (!stats.isDirectory()) {
763
- return { ok: false, message: `"${wanted}" is not a directory.` };
764
- }
765
- const resolved = canonicalPath(absolute);
766
- for (const allowed of context.roots) {
767
- if (isInside(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
768
- }
769
- const shown = context.roots.join(", ");
770
- return {
771
- ok: false,
772
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). The server reads the directory it was started for; restart it with --cwd <directory> to serve a different repository.`
773
- };
774
- }
775
- async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
776
- const loaded = await loadConfigFileDetailed(root, options);
777
- if (loaded.errors.length > 0) {
778
- return {
779
- ok: false,
780
- message: `The config file could not be read: ${loaded.errors.join("; ")} Fix it, or delete it to use the defaults \u2014 this server will not silently ignore it.`
781
- };
782
- }
783
- const cliOptions = { cwd: root };
784
- if (overrides.maxPartBytes !== void 0) {
785
- const parsed = parseByteSize(overrides.maxPartBytes);
786
- if (parsed === void 0) {
787
- return {
788
- ok: false,
789
- message: '"maxPartBytes" must be a byte count, for example 307200 or "300k".'
790
- };
791
- }
792
- cliOptions.maxPartBytes = parsed;
793
- }
794
- if (overrides.maxPartTokens !== void 0) {
795
- const parsed = parseByteSize(overrides.maxPartTokens);
796
- if (parsed === void 0) {
797
- return {
798
- ok: false,
799
- message: '"maxPartTokens" must be a token count, for example 32000 or "32k".'
800
- };
801
- }
802
- cliOptions.maxPartTokens = parsed;
803
- }
804
- if (overrides.outDir !== void 0) {
805
- if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
806
- return { ok: false, message: '"outDir" must be a non-empty string.' };
807
- }
808
- const requested = overrides.outDir.trim();
809
- const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
810
- const resolved = resolveThroughExistingAncestor(path2.resolve(root, requested));
811
- if (!permitted.some((allowed) => isInside(canonicalPath(allowed), resolved))) {
812
- const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
813
- return {
814
- ok: false,
815
- message: `"outDir" must resolve inside the repository this server serves (${shown}). A tool argument may not place the snapshot outside it; pass a directory inside the root, or restart the server with --cwd pointing at the repository you want to write.`
816
- };
817
- }
818
- cliOptions.outDir = requested;
819
- }
820
- if (overrides.changedSince !== void 0) {
821
- if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
822
- return {
823
- ok: false,
824
- message: '"changedSince" must be a git ref such as "main" or "HEAD~3".'
825
- };
826
- }
827
- cliOptions.changedSince = overrides.changedSince.trim();
828
- }
829
- if (overrides.skeleton === true) cliOptions.skeleton = true;
830
- if (overrides.sarif === true) cliOptions.sarif = true;
831
- if (overrides.staged === true) cliOptions.staged = true;
832
- if (overrides.withDependents === true) cliOptions.withDependents = true;
833
- try {
834
- const config = resolveConfig(loaded.config, cliOptions, root);
835
- return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
836
- } catch (error) {
837
- return { ok: false, message: error instanceof Error ? error.message : String(error) };
838
- }
839
- }
840
- var MANIFEST_CACHE_LIMIT = 8;
841
- var manifestCache = /* @__PURE__ */ new Map();
842
- function manifestPathFor(workspace) {
843
- return path2.resolve(workspace.root, workspace.config.outDir, "manifest.json");
844
- }
845
- function partPathFor(workspace, filename) {
846
- if (filename.length === 0 || filename.includes("\0")) return null;
847
- const partsDir = path2.resolve(workspace.root, workspace.config.outDir, "parts");
848
- const resolved = path2.resolve(partsDir, filename);
849
- const relative3 = path2.relative(partsDir, resolved);
850
- if (relative3.length === 0 || relative3.includes(path2.sep) || relative3.includes("/") || relative3.includes("\\") || path2.isAbsolute(relative3)) {
851
- return null;
852
- }
853
- let stats;
854
- try {
855
- stats = fs2.lstatSync(resolved);
856
- } catch {
857
- return null;
858
- }
859
- if (!stats.isFile()) return null;
860
- try {
861
- if (path2.dirname(fs2.realpathSync(resolved)) !== fs2.realpathSync(partsDir)) return null;
862
- } catch {
863
- return null;
864
- }
865
- return resolved;
866
- }
867
- function readManifest(workspace) {
868
- const file = manifestPathFor(workspace);
869
- const shown = path2.relative(workspace.root, file).split(path2.sep).join("/") || file;
870
- let stats;
871
- try {
872
- stats = fs2.statSync(file);
873
- } catch {
874
- return {
875
- ok: false,
876
- missing: true,
877
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
878
- };
879
- }
880
- const cached = manifestCache.get(file);
881
- if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
882
- return { ok: true, manifest: cached.manifest, file };
883
- }
884
- let raw;
885
- try {
886
- raw = fs2.readFileSync(file, "utf8");
887
- } catch (error) {
888
- return {
889
- ok: false,
890
- missing: false,
891
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
892
- };
893
- }
894
- let parsed;
895
- try {
896
- parsed = JSON.parse(raw);
897
- } catch {
898
- return { ok: false, missing: false, message: `${shown} is not valid JSON.` };
899
- }
900
- const problem = describeManifestShapeProblem(parsed);
901
- if (problem) {
902
- return { ok: false, missing: false, message: `${shown} is not a snapshot manifest: ${problem}` };
903
- }
904
- const manifest = parsed;
905
- manifestCache.delete(file);
906
- manifestCache.set(file, {
907
- mtimeMs: stats.mtimeMs,
908
- ctimeMs: stats.ctimeMs,
909
- size: stats.size,
910
- manifest
911
- });
912
- while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
913
- const oldest = manifestCache.keys().next().value;
914
- if (oldest === void 0) break;
915
- manifestCache.delete(oldest);
916
- }
917
- return { ok: true, manifest, file };
918
- }
919
- function forgetManifest(file) {
920
- manifestCache.delete(file);
921
- }
922
-
923
- // src/mcp/tools.ts
924
- var READ_ONLY = {
925
- readOnlyHint: true,
926
- destructiveHint: false,
927
- idempotentHint: true,
928
- openWorldHint: false
929
- };
930
- var WRITES = {
931
- readOnlyHint: false,
932
- // It replaces the snapshot directory but never anything it did not write, so it is additive with
933
- // respect to the user's files.
934
- destructiveHint: false,
935
- idempotentHint: true,
936
- openWorldHint: false
937
- };
938
- var MAX_RESULT_BYTES = 64 * 1024;
939
- var ROOT_PROPERTY = {
940
- type: "string",
941
- description: "Repository root. Defaults to the directory this server was started in."
942
- };
943
- var OUT_DIR_PROPERTY = {
944
- type: "string",
945
- description: "Snapshot directory, relative to the root, and it must resolve inside the served repository. Defaults to the project configuration's outDir."
946
- };
947
- var outDirOverride = (args) => ({ outDir: args.outDir });
948
- var SCOPE_PROPERTIES = {
949
- maxPartTokens: {
950
- type: "string",
951
- description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
952
- },
953
- skeleton: {
954
- type: "boolean",
955
- description: "Replace every function body with `{ /* ... */ }`, keeping signatures, imports and exports. Applies to TypeScript, JavaScript and JSX."
956
- },
957
- sarif: {
958
- type: "boolean",
959
- description: "Also write reports/audit.sarif beside reports/audit.md, for CI code scanning."
960
- },
961
- changedSince: {
962
- type: "string",
963
- description: 'Only files changed since this git ref, for example "main" or "HEAD~3".'
964
- },
965
- staged: {
966
- type: "boolean",
967
- description: "Only files staged in the git index."
968
- },
969
- withDependents: {
970
- type: "boolean",
971
- description: "With staged or changedSince, also include the files that import the changed ones (one hop)."
972
- }
973
- };
974
- function workspaceOverrides(args) {
975
- return {
976
- outDir: args.outDir,
977
- maxPartBytes: args.maxPartBytes,
978
- maxPartTokens: args.maxPartTokens,
979
- skeleton: args.skeleton,
980
- sarif: args.sarif,
981
- changedSince: args.changedSince,
982
- staged: args.staged,
983
- withDependents: args.withDependents
984
- };
985
- }
986
- function failure(message) {
987
- return { text: message, isError: true };
988
- }
989
- function plural(count, word) {
990
- return `${count} ${word}${count === 1 ? "" : "s"}`;
991
- }
992
- function formatBytes2(bytes) {
993
- if (bytes < 1024) return `${bytes} B`;
994
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
995
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
996
- }
997
- function relativeFor(workspace, absolute) {
998
- return path2.relative(workspace.root, absolute).split(path2.sep).join("/");
999
- }
1000
- function capped(values, limit = 20) {
1001
- return { count: values.length, sample: values.slice(0, limit) };
1002
- }
1003
- function summarizeDrift(drift) {
1004
- return {
1005
- missingInSnapshot: capped(drift.missingInSnapshot),
1006
- missingOnDisk: capped(drift.missingOnDisk),
1007
- unreadable: capped(drift.unreadable),
1008
- hashMismatches: capped(drift.hashMismatches),
1009
- partIssues: capped(drift.partIssues),
1010
- totalsMismatches: capped(drift.totalsMismatches),
1011
- configMismatches: capped(drift.configMismatches)
1012
- };
1013
- }
1014
- function toRelativePath(root, value) {
1015
- const cleaned = value.trim();
1016
- if (cleaned.length === 0 || cleaned.includes("\0")) return null;
1017
- const resolvedRoot = path2.resolve(root);
1018
- const absolute = path2.resolve(resolvedRoot, cleaned);
1019
- const relative3 = path2.relative(resolvedRoot, absolute);
1020
- if (relative3 === "" || relative3 === ".." || relative3.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative3)) {
1021
- return null;
1022
- }
1023
- return relative3.split(path2.sep).join("/");
1024
- }
1025
- function symbolsOf(entry) {
1026
- const summary = entry.summary;
1027
- if (!summary || typeof summary !== "object") return [];
1028
- const names = [];
1029
- const collect = (value) => {
1030
- if (!Array.isArray(value)) return;
1031
- for (const item of value) {
1032
- if (typeof item === "string") names.push(item);
1033
- }
1034
- };
1035
- const record = summary;
1036
- for (const field of [
1037
- "exports",
1038
- "reactComponents",
1039
- "routeHandlers",
1040
- "functions",
1041
- "classes",
1042
- "interfaces",
1043
- "types",
1044
- "enums",
1045
- "hooks",
1046
- "headings",
1047
- // The rest of the same records. `variables` is where a `const`, a Python constant, a Go
1048
- // `var`, a Rust `mod`, a C `#define` and a Terraform `variable` block all land, so leaving it
1049
- // out made `snapshot_locate` miss most of what a non-JavaScript file declares; `directives`
1050
- // carries `"use client"`-style markers, and `frontmatterKeys`/`keys` are the headings and
1051
- // top-level names of a Markdown or JSON file.
1052
- "variables",
1053
- "directives",
1054
- "frontmatterKeys",
1055
- "keys"
1056
- ]) {
1057
- collect(record[field]);
1058
- }
1059
- return names;
1060
- }
1061
- async function prepare(args, context, overrides = {}) {
1062
- const rootOutcome = resolveRoot(args.root, context);
1063
- if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
1064
- const opened = await openWorkspace(rootOutcome.root, overrides, context.roots, {
1065
- allowExecutableConfig: false
1066
- });
1067
- if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
1068
- return { ok: true, workspace: opened.workspace };
1069
- }
1070
- var healthTool = {
1071
- name: "snapshot_health",
1072
- title: "Snapshot health audit",
1073
- description: "Audit the generated snapshot against the repository: manifest shape, part hashes, the artifacts it claims, unmasked secrets anywhere in the written text, values from files that were excluded as sensitive, host paths, the recorded token count and freshness. Returns a score and one entry per check. Read-only; it never regenerates anything.",
1074
- inputSchema: {
1075
- type: "object",
1076
- properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY },
1077
- additionalProperties: false
1078
- },
1079
- outputSchema: {
1080
- type: "object",
1081
- properties: {
1082
- score: { type: "integer" },
1083
- counts: { type: "object" },
1084
- checks: { type: "array", items: { type: "object" } }
1085
- }
1086
- },
1087
- annotations: READ_ONLY,
1088
- async handler(args, context) {
1089
- const prepared = await prepare(args, context, outDirOverride(args));
1090
- if (!prepared.ok) return prepared.outcome;
1091
- const workspace = prepared.workspace;
1092
- const report2 = auditSnapshot({
1093
- snapshotDir: path2.resolve(workspace.root, workspace.config.outDir),
1094
- repoDir: workspace.root
1095
- });
1096
- const lines = [
1097
- "Health: " + report2.score + "/100 (" + report2.counts.pass + " passed, " + report2.counts.warn + " warning(s), " + report2.counts.fail + " failed)",
1098
- ...report2.checks.map(
1099
- (item) => (item.status === "fail" ? "FAIL " : item.status === "warn" ? "WARN " : "PASS ") + item.id + ": " + item.detail
1100
- )
1101
- ];
1102
- return {
1103
- text: lines.join("\n"),
1104
- structured: {
1105
- score: report2.score,
1106
- counts: report2.counts,
1107
- checks: report2.checks.map((item) => ({
1108
- id: item.id,
1109
- title: item.title,
1110
- severity: item.severity,
1111
- status: item.status,
1112
- detail: item.detail
1113
- }))
1114
- }
1115
- };
1116
- }
1117
- };
1118
- var statusTool = {
1119
- name: "snapshot_status",
1120
- title: "Snapshot status",
1121
- description: "Report whether a snapshot exists for this repository, when it was built, and what it covers. Reads the manifest rather than the repository, so it is cheap. Call it before deciding whether a snapshot needs to be generated.",
1122
- inputSchema: {
1123
- type: "object",
1124
- properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY },
1125
- additionalProperties: false
1126
- },
1127
- outputSchema: {
1128
- type: "object",
1129
- properties: {
1130
- present: { type: "boolean" },
1131
- root: { type: "string" },
1132
- outDir: { type: "string" },
1133
- fingerprint: { type: "string" },
1134
- generatedAt: { type: "string" },
1135
- generatorVersion: { type: "string" },
1136
- generatorVersionMatches: { type: "boolean" },
1137
- includedFiles: { type: "integer" },
1138
- skippedFiles: { type: "integer" },
1139
- partCount: { type: "integer" },
1140
- warningCount: { type: "integer" }
1141
- }
1142
- },
1143
- annotations: READ_ONLY,
1144
- async handler(args, context) {
1145
- const prepared = await prepare(args, context, outDirOverride(args));
1146
- if (!prepared.ok) return prepared.outcome;
1147
- const workspace = prepared.workspace;
1148
- const read = readManifest(workspace);
1149
- if (!read.ok) {
1150
- return {
1151
- text: read.message,
1152
- structured: {
1153
- present: false,
1154
- root: workspace.root,
1155
- outDir: workspace.config.outDir,
1156
- message: read.message
1157
- }
1158
- };
1159
- }
1160
- const manifest = read.manifest;
1161
- const versionMatches = manifest.generator.version === GENERATOR_VERSION;
1162
- const lines = [
1163
- `Snapshot: ${workspace.config.outDir}/`,
1164
- `Generated: ${manifest.generatedAt} by ${manifest.generator.name} ${manifest.generator.version}`,
1165
- `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
1166
- `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
1167
- `Fingerprint: ${manifest.fingerprint}`,
1168
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
1169
- ];
1170
- if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
1171
- if (!versionMatches) {
1172
- lines.push(
1173
- `Note: written by ${manifest.generator.version}, this server is ${GENERATOR_VERSION}. Re-run snapshot_generate if the difference matters.`
1174
- );
1175
- }
1176
- return {
1177
- text: lines.join("\n"),
1178
- structured: {
1179
- present: true,
1180
- root: workspace.root,
1181
- outDir: workspace.config.outDir,
1182
- fingerprint: manifest.fingerprint,
1183
- generatedAt: manifest.generatedAt,
1184
- generatorVersion: manifest.generator.version,
1185
- generatorVersionMatches: versionMatches,
1186
- includedFiles: manifest.counts.totalFiles,
1187
- skippedFiles: manifest.counts.skippedCount,
1188
- partCount: manifest.counts.partsCount,
1189
- warningCount: manifest.totals.warningCount,
1190
- preset: manifest.config.preset,
1191
- maxPartBytes: manifest.budgets.maxPartBytes
1192
- }
1193
- };
1194
- }
1195
- };
1196
- var planTool = {
1197
- name: "snapshot_plan",
1198
- title: "Preview a snapshot",
1199
- description: "Preview a snapshot without writing anything: how many files and parts it would contain, and why every excluded file was excluded. Use it to choose a part budget before generating.",
1200
- inputSchema: {
1201
- type: "object",
1202
- properties: {
1203
- root: ROOT_PROPERTY,
1204
- outDir: OUT_DIR_PROPERTY,
1205
- maxPartBytes: {
1206
- type: "string",
1207
- description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
1208
- },
1209
- ...SCOPE_PROPERTIES
1210
- },
1211
- additionalProperties: false
1212
- },
1213
- outputSchema: {
1214
- type: "object",
1215
- properties: {
1216
- files: { type: "integer" },
1217
- skipped: { type: "integer" },
1218
- parts: { type: "integer" },
1219
- sourceBytes: { type: "integer" },
1220
- emittedBytes: { type: "integer" },
1221
- preset: { type: "string" }
1222
- }
1223
- },
1224
- annotations: READ_ONLY,
1225
- async handler(args, context) {
1226
- const prepared = await prepare(args, context, workspaceOverrides(args));
1227
- if (!prepared.ok) return prepared.outcome;
1228
- const workspace = prepared.workspace;
1229
- const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
1230
- if (!result.ok) return failure(result.message);
1231
- const summary = result.summary;
1232
- const topReasons = summary.skipReasons;
1233
- const lines = [
1234
- "Dry run \u2014 nothing was written.",
1235
- `Preset: ${summary.preset}`,
1236
- `Would include ${plural(summary.totalFiles, "file")} in ${plural(summary.partsCount, "part")} (${formatBytes2(summary.totalSizeBytes)} of source, ${formatBytes2(summary.totalContentBytes)} emitted).`,
1237
- `Would skip ${plural(summary.skippedCount, "file")}.`
1238
- ];
1239
- if (topReasons.length > 0) {
1240
- lines.push("Top skip reasons:");
1241
- for (const entry of topReasons) lines.push(` - ${entry.reason} (${entry.count})`);
1242
- }
1243
- if (summary.warnings.length > 0) {
1244
- lines.push(`Warnings (${summary.warnings.length}):`);
1245
- for (const warning of summary.warnings.slice(0, 5)) lines.push(` - ${warning}`);
1246
- }
1247
- return {
1248
- text: lines.join("\n"),
1249
- structured: {
1250
- files: summary.totalFiles,
1251
- skipped: summary.skippedCount,
1252
- parts: summary.partsCount,
1253
- sourceBytes: summary.totalSizeBytes,
1254
- emittedBytes: summary.totalContentBytes,
1255
- preset: summary.preset,
1256
- maxPartBytes: workspace.config.maxPartBytes,
1257
- layers: summary.layers,
1258
- skipReasons: topReasons,
1259
- warnings: summary.warnings.slice(0, 5),
1260
- warningCount: summary.warnings.length
1261
- }
1262
- };
1263
- }
1264
- };
1265
- var generateTool = {
1266
- name: "snapshot_generate",
1267
- title: "Generate the snapshot",
1268
- description: "Write the snapshot to its output directory and return its fingerprint, parts and counts. Replaces the previous snapshot in that directory. A large repository can take several seconds.",
1269
- inputSchema: {
1270
- type: "object",
1271
- properties: {
1272
- root: ROOT_PROPERTY,
1273
- outDir: OUT_DIR_PROPERTY,
1274
- maxPartBytes: {
1275
- type: "string",
1276
- description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
1277
- },
1278
- ...SCOPE_PROPERTIES
1279
- },
1280
- additionalProperties: false
1281
- },
1282
- outputSchema: {
1283
- type: "object",
1284
- properties: {
1285
- fingerprint: { type: "string" },
1286
- files: { type: "integer" },
1287
- skipped: { type: "integer" },
1288
- parts: { type: "integer" },
1289
- emittedBytes: { type: "integer" }
1290
- }
1291
- },
1292
- annotations: WRITES,
1293
- async handler(args, context) {
1294
- const prepared = await prepare(args, context, workspaceOverrides(args));
1295
- if (!prepared.ok) return prepared.outcome;
1296
- const workspace = prepared.workspace;
1297
- const result = await generateInWorker(workspace.root, workspace.cliOptions);
1298
- if (!result.ok) return failure(result.message);
1299
- const summary = result.summary;
1300
- forgetManifest(manifestPathFor(workspace));
1301
- const written = relativeFor(workspace, path2.resolve(workspace.root, workspace.config.outDir));
1302
- const lines = [
1303
- `Wrote ${written}/`,
1304
- `Files: ${summary.totalFiles} included, ${summary.skippedCount} skipped, ${plural(summary.partsCount, "part")}`,
1305
- `Parts: ${summary.parts.map((part) => `${part.filename} (${formatBytes2(part.byteSize)})`).join(", ")}`,
1306
- `Fingerprint: ${summary.fingerprint}`
1307
- ];
1308
- if (summary.warnings.length > 0) {
1309
- lines.push(`Warnings (${summary.warnings.length}):`);
1310
- for (const warning of summary.warnings.slice(0, 5)) lines.push(` - ${warning}`);
1311
- }
1312
- return {
1313
- text: lines.join("\n"),
1314
- structured: {
1315
- fingerprint: summary.fingerprint,
1316
- files: summary.totalFiles,
1317
- skipped: summary.skippedCount,
1318
- parts: summary.partsCount,
1319
- emittedBytes: summary.totalContentBytes,
1320
- outDir: written,
1321
- partFiles: summary.parts.map((part) => part.filename),
1322
- warningCount: summary.warnings.length
1323
- }
1324
- };
1325
- }
1326
- };
1327
- var validateTool = {
1328
- name: "snapshot_validate",
1329
- title: "Validate the snapshot",
1330
- description: "Re-read the repository and report whether the snapshot on disk still matches it. Use it before trusting context that came from an earlier session, or after changing the config.",
1331
- inputSchema: {
1332
- type: "object",
1333
- properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY, ...SCOPE_PROPERTIES },
1334
- additionalProperties: false
1335
- },
1336
- outputSchema: {
1337
- type: "object",
1338
- properties: {
1339
- current: { type: "boolean" },
1340
- manifestPresent: { type: "boolean" }
1341
- }
1342
- },
1343
- annotations: READ_ONLY,
1344
- async handler(args, context) {
1345
- const prepared = await prepare(args, context, workspaceOverrides(args));
1346
- if (!prepared.ok) return prepared.outcome;
1347
- const workspace = prepared.workspace;
1348
- let result;
1349
- try {
1350
- result = validateSnapshot(workspace.config);
1351
- } catch (error) {
1352
- return failure(error instanceof Error ? error.message : String(error));
1353
- }
1354
- const lines = [];
1355
- if (result.valid) {
1356
- lines.push("The snapshot matches the repository.");
1357
- } else {
1358
- lines.push("The snapshot is out of date.");
1359
- const drift = result.drift;
1360
- const observations = [
1361
- ["file(s) changed on disk", drift.hashMismatches.length],
1362
- ["file(s) added since the snapshot", drift.missingInSnapshot.length],
1363
- ["file(s) gone since the snapshot", drift.missingOnDisk.length],
1364
- ["part file(s) damaged or missing", drift.partIssues.length],
1365
- ["setting(s) changed since the snapshot", drift.configMismatches.length],
1366
- ["internal count(s) disagreeing", drift.totalsMismatches.length]
1367
- ];
1368
- for (const [label, count] of observations) {
1369
- if (count > 0) lines.push(` - ${count} ${label}`);
1370
- }
1371
- for (const error of result.errors.slice(0, 5)) lines.push(` - ${error}`);
1372
- lines.push("Run snapshot_generate to refresh it.");
1373
- }
1374
- for (const warning of result.warnings.slice(0, 5)) lines.push(`Note: ${warning}`);
1375
- return {
1376
- text: lines.join("\n"),
1377
- structured: {
1378
- current: result.valid,
1379
- manifestPresent: result.manifestPresent,
1380
- drift: summarizeDrift(result.drift),
1381
- errors: result.errors.slice(0, 10),
1382
- warnings: result.warnings.slice(0, 10)
1383
- }
1384
- // A stale snapshot is an answer, not a tool failure: the caller asked whether it is current.
1385
- };
1386
- }
1387
- };
1388
- var locateTool = {
1389
- name: "snapshot_locate",
1390
- title: "Locate code in the snapshot",
1391
- description: "Find which part holds the code you need. Matches file paths, exported symbols, component names and routes from the snapshot's index, so one part can be read instead of all of them.",
1392
- inputSchema: {
1393
- type: "object",
1394
- properties: {
1395
- query: {
1396
- type: "string",
1397
- description: "Text to match, case-insensitively, against paths and exported symbols."
1398
- },
1399
- by: {
1400
- type: "string",
1401
- enum: ["auto", "path", "symbol", "route", "layer", "kind"],
1402
- default: "auto",
1403
- description: "Restrict what is matched. Defaults to every category."
1404
- },
1405
- limit: {
1406
- type: "integer",
1407
- minimum: 1,
1408
- maximum: 100,
1409
- default: 20,
1410
- description: "Maximum matches to return."
1411
- },
1412
- root: ROOT_PROPERTY,
1413
- outDir: OUT_DIR_PROPERTY
1414
- },
1415
- required: ["query"],
1416
- additionalProperties: false
1417
- },
1418
- outputSchema: {
1419
- type: "object",
1420
- properties: { total: { type: "integer" } }
1421
- },
1422
- annotations: READ_ONLY,
1423
- async handler(args, context) {
1424
- const prepared = await prepare(args, context, outDirOverride(args));
1425
- if (!prepared.ok) return prepared.outcome;
1426
- const workspace = prepared.workspace;
1427
- const read = readManifest(workspace);
1428
- if (!read.ok) return failure(read.message);
1429
- const query = String(args.query ?? "").trim();
1430
- if (query.length === 0) return failure('"query" must not be empty.');
1431
- const needle = query.toLowerCase();
1432
- const by = typeof args.by === "string" ? args.by : "auto";
1433
- const limit = typeof args.limit === "number" ? args.limit : 20;
1434
- const manifest = read.manifest;
1435
- const matches = [];
1436
- const add = (entry, matchedBy, detail) => {
1437
- matches.push({
1438
- path: entry.relativePath,
1439
- part: entry.part,
1440
- layer: entry.layer,
1441
- kind: entry.kind,
1442
- matchedBy,
1443
- ...detail ? { detail } : {}
1444
- });
1445
- };
1446
- const wants = (category) => by === "auto" || by === category;
1447
- for (const entry of manifest.files) {
1448
- if (wants("path") && entry.relativePath.toLowerCase().includes(needle)) {
1449
- add(entry, "path");
1450
- continue;
1451
- }
1452
- if (wants("symbol")) {
1453
- const symbol = symbolsOf(entry).find((name) => name.toLowerCase().includes(needle));
1454
- if (symbol) {
1455
- add(entry, "symbol", symbol);
1456
- continue;
1457
- }
1458
- }
1459
- if (wants("layer") && entry.layer.toLowerCase().includes(needle)) add(entry, "layer");
1460
- else if (wants("kind") && entry.kind.toLowerCase().includes(needle)) add(entry, "kind");
1461
- }
1462
- if (wants("route")) {
1463
- const matchedPaths = new Set(matches.map((match) => match.path));
1464
- for (const route of manifest.indexes.routes) {
1465
- const method = route.methods.find((name) => name.toLowerCase().includes(needle));
1466
- if (!route.path.toLowerCase().includes(needle) && method === void 0) continue;
1467
- if (matchedPaths.has(route.path)) continue;
1468
- matchedPaths.add(route.path);
1469
- matches.push({
1470
- path: route.path,
1471
- part: route.part,
1472
- layer: "route",
1473
- kind: "route",
1474
- matchedBy: "route",
1475
- detail: route.methods.join(", ")
1476
- });
1477
- }
1478
- }
1479
- if (matches.length === 0) {
1480
- return {
1481
- text: `Nothing in the snapshot matches "${query}". Try a shorter fragment, or snapshot_explain a path to see whether it is included at all.`,
1482
- structured: { total: 0, matches: [] }
1483
- };
1484
- }
1485
- const shown = matches.slice(0, limit);
1486
- const lines = [
1487
- `${matches.length} match${matches.length === 1 ? "" : "es"} for "${query}"` + (matches.length > shown.length ? ` (showing ${shown.length})` : "") + ":"
1488
- ];
1489
- for (const match of shown) {
1490
- const detail = match.detail ? ` \u2014 ${match.detail}` : "";
1491
- lines.push(` ${match.path}${detail} [${match.part}, ${match.layer}/${match.kind}]`);
1492
- }
1493
- if (matches.length > shown.length) {
1494
- lines.push("Raise `limit` to see more.");
1495
- }
1496
- return {
1497
- text: lines.join("\n"),
1498
- structured: { total: matches.length, returned: shown.length, matches: shown }
1499
- };
1500
- }
1501
- };
1502
- var dependentsTool = {
1503
- name: "snapshot_dependents",
1504
- title: "Follow the import graph",
1505
- description: 'For one file in the snapshot: what it imports, and which files import it. Answers "what breaks if I change this?" without reading the parts.',
1506
- inputSchema: {
1507
- type: "object",
1508
- properties: {
1509
- path: {
1510
- type: "string",
1511
- description: "Snapshot-relative path, exactly as snapshot_locate or manifest.files[] reports it."
1512
- },
1513
- direction: {
1514
- type: "string",
1515
- enum: ["both", "imports", "imported-by"],
1516
- default: "both",
1517
- description: "Which edges to return."
1518
- },
1519
- limit: {
1520
- type: "integer",
1521
- minimum: 1,
1522
- maximum: 200,
1523
- default: 50,
1524
- description: "Maximum entries per direction."
1525
- },
1526
- root: ROOT_PROPERTY,
1527
- outDir: OUT_DIR_PROPERTY
1528
- },
1529
- required: ["path"],
1530
- additionalProperties: false
1531
- },
1532
- outputSchema: {
1533
- type: "object",
1534
- properties: {
1535
- path: { type: "string" },
1536
- imports: { type: "array" },
1537
- importedBy: { type: "array" },
1538
- unresolved: { type: "array" }
1539
- }
1540
- },
1541
- annotations: READ_ONLY,
1542
- async handler(args, context) {
1543
- const prepared = await prepare(args, context, outDirOverride(args));
1544
- if (!prepared.ok) return prepared.outcome;
1545
- const read = readManifest(prepared.workspace);
1546
- if (!read.ok) return failure(read.message);
1547
- const manifest = read.manifest;
1548
- const requested = String(args.path ?? "").trim().replace(/\\/g, "/");
1549
- if (requested.length === 0) return failure('"path" must not be empty.');
1550
- const filesByPath = new Map(manifest.files.map((file) => [file.relativePath, file]));
1551
- const entry = filesByPath.get(requested) ?? manifest.files.find((file) => file.relativePath.toLowerCase() === requested.toLowerCase());
1552
- if (!entry) {
1553
- return failure(
1554
- `${requested} is not in the snapshot. Use snapshot_locate to find its path, or snapshot_explain to see whether it was excluded.`
1555
- );
1556
- }
1557
- const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
1558
- const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
1559
- const resolver = buildImportResolver(manifest.files);
1560
- const imports = [];
1561
- const unresolved = [];
1562
- if (direction !== "imported-by") {
1563
- const own = manifest.indexes.imports.byFile.find((file) => file.path === entry.relativePath);
1564
- for (const specifier of own?.imports ?? []) {
1565
- const resolved = resolveSpecifier(entry.relativePath, specifier, resolver);
1566
- if (resolved === null) {
1567
- unresolved.push(specifier);
1568
- continue;
1569
- }
1570
- const target = filesByPath.get(resolved);
1571
- if (target) imports.push({ path: resolved, specifier, part: target.part });
1572
- }
1573
- }
1574
- const importedBy = [];
1575
- if (direction !== "imports") {
1576
- for (const candidate of manifest.indexes.imports.byFile) {
1577
- if (candidate.path === entry.relativePath) continue;
1578
- const edge = candidate.imports.some(
1579
- (specifier) => resolveSpecifier(candidate.path, specifier, resolver) === entry.relativePath
1580
- );
1581
- if (!edge) continue;
1582
- const source = filesByPath.get(candidate.path);
1583
- importedBy.push({ path: candidate.path, part: source?.part ?? "" });
1584
- }
1585
- }
1586
- const shownImports = imports.slice(0, limit);
1587
- const shownImportedBy = importedBy.slice(0, limit);
1588
- const lines = [
1589
- `${entry.relativePath} \u2014 ${importedBy.length} importer(s), ${imports.length} import(s), ${unresolved.length} outside the snapshot.`
1590
- ];
1591
- if (direction !== "imports") {
1592
- lines.push("", "Imported by:");
1593
- if (shownImportedBy.length === 0) lines.push(" (nothing in the snapshot imports it)");
1594
- for (const item of shownImportedBy) lines.push(` ${item.path} [${item.part}]`);
1595
- if (importedBy.length > shownImportedBy.length) {
1596
- lines.push(` \u2026 ${importedBy.length - shownImportedBy.length} more; raise \`limit\`.`);
1597
- }
1598
- }
1599
- if (direction !== "imported-by") {
1600
- lines.push("", "Imports:");
1601
- if (shownImports.length === 0) lines.push(" (none recorded for this file)");
1602
- for (const item of shownImports) {
1603
- lines.push(` ${item.path} (from "${item.specifier}") [${item.part}]`);
1604
- }
1605
- if (imports.length > shownImports.length) {
1606
- lines.push(` \u2026 ${imports.length - shownImports.length} more; raise \`limit\`.`);
1607
- }
1608
- if (unresolved.length > 0) {
1609
- lines.push("", `Outside the snapshot (${unresolved.length}): ${unresolved.join(", ")}`);
1610
- }
1611
- }
1612
- return {
1613
- text: lines.join("\n"),
1614
- structured: {
1615
- path: entry.relativePath,
1616
- imports: shownImports,
1617
- importedBy: shownImportedBy,
1618
- unresolved
1619
- }
1620
- };
1621
- }
1622
- };
1623
- var readTool = {
1624
- name: "snapshot_read",
1625
- title: "Read a file from the snapshot",
1626
- description: "Return a line window of one file as the snapshot contains it: redacted, and bounded to a preview when the source is large. Reports the next `fromLine` when more remains.",
1627
- inputSchema: {
1628
- type: "object",
1629
- properties: {
1630
- path: {
1631
- type: "string",
1632
- description: "File path relative to the repository root, as snapshot_locate reports it."
1633
- },
1634
- fromLine: {
1635
- type: "integer",
1636
- minimum: 1,
1637
- default: 1,
1638
- description: "First line to return, 1-based."
1639
- },
1640
- lines: {
1641
- type: "integer",
1642
- minimum: 1,
1643
- maximum: 2e3,
1644
- default: 200,
1645
- description: "How many lines to return."
1646
- },
1647
- root: ROOT_PROPERTY,
1648
- outDir: OUT_DIR_PROPERTY
1649
- },
1650
- required: ["path"],
1651
- additionalProperties: false
1652
- },
1653
- outputSchema: {
1654
- type: "object",
1655
- properties: {
1656
- path: { type: "string" },
1657
- part: { type: "string" },
1658
- fromLine: { type: "integer" },
1659
- returnedLines: { type: "integer" },
1660
- totalLines: { type: "integer" },
1661
- nextFromLine: { type: "integer" },
1662
- pageable: { type: "boolean" },
1663
- reason: { type: "string" }
1664
- }
1665
- },
1666
- annotations: READ_ONLY,
1667
- async handler(args, context) {
1668
- const prepared = await prepare(args, context, outDirOverride(args));
1669
- if (!prepared.ok) return prepared.outcome;
1670
- const workspace = prepared.workspace;
1671
- if (typeof args.path !== "string") return failure('"path" must be a string.');
1672
- const relativePath = toRelativePath(workspace.root, args.path);
1673
- if (!relativePath) {
1674
- return failure(
1675
- `"${args.path}" is outside ${workspace.root}. Paths are read relative to the repository root.`
1676
- );
1677
- }
1678
- const read = readManifest(workspace);
1679
- if (!read.ok) return failure(read.message);
1680
- const manifest = read.manifest;
1681
- const entry = manifest.files.find((file) => file.relativePath === relativePath) ?? manifest.files.find((file) => file.relativePath.toLowerCase() === relativePath.toLowerCase());
1682
- if (!entry) {
1683
- const skipped = manifest.skipped.find((record) => record.path === relativePath);
1684
- if (skipped) {
1685
- const detail = skipped.detail ? ` (${skipped.detail})` : "";
1686
- return failure(
1687
- `${relativePath} is not in the snapshot: ${skipped.reason}${detail}. Sensitive and ignored files stay out unless they are included explicitly.`
1688
- );
1689
- }
1690
- return failure(
1691
- `${relativePath} is not in the snapshot. Call snapshot_locate to find the path, or snapshot_explain to learn why it was excluded.`
1692
- );
1693
- }
1694
- const partPath = partPathFor(workspace, entry.part);
1695
- if (partPath === null) {
1696
- return failure(
1697
- `${entry.part} is not a part of this snapshot: its name leaves ${workspace.config.outDir}/parts. Run snapshot_generate to rebuild it.`
1698
- );
1699
- }
1700
- let partText;
1701
- try {
1702
- partText = fs2.readFileSync(partPath, "utf8");
1703
- } catch {
1704
- return failure(
1705
- `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
1706
- );
1707
- }
1708
- const section = findSection(parsePartSections(partText), entry.relativePath);
1709
- if (!section) {
1710
- return failure(
1711
- `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
1712
- );
1713
- }
1714
- const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
1715
- const lineCount = typeof args.lines === "number" ? args.lines : 200;
1716
- const window = windowText(section.body, fromLine, lineCount);
1717
- let body = window.text;
1718
- let truncatedByBytes = false;
1719
- let clippedInsideLine = false;
1720
- if (Buffer.byteLength(body, "utf8") > MAX_RESULT_BYTES) {
1721
- const clipped = truncateToBytes(body, MAX_RESULT_BYTES);
1722
- const lastBreak = clipped.content.lastIndexOf("\n");
1723
- if (lastBreak > 0) {
1724
- body = clipped.content.slice(0, lastBreak);
1725
- } else {
1726
- body = clipped.content;
1727
- clippedInsideLine = true;
1728
- }
1729
- truncatedByBytes = true;
1730
- }
1731
- const returnedLines = body.length === 0 ? 0 : body.split("\n").length;
1732
- const moreRemain = !clippedInsideLine && !window.pastEnd && (window.truncated || truncatedByBytes);
1733
- const header = [
1734
- `${entry.relativePath} \u2014 ${entry.part}, ${entry.layer}/${entry.kind}, ${entry.language}`,
1735
- // The line range is the answer to "where am I in this file", and it is computed from the
1736
- // body the window was taken from, so it is just as meaningful for a preview as for a full
1737
- // file. It used to be replaced — not augmented — by the preview note, so a 40-line window
1738
- // into a 300-line preview came back with no range at all and the caller could not tell
1739
- // where the window ended. Both facts are stated now, and `signatures` is no longer
1740
- // silently treated as a full file.
1741
- ...section.inclusion === "preview" ? [
1742
- "Bounded preview: the snapshot holds this file's head and tail only, so these line numbers count the preview, not the source."
1743
- ] : section.inclusion === "signatures" ? [
1744
- "Signatures: function and method bodies were replaced with `{ /* ... */ }` when the snapshot was generated."
1745
- ] : [],
1746
- window.totalLines === 0 ? "This file is empty." : window.pastEnd ? `This file has ${window.totalLines} line(s); fromLine=${window.fromLine} is past its end.` : clippedInsideLine ? `Line ${window.fromLine} of ${window.totalLines}: this line is longer than one result can carry, so this page ends mid-line.` : `Lines ${window.fromLine}\u2013${window.fromLine + returnedLines - 1} of ${window.totalLines}.`
1747
- ];
1748
- const lines = [...header, "", body];
1749
- if (moreRemain) {
1750
- const next = window.fromLine + returnedLines;
1751
- lines.push("", `Truncated. Call snapshot_read with fromLine=${next} for the rest.`);
1752
- } else if (clippedInsideLine) {
1753
- lines.push(
1754
- "",
1755
- "Truncated. The remainder of this line is not reachable through snapshot_read; read the file from disk to see it."
1756
- );
1757
- }
1758
- return {
1759
- text: lines.join("\n"),
1760
- structured: {
1761
- path: entry.relativePath,
1762
- part: entry.part,
1763
- // The window itself: a caller that wants to measure or re-send what it received should
1764
- // not have to strip the header and the paging note back off `text`.
1765
- body,
1766
- layer: entry.layer,
1767
- kind: entry.kind,
1768
- language: entry.language,
1769
- inclusion: section.inclusion ?? entry.inclusionMode,
1770
- fromLine: window.fromLine,
1771
- returnedLines,
1772
- totalLines: window.totalLines,
1773
- truncated: moreRemain || clippedInsideLine,
1774
- pageable: !clippedInsideLine,
1775
- ...clippedInsideLine ? { reason: "line exceeds the result limit; its remainder is not reachable by fromLine" } : {},
1776
- nextFromLine: moreRemain ? window.fromLine + returnedLines : null,
1777
- sha256: entry.hashSha256
1778
- }
1779
- };
1780
- }
1781
- };
1782
- var explainTool = {
1783
- name: "snapshot_explain",
1784
- title: "Explain one path",
1785
- description: 'Explain how the next snapshot would treat one path: its layer, kind, language and part, or the exact reason it is excluded. Answers "why is this file missing".',
1786
- inputSchema: {
1787
- type: "object",
1788
- properties: {
1789
- path: {
1790
- type: "string",
1791
- description: "Path relative to the repository root. Directories are explained as a whole."
1792
- },
1793
- root: ROOT_PROPERTY,
1794
- outDir: OUT_DIR_PROPERTY,
1795
- ...SCOPE_PROPERTIES
1796
- },
1797
- required: ["path"],
1798
- additionalProperties: false
1799
- },
1800
- outputSchema: {
1801
- type: "object",
1802
- properties: {
1803
- path: { type: "string" },
1804
- included: { type: "boolean" },
1805
- reason: { type: "string" }
1806
- }
1807
- },
1808
- annotations: READ_ONLY,
1809
- async handler(args, context) {
1810
- const prepared = await prepare(args, context, workspaceOverrides(args));
1811
- if (!prepared.ok) return prepared.outcome;
1812
- const workspace = prepared.workspace;
1813
- if (typeof args.path !== "string") return failure('"path" must be a string.');
1814
- const relativePath = toRelativePath(workspace.root, args.path);
1815
- if (!relativePath) {
1816
- return failure(`"${args.path}" is outside ${workspace.root}.`);
1817
- }
1818
- let result;
1819
- try {
1820
- result = explainPath(workspace.config, relativePath);
1821
- } catch (error) {
1822
- return failure(error instanceof Error ? error.message : String(error));
1823
- }
1824
- return {
1825
- text: renderExplainText(result),
1826
- structured: {
1827
- path: result.path,
1828
- included: result.included,
1829
- ...result.reason ? { reason: result.reason } : {},
1830
- ...result.detail ? { detail: result.detail } : {},
1831
- ...result.layer ? { layer: result.layer } : {},
1832
- ...result.kind ? { kind: result.kind } : {},
1833
- ...result.language ? { language: result.language } : {},
1834
- ...result.part ? { part: result.part } : {},
1835
- ...result.inclusionMode ? { inclusion: result.inclusionMode } : {},
1836
- ...typeof result.lines === "number" ? { lines: result.lines } : {},
1837
- ...typeof result.bytes === "number" ? { bytes: result.bytes } : {},
1838
- ...typeof result.secretCount === "number" ? { secretCount: result.secretCount } : {}
1839
- }
1840
- };
1841
- }
1842
- };
1843
- function buildTools() {
1844
- return [
1845
- statusTool,
1846
- healthTool,
1847
- planTool,
1848
- generateTool,
1849
- validateTool,
1850
- locateTool,
1851
- dependentsTool,
1852
- readTool,
1853
- explainTool
1854
- ];
1855
- }
1856
-
1857
- // src/mcp/prompts.ts
1858
- var ORIENT = `You have a codebase-snapshot server for this repository. Build a map of it before reading any code.
1859
-
1860
- 1. Call snapshot_status. If no snapshot exists, call snapshot_plan to preview it, then snapshot_generate.
1861
- 2. Call snapshot_locate for the areas that matter. Search by exported symbol, route or path fragment rather than guessing filenames.
1862
- 3. Report back: the layers present, the entry points, and the files that matter here \u2014 cited as paths with their part.
1863
- 4. Read one file at a time with snapshot_read, one window at a time. Do not read a part end to end.`;
1864
- var KEEP_CURRENT = `Keep the context you were given provably current while you work.
1865
-
1866
- 1. Before relying on a snapshot from an earlier session, call snapshot_validate.
1867
- 2. If it reports drift, call snapshot_generate once, then snapshot_validate again.
1868
- 3. After changes you make, call snapshot_validate and report what it said.
1869
- 4. Never call a snapshot current unless snapshot_validate said so in this session.`;
1870
- function withFocus(base, focus) {
1871
- return typeof focus === "string" && focus.trim().length > 0 ? `${base}
1872
-
1873
- Focus for this pass: ${focus.trim()}` : base;
1874
- }
1875
- function buildPrompts() {
1876
- return [
1877
- {
1878
- name: "orient",
1879
- title: "Orient in this repository",
1880
- description: "Map the repository from the snapshot before reading any of it.",
1881
- arguments: [
1882
- {
1883
- name: "focus",
1884
- description: 'Optional area to concentrate on, for example "authentication".',
1885
- required: false
1886
- }
1887
- ],
1888
- build(args) {
1889
- return {
1890
- description: "Map the repository before reading it.",
1891
- messages: [{ role: "user", content: { type: "text", text: withFocus(ORIENT, args.focus) } }]
1892
- };
1893
- }
1894
- },
1895
- {
1896
- name: "keep-current",
1897
- title: "Keep the snapshot current",
1898
- description: "Validate before trusting earlier context, and again after making changes.",
1899
- arguments: [],
1900
- build() {
1901
- return {
1902
- description: "Keep the context current.",
1903
- messages: [{ role: "user", content: { type: "text", text: KEEP_CURRENT } }]
1904
- };
1905
- }
1906
- }
1907
- ];
1908
- }
1909
-
1910
- // src/mcp/uris.ts
1911
- var STATIC_RESOURCE_URIS = [
1912
- "snapshot://manifest",
1913
- "snapshot://contract",
1914
- "snapshot://skill",
1915
- "snapshot://prompt",
1916
- "snapshot://reports/audit",
1917
- "snapshot://reports/tree",
1918
- "snapshot://reports/navigation"
1919
- ];
1920
- var RESOURCE_TEMPLATE_URIS = ["snapshot://parts/{index}"];
1921
-
1922
- // src/agent/option-scope.ts
1923
- var VALIDATE_OPTIONS = [
1924
- "sarif",
1925
- "skeleton",
1926
- "changed-since",
1927
- "staged",
1928
- "with-dependents",
1929
- "cwd",
1930
- "out-dir",
1931
- "max-part-bytes",
1932
- "max-part-tokens",
1933
- "large-file-bytes",
1934
- "max-monolith-bytes",
1935
- "max-parts",
1936
- "brief",
1937
- "prompt-task",
1938
- "include-monolith",
1939
- "include-sensitive-files",
1940
- "skip-artifacts",
1941
- "only-artifacts",
1942
- "no-config",
1943
- "discovery",
1944
- "format",
1945
- "no-update-check",
1946
- "mode",
1947
- "help",
1948
- "version"
1949
- ];
1950
- var COMMAND_OPTION_SCOPE = {
1951
- generate: [
1952
- "sarif",
1953
- "skeleton",
1954
- "changed-since",
1955
- "staged",
1956
- "with-dependents",
1957
- "cwd",
1958
- "out-dir",
1959
- "max-part-bytes",
1960
- "max-part-tokens",
1961
- "large-file-bytes",
1962
- "max-monolith-bytes",
1963
- "attachment-slots",
1964
- "max-parts",
1965
- "brief",
1966
- "prompt-task",
1967
- "include-monolith",
1968
- "include-sensitive-files",
1969
- "skip-artifacts",
1970
- "only-artifacts",
1971
- "no-config",
1972
- "discovery",
1973
- "format",
1974
- "mode",
1975
- "dry-run",
1976
- "watch",
1977
- "autopilot",
1978
- "no-install",
1979
- "no-update-check",
1980
- "help",
1981
- "version"
1982
- ],
1983
- // The health audit resolves the config only to find the output directory; --strict decides the
1984
- // exit code, and every other setting would be a promise the command does not keep.
1985
- health: ["cwd", "out-dir", "format", "strict", "no-update-check", "help"],
1986
- validate: VALIDATE_OPTIONS,
1987
- // `report` reads `manifest.json` and prints what is there; a generation setting would change
1988
- // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
1989
- // — the exact "flag that parses but changes nothing" this table exists to prevent — while
1990
- // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
1991
- // list, so removing them narrows the two together.
1992
- report: [
1993
- "cwd",
1994
- "out-dir",
1995
- "no-config",
1996
- "no-update-check",
1997
- "format",
1998
- "mode",
1999
- "help",
2000
- "version"
2001
- ],
2002
- explain: [
2003
- // The scope decides what `explain` says about a file, dependents included: without these,
2004
- // a file that is in the snapshot only because it imports a changed one was explained as
2005
- // `included: false, reason: "unchanged"`.
2006
- "changed-since",
2007
- "staged",
2008
- "with-dependents",
2009
- "cwd",
2010
- "out-dir",
2011
- // `--large-file-bytes` changes the inclusion mode `explain` reports, so it belongs here.
2012
- // `--max-part-bytes`, `--max-monolith-bytes`, `--include-monolith`, `--skip-artifacts` and
2013
- // `--only-artifacts` were accepted and never read: a per-file answer cannot depend on how the
2014
- // whole snapshot is partitioned, and none of them changes whether this file is included.
2015
- // Removed rather than implemented, because a flag that parses and does nothing is the defect
2016
- // this table exists to prevent.
2017
- "large-file-bytes",
2018
- "include-sensitive-files",
2019
- "no-config",
2020
- "discovery",
2021
- "no-update-check",
2022
- "format",
2023
- "mode",
2024
- "help",
2025
- "version"
2026
- ],
2027
- diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
2028
- describe: ["format", "mode", "help", "version"],
2029
- init: [
2030
- "install-hook",
2031
- "cwd",
2032
- "out-dir",
2033
- "max-part-bytes",
2034
- "include-sensitive-files",
2035
- "skip-artifacts",
2036
- "only-artifacts",
2037
- "preset",
2038
- "include",
2039
- "exclude",
2040
- "yes",
2041
- "force",
2042
- "dry-run",
2043
- "no-update-check",
2044
- "format",
2045
- "mode",
2046
- "help",
2047
- "version"
2048
- ],
2049
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
2050
- // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
2051
- // messages, and there is no second shape to choose, so offering the flag would be a lie.
2052
- mcp: ["cwd", "mode", "help", "version"],
2053
- // `setup` generates through the `generate` command, so every generation setting it can
2054
- // honour is in scope. Rejecting them made the one-command path unable to express a walk
2055
- // scan, a monolith or a different large-file threshold; the alternative was to run
2056
- // `setup` and then edit the config it had just written.
2057
- setup: [
2058
- "install-hook",
2059
- "cwd",
2060
- "out-dir",
2061
- "max-part-bytes",
2062
- // Persisted into the config `setup` writes, then forwarded to the generation it runs — so
2063
- // the snapshot it produces validates against the config beside it. Accepting a setting here
2064
- // without writing it down made `setup --large-file-bytes 100k` finish with a snapshot its
2065
- // own `validate` called drifted, on the first run of a brand-new project.
2066
- "max-part-tokens",
2067
- "skeleton",
2068
- "sarif",
2069
- "large-file-bytes",
2070
- "max-monolith-bytes",
2071
- "include-monolith",
2072
- "include-sensitive-files",
2073
- "skip-artifacts",
2074
- "only-artifacts",
2075
- "discovery",
2076
- "preset",
2077
- "include",
2078
- "exclude",
2079
- "yes",
2080
- "force",
2081
- "no-install",
2082
- "dry-run",
2083
- "no-update-check",
2084
- "format",
2085
- "mode",
2086
- "help",
2087
- "version"
2088
- ]
2089
- };
2090
- var COMMAND_ORDER = [
2091
- "generate",
2092
- "validate",
2093
- "health",
2094
- "report",
2095
- "explain",
2096
- "init",
2097
- "setup",
2098
- "diff",
2099
- "describe",
2100
- "skill",
2101
- "mcp"
2102
- ];
2103
- function commandsForOption(option) {
2104
- return COMMAND_ORDER.filter((command) => COMMAND_OPTION_SCOPE[command].includes(option));
2105
- }
2106
- function optionAppliesTo(option) {
2107
- return commandsForOption(option).join("/");
2108
- }
2109
-
2110
- // src/agent/contract.ts
2111
- var CONTRACT_VERSION = "1.0.0";
2112
- var PACKAGE_NAME = "codebase-snapshot";
2113
- var MAJOR_VERSION = GENERATOR_VERSION.split(".")[0];
2114
- var ARTIFACT_SUMMARY = {
2115
- readme: "README.md describing the snapshot at the output root.",
2116
- prompt: "PROMPT.md: the instruction sheet to paste with the snapshot, rendered from its manifest.",
2117
- manifest: "manifest.json: machine-readable index of every file, part, hash and config.",
2118
- parts: "parts/*.md: the packed, budget-limited markdown parts that carry the code.",
2119
- navigation: "reports/navigation.md: links between parts and layers.",
2120
- projectTree: "reports/project-tree.md: the directory tree of included files.",
2121
- audit: "reports/audit.md: secret findings, large files, parse diagnostics, git state.",
2122
- monolith: "full-codebase.json and full-codebase.md: the whole repository in one file (off by default)."
2123
- };
2124
- var ARTIFACT_DEFAULTS = {
2125
- readme: true,
2126
- prompt: true,
2127
- manifest: true,
2128
- parts: true,
2129
- navigation: true,
2130
- projectTree: true,
2131
- audit: true,
2132
- monolith: false
2133
- };
2134
- function renderContractText(contract) {
2135
- const lines = [];
2136
- lines.push(`${contract.package} v${contract.version}`);
2137
- lines.push(contract.summary);
2138
- lines.push("");
2139
- lines.push(`Node : ${contract.requires.node}`);
2140
- lines.push(`Schema : ${contract.schemaVersion} (contract ${contract.contractVersion})`);
2141
- lines.push(`One-shot : ${contract.invocation.oneShot} <command>`);
2142
- lines.push(`Installed : ${contract.invocation.installed} <command>`);
2143
- lines.push("");
2144
- lines.push("Workflow:");
2145
- for (const step of contract.workflow) {
2146
- lines.push(` ${step.step}. ${step.id}`);
2147
- lines.push(` run : ${step.run}`);
2148
- lines.push(` expect : ${step.expect}`);
2149
- if (step.notes) lines.push(` note : ${step.notes}`);
2150
- }
2151
- lines.push("");
2152
- lines.push("Commands:");
2153
- for (const command of contract.commands) {
2154
- const args = command.positionals.length > 0 ? ` ${command.positionals.join(" ")}` : "";
2155
- lines.push(` ${(command.name + args).padEnd(26)} ${command.summary}`);
2156
- }
2157
- lines.push("");
2158
- lines.push("Exit codes:");
2159
- for (const [code, meaning] of Object.entries(contract.exitCodes)) {
2160
- lines.push(` ${code} ${meaning}`);
2161
- }
2162
- lines.push("");
2163
- lines.push(`Presets (${contract.presets.length}): ${contract.presets.map((p) => p.name).join(", ")}`);
2164
- lines.push("");
2165
- lines.push("Artifacts:");
2166
- for (const artifact of contract.artifacts) {
2167
- lines.push(` ${artifact.name.padEnd(12)} ${artifact.default ? "on " : "off"} ${artifact.summary}`);
2168
- }
2169
- lines.push("");
2170
- lines.push("Options:");
2171
- for (const option of contract.options) {
2172
- const fallback = option.default === void 0 ? "" : ` [${JSON.stringify(option.default)}]`;
2173
- lines.push(` ${option.flag.padEnd(24)} ${option.appliesTo.padEnd(32)}${fallback}`);
2174
- lines.push(` ${"".padEnd(24)} ${option.summary}`);
2175
- }
2176
- lines.push("");
2177
- lines.push("MCP:");
2178
- lines.push(` command ${contract.mcp.command}`);
2179
- lines.push(` transport ${contract.mcp.transport}`);
2180
- lines.push(
2181
- ` versions modern ${contract.mcp.protocolVersions.modern.join(", ")} / legacy ${contract.mcp.protocolVersions.legacy.join(", ")}`
2182
- );
2183
- lines.push(
2184
- ` tools ${contract.mcp.tools.map((tool) => tool.readOnly ? tool.name : `${tool.name} (writes)`).join(", ")}`
2185
- );
2186
- lines.push(` prompts ${contract.mcp.prompts.map((prompt) => prompt.name).join(", ")}`);
2187
- lines.push(` resources ${contract.mcp.resources.join(", ")}`);
2188
- lines.push(` templates ${contract.mcp.resourceTemplates.join(", ")}`);
2189
- lines.push("");
2190
- lines.push("Safety:");
2191
- for (const note of contract.safety) lines.push(` - ${note}`);
2192
- lines.push("");
2193
- lines.push("Troubleshooting:");
2194
- for (const item of contract.troubleshooting) {
2195
- lines.push(` ${item.symptom}`);
2196
- lines.push(` cause: ${item.cause}`);
2197
- lines.push(` fix : ${item.fix}`);
2198
- }
2199
- lines.push("");
2200
- lines.push("This is the human rendering. Agents should use: describe --format json");
2201
- return lines.join("\n");
2202
- }
2203
- function buildAgentContract() {
2204
- return {
2205
- generator: GENERATOR_NAME,
2206
- package: PACKAGE_NAME,
2207
- version: GENERATOR_VERSION,
2208
- schemaVersion: SCHEMA_VERSION,
2209
- contractVersion: CONTRACT_VERSION,
2210
- 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).",
2211
- requires: { node: ">=18.0.0", dependencies: ["typescript"] },
2212
- invocation: {
2213
- oneShot: `npx ${PACKAGE_NAME}@latest`,
2214
- installed: "npx codebase-snapshot",
2215
- bins: ["codebase-snapshot", "snapshot"],
2216
- notes: [
2217
- `The bare package name also works: npx ${PACKAGE_NAME} <command>.`,
2218
- "`codebase-snapshot` is the canonical name and the one to script against. `snapshot` is the short alias a global install provides; in a project that has the package installed, `npx snapshot` resolves the local bin first.",
2219
- `Pin an exact version \u2014 for example \`npx ${PACKAGE_NAME}@${GENERATOR_VERSION} --version\` \u2014 when you need the same build on every machine. A major range is not enough before 1.0: npm's caret on a 0.x version pins the minor, and 0.x minors are breaking by convention.`,
2220
- "Both bin names point at the same file. npm resolves a package by its bin entries, so they must stay aliases of one executable.",
2221
- "A bare run in a project with no configuration asks once, sets the project up and generates \u2014 but only at a terminal. With no TTY it exits 2 and names the alternatives, so an unattended caller must say what it wants: `generate` after `init --yes`, or `--autopilot`.",
2222
- "Human progress goes to stderr. With --format json the payload on stdout is pure JSON.",
2223
- "A failing run also writes pure JSON to stdout: { error: { message, exitCode } }. The exit code and the stderr line are unchanged."
2224
- ]
2225
- },
2226
- workflow: [
2227
- {
2228
- step: 1,
2229
- id: "verify",
2230
- run: `npx ${PACKAGE_NAME}@latest --version`,
2231
- // The requirement is the major version; the exact build is context. A
2232
- // floating tag may print a different patch today than next week, and an agent
2233
- // must not conclude that a working tool is broken because of a patch.
2234
- expect: `prints v${MAJOR_VERSION} or newer on stdout and exits 0 (this build is v${GENERATOR_VERSION}: compare the major version, not the patch)`,
2235
- notes: `If it prints an older major than this contract's, the @latest tag is behind the release: pin the exact version with \`npx ${PACKAGE_NAME}@${GENERATOR_VERSION} --version\` instead of retrying @latest. If it prints nothing, clear the npm cache and retry, or use \`npx -p <pkg> codebase-snapshot\`.`
2236
- },
2237
- {
2238
- step: 2,
2239
- id: "understand",
2240
- run: `npx ${PACKAGE_NAME}@latest describe --format json`,
2241
- expect: "the full contract as JSON: commands, options, presets, exit codes",
2242
- notes: "Read this before acting if you have no prior knowledge of the tool."
2243
- },
2244
- {
2245
- step: 3,
2246
- id: "configure",
2247
- run: `npx ${PACKAGE_NAME}@latest init --yes`,
2248
- expect: 'writes a commented config file listing every setting at its current value: snapshot.config.ts only when the running Node can strip types (>= 22.6) and the project is an ES module (`"type": "module"` in package.json); snapshot.config.mjs otherwise',
2249
- notes: "Non-interactive. The detected preset is chosen automatically; override with --preset <name>. Skip this step to run on built-in defaults."
2250
- },
2251
- {
2252
- step: 4,
2253
- id: "generate",
2254
- run: `npx ${PACKAGE_NAME}@latest generate`,
2255
- expect: "exit 0, and ./snapshot/ written with parts, reports and manifest.json"
2256
- },
2257
- {
2258
- step: 5,
2259
- id: "verify-output",
2260
- run: `npx ${PACKAGE_NAME}@latest validate`,
2261
- expect: "exit 0 means the snapshot matches the files on disk",
2262
- notes: "Exit 1 means drift or a damaged snapshot; re-run generate."
2263
- },
2264
- {
2265
- step: 6,
2266
- id: "consume",
2267
- run: "read ./snapshot/PROMPT.md first, then ./snapshot/parts/*.md, ./snapshot/manifest.json and ./snapshot/reports/audit.md",
2268
- expect: "the code, the index of what was included, and the risk findings",
2269
- 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."
2270
- }
2271
- ],
2272
- commands: [
2273
- {
2274
- name: "generate",
2275
- aliases: ["default"],
2276
- summary: "Write the snapshot. This is the command you normally want. In a project with no configuration, a terminal asks once and sets the project up first; without a terminal it exits 2 and names `--autopilot` and `init --yes`.",
2277
- positionals: [],
2278
- exits: [0, 1, 2]
2279
- },
2280
- {
2281
- name: "validate",
2282
- aliases: ["check"],
2283
- summary: "Compare the snapshot on disk with the repository; exit 1 on drift. `check` is an alias of `validate`.",
2284
- positionals: [],
2285
- exits: [0, 1]
2286
- },
2287
- {
2288
- name: "health",
2289
- aliases: [],
2290
- summary: "Audit a generated snapshot against the repository it describes: manifest shape, part hashes, artifact claims, unmasked secrets in any artifact, values from excluded sensitive files, host paths, the recorded token count and freshness. Exits 0 clean, 1 when a check fails, 2 with --strict when a critical check fails.",
2291
- positionals: [],
2292
- exits: [0, 1, 2]
2293
- },
2294
- {
2295
- name: "report",
2296
- aliases: [],
2297
- summary: "Print snapshot health, layer metrics and the secret audit.",
2298
- positionals: [],
2299
- exits: [0, 1]
2300
- },
2301
- {
2302
- name: "setup",
2303
- aliases: [],
2304
- summary: "Everything a repository needs in one command, with defaults: write the config when there is none (an existing one is kept), add the npm scripts, devDependency and .gitignore entries, install dependencies with the project's package manager, then generate the snapshot. --no-install skips the install; --dry-run writes nothing.",
2305
- positionals: [],
2306
- exits: [0, 1, 2]
2307
- },
2308
- {
2309
- name: "init",
2310
- aliases: [],
2311
- summary: "Write a commented config file (snapshot.config.ts only when Node can strip types and the project is an ES module; snapshot.config.mjs otherwise), add the snapshot scripts and the devDependency, ignore the snapshot directories, and write a BRIEF.md scaffold for the owner half of PROMPT.md. No agent file is written. Interactive, or --yes for CI.",
2312
- positionals: [],
2313
- exits: [0, 1, 2]
2314
- },
2315
- {
2316
- name: "explain",
2317
- aliases: [],
2318
- summary: "Explain how one path would be treated: layer, kind, part, skip reason. Always exits 0 when it can report; read `included` and `reason` instead of the exit code.",
2319
- positionals: ["<path>"],
2320
- exits: [0]
2321
- },
2322
- {
2323
- name: "diff",
2324
- aliases: [],
2325
- summary: "Compare two snapshots (directories or manifest.json files).",
2326
- positionals: ["<before>", "<after>"],
2327
- exits: [0, 1]
2328
- },
2329
- {
2330
- name: "describe",
2331
- aliases: [],
2332
- summary: "Print this contract. --format json for machines, text for humans.",
2333
- positionals: [],
2334
- exits: [0]
2335
- },
2336
- {
2337
- name: "skill",
2338
- aliases: [],
2339
- summary: "Print the agent skill, or --install it into the tool registries this repository's agent reads (.claude/skills, .cursor/rules). Files it creates are added to .gitignore. It never writes AGENTS.md: that file belongs to the repository.",
2340
- positionals: [],
2341
- exits: [0, 1, 2]
2342
- },
2343
- {
2344
- name: "mcp",
2345
- aliases: [],
2346
- summary: "Serve this repository to an MCP client over stdio. The tools, resources and protocol versions it offers are listed in this contract's `mcp` block.",
2347
- positionals: [],
2348
- exits: [0, 2]
2349
- }
2350
- ],
2351
- exitCodes: {
2352
- "0": "success (and validate: no drift)",
2353
- "1": "drift detected, or generation refused/failed (nothing was written)",
2354
- "2": "usage error: unknown flag/command, bad value, wrong argument count"
2355
- },
2356
- options: [
2357
- {
2358
- flag: "--out-dir",
2359
- type: "string",
2360
- default: "snapshot",
2361
- appliesTo: optionAppliesTo("out-dir"),
2362
- summary: "Where the snapshot is written. Must not be the repo root or a directory the tool did not create."
2363
- },
2364
- {
2365
- flag: "--max-part-bytes",
2366
- type: "string",
2367
- default: 307200,
2368
- appliesTo: optionAppliesTo("max-part-bytes"),
2369
- summary: 'Byte budget per markdown part. Accepts "120k" / "1.5mb". Minimum 4096.'
2370
- },
2371
- {
2372
- flag: "--max-part-tokens",
2373
- type: "string",
2374
- default: "unset",
2375
- appliesTo: optionAppliesTo("max-part-tokens"),
2376
- summary: "Ceiling on a part expressed in tokens. Converted to bytes at 4 bytes/token and enforced as that byte ceiling \u2014 the estimate in manifest.parts[].estimatedTokens is not a hard bound, and a warning names any part whose estimate exceeds it. Minimum 1024."
2377
- },
2378
- {
2379
- flag: "--large-file-bytes",
2380
- type: "string",
2381
- default: 307200,
2382
- appliesTo: optionAppliesTo("large-file-bytes"),
2383
- summary: "Above this size a file gets a head/tail preview instead of the full body. It defaults to maxPartBytes and may not exceed it: a file between the two could not fit a part."
2384
- },
2385
- {
2386
- flag: "--max-monolith-bytes",
2387
- type: "string",
2388
- default: "unset",
2389
- appliesTo: optionAppliesTo("max-monolith-bytes"),
2390
- summary: "Skip the monolith artifacts when they would exceed this size."
2391
- },
2392
- {
2393
- flag: "--include-monolith",
2394
- type: "boolean",
2395
- default: false,
2396
- appliesTo: optionAppliesTo("include-monolith"),
2397
- summary: "Also write full-codebase.json and full-codebase.md."
2398
- },
2399
- {
2400
- flag: "--include-sensitive-files",
2401
- type: "boolean",
2402
- default: false,
2403
- appliesTo: optionAppliesTo("include-sensitive-files"),
2404
- summary: "Also emit .env / *.pem / .npmrc style files. Off by default; they are recorded as skipped."
2405
- },
2406
- {
2407
- flag: "--discovery",
2408
- type: "string",
2409
- default: "auto",
2410
- appliesTo: optionAppliesTo("discovery"),
2411
- 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)."
2412
- },
2413
- {
2414
- flag: "--attachment-slots",
2415
- type: "number",
2416
- default: "10",
2417
- appliesTo: optionAppliesTo("attachment-slots"),
2418
- 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."
2419
- },
2420
- {
2421
- flag: "--brief",
2422
- type: "string",
2423
- default: "unset",
2424
- appliesTo: optionAppliesTo("brief"),
2425
- summary: "Path to the owner-written half of PROMPT.md: Stakes, The system, What came before, The bar and Calibration replace or extend the generated prose; any other heading is kept as Owner notes. The measured headings cannot be redefined; fenced code is content, not headings. The file is capped at 64 KiB. A missing file is an error and an edited file is config drift."
2426
- },
2427
- {
2428
- flag: "--prompt-task",
2429
- type: "string",
2430
- default: "audit",
2431
- appliesTo: optionAppliesTo("prompt-task"),
2432
- summary: "Which job the brief is written for: audit (default), review or explain. It changes the opening section, not the standard."
2433
- },
2434
- {
2435
- flag: "--max-parts",
2436
- type: "number",
2437
- default: "unset",
2438
- appliesTo: optionAppliesTo("max-parts"),
2439
- 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."
2440
- },
2441
- {
2442
- flag: "--skip-artifacts",
2443
- type: "string",
2444
- default: "unset",
2445
- appliesTo: optionAppliesTo("skip-artifacts"),
2446
- summary: "Comma-separated artifacts to omit (readme, manifest, parts, navigation, projectTree, audit, monolith)."
2447
- },
2448
- {
2449
- flag: "--only-artifacts",
2450
- type: "string",
2451
- default: "unset",
2452
- appliesTo: optionAppliesTo("only-artifacts"),
2453
- summary: "Write only these artifacts. Cannot be combined with --skip-artifacts."
2454
- },
2455
- {
2456
- flag: "--skeleton",
2457
- type: "boolean",
2458
- default: false,
2459
- appliesTo: optionAppliesTo("skeleton"),
2460
- summary: 'Replace function and method bodies with `{ /* ... */ }` in JS, JSX, TS and TSX files (including .mjs/.cjs; .d.ts files have nothing to collapse), keeping signatures and comments. The part records inclusionMode "signatures" for each file it touched.'
2461
- },
2462
- {
2463
- flag: "--sarif",
2464
- type: "boolean",
2465
- default: false,
2466
- appliesTo: optionAppliesTo("sarif"),
2467
- summary: "Also write reports/audit.sarif (SARIF 2.1.0) so a CI security gate can read the redaction findings. The matched value is never included."
2468
- },
2469
- {
2470
- flag: "--strict",
2471
- type: "boolean",
2472
- default: false,
2473
- appliesTo: optionAppliesTo("strict"),
2474
- summary: "health only: exit 2 when a critical check fails, and 1 when a warning is the only thing left. Without it a critical check exits 1 and warnings exit 0."
2475
- },
2476
- {
2477
- flag: "--changed-since",
2478
- type: "string",
2479
- default: "unset",
2480
- appliesTo: optionAppliesTo("changed-since"),
2481
- summary: 'Snapshot only the files that differ from this git ref, plus untracked ones. Everything else is recorded in skipped[] with reason "unchanged". Requires a git checkout.'
2482
- },
2483
- {
2484
- flag: "--staged",
2485
- type: "boolean",
2486
- default: false,
2487
- appliesTo: optionAppliesTo("staged"),
2488
- summary: "Snapshot only the files staged in the index. The pre-commit counterpart of --changed-since."
2489
- },
2490
- {
2491
- flag: "--with-dependents",
2492
- type: "boolean",
2493
- default: false,
2494
- appliesTo: optionAppliesTo("with-dependents"),
2495
- summary: "Widen a changed-files scope by one hop: files that import a changed file are included too. Only meaningful with --changed-since or --staged."
2496
- },
2497
- {
2498
- flag: "--format",
2499
- type: "string",
2500
- default: "text",
2501
- // `optionAppliesTo` always returns the explicit slash list, so this is the same scoped form
2502
- // as every other option — no prose sentinel a machine consumer could misread.
2503
- appliesTo: optionAppliesTo("format"),
2504
- summary: 'Output format: "text" or "json". JSON goes to stdout, progress to stderr.'
2505
- },
2506
- {
2507
- flag: "--mode",
2508
- type: "string",
2509
- default: "generate",
2510
- appliesTo: optionAppliesTo("mode"),
2511
- summary: "Select the command when no command word is given. Values: generate, validate, check, report, init, setup, explain, diff, describe, skill, mcp. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
2512
- },
2513
- {
2514
- flag: "--cwd",
2515
- type: "string",
2516
- default: "process.cwd()",
2517
- appliesTo: optionAppliesTo("cwd"),
2518
- summary: "Repository to operate on. Must be an existing directory."
2519
- },
2520
- {
2521
- flag: "--dry-run",
2522
- type: "boolean",
2523
- default: false,
2524
- appliesTo: optionAppliesTo("dry-run"),
2525
- summary: "Compute everything and print the result without writing."
2526
- },
2527
- {
2528
- flag: "--watch",
2529
- type: "boolean",
2530
- default: false,
2531
- appliesTo: optionAppliesTo("watch"),
2532
- summary: "Regenerate on every change until interrupted."
2533
- },
2534
- {
2535
- flag: "--no-config",
2536
- type: "boolean",
2537
- default: false,
2538
- appliesTo: optionAppliesTo("no-config"),
2539
- summary: "Ignore the config file and run on the built-in defaults."
2540
- },
2541
- {
2542
- flag: "--preset",
2543
- type: "string",
2544
- default: "detected",
2545
- appliesTo: optionAppliesTo("preset"),
2546
- summary: "Force a project preset instead of detecting one. Unknown names are a usage error."
2547
- },
2548
- {
2549
- flag: "--include",
2550
- type: "string",
2551
- default: "unset",
2552
- appliesTo: optionAppliesTo("include"),
2553
- summary: "Comma-separated allow-list of globs to record in the generated config."
2554
- },
2555
- {
2556
- flag: "--exclude",
2557
- type: "string",
2558
- default: "unset",
2559
- appliesTo: optionAppliesTo("exclude"),
2560
- summary: "Comma-separated globs to record in the generated config."
2561
- },
2562
- {
2563
- flag: "--yes",
2564
- type: "boolean",
2565
- default: false,
2566
- appliesTo: optionAppliesTo("yes"),
2567
- summary: "Accept every default without prompting. Required in a non-TTY."
2568
- },
2569
- {
2570
- flag: "--force",
2571
- type: "boolean",
2572
- default: false,
2573
- appliesTo: optionAppliesTo("force"),
2574
- summary: "Overwrite an existing config file."
2575
- },
2576
- {
2577
- flag: "--autopilot",
2578
- type: "boolean",
2579
- default: false,
2580
- appliesTo: optionAppliesTo("autopilot"),
2581
- summary: "Set the project up without asking, then generate: detect the preset, write the config and .gitignore, add the npm scripts and devDependency, install with the project's own package manager, generate. Autopilot chooses the preset and takes no --preset/--include/--exclude/--install-hook: those belong to `setup` or `init`. Never overwrites an existing config, and never prompts. Refuses an empty directory (exit 1); contradicts --no-config (exit 2)."
2582
- },
2583
- {
2584
- flag: "--install",
2585
- type: "boolean",
2586
- default: false,
2587
- appliesTo: optionAppliesTo("install"),
2588
- summary: "Write the skill into the repository instead of printing it."
2589
- },
2590
- {
2591
- flag: "--target",
2592
- type: "string",
2593
- default: "all",
2594
- appliesTo: optionAppliesTo("target"),
2595
- summary: 'Where to install: "claude", "cursor" or "all".'
2596
- },
2597
- {
2598
- flag: "--no-install",
2599
- type: "boolean",
2600
- default: false,
2601
- appliesTo: optionAppliesTo("no-install"),
2602
- summary: "Skip installing the dependency before generating: `setup`, or `generate --autopilot` (CI, offline, or a lockfile you do not want a package manager to touch)."
2603
- },
2604
- {
2605
- flag: "--install-hook",
2606
- type: "boolean",
2607
- default: false,
2608
- appliesTo: optionAppliesTo("install-hook"),
2609
- summary: "After writing the config, install a pre-commit hook that runs `validate`. An existing hook this tool did not write is left alone."
2610
- },
2611
- {
2612
- flag: "--no-update-check",
2613
- type: "boolean",
2614
- default: false,
2615
- appliesTo: optionAppliesTo("no-update-check"),
2616
- summary: "Skip the check for a newer published version. The check is already skipped when stdout is not a terminal, in CI, in a JSON invocation, and in `mcp`, which makes no network requests."
2617
- }
2618
- ],
2619
- presets: PRESETS.map((preset) => ({
2620
- name: preset.name,
2621
- priority: preset.priority,
2622
- recommendedBudget: preset.recommendedBudget ?? "300k",
2623
- excludes: preset.exclude ? [...preset.exclude] : []
2624
- })),
2625
- artifacts: ARTIFACT_NAMES.map((name) => ({
2626
- name,
2627
- default: ARTIFACT_DEFAULTS[name] ?? true,
2628
- summary: ARTIFACT_SUMMARY[name] ?? name
2629
- })),
2630
- config: {
2631
- fileNames: [
2632
- "snapshot.config.ts",
2633
- "snapshot.config.js",
2634
- "snapshot.config.mjs",
2635
- "snapshot.config.cjs",
2636
- "snapshot.config.json",
2637
- ".snapshotrc.json",
2638
- ".snapshotrc",
2639
- 'package.json \u2192 "snapshot" key'
2640
- ],
2641
- settings: [
2642
- { key: "outDir", type: "string", default: "snapshot", summary: "Snapshot output directory." },
2643
- { key: "tmpDir", type: "string", default: "snapshot.tmp", summary: "Scratch directory used for the atomic swap." },
2644
- { key: "branch", type: "string", default: "main", summary: "Branch recorded when git cannot report one." },
2645
- { key: "preset", type: "string", default: "detected", summary: "Force a preset. Unknown names are an error." },
2646
- { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
2647
- { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
2648
- { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
2649
- { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
2650
- { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
2651
- { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
2652
- { key: "withDependents", type: "boolean", default: false, summary: "With a changed-files scope, also include one hop of importers." },
2653
- { key: "largeFileBytes", type: "number | string", default: 307200, summary: "Preview threshold for large files; defaults to maxPartBytes and may not exceed it." },
2654
- { key: "previewHeadLines", type: "number", default: 80, summary: "Lines kept from the head of a large file." },
2655
- { key: "previewTailLines", type: "number", default: 40, summary: "Lines kept from the tail of a large file." },
2656
- { key: "includeMonolith", type: "boolean", default: false, summary: "Also write the single-file monolith." },
2657
- { key: "maxMonolithBytes", type: "number | string | null", default: null, summary: "Skip the monolith above this size." },
2658
- { key: "includeSensitiveFiles", type: "boolean", default: false, summary: "Emit .env / *.pem / credential files." },
2659
- { key: "include", type: "string[]", default: "[]", summary: "Allow-list of globs; empty means everything." },
2660
- { key: "excludePatterns", type: "string[]", default: "[]", summary: "Extra exclude globs." },
2661
- { key: "brief", type: "string", default: "unset", summary: "Path to the owner-written half of PROMPT.md. Recognised headings: Stakes, The system, What came before, The bar, Calibration; unknown headings are kept as Owner notes; measured headings are refused. The file is digested, so editing it is drift." },
2662
- { key: "promptTask", type: "string", default: "audit", summary: "Which job the brief is written for: audit, review or explain. The standard and the coverage duty are the same in all three." },
2663
- { 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." },
2664
- { 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." },
2665
- { 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." },
2666
- { key: "artifacts", type: "object", default: "all on except monolith", summary: "Per-artifact opt-out." },
2667
- { key: "budgets", type: "object", default: "{ default, byLayer }", summary: "Per-layer byte budgets." },
2668
- { key: "layersMode", type: '"merge" | "replace"', default: "merge", summary: "Whether custom layers extend or replace the preset's." },
2669
- { key: "layers", type: "array", default: "preset layers", summary: "Custom layer rules (glob or RegExp)." },
2670
- { key: "kinds", type: "array", default: "preset kinds", summary: "Custom kind rules." },
2671
- { key: "secrets", type: "object", default: "{}", summary: "Custom secret patterns, or disable the defaults." },
2672
- { 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." },
2673
- { key: "hooks", type: "object", default: "{}", summary: "afterGenerate(manifest) runs after a successful generate." }
2674
- ]
2675
- },
2676
- output: {
2677
- layout: [
2678
- "<outDir>/README.md",
2679
- "<outDir>/PROMPT.md",
2680
- "<outDir>/manifest.json",
2681
- "<outDir>/parts/part-NNN.md",
2682
- "<outDir>/reports/project-tree.md",
2683
- "<outDir>/reports/navigation.md",
2684
- "<outDir>/reports/audit.md",
2685
- "<outDir>/.codebase-snapshot (ownership marker, always written)"
2686
- ],
2687
- notes: [
2688
- "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.",
2689
- "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.",
2690
- "indexes.imports.byFile includes previewed files (their import specifiers are still extracted); such an entry carries `exportsOmitted: true` instead of pretending it exports nothing.",
2691
- "validate re-checks manifest.incomplete[] against files[] and refuses a manifest whose two statements of what is missing disagree.",
2692
- "manifest.skipped[] carries the path and the exact reason it was excluded.",
2693
- "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.",
2694
- `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
2695
- ]
2696
- },
2697
- safety: [
2698
- "Sensitive files (.env, *.pem, .npmrc, .ssh/, .tfstate) are excluded by default and listed in manifest.skipped[].",
2699
- "Secret-shaped strings in ordinary source files are redacted in the emitted parts.",
2700
- "The tool refuses to replace an outDir that it did not create, so a mistyped outDir cannot delete source code.",
2701
- "Nothing is ever written above the repository root; --out-dir may not be the root or an ancestor."
2702
- ],
2703
- mcp: {
2704
- command: `npx ${PACKAGE_NAME} mcp`,
2705
- transport: "stdio",
2706
- protocolVersions: {
2707
- modern: [...MODERN_PROTOCOL_VERSIONS],
2708
- legacy: [...LEGACY_PROTOCOL_VERSIONS],
2709
- default: DEFAULT_LEGACY_PROTOCOL_VERSION
2710
- },
2711
- tools: buildTools().map((tool) => ({
2712
- name: tool.name,
2713
- title: tool.title,
2714
- summary: tool.description,
2715
- readOnly: tool.annotations.readOnlyHint,
2716
- parameters: Object.keys(tool.inputSchema.properties),
2717
- required: tool.inputSchema.required ?? []
2718
- })),
2719
- prompts: buildPrompts().map((prompt) => ({
2720
- name: prompt.name,
2721
- summary: prompt.description,
2722
- arguments: prompt.arguments.map((argument) => argument.name)
2723
- })),
2724
- resources: [...STATIC_RESOURCE_URIS],
2725
- resourceTemplates: [...RESOURCE_TEMPLATE_URIS],
2726
- notes: [
2727
- "stdout carries JSON-RPC messages only; every note and log line goes to stderr.",
2728
- "The server speaks both protocol eras: the legacy `initialize` handshake and the stateless revision, which is detected from `server/discover` or from per-request `_meta`.",
2729
- "Everything it can do is a subset of the CLI. It never installs packages and never writes a config file.",
2730
- "A `root` argument may name a sub-directory of the server's --cwd, and nothing outside it is readable."
2731
- ]
2732
- },
2733
- troubleshooting: [
2734
- {
2735
- symptom: "Command prints nothing and exits 0",
2736
- cause: "A stale global install of this package (often a leftover `npm link`) is shadowing npx: npm runs the global binary instead of installing the published one.",
2737
- fix: "Check `npm ls -g --depth=0` for codebase-snapshot and remove it with `npm rm -g codebase-snapshot`. If it is not installed globally, clear the npx cache with `npm cache clean --force` and retry."
2738
- },
2739
- {
2740
- symptom: "Exit 1 with 'Refusing to replace outDir'",
2741
- cause: "The outDir exists and contains files this tool did not write.",
2742
- fix: "Choose a new/empty --out-dir, or delete the existing directory yourself."
2743
- },
2744
- {
2745
- symptom: "Exit 1 with 'The config file could not be read'",
2746
- cause: "snapshot.config.* exists but does not parse.",
2747
- fix: "Fix the syntax, or delete the config to use the defaults."
2748
- },
2749
- {
2750
- symptom: "Exit 1 from validate",
2751
- cause: "The snapshot no longer matches the files on disk.",
2752
- fix: "Re-run generate."
2753
- },
2754
- {
2755
- symptom: "A directory you expected is missing from the snapshot",
2756
- cause: "It is excluded by the preset, by default ignores, or by your own globs.",
2757
- fix: "Run `explain <path>`; manifest.skipped[] also records the reason for every file."
2758
- }
2759
- ]
2760
- };
2761
- }
2762
-
2763
- // src/agent/skill.ts
2764
- var PACKAGE_NAME2 = "codebase-snapshot";
2765
- var MAJOR_VERSION2 = GENERATOR_VERSION.split(".")[0];
2766
- var SKILL_NAME = "codebase-snapshot";
2767
- function renderSkill() {
2768
- return `---
2769
- name: ${SKILL_NAME}
2770
- 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.
2771
- version: ${GENERATOR_VERSION}
2772
- ---
2773
-
2774
- # codebase-snapshot
2775
-
2776
- Turns a repository into an LLM-ready snapshot under \`./snapshot/\`: code packed into
2777
- size-budgeted markdown parts, plus a manifest that indexes every file, a project tree, a
2778
- navigation index and a secret audit.
2779
-
2780
- Use it when you need to understand a whole repository, or produce repository context for
2781
- another model, and reading files one by one would not fit in context.
2782
-
2783
- ## Before you start
2784
-
2785
- This tool is a Node CLI. It needs **Node.js 18 or newer**. You do not need to install it
2786
- globally, and you do not need to clone anything.
2787
-
2788
- **Pin a version** \u2014 \`npx ${PACKAGE_NAME2}@${GENERATOR_VERSION} <command>\` \u2014 when you
2789
- need the same version on every machine. The bare package name works too: this package ships
2790
- one executable file, published under two names (\`codebase-snapshot\` and \`snapshot\`), which is
2791
- what lets npm pick it. A global install gives the short command \`snapshot\`; inside a project
2792
- that has this package installed, \`npx snapshot\` resolves the local copy first. If a command
2793
- exits 0 printing nothing, the executable was not resolved \u2014 clear the npm cache and retry;
2794
- do not assume the repository is broken.
2795
-
2796
- ## Step by step
2797
-
2798
- 1. **Verify the tool.** Run \`npx ${PACKAGE_NAME2}@latest --version\`. Expect \`v${MAJOR_VERSION2}\` or
2799
- newer on stdout \u2014 compare the major version, not the patch, because the
2800
- \`@latest\` tag can lag this release. If what it prints is older, pin the exact
2801
- release (\`@${GENERATOR_VERSION}\`) instead of retrying. Empty output means you hit the
2802
- bare-spec problem above.
2803
-
2804
- 2. **Read the contract, not the prose.** Run
2805
- \`npx ${PACKAGE_NAME2}@latest describe --format json\`. It returns the full machine
2806
- contract: every command, every option with its default, the exit-code meanings, the
2807
- 25 project presets, the artifact list, the config settings and a troubleshooting
2808
- table. Read it before you make decisions; do not guess option names.
2809
-
2810
- 3. **Look before you leap (optional but cheap).** To see how a specific file or directory
2811
- would be treated, run \`npx ${PACKAGE_NAME2}@latest explain <path>\`. It reports the
2812
- layer, kind, language, target part, and the exact reason a path would be skipped.
2813
- \`--format json\` if you want to parse it.
2814
-
2815
- 3b. **One command, if the user just wants it working.** \`npx ${PACKAGE_NAME2}@latest setup\`
2816
- does steps 4\u20136 in one go with defaults: it writes the config (an existing one is kept),
2817
- adds the npm scripts and the devDependency, installs with the project's package manager,
2818
- and generates. Use \`--no-install\` when the machine is offline or the user does not want
2819
- their lockfile touched. \`--autopilot\` does exactly the same thing from the default
2820
- command (\`npx ${PACKAGE_NAME2}@latest --autopilot\`) and is the form to reach for when a
2821
- single invocation must both set the project up and produce the snapshot. Prefer the
2822
- explicit steps below when you need to control any of those, or when something fails and
2823
- you want to see which part.
2824
-
2825
- 4. **Configure (recommended).** Run \`npx ${PACKAGE_NAME2}@latest init --yes\`. It detects
2826
- the project shape, then writes a commented config file listing **every** setting at its
2827
- current value. The filename depends on the project: \`snapshot.config.ts\` only when
2828
- the running Node can strip types (Node >= 22.6) **and** the project is an ES module
2829
- (\`"type": "module"\` in package.json); otherwise \`snapshot.config.mjs\`. Pass
2830
- \`--preset <name>\` only if detection is wrong; the preset names are in the contract.
2831
- Skipping this step is safe **at a terminal**: the first \`generate\` asks once, can write
2832
- the config for you and then generates. Unattended, a \`generate\` with no config exits 2 \u2014
2833
- run this step, or \`--autopilot\`, or pass \`--no-config\` to run deliberately on the
2834
- built-in defaults.
2835
-
2836
- 5. **Generate.** Run \`npx ${PACKAGE_NAME2}@latest generate\`. Expect exit 0 and a
2837
- \`./snapshot/\` directory. If you need a different location use \`--out-dir <path>\`; if
2838
- you need smaller or larger parts use \`--max-part-bytes 120k\`.
2839
-
2840
- 6. **Verify.** Run \`npx ${PACKAGE_NAME2}@latest validate\`. Exit 0 means the snapshot
2841
- matches the files on disk. Exit 1 means drift \u2014 re-run step 5.
2842
-
2843
- 7. **Read the output in this order:**
2844
- - \`snapshot/parts/part-*.md\` \u2014 the code itself. Each file carries one \`- Meta:\` line
2845
- (layer/kind, language, inclusion, size) and, only when the body is **not** the whole
2846
- file, a structural summary (imports, exports, classes, functions). A full file has no
2847
- summary line, because the summary would repeat the code three lines below it \u2014 read
2848
- \`manifest.json\` for it. A summary dropped to fit the budget appears as a
2849
- \`Summary: (omitted \u2026)\` line.
2850
- - \`snapshot/manifest.json\` \u2014 the index. \`files[]\` has \`relativePath\`, \`layer\`,
2851
- \`kind\`, \`language\`, \`part\`, \`inclusionMode\`, \`hashSha256\` and the structural
2852
- \`summary\`, plus \`encoding\` when the file was not plain UTF-8. \`summary\` is
2853
- **optional**: it is absent for languages with no structural summary, and
2854
- \`summaryOmitted: true\` marks one dropped for size, and the reason in \`summaryOmittedReason\` says which rule \u2014 never assume it
2855
- exists. The per-file \`hashSha256\` is only here and in the manifest; it is not printed
2856
- into the parts.
2857
- \`skipped[]\` records every excluded file **and why**. The top-level \`incomplete[]\` records every included
2858
- file whose body is not the whole file, with its reason and omittedRanges: ask that list,
2859
- not the footer of a part, when the question is whether anything was lost. Prefer querying this over
2860
- re-reading the parts.
2861
- - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
2862
- state. Read this before you quote code back to a user.
2863
- - \`snapshot/reports/project-tree.md\` and \`navigation.md\` \u2014 structure and cross-links.
2864
- - \`snapshot/PROMPT.md\` \u2014 the instruction sheet to hand to the model that receives the
2865
- snapshot: paste it with the parts. It is rendered from this run's manifest and names the
2866
- parts, the partial files and the fingerprint, so do not rewrite it by hand \u2014 \`validate\`
2867
- fails when it was edited.
2868
-
2869
- ## Project types
2870
-
2871
- Detection is automatic and covers Next.js, Nuxt, SvelteKit, Remix, Astro, Angular, Solid,
2872
- Vue+React with Vite, Nest, Express/Fastify/Koa, any Node library, monorepos, Django,
2873
- FastAPI/Flask, plain Python, Go, Rust, Java/Spring, .NET, PHP/Laravel, Ruby/Rails,
2874
- Terraform/Docker infra, docs-only repositories, and a generic fallback. It sets sensible
2875
- layers, kinds, ecosystem ignore patterns and a recommended part budget. For non-TypeScript
2876
- languages it extracts imports, exports, classes and functions structurally; Vue, Svelte and
2877
- Astro script blocks go through the real TypeScript compiler. You do not need to configure
2878
- any of this to get a good first snapshot.
2879
-
2880
- ## Things that will surprise you
2881
-
2882
- - **Sensitive files are excluded by default** (\`.env\`, \`*.pem\`, \`.npmrc\`, \`.ssh/\`,
2883
- \`.tfstate\`) and are listed in \`manifest.skipped[]\`. Add \`--include-sensitive-files\` only
2884
- if the user asks for them explicitly.
2885
- - **Secret-shaped strings inside normal source files are redacted** in the emitted parts.
2886
- If the user needs the raw value, say so rather than working around it.
2887
- - **The output directory is owned by the tool.** It is replaced atomically, and the tool
2888
- refuses to replace a directory it did not create. Never point \`--out-dir\` at source
2889
- code; if you see \`Refusing to replace outDir\`, choose a new directory rather than
2890
- deleting anything.
2891
- - **Exit 2 is a usage error**, not a failure of the repository. Re-read the contract
2892
- before retrying.
2893
- - **A first run refuses rather than guessing.** In a project with no config and no previous
2894
- snapshot, \`generate\` without a terminal exits 2 instead of silently using defaults. That
2895
- is deliberate: say which set-up you want (\`--autopilot\`, \`init --yes\`, or \`--no-config\`)
2896
- rather than retrying the same command.
2897
- - **\`--format json\` keeps stdout pure.** Progress goes to stderr, so \`stdout\` is safe to
2898
- pipe into a JSON parser.
2899
-
2900
- ## Making this available to other agents
2901
-
2902
- Run \`npx ${PACKAGE_NAME2}@latest skill --install\`. It writes this skill into the two
2903
- registries agent tools read by name \u2014 \`.claude/skills/${SKILL_NAME}/SKILL.md\` and
2904
- \`.cursor/rules/${SKILL_NAME}.mdc\` \u2014 and appends exactly those files to \`.gitignore\`, so the
2905
- install leaves nothing untracked. It is idempotent, and it refuses a target that resolves
2906
- outside the repository, so a linked \`.claude/\` cannot be used to write elsewhere.
2907
-
2908
- It never writes \`AGENTS.md\`. That file is the repository's own agent contract \u2014 build
2909
- commands, conventions, house rules \u2014 and this tool has no business editing it. If you want
2910
- this skill in there, run \`npx ${PACKAGE_NAME2}@latest skill\` and paste the text yourself: the
2911
- diff, and the commit, are then yours.
2912
-
2913
- ## When the client speaks MCP
2914
-
2915
- If the agent runs inside an MCP client, \`npx ${PACKAGE_NAME2}@latest mcp\` serves this repository
2916
- as nine tools over stdio instead of shelling out. Its reads come from the snapshot rather than
2917
- the working tree, so excluded files and redacted values never reach the context. Use
2918
- \`snapshot_locate\` before \`snapshot_read\`, and \`snapshot_validate\` before trusting a snapshot
2919
- from an earlier session.
2920
- `;
2921
- }
2922
-
2923
- // src/mcp/resources.ts
2924
- var MAX_RESOURCE_BYTES = 512 * 1024;
2925
- var ResourceTooLargeError = class extends Error {
2926
- constructor(uri, bytes, limit, message) {
2927
- super(message);
2928
- this.uri = uri;
2929
- this.bytes = bytes;
2930
- this.limit = limit;
2931
- this.name = "ResourceTooLargeError";
2932
- }
2933
- uri;
2934
- bytes;
2935
- limit;
2936
- };
2937
- var ResourceNotFoundError = class extends Error {
2938
- constructor(uri, message) {
2939
- super(message);
2940
- this.uri = uri;
2941
- this.name = "ResourceNotFoundError";
2942
- }
2943
- uri;
2944
- };
2945
- function refuseTooLarge(uri, bytes, advice) {
2946
- throw new ResourceTooLargeError(
2947
- uri,
2948
- bytes,
2949
- MAX_RESOURCE_BYTES,
2950
- `${uri} is ${formatBytes3(bytes)}, above the ${formatBytes3(MAX_RESOURCE_BYTES)} single-read limit, so it was not returned. ${advice}`
2951
- );
2952
- }
2953
- function ensureSingleRead(uri, text, advice) {
2954
- const bytes = Buffer.byteLength(text, "utf8");
2955
- if (bytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, bytes, advice);
2956
- return text;
2957
- }
2958
- var MANIFEST_ADVICE = "Cutting a JSON document at the limit leaves invalid JSON, so this resource is never truncated. Use the snapshot_locate, snapshot_read and snapshot_status tools instead \u2014 they read the manifest directly \u2014 or read manifest.json from the snapshot directory.";
2959
- var PART_ADVICE = "A part cut at the limit is a fragment of a file, not the file. Use snapshot_locate to find the file inside this part that you need, then snapshot_read for a bounded window of it.";
2960
- var PROMPT_URI = "snapshot://prompt";
2961
- var PROMPT_ADVICE = "PROMPT.md is written whole and never truncated; regenerate it with snapshot_generate, then read it from the snapshot directory.";
2962
- var REPORT_ADVICE = "A report cut at the limit would look complete and would not be. Read it from the snapshot directory instead: the file on disk is complete.";
2963
- var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
2964
- var REPORT_URIS = /* @__PURE__ */ new Map([
2965
- ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
2966
- ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
2967
- ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
2968
- ]);
2969
- function formatBytes3(bytes) {
2970
- if (bytes < 1024) return `${bytes} B`;
2971
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
2972
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2973
- }
2974
- async function workspaceFor(context) {
2975
- const root = resolveRoot(void 0, context);
2976
- if (!root.ok) return { error: root.message };
2977
- const opened = await openWorkspace(root.root, {}, void 0, { allowExecutableConfig: false });
2978
- if (!opened.ok) return { error: opened.message };
2979
- return opened.workspace;
2980
- }
2981
- function readFileIfPresent(file) {
2982
- try {
2983
- return fs2.readFileSync(file, "utf8");
2984
- } catch {
2985
- return null;
2986
- }
2987
- }
2988
- function buildResourceProvider() {
2989
- return {
2990
- async list(context) {
2991
- const resources = [
2992
- {
2993
- uri: "snapshot://manifest",
2994
- name: "manifest",
2995
- title: "Snapshot manifest",
2996
- description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded. A manifest larger than 512 kB is refused with its size instead of truncated: cut JSON does not parse. Use snapshot_locate, snapshot_read and snapshot_status for a large repository.",
2997
- mimeType: "application/json"
2998
- },
2999
- {
3000
- uri: "snapshot://contract",
3001
- name: "contract",
3002
- title: "Tool contract",
3003
- description: "The machine-readable description of the codebase-snapshot command line.",
3004
- mimeType: "application/json"
3005
- },
3006
- {
3007
- uri: "snapshot://skill",
3008
- name: "skill",
3009
- title: "Agent skill",
3010
- description: "Usage guidance for an agent working with this tool.",
3011
- mimeType: "text/markdown"
3012
- },
3013
- {
3014
- uri: PROMPT_URI,
3015
- name: "prompt",
3016
- title: "Snapshot brief",
3017
- description: "The brief for this snapshot: the job, what the snapshot contains, what it omits, the history it was built from and the standard the answer is held to. Read this before the parts; it names which part holds which file.",
3018
- mimeType: "text/markdown"
3019
- }
3020
- ];
3021
- for (const [uri, report2] of REPORT_URIS) {
3022
- resources.push({
3023
- uri,
3024
- name: report2.file.replace(/\.md$/, ""),
3025
- title: report2.title,
3026
- description: `${report2.title} from the most recent snapshot. A report larger than 512 kB is refused rather than truncated; read the file from the snapshot directory.`,
3027
- mimeType: "text/markdown"
3028
- });
3029
- }
3030
- const workspace = await workspaceFor(context);
3031
- if ("error" in workspace) return resources;
3032
- const read = readManifest(workspace);
3033
- if (!read.ok) return resources;
3034
- for (const part of read.manifest.parts) {
3035
- const readable = part.byteSize <= MAX_RESOURCE_BYTES;
3036
- resources.push({
3037
- uri: `snapshot://parts/${part.index}`,
3038
- name: `part-${String(part.index).padStart(3, "0")}`,
3039
- title: `Part ${part.index} (${part.fileCount} files, ${formatBytes3(part.byteSize)})`,
3040
- description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes3(part.byteSize)}.` + (readable ? "" : ` Above the ${formatBytes3(MAX_RESOURCE_BYTES)} single-read limit, so this resource is refused rather than truncated; use snapshot_locate and snapshot_read.`),
3041
- mimeType: "text/markdown"
3042
- });
3043
- }
3044
- return resources;
3045
- },
3046
- templates() {
3047
- return [
3048
- {
3049
- uriTemplate: "snapshot://parts/{index}",
3050
- name: "part",
3051
- title: "Snapshot part",
3052
- description: "One budgeted part of the snapshot, by its 1-based index.",
3053
- mimeType: "text/markdown"
3054
- }
3055
- ];
3056
- },
3057
- async read(uri, context) {
3058
- if (uri === "snapshot://contract") {
3059
- const contract = buildAgentContract();
3060
- return {
3061
- uri,
3062
- mimeType: "application/json",
3063
- text: ensureSingleRead(
3064
- uri,
3065
- JSON.stringify(contract, null, 2),
3066
- "Run 'codebase-snapshot describe --format json' for the complete contract."
3067
- )
3068
- };
3069
- }
3070
- if (uri === "snapshot://skill") {
3071
- return {
3072
- uri,
3073
- mimeType: "text/markdown",
3074
- text: ensureSingleRead(
3075
- uri,
3076
- renderSkill(),
3077
- "Print it with 'codebase-snapshot skill'."
3078
- )
3079
- };
3080
- }
3081
- const workspace = await workspaceFor(context);
3082
- if ("error" in workspace) return null;
3083
- if (uri === PROMPT_URI) {
3084
- const text = readFileIfPresent(
3085
- path2.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
3086
- );
3087
- if (text === null) {
3088
- throw new ResourceNotFoundError(
3089
- uri,
3090
- "This snapshot contains no PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), or nothing has been generated yet. Run snapshot_generate first."
3091
- );
3092
- }
3093
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, PROMPT_ADVICE) };
3094
- }
3095
- const report2 = REPORT_URIS.get(uri);
3096
- if (report2) {
3097
- const text = readFileIfPresent(
3098
- path2.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
3099
- );
3100
- if (text === null) {
3101
- throw new ResourceNotFoundError(
3102
- uri,
3103
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
3104
- );
3105
- }
3106
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, REPORT_ADVICE) };
3107
- }
3108
- if (uri === "snapshot://manifest") {
3109
- const read = readManifest(workspace);
3110
- if (!read.ok) return null;
3111
- const text = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
3112
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text, MANIFEST_ADVICE) };
3113
- }
3114
- const partMatch = PART_URI.exec(uri);
3115
- if (partMatch) {
3116
- const read = readManifest(workspace);
3117
- if (!read.ok) return null;
3118
- const index = Number(partMatch[1]);
3119
- const part = read.manifest.parts.find((candidate) => candidate.index === index);
3120
- if (!part) return null;
3121
- const partPath = partPathFor(workspace, part.filename);
3122
- if (partPath === null) return null;
3123
- let partBytes;
3124
- try {
3125
- partBytes = fs2.statSync(partPath).size;
3126
- } catch {
3127
- return null;
3128
- }
3129
- if (partBytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, partBytes, PART_ADVICE);
3130
- const text = readFileIfPresent(partPath);
3131
- if (text === null) return null;
3132
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, PART_ADVICE) };
3133
- }
3134
- return null;
3135
- }
3136
- };
3137
- }
3138
-
3139
- // src/mcp/schema.ts
3140
- function validateArguments(schema, value) {
3141
- if (value === void 0) value = {};
3142
- if (!isJsonObject(value)) return ["arguments must be a JSON object"];
3143
- const problems = [];
3144
- const known = new Set(Object.keys(schema.properties));
3145
- for (const key of Object.keys(value)) {
3146
- if (!known.has(key) && schema.additionalProperties !== true) {
3147
- const allowed = [...known].sort().join(", ");
3148
- problems.push(`unknown argument "${key}" (accepted: ${allowed || "none"})`);
3149
- }
3150
- }
3151
- for (const required of schema.required ?? []) {
3152
- if (value[required] === void 0) problems.push(`missing required argument "${required}"`);
3153
- }
3154
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
3155
- const argument = value[key];
3156
- if (argument === void 0) continue;
3157
- problems.push(...checkValue(key, propertySchema, argument));
3158
- }
3159
- return problems;
3160
- }
3161
- function checkValue(path5, schema, value) {
3162
- if (schema.enum && !schema.enum.includes(value)) {
3163
- return [`"${path5}" must be one of: ${schema.enum.join(", ")}`];
3164
- }
3165
- switch (schema.type) {
3166
- case "string": {
3167
- if (typeof value !== "string") return [`"${path5}" must be a string`];
3168
- const problems = [];
3169
- if (schema.minLength !== void 0 && value.length < schema.minLength) {
3170
- problems.push(`"${path5}" must be at least ${schema.minLength} character(s)`);
3171
- }
3172
- if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
3173
- problems.push(`"${path5}" must be at most ${schema.maxLength} character(s)`);
3174
- }
3175
- return problems;
3176
- }
3177
- case "number":
3178
- case "integer": {
3179
- if (typeof value !== "number" || Number.isNaN(value)) {
3180
- return [`"${path5}" must be a number`];
3181
- }
3182
- if (schema.type === "integer" && !Number.isInteger(value)) {
3183
- return [`"${path5}" must be an integer`];
3184
- }
3185
- const problems = [];
3186
- if (schema.minimum !== void 0 && value < schema.minimum) {
3187
- problems.push(`"${path5}" must be >= ${schema.minimum}`);
3188
- }
3189
- if (schema.maximum !== void 0 && value > schema.maximum) {
3190
- problems.push(`"${path5}" must be <= ${schema.maximum}`);
3191
- }
3192
- return problems;
3193
- }
3194
- case "boolean":
3195
- return typeof value === "boolean" ? [] : [`"${path5}" must be a boolean`];
3196
- case "array": {
3197
- if (!Array.isArray(value)) return [`"${path5}" must be an array`];
3198
- if (!schema.items) return [];
3199
- const problems = [];
3200
- value.forEach((item, index) => {
3201
- problems.push(...checkValue(`${path5}[${index}]`, schema.items, item));
3202
- });
3203
- return problems;
3204
- }
3205
- case "object":
3206
- return isJsonObject(value) ? [] : [`"${path5}" must be an object`];
3207
- default:
3208
- return [];
3209
- }
3210
- }
3211
- function applyDefaults(schema, value) {
3212
- const out = { ...value };
3213
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
3214
- if (out[key] === void 0 && propertySchema.default !== void 0) {
3215
- out[key] = propertySchema.default;
3216
- }
3217
- }
3218
- return out;
3219
- }
3220
- function coerceNumericStrings(schema, value) {
3221
- const out = { ...value };
3222
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
3223
- const raw = out[key];
3224
- if (typeof raw !== "string") continue;
3225
- if (propertySchema.type !== "number" && propertySchema.type !== "integer") continue;
3226
- if (raw.trim().length === 0) continue;
3227
- const parsed = Number(raw);
3228
- if (Number.isFinite(parsed)) out[key] = parsed;
3229
- }
3230
- return out;
3231
- }
3232
-
3233
- // src/mcp/server.ts
3234
- function capabilities() {
3235
- return {
3236
- tools: { listChanged: false },
3237
- resources: { subscribe: false, listChanged: false },
3238
- prompts: { listChanged: false }
3239
- };
3240
- }
3241
- function requestIdOf(message) {
3242
- const raw = message.id;
3243
- return typeof raw === "string" || typeof raw === "number" ? raw : null;
3244
- }
3245
- function createMcpServer(options) {
3246
- const session = createSession();
3247
- const toolsByName = new Map(options.tools.map((tool) => [tool.name, tool]));
3248
- const promptsByName = new Map(options.prompts.map((prompt) => [prompt.name, prompt]));
3249
- const identity = () => ({
3250
- name: options.info.name,
3251
- title: options.info.title,
3252
- version: options.info.version,
3253
- websiteUrl: options.info.websiteUrl
3254
- });
3255
- const ok = (id, result, modern) => successResponse(id, result, modern, options.info);
3256
- function handleNotification(method) {
3257
- if (method === METHOD.initialized && session.era === "legacy") session.ready = true;
3258
- }
3259
- function initialize(id, params) {
3260
- const negotiation = negotiateLegacyVersion(params?.protocolVersion);
3261
- session.era = "legacy";
3262
- session.protocolVersion = negotiation.version;
3263
- session.ready = true;
3264
- options.context.log(
3265
- negotiation.matched ? `mcp: client initialized with protocol ${negotiation.version}` : `mcp: client asked for an unsupported version and was offered ${negotiation.version}`
3266
- );
3267
- return {
3268
- jsonrpc: "2.0",
3269
- id,
3270
- result: {
3271
- protocolVersion: negotiation.version,
3272
- capabilities: capabilities(),
3273
- serverInfo: identity(),
3274
- instructions: options.instructions
3275
- }
3276
- };
3277
- }
3278
- function discover(id) {
3279
- session.era = "modern";
3280
- session.ready = true;
3281
- return ok(
3282
- id,
3283
- {
3284
- supportedVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
3285
- capabilities: capabilities(),
3286
- instructions: options.instructions,
3287
- // The capability set depends on which repository the server was started for, so the answer
3288
- // may be cached only by the client that asked, and not at all after this response.
3289
- cacheScope: "private",
3290
- ttlMs: 0
3291
- },
3292
- true
3293
- );
3294
- }
3295
- function listTools(id, modern) {
3296
- const tools = options.tools.map((tool) => ({
3297
- name: tool.name,
3298
- title: tool.title,
3299
- description: tool.description,
3300
- inputSchema: tool.inputSchema,
3301
- ...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
3302
- annotations: tool.annotations
3303
- }));
3304
- return ok(id, { tools }, modern);
3305
- }
3306
- async function callTool(id, modern, params) {
3307
- const name = params?.name;
3308
- if (typeof name !== "string") {
3309
- return errorResponse(id, ERROR_CODES.invalidParams, 'tools/call requires a "name" string.');
3310
- }
3311
- const tool = toolsByName.get(name);
3312
- if (!tool) {
3313
- const known = [...toolsByName.keys()].sort().join(", ");
3314
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown tool "${name}". Available: ${known}.`);
3315
- }
3316
- const rawArguments = params?.arguments ?? {};
3317
- if (!isJsonObject(rawArguments)) {
3318
- return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
3319
- }
3320
- const supplied = coerceNumericStrings(tool.inputSchema, rawArguments);
3321
- const problems = validateArguments(tool.inputSchema, supplied);
3322
- if (problems.length > 0) {
3323
- return ok(
3324
- id,
3325
- {
3326
- content: [{ type: "text", text: `Invalid arguments for ${tool.name}:
3327
- - ${problems.join("\n- ")}` }],
3328
- isError: true
3329
- },
3330
- modern
3331
- );
3332
- }
3333
- const args = applyDefaults(tool.inputSchema, supplied);
3334
- let outcome;
3335
- try {
3336
- outcome = await tool.handler(args, options.context);
3337
- } catch (error) {
3338
- const detail = error instanceof Error ? error.message : String(error);
3339
- options.context.log(`mcp: tool ${tool.name} failed: ${detail}`);
3340
- return ok(
3341
- id,
3342
- { content: [{ type: "text", text: `${tool.name} failed: ${detail}` }], isError: true },
3343
- modern
3344
- );
3345
- }
3346
- return ok(
3347
- id,
3348
- {
3349
- content: [{ type: "text", text: outcome.text }],
3350
- ...outcome.structured ? { structuredContent: outcome.structured } : {},
3351
- ...outcome.isError ? { isError: true } : {}
3352
- },
3353
- modern
3354
- );
3355
- }
3356
- async function listResources(id, modern) {
3357
- const resources = await options.resources.list(options.context);
3358
- return ok(id, { resources }, modern);
3359
- }
3360
- async function readResource(id, modern, params) {
3361
- const uri = params?.uri;
3362
- if (typeof uri !== "string") {
3363
- return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
3364
- }
3365
- let contents;
3366
- try {
3367
- contents = await options.resources.read(uri, options.context);
3368
- } catch (error) {
3369
- if (error instanceof ResourceNotFoundError) {
3370
- return errorResponse(id, ERROR_CODES.resourceNotFound, error.message, { uri: error.uri });
3371
- }
3372
- if (error instanceof ResourceTooLargeError) {
3373
- options.context.log(
3374
- `mcp: refused ${error.uri} (${error.bytes} bytes, limit ${error.limit}); returning it would truncate it`
3375
- );
3376
- return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
3377
- uri: error.uri,
3378
- bytes: error.bytes,
3379
- limit: error.limit
3380
- });
3381
- }
3382
- throw error;
3383
- }
3384
- if (!contents) {
3385
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
3386
- }
3387
- return ok(id, { contents: [contents] }, modern);
3388
- }
3389
- function listPrompts(id, modern) {
3390
- const prompts = options.prompts.map((prompt) => ({
3391
- name: prompt.name,
3392
- ...prompt.title ? { title: prompt.title } : {},
3393
- description: prompt.description,
3394
- arguments: prompt.arguments
3395
- }));
3396
- return ok(id, { prompts }, modern);
3397
- }
3398
- function getPrompt(id, modern, params) {
3399
- const name = params?.name;
3400
- if (typeof name !== "string") {
3401
- return errorResponse(id, ERROR_CODES.invalidParams, 'prompts/get requires a "name" string.');
3402
- }
3403
- const prompt = promptsByName.get(name);
3404
- if (!prompt) {
3405
- const known = [...promptsByName.keys()].sort().join(", ");
3406
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown prompt "${name}". Available: ${known}.`);
3407
- }
3408
- const rawArguments = params?.arguments ?? {};
3409
- if (!isJsonObject(rawArguments)) {
3410
- return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
3411
- }
3412
- const built = prompt.build(rawArguments);
3413
- const messages = built.messages.map((message) => ({
3414
- role: message.role,
3415
- content: { type: "text", text: message.content.text }
3416
- }));
3417
- return ok(id, { description: built.description, messages }, modern);
3418
- }
3419
- async function route(name, id, modern, params) {
3420
- switch (name) {
3421
- case METHOD.initialize:
3422
- return modern ? errorResponse(
3423
- id,
3424
- ERROR_CODES.methodNotFound,
3425
- '"initialize" does not exist in this protocol revision; call "server/discover".'
3426
- ) : initialize(id, params);
3427
- case METHOD.discover:
3428
- return discover(id);
3429
- case METHOD.ping:
3430
- return modern ? errorResponse(
3431
- id,
3432
- ERROR_CODES.methodNotFound,
3433
- '"ping" was removed in this protocol revision; call "server/discover".'
3434
- ) : ok(id, {}, modern);
3435
- }
3436
- if (!session.ready) {
3437
- return errorResponse(
3438
- id,
3439
- ERROR_CODES.invalidRequest,
3440
- 'This connection has not been initialized. Send "initialize" first.'
3441
- );
3442
- }
3443
- switch (name) {
3444
- case METHOD.toolsList:
3445
- return listTools(id, modern);
3446
- case METHOD.toolsCall:
3447
- return callTool(id, modern, params);
3448
- case METHOD.resourcesList:
3449
- return listResources(id, modern);
3450
- case METHOD.resourcesRead:
3451
- return readResource(id, modern, params);
3452
- case METHOD.resourceTemplatesList:
3453
- return ok(id, { resourceTemplates: options.resources.templates() }, modern);
3454
- case METHOD.promptsList:
3455
- return listPrompts(id, modern);
3456
- case METHOD.promptsGet:
3457
- return getPrompt(id, modern, params);
3458
- default:
3459
- return errorResponse(id, ERROR_CODES.methodNotFound, `Unknown method "${name}".`);
3460
- }
3461
- }
3462
- async function dispatch(message) {
3463
- if (!isJsonObject(message)) {
3464
- return errorResponse(
3465
- null,
3466
- ERROR_CODES.invalidRequest,
3467
- Array.isArray(message) ? "Batch requests are not supported: send one JSON-RPC message per line." : "Message is not a JSON object."
3468
- );
3469
- }
3470
- const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
3471
- const method = message.method;
3472
- const params = message.params;
3473
- if (message.jsonrpc !== "2.0" && isRequest) {
3474
- return errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, 'Message must carry "jsonrpc": "2.0".');
3475
- }
3476
- if (typeof method !== "string" || method.length === 0) {
3477
- return isRequest ? errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, 'Message must carry a "method" string.') : null;
3478
- }
3479
- if (params !== void 0 && !isJsonObject(params)) {
3480
- return isRequest ? errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, '"params" must be a JSON object when present.') : null;
3481
- }
3482
- const named = params;
3483
- const decision = classifyRequest(method, named, session);
3484
- const modern = decision.kind === "era" ? decision.era === "modern" : session.era === "modern";
3485
- if (!isRequest) {
3486
- if (decision.kind === "era" && session.era === null) {
3487
- session.era = decision.era;
3488
- session.protocolVersion = decision.version;
3489
- }
3490
- handleNotification(method);
3491
- return null;
3492
- }
3493
- const id = requestIdOf(message);
3494
- if (id === null) {
3495
- return errorResponse(null, ERROR_CODES.invalidRequest, 'A request "id" must be a string or a number.');
3496
- }
3497
- if (decision.kind === "error") {
3498
- return errorResponse(id, decision.code, decision.message, decision.data);
3499
- }
3500
- if (session.era === null) {
3501
- session.era = decision.era;
3502
- session.protocolVersion = decision.version;
3503
- }
3504
- return route(method, id, modern, named);
3505
- }
3506
- return {
3507
- session,
3508
- async handle(message) {
3509
- try {
3510
- return await dispatch(message);
3511
- } catch (error) {
3512
- const detail = error instanceof Error ? error.message : String(error);
3513
- options.context.log(`mcp: internal error: ${detail}`);
3514
- const id = isJsonObject(message) ? requestIdOf(message) : null;
3515
- return errorResponse(id, ERROR_CODES.internalError, "Internal server error.");
3516
- }
3517
- }
3518
- };
3519
- }
3520
-
3521
- // src/mcp/instructions.ts
3522
- var SERVER_INSTRUCTIONS = [
3523
- "codebase-snapshot serves this repository as a size-budgeted snapshot, not as a directory walk.",
3524
- "",
3525
- "Work in this order:",
3526
- "1. snapshot_status \u2014 is there a snapshot here, and has the tree moved since it was built?",
3527
- "2. snapshot_locate \u2014 find which part holds the code you need.",
3528
- "3. snapshot_read \u2014 read a window of one file. Never read a part end to end.",
3529
- "4. snapshot_dependents \u2014 before changing a file, see what imports it.",
3530
- "5. snapshot_validate \u2014 before trusting context that came from an earlier conversation.",
3531
- "",
3532
- "Rules that matter:",
3533
- "- Parts are budgeted, not small: a 12-part snapshot is hundreds of kilobytes. Use snapshot_locate first.",
3534
- "- A file absent from the snapshot has a recorded reason. Ask snapshot_explain, do not assume.",
3535
- "- snapshot_generate is the only tool that writes. It never installs packages and never writes config.",
3536
- "- Paths are relative to the repository root the server was started for, and nothing outside it is readable."
3537
- ].join("\n");
3538
-
3539
- // src/mcp/stdio.ts
3540
- var MAX_LINE_BYTES = 32 * 1024 * 1024;
3541
- function createWriter(output) {
3542
- return {
3543
- write(value) {
3544
- return new Promise((resolve5, reject) => {
3545
- output.write(`${JSON.stringify(value)}
3546
- `, (error) => {
3547
- if (error) reject(error);
3548
- else resolve5();
3549
- });
3550
- });
3551
- }
3552
- };
3553
- }
3554
- function createLineReader(input, options) {
3555
- let buffer = "";
3556
- let bufferBytes = 0;
3557
- let discarding = false;
3558
- let discardedBytes = 0;
3559
- const deliver = (line) => {
3560
- if (discarding) {
3561
- discarding = false;
3562
- discardedBytes = 0;
3563
- return;
3564
- }
3565
- const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line;
3566
- if (trimmed.trim().length === 0) return;
3567
- options.onLine(trimmed);
3568
- };
3569
- const discardBuffered = () => {
3570
- discarding = true;
3571
- discardedBytes += bufferBytes;
3572
- buffer = "";
3573
- bufferBytes = 0;
3574
- options.onOverflow?.(discardedBytes);
3575
- };
3576
- const drain = () => {
3577
- let index = buffer.indexOf("\n");
3578
- while (index >= 0) {
3579
- const line = buffer.slice(0, index);
3580
- buffer = buffer.slice(index + 1);
3581
- if (discarding) {
3582
- deliver(line);
3583
- } else {
3584
- const lineBytes = Buffer.byteLength(line, "utf8");
3585
- if (lineBytes > MAX_LINE_BYTES) options.onOverflow?.(lineBytes);
3586
- else deliver(line);
3587
- }
3588
- index = buffer.indexOf("\n");
3589
- }
3590
- bufferBytes = Buffer.byteLength(buffer, "utf8");
3591
- if (!discarding && bufferBytes > MAX_LINE_BYTES) discardBuffered();
3592
- };
3593
- const onData = (chunk) => {
3594
- const chunkBytes = Buffer.byteLength(chunk, "utf8");
3595
- if (discarding) {
3596
- const index = chunk.indexOf("\n");
3597
- if (index < 0) {
3598
- discardedBytes += chunkBytes;
3599
- return;
3600
- }
3601
- buffer = chunk.slice(index + 1);
3602
- bufferBytes = Buffer.byteLength(buffer, "utf8");
3603
- deliver("");
3604
- drain();
3605
- return;
3606
- }
3607
- if (chunk.indexOf("\n") < 0 && bufferBytes + chunkBytes > MAX_LINE_BYTES) {
3608
- discarding = true;
3609
- discardedBytes = bufferBytes + chunkBytes;
3610
- buffer = "";
3611
- bufferBytes = 0;
3612
- options.onOverflow?.(discardedBytes);
3613
- return;
3614
- }
3615
- buffer += chunk;
3616
- drain();
3617
- };
3618
- const onEnd = () => {
3619
- const rest = buffer;
3620
- const restBytes = bufferBytes || Buffer.byteLength(rest, "utf8");
3621
- buffer = "";
3622
- bufferBytes = 0;
3623
- if (rest.length === 0) return;
3624
- if (discarding) {
3625
- discarding = false;
3626
- discardedBytes = 0;
3627
- return;
3628
- }
3629
- if (restBytes > MAX_LINE_BYTES) {
3630
- options.onOverflow?.(restBytes);
3631
- return;
3632
- }
3633
- deliver(rest);
3634
- };
3635
- input.setEncoding("utf8");
3636
- input.on("data", onData);
3637
- input.on("end", onEnd);
3638
- return () => {
3639
- input.off("data", onData);
3640
- input.off("end", onEnd);
3641
- };
3642
- }
3643
-
3644
- // src/mcp/run.ts
3645
- var PROJECT_URL = "https://ankurhalder.github.io/codebase-snapshot/";
3646
- function createServer(options) {
3647
- const cwd = options.cwd;
3648
- const roots = options.roots && options.roots.length > 0 ? options.roots : [cwd];
3649
- const context = {
3650
- cwd,
3651
- roots,
3652
- log: options.log ?? ((line) => process.stderr.write(`${line}
3653
- `))
3654
- };
3655
- return createMcpServer({
3656
- info: {
3657
- name: GENERATOR_NAME,
3658
- title: "codebase-snapshot",
3659
- version: GENERATOR_VERSION,
3660
- websiteUrl: PROJECT_URL
3661
- },
3662
- instructions: SERVER_INSTRUCTIONS,
3663
- tools: buildTools(),
3664
- resources: buildResourceProvider(),
3665
- prompts: buildPrompts(),
3666
- context
3667
- });
3668
- }
3669
- async function runStdioServer(options) {
3670
- const log = options.log ?? ((line) => process.stderr.write(`${line}
3671
- `));
3672
- const server = createServer(options);
3673
- const writer = createWriter(process.stdout);
3674
- let writeChain = Promise.resolve();
3675
- const send = (message) => {
3676
- writeChain = writeChain.then(() => writer.write(message)).catch((error) => {
3677
- log(`mcp: could not write a response: ${error instanceof Error ? error.message : String(error)}`);
3678
- });
3679
- return writeChain;
3680
- };
3681
- const MAX_IN_FLIGHT = 4;
3682
- let inFlight = 0;
3683
- let inputEnded = false;
3684
- let resolveDone = () => void 0;
3685
- const finished = new Promise((resolve5) => {
3686
- resolveDone = resolve5;
3687
- });
3688
- const finishIfIdle = () => {
3689
- if (inputEnded && inFlight === 0) resolveDone(0);
3690
- };
3691
- const handleLine = async (line) => {
3692
- let message;
3693
- try {
3694
- message = JSON.parse(line);
3695
- } catch {
3696
- await send(errorResponse(null, ERROR_CODES.parseError, "Message is not valid JSON."));
3697
- return;
3698
- }
3699
- const response = await server.handle(message);
3700
- if (response) await send(response);
3701
- };
3702
- const rejectOverloaded = (line) => {
3703
- let id = null;
3704
- try {
3705
- const parsed = JSON.parse(line);
3706
- if (!isJsonObject(parsed)) return;
3707
- if (typeof parsed.id === "string" || typeof parsed.id === "number") id = parsed.id;
3708
- else return;
3709
- } catch {
3710
- return;
3711
- }
3712
- void send(
3713
- errorResponse(
3714
- id,
3715
- ERROR_CODES.overloaded,
3716
- `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
3717
- )
3718
- );
3719
- };
3720
- const stopReading = createLineReader(process.stdin, {
3721
- onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
3722
- onLine: (line) => {
3723
- if (inFlight >= MAX_IN_FLIGHT) {
3724
- rejectOverloaded(line);
3725
- return;
3726
- }
3727
- inFlight += 1;
3728
- void handleLine(line).finally(() => {
3729
- inFlight -= 1;
3730
- finishIfIdle();
3731
- });
3732
- }
3733
- });
3734
- const onEnd = () => {
3735
- inputEnded = true;
3736
- finishIfIdle();
3737
- };
3738
- process.stdin.on("end", onEnd);
3739
- process.stdin.on("close", onEnd);
3740
- log(`mcp: serving ${options.cwd} over stdio`);
3741
- const code = await finished;
3742
- stopReading();
3743
- process.stdin.off("end", onEnd);
3744
- process.stdin.off("close", onEnd);
3745
- await writeChain;
3746
- return code;
3747
- }
3748
-
3749
- export { COMMAND_OPTION_SCOPE, ERROR_CODES, LEGACY_PROTOCOL_VERSIONS, MAX_LINE_BYTES, METHOD, MODERN_PROTOCOL_VERSIONS, SERVER_INSTRUCTIONS, SKILL_NAME, SUPPORTED_PROTOCOL_VERSIONS, auditSnapshot, buildAgentContract, buildPrompts, buildResourceProvider, buildTools, classifyRequest, coerceNumericStrings, commandsForOption, createLineReader, createMcpServer, createServer, createSession, createWriter, findSection, inspectModernMeta, negotiateLegacyVersion, parsePartSections, renderContractText, renderSkill, runStdioServer, validateArguments, windowText };