veoflow 0.4.1 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/veo.mjs CHANGED
@@ -181,6 +181,8 @@ function classify(path) {
181
181
  function unsupportedLanguage(path) {
182
182
  const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
183
183
  if (name.endsWith(".component.html")) return "Angular template";
184
+ if (name === "dockerfile" || name.startsWith("dockerfile.") || name.endsWith(".dockerfile"))
185
+ return "Docker";
184
186
  const dot = name.lastIndexOf(".");
185
187
  return dot > 0 ? UNSUPPORTED[name.slice(dot + 1)] ?? null : null;
186
188
  }
@@ -244,7 +246,15 @@ var init_classify = __esm({
244
246
  hs: "Haskell",
245
247
  lua: "Lua",
246
248
  pl: "Perl",
247
- astro: "Astro"
249
+ astro: "Astro",
250
+ html: "HTML",
251
+ htm: "HTML",
252
+ css: "CSS",
253
+ scss: "CSS",
254
+ sass: "CSS",
255
+ less: "CSS",
256
+ tf: "Terraform",
257
+ hcl: "HCL"
248
258
  };
249
259
  utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
250
260
  }
@@ -292,7 +302,7 @@ function literalPrefix(pattern) {
292
302
  return i < 0 ? p : p.slice(0, i);
293
303
  }
294
304
  function defaultExcludedFile(path) {
295
- return /\.timestamp-\d+(?:-[0-9a-f]+)?\.[cm]?[jt]s$/i.test(path) ? "generated" : null;
305
+ return /\.timestamp-\d+(?:-[0-9a-f]+)?\.[cm]?[jt]s$/i.test(path) || /[.-]min\.[cm]?js$|\.bundle\.[cm]?js$/i.test(path) ? "generated" : null;
296
306
  }
297
307
  function defaultExcludedDir(path) {
298
308
  const parts = path.split("/");
@@ -369,6 +379,11 @@ var init_glob = __esm({
369
379
  ".svn",
370
380
  "node_modules",
371
381
  "bower_components",
382
+ // Vendored third-party code (#261, plan D57): Yarn's releases and plugins, vendor/, third_party/.
383
+ ".yarn",
384
+ "vendor",
385
+ "third_party",
386
+ "third-party",
372
387
  "dist",
373
388
  "build",
374
389
  "out",
@@ -385,7 +400,16 @@ var init_glob = __esm({
385
400
  ...TOOL_DIRS
386
401
  ]);
387
402
  VCS_DIRS = /* @__PURE__ */ new Set([".git", ".hg", ".svn"]);
388
- LIBRARY_DIRS = /* @__PURE__ */ new Set(["node_modules", "bower_components", ".venv", "venv"]);
403
+ LIBRARY_DIRS = /* @__PURE__ */ new Set([
404
+ "node_modules",
405
+ "bower_components",
406
+ ".venv",
407
+ "venv",
408
+ ".yarn",
409
+ "vendor",
410
+ "third_party",
411
+ "third-party"
412
+ ]);
389
413
  OptIn = class {
390
414
  paths;
391
415
  anchored;
@@ -643,7 +667,7 @@ function sha256File(abs) {
643
667
  }
644
668
  return hash2.digest("hex");
645
669
  }
646
- function fileFromBytes(path, language, bytes, maxFileBytes) {
670
+ function fileFromBytes(path, language, bytes, maxFileBytes, optedIn = false) {
647
671
  const file2 = { path, language, size: bytes.length, contentHash: sha256(bytes) };
648
672
  const skip = languageSkip(path, language);
649
673
  if (skip) return { ...file2, skip };
@@ -651,8 +675,24 @@ function fileFromBytes(path, language, bytes, maxFileBytes) {
651
675
  if (looksBinary(bytes)) return { ...file2, skip: "binary" };
652
676
  const content = decodeUtf8(bytes);
653
677
  if (content === null) return { ...file2, skip: "invalid-utf8" };
678
+ if (!optedIn && (language === "javascript" || language === "jsx") && looksMinified(content))
679
+ return { ...file2, skip: "minified" };
654
680
  return { ...file2, content };
655
681
  }
682
+ function looksMinified(content) {
683
+ if (content.length < MINIFIED_MIN_BYTES) return false;
684
+ let long = 0;
685
+ let space = 0;
686
+ for (const line of content.split("\n"))
687
+ if (line.length > 1e3) {
688
+ long += line.length;
689
+ for (let i = 0; i < line.length; i++) {
690
+ const c = line.charCodeAt(i);
691
+ if (c === 32 || c === 9 || c === 13) space++;
692
+ }
693
+ }
694
+ return long > content.length / 2 && space < long * 0.08;
695
+ }
656
696
  function planSource(source, options = {}) {
657
697
  const maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
658
698
  const hardMax = Math.max(maxFileBytes, options.hardMaxFileBytes ?? HARD_MAX_FILE_BYTES);
@@ -712,8 +752,74 @@ function planSource(source, options = {}) {
712
752
  plan.notices.push("No JavaScript or TypeScript files were found.");
713
753
  const unsupported = unsupportedNotice(plan.unsupported);
714
754
  if (unsupported) plan.notices.push(unsupported);
755
+ const minified = plan.files.filter((f) => f.skip === "minified").length;
756
+ if (minified)
757
+ plan.notices.push(
758
+ `${minified} minified file${minified === 1 ? " is" : "s are"} not analyzed (built output); choose ${minified === 1 ? "it" : "them"} to analyze anyway.`
759
+ );
760
+ const unread = unreadNotice(plan.files);
761
+ if (unread) plan.notices.push(unread);
762
+ const tooLarge = plan.files.filter((f) => f.skip === "too-large");
763
+ const choosable = tooLarge.filter((f) => f.size <= hardMax).length;
764
+ const never2 = tooLarge.length - choosable;
765
+ if (choosable)
766
+ plan.notices.push(
767
+ `${count(choosable, "file")} over the ${megabytes(maxFileBytes)} size limit ${choosable === 1 ? "is" : "are"} not analyzed; choose ${choosable === 1 ? "it" : "them"} to analyze anyway (up to ${megabytes(hardMax)}).`
768
+ );
769
+ if (never2)
770
+ plan.notices.push(
771
+ `${count(never2, "file")} over ${megabytes(hardMax)} ${never2 === 1 ? "is" : "are"} never analyzed.`
772
+ );
773
+ const ignored = ignoredSourceFolders(source.root, plan.unpinned);
774
+ if (ignored.length)
775
+ plan.notices.push(
776
+ `${ignored.length === 1 ? `${ignored[0]} holds source files but is` : `${ignored.length} folders holding source files (${ignored.slice(0, 3).join(", ")}${ignored.length > 3 ? ", \u2026" : ""}) are`} left out by .gitignore, so ${ignored.length === 1 ? "it isn't" : "they aren't"} in the commit and ${ignored.length === 1 ? "isn't" : "aren't"} analyzed.`
777
+ );
715
778
  return plan;
716
779
  }
780
+ function unreadNotice(files) {
781
+ const by = /* @__PURE__ */ new Map();
782
+ for (const f of files)
783
+ if (f.skip === "language-not-analyzed") {
784
+ const name = LANGUAGE_NAMES[f.language] ?? f.language;
785
+ by.set(name, (by.get(name) ?? 0) + 1);
786
+ }
787
+ if (!by.size) return null;
788
+ const parts = [...by].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([name, n]) => `${n.toLocaleString("en-US")} ${name} ${n === 1 ? "file" : "files"}`);
789
+ const list = parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
790
+ const total = [...by.values()].reduce((a, b) => a + b, 0);
791
+ return `${list} ${total === 1 ? "is" : "are"} listed but not analyzed yet: veoflow analyzes JavaScript and TypeScript (with Vue, Svelte and Angular components) today.`;
792
+ }
793
+ function ignoredSourceFolders(root, unpinned) {
794
+ const out = [];
795
+ for (const u of unpinned) {
796
+ if (u.reason !== "gitignored" || !u.path.endsWith("/")) continue;
797
+ const rel = u.path.slice(0, -1);
798
+ if (rel.split("/").some(
799
+ (part) => DEFAULT_EXCLUDED_DIRS.has(part) || OUTPUT_FOLDERS.has(part.toLowerCase()) || part.startsWith(".")
800
+ ))
801
+ continue;
802
+ let budget = 2e3;
803
+ const holds = (dir) => {
804
+ let entries;
805
+ try {
806
+ entries = readdirSync(dir, { withFileTypes: true });
807
+ } catch {
808
+ return false;
809
+ }
810
+ for (const e of entries) {
811
+ if (--budget < 0) return false;
812
+ if (e.isFile() && classify(e.name)) return true;
813
+ if (e.isDirectory() && !e.isSymbolicLink() && !DEFAULT_EXCLUDED_DIRS.has(e.name) && !e.name.startsWith(".")) {
814
+ if (holds(join2(dir, e.name))) return true;
815
+ }
816
+ }
817
+ return false;
818
+ };
819
+ if (holds(join2(root, ...rel.split("/")))) out.push(u.path);
820
+ }
821
+ return out;
822
+ }
717
823
  function isSourcePath(rel) {
718
824
  return classify(rel) !== null || rel.toLowerCase().endsWith(".html");
719
825
  }
@@ -996,7 +1102,7 @@ function planGit(source, top, prefix, head, branch, filter, maxFileBytes, hardMa
996
1102
  });
997
1103
  continue;
998
1104
  } else {
999
- planned = fileFromBytes(f.rel, f.language, bytes, limit(f));
1105
+ planned = fileFromBytes(f.rel, f.language, bytes, limit(f), optIn.covers(f.rel));
1000
1106
  }
1001
1107
  if (f.commit) planned.commit = f.commit;
1002
1108
  if (f.origin) planned.origin = f.origin;
@@ -1196,7 +1302,7 @@ function planPlain(source, filter, maxFileBytes, hardMax, onlyPaths) {
1196
1302
  plan.files.push({ path: rel, language, size: st.size, contentHash: "", skip: "unreadable" });
1197
1303
  continue;
1198
1304
  }
1199
- plan.files.push(fileFromBytes(rel, language, bytes, limit(rel)));
1305
+ plan.files.push(fileFromBytes(rel, language, bytes, limit(rel), optIn.covers(rel)));
1200
1306
  }
1201
1307
  };
1202
1308
  walk(source.root, rootReal, false);
@@ -1261,7 +1367,7 @@ function planPlain(source, filter, maxFileBytes, hardMax, onlyPaths) {
1261
1367
  plan.revision = `sha256:${sha256(lines.join(""))}`;
1262
1368
  return plan;
1263
1369
  }
1264
- var RULE_EXCLUDED_LIMIT, RuleExcludedCollector, DEFAULT_MAX_FILE_BYTES, HARD_MAX_FILE_BYTES, RESOLVER_MANIFEST, RESOLVER_INPUT, UnsupportedCounter, WORKSPACE_FILES;
1370
+ var RULE_EXCLUDED_LIMIT, RuleExcludedCollector, DEFAULT_MAX_FILE_BYTES, HARD_MAX_FILE_BYTES, RESOLVER_MANIFEST, RESOLVER_INPUT, MINIFIED_MIN_BYTES, count, megabytes, OUTPUT_FOLDERS, LANGUAGE_NAMES, UnsupportedCounter, WORKSPACE_FILES;
1265
1371
  var init_plan = __esm({
1266
1372
  "packages/planner/src/plan.ts"() {
1267
1373
  "use strict";
@@ -1303,6 +1409,35 @@ var init_plan = __esm({
1303
1409
  HARD_MAX_FILE_BYTES = 64 * 1024 * 1024;
1304
1410
  RESOLVER_MANIFEST = /(^|\/)(package\.json|(ts|js)config[^/]*\.json|package-lock\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|\.npmrc|\.yarnrc\.yml)$/;
1305
1411
  RESOLVER_INPUT = /\.(json|jsonc|lock|ya?ml|toml|mod|sum)$|(^|\/)(\.npmrc|\.nvmrc|\.babelrc)$/i;
1412
+ MINIFIED_MIN_BYTES = 2e4;
1413
+ count = (n, noun) => `${n.toLocaleString("en-US")} ${noun}${n === 1 ? "" : "s"}`;
1414
+ megabytes = (bytes) => `${Number((bytes / (1024 * 1024)).toFixed(2))} MB`;
1415
+ OUTPUT_FOLDERS = /* @__PURE__ */ new Set([
1416
+ "lib",
1417
+ "esm",
1418
+ "cjs",
1419
+ "es",
1420
+ "types",
1421
+ "typings",
1422
+ "public",
1423
+ "storybook-static",
1424
+ "cdk.out",
1425
+ "env",
1426
+ "htmlcov",
1427
+ "site",
1428
+ "_site",
1429
+ "out-tsc",
1430
+ "tmp",
1431
+ "temp",
1432
+ "cache",
1433
+ "generated",
1434
+ "gen",
1435
+ "artifacts",
1436
+ "release",
1437
+ "releases",
1438
+ "docs"
1439
+ ]);
1440
+ LANGUAGE_NAMES = { python: "Python", go: "Go", rust: "Rust" };
1306
1441
  UnsupportedCounter = class {
1307
1442
  counts = /* @__PURE__ */ new Map();
1308
1443
  add(path) {
@@ -1360,6 +1495,8 @@ function listDirectory(source, dir, options = {}) {
1360
1495
  else if (e.kind === "dir" ? filter.excludesDir(e.path) || filter.includesNothingIn(e.path) : !filter.matches(e.path))
1361
1496
  entry.excludedBy = "rule";
1362
1497
  else if (e.kind === "file" && (e.size ?? 0) > maxFileBytes) entry.excludedBy = "too-large";
1498
+ else if (mayBeMinified(entry) && options.skipped?.(e.path) === "minified")
1499
+ entry.excludedBy = "minified";
1363
1500
  } else if (entry.notAnalyzable === "over-hard-cap") entry.excludedBy = "too-large";
1364
1501
  entries.push(entry);
1365
1502
  }
@@ -1445,25 +1582,26 @@ function applySelection(source, paths, selected, options = {}) {
1445
1582
  `${path} can't be analyzed (${first.notAnalyzable === "over-hard-cap" ? "it is over the 64 MB cap" : first.notAnalyzable === "symlink" ? "it is a symbolic link" : "type declarations are not analyzed"})`,
1446
1583
  { fields: ["paths"] }
1447
1584
  );
1448
- const inside = (p) => p === path || p.startsWith(`${path}/`);
1585
+ const inside2 = (p) => p === path || p.startsWith(`${path}/`);
1449
1586
  const written = (rule) => {
1450
1587
  const r = rule.replace(/^\/+/, "").replace(/\/+$/, "");
1451
- return rule.startsWith("/") && (kind === "dir" ? inside(r) : r === path);
1588
+ return rule.startsWith("/") && (kind === "dir" ? inside2(r) : r === path);
1452
1589
  };
1453
1590
  if (selected) {
1454
1591
  rules = { ...rules, exclude: rules.exclude.filter((r) => !written(r)) };
1455
- if (entry().excludedBy) rules = { ...rules, optIn: [...rules.optIn.filter((p) => !inside(p)), path] };
1456
- for (const o of rules.optIn.filter((p) => p !== path && inside(p))) {
1592
+ if (entry().excludedBy) rules = { ...rules, optIn: [...rules.optIn.filter((p) => !inside2(p)), path] };
1593
+ for (const o of rules.optIn.filter((p) => p !== path && inside2(p))) {
1457
1594
  const without = { ...rules, optIn: rules.optIn.filter((p) => p !== o) };
1458
1595
  let needed = false;
1459
1596
  try {
1460
- needed = !!find({ ...source, ...without }, o, options).excludedBy;
1597
+ const below = find({ ...source, ...without }, o, options);
1598
+ needed = !!below.excludedBy || mayBeMinified(below);
1461
1599
  } catch {
1462
1600
  }
1463
1601
  if (!needed) rules = without;
1464
1602
  }
1465
1603
  } else {
1466
- rules = { ...rules, optIn: rules.optIn.filter((p) => !inside(p)) };
1604
+ rules = { ...rules, optIn: rules.optIn.filter((p) => !inside2(p)) };
1467
1605
  if (!entry().excludedBy)
1468
1606
  rules = { ...rules, exclude: [...rules.exclude, kind === "dir" ? `/${path}/` : `/${path}`] };
1469
1607
  }
@@ -1481,7 +1619,7 @@ function find(source, path, options) {
1481
1619
  });
1482
1620
  return entry;
1483
1621
  }
1484
- var notFound;
1622
+ var notFound, mayBeMinified;
1485
1623
  var init_browse = __esm({
1486
1624
  "packages/planner/src/browse.ts"() {
1487
1625
  "use strict";
@@ -1494,6 +1632,7 @@ var init_browse = __esm({
1494
1632
  kind: "folder",
1495
1633
  id: dir
1496
1634
  });
1635
+ mayBeMinified = (e) => e.kind === "file" && (e.language === "javascript" || e.language === "jsx") && (e.size ?? 0) >= MINIFIED_MIN_BYTES;
1497
1636
  }
1498
1637
  });
1499
1638
 
@@ -1685,6 +1824,7 @@ var init_project_store = __esm({
1685
1824
  };
1686
1825
  SCHEMA = `
1687
1826
  CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
1827
+ CREATE TABLE IF NOT EXISTS run_summaries (run INTEGER NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (run, key));
1688
1828
  CREATE TABLE IF NOT EXISTS runs (
1689
1829
  run_id INTEGER PRIMARY KEY,
1690
1830
  kind TEXT NOT NULL,
@@ -1787,6 +1927,16 @@ CREATE TABLE IF NOT EXISTS lock (
1787
1927
  const within = this.stages ? stages.filter((s) => this.stages.includes(s)) : stages;
1788
1928
  return new _GraphReader(this.#db, this.run, within, this.base);
1789
1929
  }
1930
+ /**
1931
+ * The scopes a stage's visible facts are written under (#259), read through
1932
+ * the scope index: a stage finds what it wrote without reading other facts.
1933
+ */
1934
+ scopesOf(stage) {
1935
+ if (!STAGE_NAME.test(stage)) throw new Error(`invalid stage name ${JSON.stringify(stage)}`);
1936
+ if (this.stages && !this.stages.includes(stage)) return [];
1937
+ const sql = `SELECT DISTINCT scope FROM facts INDEXED BY facts_by_scope WHERE stage = :stage AND ${visibleAt(this.base === void 0 ? { run: this.run } : { run: this.run, base: this.base })} ORDER BY scope`;
1938
+ return this.#db.prepare(sql).all({ stage, ...this.pin }).map((r) => r.scope);
1939
+ }
1790
1940
  rows(where, params) {
1791
1941
  const sql = `SELECT payload, rev FROM facts WHERE ${this.visible} AND ${where} ORDER BY id`;
1792
1942
  return this.#db.prepare(sql).all({ ...params, ...this.pin }).map((r) => {
@@ -1995,6 +2145,16 @@ CREATE TABLE IF NOT EXISTS lock (
1995
2145
  const row = this.#db.prepare("SELECT * FROM runs WHERE run_id = ?").get(runId);
1996
2146
  return row ? toRunInfo(row) : void 0;
1997
2147
  }
2148
+ runSummary(runId, key) {
2149
+ const row = this.#db.prepare("SELECT value FROM run_summaries WHERE run = ? AND key = ?").get(runId, key);
2150
+ return row ? JSON.parse(row.value) : void 0;
2151
+ }
2152
+ setRunSummary(runId, key, value) {
2153
+ transaction(this.#db, () => {
2154
+ if (this.runInfo(runId)?.status !== "committed") throw new Error(`run ${runId} is not committed`);
2155
+ this.#db.prepare("INSERT OR REPLACE INTO run_summaries (run, key, value) VALUES (?, ?, ?)").run(runId, key, JSON.stringify(value));
2156
+ });
2157
+ }
1998
2158
  /**
1999
2159
  * Fail any run left `running` by a process that no longer exists (e.g. it
2000
2160
  * was killed), undoing its writes. Returns the recovered run ids.
@@ -2099,6 +2259,7 @@ CREATE TABLE IF NOT EXISTS lock (
2099
2259
  this.#db.prepare("DELETE FROM facts WHERE side = ?").run(run_id);
2100
2260
  this.#db.prepare("DELETE FROM side_closed WHERE run = ?").run(run_id);
2101
2261
  this.#db.prepare("DELETE FROM runs WHERE run_id = ?").run(run_id);
2262
+ this.#db.prepare("DELETE FROM run_summaries WHERE run = ?").run(run_id);
2102
2263
  }
2103
2264
  return drafts.length;
2104
2265
  }
@@ -2310,6 +2471,7 @@ CREATE TABLE IF NOT EXISTS lock (
2310
2471
  this.#db.prepare("DELETE FROM side_closed WHERE run IN (SELECT value FROM json_each(:dropped))").run({ dropped: droppedSide });
2311
2472
  const ids2 = JSON.stringify(drop.map((r) => r.runId));
2312
2473
  this.#db.prepare("DELETE FROM runs WHERE run_id IN (SELECT value FROM json_each(?))").run(ids2);
2474
+ this.#db.prepare("DELETE FROM run_summaries WHERE run IN (SELECT value FROM json_each(?))").run(ids2);
2313
2475
  this.#db.prepare("DELETE FROM reader_pins WHERE expires_at <= ?").run(at);
2314
2476
  return {
2315
2477
  runs: drop.map((r) => r.runId),
@@ -3634,7 +3796,7 @@ var PROTOCOL_VERSION;
3634
3796
  var init_protocol = __esm({
3635
3797
  "protocol/index.ts"() {
3636
3798
  "use strict";
3637
- PROTOCOL_VERSION = "1.5.0";
3799
+ PROTOCOL_VERSION = "1.7.0";
3638
3800
  }
3639
3801
  });
3640
3802
 
@@ -3746,6 +3908,8 @@ function factsForFile(sourceId, file2, result2) {
3746
3908
  status: u.status,
3747
3909
  importSpecifier: u.importSpecifier,
3748
3910
  importedName: u.importedName,
3911
+ // A method of what an imported class makes (#281): only with its receiver.
3912
+ ...u.receiver && u.member ? { member: u.member, receiver: u.receiver } : {},
3749
3913
  evidence: evidence(u.site)
3750
3914
  };
3751
3915
  facts.push(site);
@@ -3935,7 +4099,7 @@ var init_stage1 = __esm({
3935
4099
  init_src4();
3936
4100
  init_protocol();
3937
4101
  STAGE1 = "stage1";
3938
- QUIET_SKIPS = /* @__PURE__ */ new Set(["language-not-analyzed", "declaration-file", "entitlement"]);
4102
+ QUIET_SKIPS = /* @__PURE__ */ new Set(["language-not-analyzed", "declaration-file", "entitlement", "minified"]);
3939
4103
  byOffset = (a, b) => a.site.start.offset - b.site.start.offset || a.site.end.offset - b.site.end.offset;
3940
4104
  BATCH_BYTES2 = 32 << 20;
3941
4105
  stage1 = { name: STAGE1, run: runStage1 };
@@ -3963,12 +4127,7 @@ function runTemplateLink(ctx) {
3963
4127
  scopes.add(scope);
3964
4128
  facts.push({ scope, fact });
3965
4129
  };
3966
- for (const e of view.facts("CALLS_CROSS_FILE"))
3967
- if (e.via === "template-link") scopes.add(scopeOf(`${e.evidence.file}|${e.component}`));
3968
- for (const u of view.facts("UnresolvedCallSite"))
3969
- if (u.component) scopes.add(scopeOf(`${u.file}|${u.component}`));
3970
- for (const f of view.facts("Finding"))
3971
- if (f.id.startsWith(`${TEMPLATE_LINK}|`)) scopes.add(scopeOf(f.component ?? f.file));
4130
+ for (const scope of view.scopesOf(TEMPLATE_LINK)) scopes.add(scope);
3972
4131
  const roots = ctx.plans.map((p) => ({
3973
4132
  source: p.sourceId,
3974
4133
  root: p.root,
@@ -3999,9 +4158,9 @@ function runTemplateLink(ctx) {
3999
4158
  if (ownerRoot) {
4000
4159
  const abs = join8(ownerRoot.root, ...owner.path.split("/").slice(0, -1), ...d.specifier.split("/"));
4001
4160
  for (const r of roots) {
4002
- const inside = relative2(r.root, abs);
4003
- if (inside && !inside.startsWith("..") && !inside.startsWith(sep4) && !/^[a-zA-Z]:/.test(inside)) {
4004
- const inRel = inside.split(sep4).join("/");
4161
+ const inside2 = relative2(r.root, abs);
4162
+ if (inside2 && !inside2.startsWith("..") && !inside2.startsWith(sep4) && !/^[a-zA-Z]:/.test(inside2)) {
4163
+ const inRel = inside2.split(sep4).join("/");
4005
4164
  const file2 = fileById.get(ids.file(r.source, inRel));
4006
4165
  if (file2)
4007
4166
  return file2.language === "angular-template" ? { kind: "file", file: file2 } : { kind: "not-analyzed" };
@@ -4276,6 +4435,7 @@ var init_engine = __esm({
4276
4435
  slug2 = (s) => s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-.]+|-+$/g, "").slice(0, 48) || "source";
4277
4436
  LICENSE_FINDINGS = /* @__PURE__ */ new Set(["license", "entitlement", "frozen"]);
4278
4437
  Engine = class {
4438
+ afterCommit;
4279
4439
  catalog;
4280
4440
  /** Run events from every project (run.started, stage.completed, ...). */
4281
4441
  events = new EventEmitter();
@@ -4307,6 +4467,7 @@ var init_engine = __esm({
4307
4467
  this.repository = options.repository ?? new GraphRepository();
4308
4468
  this.license = options.license ?? {};
4309
4469
  this.runner = options.runner;
4470
+ this.afterCommit = options.afterCommit;
4310
4471
  if (options.runner && options.repository)
4311
4472
  throw new Error(
4312
4473
  "a runner's run processes use the SQLite backend: give a runner or a repository, not both"
@@ -4397,6 +4558,20 @@ var init_engine = __esm({
4397
4558
  }
4398
4559
  // -------------------------------------------------------------------------
4399
4560
  // projects and sources
4561
+ /** A folder's git repository top, or null for a plain folder; kept, since it rarely changes. */
4562
+ repoTops = /* @__PURE__ */ new Map();
4563
+ repoTop(root) {
4564
+ let top = this.repoTops.get(root);
4565
+ if (top === void 0) {
4566
+ try {
4567
+ top = repoInfo(root)?.top ?? null;
4568
+ } catch {
4569
+ top = null;
4570
+ }
4571
+ this.repoTops.set(root, top);
4572
+ }
4573
+ return top;
4574
+ }
4400
4575
  listProjects() {
4401
4576
  return {
4402
4577
  projects: this.catalog.listProjects().map((p) => {
@@ -4408,6 +4583,9 @@ var init_engine = __esm({
4408
4583
  try {
4409
4584
  const store = this.handle(p).store;
4410
4585
  summary2.committedRun = store.currentRun();
4586
+ const tops = this.catalog.listSources(p.id).map((s) => this.repoTop(s.root));
4587
+ summary2.repositories = new Set(tops.filter((t) => t !== null)).size;
4588
+ summary2.folders = tops.filter((t) => t === null).length;
4411
4589
  const latest = store.runs().filter((r) => r.base === void 0).at(-1);
4412
4590
  if (latest)
4413
4591
  summary2.latest = {
@@ -4573,7 +4751,10 @@ var init_engine = __esm({
4573
4751
  id: args.source
4574
4752
  });
4575
4753
  const maxFileBytes = this.catalog.projectSettings(project2.id).maxFileMB * MB;
4576
- const rules = applySelection(source, args.paths, args.selected, { maxFileBytes });
4754
+ const rules = applySelection(source, args.paths, args.selected, {
4755
+ maxFileBytes,
4756
+ skipped: this.lastSkips(project2, source.id)
4757
+ });
4577
4758
  return { source: this.catalog.updateSource(project2.id, source.id, rules) };
4578
4759
  }
4579
4760
  /**
@@ -4660,7 +4841,16 @@ var init_engine = __esm({
4660
4841
  project: project2.id,
4661
4842
  source: source.id,
4662
4843
  dir,
4663
- entries: listDirectory(source, dir, { maxFileBytes })
4844
+ entries: listDirectory(source, dir, { maxFileBytes, skipped: this.lastSkips(project2, source.id) })
4845
+ };
4846
+ }
4847
+ /** Why the current run skipped each file of a source, read as asked (none before the first run). */
4848
+ lastSkips(project2, sourceId) {
4849
+ if (this.handle(project2).store.currentRun() === null) return void 0;
4850
+ const reader = this.reader(project2);
4851
+ return (path) => {
4852
+ const file2 = reader.fact(ids.file(sourceId, path));
4853
+ return file2?.type === "File" && file2.status === "not_analyzed" ? file2.reason : void 0;
4664
4854
  };
4665
4855
  }
4666
4856
  // -------------------------------------------------------------------------
@@ -4709,6 +4899,13 @@ var init_engine = __esm({
4709
4899
  }
4710
4900
  }).then((info) => {
4711
4901
  if (info.status === "committed") {
4902
+ if (this.afterCommit && info.kind === "history")
4903
+ try {
4904
+ this.afterCommit(this, project2.id, info.runId);
4905
+ } catch (e) {
4906
+ process.stderr.write(`veoflow: after the run: ${e.message}
4907
+ `);
4908
+ }
4712
4909
  try {
4713
4910
  pruneHistory(handle, this.retention);
4714
4911
  } catch (e) {
@@ -5385,6 +5582,43 @@ var init_engine = __esm({
5385
5582
  * stages' query modules (plan D43: R2's queries live in their own package).
5386
5583
  * R1's own reads stay limited to R1's stages.
5387
5584
  */
5585
+ /**
5586
+ * Start an internal command in a separate process (`<runner> <args…>`, as
5587
+ * runs are), so heavy derived work never blocks this process (#249).
5588
+ * Says "no-runner" when this engine has none (work is then done in-process).
5589
+ */
5590
+ spawnInternal(args, timeoutMs = 10 * 6e4) {
5591
+ if (!this.runner) return Promise.resolve("no-runner");
5592
+ const [command, ...base2] = this.runner.command;
5593
+ const child = spawn(command, [...base2, ...args], {
5594
+ stdio: "ignore",
5595
+ env: { ...process.env, VEOFLOW_HOME: this.catalog.home }
5596
+ });
5597
+ const timer = setTimeout(() => child.kill(), timeoutMs);
5598
+ timer.unref?.();
5599
+ return new Promise((resolve9) => {
5600
+ child.once("error", () => {
5601
+ clearTimeout(timer);
5602
+ resolve9("failed");
5603
+ });
5604
+ child.once("exit", (code) => {
5605
+ clearTimeout(timer);
5606
+ resolve9(code === 0 ? "ok" : "failed");
5607
+ });
5608
+ });
5609
+ }
5610
+ /** Whether this engine has a run of the project in progress (its process may still be finishing up). */
5611
+ runInProgress(project2) {
5612
+ return (this.inflight.get(project2)?.size ?? 0) > 0;
5613
+ }
5614
+ /** A committed run's kept summary, by key (#249); undefined until one is kept. */
5615
+ runSummary(project2, run2, key) {
5616
+ return this.handle(this.resolveProject({ project: project2 })).store.runSummary(run2, key);
5617
+ }
5618
+ /** Keep a summary derived from a committed run's graph (#249). */
5619
+ setRunSummary(project2, run2, key, value) {
5620
+ this.handle(this.resolveProject({ project: project2 })).store.setRunSummary(run2, key, value);
5621
+ }
5388
5622
  readAllStages(args, cwd) {
5389
5623
  const project2 = this.resolveProject(args, cwd);
5390
5624
  const reader = this.pinnedReader(project2, args.run);
@@ -5788,9 +6022,9 @@ var init_engine = __esm({
5788
6022
  total,
5789
6023
  groupCount: sorted.length,
5790
6024
  truncated: sorted.length > limit,
5791
- groups: sorted.slice(0, limit).map(([key, count]) => {
6025
+ groups: sorted.slice(0, limit).map(([key, count2]) => {
5792
6026
  const name = named?.(key);
5793
- return name === void 0 ? { key, count } : { key, count, name };
6027
+ return name === void 0 ? { key, count: count2 } : { key, count: count2, name };
5794
6028
  })
5795
6029
  };
5796
6030
  }
@@ -5839,6 +6073,11 @@ var init_engine = __esm({
5839
6073
  }
5840
6074
  /** Unresolved call sites: open questions only, unless `includeAll` (design A6). */
5841
6075
  listUnresolvedSites(args, cwd) {
6076
+ const paged = args.limit !== void 0 || args.offset !== void 0;
6077
+ if (args.limit !== void 0 && (!Number.isInteger(args.limit) || args.limit < 1))
6078
+ throw new VeoError("invalid-arguments", "limit must be 1 or more", { fields: ["limit"] });
6079
+ if (args.offset !== void 0 && (!Number.isInteger(args.offset) || args.offset < 0))
6080
+ throw new VeoError("invalid-arguments", "offset must be 0 or more", { fields: ["offset"] });
5842
6081
  const project2 = this.resolveProject(args, cwd);
5843
6082
  this.checkSource(project2, args.source);
5844
6083
  const reader = this.reader(project2, args.run);
@@ -5846,9 +6085,15 @@ var init_engine = __esm({
5846
6085
  throw new VeoError("not-found", `no file ${args.file}`, { kind: "file", id: args.file });
5847
6086
  const everywhere = args.file ? visibleSites(reader.inFile(args.file)) : visibleSites(reader.facts("UnresolvedCallSite"), reader);
5848
6087
  const all2 = args.source ? everywhere.filter((s) => s.file.startsWith(`${args.source}:`)) : everywhere;
6088
+ const listed = args.includeAll ? all2 : all2.filter(isOpenQuestion);
6089
+ if (!paged) return { ...this.meta(project2, reader), sites: withProvenance(reader, listed) };
6090
+ const offset = args.offset ?? 0;
6091
+ const page = listed.slice(offset, args.limit === void 0 ? void 0 : offset + args.limit);
5849
6092
  return {
5850
6093
  ...this.meta(project2, reader),
5851
- sites: withProvenance(reader, args.includeAll ? all2 : all2.filter(isOpenQuestion))
6094
+ sites: withProvenance(reader, page),
6095
+ total: listed.length,
6096
+ offset
5852
6097
  };
5853
6098
  }
5854
6099
  /** The analyzed text around an evidence span (exactly what was analyzed). */
@@ -6156,6 +6401,12 @@ var init_src6 = __esm({
6156
6401
  function cmp(a, b) {
6157
6402
  return a < b ? -1 : a > b ? 1 : 0;
6158
6403
  }
6404
+ function nonNegative(offset) {
6405
+ const n = offset ?? 0;
6406
+ if (!Number.isInteger(n) || n < 0)
6407
+ throw new VeoError("invalid-arguments", "offset must be 0 or more", { fields: ["offset"] });
6408
+ return n;
6409
+ }
6159
6410
  function positiveLimit(limit, def, max) {
6160
6411
  const n = limit ?? def;
6161
6412
  if (!Number.isInteger(n) || n < 1 || n > max)
@@ -6195,30 +6446,35 @@ function findingsIn(reader, groupOf, files) {
6195
6446
  path: pathOf(fact.file),
6196
6447
  group: groupOf.get(fact.file)?.id ?? null,
6197
6448
  line: fact.evidence.span.start.line,
6198
- text,
6449
+ text: oneLine(text),
6199
6450
  reason,
6200
6451
  ...candidates ? { candidates } : {},
6201
6452
  ...exhaustive === false ? { exhaustive } : {},
6202
6453
  evidence: fact.evidence
6203
6454
  });
6204
6455
  for (const u of each("UnresolvedImport"))
6205
- row(u, u.outcome === "broken" ? "broken" : u.outcome, u.specifier, u.reason);
6456
+ if (u.reason !== "asset") row(u, u.outcome === "broken" ? "broken" : u.outcome, u.specifier, u.reason);
6206
6457
  const expressions = /* @__PURE__ */ new Map();
6458
+ const resolutions = each("SiteResolution");
6207
6459
  const narrowed = new Set(
6208
- each("SiteResolution").filter((r) => r.status === "unresolved" && r.importOutcome === null && r.candidates?.length).map((r) => r.site)
6460
+ resolutions.filter((r) => r.status === "unresolved" && r.importOutcome === null && r.candidates?.length).map((r) => r.site)
6209
6461
  );
6210
6462
  for (const s of each("UnresolvedCallSite")) {
6211
6463
  expressions.set(s.id, s.expression);
6212
6464
  if (isOpenQuestion(s) && !narrowed.has(s.id)) row(s, "open-call", s.expression, s.reason);
6213
6465
  }
6214
- for (const r of each("SiteResolution")) {
6466
+ for (const r of resolutions) {
6215
6467
  if (r.status !== "unresolved" || r.importOutcome !== null) continue;
6216
6468
  const text = expressions.get(r.site) ?? r.site;
6217
- if (r.candidates?.length) row(r, "open-call", text, "ambiguous", r.candidates.length, r.exhaustive);
6469
+ if (r.candidates?.length) row(r, "open-call", text, "candidates", r.candidates.length, r.exhaustive);
6218
6470
  else row(r, "open-call", text, r.steps.at(-1)?.kind ?? "unresolved");
6219
6471
  }
6220
6472
  return rows.sort(byEvidence);
6221
6473
  }
6474
+ function oneLine(text, max = 120) {
6475
+ const flat = text.replace(/\s+/g, " ").trim();
6476
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
6477
+ }
6222
6478
  function tally(counts, kind) {
6223
6479
  if (kind === "broken") counts.broken++;
6224
6480
  else if (kind === "not-analyzed") counts.notAnalyzed++;
@@ -6242,27 +6498,38 @@ function summary(g, functions, findings) {
6242
6498
  }
6243
6499
  function listGroups(engine, args, cwd) {
6244
6500
  const limit = positiveLimit(args.limit, GROUPS_MAX, GROUPS_MAX);
6501
+ const offset = nonNegative(args.offset);
6245
6502
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
6246
6503
  const inScope = (source) => args.source === void 0 || source === args.source;
6247
6504
  const groups2 = reader.facts("Group").filter((g) => inScope(g.source)).sort((a, b) => cmp(a.id, b.id));
6248
6505
  const groupOf = groupIndex(groups2);
6249
6506
  const findings = /* @__PURE__ */ new Map();
6250
- let brokenImports = 0;
6507
+ let brokenImports2 = 0;
6251
6508
  let openCalls = 0;
6252
- for (const f of findingsIn(reader, groupOf, null)) {
6253
- if (!inScope(sourceOf2(f.file))) continue;
6254
- if (f.kind === "broken") brokenImports++;
6255
- if (f.kind === "open-call") openCalls++;
6256
- if (!f.group) continue;
6257
- const c = findings.get(f.group) ?? zero();
6258
- tally(c, f.kind);
6259
- findings.set(f.group, c);
6260
- }
6509
+ const run2 = args.run ?? meta3.committedRun;
6510
+ const kept = run2 === null ? void 0 : keptFindingSummary(engine, meta3.project, run2);
6511
+ if (kept) {
6512
+ for (const g of groups2) if (kept.groups[g.id]) findings.set(g.id, kept.groups[g.id]);
6513
+ for (const [source, c] of Object.entries(kept.sources))
6514
+ if (inScope(source)) {
6515
+ brokenImports2 += c.broken;
6516
+ openCalls += c.openCalls;
6517
+ }
6518
+ } else
6519
+ for (const f of findingsIn(reader, groupOf, null)) {
6520
+ if (!inScope(sourceOf2(f.file))) continue;
6521
+ if (f.kind === "broken") brokenImports2++;
6522
+ if (f.kind === "open-call") openCalls++;
6523
+ if (!f.group) continue;
6524
+ const c = findings.get(f.group) ?? zero();
6525
+ tally(c, f.kind);
6526
+ findings.set(f.group, c);
6527
+ }
6261
6528
  const functions = reader.countByFile("Function");
6262
6529
  const files = reader.facts("File").filter((f) => inScope(f.source));
6263
6530
  let fnCount = 0;
6264
6531
  for (const f of files) fnCount += functions.get(f.id) ?? 0;
6265
- const shown = groups2.slice(0, limit);
6532
+ const shown = groups2.slice(offset, offset + limit);
6266
6533
  const ids2 = new Set(shown.map((g) => g.id));
6267
6534
  const importers = /* @__PURE__ */ new Map();
6268
6535
  for (const g of groups2) for (const p of g.externalPackages) importers.set(p, (importers.get(p) ?? 0) + 1);
@@ -6276,12 +6543,13 @@ function listGroups(engine, args, cwd) {
6276
6543
  stats: {
6277
6544
  files: files.length,
6278
6545
  functions: fnCount,
6279
- crossFileCalls: reader.facts("CALLS_CROSS_FILE").filter((e) => inScope(sourceOf2(e.evidence.file))).length,
6280
- brokenImports,
6546
+ crossFileCalls: [...reader.countByFile("CALLS_CROSS_FILE")].filter(([file2]) => inScope(sourceOf2(file2))).reduce((n, [, c]) => n + c, 0),
6547
+ brokenImports: brokenImports2,
6281
6548
  openCalls
6282
6549
  },
6283
6550
  total: groups2.length,
6284
- truncated: groups2.length > limit,
6551
+ offset,
6552
+ truncated: groups2.length > offset + limit,
6285
6553
  groups: shown.map((g) => summary(g, functions, findings)),
6286
6554
  dependsOn: reader.facts("DEPENDS_ON").filter((d) => ids2.has(d.from) && ids2.has(d.to)).sort((a, b) => cmp(a.id, b.id)).map(({ id, from, to, imports, calls, evidence }) => ({ id, from, to, imports, calls, evidence })),
6287
6555
  externalPackages: {
@@ -6555,6 +6823,33 @@ function listFindings(engine, args, cwd) {
6555
6823
  files = g.files;
6556
6824
  } else if (args.file !== void 0) files = [fileFact(reader, args.file).id];
6557
6825
  const kinds = new Set(args.kind?.length ? args.kind : ["broken", "not-analyzed", "open-call"]);
6826
+ const offset = nonNegative(args.offset);
6827
+ const run2 = args.run ?? meta3.committedRun;
6828
+ const kept = run2 === null || args.source !== void 0 || args.file !== void 0 ? void 0 : keptFindingSummary(engine, meta3.project, run2);
6829
+ const keptCounts = kept && (args.group === void 0 ? kept.counts : kept.groups[args.group] ?? zero());
6830
+ if (keptCounts) {
6831
+ const order = (files ?? reader.facts("File").map((f) => f.id)).slice().sort(cmp);
6832
+ const total = [...kinds].reduce((n, k) => n + keptCounts[KIND_COUNT[k]], 0);
6833
+ const page = [];
6834
+ let skipped = 0;
6835
+ for (const file2 of order) {
6836
+ if (page.length >= limit || skipped + page.length >= total) break;
6837
+ for (const f of findingsIn(reader, groupOf, [file2])) {
6838
+ if (!kinds.has(f.kind)) continue;
6839
+ if (skipped < offset) skipped++;
6840
+ else page.push(f);
6841
+ }
6842
+ }
6843
+ return {
6844
+ ...meta3,
6845
+ stage2: stage22,
6846
+ counts: keptCounts,
6847
+ total,
6848
+ offset,
6849
+ truncated: offset + Math.min(page.length, limit) < total,
6850
+ findings: page.slice(0, limit)
6851
+ };
6852
+ }
6558
6853
  const counts = zero();
6559
6854
  const rows = [];
6560
6855
  for (const f of findingsIn(reader, groupOf, files)) {
@@ -6567,8 +6862,9 @@ function listFindings(engine, args, cwd) {
6567
6862
  stage2: stage22,
6568
6863
  counts,
6569
6864
  total: rows.length,
6570
- truncated: rows.length > limit,
6571
- findings: rows.slice(0, limit)
6865
+ offset,
6866
+ truncated: rows.length > offset + limit,
6867
+ findings: rows.slice(offset, offset + limit)
6572
6868
  };
6573
6869
  }
6574
6870
  function siteLinks(engine, args, cwd) {
@@ -6611,7 +6907,30 @@ function siteLinks(engine, args, cwd) {
6611
6907
  });
6612
6908
  return { ...meta3, stage2: stage22, links };
6613
6909
  }
6614
- var STAGE2, GROUPS_MAX, GROUP_NODES_MAX, GROUP_COLLAPSE_OVER, IMPORTS_MAX, FINDINGS_MAX, TOP_PACKAGES, pathOf, sourceOf2, byEvidence, FINDING_KINDS, zero;
6910
+ function summarizeFindings(engine, project2, run2) {
6911
+ const { reader } = open(engine, { project: project2, run: run2 });
6912
+ const files = reader.facts("File");
6913
+ const summary2 = {
6914
+ counts: zero(),
6915
+ groups: {},
6916
+ sources: {},
6917
+ files: {
6918
+ listed: files.length,
6919
+ analyzed: files.filter((f) => f.status === "analyzed" || f.status === "degraded").length
6920
+ }
6921
+ };
6922
+ for (const f of findingsIn(reader, groupIndex(reader.facts("Group")), null)) {
6923
+ tally(summary2.counts, f.kind);
6924
+ if (f.group) tally(summary2.groups[f.group] ??= zero(), f.kind);
6925
+ tally(summary2.sources[sourceOf2(f.file)] ??= zero(), f.kind);
6926
+ }
6927
+ engine.setRunSummary(project2, run2, FINDINGS_SUMMARY, summary2);
6928
+ return summary2.counts;
6929
+ }
6930
+ function keptFindingSummary(engine, project2, run2) {
6931
+ return engine.runSummary(project2, run2, FINDINGS_SUMMARY);
6932
+ }
6933
+ var STAGE2, GROUPS_MAX, GROUP_NODES_MAX, GROUP_COLLAPSE_OVER, IMPORTS_MAX, FINDINGS_MAX, TOP_PACKAGES, pathOf, sourceOf2, byEvidence, FINDING_KINDS, KIND_COUNT, zero, FINDINGS_SUMMARY;
6615
6934
  var init_reads = __esm({
6616
6935
  "packages/query-imports/src/reads.ts"() {
6617
6936
  "use strict";
@@ -6627,7 +6946,14 @@ var init_reads = __esm({
6627
6946
  sourceOf2 = (fileId) => fileId.slice(0, fileId.indexOf(":"));
6628
6947
  byEvidence = (a, b) => cmp(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp(a.id, b.id);
6629
6948
  FINDING_KINDS = ["broken", "not-analyzed", "pending", "open-call"];
6949
+ KIND_COUNT = {
6950
+ broken: "broken",
6951
+ "not-analyzed": "notAnalyzed",
6952
+ pending: "pending",
6953
+ "open-call": "openCalls"
6954
+ };
6630
6955
  zero = () => ({ broken: 0, notAnalyzed: 0, pending: 0, openCalls: 0 });
6956
+ FINDINGS_SUMMARY = "findings/v3";
6631
6957
  }
6632
6958
  });
6633
6959
 
@@ -6870,7 +7196,8 @@ function explain(engine, args, cwd) {
6870
7196
  stage2: stage22,
6871
7197
  total: items.length,
6872
7198
  truncated: items.length > EXPLAIN_MAX,
6873
- items: items.slice(0, EXPLAIN_MAX)
7199
+ items: items.slice(0, EXPLAIN_MAX),
7200
+ ...file2.status !== "analyzed" ? { file: { status: file2.status, ...file2.reason ? { reason: file2.reason } : {} } } : {}
6874
7201
  };
6875
7202
  }
6876
7203
  var EXPLAIN_MAX, pathOf2, cmp2, IMPORT_REASONS, SITE_REASONS, STATUS_WORDS, base, RESOLUTION_WORDS;
@@ -6891,6 +7218,8 @@ var init_explain = __esm({
6891
7218
  "default-excluded": "the file is in a folder left out of analysis (installed, generated or tool code)",
6892
7219
  "excluded-by-rule": "a rule of the source leaves the file out",
6893
7220
  "too-large": "the file is over the size limit",
7221
+ asset: "it is a stylesheet, image, font or data file the bundler handles, not code",
7222
+ minified: "the file is minified (built output); choose it to analyze it",
6894
7223
  "language-not-analyzed": "the file's language isn't analyzed yet"
6895
7224
  };
6896
7225
  SITE_REASONS = {
@@ -6901,6 +7230,7 @@ var init_explain = __esm({
6901
7230
  "dynamic-sql": "it runs SQL built at run time",
6902
7231
  "imported-symbol": "it calls something imported from another file, which Stage 2 links",
6903
7232
  "runtime-global": "it is part of the language or runtime (a built-in), outside the code analyzed",
7233
+ "builtin-value": "the value it is called on is built in (a string, a number, a DOM element, a fetch response), so it runs code of the runtime, outside the code analyzed",
6904
7234
  "template-binding": "it is a call in a template file, resolved against the components that declare the template",
6905
7235
  "template-reference": "it names a component, directive, pipe or member registered outside this file, which Stage 2 links"
6906
7236
  };
@@ -7024,10 +7354,51 @@ async function checkCode(engine, args, cwd = process.cwd()) {
7024
7354
  },
7025
7355
  stage2: { agree: 0, "different-callee": 0, "checker-only": 0, "not-linked-yet": 0, changed: 0 }
7026
7356
  };
7357
+ const compilerCallees = (s) => {
7358
+ const out = /* @__PURE__ */ new Set();
7359
+ for (const c of calls) {
7360
+ if (c.file !== s.file || c.site.start.line !== s.line || c.site.start.column !== s.column) continue;
7361
+ if (c.site.end.line !== s.end.line || c.site.end.column !== s.end.column || !c.callee) continue;
7362
+ const def = checkers.adapterDef(adapterFiles, c);
7363
+ const fn = def ? reader.facts("Function", fileId(c.callee.file)).find((f) => f.qualifiedName === def.qualifiedName) : void 0;
7364
+ if (fn) out.add(fn.id);
7365
+ }
7366
+ return out;
7367
+ };
7368
+ const perFile = /* @__PURE__ */ new Map();
7369
+ const factsOf = (file2) => {
7370
+ let got = perFile.get(file2);
7371
+ if (!got) {
7372
+ got = {
7373
+ sites: reader.facts("UnresolvedCallSite", file2),
7374
+ resolutions: new Map(reader.facts("SiteResolution", file2).map((r) => [r.site, r]))
7375
+ };
7376
+ perFile.set(file2, got);
7377
+ }
7378
+ return got;
7379
+ };
7380
+ const candidatesAt = (s) => {
7381
+ const file2 = fileId(s.file);
7382
+ const { sites: sites2, resolutions } = factsOf(file2);
7383
+ const site = sites2.find(
7384
+ (x) => x.evidence.span.start.line === s.line && x.evidence.span.start.column === s.column && x.evidence.span.end.line === s.end.line && x.evidence.span.end.column === s.end.column
7385
+ );
7386
+ const res = site && resolutions.get(site.id);
7387
+ if (!res?.candidates?.length) return void 0;
7388
+ const functions = res.candidates.map((c) => c.function);
7389
+ const compiler = compilerCallees(s);
7390
+ return {
7391
+ functions,
7392
+ exhaustive: res.exhaustive !== false,
7393
+ // Unknown, not "not among them", when the compiler's callee maps to no function.
7394
+ ...compiler.size ? { includesCompiler: functions.some((f) => compiler.has(f)) } : {}
7395
+ };
7396
+ };
7027
7397
  for (const s of report.sites) {
7028
7398
  if (DISAGREE.has(s.category)) {
7029
7399
  const category2 = s.category;
7030
7400
  counts.stage1[category2]++;
7401
+ const narrowed = category2 === "checker-only" && stage22 ? candidatesAt(s) : void 0;
7031
7402
  sites.push({
7032
7403
  stage: "stage1",
7033
7404
  category: category2,
@@ -7037,7 +7408,8 @@ async function checkCode(engine, args, cwd = process.cwd()) {
7037
7408
  column: s.column,
7038
7409
  veoflow: s.adapter,
7039
7410
  compiler: s.checker,
7040
- ...changed.has(s.file) ? { changed: true } : {}
7411
+ ...changed.has(s.file) ? { changed: true } : {},
7412
+ ...narrowed ? { candidates: narrowed } : {}
7041
7413
  });
7042
7414
  continue;
7043
7415
  }
@@ -7107,6 +7479,84 @@ var init_check = __esm({
7107
7479
  }
7108
7480
  });
7109
7481
 
7482
+ // packages/query-imports/src/totals.ts
7483
+ function projectTotals(engine, args, cwd) {
7484
+ const top = args.top ?? 10;
7485
+ if (!Number.isInteger(top) || top < 0 || top > TOTALS_TOP_MAX)
7486
+ throw new VeoError("invalid-arguments", `top must be 0 to ${TOTALS_TOP_MAX}`, { fields: ["top"] });
7487
+ if (args.source !== void 0 && (typeof args.source !== "string" || args.source === ""))
7488
+ throw new VeoError("invalid-arguments", "source must be a non-empty id", { fields: ["source"] });
7489
+ const { meta: meta3, reader } = engine.readAllStages(args, cwd);
7490
+ const inScope = (id) => args.source === void 0 || id.startsWith(`${args.source}:`);
7491
+ const sum = (counts) => {
7492
+ let n = 0;
7493
+ for (const [file2, c] of counts) if (inScope(file2)) n += c;
7494
+ return n;
7495
+ };
7496
+ const fileOf = (fn) => fn.slice(0, fn.indexOf(":", fn.indexOf(":") + 1));
7497
+ const files = { listed: 0, analyzed: 0, partly: 0, notAnalyzed: [] };
7498
+ const why = /* @__PURE__ */ new Map();
7499
+ const listed = reader.facts("File").filter((f) => inScope(f.id));
7500
+ for (const f of listed) {
7501
+ files.listed++;
7502
+ if (f.status === "analyzed") files.analyzed++;
7503
+ else if (f.status === "degraded") files.partly++;
7504
+ else {
7505
+ const reason = f.reason ?? f.status;
7506
+ why.set(reason, (why.get(reason) ?? 0) + 1);
7507
+ }
7508
+ }
7509
+ files.notAnalyzed = [...why].map(([reason, n]) => ({ reason, files: n })).sort((a, b) => b.files - a.files || (a.reason < b.reason ? -1 : 1));
7510
+ let mostCalled2 = [];
7511
+ if (top > 0) {
7512
+ const own2 = new Map(listed.filter((f) => !f.origin).map((f) => [f.id, f.path]));
7513
+ mostCalled2 = [...reader.callCounts("dst")].filter(([id]) => own2.has(fileOf(id))).sort((a, b) => b[1].calls - a[1].calls || (a[0] < b[0] ? -1 : 1)).slice(0, top).map(([id, c]) => {
7514
+ const f = reader.fact(id);
7515
+ const file2 = fileOf(id);
7516
+ return {
7517
+ id,
7518
+ name: f?.type === "Function" ? f.qualifiedName : id.slice(file2.length + 1),
7519
+ path: own2.get(file2),
7520
+ calls: c.calls,
7521
+ callers: c.functions
7522
+ };
7523
+ });
7524
+ }
7525
+ const findings = listFindings(
7526
+ engine,
7527
+ {
7528
+ ...args.project !== void 0 ? { project: args.project } : {},
7529
+ // The same run as the counts above, even if another commits meanwhile.
7530
+ ...args.run !== void 0 ? { run: args.run } : meta3.committedRun !== null ? { run: meta3.committedRun } : {},
7531
+ ...args.source !== void 0 ? { source: args.source } : {},
7532
+ kind: ["open-call"],
7533
+ limit: 1
7534
+ },
7535
+ cwd
7536
+ );
7537
+ return {
7538
+ ...meta3,
7539
+ stage2: reader.count("Group") > 0,
7540
+ source: args.source ?? null,
7541
+ calls: {
7542
+ withinFiles: sum(reader.countByFile("CALLS")),
7543
+ acrossFiles: sum(reader.countByFile("CALLS_CROSS_FILE"))
7544
+ },
7545
+ openCalls: findings.counts.openCalls,
7546
+ files,
7547
+ mostCalled: mostCalled2
7548
+ };
7549
+ }
7550
+ var TOTALS_TOP_MAX;
7551
+ var init_totals = __esm({
7552
+ "packages/query-imports/src/totals.ts"() {
7553
+ "use strict";
7554
+ init_src();
7555
+ init_reads();
7556
+ TOTALS_TOP_MAX = 100;
7557
+ }
7558
+ });
7559
+
7110
7560
  // packages/query-imports/src/report.ts
7111
7561
  import { arch, platform, release } from "node:os";
7112
7562
  function spanOf(f) {
@@ -7295,6 +7745,7 @@ var init_src7 = __esm({
7295
7745
  init_reads();
7296
7746
  init_explain();
7297
7747
  init_check();
7748
+ init_totals();
7298
7749
  init_report();
7299
7750
  CROSS_FILE_CALLS_MAX = 500;
7300
7751
  }
@@ -9404,11 +9855,11 @@ function lockedVersions(path, text) {
9404
9855
  }
9405
9856
  function statements(source, path, result2) {
9406
9857
  const fileId = ids.file(source, path);
9407
- const byKey = /* @__PURE__ */ new Map();
9858
+ const byKey2 = /* @__PURE__ */ new Map();
9408
9859
  const formOf = (i) => i.kind === "require" ? "require" : i.kind === "dynamic" ? "dynamic" : i.typeOnly ? "type-only" : "static";
9409
9860
  for (const i of result2.imports) {
9410
9861
  const key = `${i.span.start.offset}\0${i.specifier}`;
9411
- const existing = byKey.get(key);
9862
+ const existing = byKey2.get(key);
9412
9863
  const binding2 = [
9413
9864
  i.kind === "namespace" ? "*" : i.importedName,
9414
9865
  i.localName
@@ -9418,7 +9869,7 @@ function statements(source, path, result2) {
9418
9869
  if (existing.form === "type-only" && !i.typeOnly) existing.form = "static";
9419
9870
  continue;
9420
9871
  }
9421
- byKey.set(key, {
9872
+ byKey2.set(key, {
9422
9873
  source,
9423
9874
  path,
9424
9875
  fileId,
@@ -9436,12 +9887,12 @@ function statements(source, path, result2) {
9436
9887
  e.kind === "reexport-all" ? "*" : e.sourceName ?? e.exportedName,
9437
9888
  e.exportedName
9438
9889
  ];
9439
- const existing = byKey.get(key);
9890
+ const existing = byKey2.get(key);
9440
9891
  if (existing) {
9441
9892
  existing.bindings.push(binding2);
9442
9893
  if (existing.form === "type-only" && !e.typeOnly) existing.form = "re-export";
9443
9894
  } else
9444
- byKey.set(key, {
9895
+ byKey2.set(key, {
9445
9896
  source,
9446
9897
  path,
9447
9898
  fileId,
@@ -9451,7 +9902,7 @@ function statements(source, path, result2) {
9451
9902
  bindings: [binding2]
9452
9903
  });
9453
9904
  }
9454
- const list = [...byKey.values()].sort(
9905
+ const list = [...byKey2.values()].sort(
9455
9906
  (a, b) => a.span.start.offset - b.span.start.offset || (a.specifier < b.specifier ? -1 : 1)
9456
9907
  );
9457
9908
  const seen = /* @__PURE__ */ new Map();
@@ -9562,8 +10013,8 @@ function resolveImports2(plans, files) {
9562
10013
  const escapes = /* @__PURE__ */ new Map();
9563
10014
  for (const s of toResolve) {
9564
10015
  if (!isRelative(s.specifier)) continue;
9565
- const inside = posix2.normalize(posix2.join(posix2.dirname(s.path), s.specifier));
9566
- if (inside !== ".." && !inside.startsWith("../")) continue;
10016
+ const inside2 = posix2.normalize(posix2.join(posix2.dirname(s.path), s.specifier));
10017
+ if (inside2 !== ".." && !inside2.startsWith("../")) continue;
9567
10018
  const plan = treeOf.get(s.source).plan;
9568
10019
  const abs = resolvePath(plan.root, ...posix2.dirname(s.path).split("/"), ...s.specifier.split("/"));
9569
10020
  const within = (root) => {
@@ -9804,6 +10255,43 @@ function resolveImports2(plans, files) {
9804
10255
  return true;
9805
10256
  });
9806
10257
  };
10258
+ const exportedSources = (dir, pkg, sub) => {
10259
+ const exports = pkg.exports;
10260
+ if (!exports || typeof exports !== "object" || Array.isArray(exports)) return [];
10261
+ const code = [];
10262
+ const types = [];
10263
+ const collect = (v, typesOnly) => {
10264
+ if (typeof v === "string") (typesOnly || /\.d\.[cm]?ts$/.test(v) ? types : code).push(v);
10265
+ else if (Array.isArray(v)) v.forEach((x) => collect(x, typesOnly));
10266
+ else if (v && typeof v === "object")
10267
+ for (const [k, x] of Object.entries(v)) collect(x, typesOnly || k === "types" || k === "typings");
10268
+ };
10269
+ const key = `./${sub}`;
10270
+ const map2 = exports;
10271
+ let middle = null;
10272
+ if (key in map2) collect(map2[key], false);
10273
+ else {
10274
+ const best = Object.keys(map2).filter((k) => {
10275
+ const star2 = k.indexOf("*");
10276
+ return star2 >= 0 && key.startsWith(k.slice(0, star2)) && key.endsWith(k.slice(star2 + 1)) && key.length >= k.length - 1;
10277
+ }).sort((a, b) => b.indexOf("*") - a.indexOf("*") || b.length - a.length)[0];
10278
+ if (!best) return [];
10279
+ const star = best.indexOf("*");
10280
+ middle = key.slice(star, key.length - (best.length - star - 1));
10281
+ collect(map2[best], false);
10282
+ }
10283
+ const out2 = [];
10284
+ for (const t of [...code, ...types]) {
10285
+ const rel = (middle === null ? t : t.replace("*", middle)).replace(/^\.\//, "").replace(/(\.d)?\.[cm]?[jt]sx?$/, "");
10286
+ const parts = rel.split("/");
10287
+ if (!parts[0] || !BUILD_DIRS.has(parts[0]) || parts.length < 2) continue;
10288
+ let inner = 1;
10289
+ while (inner < parts.length - 1 && BUILD_DIRS.has(parts[inner])) inner++;
10290
+ for (const rest of [parts.slice(inner), parts.slice(1)])
10291
+ out2.push(join14(dir, "src", ...rest), join14(dir, ...rest));
10292
+ }
10293
+ return [...new Set(out2)];
10294
+ };
9807
10295
  const frameworkFallback = (t, from, specifier) => {
9808
10296
  specifier = specifier.replace(/\?[^/]*$/, "");
9809
10297
  const name = packageName(specifier);
@@ -9811,7 +10299,7 @@ function resolveImports2(plans, files) {
9811
10299
  const pkg = link2 ? link2.tree.manifests.get(join14(link2.dir, "package.json")) : void 0;
9812
10300
  if (link2 && pkg && entriesInMissingBuild(link2.tree, link2.dir, pkg)) {
9813
10301
  const sub = specifier.slice(name.length).replace(/^\//, "");
9814
- const bases = sub ? [join14(link2.dir, "src", sub), join14(link2.dir, sub)] : [
10302
+ const bases = sub ? [...exportedSources(link2.dir, pkg, sub), join14(link2.dir, "src", sub), join14(link2.dir, sub)] : [
9815
10303
  ...typeof pkg.source === "string" ? [join14(link2.dir, pkg.source)] : [],
9816
10304
  join14(link2.dir, "src/index"),
9817
10305
  join14(link2.dir, "index")
@@ -10265,8 +10753,15 @@ function resolveImports2(plans, files) {
10265
10753
  target2 = {
10266
10754
  kind: "unresolved",
10267
10755
  outcome: "not-analyzed",
10268
- reason: file2?.reason ?? (file2 ? "not-analyzed" : "language-not-analyzed"),
10269
- steps: [...steps, { kind: "not-analyzed", detail: `${where} is not analyzed` }]
10756
+ // A stylesheet, image, font or data file isn't code to analyze (#265): `asset`, not a finding.
10757
+ reason: file2?.reason ?? (file2 ? "not-analyzed" : isAsset(where) ? "asset" : "language-not-analyzed"),
10758
+ steps: [
10759
+ ...steps,
10760
+ {
10761
+ kind: "not-analyzed",
10762
+ detail: !file2 && isAsset(where) ? `${where} is an asset (not code)` : `${where} is not analyzed`
10763
+ }
10764
+ ]
10270
10765
  };
10271
10766
  } else if (aliasOutside) {
10272
10767
  target2 = {
@@ -10753,7 +11248,7 @@ function importFacts(resolved) {
10753
11248
  }
10754
11249
  return { edges, unresolved, packages: [...packages.values()] };
10755
11250
  }
10756
- var import_semver, SCRIPT_LANGUAGES, BATCH_BYTES3, BUILTINS, PROBE_EXTENSIONS, OWN_EXTENSIONS, VITE_BASED, DOCUSAURUS_CLIENT, isRelative, isUrl, DEPENDENCY_FIELDS, aboveCache;
11251
+ var import_semver, SCRIPT_LANGUAGES, BATCH_BYTES3, BUILTINS, PROBE_EXTENSIONS, ASSET, isAsset, OWN_EXTENSIONS, VITE_BASED, DOCUSAURUS_CLIENT, isRelative, isUrl, DEPENDENCY_FIELDS, aboveCache;
10757
11252
  var init_imports = __esm({
10758
11253
  "packages/stage2/src/imports.ts"() {
10759
11254
  "use strict";
@@ -10778,6 +11273,8 @@ var init_imports = __esm({
10778
11273
  ".svelte",
10779
11274
  ".json"
10780
11275
  ];
11276
+ ASSET = /\.(css|scss|sass|less|styl|pcss|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|otf|eot|mp3|mp4|webm|ogg|wav|json|ya?ml|toml|md|txt|csv|glsl|frag|vert)(\?.*)?$/i;
11277
+ isAsset = (path) => ASSET.test(path);
10781
11278
  OWN_EXTENSIONS = /* @__PURE__ */ new Set([
10782
11279
  ".js",
10783
11280
  ".jsx",
@@ -10872,10 +11369,10 @@ function typeGraph(input2) {
10872
11369
  return via?.target.kind === "file" ? exportedAt(via.target.file.id, e.sourceName ?? name, depth + 1) : null;
10873
11370
  }
10874
11371
  if (e.kind === "default" && !e.localName && !e.sourceName) {
10875
- const inside = result2.types.find(
11372
+ const inside2 = result2.types.find(
10876
11373
  (t) => t.span.start.offset >= e.span.start.offset && t.span.end.offset <= e.span.end.offset
10877
11374
  );
10878
- return inside ? { file: file2, name: inside.name } : null;
11375
+ return inside2 ? { file: file2, name: inside2.name } : null;
10879
11376
  }
10880
11377
  if (e.kind === "named" || e.kind === "default") {
10881
11378
  const local = e.localName ?? e.sourceName ?? name;
@@ -10909,7 +11406,8 @@ function typeGraph(input2) {
10909
11406
  const found = declaredAt(file2, b.name);
10910
11407
  const base2 = declared2(found) ? found : null;
10911
11408
  const clause = evidence(file2, b.span);
10912
- if (t.kind === "class" && b.relation === "extends") parentOf2.set(declKey(decl), { base: base2, clause });
11409
+ if (t.kind === "class" && b.relation === "extends")
11410
+ parentOf2.set(declKey(decl), { base: base2, name: b.name, clause });
10913
11411
  if (!base2) continue;
10914
11412
  const list = subtypes.get(declKey(base2)) ?? [];
10915
11413
  list.push({ decl, kind: t.kind, clause });
@@ -10964,7 +11462,35 @@ function typeGraph(input2) {
10964
11462
  }
10965
11463
  return "unknown";
10966
11464
  };
11465
+ const inherited = (d, member, isStatic) => {
11466
+ const seen = /* @__PURE__ */ new Set();
11467
+ for (let at = d; at; ) {
11468
+ if (seen.has(declKey(at))) return "unknown";
11469
+ seen.add(declKey(at));
11470
+ const info = typesByKey.get(declKey(at));
11471
+ if (!info || info.kind !== "class") return "unknown";
11472
+ const table = isStatic ? info.statics ?? [] : info.members;
11473
+ if (table.some((x) => x.name === "[written]")) return "other";
11474
+ if (table.some((x) => x.name.startsWith("[") && !x.name.startsWith("[Symbol."))) return "unknown";
11475
+ const m = table.find((x) => x.name === member);
11476
+ if (m) {
11477
+ const fn = m.kind === "method" && m.function ? fnByName.get(`${at.file}\0${m.function}`) : void 0;
11478
+ return fn ? { fn, definer: at } : "other";
11479
+ }
11480
+ const parent = parentOf2.get(declKey(at));
11481
+ if (!parent) return "none";
11482
+ if (parent.base) {
11483
+ at = parent.base;
11484
+ continue;
11485
+ }
11486
+ const imp = importOf(at.file, parent.name);
11487
+ if (imp?.target.kind === "package") return { pkg: imp.target.pkg.id, name: imp.target.pkg.name };
11488
+ return "unknown";
11489
+ }
11490
+ return "unknown";
11491
+ };
10967
11492
  return {
11493
+ inherited,
10968
11494
  resultOf,
10969
11495
  pathOf: pathOf4,
10970
11496
  sourceOf: sourceOf4,
@@ -11011,18 +11537,18 @@ function candidateSets(input2, graph = typeGraph(input2)) {
11011
11537
  const key = declKey;
11012
11538
  const records = /* @__PURE__ */ new Map();
11013
11539
  const recordOf = (site) => {
11014
- let byKey = records.get(site.file);
11015
- if (!byKey) {
11016
- byKey = new Map(
11540
+ let byKey2 = records.get(site.file);
11541
+ if (!byKey2) {
11542
+ byKey2 = new Map(
11017
11543
  (resultOf(site.file)?.unresolved ?? []).map((u) => [
11018
11544
  `${u.caller}\0${u.expression}\0${u.site.start.offset}`,
11019
11545
  u
11020
11546
  ])
11021
11547
  );
11022
- records.set(site.file, byKey);
11548
+ records.set(site.file, byKey2);
11023
11549
  }
11024
11550
  const caller = site.enclosingFn.slice(site.file.length + 1);
11025
- return byKey.get(`${caller}\0${site.expression}\0${site.evidence.span.start.offset}`);
11551
+ return byKey2.get(`${caller}\0${site.expression}\0${site.evidence.span.start.offset}`);
11026
11552
  };
11027
11553
  const typedMemo = /* @__PURE__ */ new Map();
11028
11554
  const typedCandidates = (type, member) => {
@@ -11540,7 +12066,7 @@ function groups(input2) {
11540
12066
  const asClusters = (files2) => {
11541
12067
  for (const c of clusters(files2, input2.imports, input2.calls, fnFile))
11542
12068
  push({
11543
- id: ids.cluster(plan.sourceId, c.name),
12069
+ id: ids.cluster(plan.sourceId, c.key),
11544
12070
  name: c.name,
11545
12071
  kind: "cluster",
11546
12072
  source: plan.sourceId,
@@ -11641,10 +12167,10 @@ function folderUnits(files) {
11641
12167
  roots.add("");
11642
12168
  continue;
11643
12169
  }
11644
- const inside = analyzed.filter((f) => top(f) === dir);
11645
- const direct = inside.filter((f) => f.path.split("/").length === 2);
12170
+ const inside2 = analyzed.filter((f) => top(f) === dir);
12171
+ const direct = inside2.filter((f) => f.path.split("/").length === 2);
11646
12172
  const children = new Set(
11647
- inside.filter((f) => f.path.split("/").length > 2).map((f) => f.path.split("/")[1])
12173
+ inside2.filter((f) => f.path.split("/").length > 2).map((f) => f.path.split("/")[1])
11648
12174
  );
11649
12175
  if (direct.length === 0 && children.size >= 2) for (const c of children) roots.add(`${dir}/${c}`);
11650
12176
  else roots.add(dir);
@@ -11700,23 +12226,46 @@ function clusters(files, imports, calls, fnFile) {
11700
12226
  list.push(files[i]);
11701
12227
  members2.set(c, list);
11702
12228
  });
11703
- const named = [...members2.values()].map((list) => {
11704
- const counts = /* @__PURE__ */ new Map();
11705
- for (const f of list) counts.set(posix4.dirname(f.path), (counts.get(posix4.dirname(f.path)) ?? 0) + 1);
11706
- const root = [...counts].sort((x, y) => y[1] - x[1] || cmp4(x[0], y[0]))[0][0];
11707
- return { root: root === "." ? "" : root, files: list };
12229
+ return [...members2.values()].map(nameCluster).sort(byKey).map(disambiguate());
12230
+ }
12231
+ function ancestors(dir) {
12232
+ if (!dir) return [""];
12233
+ const parts = dir.split("/");
12234
+ return ["", ...parts.map((_, i) => parts.slice(0, i + 1).join("/"))];
12235
+ }
12236
+ function nameCluster(list) {
12237
+ const dirs = list.map((f) => {
12238
+ const d = posix4.dirname(f.path);
12239
+ return d === "." ? "" : d;
11708
12240
  });
11709
- named.sort(
11710
- (a, b) => cmp4(a.root, b.root) || b.files.length - a.files.length || cmp4(a.files[0].path, b.files[0].path)
11711
- );
12241
+ const counts = /* @__PURE__ */ new Map();
12242
+ for (const d of dirs) for (const a of ancestors(d)) counts.set(a, (counts.get(a) ?? 0) + 1);
12243
+ const root = [...counts].filter(([, n]) => n === list.length).sort((x, y) => y[0].length - x[0].length)[0][0];
12244
+ const need = Math.ceil(list.length * 0.75);
12245
+ const main2 = [...counts].filter(([dir, n]) => n >= need && inside(`${dir}/x`, root)).sort((x, y) => y[0].length - x[0].length || y[1] - x[1] || cmp4(x[0], y[0]))[0][0];
12246
+ const outside = list.length - counts.get(main2);
12247
+ const roles = /* @__PURE__ */ new Map();
12248
+ for (const f of list) {
12249
+ const parts = posix4.basename(f.path).split(".");
12250
+ if (parts.length >= 3)
12251
+ roles.set(parts[parts.length - 2], (roles.get(parts[parts.length - 2]) ?? 0) + 1);
12252
+ }
12253
+ const [role, shared] = [...roles].sort((x, y) => y[1] - x[1] || cmp4(x[0], y[0]))[0] ?? ["", 0];
12254
+ const base2 = `${main2 || "(root)"}${list.length > 1 && shared >= Math.ceil(list.length * 0.6) ? ` \xB7 ${role} files` : ""}`;
12255
+ const name = outside > 0 ? `${base2} (+${outside} elsewhere in ${root || "the repository"})` : base2;
12256
+ return { name, root, main: main2, files: list };
12257
+ }
12258
+ function disambiguate() {
11712
12259
  const seen = /* @__PURE__ */ new Set();
11713
- return named.map((c) => {
11714
- const base2 = c.root || "(root)";
11715
- const first = c.root ? c.files[0].path.slice(c.root.length + 1) : c.files[0].path;
11716
- const name = seen.has(base2) ? `${base2} (${first})` : base2;
11717
- seen.add(base2);
11718
- return { name, root: c.root, files: c.files };
11719
- });
12260
+ return (c) => {
12261
+ const key = c.main || "(root)";
12262
+ const taken = seen.has(key);
12263
+ seen.add(key);
12264
+ if (!taken) return { key, name: c.name, root: c.root, files: c.files };
12265
+ const first = [...c.files].map((f) => f.path).sort(cmp4).find((p) => inside(p, c.main));
12266
+ const within = c.main ? first.slice(c.main.length + 1) : first;
12267
+ return { key: `${key} (${within})`, name: `${c.name} (${within})`, root: c.root, files: c.files };
12268
+ };
11720
12269
  }
11721
12270
  function louvain(n, edges) {
11722
12271
  let assignment = Array.from({ length: n }, (_, i) => i);
@@ -11798,7 +12347,7 @@ function localMoves(n, edges, initial) {
11798
12347
  }
11799
12348
  return { community, moved };
11800
12349
  }
11801
- var DEFAULT_CLUSTER_THRESHOLD, cmp4;
12350
+ var DEFAULT_CLUSTER_THRESHOLD, cmp4, inside, byKey;
11802
12351
  var init_groups = __esm({
11803
12352
  "packages/stage2/src/groups.ts"() {
11804
12353
  "use strict";
@@ -11806,6 +12355,8 @@ var init_groups = __esm({
11806
12355
  init_imports();
11807
12356
  DEFAULT_CLUSTER_THRESHOLD = 200;
11808
12357
  cmp4 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
12358
+ inside = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
12359
+ byKey = (a, b) => cmp4(a.main, b.main) || b.files.length - a.files.length || cmp4(a.files[0].path, b.files[0].path);
11809
12360
  }
11810
12361
  });
11811
12362
 
@@ -12138,6 +12689,47 @@ function link(input2, graph = typeGraph(input2)) {
12138
12689
  };
12139
12690
  return missing(f, "member", `Stage 2 can't tell what instances of ${at(cls)} run for ${m}`);
12140
12691
  };
12692
+ const classMember = (statement, name, member, receiver) => {
12693
+ const f = follow(statement, name, [], 0);
12694
+ const what = receiver === "class" ? `the static ${member}` : member;
12695
+ if (f.kind === "external")
12696
+ return {
12697
+ ...f,
12698
+ steps: [...f.steps, { kind: "instance", detail: `${name} is a class of a package: it runs ${what}` }]
12699
+ };
12700
+ if (f.kind !== "function") return f.kind === "value" ? missing(f, "member", `${name} isn't a class`) : f;
12701
+ if (!f.cls) return missing(f, "member", `${name} is a function, not a class Stage 2 follows members of`);
12702
+ const cls = f.cls;
12703
+ const r = graph.inherited(cls, member, receiver === "class");
12704
+ const kind = receiver === "class" ? "static" : "instance";
12705
+ if (r === "none") return missing(f, "member", `no class up ${at(cls)}'s chain declares ${what}`);
12706
+ if (r === "other")
12707
+ return missing(
12708
+ f,
12709
+ "not-a-function",
12710
+ `${at(cls)}'s ${what} isn't a method (a field, an accessor, or abstract)`
12711
+ );
12712
+ if (r === "unknown")
12713
+ return missing(f, "member", `${at(cls)}'s classes can't all be followed for ${what}`);
12714
+ if ("pkg" in r)
12715
+ return {
12716
+ kind: "external",
12717
+ pkg: r.pkg,
12718
+ steps: [...f.steps, { kind, detail: `${at(cls)} inherits ${what} from a class of ${r.name}` }]
12719
+ };
12720
+ return {
12721
+ kind: "function",
12722
+ fn: r.fn.id,
12723
+ hops: f.hops,
12724
+ steps: [
12725
+ ...f.steps,
12726
+ {
12727
+ kind,
12728
+ detail: r.definer.file === cls.file && r.definer.name === cls.name ? `${at(cls)} declares ${what}` : `${at(cls)} inherits ${what} from ${at(r.definer)}`
12729
+ }
12730
+ ]
12731
+ };
12732
+ };
12141
12733
  const valueCall = (f, name, depth) => {
12142
12734
  const v = f.value;
12143
12735
  if (v.kind === "instance" || v.kind === "object")
@@ -12197,49 +12789,65 @@ function link(input2, graph = typeGraph(input2)) {
12197
12789
  });
12198
12790
  continue;
12199
12791
  }
12200
- const local = /^[\w$]+/.exec(site.expression)?.[0] ?? null;
12201
- const binding2 = statement.statement.bindings.find(([, l]) => l === local);
12202
- const rest = local ? site.expression.slice(local.length) : site.expression;
12203
- let name;
12204
- let member = false;
12205
- if (binding2 && binding2[0] === "*") {
12206
- name = site.importedName && rest === `.${site.importedName}` ? site.importedName : null;
12207
- } else if (binding2 && binding2[0] === null) {
12208
- name = rest === "" ? "default" : site.importedName && rest === `.${site.importedName}` ? site.importedName : null;
12792
+ let found;
12793
+ let steps;
12794
+ let via = "import";
12795
+ if (site.receiver && site.member) {
12796
+ const cls = site.importedName ?? "default";
12797
+ found = classMember(statement, cls, site.member, site.receiver);
12798
+ via = /^(this|super)\./.test(site.expression) ? "inherited" : "import";
12799
+ steps = [
12800
+ {
12801
+ kind: "import",
12802
+ detail: `${site.expression} calls ${site.member} on ${site.receiver === "class" ? "the class" : "an instance of"} ${cls}, imported from ${site.importSpecifier}`
12803
+ },
12804
+ ...found.steps
12805
+ ];
12209
12806
  } else {
12210
- name = site.importedName ?? binding2?.[0] ?? null;
12211
- member = rest !== "" && !/^\.(call|apply|bind)$/.test(rest);
12212
- }
12213
- if (name === null) {
12214
- const t = statement.target;
12215
- resolutions.push({
12216
- ...base2,
12217
- status: t.kind === "package" ? "external" : "unresolved",
12218
- target: null,
12219
- externalPackage: t.kind === "package" ? t.pkg.id : null,
12220
- importOutcome: t.kind === "unresolved" ? t.outcome : null,
12221
- steps: [
12222
- { kind: "import", detail: `${site.expression} goes through ${site.importSpecifier}` },
12223
- ...t.kind === "file" ? [{ kind: "computed", detail: `${site.expression} has no static name to follow` }] : t.steps
12224
- ]
12225
- });
12226
- continue;
12227
- }
12228
- let followed = follow(statement, name, [], 0);
12229
- let path = member ? rest : "";
12230
- if (binding2?.[0] === null && name !== "default" && followed.kind === "missing" && followed.steps.at(-1)?.kind === "not-exported") {
12231
- const whole = follow(statement, "default", [], 0);
12232
- if (whole.kind === "value" || whole.kind === "function" && whole.cls) {
12233
- followed = whole;
12234
- name = "default";
12235
- path = rest;
12807
+ const local = /^[\w$]+/.exec(site.expression)?.[0] ?? null;
12808
+ const binding2 = statement.statement.bindings.find(([, l]) => l === local);
12809
+ const rest = local ? site.expression.slice(local.length) : site.expression;
12810
+ let name;
12811
+ let member = false;
12812
+ if (binding2 && binding2[0] === "*") {
12813
+ name = site.importedName && rest === `.${site.importedName}` ? site.importedName : null;
12814
+ } else if (binding2 && binding2[0] === null) {
12815
+ name = rest === "" ? "default" : site.importedName && rest === `.${site.importedName}` ? site.importedName : null;
12816
+ } else {
12817
+ name = site.importedName ?? binding2?.[0] ?? null;
12818
+ member = rest !== "" && !/^\.(call|apply|bind)$/.test(rest);
12819
+ }
12820
+ if (name === null) {
12821
+ const t = statement.target;
12822
+ resolutions.push({
12823
+ ...base2,
12824
+ status: t.kind === "package" ? "external" : "unresolved",
12825
+ target: null,
12826
+ externalPackage: t.kind === "package" ? t.pkg.id : null,
12827
+ importOutcome: t.kind === "unresolved" ? t.outcome : null,
12828
+ steps: [
12829
+ { kind: "import", detail: `${site.expression} goes through ${site.importSpecifier}` },
12830
+ ...t.kind === "file" ? [{ kind: "computed", detail: `${site.expression} has no static name to follow` }] : t.steps
12831
+ ]
12832
+ });
12833
+ continue;
12834
+ }
12835
+ let followed = follow(statement, name, [], 0);
12836
+ let path = member ? rest : "";
12837
+ if (binding2?.[0] === null && name !== "default" && followed.kind === "missing" && followed.steps.at(-1)?.kind === "not-exported") {
12838
+ const whole = follow(statement, "default", [], 0);
12839
+ if (whole.kind === "value" || whole.kind === "function" && whole.cls) {
12840
+ followed = whole;
12841
+ name = "default";
12842
+ path = rest;
12843
+ }
12236
12844
  }
12845
+ found = settle2(followed, site.expression, name, path);
12846
+ steps = [
12847
+ { kind: "import", detail: `${site.expression} is ${name} imported from ${site.importSpecifier}` },
12848
+ ...found.steps
12849
+ ];
12237
12850
  }
12238
- const found = settle2(followed, site.expression, name, path);
12239
- const steps = [
12240
- { kind: "import", detail: `${site.expression} is ${name} imported from ${site.importSpecifier}` },
12241
- ...found.steps
12242
- ];
12243
12851
  switch (found.kind) {
12244
12852
  case "function":
12245
12853
  resolutions.push({
@@ -12247,7 +12855,7 @@ function link(input2, graph = typeGraph(input2)) {
12247
12855
  status: "linked",
12248
12856
  target: found.fn,
12249
12857
  externalPackage: null,
12250
- via: "import",
12858
+ via,
12251
12859
  importOutcome: null,
12252
12860
  steps,
12253
12861
  hops: found.hops
@@ -16992,14 +17600,14 @@ function codePointLength(str3) {
16992
17600
  const units = str3.length;
16993
17601
  if (!highSurrogate.test(str3))
16994
17602
  return units;
16995
- let count = units;
17603
+ let count2 = units;
16996
17604
  for (let i = 0; i < units - 1; i++) {
16997
17605
  if ((str3.charCodeAt(i) & 64512) === 55296 && (str3.charCodeAt(i + 1) & 64512) === 56320) {
16998
- count--;
17606
+ count2--;
16999
17607
  i++;
17000
17608
  }
17001
17609
  }
17002
- return count;
17610
+ return count2;
17003
17611
  }
17004
17612
  function getLengthableOrigin(input2) {
17005
17613
  if (Array.isArray(input2))
@@ -21462,8 +22070,8 @@ var init_az = __esm({
21462
22070
  });
21463
22071
 
21464
22072
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/locales/be.js
21465
- function getBelarusianPlural(count, one, few, many) {
21466
- const absCount = Math.abs(count);
22073
+ function getBelarusianPlural(count2, one, few, many) {
22074
+ const absCount = Math.abs(count2);
21467
22075
  const lastDigit = absCount % 10;
21468
22076
  const lastTwoDigits = absCount % 100;
21469
22077
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -24236,8 +24844,8 @@ var init_hu = __esm({
24236
24844
  });
24237
24845
 
24238
24846
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/locales/hy.js
24239
- function getArmenianPlural(count, one, many) {
24240
- return Math.abs(count) === 1 ? one : many;
24847
+ function getArmenianPlural(count2, one, many) {
24848
+ return Math.abs(count2) === 1 ? one : many;
24241
24849
  }
24242
24850
  function withDefiniteArticle(word) {
24243
24851
  if (!word)
@@ -27112,8 +27720,8 @@ var init_ro = __esm({
27112
27720
  });
27113
27721
 
27114
27722
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/locales/ru.js
27115
- function getRussianPlural(count, one, few, many) {
27116
- const absCount = Math.abs(count);
27723
+ function getRussianPlural(count2, one, few, many) {
27724
+ const absCount = Math.abs(count2);
27117
27725
  const lastDigit = absCount % 10;
27118
27726
  const lastTwoDigits = absCount % 100;
27119
27727
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -43423,20 +44031,20 @@ var require_resolve = __commonJS({
43423
44031
  return false;
43424
44032
  }
43425
44033
  function countKeys(schema) {
43426
- let count = 0;
44034
+ let count2 = 0;
43427
44035
  for (const key in schema) {
43428
44036
  if (key === "$ref")
43429
44037
  return Infinity;
43430
- count++;
44038
+ count2++;
43431
44039
  if (SIMPLE_INLINED.has(key))
43432
44040
  continue;
43433
44041
  if (typeof schema[key] == "object") {
43434
- (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
44042
+ (0, util_1.eachItem)(schema[key], (sch) => count2 += countKeys(sch));
43435
44043
  }
43436
- if (count === Infinity)
44044
+ if (count2 === Infinity)
43437
44045
  return Infinity;
43438
44046
  }
43439
- return count;
44047
+ return count2;
43440
44048
  }
43441
44049
  function getFullPath(resolver, id = "", normalize2) {
43442
44050
  if (normalize2 !== false)
@@ -46918,8 +47526,8 @@ var require_contains = __commonJS({
46918
47526
  cxt.result(valid, () => cxt.reset());
46919
47527
  function validateItemsWithCount() {
46920
47528
  const schValid = gen.name("_valid");
46921
- const count = gen.let("count", 0);
46922
- validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
47529
+ const count2 = gen.let("count", 0);
47530
+ validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2)));
46923
47531
  }
46924
47532
  function validateItems(_valid, block) {
46925
47533
  gen.forRange("i", 0, len, (i) => {
@@ -46932,16 +47540,16 @@ var require_contains = __commonJS({
46932
47540
  block();
46933
47541
  });
46934
47542
  }
46935
- function checkLimits(count) {
46936
- gen.code((0, codegen_1._)`${count}++`);
47543
+ function checkLimits(count2) {
47544
+ gen.code((0, codegen_1._)`${count2}++`);
46937
47545
  if (max === void 0) {
46938
- gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
47546
+ gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true).break());
46939
47547
  } else {
46940
- gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
47548
+ gen.if((0, codegen_1._)`${count2} > ${max}`, () => gen.assign(valid, false).break());
46941
47549
  if (min === 1)
46942
47550
  gen.assign(valid, true);
46943
47551
  else
46944
- gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
47552
+ gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true));
46945
47553
  }
46946
47554
  }
46947
47555
  }
@@ -50431,13 +51039,24 @@ var init_server3 = __esm({
50431
51039
  },
50432
51040
  call: (e, a, cwd) => crossFileCalls(e, a, cwd)
50433
51041
  },
51042
+ project_totals: {
51043
+ description: "A project's totals as every screen states them (#254): calls within files and across them, the open calls Findings lists (Stage 1's open questions plus calls through imports that couldn't be linked), the own-code functions called most, counting calls from other files, and the files listed: how many were analyzed (fully or partly) and the rest by why not. `stage2: false` means calls across files aren't linked.",
51044
+ input: {
51045
+ project,
51046
+ run,
51047
+ source: external_exports.string().optional().describe("One source only"),
51048
+ top: external_exports.number().int().optional().describe(`How many most-called functions (0 to ${TOTALS_TOP_MAX}; default 10)`)
51049
+ },
51050
+ call: (e, a, cwd) => projectTotals(e, a, cwd)
51051
+ },
50434
51052
  list_groups: {
50435
51053
  description: "The project map (R2): groups of files (workspace packages, repositories, and clusters inside large ones), each with file, function and external-package counts and finding counts; DEPENDS_ON edges between them (imports and cross-file calls, with one as evidence); the external packages (how many, and the most imported); and project totals. `stage2: false` means Stage 2 hasn't run.",
50436
51054
  input: {
50437
51055
  project,
50438
51056
  run,
50439
51057
  source: external_exports.string().optional().describe("One source only"),
50440
- limit: external_exports.number().int().optional().describe(`At most this many groups (1 to ${GROUPS_MAX}; default ${GROUPS_MAX})`)
51058
+ limit: external_exports.number().int().optional().describe(`At most this many groups (1 to ${GROUPS_MAX}; default ${GROUPS_MAX})`),
51059
+ offset: external_exports.number().int().optional().describe("Skip this many groups first (paging; default 0)")
50441
51060
  },
50442
51061
  call: (e, a, cwd) => listGroups(e, a, cwd)
50443
51062
  },
@@ -50466,12 +51085,13 @@ var init_server3 = __esm({
50466
51085
  source: external_exports.string().optional(),
50467
51086
  group: external_exports.string().optional().describe("A group id"),
50468
51087
  file: external_exports.string().optional().describe("A file id"),
50469
- limit: external_exports.number().int().optional().describe(`At most this many (1 to ${FINDINGS_MAX}; default 100)`)
51088
+ limit: external_exports.number().int().optional().describe(`At most this many (1 to ${FINDINGS_MAX}; default 100)`),
51089
+ offset: external_exports.number().int().optional().describe("Skip this many first (paging; default 0); `total` counts them all")
50470
51090
  },
50471
51091
  call: (e, a, cwd) => listFindings(e, a, cwd)
50472
51092
  },
50473
51093
  explain: {
50474
- description: "Why a link, an import or an unresolved call came out as it did (R2): the steps the analysis took, or where they stopped (how an import specifier resolved, each re-export hop, the definition; why a call wasn't resolved; which component a template call was read against). Pass an id (an import, a call, a call site, a resolution or a finding) or a file and a line (everything on that line).",
51094
+ description: "Why a link, an import or an unresolved call came out as it did (R2): the steps the analysis took, or where they stopped (how an import specifier resolved, each re-export hop, the definition; why a call wasn't resolved; which component a template call was read against). Pass an id (an import, a call, a call site, a resolution or a finding) or a file and a line (everything on that line; `file` then says when the file wasn't fully analyzed, and why).",
50475
51095
  input: {
50476
51096
  project,
50477
51097
  run,
@@ -50488,7 +51108,9 @@ var init_server3 = __esm({
50488
51108
  run,
50489
51109
  file: external_exports.string().optional().describe("A file id, to restrict to one file"),
50490
51110
  includeAll: external_exports.boolean().optional(),
50491
- source: external_exports.string().optional().describe("One source only")
51111
+ source: external_exports.string().optional().describe("One source only"),
51112
+ limit: external_exports.number().int().optional().describe("At most this many sites (paging); with it, `total` counts them all"),
51113
+ offset: external_exports.number().int().optional().describe("Skip this many sites first (paging)")
50492
51114
  },
50493
51115
  call: (e, a, cwd) => e.listUnresolvedSites(a, cwd)
50494
51116
  },
@@ -53631,7 +54253,7 @@ var require_fastify_plugin = __commonJS({
53631
54253
  "use strict";
53632
54254
  var getPluginName = require_getPluginName();
53633
54255
  var toCamelCase = require_toCamelCase();
53634
- var count = 0;
54256
+ var count2 = 0;
53635
54257
  function plugin(fn, options = {}) {
53636
54258
  let autoName = false;
53637
54259
  if (fn.default !== void 0) {
@@ -53655,7 +54277,7 @@ var require_fastify_plugin = __commonJS({
53655
54277
  }
53656
54278
  if (!options.name) {
53657
54279
  autoName = true;
53658
- options.name = getPluginName(fn) + "-auto-" + count++;
54280
+ options.name = getPluginName(fn) + "-auto-" + count2++;
53659
54281
  }
53660
54282
  fn[/* @__PURE__ */ Symbol.for("skip-override")] = options.encapsulate !== true;
53661
54283
  fn[/* @__PURE__ */ Symbol.for("fastify.display-name")] = options.name;
@@ -54574,8 +55196,8 @@ var require_depd = __commonJS({
54574
55196
  return deprecate;
54575
55197
  }
54576
55198
  function eehaslisteners(emitter, type) {
54577
- var count = typeof emitter.listenerCount !== "function" ? emitter.listeners(type).length : emitter.listenerCount(type);
54578
- return count > 0;
55199
+ var count2 = typeof emitter.listenerCount !== "function" ? emitter.listeners(type).length : emitter.listenerCount(type);
55200
+ return count2 > 0;
54579
55201
  }
54580
55202
  function isignored(namespace) {
54581
55203
  if (process.noDeprecation) {
@@ -61956,13 +62578,13 @@ var require_stream_writable = __commonJS({
61956
62578
  var buffer = new Array(l);
61957
62579
  var holder = state.corkedRequestsFree;
61958
62580
  holder.entry = entry;
61959
- var count = 0;
62581
+ var count2 = 0;
61960
62582
  var allBuffers = true;
61961
62583
  while (entry) {
61962
- buffer[count] = entry;
62584
+ buffer[count2] = entry;
61963
62585
  if (!entry.isBuf) allBuffers = false;
61964
62586
  entry = entry.next;
61965
- count += 1;
62587
+ count2 += 1;
61966
62588
  }
61967
62589
  buffer.allBuffers = allBuffers;
61968
62590
  doWrite(stream, state, true, state.length, buffer, "", holder.finish);
@@ -79282,9 +79904,9 @@ var require_parseJson = __commonJS({
79282
79904
  pos++;
79283
79905
  } else if (c === "u") {
79284
79906
  pos++;
79285
- let count = 4;
79907
+ let count2 = 4;
79286
79908
  let code = 0;
79287
- while (count--) {
79909
+ while (count2--) {
79288
79910
  code <<= 4;
79289
79911
  c = s[pos];
79290
79912
  if (c === void 0) {
@@ -80718,12 +81340,12 @@ var require_schemes2 = __commonJS({
80718
81340
  mailtoComponent.path = void 0;
80719
81341
  }
80720
81342
  let query = "";
80721
- let count = 0;
81343
+ let count2 = 0;
80722
81344
  for (const name in headers) {
80723
- if (count++ !== 0) query += "&";
81345
+ if (count2++ !== 0) query += "&";
80724
81346
  query += mailtoEncodeHeaderName(name) + "=" + encodeWithAllow(String(headers[name]), HFNAME);
80725
81347
  }
80726
- if (count !== 0) {
81348
+ if (count2 !== 0) {
80727
81349
  mailtoComponent.query = query;
80728
81350
  } else {
80729
81351
  mailtoComponent.headers = void 0;
@@ -91411,6 +92033,24 @@ var init_config = __esm({
91411
92033
  });
91412
92034
 
91413
92035
  // packages/agents/src/grammar.ts
92036
+ function stage2Ran(ctx) {
92037
+ return ctx.engine.readAllStages({ project: ctx.project, ...ctx.run !== void 0 ? { run: ctx.run } : {} }).reader.count("Group") > 0;
92038
+ }
92039
+ function onlyCross(cross, listed) {
92040
+ const seen = new Set(listed.map((c) => c.id));
92041
+ const calls = cross.calls.filter((c) => !seen.has(c.id));
92042
+ return { calls, total: cross.total - (cross.calls.length - calls.length) };
92043
+ }
92044
+ function callTotals(ctx, fn) {
92045
+ const { reader } = ctx.engine.readAllStages({
92046
+ project: ctx.project,
92047
+ ...ctx.run !== void 0 ? { run: ctx.run } : {}
92048
+ });
92049
+ return {
92050
+ callers: reader.callCounts("dst", [fn]).get(fn)?.functions ?? 0,
92051
+ callees: reader.callCounts("src", [fn]).get(fn)?.functions ?? 0
92052
+ };
92053
+ }
91414
92054
  function tool(ctx, name, args, run2) {
91415
92055
  const scoped = ctx.source !== void 0 && SCOPED_TOOLS.has(name) && args.file === void 0;
91416
92056
  ctx.calls.push({
@@ -91612,11 +92252,16 @@ function nameRepositories(engine, project2, results) {
91612
92252
  return repo && item.detail && !item.detail.startsWith(`${repo} \u203A `) ? { ...item, detail: `${repo} \u203A ${item.detail}` } : item;
91613
92253
  });
91614
92254
  }
91615
- var IN_FILE_NOTE, SCOPED_TOOLS, target, plural3, fnItem, fileItem, callers, callees, definition, fileFunctions, fileQuestions, TOP, largestFiles, mostCalled, questionsByReason, filesByQuestions, overview, REASONS, STATUS_WORDS2, LANGUAGE_WORDS, INTENTS, EXAMPLES, HELP_SUMMARY;
92255
+ var IN_FILE_NOTE, fnItemWithTotals, SCOPED_TOOLS, target, plural3, fnItem, fileItem, callers, callees, definition, fileFunctions, fileQuestions, TOP, largestFiles, mostCalled, brokenImports, questionsByReason, filesByQuestions, overview, REASONS, STATUS_WORDS2, LANGUAGE_WORDS, INTENTS, EXAMPLES, HELP_SUMMARY;
91616
92256
  var init_grammar = __esm({
91617
92257
  "packages/agents/src/grammar.ts"() {
91618
92258
  "use strict";
91619
- IN_FILE_NOTE = "Calls are linked within each file for now; calls from other files are not shown yet.";
92259
+ init_src7();
92260
+ IN_FILE_NOTE = "Calls through imports aren't linked in this analysis (Stage 2 didn't run): only calls within each file, and from component templates, are shown.";
92261
+ fnItemWithTotals = (ctx, h) => {
92262
+ const t = callTotals(ctx, h.id);
92263
+ return fnItem({ ...h, callers: t.callers, callees: t.callees });
92264
+ };
91620
92265
  SCOPED_TOOLS = /* @__PURE__ */ new Set(["search_nodes", "aggregate", "list_unresolved_sites"]);
91621
92266
  target = (m) => m[2] ? `${m[1]} in ${m[2]}` : m[1];
91622
92267
  plural3 = (n, one, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
@@ -91647,13 +92292,27 @@ var init_grammar = __esm({
91647
92292
  { function: r.hit.id, direction: "in" },
91648
92293
  () => ctx.engine.listCalls({ project: ctx.project, function: r.hit.id, direction: "in" })
91649
92294
  );
91650
- const fns = new Set(out.calls.map((c) => c.function.id));
92295
+ const cross = tool(
92296
+ ctx,
92297
+ "cross_file_calls",
92298
+ { function: r.hit.id, direction: "in", limit: 500 },
92299
+ () => crossFileCalls(ctx.engine, {
92300
+ project: ctx.project,
92301
+ ...ctx.run !== void 0 ? { run: ctx.run } : {},
92302
+ function: r.hit.id,
92303
+ direction: "in",
92304
+ limit: 500
92305
+ })
92306
+ );
92307
+ const { calls: crossCalls, total: crossTotal } = onlyCross(cross, out.calls);
92308
+ const total = out.calls.length + crossTotal;
92309
+ const fns = /* @__PURE__ */ new Set([...out.calls.map((c) => c.function.id), ...crossCalls.map((c) => c.from.id)]);
92310
+ const linked = stage2Ran(ctx);
91651
92311
  return {
91652
- summary: out.calls.length === 0 ? `No calls to ${say(r.hit.name)} were found.` : `${say(r.hit.name)} is called ${plural3(out.calls.length, "time")} by ${plural3(fns.size, "function")}.`,
91653
- // The caveat matters most when nothing in the file calls it.
91654
- ...out.calls.length === 0 ? { note: IN_FILE_NOTE } : {},
92312
+ summary: total === 0 ? `No calls to ${say(r.hit.name)} were found.` : `${say(r.hit.name)} is called ${plural3(total, "time")} by ${cross.truncated ? "at least " : ""}${plural3(fns.size, "function")}${crossTotal ? ` (${plural3(crossTotal, "call")} from other files)` : ""}.`,
92313
+ ...!linked ? { note: IN_FILE_NOTE } : cross.truncated ? { note: `The first ${cross.calls.length} calls from other files are listed.` } : {},
91655
92314
  results: [
91656
- fnItem(r.hit),
92315
+ fnItemWithTotals(ctx, r.hit),
91657
92316
  ...out.calls.map((c) => ({
91658
92317
  kind: "call",
91659
92318
  id: c.id,
@@ -91665,6 +92324,15 @@ var init_grammar = __esm({
91665
92324
  file: c.evidence.file,
91666
92325
  path: c.function.path,
91667
92326
  line: c.evidence.span.start.line
92327
+ })),
92328
+ ...crossCalls.map((c) => ({
92329
+ kind: "call",
92330
+ id: c.id,
92331
+ label: c.from.name,
92332
+ detail: `${c.from.path}:${c.evidence.span.start.line} \xB7 from another file`,
92333
+ file: c.evidence.file,
92334
+ path: c.from.path,
92335
+ line: c.evidence.span.start.line
91668
92336
  }))
91669
92337
  ],
91670
92338
  suggestions: [`what does ${r.hit.name} call`]
@@ -91680,18 +92348,51 @@ var init_grammar = __esm({
91680
92348
  () => ctx.engine.listCalls({ project: ctx.project, function: r.hit.id, direction: "out" })
91681
92349
  );
91682
92350
  const file2 = r.hit.id.slice(0, r.hit.id.lastIndexOf(":"));
92351
+ const cross = tool(
92352
+ ctx,
92353
+ "cross_file_calls",
92354
+ { function: r.hit.id, direction: "out", limit: 500 },
92355
+ () => crossFileCalls(ctx.engine, {
92356
+ project: ctx.project,
92357
+ ...ctx.run !== void 0 ? { run: ctx.run } : {},
92358
+ function: r.hit.id,
92359
+ direction: "out",
92360
+ limit: 500
92361
+ })
92362
+ );
92363
+ const { reader } = ctx.engine.readAllStages({
92364
+ project: ctx.project,
92365
+ ...ctx.run !== void 0 ? { run: ctx.run } : {}
92366
+ });
92367
+ const resolution = new Map(reader.facts("SiteResolution", file2).map((x) => [x.site, x]));
92368
+ const linkedSites = new Set(cross.calls.map((c) => c.id.replace(/^CALLS_CROSS_FILE\|site\|/, "")));
91683
92369
  const sites = tool(
91684
92370
  ctx,
91685
92371
  "list_unresolved_sites",
91686
92372
  { file: file2, includeAll: true },
91687
92373
  () => ctx.engine.listUnresolvedSites({ project: ctx.project, file: file2, includeAll: true })
91688
- ).sites.filter((s) => s.enclosingFn === r.hit.id);
92374
+ ).sites.filter((s) => s.enclosingFn === r.hit.id && !linkedSites.has(s.id));
92375
+ const nameOf = (id) => {
92376
+ const f = reader.fact(id);
92377
+ return f?.type === "Function" ? `${say(f.qualifiedName)} (${f.file.slice(f.file.indexOf(":") + 1)})` : id;
92378
+ };
92379
+ const { calls: crossCalls, total: crossTotal } = onlyCross(cross, out.calls);
92380
+ const resolved = out.calls.length + crossTotal;
92381
+ const narrowed = sites.filter((s) => resolution.get(s.id)?.candidates?.length).length;
91689
92382
  return {
91690
- summary: `${say(r.hit.name)} makes ${plural3(out.calls.length, "resolved call")}${sites.length ? ` and ${plural3(sites.length, "unresolved call site")}` : ""}.`,
91691
- // The caveat matters most when nothing in the file calls it.
91692
- ...out.calls.length === 0 ? { note: IN_FILE_NOTE } : {},
92383
+ summary: `${say(r.hit.name)} makes ${plural3(resolved, "resolved call")}${crossTotal ? ` (${plural3(crossTotal, "call")} to other files)` : ""}${sites.length ? ` and ${plural3(sites.length, "unresolved call site")}` : ""}${narrowed ? `, ${plural3(narrowed, "with known candidates", "with known candidates")}` : ""}.`,
92384
+ ...!stage2Ran(ctx) ? { note: IN_FILE_NOTE } : {},
91693
92385
  results: [
91694
- fnItem(r.hit),
92386
+ fnItemWithTotals(ctx, r.hit),
92387
+ ...crossCalls.map((c) => ({
92388
+ kind: "call",
92389
+ id: c.id,
92390
+ label: c.to.name,
92391
+ detail: `${r.hit.path}:${c.evidence.span.start.line} \xB7 in ${c.to.path}`,
92392
+ file: c.evidence.file,
92393
+ path: r.hit.path,
92394
+ line: c.evidence.span.start.line
92395
+ })),
91695
92396
  ...out.calls.map((c) => ({
91696
92397
  kind: "call",
91697
92398
  id: c.id,
@@ -91703,15 +92404,20 @@ var init_grammar = __esm({
91703
92404
  path: r.hit.path,
91704
92405
  line: c.evidence.span.start.line
91705
92406
  })),
91706
- ...sites.map((s) => ({
91707
- kind: "site",
91708
- id: s.id,
91709
- label: `? ${s.expression}`,
91710
- detail: `${r.hit.path}:${s.evidence.span.start.line} \xB7 ${REASONS[s.reason] ?? s.reason}`,
91711
- file: s.file,
91712
- path: r.hit.path,
91713
- line: s.evidence.span.start.line
91714
- }))
92407
+ ...sites.map((s) => {
92408
+ const res = resolution.get(s.id);
92409
+ const candidates = res?.candidates ?? [];
92410
+ const why = candidates.length ? `possibly ${candidates.map((c) => nameOf(c.function)).join(" or ")}${res.exhaustive === false ? " (known; there may be others)" : ""}` : REASONS[s.reason] ?? s.reason;
92411
+ return {
92412
+ kind: "site",
92413
+ id: s.id,
92414
+ label: `? ${s.expression}`,
92415
+ detail: `${r.hit.path}:${s.evidence.span.start.line} \xB7 ${why}`,
92416
+ file: s.file,
92417
+ path: r.hit.path,
92418
+ line: s.evidence.span.start.line
92419
+ };
92420
+ })
91715
92421
  ],
91716
92422
  suggestions: [`who calls ${r.hit.name}`]
91717
92423
  };
@@ -91815,12 +92521,33 @@ var init_grammar = __esm({
91815
92521
  };
91816
92522
  };
91817
92523
  mostCalled = (ctx) => {
91818
- const args = { label: "CALLS", groupBy: "to", filters: { ownCode: true } };
91819
- const r = tool(ctx, "aggregate", args, () => ctx.engine.aggregate({ project: ctx.project, ...args }));
91820
- const top = r.groups.slice(0, TOP);
92524
+ const linked = stage2Ran(ctx);
92525
+ let groups2;
92526
+ if (!linked) {
92527
+ const args = { label: "CALLS", groupBy: "to", filters: { ownCode: true } };
92528
+ groups2 = tool(
92529
+ ctx,
92530
+ "aggregate",
92531
+ args,
92532
+ () => ctx.engine.aggregate({ project: ctx.project, ...args })
92533
+ ).groups;
92534
+ } else {
92535
+ const args = { top: TOP, ...ctx.source ? { source: ctx.source } : {} };
92536
+ groups2 = tool(
92537
+ ctx,
92538
+ "project_totals",
92539
+ args,
92540
+ () => projectTotals(ctx.engine, {
92541
+ project: ctx.project,
92542
+ ...ctx.run !== void 0 ? { run: ctx.run } : {},
92543
+ ...args
92544
+ })
92545
+ ).mostCalled.map((f) => ({ key: f.id, name: f.name, count: f.calls }));
92546
+ }
92547
+ const top = groups2.slice(0, TOP);
91821
92548
  return {
91822
92549
  summary: top.length ? `The most-called function is ${say(top[0].name ?? top[0].key)} (${plural3(top[0].count, "call")}).` : "No calls have been found yet.",
91823
- note: IN_FILE_NOTE,
92550
+ ...!linked ? { note: IN_FILE_NOTE } : {},
91824
92551
  results: top.map((g) => {
91825
92552
  const file2 = g.key.slice(0, g.key.lastIndexOf(":"));
91826
92553
  return {
@@ -91835,6 +92562,35 @@ var init_grammar = __esm({
91835
92562
  })
91836
92563
  };
91837
92564
  };
92565
+ brokenImports = (ctx) => {
92566
+ const args = { kind: ["broken"], limit: 50, ...ctx.source ? { source: ctx.source } : {} };
92567
+ const r = tool(
92568
+ ctx,
92569
+ "list_findings",
92570
+ args,
92571
+ () => listFindings(ctx.engine, {
92572
+ project: ctx.project,
92573
+ ...ctx.run !== void 0 ? { run: ctx.run } : {},
92574
+ ...args,
92575
+ kind: ["broken"]
92576
+ })
92577
+ );
92578
+ const n = r.counts.broken;
92579
+ return {
92580
+ summary: n ? `${plural3(n, "broken import")}: imports whose target doesn't exist in the code analyzed.` : "No broken imports were found.",
92581
+ ...n > r.findings.length ? { note: `The first ${r.findings.length} are listed; Findings lists them all.` } : {},
92582
+ results: r.findings.map((f) => ({
92583
+ kind: "file",
92584
+ id: f.file,
92585
+ label: f.text,
92586
+ detail: `${f.path}:${f.line} \xB7 ${f.reason.replace(/-/g, " ")}`,
92587
+ file: f.file,
92588
+ path: f.path,
92589
+ line: f.line
92590
+ })),
92591
+ suggestions: ["open questions by reason", "overview"]
92592
+ };
92593
+ };
91838
92594
  questionsByReason = (ctx) => {
91839
92595
  const r = tool(
91840
92596
  ctx,
@@ -91921,15 +92677,29 @@ var init_grammar = __esm({
91921
92677
  filters: { open: true }
91922
92678
  })
91923
92679
  );
91924
- const group = (id, label, count) => ({
92680
+ const group = (id, label, count2) => ({
91925
92681
  kind: "group",
91926
92682
  id,
91927
92683
  label,
91928
- count
92684
+ count: count2
91929
92685
  });
91930
92686
  const n = (x) => x.toLocaleString("en-US");
92687
+ const totalsArgs = { top: 0, ...ctx.source ? { source: ctx.source } : {} };
92688
+ const totals = stage2Ran(ctx) ? tool(
92689
+ ctx,
92690
+ "project_totals",
92691
+ totalsArgs,
92692
+ () => projectTotals(ctx.engine, {
92693
+ project: ctx.project,
92694
+ ...ctx.run !== void 0 ? { run: ctx.run } : {},
92695
+ ...totalsArgs
92696
+ })
92697
+ ) : null;
91931
92698
  return {
91932
- summary: `${plural3(files.total, "file")}, ${plural3(fns.total, "function")}, ${plural3(calls.total, "call")} and ${plural3(open3.total, "open question")}.`,
92699
+ summary: totals ? `${plural3(files.total, "file")}, ${plural3(fns.total, "function")}, ${plural3(totals.calls.withinFiles + totals.calls.acrossFiles, "call")} (${n(totals.calls.acrossFiles)} across files) and ${plural3(totals.openCalls, "open call")}.` : `${plural3(files.total, "file")}, ${plural3(fns.total, "function")}, ${plural3(calls.total, "call")} and ${plural3(open3.total, "open question")}.`,
92700
+ ...totals && totals.openCalls !== open3.total ? {
92701
+ note: `${plural3(open3.total, "open question")} within files, by reason below; Findings also lists calls through imports that couldn't be linked.`
92702
+ } : {},
91933
92703
  results: [
91934
92704
  ...files.groups.map(
91935
92705
  (g) => group(
@@ -91961,6 +92731,7 @@ var init_grammar = __esm({
91961
92731
  reflection: "reflection",
91962
92732
  "imported-symbol": "imported",
91963
92733
  "runtime-global": "built-in",
92734
+ "builtin-value": "on a built-in value",
91964
92735
  "template-binding": "awaiting its component",
91965
92736
  "template-reference": "registered elsewhere"
91966
92737
  };
@@ -92024,6 +92795,15 @@ var init_grammar = __esm({
92024
92795
  ],
92025
92796
  handle: questionsByReason
92026
92797
  },
92798
+ {
92799
+ // #265: a findings question, not a function's name.
92800
+ name: "broken-imports",
92801
+ patterns: [
92802
+ /^(?:(?:show|list|find)\s+(?:me\s+)?|(?:what|which)\s+are\s+)?(?:the\s+|all\s+)?broken\s+imports?$/,
92803
+ /^(?:which\s+|what\s+)?imports?\s+(?:are\s+)?broken$/
92804
+ ],
92805
+ handle: brokenImports
92806
+ },
92027
92807
  {
92028
92808
  name: "largest-files",
92029
92809
  patterns: [
@@ -92102,8 +92882,8 @@ function toolDefinitions() {
92102
92882
  function systemPrompt(project2) {
92103
92883
  return [
92104
92884
  "You answer questions about a codebase using veoflow's knowledge graph of it.",
92105
- `The project is "${project2}". What the graph holds today: files; functions (with qualified names such as Cart.addItem); calls between functions resolved within each file; and unresolved call sites (dynamic dispatch, imported symbols waiting for cross-file linking, runtime globals).`,
92106
- "Calls across files are not linked yet, so a function can have callers in other files that the graph does not show; say so when it matters.",
92885
+ `The project is "${project2}". What the graph holds today: files; functions (with qualified names such as Cart.addItem); calls between functions resolved within each file; calls across files when cross-file linking (Stage 2) ran; and unresolved call sites (dynamic dispatch, imported symbols, runtime globals).`,
92886
+ "list_calls returns calls within each file; cross_file_calls returns the calls between files. When cross_file_calls finds none and the project has imports, cross-file linking may not have run: say so when it matters.",
92107
92887
  "Always look things up with the tools before answering, even when the question seems general; never guess or rely on memory. Start with search_nodes to find functions or files by name, then use list_calls, file_outline, get_function, list_unresolved_sites or aggregate.",
92108
92888
  'Some names are generated for anonymous functions, such as authRoutes.<callback:post>#5. In your answer describe them in words with their location ("the post callback in authRoutes at src/routes/auth.ts:519") rather than repeating the generated name.',
92109
92889
  "Cite locations exactly as path:line from tool results (for example src/cart.ts:42).",
@@ -92259,9 +93039,9 @@ function splitMentioned(prose, citations, items) {
92259
93039
  if (m && (!at.has(key) || m.index < at.get(key))) at.set(key, m.index);
92260
93040
  }
92261
93041
  }
92262
- const byKey = new Map(items.map((i) => [`${i.kind}:${i.id}`, i]));
92263
- for (const c of citations) if (c.target) byKey.set(`${c.target.kind}:${c.target.id}`, c.target);
92264
- const mentioned = [...at].sort(([, a], [, b]) => a - b).map(([key]) => byKey.get(key)).filter(Boolean);
93042
+ const byKey2 = new Map(items.map((i) => [`${i.kind}:${i.id}`, i]));
93043
+ for (const c of citations) if (c.target) byKey2.set(`${c.target.kind}:${c.target.id}`, c.target);
93044
+ const mentioned = [...at].sort(([, a], [, b]) => a - b).map(([key]) => byKey2.get(key)).filter(Boolean);
92265
93045
  const keys = new Set(mentioned.map((i) => `${i.kind}:${i.id}`));
92266
93046
  return { mentioned, lookups: items.filter((i) => !keys.has(`${i.kind}:${i.id}`)) };
92267
93047
  }
@@ -92436,6 +93216,8 @@ var init_chat = __esm({
92436
93216
  "file_outline",
92437
93217
  "get_function",
92438
93218
  "list_calls",
93219
+ "cross_file_calls",
93220
+ "project_totals",
92439
93221
  "list_unresolved_sites",
92440
93222
  "run_status"
92441
93223
  ];
@@ -92652,11 +93434,26 @@ async function createServer(engine, options = {}) {
92652
93434
  socket.on("close", () => clients.delete(socket));
92653
93435
  });
92654
93436
  app.get("/api/health", async () => ({ ok: true }));
93437
+ const summarizing = /* @__PURE__ */ new Set();
93438
+ const unsummarizable = /* @__PURE__ */ new Set();
93439
+ const ensureCounts = (project2, run2) => {
93440
+ const key = `${project2}\0${run2}`;
93441
+ if (summarizing.has(key) || unsummarizable.has(key)) return;
93442
+ summarizing.add(key);
93443
+ void engine.spawnInternal(["__summarize", project2, String(run2)]).then((outcome) => {
93444
+ if (outcome === "no-runner") summarizeFindings(engine, project2, run2);
93445
+ else if (outcome === "failed") unsummarizable.add(key);
93446
+ }).catch(() => unsummarizable.add(key)).finally(() => summarizing.delete(key));
93447
+ };
92655
93448
  app.get("/api/projects", async (req) => ({
92656
93449
  projects: engine.listProjects().projects.map((p) => {
92657
93450
  if (req.query.findings !== "1" || p.error || p.committedRun === null) return p;
92658
93451
  try {
92659
- return { ...p, findings: listFindings(engine, { project: p.id, limit: 1 }).counts };
93452
+ const kept = keptFindingSummary(engine, p.id, p.committedRun);
93453
+ if (kept) return { ...p, findings: kept.counts, ...kept.files ? { files: kept.files } : {} };
93454
+ if (unsummarizable.has(`${p.id}\0${p.committedRun}`)) return p;
93455
+ if (!engine.runInProgress(p.id)) ensureCounts(p.id, p.committedRun);
93456
+ return { ...p, findingsPending: true };
92660
93457
  } catch {
92661
93458
  return p;
92662
93459
  }
@@ -92944,18 +93741,27 @@ async function createServer(engine, options = {}) {
92944
93741
  params: projectParams,
92945
93742
  querystring: {
92946
93743
  type: "object",
92947
- properties: { file: str2, source: str2, includeAll: { type: "string", enum: ["true", "false"] } }
93744
+ properties: {
93745
+ file: str2,
93746
+ source: str2,
93747
+ includeAll: { type: "string", enum: ["true", "false"] },
93748
+ limit: { type: "string", pattern: "^[1-9][0-9]*$" },
93749
+ offset: { type: "string", pattern: "^(0|[1-9][0-9]*)$" }
93750
+ }
92948
93751
  }
92949
93752
  }
92950
93753
  },
92951
93754
  async (req) => engine.listUnresolvedSites({
92952
93755
  ...req.params,
92953
93756
  ...req.query.file ? { file: req.query.file } : {},
93757
+ ...req.query.limit ? { limit: Number(req.query.limit) } : {},
93758
+ ...req.query.offset ? { offset: Number(req.query.offset) } : {},
92954
93759
  ...req.query.source !== void 0 ? { source: req.query.source } : {},
92955
93760
  includeAll: req.query.includeAll === "true"
92956
93761
  })
92957
93762
  );
92958
93763
  const positive = { type: "string", pattern: "^[1-9][0-9]*$" };
93764
+ const count2 = { type: "string", pattern: "^(0|[1-9][0-9]*)$" };
92959
93765
  const oneOrMore = (item) => ({ anyOf: [item, { type: "array", items: item }] });
92960
93766
  const list = (v) => v === void 0 ? void 0 : Array.isArray(v) ? v : [v];
92961
93767
  app.get(
@@ -92966,14 +93772,15 @@ async function createServer(engine, options = {}) {
92966
93772
  querystring: {
92967
93773
  type: "object",
92968
93774
  additionalProperties: false,
92969
- properties: { source: str2, limit: positive }
93775
+ properties: { source: str2, limit: positive, offset: count2 }
92970
93776
  }
92971
93777
  }
92972
93778
  },
92973
93779
  async (req) => listGroups(engine, {
92974
93780
  ...req.params,
92975
93781
  ...req.query.source !== void 0 ? { source: req.query.source } : {},
92976
- ...req.query.limit ? { limit: Number(req.query.limit) } : {}
93782
+ ...req.query.limit ? { limit: Number(req.query.limit) } : {},
93783
+ ...req.query.offset ? { offset: Number(req.query.offset) } : {}
92977
93784
  })
92978
93785
  );
92979
93786
  app.get(
@@ -93028,18 +93835,20 @@ async function createServer(engine, options = {}) {
93028
93835
  source: str2,
93029
93836
  group: str2,
93030
93837
  file: str2,
93031
- limit: positive
93838
+ limit: positive,
93839
+ offset: count2
93032
93840
  }
93033
93841
  }
93034
93842
  }
93035
93843
  },
93036
93844
  async (req) => {
93037
- const { limit, kind, ...rest } = req.query;
93845
+ const { limit, offset, kind, ...rest } = req.query;
93038
93846
  return listFindings(engine, {
93039
93847
  ...req.params,
93040
93848
  ...rest,
93041
93849
  ...kind !== void 0 ? { kind: list(kind) } : {},
93042
- ...limit ? { limit: Number(limit) } : {}
93850
+ ...limit ? { limit: Number(limit) } : {},
93851
+ ...offset ? { offset: Number(offset) } : {}
93043
93852
  });
93044
93853
  }
93045
93854
  );
@@ -93065,6 +93874,27 @@ async function createServer(engine, options = {}) {
93065
93874
  return crossFileCalls(engine, { ...req.params, ...rest, ...limit ? { limit: Number(limit) } : {} });
93066
93875
  }
93067
93876
  );
93877
+ app.get(
93878
+ "/api/projects/:project/totals",
93879
+ {
93880
+ schema: {
93881
+ params: projectParams,
93882
+ querystring: {
93883
+ type: "object",
93884
+ additionalProperties: false,
93885
+ properties: { source: str2, top: { type: "string", pattern: "^[0-9]+$" } }
93886
+ }
93887
+ }
93888
+ },
93889
+ async (req) => {
93890
+ const { top, ...rest } = req.query;
93891
+ return projectTotals(engine, {
93892
+ ...req.params,
93893
+ ...rest,
93894
+ ...top !== void 0 ? { top: Number(top) } : {}
93895
+ });
93896
+ }
93897
+ );
93068
93898
  app.get(
93069
93899
  "/api/projects/:project/explain",
93070
93900
  {
@@ -93668,6 +94498,10 @@ function describeCheck(r, cwd, projectFlag) {
93668
94498
  `${shown}:${site.line}:${site.column} ${words[site.category] ?? site.category} (${site.stage})`
93669
94499
  );
93670
94500
  out.push(` veoflow: ${site.veoflow}`);
94501
+ if (site.candidates)
94502
+ out.push(
94503
+ ` candidates: ${site.candidates.functions.length} ${site.candidates.exhaustive ? "(all)" : "(known; may not be all)"}${site.candidates.includesCompiler === void 0 ? "" : site.candidates.includesCompiler ? ", the compiler's among them" : ", the compiler's not among them"}`
94504
+ );
93671
94505
  out.push(` compiler: ${site.compiler}`);
93672
94506
  out.push(
93673
94507
  site.changed ? ` why: changed since the analysis; veoflow run, then veoflow explain ${shown}:${site.line}${projectFlag ? ` --project ${projectFlag}` : ""}` : ` why: veoflow explain ${shown}:${site.line}${projectFlag ? ` --project ${projectFlag}` : ""}`
@@ -93736,7 +94570,9 @@ async function runAnalysis(engine, project2, io, source, draft = false, commit =
93736
94570
  ...branch !== void 0 ? { branch } : {},
93737
94571
  ...debug ? { debug: true, ...debug.until !== void 0 ? { until: debug.until } : {} } : {}
93738
94572
  });
93739
- for (const s of run2.sources) for (const n of s.notices ?? []) io.out(` note: ${n}`);
94573
+ for (const s of run2.sources)
94574
+ for (const n of s.notices ?? [])
94575
+ io.out(` note: ${run2.sources.length > 1 ? `${s.sourceId}: ` : ""}${n}`);
93740
94576
  if (draft && run2.kind !== "draft")
93741
94577
  io.out(" note: nothing to draft (no git source, or no analysis yet): this was an ordinary run");
93742
94578
  if (run2.status === "committed" && run2.kind === "draft") {
@@ -93763,8 +94599,8 @@ async function runAnalysis(engine, project2, io, source, draft = false, commit =
93763
94599
  return 0;
93764
94600
  }
93765
94601
  if (run2.status === "committed") {
93766
- const reader = engine.listFiles({ project: project2 });
93767
- io.out(`run ${run2.runId} committed: ${reader.files.length} files`);
94602
+ const { files } = engine.listFiles({ project: project2 });
94603
+ io.out(`run ${run2.runId} committed: ${files.length} files${fileBreakdown(files)}`);
93768
94604
  return 0;
93769
94605
  }
93770
94606
  io.err(`run ${run2.runId} failed: ${run2.error ?? "unknown error"}`);
@@ -93773,6 +94609,39 @@ async function runAnalysis(engine, project2, io, source, draft = false, commit =
93773
94609
  engine.events.off("event", listener);
93774
94610
  }
93775
94611
  }
94612
+ var FILE_REASONS = {
94613
+ "language-not-analyzed": "language not analyzed yet",
94614
+ "parse-failure": "could not be parsed",
94615
+ "declaration-file": "type declarations",
94616
+ "too-large": "over the size limit",
94617
+ minified: "minified",
94618
+ binary: "not text",
94619
+ "invalid-utf8": "not UTF-8",
94620
+ unreadable: "unreadable",
94621
+ entitlement: "beyond the license",
94622
+ frozen: "kept from an earlier analysis"
94623
+ };
94624
+ function fileBreakdown(files) {
94625
+ const analyzed = files.filter((f) => f.status === "analyzed").length;
94626
+ if (analyzed === files.length) return "";
94627
+ const n = (x) => x.toLocaleString("en-US");
94628
+ const why = (list) => {
94629
+ const by = /* @__PURE__ */ new Map();
94630
+ for (const f of list) {
94631
+ const w = FILE_REASONS[f.reason ?? ""] ?? f.reason ?? f.status;
94632
+ by.set(w, (by.get(w) ?? 0) + 1);
94633
+ }
94634
+ const sorted = [...by].sort((a, b) => b[1] - a[1]);
94635
+ return sorted.length === 1 ? sorted[0][0] : sorted.map(([w, c]) => `${n(c)} ${w}`).join(", ");
94636
+ };
94637
+ const partly = files.filter((f) => f.status === "degraded" || f.status === "parse_error");
94638
+ const not = files.filter((f) => f.status === "not_analyzed");
94639
+ return ` (${[
94640
+ `${n(analyzed)} analyzed`,
94641
+ ...partly.length ? [`${n(partly.length)} partly (${why(partly)})`] : [],
94642
+ ...not.length ? [`${n(not.length)} not analyzed (${why(not)})`] : []
94643
+ ].join(", ")})`;
94644
+ }
93776
94645
  function selfCommand() {
93777
94646
  return [process.execPath, resolve8(dirname8(fileURLToPath2(import.meta.url)), "../bin/veoflow.mjs")];
93778
94647
  }
@@ -93799,6 +94668,7 @@ async function serveRun(io) {
93799
94668
  }
93800
94669
  const engine = new Engine(io.home, {
93801
94670
  stages: request.stages.map((n) => known[n]),
94671
+ afterCommit: summarizeFindings,
93802
94672
  ...request.retention ? { retention: request.retention } : {},
93803
94673
  license: request.license,
93804
94674
  killableRuns: true
@@ -93811,6 +94681,17 @@ async function serveRun(io) {
93811
94681
  await last;
93812
94682
  return 0;
93813
94683
  }
94684
+ function usageFor(command) {
94685
+ const out = [];
94686
+ let inside2 = false;
94687
+ for (const line of USAGE.split("\n")) {
94688
+ if (/^ {2}veoflow /.test(line))
94689
+ inside2 = line.startsWith(` veoflow ${command} `) || line === ` veoflow ${command}`;
94690
+ else if (!/^ {3,}/.test(line)) inside2 = false;
94691
+ if (inside2) out.push(line);
94692
+ }
94693
+ return out.length ? out.join("\n") : null;
94694
+ }
93814
94695
  async function main(argv, io) {
93815
94696
  const [command, ...rest] = argv;
93816
94697
  if (!command) {
@@ -93825,8 +94706,29 @@ async function main(argv, io) {
93825
94706
  io.out(version2());
93826
94707
  return 0;
93827
94708
  }
94709
+ if (rest.includes("--help") || rest.includes("-h")) {
94710
+ const lines = usageFor(command);
94711
+ if (lines) {
94712
+ io.out(lines);
94713
+ return 0;
94714
+ }
94715
+ }
93828
94716
  const self2 = io.self ?? selfCommand();
93829
94717
  if (command === "__run") return await serveRun(io);
94718
+ if (command === "__summarize") {
94719
+ const [project2, run2] = rest;
94720
+ if (!project2 || !/^\d+$/.test(run2 ?? "")) {
94721
+ io.err("usage: veoflow __summarize <project> <run>");
94722
+ return 2;
94723
+ }
94724
+ const engine2 = new Engine(io.home);
94725
+ try {
94726
+ summarizeFindings(engine2, project2, Number(run2));
94727
+ } finally {
94728
+ engine2.close();
94729
+ }
94730
+ return 0;
94731
+ }
93830
94732
  if (command === "mcp") {
93831
94733
  const { serveStdio: serveStdio2 } = await Promise.resolve().then(() => (init_src9(), src_exports2));
93832
94734
  await serveStdio2(io.home, version2(), { runner: { command: self2 } });
@@ -93834,6 +94736,8 @@ async function main(argv, io) {
93834
94736
  }
93835
94737
  const engine = new Engine(io.home, {
93836
94738
  stages: [stage2],
94739
+ // Finding counts kept with each run, so the projects home never scans findings (#249).
94740
+ afterCommit: summarizeFindings,
93837
94741
  ...command === "serve" ? { runner: { command: self2 } } : ["run", "add", "include", "exclude"].includes(command) ? { killableRuns: true } : {}
93838
94742
  });
93839
94743
  let keepOpen = false;
@@ -93869,6 +94773,21 @@ async function main(argv, io) {
93869
94773
  if (!existsSync10(root) || !statSync5(root).isDirectory())
93870
94774
  throw new VeoError("source-not-found", `${root} is not a directory`);
93871
94775
  let project2 = values.project ?? engine.catalog.resolveProjectForCwd(io.cwd)?.id;
94776
+ if (values.project !== void 0) {
94777
+ const want = values.project;
94778
+ const all2 = engine.catalog.listProjects();
94779
+ const named = all2.filter((p) => p.name.toLowerCase() === want.toLowerCase());
94780
+ const found = all2.find((p) => p.id === want) ?? (named.length === 1 ? named[0] : void 0);
94781
+ if (!found && named.length > 1)
94782
+ throw new UsageError(
94783
+ `${named.length} projects are named ${want} (${named.map((p) => p.id).join(", ")}); pass one's id`
94784
+ );
94785
+ if (!found)
94786
+ throw new UsageError(
94787
+ `no project ${want}: create it with veoflow init "${want}"${all2.length === 0 ? ", or leave out --project to make one named after the folder" : ""}`
94788
+ );
94789
+ project2 = found.id;
94790
+ }
93872
94791
  if (!project2) {
93873
94792
  const all2 = engine.catalog.listProjects();
93874
94793
  if (all2.length === 1) project2 = all2[0].id;
@@ -94099,7 +95018,7 @@ async function main(argv, io) {
94099
95018
  const mode = values.mode ?? "auto";
94100
95019
  if (mode !== "auto" && mode !== "grammar" && mode !== "model")
94101
95020
  throw new UsageError(`invalid --mode ${mode} (auto, grammar or model)`);
94102
- const { ask: ask2 } = await Promise.resolve().then(() => (init_src10(), src_exports3));
95021
+ const { ask: ask2, say: say2 } = await Promise.resolve().then(() => (init_src10(), src_exports3));
94103
95022
  const project2 = pickProject(engine, values.project, io.cwd);
94104
95023
  const answer = await ask2(engine, engine.catalog.home, project2, positionals.join(" "), {
94105
95024
  mode,
@@ -94117,7 +95036,9 @@ ${plain(answer.prose)}`);
94117
95036
  if (!c.verified) io.out(`unverified: ${c.text} was not returned by any tool`);
94118
95037
  if (answer.results.length) io.out("");
94119
95038
  for (const r of answer.results.slice(0, 25))
94120
- io.out(` ${r.label}${r.detail ? ` (${r.detail})` : ""}`);
95039
+ io.out(
95040
+ ` ${r.kind === "function" || r.kind === "call" ? say2(r.label) : r.label}${r.detail ? ` (${r.detail})` : ""}`
95041
+ );
94121
95042
  if (answer.results.length > 25) io.out(` \u2026 ${answer.results.length - 25} more`);
94122
95043
  if (answer.truncated) io.out(`truncated: ${answer.truncated.reason}`);
94123
95044
  if (answer.suggestions?.length) io.out(`
@@ -94210,11 +95131,26 @@ try: ${answer.suggestions.join(" \xB7 ")}`);
94210
95131
  io.out(JSON.stringify(r, null, 2));
94211
95132
  return 0;
94212
95133
  }
94213
- if (r.items.length === 0) io.out(`nothing to explain on line ${m[2]} of ${file2}`);
95134
+ if (r.file?.status === "not_analyzed")
95135
+ io.out(
95136
+ `${m[1]} isn't analyzed (${FILE_REASONS[r.file.reason ?? ""] ?? r.file.reason ?? "not analyzed"}), so there is nothing to explain on line ${m[2]}`
95137
+ );
95138
+ else if (r.items.length === 0) io.out(`nothing to explain on line ${m[2]} of ${file2}`);
95139
+ if (r.file && r.file.status !== "not_analyzed")
95140
+ io.out(
95141
+ `note: ${m[1]} was only partly analyzed (${FILE_REASONS[r.file.reason ?? ""] ?? r.file.reason ?? r.file.status})`
95142
+ );
95143
+ const flat = (t, max = 160) => {
95144
+ const one = t.replace(/\s+/g, " ").trim();
95145
+ return one.length > max ? `${one.slice(0, max - 1)}\u2026` : one;
95146
+ };
94214
95147
  for (const item of r.items) {
94215
- io.out(`${item.subject} ${item.outcome} (${item.path}${item.line ? `:${item.line}` : ""})`);
94216
- io.out(` ${item.summary}`);
94217
- for (const [i, step] of item.steps.entries()) io.out(` ${i + 1}. ${step.detail}`);
95148
+ io.out(
95149
+ `${flat(item.subject, 80)} ${item.outcome} (${item.path}${item.line ? `:${item.line}` : ""})`
95150
+ );
95151
+ io.out(` ${flat(item.summary)}`);
95152
+ const steps = item.steps[0]?.detail === item.summary ? item.steps.slice(1) : item.steps;
95153
+ for (const [i, step] of steps.entries()) io.out(` ${i + 1}. ${flat(step.detail)}`);
94218
95154
  for (const c of item.candidates ?? []) io.out(` could be ${c.name} (${c.path})`);
94219
95155
  }
94220
95156
  if (r.truncated) io.out(`(${r.total - r.items.length} more not shown; use --json)`);
@@ -94450,5 +95386,7 @@ function plain(text) {
94450
95386
  return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
94451
95387
  }
94452
95388
  export {
94453
- main
95389
+ fileBreakdown,
95390
+ main,
95391
+ usageFor
94454
95392
  };