codebase-snapshot 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -30,6 +30,136 @@ deprecated with an explanatory message instead. `latest` has pointed at 0.9.0 si
30
30
 
31
31
  ---
32
32
 
33
+ ## 0.14.0
34
+
35
+ **The audit now proves the manifest, instead of trusting it.**
36
+
37
+ 0.13.x was the health service facing its own claims. Each sub-bump asked "what does this audit
38
+ actually verify?", and five answers were uncomfortable:
39
+
40
+ - **0.13.3** `GET /metrics`: request totals, per-method counts, refusals, rate limits, tool count and
41
+ uptime in Prometheus text, with no path or credential as a label.
42
+ - **0.13.4** a workspace member is compared with its `WORKSPACE.json`: fingerprint and file count must
43
+ agree, and a stale index warns with the field that disagrees.
44
+ - **0.13.6** every file body in a part is compared with the manifest's `includedBytes` and
45
+ `includedLines`, by anchor. A truncated part with an updated hash used to pass every check.
46
+ - **0.13.7** `counts.totalFiles`, `counts.partsCount`, `counts.skippedCount`, `totals.totalContentBytes`
47
+ and the per-layer counts are recomputed from the manifest's own arrays. A manifest claiming five
48
+ more files than it held passed everything before this.
49
+ - **0.13.9/0.13.10** each single-file pack (JSON, XML, markdown) must hold exactly the files the
50
+ manifest lists. A digest proves the pack is the recorded file, not that the recorded pack is
51
+ complete.
52
+
53
+ ### What this milestone changes for a reader
54
+
55
+ - A snapshot that says it contains something it does not now fails the audit with the field and both
56
+ numbers, instead of scoring 100.
57
+ - The audit is stricter about its own bookkeeping, so a hand-edited manifest is a failure even when
58
+ every hash was updated to match.
59
+ - The JSON, XML and markdown packs are audited as deliverables rather than as opaque artifacts.
60
+
61
+ ### How it was verified
62
+
63
+ Full `npm run verify`: 1323 tests, 1315 pass, 0 fail, 8 host skips; 29 site pages with no link or
64
+ metadata problems; a 52-file tarball whose lockfile agrees with `package.json`. Each new check was
65
+ probed by breaking the thing it checks: a truncated part, an edited count, a pack minus one entry, an
66
+ index with a wrong fingerprint — and each probe became a test.
67
+ ## 0.13.10
68
+
69
+ - **Every single-file pack is checked for membership, not only the JSON one.** The XML pack writes
70
+ paths as `<file path="…">` and the markdown pack as `## File: …`; each has a small reader and the
71
+ same both-directions comparison against `manifest.files`. A pack entry deleted and the digest
72
+ updated is a critical failure in all three formats.
73
+
74
+ Verified: clean `--pack xml`, `--pack single` and `--pack json` snapshots pass their checks; removing
75
+ one file section from the XML and the markdown pack and re-digesting fails with
76
+ `is in the manifest but not the pack`.
77
+ ## 0.13.9
78
+
79
+ - **The JSON monolith must hold every file the manifest lists.** The pack's digest proves it is the
80
+ file the manifest recorded, not that the manifest recorded a complete pack. The audit parses it and
81
+ compares the file set both ways: an entry removed and the digest updated is now a critical failure.
82
+ - Membership only, deliberately: the pack keeps a file's final newline and a part body does not, and
83
+ normalising that difference would duplicate the per-file body accounting with a fragile check.
84
+
85
+ Verified: a clean `--pack json` snapshot passes; removing one entry and re-digesting the artifact
86
+ fails with `is in the manifest but not the pack`.
87
+ ## 0.13.8
88
+
89
+ - The goal log records the 0.13.6-0.13.7 round: per-file body accounting and the count recomputation,
90
+ with the probes that found both gaps.
91
+ ## 0.13.7
92
+
93
+ **The audit checks the counts against the data they summarise.**
94
+
95
+ - `counts.totalFiles`, `counts.partsCount`, `counts.skippedCount`, `totals.totalContentBytes` and the
96
+ per-layer counts were quoted, never verified. A manifest edited to claim five more files than the
97
+ parts hold passed every check — each part hashed correctly and the artifacts were present.
98
+ - The audit recomputes all of them from the manifest's own arrays and fails with the field and both
99
+ numbers when they disagree (probed: `counts.totalFiles: manifest says 7, the data has 2`).
100
+
101
+ Verified: a clean snapshot passes the check, and one edited count field fails with its name.
102
+ ## 0.13.6
103
+
104
+ **The audit checks every file body against the manifest accounting.**
105
+
106
+ - The manifest records `includedBytes` and `includedLines` per file; nothing verified them against
107
+ the parts. A part could be truncated or edited, its hash updated in the manifest, and every
108
+ integrity check would agree while the reader received less than the manifest promised.
109
+ - Each part is parsed once with the same parser the MCP reader uses (moved to
110
+ `src/partitioner/part-format.ts` so the auditor does not import the server), and every file's
111
+ section is compared by anchor: bytes must equal `includedBytes`, lines must equal `includedLines`.
112
+ A missing section is a failure with the path named.
113
+
114
+ Verified: the check passes on this repository in five modes (full, strip-comments,
115
+ remove-empty-lines, skeleton, forced previews); deleting one line from a part without touching the
116
+ manifest fails the audit.
117
+ ## 0.13.5
118
+
119
+ - The goal log records the 0.13.3-0.13.4 round: Prometheus metrics on the HTTP transport and the
120
+ workspace-index check in the health audit.
121
+ ## 0.13.4
122
+
123
+ - **The health audit checks a workspace member against its index.** When `WORKSPACE.json` sits beside
124
+ the snapshot, the member's recorded fingerprint and file count must match the snapshot; a stale or
125
+ edited index warns (and `--strict` exits 1) rather than leaving the deliverable saying two things
126
+ about one directory. An index that cannot be read warns with the parse error; an index that does not
127
+ list this member is a skip with the reason.
128
+
129
+ Verified: editing a member's fingerprint makes the audit warn with the field that disagrees, and
130
+ regenerating the workspace makes it pass again.
131
+ ## 0.13.3
132
+
133
+ - **`GET /metrics` on the HTTP transport.** Prometheus text, no dependency: request totals, a count
134
+ per method, refusals (a disallowed CORS origin) and rate-limit rejections, plus the tool count and
135
+ uptime. Labels are fixed — no path, no tool name, no credential — because a label built from a URL
136
+ is an unbounded map and would publish what was asked for to the monitoring system.
137
+ - `/healthz` and `/metrics` need no token (neither exposes repository data); everything else still
138
+ does.
139
+
140
+ Verified: a refused origin and a normal request move their counters, and no request path appears in
141
+ the output.
142
+ ## 0.13.2
143
+
144
+ - The goal log records the milestone: 0.13.0 tagged, released on GitHub and **published to npm**
145
+ through the train (the registry reports `latest = 0.13.0`), plus the 0.12.99 security fix and the
146
+ 0.13.1 portability fix the release workflow exposed.
147
+ - `ROADMAP.md` carries a milestone table with the published state, so the next milestone has a place
148
+ to be recorded rather than being inferred from the changelog.
149
+ ## 0.13.1
150
+
151
+ **The test suite could not run on Linux, so the release workflow never passed.**
152
+
153
+ - Twelve test files built the binary path with `new URL(import.meta.url).pathname` and stripped a
154
+ leading slash. On Windows that yields `C:/…` and works; on Linux it yields `home/runner/…` — a
155
+ *relative* path — so `dist/bin.js` resolved under the scratch directory and the test failed with
156
+ `Cannot find module`. The release workflow runs the suite on Ubuntu, so the first milestone release
157
+ failed there even though every local run was green.
158
+ - All twelve now use `fileURLToPath(import.meta.url)`, which is absolute on both platforms. The
159
+ rewrite was mechanical; the eleven suites it touches were re-run.
160
+
161
+ Verified: 49 tests across the eleven rewritten suites pass locally, and the construct no longer
162
+ depends on the platform.
33
163
  ## 0.13.0
