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.
@@ -3994,7 +3994,7 @@ function applySpansKeepingQuotes(line, spans) {
3994
3994
 
3995
3995
  // src/version.ts
3996
3996
  var GENERATOR_NAME = "codebase-snapshot";
3997
- var GENERATOR_VERSION = "0.13.0";
3997
+ var GENERATOR_VERSION = "0.14.0";
3998
3998
  var SCHEMA_VERSION = "3.0.0";
3999
3999
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4000
4000
  function isOurGeneratorName(name) {
@@ -10039,6 +10039,92 @@ function verifySnapshotSignature(snapshotDir) {
10039
10039
  return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
10040
10040
  }
10041
10041
 
10042
+ // src/partitioner/part-format.ts
10043
+ var FILE_HEADING = "### FILE: ";
10044
+ var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
10045
+ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10046
+ var META_PREFIX = "- Meta: ";
10047
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10048
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10049
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10050
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10051
+ function readIncludedLines(fields) {
10052
+ const last = fields[fields.length - 1];
10053
+ if (last === void 0) return null;
10054
+ const counts = COMPACT_COUNTS.exec(last.trim());
10055
+ return counts === null ? null : Number(counts[1]);
10056
+ }
10057
+ function parsePartSections(partText) {
10058
+ const lines = partText.split("\n");
10059
+ const sections = [];
10060
+ let index = 0;
10061
+ while (index < lines.length) {
10062
+ if (!lines[index].startsWith(FILE_HEADING)) {
10063
+ index += 1;
10064
+ continue;
10065
+ }
10066
+ const heading = lines[index].slice(FILE_HEADING.length);
10067
+ const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
10068
+ let cursor = index + 1;
10069
+ let inclusion = null;
10070
+ let includedLines = null;
10071
+ while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
10072
+ const line = lines[cursor];
10073
+ if (line.startsWith(FILE_HEADING)) break;
10074
+ if (line.startsWith(META_PREFIX)) {
10075
+ const fields = line.slice(META_PREFIX.length).split("|");
10076
+ for (const field of fields) {
10077
+ const value = field.trim();
10078
+ if (INCLUSION_MODES.has(value)) inclusion = value;
10079
+ }
10080
+ includedLines = readIncludedLines(fields);
10081
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10082
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10083
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10084
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
10085
+ includedLines = Number.isFinite(value) ? value : null;
10086
+ }
10087
+ cursor += 1;
10088
+ }
10089
+ if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
10090
+ index = cursor + 1;
10091
+ continue;
10092
+ }
10093
+ let fenceLine = cursor + 1;
10094
+ while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
10095
+ const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
10096
+ if (!fenceMatch) {
10097
+ index = cursor + 1;
10098
+ continue;
10099
+ }
10100
+ const fence = fenceMatch[1];
10101
+ const body = [];
10102
+ let bodyLine = fenceLine + 1;
10103
+ while (bodyLine < lines.length && lines[bodyLine] !== fence) {
10104
+ body.push(lines[bodyLine]);
10105
+ bodyLine += 1;
10106
+ }
10107
+ sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
10108
+ index = bodyLine + 1;
10109
+ }
10110
+ return sections;
10111
+ }
10112
+ function findSection(sections, relativePath) {
10113
+ const anchor = anchorForPath(relativePath);
10114
+ const byAnchor = sections.find((section) => section.anchor === anchor);
10115
+ if (byAnchor) return byAnchor;
10116
+ const rendered = displayPath(relativePath);
10117
+ const samePath = (section) => section.path === relativePath || section.path === rendered;
10118
+ const exact = sections.find(samePath);
10119
+ if (exact) return exact;
10120
+ const foldedPath = rendered.toLowerCase();
10121
+ const folded = sections.filter((section) => {
10122
+ const path26 = section.path.toLowerCase();
10123
+ return path26 === relativePath.toLowerCase() || path26 === foldedPath;
10124
+ });
10125
+ return folded.length === 1 ? folded[0] : null;
10126
+ }
10127
+
10042
10128
  // src/auditor/health.ts