34
164
 
35
165
  **The first published milestone.** Every release from 0.12.15 to 0.12.99 is tagged in this
package/README.md CHANGED
@@ -210,7 +210,7 @@ Everything an agent needs is available as data, and the tool can install its own
210
210
  ```bash
211
211
  npx codebase-snapshot describe --format json # contract: workflow, options, exit codes
212
212
  npx codebase-snapshot skill --install # into .claude/skills + .cursor/rules
213
- npx -y codebase-snapshot@0.13.0 mcp # or serve it over MCP
213
+ npx -y codebase-snapshot@0.14.0 mcp # or serve it over MCP
214
214
  ```
215
215
 
216
216
  An agent told only "use `npx codebase-snapshot`" can read the contract, follow its ordered
package/SECURITY.md CHANGED
@@ -6,11 +6,11 @@ Only the latest published release receives security fixes.
6
6
 
7
7
  | Version | Supported |
8
8
  | :--- | :--- |
9
- | <!--@majorMinor-->0.13<!--/@majorMinor-->.x | ✅ |
9
+ | <!--@majorMinor-->0.14<!--/@majorMinor-->.x | ✅ |
10
10
  | anything older | ❌ |
11
11
 
12
12
  The number line restarted at 0.9.0 when the package moved to the unscoped `codebase-snapshot` name,
13
- so <!--@majorMinor-->0.13<!--/@majorMinor-->.x is newer than 4.4.1, not older. That is explained in full in the
13
+ so <!--@majorMinor-->0.14<!--/@majorMinor-->.x is newer than 4.4.1, not older. That is explained in full in the
14
14
  [changelog](CHANGELOG.md#a-note-on-version-numbers).
15
15
 
16
16
  ## Reporting a vulnerability
package/dist/bin.js CHANGED
@@ -2191,7 +2191,7 @@ function applySpansKeepingQuotes(line, spans) {
2191
2191
 
2192
2192
  // src/version.ts
2193
2193
  var GENERATOR_NAME = "codebase-snapshot";
2194
- var GENERATOR_VERSION = "0.13.0";
2194
+ var GENERATOR_VERSION = "0.14.0";
2195
2195
  var SCHEMA_VERSION = "3.0.0";
2196
2196
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2197
2197
  function isOurGeneratorName(name) {
@@ -11878,6 +11878,92 @@ function verifySnapshotSignature(snapshotDir) {
11878
11878
  return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
11879
11879
  }
11880
11880
 
11881
+ // src/partitioner/part-format.ts
11882
+ var FILE_HEADING = "### FILE: ";
11883
+ var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
11884
+ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
11885
+ var META_PREFIX = "- Meta: ";
11886
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
11887
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
11888
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
11889
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
11890
+ function readIncludedLines(fields) {
11891
+ const last = fields[fields.length - 1];
11892
+ if (last === void 0) return null;
11893
+ const counts = COMPACT_COUNTS.exec(last.trim());
11894
+ return counts === null ? null : Number(counts[1]);
11895
+ }
11896
+ function parsePartSections(partText) {
11897
+ const lines = partText.split("\n");
11898
+ const sections = [];
11899
+ let index = 0;
11900
+ while (index < lines.length) {
11901
+ if (!lines[index].startsWith(FILE_HEADING)) {
11902
+ index += 1;
11903
+ continue;
11904
+ }
11905
+ const heading = lines[index].slice(FILE_HEADING.length);
11906
+ const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
11907
+ let cursor = index + 1;
11908
+ let inclusion = null;
11909
+ let includedLines = null;
11910
+ while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
11911
+ const line = lines[cursor];
11912
+ if (line.startsWith(FILE_HEADING)) break;
11913
+ if (line.startsWith(META_PREFIX)) {
11914
+ const fields = line.slice(META_PREFIX.length).split("|");
11915
+ for (const field of fields) {
11916
+ const value = field.trim();
11917
+ if (INCLUSION_MODES.has(value)) inclusion = value;
11918
+ }
11919
+ includedLines = readIncludedLines(fields);
11920
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
11921
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
11922
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
11923
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
11924
+ includedLines = Number.isFinite(value) ? value : null;
11925
+ }
11926
+ cursor += 1;
11927
+ }
11928
+ if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
11929
+ index = cursor + 1;
11930
+ continue;
11931
+ }
11932
+ let fenceLine = cursor + 1;
11933
+ while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
11934
+ const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
11935
+ if (!fenceMatch) {
11936
+ index = cursor + 1;
11937
+ continue;
11938
+ }
11939
+ const fence = fenceMatch[1];
11940
+ const body = [];
11941
+ let bodyLine = fenceLine + 1;
11942
+ while (bodyLine < lines.length && lines[bodyLine] !== fence) {
11943
+ body.push(lines[bodyLine]);
11944
+ bodyLine += 1;
11945
+ }
11946
+ sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
11947
+ index = bodyLine + 1;
11948
+ }
11949
+ return sections;
11950
+ }
11951
+ function findSection(sections, relativePath) {
11952
+ const anchor = anchorForPath(relativePath);
11953
+ const byAnchor = sections.find((section) => section.anchor === anchor);
11954
+ if (byAnchor) return byAnchor;
11955
+ const rendered = displayPath(relativePath);
11956
+ const samePath = (section) => section.path === relativePath || section.path === rendered;
11957
+ const exact = sections.find(samePath);
11958
+ if (exact) return exact;
11959
+ const foldedPath = rendered.toLowerCase();
11960
+ const folded = sections.filter((section) => {
11961
+ const path28 = section.path.toLowerCase();
11962
+ return path28 === relativePath.toLowerCase() || path28 === foldedPath;
11963
+ });
11964
+ return folded.length === 1 ? folded[0] : null;
11965
+ }
11966
+
11881
11967
  // src/auditor/health.ts
11882
11968
  var ARTIFACT_FILES = {
11883
11969
  readme: "README.md",
@@ -12187,6 +12273,206 @@ function auditSnapshot(options) {
12187
12273
  )
12188
12274
  );
12189
12275
  }