10043
10129
  var ARTIFACT_FILES = {
10044
10130
  readme: "README.md",
@@ -10348,6 +10434,206 @@ function auditSnapshot(options) {
10348
10434
  )
10349
10435
  );
10350
10436
  }
10437
+ const bookkeeping = [];
10438
+ const expect = (name, recorded2, computed) => {
10439
+ if (recorded2 !== computed) bookkeeping.push(name + ": manifest says " + recorded2 + ", the data has " + computed);
10440
+ };
10441
+ expect("counts.totalFiles", manifest.counts.totalFiles, manifest.files.length);
10442
+ expect("counts.partsCount", manifest.counts.partsCount, manifest.parts.length);
10443
+ expect("counts.skippedCount", manifest.counts.skippedCount, manifest.skipped.length);
10444
+ if (typeof manifest.totals.includedFiles === "number") {
10445
+ expect("totals.includedFiles", manifest.totals.includedFiles, manifest.files.length);
10446
+ }
10447
+ const contentBytes = manifest.files.reduce((sum, file) => sum + file.includedBytes, 0);
10448
+ expect("totals.totalContentBytes", manifest.totals.totalContentBytes, contentBytes);
10449
+ const layerCounts = /* @__PURE__ */ new Map();
10450
+ for (const file of manifest.files) layerCounts.set(file.layer, (layerCounts.get(file.layer) ?? 0) + 1);
10451
+ for (const [layer2, count] of layerCounts) {
10452
+ expect("layers." + layer2, manifest.layers[layer2] ?? -1, count);
10453
+ }
10454
+ for (const layer2 of Object.keys(manifest.layers)) {
10455
+ if (!layerCounts.has(layer2)) expect("layers." + layer2, manifest.layers[layer2], 0);
10456
+ }
10457
+ checks.push(
10458
+ bookkeeping.length === 0 ? check(
10459
+ "bookkeeping",
10460
+ "The counts equal the data they summarise",
10461
+ "critical",
10462
+ "pass",
10463
+ "Files, parts, skips, content bytes and layer counts all agree."
10464
+ ) : check(
10465
+ "bookkeeping",
10466
+ "The counts equal the data they summarise",
10467
+ "critical",
10468
+ "fail",
10469
+ bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
10470
+ )
10471
+ );
10472
+ const packReaders = [
10473
+ {
10474
+ key: "fullJson",
10475
+ file: "full-codebase.json",
10476
+ label: "JSON",
10477
+ paths: (text2) => {
10478
+ try {
10479
+ const parsed = JSON.parse(text2);
10480
+ if (!Array.isArray(parsed?.files)) return null;
10481
+ return new Set(parsed.files.map((entry) => String(entry?.relativePath)));
10482
+ } catch {
10483
+ return null;
10484
+ }
10485
+ }
10486
+ },
10487
+ {
10488
+ key: "fullXml",
10489
+ file: "full-codebase.xml",
10490
+ label: "XML",
10491
+ paths: (text2) => {
10492
+ const found = [...text2.matchAll(/<file path="([^"]+)"/g)].map((match) => match[1]);
10493
+ if (found.length === 0) return null;
10494
+ return new Set(found.map((value) => value.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")));
10495
+ }
10496
+ },
10497
+ {
10498
+ key: "fullMarkdown",
10499
+ file: "full-codebase.md",
10500
+ label: "markdown",
10501
+ paths: (text2) => {
10502
+ const found = [...text2.matchAll(/^## File: (.+)$/gm)].map((match) => match[1].trim());
10503
+ if (found.length === 0) return null;
10504
+ return new Set(found);
10505
+ }
10506
+ }
10507
+ ];
10508
+ for (const reader of packReaders) {
10509
+ if (manifest.artifacts?.[reader.key] == null) continue;
10510
+ const packText = readText2(path25.join(snapshotDir, reader.file));
10511
+ const problems = [];
10512
+ if (packText === null) {
10513
+ problems.push(reader.file + " is recorded but unreadable");
10514
+ } else {
10515
+ const packed = reader.paths(packText);
10516
+ if (packed === null) {
10517
+ problems.push(reader.file + " could not be parsed for its file list");
10518
+ } else {
10519
+ const known2 = new Set(manifest.files.map((file) => file.relativePath));
10520
+ for (const file of manifest.files) {
10521
+ if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
10522
+ }
10523
+ for (const path26 of packed) {
10524
+ if (!known2.has(path26)) problems.push(path26 + " is in the pack but not the manifest");
10525
+ }
10526
+ }
10527
+ }
10528
+ const title = "The " + reader.label + " pack holds every file the manifest lists";
10529
+ checks.push(
10530
+ problems.length === 0 ? check(
10531
+ "pipeline.monolith",
10532
+ title,
10533
+ "critical",
10534
+ "pass",
10535
+ manifest.files.length + " file(s) present in " + reader.file + ", and nothing extra."
10536
+ ) : check(
10537
+ "pipeline.monolith",
10538
+ title,
10539
+ "critical",
10540
+ "fail",
10541
+ problems.length + " problem(s): " + sample(problems)
10542
+ )
10543
+ );
10544
+ }
10545
+ const bodyProblems = [];
10546
+ let bodiesChecked = 0;
10547
+ for (const part of manifest.parts) {
10548
+ const partText = readText2(path25.join(snapshotDir, "parts", part.filename));
10549
+ if (partText === null) continue;
10550
+ const sections = parsePartSections(partText);
10551
+ for (const file of manifest.files) {
10552
+ if (file.part !== part.filename) continue;
10553
+ const section = findSection(sections, file.relativePath);
10554
+ if (section === null) {
10555
+ bodyProblems.push(file.relativePath + " has no section in " + part.filename);
10556
+ continue;
10557
+ }
10558
+ bodiesChecked += 1;
10559
+ const bytes = Buffer.byteLength(section.body, "utf8");
10560
+ const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
10561
+ if (bytes !== file.includedBytes) {
10562
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
10563
+ } else if (bodyLines !== file.includedLines) {
10564
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedLines + " line(s), part holds " + bodyLines);
10565
+ }
10566
+ }
10567
+ }
10568
+ checks.push(
10569
+ bodyProblems.length === 0 ? check(
10570
+ "pipeline.bodies",
10571
+ "Every file body matches the manifest accounting",
10572
+ "critical",
10573
+ "pass",
10574
+ bodiesChecked + " file body/bodies match their recorded bytes and lines."
10575
+ ) : check(
10576
+ "pipeline.bodies",
10577
+ "Every file body matches the manifest accounting",
10578
+ "critical",
10579
+ "fail",
10580
+ bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
10581
+ )
10582
+ );
10583
+ const indexParent = path25.dirname(snapshotDir);
10584
+ const indexPath = path25.join(indexParent, "WORKSPACE.json");
10585
+ if (fs24.existsSync(indexPath)) {
10586
+ const indexText = readText2(indexPath);
10587
+ let members = [];
10588
+ let problem2 = null;
10589
+ try {
10590
+ const parsed = JSON.parse(indexText ?? "null");
10591
+ if (!Array.isArray(parsed?.members)) problem2 = "its members field is not an array";
10592
+ else members = parsed.members;
10593
+ } catch (error) {
10594
+ problem2 = error.message;
10595
+ }
10596
+ const memberName = path25.basename(snapshotDir);
10597
+ const member = members.find((entry) => entry.name === memberName);
10598
+ if (problem2 !== null) {
10599
+ checks.push(check(
10600
+ "workspace.index",
10601
+ "The workspace index agrees with this member",
10602
+ "warning",
10603
+ "warn",
10604
+ "WORKSPACE.json could not be read: " + problem2
10605
+ ));
10606
+ } else if (member === void 0) {
10607
+ checks.push(check(
10608
+ "workspace.index",
10609
+ "The workspace index agrees with this member",
10610
+ "warning",
10611
+ "skip",
10612
+ "WORKSPACE.json lists no member named " + memberName + "."
10613
+ ));
10614
+ } else {
10615
+ const disagreements = [];
10616
+ if (member.fingerprint !== manifest.fingerprint) disagreements.push("fingerprint");
10617
+ if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
10618
+ disagreements.push("file count");
10619
+ }
10620
+ checks.push(
10621
+ disagreements.length === 0 ? check(
10622
+ "workspace.index",
10623
+ "The workspace index agrees with this member",
10624
+ "warning",
10625
+ "pass",
10626
+ "Member " + memberName + " matches the index fingerprint and file count."
10627
+ ) : check(
10628
+ "workspace.index",
10629
+ "The workspace index agrees with this member",
10630
+ "warning",
10631
+ "warn",
10632
+ "The index disagrees with this member on: " + disagreements.join(", ") + ". Regenerate the workspace."
10633
+ )
10634
+ );
10635
+ }
10636
+ }
10351
10637
  const rules = [...compileSecretRules(DEFAULT_SECRET_PATTERNS), ...options.secretRules ?? []];
10352
10638
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
10353
10639
  const leakHits = [];
@@ -10859,90 +11145,6 @@ function generateInWorker(cwd, cliOptions, options = {}) {
10859
11145
  }
10860
11146
 
10861
11147
  // src/mcp/part.ts
10862
- var FILE_HEADING = "### FILE: ";
10863
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
10864
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10865
- var META_PREFIX = "- Meta: ";
10866
- var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10867
- var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10868
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10869
- var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10870
- function readIncludedLines(fields) {
10871
- const last = fields[fields.length - 1];
10872
- if (last === void 0) return null;
10873
- const counts = COMPACT_COUNTS.exec(last.trim());
10874
- return counts === null ? null : Number(counts[1]);
10875
- }
10876
- function parsePartSections(partText) {
10877
- const lines = partText.split("\n");
10878
- const sections = [];
10879
- let index = 0;
10880
- while (index < lines.length) {
10881
- if (!lines[index].startsWith(FILE_HEADING)) {
10882
- index += 1;
10883
- continue;
10884
- }
10885
- const heading = lines[index].slice(FILE_HEADING.length);
10886
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
10887
- let cursor = index + 1;
10888
- let inclusion = null;
10889
- let includedLines = null;
10890
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
10891
- const line = lines[cursor];
10892
- if (line.startsWith(FILE_HEADING)) break;
10893
- if (line.startsWith(META_PREFIX)) {
10894
- const fields = line.slice(META_PREFIX.length).split("|");
10895
- for (const field of fields) {
10896
- const value = field.trim();
10897
- if (INCLUSION_MODES.has(value)) inclusion = value;
10898
- }
10899
- includedLines = readIncludedLines(fields);
10900
- } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10901
- inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10902
- } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10903
- const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
10904
- includedLines = Number.isFinite(value) ? value : null;
10905
- }
10906
- cursor += 1;
10907
- }
10908
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
10909
- index = cursor + 1;
10910
- continue;
10911
- }
10912
- let fenceLine = cursor + 1;
10913
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
10914
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
10915
- if (!fenceMatch) {
10916
- index = cursor + 1;
10917
- continue;
10918
- }
10919
- const fence = fenceMatch[1];
10920
- const body = [];
10921
- let bodyLine = fenceLine + 1;
10922
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
10923
- body.push(lines[bodyLine]);
10924
- bodyLine += 1;
10925
- }
10926
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
10927
- index = bodyLine + 1;
10928
- }
10929
- return sections;
10930
- }
10931
- function findSection(sections, relativePath) {
10932
- const anchor = anchorForPath(relativePath);
10933
- const byAnchor = sections.find((section) => section.anchor === anchor);
10934
- if (byAnchor) return byAnchor;
10935
- const rendered = displayPath(relativePath);
10936
- const samePath = (section) => section.path === relativePath || section.path === rendered;
10937
- const exact = sections.find(samePath);
10938
- if (exact) return exact;
10939
- const foldedPath = rendered.toLowerCase();
10940
- const folded = sections.filter((section) => {
10941
- const path26 = section.path.toLowerCase();
10942
- return path26 === relativePath.toLowerCase() || path26 === foldedPath;
10943
- });
10944
- return folded.length === 1 ? folded[0] : null;
10945
- }
10946
11148
  function windowText(body, fromLine, lineCount) {
10947
11149
  const lines = body.split("\n");
10948
11150
  const total = body.length === 0 ? 0 : lines.length;
@@ -1,4 +1,4 @@
1
- import { createServer, buildTools, GENERATOR_VERSION } from './chunk-BOJYZQFB.js';
1
+ import { createServer, buildTools, GENERATOR_VERSION } from './chunk-2YNQ42B3.js';
2
2
  import * as http from 'http';
3
3
  import * as crypto from 'crypto';
4
4
 
@@ -49,12 +49,23 @@ async function startHttpTransport(options) {
49
49
  return fromQuery !== null && timingSafeEqual2(fromQuery, token);
50
50
  };
51
51
  const sessions = /* @__PURE__ */ new Map();
52
+ const metrics = {
53
+ requests: 0,
54
+ byMethod: /* @__PURE__ */ new Map(),
55
+ refused: 0,
56
+ rateLimited: 0};
57
+ const noteRequest = (request) => {
58
+ metrics.requests += 1;
59
+ const method = request.method ?? "UNKNOWN";
60
+ metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
61
+ };
52
62
  const allowedOrigin = (origin) => {
53
63
  if (origin === void 0) return null;
54
64
  if (isLoopbackOrigin(origin)) return origin;
55
65
  return extraOrigins.includes(origin) ? origin : null;
56
66
  };
57
67
  const httpServer = http.createServer((request, response) => {
68
+ noteRequest(request);
58
69
  const send = (status, body, extra = {}) => {
59
70
  const text = typeof body === "string" ? body : JSON.stringify(body);
60
71
  response.writeHead(status, {
@@ -68,6 +79,7 @@ async function startHttpTransport(options) {
68
79
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
69
80
  const allowed = allowedOrigin(origin);
70
81
  if (origin !== void 0 && allowed === null) {
82
+ metrics.refused += 1;
71
83
  send(403, { error: "origin not allowed" });
72
84
  return;
73
85
  }
@@ -97,6 +109,33 @@ async function startHttpTransport(options) {
97
109
  );
98
110
  return;
99
111
  }
112
+ if (request.method === "GET" && request.url === "/metrics") {
113
+ const lines = [
114
+ "# HELP snapshot_uptime_seconds Seconds since the process started.",
115
+ "# TYPE snapshot_uptime_seconds gauge",
116
+ "snapshot_uptime_seconds " + Math.round(process.uptime()),
117
+ "# HELP snapshot_requests_total HTTP requests received.",
118
+ "# TYPE snapshot_requests_total counter",
119
+ "snapshot_requests_total " + metrics.requests,
120
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
121
+ "# TYPE snapshot_requests_refused_total counter",
122
+ "snapshot_requests_refused_total " + metrics.refused,
123
+ "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
124
+ "# TYPE snapshot_requests_rate_limited_total counter",
125
+ "snapshot_requests_rate_limited_total " + metrics.rateLimited,
126
+ "# HELP snapshot_tools Number of tools this server serves.",
127
+ "# TYPE snapshot_tools gauge",
128
+ "snapshot_tools " + toolCount
129
+ ];
130
+ for (const [method, count] of metrics.byMethod) {
131
+ lines.push('snapshot_requests_by_method_total{method="' + method + '"} ' + count);
132
+ }
133
+ send(200, lines.join("\n") + "\n", {
134
+ ...cors,
135
+ "content-type": "text/plain; version=0.0.4; charset=utf-8"
136
+ });
137
+ return;
138
+ }
100
139
  const url = new URL(request.url ?? "/", "http://localhost");
101
140
  if (request.method === "GET" && url.pathname === "/sse") {
102
141
  if (!tokenAccepted(request, url)) {
@@ -188,6 +227,7 @@ async function startHttpTransport(options) {
188
227
  const window = sessions.get(remote);
189
228
  if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
190
229
  else if (window.count >= RATE_LIMIT) {
230
+ metrics.rateLimited += 1;
191
231
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
192
232
  return;
193
233
  } else window.count += 1;