12276
+ const bookkeeping = [];
12277
+ const expect = (name, recorded2, computed) => {
12278
+ if (recorded2 !== computed) bookkeeping.push(name + ": manifest says " + recorded2 + ", the data has " + computed);
12279
+ };
12280
+ expect("counts.totalFiles", manifest.counts.totalFiles, manifest.files.length);
12281
+ expect("counts.partsCount", manifest.counts.partsCount, manifest.parts.length);
12282
+ expect("counts.skippedCount", manifest.counts.skippedCount, manifest.skipped.length);
12283
+ if (typeof manifest.totals.includedFiles === "number") {
12284
+ expect("totals.includedFiles", manifest.totals.includedFiles, manifest.files.length);
12285
+ }
12286
+ const contentBytes = manifest.files.reduce((sum, file) => sum + file.includedBytes, 0);
12287
+ expect("totals.totalContentBytes", manifest.totals.totalContentBytes, contentBytes);
12288
+ const layerCounts = /* @__PURE__ */ new Map();
12289
+ for (const file of manifest.files) layerCounts.set(file.layer, (layerCounts.get(file.layer) ?? 0) + 1);
12290
+ for (const [layer2, count] of layerCounts) {
12291
+ expect("layers." + layer2, manifest.layers[layer2] ?? -1, count);
12292
+ }
12293
+ for (const layer2 of Object.keys(manifest.layers)) {
12294
+ if (!layerCounts.has(layer2)) expect("layers." + layer2, manifest.layers[layer2], 0);
12295
+ }
12296
+ checks.push(
12297
+ bookkeeping.length === 0 ? check(
12298
+ "bookkeeping",
12299
+ "The counts equal the data they summarise",
12300
+ "critical",
12301
+ "pass",
12302
+ "Files, parts, skips, content bytes and layer counts all agree."
12303
+ ) : check(
12304
+ "bookkeeping",
12305
+ "The counts equal the data they summarise",
12306
+ "critical",
12307
+ "fail",
12308
+ bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
12309
+ )
12310
+ );
12311
+ const packReaders = [
12312
+ {
12313
+ key: "fullJson",
12314
+ file: "full-codebase.json",
12315
+ label: "JSON",
12316
+ paths: (text2) => {
12317
+ try {
12318
+ const parsed = JSON.parse(text2);
12319
+ if (!Array.isArray(parsed?.files)) return null;
12320
+ return new Set(parsed.files.map((entry) => String(entry?.relativePath)));
12321
+ } catch {
12322
+ return null;
12323
+ }
12324
+ }
12325
+ },
12326
+ {
12327
+ key: "fullXml",
12328
+ file: "full-codebase.xml",
12329
+ label: "XML",
12330
+ paths: (text2) => {
12331
+ const found = [...text2.matchAll(/<file path="([^"]+)"/g)].map((match) => match[1]);
12332
+ if (found.length === 0) return null;
12333
+ return new Set(found.map((value) => value.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")));
12334
+ }
12335
+ },
12336
+ {
12337
+ key: "fullMarkdown",
12338
+ file: "full-codebase.md",
12339
+ label: "markdown",
12340
+ paths: (text2) => {
12341
+ const found = [...text2.matchAll(/^## File: (.+)$/gm)].map((match) => match[1].trim());
12342
+ if (found.length === 0) return null;
12343
+ return new Set(found);
12344
+ }
12345
+ }
12346
+ ];
12347
+ for (const reader of packReaders) {
12348
+ if (manifest.artifacts?.[reader.key] == null) continue;
12349
+ const packText = readText2(path16.join(snapshotDir, reader.file));
12350
+ const problems = [];
12351
+ if (packText === null) {
12352
+ problems.push(reader.file + " is recorded but unreadable");
12353
+ } else {
12354
+ const packed = reader.paths(packText);
12355
+ if (packed === null) {
12356
+ problems.push(reader.file + " could not be parsed for its file list");
12357
+ } else {
12358
+ const known2 = new Set(manifest.files.map((file) => file.relativePath));
12359
+ for (const file of manifest.files) {
12360
+ if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
12361
+ }
12362
+ for (const path28 of packed) {
12363
+ if (!known2.has(path28)) problems.push(path28 + " is in the pack but not the manifest");
12364
+ }
12365
+ }
12366
+ }
12367
+ const title = "The " + reader.label + " pack holds every file the manifest lists";
12368
+ checks.push(
12369
+ problems.length === 0 ? check(
12370
+ "pipeline.monolith",
12371
+ title,
12372
+ "critical",
12373
+ "pass",
12374
+ manifest.files.length + " file(s) present in " + reader.file + ", and nothing extra."
12375
+ ) : check(
12376
+ "pipeline.monolith",
12377
+ title,
12378
+ "critical",
12379
+ "fail",
12380
+ problems.length + " problem(s): " + sample(problems)
12381
+ )
12382
+ );
12383
+ }
12384
+ const bodyProblems = [];
12385
+ let bodiesChecked = 0;
12386
+ for (const part of manifest.parts) {
12387
+ const partText = readText2(path16.join(snapshotDir, "parts", part.filename));
12388
+ if (partText === null) continue;
12389
+ const sections = parsePartSections(partText);
12390
+ for (const file of manifest.files) {
12391
+ if (file.part !== part.filename) continue;
12392
+ const section = findSection(sections, file.relativePath);
12393
+ if (section === null) {
12394
+ bodyProblems.push(file.relativePath + " has no section in " + part.filename);
12395
+ continue;
12396
+ }
12397
+ bodiesChecked += 1;
12398
+ const bytes = Buffer.byteLength(section.body, "utf8");
12399
+ const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
12400
+ if (bytes !== file.includedBytes) {
12401
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
12402
+ } else if (bodyLines !== file.includedLines) {
12403
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedLines + " line(s), part holds " + bodyLines);
12404
+ }
12405
+ }
12406
+ }
12407
+ checks.push(
12408
+ bodyProblems.length === 0 ? check(
12409
+ "pipeline.bodies",
12410
+ "Every file body matches the manifest accounting",
12411
+ "critical",
12412
+ "pass",
12413
+ bodiesChecked + " file body/bodies match their recorded bytes and lines."
12414
+ ) : check(
12415
+ "pipeline.bodies",
12416
+ "Every file body matches the manifest accounting",
12417
+ "critical",
12418
+ "fail",
12419
+ bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
12420
+ )
12421
+ );
12422
+ const indexParent = path16.dirname(snapshotDir);
12423
+ const indexPath = path16.join(indexParent, "WORKSPACE.json");
12424
+ if (fs16.existsSync(indexPath)) {
12425
+ const indexText = readText2(indexPath);
12426
+ let members = [];
12427
+ let problem2 = null;
12428
+ try {
12429
+ const parsed = JSON.parse(indexText ?? "null");
12430
+ if (!Array.isArray(parsed?.members)) problem2 = "its members field is not an array";
12431
+ else members = parsed.members;
12432
+ } catch (error) {
12433
+ problem2 = error.message;
12434
+ }
12435
+ const memberName = path16.basename(snapshotDir);
12436
+ const member = members.find((entry) => entry.name === memberName);
12437
+ if (problem2 !== null) {
12438
+ checks.push(check(
12439
+ "workspace.index",
12440
+ "The workspace index agrees with this member",
12441
+ "warning",
12442
+ "warn",
12443
+ "WORKSPACE.json could not be read: " + problem2
12444
+ ));
12445
+ } else if (member === void 0) {
12446
+ checks.push(check(
12447
+ "workspace.index",
12448
+ "The workspace index agrees with this member",
12449
+ "warning",
12450
+ "skip",
12451
+ "WORKSPACE.json lists no member named " + memberName + "."
12452
+ ));
12453
+ } else {
12454
+ const disagreements = [];
12455
+ if (member.fingerprint !== manifest.fingerprint) disagreements.push("fingerprint");
12456
+ if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
12457
+ disagreements.push("file count");
12458
+ }
12459
+ checks.push(
12460
+ disagreements.length === 0 ? check(
12461
+ "workspace.index",
12462
+ "The workspace index agrees with this member",
12463
+ "warning",
12464
+ "pass",
12465
+ "Member " + memberName + " matches the index fingerprint and file count."
12466
+ ) : check(
12467
+ "workspace.index",
12468
+ "The workspace index agrees with this member",
12469
+ "warning",
12470
+ "warn",
12471
+ "The index disagrees with this member on: " + disagreements.join(", ") + ". Regenerate the workspace."
12472
+ )
12473
+ );
12474
+ }
12475
+ }
12190
12476
  const rules = [...compileSecretRules(DEFAULT_SECRET_PATTERNS), ...options.secretRules ?? []];
12191
12477
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
12192
12478
  const leakHits = [];
@@ -12465,90 +12751,6 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12465
12751
  }
12466
12752
 
12467
12753
  // src/mcp/part.ts
12468
- var FILE_HEADING = "### FILE: ";
12469
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
12470
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
12471
- var META_PREFIX = "- Meta: ";
12472
- var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
12473
- var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
12474
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
12475
- var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
12476
- function readIncludedLines(fields) {
12477
- const last = fields[fields.length - 1];
12478
- if (last === void 0) return null;
12479
- const counts = COMPACT_COUNTS.exec(last.trim());
12480
- return counts === null ? null : Number(counts[1]);
12481
- }
12482
- function parsePartSections(partText) {
12483
- const lines = partText.split("\n");
12484
- const sections = [];
12485
- let index = 0;
12486
- while (index < lines.length) {
12487
- if (!lines[index].startsWith(FILE_HEADING)) {
12488
- index += 1;
12489
- continue;
12490
- }
12491
- const heading = lines[index].slice(FILE_HEADING.length);
12492
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
12493
- let cursor = index + 1;
12494
- let inclusion = null;
12495
- let includedLines = null;
12496
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
12497
- const line = lines[cursor];
12498
- if (line.startsWith(FILE_HEADING)) break;
12499
- if (line.startsWith(META_PREFIX)) {
12500
- const fields = line.slice(META_PREFIX.length).split("|");
12501
- for (const field of fields) {
12502
- const value = field.trim();
12503
- if (INCLUSION_MODES.has(value)) inclusion = value;
12504
- }
12505
- includedLines = readIncludedLines(fields);
12506
- } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
12507
- inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
12508
- } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
12509
- const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
12510
- includedLines = Number.isFinite(value) ? value : null;
12511
- }
12512
- cursor += 1;
12513
- }
12514
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
12515
- index = cursor + 1;
12516
- continue;
12517
- }
12518
- let fenceLine = cursor + 1;
12519
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
12520
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
12521
- if (!fenceMatch) {
12522
- index = cursor + 1;
12523
- continue;
12524
- }
12525
- const fence = fenceMatch[1];
12526
- const body = [];
12527
- let bodyLine = fenceLine + 1;
12528
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
12529
- body.push(lines[bodyLine]);
12530
- bodyLine += 1;
12531
- }
12532
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
12533
- index = bodyLine + 1;
12534
- }
12535
- return sections;
12536
- }
12537
- function findSection(sections, relativePath) {
12538
- const anchor = anchorForPath(relativePath);
12539
- const byAnchor = sections.find((section) => section.anchor === anchor);
12540
- if (byAnchor) return byAnchor;
12541
- const rendered = displayPath(relativePath);
12542
- const samePath = (section) => section.path === relativePath || section.path === rendered;
12543
- const exact = sections.find(samePath);
12544
- if (exact) return exact;
12545
- const foldedPath = rendered.toLowerCase();
12546
- const folded = sections.filter((section) => {
12547
- const path28 = section.path.toLowerCase();
12548
- return path28 === relativePath.toLowerCase() || path28 === foldedPath;
12549
- });
12550
- return folded.length === 1 ? folded[0] : null;
12551
- }
12552
12754
  function windowText(body, fromLine, lineCount) {
12553
12755
  const lines = body.split("\n");
12554
12756
  const total = body.length === 0 ? 0 : lines.length;
@@ -20380,12 +20582,25 @@ async function startHttpTransport(options) {
20380
20582
  return fromQuery !== null && timingSafeEqual3(fromQuery, token);
20381
20583
  };
20382
20584
  const sessions = /* @__PURE__ */ new Map();
20585
+ const metrics = {
20586
+ requests: 0,
20587
+ byMethod: /* @__PURE__ */ new Map(),
20588
+ refused: 0,
20589
+ rateLimited: 0,
20590
+ started: Date.now()
20591
+ };
20592
+ const noteRequest = (request) => {
20593
+ metrics.requests += 1;
20594
+ const method = request.method ?? "UNKNOWN";
20595
+ metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
20596
+ };
20383
20597
  const allowedOrigin = (origin) => {
20384
20598
  if (origin === void 0) return null;
20385
20599
  if (isLoopbackOrigin(origin)) return origin;
20386
20600
  return extraOrigins.includes(origin) ? origin : null;
20387
20601
  };
20388
20602
  const httpServer = http3.createServer((request, response) => {
20603
+ noteRequest(request);
20389
20604
  const send = (status, body, extra = {}) => {
20390
20605
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
20391
20606
  response.writeHead(status, {
@@ -20399,6 +20614,7 @@ async function startHttpTransport(options) {
20399
20614
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
20400
20615
  const allowed = allowedOrigin(origin);
20401
20616
  if (origin !== void 0 && allowed === null) {
20617
+ metrics.refused += 1;
20402
20618
  send(403, { error: "origin not allowed" });
20403
20619
  return;
20404
20620
  }
@@ -20428,6 +20644,33 @@ async function startHttpTransport(options) {
20428
20644
  );
20429
20645
  return;
20430
20646
  }
20647
+ if (request.method === "GET" && request.url === "/metrics") {
20648
+ const lines = [
20649
+ "# HELP snapshot_uptime_seconds Seconds since the process started.",
20650
+ "# TYPE snapshot_uptime_seconds gauge",
20651
+ "snapshot_uptime_seconds " + Math.round(process.uptime()),
20652
+ "# HELP snapshot_requests_total HTTP requests received.",
20653
+ "# TYPE snapshot_requests_total counter",
20654
+ "snapshot_requests_total " + metrics.requests,
20655
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
20656
+ "# TYPE snapshot_requests_refused_total counter",
20657
+ "snapshot_requests_refused_total " + metrics.refused,
20658
+ "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
20659
+ "# TYPE snapshot_requests_rate_limited_total counter",
20660
+ "snapshot_requests_rate_limited_total " + metrics.rateLimited,
20661
+ "# HELP snapshot_tools Number of tools this server serves.",
20662
+ "# TYPE snapshot_tools gauge",
20663
+ "snapshot_tools " + toolCount
20664
+ ];
20665
+ for (const [method, count] of metrics.byMethod) {
20666
+ lines.push('snapshot_requests_by_method_total{method="' + method + '"} ' + count);
20667
+ }
20668
+ send(200, lines.join("\n") + "\n", {
20669
+ ...cors,
20670
+ "content-type": "text/plain; version=0.0.4; charset=utf-8"
20671
+ });
20672
+ return;
20673
+ }
20431
20674
  const url = new URL(request.url ?? "/", "http://localhost");
20432
20675
  if (request.method === "GET" && url.pathname === "/sse") {
20433
20676
  if (!tokenAccepted(request, url)) {
@@ -20519,6 +20762,7 @@ async function startHttpTransport(options) {
20519
20762
  const window = sessions.get(remote);
20520
20763
  if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
20521
20764
  else if (window.count >= RATE_LIMIT) {
20765
+ metrics.rateLimited += 1;
20522
20766
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
20523
20767
  return;
20524
20768
  } else window.count += 1;