megareviewer 0.2.3 → 0.2.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/server.js CHANGED
@@ -265,16 +265,16 @@ var init_values = __esm({
265
265
  var sleep;
266
266
  var init_sleep = __esm({
267
267
  "node_modules/.pnpm/@anthropic-ai+sdk@0.137.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"() {
268
- sleep = (ms, signal) => new Promise((resolve3) => {
268
+ sleep = (ms, signal) => new Promise((resolve4) => {
269
269
  if (signal?.aborted)
270
- return resolve3();
270
+ return resolve4();
271
271
  const onAbort = () => {
272
272
  clearTimeout(timer);
273
- resolve3();
273
+ resolve4();
274
274
  };
275
275
  const timer = setTimeout(() => {
276
276
  signal?.removeEventListener("abort", onAbort);
277
- resolve3();
277
+ resolve4();
278
278
  }, ms);
279
279
  signal?.addEventListener("abort", onAbort, { once: true });
280
280
  });
@@ -4864,8 +4864,8 @@ var init_api_promise = __esm({
4864
4864
  APIPromise = /* @__PURE__ */ (() => {
4865
4865
  class APIPromise2 extends Promise {
4866
4866
  constructor(client, responsePromise, parseResponse = defaultParseResponse) {
4867
- super((resolve3) => {
4868
- resolve3(null);
4867
+ super((resolve4) => {
4868
+ resolve4(null);
4869
4869
  });
4870
4870
  this.responsePromise = responsePromise;
4871
4871
  this.parseResponse = parseResponse;
@@ -5711,12 +5711,12 @@ var init_MessageStream = __esm({
5711
5711
  }
5712
5712
  return this._emit("error", new AnthropicError(String(error62)));
5713
5713
  });
5714
- __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve3, reject) => {
5715
- __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve3, "f");
5714
+ __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve4, reject) => {
5715
+ __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve4, "f");
5716
5716
  __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f");
5717
5717
  }), "f");
5718
- __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve3, reject) => {
5719
- __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve3, "f");
5718
+ __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve4, reject) => {
5719
+ __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve4, "f");
5720
5720
  __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f");
5721
5721
  }), "f");
5722
5722
  __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => {
@@ -5908,11 +5908,11 @@ var init_MessageStream = __esm({
5908
5908
  * const message = await stream.emitted('message') // rejects if the stream errors
5909
5909
  */
5910
5910
  emitted(event) {
5911
- return new Promise((resolve3, reject) => {
5911
+ return new Promise((resolve4, reject) => {
5912
5912
  __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
5913
5913
  if (event !== "error")
5914
5914
  this.once("error", reject);
5915
- this.once(event, resolve3);
5915
+ this.once(event, resolve4);
5916
5916
  });
5917
5917
  }
5918
5918
  async done() {
@@ -6247,7 +6247,7 @@ var init_MessageStream = __esm({
6247
6247
  if (done) {
6248
6248
  return { value: void 0, done: true };
6249
6249
  }
6250
- return new Promise((resolve3, reject) => readQueue.push({ resolve: resolve3, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
6250
+ return new Promise((resolve4, reject) => readQueue.push({ resolve: resolve4, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
6251
6251
  }
6252
6252
  const chunk = pushQueue.shift();
6253
6253
  return { value: chunk, done: false };
@@ -8890,16 +8890,16 @@ var init_async_queue = __esm({
8890
8890
  if (__classPrivateFieldGet(this, _AsyncQueue_closed, "f") || signal?.aborted) {
8891
8891
  return Promise.resolve({ done: true, value: void 0 });
8892
8892
  }
8893
- return new Promise((resolve3) => {
8893
+ return new Promise((resolve4) => {
8894
8894
  const waiter = (r) => {
8895
8895
  signal?.removeEventListener("abort", onAbort);
8896
- resolve3(r);
8896
+ resolve4(r);
8897
8897
  };
8898
8898
  const onAbort = () => {
8899
8899
  const idx = __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").indexOf(waiter);
8900
8900
  if (idx >= 0)
8901
8901
  __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").splice(idx, 1);
8902
- resolve3({ done: true, value: void 0 });
8902
+ resolve4({ done: true, value: void 0 });
8903
8903
  };
8904
8904
  __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").push(waiter);
8905
8905
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -9626,13 +9626,13 @@ var init_json_schema = __esm({
9626
9626
 
9627
9627
  // node_modules/.pnpm/@anthropic-ai+sdk@0.137.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs
9628
9628
  function promiseWithResolvers() {
9629
- let resolve3;
9629
+ let resolve4;
9630
9630
  let reject;
9631
9631
  const promise2 = new Promise((res, rej) => {
9632
- resolve3 = res;
9632
+ resolve4 = res;
9633
9633
  reject = rej;
9634
9634
  });
9635
- return { promise: promise2, resolve: resolve3, reject };
9635
+ return { promise: promise2, resolve: resolve4, reject };
9636
9636
  }
9637
9637
  var init_promise = __esm({
9638
9638
  "node_modules/.pnpm/@anthropic-ai+sdk@0.137.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs"() {
@@ -9784,10 +9784,10 @@ async function setupSkills(ctx) {
9784
9784
  for (const skill of session.agent.skills) {
9785
9785
  try {
9786
9786
  const version3 = await client.beta.skills.versions.retrieve(skill.version, { skill_id: skill.skill_id });
9787
- let dirname5 = path.basename(version3.name.trim());
9788
- if (dirname5 === "" || dirname5 === "." || dirname5 === "..")
9789
- dirname5 = skill.skill_id;
9790
- const dest = path.resolve(skillsRoot, dirname5);
9787
+ let dirname6 = path.basename(version3.name.trim());
9788
+ if (dirname6 === "" || dirname6 === "." || dirname6 === "..")
9789
+ dirname6 = skill.skill_id;
9790
+ const dest = path.resolve(skillsRoot, dirname6);
9791
9791
  if (dest !== skillsRoot && !dest.startsWith(skillsRoot + path.sep)) {
9792
9792
  log.warn("skill name escapes the skills dir; skipping", {
9793
9793
  component: "agent-tool-context",
@@ -10427,10 +10427,10 @@ async function settledOrAborted(p, signal) {
10427
10427
  return;
10428
10428
  }
10429
10429
  let onAbort;
10430
- const aborted2 = new Promise((resolve3) => {
10431
- onAbort = resolve3;
10430
+ const aborted2 = new Promise((resolve4) => {
10431
+ onAbort = resolve4;
10432
10432
  if (signal.aborted)
10433
- resolve3();
10433
+ resolve4();
10434
10434
  });
10435
10435
  signal.addEventListener("abort", onAbort, { once: true });
10436
10436
  try {
@@ -11514,7 +11514,7 @@ function betaGrepTool(ctx) {
11514
11514
  });
11515
11515
  }
11516
11516
  function runRipgrep(rg, pattern, searchPath, signal) {
11517
- return new Promise((resolve3, reject) => {
11517
+ return new Promise((resolve4, reject) => {
11518
11518
  const proc = cp.spawn(rg, ["-n", "--no-heading", "-e", pattern, "--", searchPath], {
11519
11519
  ...signal ? { signal } : {}
11520
11520
  });
@@ -11536,12 +11536,12 @@ function runRipgrep(rg, pattern, searchPath, signal) {
11536
11536
  if (signal?.aborted)
11537
11537
  return reject(new ToolError("grep: aborted"));
11538
11538
  if (truncated)
11539
- return resolve3(out2 + `
11539
+ return resolve4(out2 + `
11540
11540
  [output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);
11541
11541
  if (code2 === 0)
11542
- return resolve3(out2);
11542
+ return resolve4(out2);
11543
11543
  if (code2 === 1)
11544
- return resolve3("no matches");
11544
+ return resolve4("no matches");
11545
11545
  reject(new ToolError(`grep: rg failed: ${errOut || `exit ${code2}`}`));
11546
11546
  });
11547
11547
  proc.on("error", (e) => {
@@ -11723,8 +11723,8 @@ var init_node2 = __esm({
11723
11723
  `;
11724
11724
  __classPrivateFieldGet(this, _BashSession_proc, "f").stdin.write(wrapped);
11725
11725
  if (__classPrivateFieldGet(this, _BashSession_buf, "f").indexOf(sentinel2) < 0) {
11726
- const { promise: sentinelSeen, resolve: resolve3 } = promiseWithResolvers();
11727
- __classPrivateFieldSet(this, _BashSession_waiting, { sentinel: sentinel2, resolve: resolve3 }, "f");
11726
+ const { promise: sentinelSeen, resolve: resolve4 } = promiseWithResolvers();
11727
+ __classPrivateFieldSet(this, _BashSession_waiting, { sentinel: sentinel2, resolve: resolve4 }, "f");
11728
11728
  let timer;
11729
11729
  let onAbort;
11730
11730
  try {
@@ -11886,8 +11886,8 @@ async function withTimeout(p, ms) {
11886
11886
  try {
11887
11887
  return await Promise.race([
11888
11888
  p.then(() => false, () => false),
11889
- new Promise((resolve3) => {
11890
- timer = setTimeout(() => resolve3(true), ms);
11889
+ new Promise((resolve4) => {
11890
+ timer = setTimeout(() => resolve4(true), ms);
11891
11891
  })
11892
11892
  ]);
11893
11893
  } finally {
@@ -13724,12 +13724,12 @@ var init_BetaMessageStream = __esm({
13724
13724
  }
13725
13725
  return this._emit("error", new AnthropicError(String(error62)));
13726
13726
  });
13727
- __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve3, reject) => {
13728
- __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve3, "f");
13727
+ __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve4, reject) => {
13728
+ __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve4, "f");
13729
13729
  __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
13730
13730
  }), "f");
13731
- __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve3, reject) => {
13732
- __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve3, "f");
13731
+ __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve4, reject) => {
13732
+ __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve4, "f");
13733
13733
  __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f");
13734
13734
  }), "f");
13735
13735
  __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => {
@@ -13924,11 +13924,11 @@ var init_BetaMessageStream = __esm({
13924
13924
  * const message = await stream.emitted('message') // rejects if the stream errors
13925
13925
  */
13926
13926
  emitted(event) {
13927
- return new Promise((resolve3, reject) => {
13927
+ return new Promise((resolve4, reject) => {
13928
13928
  __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
13929
13929
  if (event !== "error")
13930
13930
  this.once("error", reject);
13931
- this.once(event, resolve3);
13931
+ this.once(event, resolve4);
13932
13932
  });
13933
13933
  }
13934
13934
  async done() {
@@ -14316,7 +14316,7 @@ var init_BetaMessageStream = __esm({
14316
14316
  if (done) {
14317
14317
  return { value: void 0, done: true };
14318
14318
  }
14319
- return new Promise((resolve3, reject) => readQueue.push({ resolve: resolve3, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
14319
+ return new Promise((resolve4, reject) => readQueue.push({ resolve: resolve4, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
14320
14320
  }
14321
14321
  const chunk = pushQueue.shift();
14322
14322
  return { value: chunk, done: false };
@@ -26350,13 +26350,13 @@ process.on("warning", (warning) => {
26350
26350
 
26351
26351
  // src/cli/main.ts
26352
26352
  import { existsSync } from "node:fs";
26353
- import { dirname as dirname4, join as join7 } from "node:path";
26353
+ import { dirname as dirname5, join as join8 } from "node:path";
26354
26354
  import { fileURLToPath } from "node:url";
26355
26355
 
26356
26356
  // package.json
26357
26357
  var package_default = {
26358
26358
  name: "megareviewer",
26359
- version: "0.2.3",
26359
+ version: "0.2.4",
26360
26360
  description: "Guided code review for GitHub and Bitbucket Cloud pull requests: intent first, changes sorted by risk, decisions to approve.",
26361
26361
  keywords: [
26362
26362
  "code-review",
@@ -26512,7 +26512,7 @@ init_sdk();
26512
26512
  init_credentials();
26513
26513
  import { randomBytes } from "node:crypto";
26514
26514
  import { mkdirSync } from "node:fs";
26515
- import { join as join4 } from "node:path";
26515
+ import { join as join5 } from "node:path";
26516
26516
  import { setTimeout as sleep2 } from "node:timers/promises";
26517
26517
 
26518
26518
  // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/external.js
@@ -31582,7 +31582,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
31582
31582
  var NONE = 0;
31583
31583
  var ASSUMED = 1;
31584
31584
  var PROVEN = 2;
31585
- function isRecursive(inst, stack, resolve3) {
31585
+ function isRecursive(inst, stack, resolve4) {
31586
31586
  const cached2 = recursive.get(inst);
31587
31587
  if (cached2 !== void 0)
31588
31588
  return cached2 ? PROVEN : NONE;
@@ -31592,7 +31592,7 @@ function isRecursive(inst, stack, resolve3) {
31592
31592
  let result = NONE;
31593
31593
  const check3 = (child) => {
31594
31594
  if (result !== PROVEN && child?._zod) {
31595
- const answer = isRecursive(child, stack, resolve3);
31595
+ const answer = isRecursive(child, stack, resolve4);
31596
31596
  if (answer > result)
31597
31597
  result = answer;
31598
31598
  }
@@ -31603,7 +31603,7 @@ function isRecursive(inst, stack, resolve3) {
31603
31603
  const desc = Object.getOwnPropertyDescriptor(sh, key);
31604
31604
  if (spread && !desc.enumerable)
31605
31605
  continue;
31606
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
31606
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve4) : NONE;
31607
31607
  if (child > answer)
31608
31608
  answer = child;
31609
31609
  }
@@ -31667,7 +31667,7 @@ function isRecursive(inst, stack, resolve3) {
31667
31667
  break;
31668
31668
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
31669
31669
  case "lazy": {
31670
- const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
31670
+ const inner = def._cachedInner ?? (resolve4 ? inst._zod.innerType : void 0);
31671
31671
  merge3(inner ? isRecursive(inner, stack, false) : ASSUMED);
31672
31672
  break;
31673
31673
  }
@@ -46232,41 +46232,212 @@ function date4(params) {
46232
46232
  return _coercedDate(ZodDate, params);
46233
46233
  }
46234
46234
 
46235
+ // src/domain/diff/imports.ts
46236
+ var FAMILIES = {
46237
+ typescript: "javascript",
46238
+ tsx: "javascript",
46239
+ javascript: "javascript"
46240
+ };
46241
+ var languageFamily = (language) => FAMILIES[language] ?? language;
46242
+ var RESOLVED = /* @__PURE__ */ new Set(["typescript", "tsx", "javascript", "python", "go", "java"]);
46243
+ var resolvesImports = (language) => RESOLVED.has(language);
46244
+ var DIRECTORY_PACKAGES = /* @__PURE__ */ new Set(["go", "java"]);
46245
+ var sharesPackage = (language, from, to) => DIRECTORY_PACKAGES.has(language) && dirname2(from) === dirname2(to);
46246
+ var dirname2 = (path4) => path4.slice(0, Math.max(path4.lastIndexOf("/"), 0));
46247
+ var basename = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
46248
+ var join2 = (dir, path4) => dir === "" ? path4 : `${dir}/${path4}`;
46249
+ var stem = (path4) => {
46250
+ const name2 = basename(path4).replace(/\.d\.ts$/, "");
46251
+ const dot = name2.lastIndexOf(".");
46252
+ return join2(dirname2(path4), dot <= 0 ? name2 : name2.slice(0, dot));
46253
+ };
46254
+ var resolve2 = (dir, relative) => {
46255
+ const parts2 = dir === "" ? [] : dir.split("/");
46256
+ for (const part of relative.split("/")) {
46257
+ if (part === "" || part === ".") continue;
46258
+ if (part === "..") {
46259
+ if (parts2.length === 0) return null;
46260
+ parts2.pop();
46261
+ } else {
46262
+ parts2.push(part);
46263
+ }
46264
+ }
46265
+ return parts2.join("/");
46266
+ };
46267
+ var covers = (path4, target, anchored) => {
46268
+ const module2 = /(^|\/)(index|__init__)$/.test(target) ? dirname2(target) : target;
46269
+ const at = anchored ? stem(path4) === target : stem(path4) === target || stem(path4).endsWith(`/${target}`);
46270
+ const inside = anchored ? module2 === "" || path4.startsWith(`${module2}/`) : path4.startsWith(`${module2}/`) || path4.includes(`/${module2}/`);
46271
+ return at || inside;
46272
+ };
46273
+ var JS_EXTENSION = /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;
46274
+ var javascriptReach = (from, { module: module2, names }) => {
46275
+ const bare = module2.replace(JS_EXTENSION, "");
46276
+ if (bare.startsWith(".")) {
46277
+ const target = resolve2(dirname2(from), bare);
46278
+ if (target === null) return null;
46279
+ const reaches2 = (path4) => covers(path4, target, true);
46280
+ return { names, name: reaches2, member: reaches2 };
46281
+ }
46282
+ const aliased = bare.replace(/^[@~#]\//, "");
46283
+ if (!aliased.includes("/")) return null;
46284
+ const reaches = (path4) => covers(path4, aliased, false);
46285
+ return { names, name: reaches, member: reaches };
46286
+ };
46287
+ var pythonReach = (from, { module: module2, names }) => {
46288
+ const dots = /^\.*/.exec(module2)?.[0].length ?? 0;
46289
+ const rest = module2.slice(dots).replaceAll(".", "/");
46290
+ let target = rest;
46291
+ if (dots > 0) {
46292
+ const base = resolve2(dirname2(from), "../".repeat(dots - 1));
46293
+ target = base === null ? null : join2(base, rest).replace(/\/$/, "");
46294
+ }
46295
+ if (target === null) return null;
46296
+ const anchored = dots > 0;
46297
+ const resolved = target;
46298
+ const within = (path4, module3) => covers(path4, module3, anchored);
46299
+ const isModule = (path4) => [resolved, join2(resolved, "__init__")].some(
46300
+ (name2) => anchored ? stem(path4) === name2 : stem(path4) === name2 || stem(path4).endsWith(`/${name2}`)
46301
+ );
46302
+ return {
46303
+ names,
46304
+ name: (path4) => within(path4, resolved),
46305
+ // `from pkg import mod` imports a module, so `mod.f()` reaches pkg/mod.py.
46306
+ member: (path4) => names === null ? within(path4, resolved) : isModule(path4) || names.some((name2) => within(path4, join2(resolved, name2)))
46307
+ };
46308
+ };
46309
+ var goReach = ({ module: module2 }) => {
46310
+ const reaches = (path4) => {
46311
+ const dir = dirname2(path4);
46312
+ return dir !== "" && (module2 === dir || module2.endsWith(`/${dir}`));
46313
+ };
46314
+ return { names: null, name: reaches, member: reaches };
46315
+ };
46316
+ var javaReach = ({ module: module2, names }) => {
46317
+ const path4 = module2.replaceAll(".", "/");
46318
+ const reaches = names?.includes("*") ? (file2) => dirname2(file2) === path4 || dirname2(file2).endsWith(`/${path4}`) : (file2) => (
46319
+ // `import static a.b.C.m` names a member of a/b/C.
46320
+ [path4, dirname2(path4)].some(
46321
+ (target) => target !== "" && (stem(file2) === target || stem(file2).endsWith(`/${target}`))
46322
+ )
46323
+ );
46324
+ return { names: null, name: reaches, member: reaches };
46325
+ };
46326
+ var importReach = (from, language, symbolImport) => {
46327
+ switch (languageFamily(language)) {
46328
+ case "javascript":
46329
+ return javascriptReach(from, symbolImport);
46330
+ case "python":
46331
+ return pythonReach(from, symbolImport);
46332
+ case "go":
46333
+ return goReach(symbolImport);
46334
+ case "java":
46335
+ return javaReach(symbolImport);
46336
+ default:
46337
+ return null;
46338
+ }
46339
+ };
46340
+
46341
+ // src/domain/diff/test-files.ts
46342
+ var basename2 = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
46343
+ var directories = (path4) => path4.split("/").slice(0, -1);
46344
+ var TEST_DIRECTORIES = /* @__PURE__ */ new Set(["__tests__", "test", "tests", "spec"]);
46345
+ var isTestFile = (path4) => {
46346
+ const name2 = basename2(path4);
46347
+ return /\.(test|spec)\.[^.]+$/i.test(name2) || /_(test|spec)\.[^.]+$/i.test(name2) || /^test_.*\.py$/i.test(name2) || /Tests?\.(java|kt)$/.test(name2) || directories(path4).some((directory) => TEST_DIRECTORIES.has(directory.toLowerCase()));
46348
+ };
46349
+
46235
46350
  // src/domain/diff/call-graph.ts
46236
46351
  var MAX_HINTS_PER_HUNK = 10;
46237
46352
  var buildCallGraphHints = (files, symbolsByPath) => {
46238
- const hunks = files.flatMap((file2) => file2.hunks.map((hunk) => ({ path: file2.path, hunk }))).map((entry, order2) => ({ ...entry, order: order2 }));
46353
+ const hunks = files.flatMap((file2) => file2.hunks.map((hunk) => ({ file: file2, hunk }))).map((entry, order2) => ({ ...entry, order: order2 }));
46239
46354
  const changedBy = /* @__PURE__ */ new Map();
46240
- for (const entry of hunks) {
46241
- const added = newLines(entry.hunk, ["add"]);
46242
- for (const definition of symbolsByPath.get(entry.path)?.definitions ?? []) {
46243
- if (!added.some((line) => line >= definition.startLine && line <= definition.endLine)) {
46244
- continue;
46355
+ for (const at of hunks) {
46356
+ for (const definition of changedDefinitions(at.hunk, symbolsByPath.get(at.file.path))) {
46357
+ const changes = changedBy.get(definition.name) ?? [];
46358
+ if (!changes.some((change) => change.definition === definition)) {
46359
+ changedBy.set(definition.name, [...changes, { at, definition }]);
46245
46360
  }
46246
- const changers = changedBy.get(definition.name) ?? [];
46247
- if (!changers.includes(entry)) changedBy.set(definition.name, [...changers, entry]);
46248
46361
  }
46249
46362
  }
46363
+ const reaches = new Map(
46364
+ files.map((file2) => [
46365
+ file2.path,
46366
+ (symbolsByPath.get(file2.path)?.imports ?? []).flatMap(
46367
+ (symbolImport) => (file2.language === null ? null : importReach(file2.path, file2.language, symbolImport)) ?? []
46368
+ )
46369
+ ])
46370
+ );
46371
+ const visible = (from, kind, name2, to) => from.path === to.path || canLink(from, to) && (!resolvesImports(from.language ?? "") || sharesPackage(from.language ?? "", from.path, to.path) || (reaches.get(from.path) ?? []).some((reach) => reachesBy(reach, kind, name2, to.path)));
46250
46372
  return hunks.flatMap((from) => {
46251
46373
  const lines = new Set(newLines(from.hunk, ["add", "context"]));
46252
- const firstLine = /* @__PURE__ */ new Map();
46253
- for (const { name: name2, line } of symbolsByPath.get(from.path)?.references ?? []) {
46254
- const first = firstLine.get(name2);
46255
- if (lines.has(line) && (first === void 0 || line < first)) firstLine.set(name2, line);
46256
- }
46257
- const candidates = [...firstLine].flatMap(
46258
- ([symbol2, line]) => (changedBy.get(symbol2) ?? []).filter((to) => to.hunk.id !== from.hunk.id).map((to) => ({ to, symbol: symbol2, line, sameFile: to.path === from.path }))
46259
- );
46260
- return candidates.sort(
46374
+ const firstUse = { call: /* @__PURE__ */ new Map(), type: /* @__PURE__ */ new Map() };
46375
+ const own2 = symbolsByPath.get(from.file.path);
46376
+ for (const { name: name2, line, kind } of own2?.references ?? []) {
46377
+ if (!lines.has(line)) continue;
46378
+ const reached = (changedBy.get(name2) ?? []).filter(
46379
+ ({ at, definition }) => visible(from.file, kind === "member" ? "member" : "name", name2, at.file) && !(at.file.path === from.file.path && enclosesLine(definition, line))
46380
+ );
46381
+ const local = reached.filter(
46382
+ ({ at, definition }) => at.file.path === from.file.path && enclosesLine(containerOf(definition, own2?.definitions ?? []), line)
46383
+ );
46384
+ const byUse = firstUse[kind === "type" ? "type" : "call"];
46385
+ for (const { at: to } of local.length > 0 ? local : reached) {
46386
+ if (to.hunk.id === from.hunk.id) continue;
46387
+ const uses = byUse.get(to) ?? /* @__PURE__ */ new Map();
46388
+ const first = uses.get(name2);
46389
+ if (first === void 0 || line < first) uses.set(name2, line);
46390
+ byUse.set(to, uses);
46391
+ }
46392
+ }
46393
+ const hints = (use) => [...firstUse[use]].flatMap(
46394
+ ([to, uses]) => [...uses].filter(([symbol2]) => use === "call" || !firstUse.call.get(to)?.has(symbol2)).map(([symbol2, line]) => ({
46395
+ to,
46396
+ symbol: symbol2,
46397
+ line,
46398
+ sameFile: to.file.path === from.file.path
46399
+ }))
46400
+ ).sort(
46261
46401
  (a, b) => Number(b.sameFile) - Number(a.sameFile) || compare(a.symbol, b.symbol) || a.to.order - b.to.order
46262
46402
  ).slice(0, MAX_HINTS_PER_HUNK).map(({ to, symbol: symbol2, line }) => ({
46263
46403
  fromHunkId: from.hunk.id,
46264
46404
  toHunkId: to.hunk.id,
46265
46405
  symbol: symbol2,
46266
- line
46406
+ line,
46407
+ use
46267
46408
  }));
46409
+ return [...hints("call"), ...hints("type")];
46268
46410
  });
46269
46411
  };
46412
+ var changedDefinitionNames = (files, symbolsByPath) => new Map(
46413
+ files.flatMap(
46414
+ (file2) => file2.hunks.map((hunk) => [
46415
+ hunk.id,
46416
+ [...changedDefinitions(hunk, symbolsByPath.get(file2.path))].map(
46417
+ (definition) => definition.name
46418
+ )
46419
+ ])
46420
+ )
46421
+ );
46422
+ var changedDefinitions = (hunk, symbols) => {
46423
+ const changed = /* @__PURE__ */ new Set();
46424
+ for (const line of newLines(hunk, ["add"])) {
46425
+ const around = (symbols?.definitions ?? []).filter(
46426
+ (definition) => line >= definition.startLine && line <= definition.endLine
46427
+ );
46428
+ const span = Math.min(...around.map((definition) => definition.endLine - definition.startLine));
46429
+ for (const definition of around) {
46430
+ if (definition.endLine - definition.startLine === span) changed.add(definition);
46431
+ }
46432
+ }
46433
+ return changed;
46434
+ };
46435
+ var containerOf = (definition, definitions) => definitions.filter(
46436
+ (other) => other !== definition && other.startLine <= definition.startLine && other.endLine >= definition.endLine && other.endLine - other.startLine > definition.endLine - definition.startLine
46437
+ ).sort((a, b) => a.endLine - a.startLine - (b.endLine - b.startLine))[0];
46438
+ var enclosesLine = (definition, line) => definition !== void 0 && line >= definition.startLine && line <= definition.endLine;
46439
+ var canLink = (from, to) => from.language !== null && to.language !== null && languageFamily(from.language) === languageFamily(to.language) && (isTestFile(from.path) || !isTestFile(to.path));
46440
+ var reachesBy = (reach, kind, name2, path4) => kind === "member" ? reach.member(path4) : (reach.names === null || reach.names.includes(name2)) && reach.name(path4);
46270
46441
  var newLines = (hunk, kinds) => hunk.lines.flatMap(
46271
46442
  (line) => kinds.includes(line.kind) && line.newLine !== null ? [line.newLine] : []
46272
46443
  );
@@ -46344,7 +46515,8 @@ var CallGraphHint = external_exports.object({
46344
46515
  fromHunkId: HunkId,
46345
46516
  toHunkId: HunkId,
46346
46517
  symbol: external_exports.string().min(1),
46347
- line: external_exports.number().int().positive()
46518
+ line: external_exports.number().int().positive(),
46519
+ use: external_exports.enum(["call", "type"])
46348
46520
  }).readonly();
46349
46521
 
46350
46522
  // src/domain/diff/hunk-id.ts
@@ -46666,10 +46838,10 @@ var parseHunk = (lines, start3) => {
46666
46838
  };
46667
46839
 
46668
46840
  // src/domain/diff/path.ts
46669
- var basename = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
46670
- var dirname2 = (path4) => path4.slice(0, Math.max(path4.lastIndexOf("/"), 0));
46841
+ var basename3 = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
46842
+ var dirname3 = (path4) => path4.slice(0, Math.max(path4.lastIndexOf("/"), 0));
46671
46843
  var extension = (path4) => {
46672
- const name2 = basename(path4);
46844
+ const name2 = basename3(path4);
46673
46845
  const dot = name2.lastIndexOf(".");
46674
46846
  return dot <= 0 ? "" : name2.slice(dot).toLowerCase();
46675
46847
  };
@@ -46695,7 +46867,7 @@ var LOCKFILE_MANIFESTS = /* @__PURE__ */ new Map([
46695
46867
  ["mix.lock", ["mix.exs"]],
46696
46868
  ["pubspec.lock", ["pubspec.yaml"]]
46697
46869
  ]);
46698
- var isLockfile = (path4) => LOCKFILE_MANIFESTS.has(basename(path4));
46870
+ var isLockfile = (path4) => LOCKFILE_MANIFESTS.has(basename3(path4));
46699
46871
 
46700
46872
  // src/domain/diff/generated.ts
46701
46873
  var MARKERS = [
@@ -46706,7 +46878,7 @@ var MARKERS = [
46706
46878
  var MARKER_LINES = 5;
46707
46879
  var generatedReason = (file2, context2) => {
46708
46880
  const paths = file2.oldPath === null ? [file2.path] : [file2.path, file2.oldPath];
46709
- if (paths.every(isLockfile)) return `lockfile (${basename(file2.path)})`;
46881
+ if (paths.every(isLockfile)) return `lockfile (${basename3(file2.path)})`;
46710
46882
  const attributes2 = paths.map(context2.attributeFor);
46711
46883
  const [attribute] = attributes2;
46712
46884
  if (attribute && attributes2.every((a) => a === attribute)) return `.gitattributes: ${attribute}`;
@@ -46998,13 +47170,13 @@ var findMechanicalProofs = (files, context2) => {
46998
47170
  var lockfileWarnings = (files) => {
46999
47171
  const changed = files.flatMap((file2) => file2.oldPath ? [file2.path, file2.oldPath] : [file2.path]);
47000
47172
  return files.flatMap((file2) => {
47001
- const manifests = LOCKFILE_MANIFESTS.get(basename(file2.path));
47173
+ const manifests = LOCKFILE_MANIFESTS.get(basename3(file2.path));
47002
47174
  if (manifests === void 0) return [];
47003
- const dir = dirname2(file2.path);
47175
+ const dir = dirname3(file2.path);
47004
47176
  const inScope = changed.filter((path4) => dir === "" || path4.startsWith(`${dir}/`));
47005
47177
  const hasManifest = inScope.some(
47006
47178
  (path4) => manifests.some(
47007
- (manifest) => manifest.startsWith("*") ? basename(path4).endsWith(manifest.slice(1)) : basename(path4) === manifest
47179
+ (manifest) => manifest.startsWith("*") ? basename3(path4).endsWith(manifest.slice(1)) : basename3(path4) === manifest
47008
47180
  )
47009
47181
  );
47010
47182
  if (hasManifest) return [];
@@ -47153,7 +47325,11 @@ var TourStep = external_exports.object({
47153
47325
  id: TourStepId,
47154
47326
  title: external_exports.string().min(1),
47155
47327
  explanation: external_exports.string(),
47156
- hunkIds: external_exports.array(HunkId).readonly()
47328
+ hunkIds: external_exports.array(HunkId).readonly(),
47329
+ /** flow: an entry point and the code it runs; supporting: changes no flow runs, by kind. */
47330
+ kind: external_exports.enum(["flow", "supporting"]),
47331
+ /** Hunks of earlier steps this step passes through, in reading order. */
47332
+ via: external_exports.array(HunkId).readonly()
47157
47333
  }).readonly();
47158
47334
  var Tour = external_exports.object({
47159
47335
  steps: external_exports.array(TourStep).readonly(),
@@ -47218,339 +47394,364 @@ var analysisId = (key) => {
47218
47394
  return AnalysisId.parse(`a_${fnv1a64(input2)}`);
47219
47395
  };
47220
47396
 
47221
- // src/domain/review/risk-rules.ts
47222
- var NO_RULE = "No contract rule matched.";
47223
- var basename2 = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
47224
- var directories = (path4) => path4.split("/").slice(0, -1);
47225
- var extension2 = (path4) => {
47226
- const name2 = basename2(path4);
47227
- const dot = name2.lastIndexOf(".");
47228
- return dot <= 0 ? "" : name2.slice(dot).toLowerCase();
47229
- };
47230
- var pathWords = (path4) => (path4.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[0-9]+/g) ?? []).map((word) => word.toLowerCase());
47231
- var TEST_DIRECTORIES = /* @__PURE__ */ new Set(["__tests__", "test", "tests", "spec"]);
47232
- var isTestFile = (path4) => {
47233
- const name2 = basename2(path4);
47234
- return /\.(test|spec)\.[^.]+$/i.test(name2) || /_(test|spec)\.[^.]+$/i.test(name2) || /^test_.*\.py$/i.test(name2) || /Tests?\.(java|kt)$/.test(name2) || directories(path4).some((directory) => TEST_DIRECTORIES.has(directory.toLowerCase()));
47235
- };
47236
- var MANIFESTS = /* @__PURE__ */ new Set([
47237
- "package.json",
47238
- "pnpm-workspace.yaml",
47239
- "Cargo.toml",
47240
- "go.mod",
47241
- "pyproject.toml",
47242
- "Pipfile",
47243
- "Gemfile",
47244
- "composer.json",
47245
- "Podfile",
47246
- "pubspec.yaml",
47247
- "mix.exs",
47248
- "flake.nix",
47249
- "build.gradle",
47250
- "build.gradle.kts",
47251
- "pom.xml"
47252
- ]);
47253
- var SCHEMA_EXTENSIONS = /* @__PURE__ */ new Set([".sql", ".prisma", ".proto", ".graphql", ".gql", ".avsc"]);
47254
- var SCHEMA_DIRECTORIES = /* @__PURE__ */ new Set(["migrations", "migrate"]);
47255
- var CI_BASENAMES = /* @__PURE__ */ new Set([".gitlab-ci.yml", "bitbucket-pipelines.yml", "Jenkinsfile"]);
47256
- var INFRASTRUCTURE_EXTENSIONS = /* @__PURE__ */ new Set([".tf", ".tfvars"]);
47257
- var CONFIG_BASENAMES = /* @__PURE__ */ new Set([".npmrc", "CODEOWNERS", ".gitattributes"]);
47258
- var APP_CONFIG_EXTENSIONS = /* @__PURE__ */ new Set([
47259
- ".yaml",
47260
- ".yml",
47261
- ".json",
47262
- ".toml",
47263
- ".ini",
47264
- ".properties",
47265
- ".conf",
47266
- ".cfg"
47267
- ]);
47268
- var APP_CONFIG_DIRECTORIES = /* @__PURE__ */ new Set(["config", "configs", "conf", "settings"]);
47269
- var SECURITY_WORDS = /* @__PURE__ */ new Set([
47270
- "admin",
47271
- "auth",
47272
- "authn",
47273
- "authz",
47274
- "authentication",
47275
- "authorization",
47276
- "oauth",
47277
- "session",
47278
- "sessions",
47279
- "token",
47280
- "tokens",
47281
- "jwt",
47282
- "permission",
47283
- "permissions",
47284
- "acl",
47285
- "rbac",
47286
- "crypto",
47287
- "secret",
47288
- "secrets",
47289
- "password",
47290
- "passwords",
47291
- "credential",
47292
- "credentials",
47293
- "security",
47294
- "csrf",
47295
- "cors",
47296
- "login",
47297
- "saml",
47298
- "sso"
47299
- ]);
47300
- var PATH_RULES = [
47301
- (path4) => {
47302
- const name2 = basename2(path4);
47303
- const manifest = MANIFESTS.has(name2) || /^requirements.*\.txt$/.test(name2) || extension2(path4) === ".csproj";
47304
- return manifest ? `changes dependencies (${name2})` : null;
47305
- },
47306
- (path4) => SCHEMA_EXTENSIONS.has(extension2(path4)) || directories(path4).some((directory) => SCHEMA_DIRECTORIES.has(directory.toLowerCase())) || /^(openapi|swagger)/i.test(basename2(path4)) ? "changes a schema or migration" : null,
47307
- (path4) => {
47308
- const name2 = basename2(path4);
47309
- const lower = name2.toLowerCase();
47310
- return path4.startsWith(".github/workflows/") || path4.startsWith(".circleci/") || CI_BASENAMES.has(name2) || lower.startsWith("dockerfile") || lower.endsWith(".dockerfile") || lower.startsWith("docker-compose") || /^compose\.ya?ml$/.test(lower) || INFRASTRUCTURE_EXTENSIONS.has(extension2(path4)) ? "changes CI or infrastructure" : null;
47311
- },
47312
- (path4) => {
47313
- const name2 = basename2(path4);
47314
- return CONFIG_BASENAMES.has(name2) || name2.startsWith(".env") || name2.startsWith(".yarnrc") || /^tsconfig.*\.json$/.test(name2) ? `changes repository config (${name2})` : null;
47315
- },
47316
- (path4) => {
47317
- const name2 = basename2(path4);
47318
- const inConfig = directories(path4).some(
47319
- (directory) => APP_CONFIG_DIRECTORIES.has(directory.toLowerCase())
47397
+ // src/domain/review/entry-points.ts
47398
+ var METHODS = "get|post|put|patch|delete|head|options|all";
47399
+ var RECEIVER = String.raw`(?:app|router|server|mux|r|e|g|fastify|\w*(?:Router|router|App))`;
47400
+ var PATH = String.raw`["'\`](\/[^"'\`]*)["'\`]`;
47401
+ var ROUTE_PATTERNS = [
47402
+ // FastAPI and the like: @router.put("/p").
47403
+ (line) => [...line.matchAll(new RegExp(String.raw`@[\w.]+\.(${METHODS})\(\s*${PATH}`, "gi"))].map(
47404
+ ([, method = "", path4 = ""]) => ({ method: method.toUpperCase(), path: path4 })
47405
+ ),
47406
+ // Flask: @app.route("/p", methods=["GET", "POST"]).
47407
+ (line) => {
47408
+ const match2 = new RegExp(String.raw`@[\w.]+\.route\(\s*${PATH}(.*)`).exec(line);
47409
+ if (match2 === null) return [];
47410
+ const [, path4 = "", rest = ""] = match2;
47411
+ const methods = /methods\s*=\s*[[(]([^\])]*)/.exec(rest)?.[1];
47412
+ const listed2 = [...(methods ?? "").matchAll(/["'](\w+)["']/g)].map(
47413
+ ([, m = ""]) => m.toUpperCase()
47320
47414
  );
47321
- return APP_CONFIG_EXTENSIONS.has(extension2(path4)) && (inConfig || /^(config|settings|application)\./i.test(name2)) ? `changes app config (${name2})` : null;
47322
- },
47323
- (path4) => pathWords(path4).some((word) => SECURITY_WORDS.has(word)) ? "auth or security path" : null
47324
- ];
47325
- var DANGEROUS_CALLS = [
47326
- { pattern: /(?<![\w$])eval\s*\(/, label: "eval()" },
47327
- { pattern: /\bnew\s+Function\s*\(/, label: "new Function()" },
47328
- { pattern: /\binnerHTML\b/, label: "innerHTML" },
47329
- { pattern: /\bouterHTML\b/, label: "outerHTML" },
47330
- { pattern: /\binsertAdjacentHTML\b/, label: "insertAdjacentHTML" },
47331
- { pattern: /\bdocument\.write(ln)?\s*\(/, label: "document.write()" },
47332
- { pattern: /\bdangerouslySetInnerHTML\b/, label: "dangerouslySetInnerHTML" },
47333
- { pattern: /\bchild_process\b/, label: "child_process" },
47334
- { pattern: /\brejectUnauthorized\s*:\s*false\b/, label: "rejectUnauthorized: false" },
47335
- { pattern: /\bNODE_TLS_REJECT_UNAUTHORIZED\b/, label: "NODE_TLS_REJECT_UNAUTHORIZED" },
47336
- { pattern: /\bverify\s*=\s*False\b/, label: "verify=False" },
47337
- { pattern: /\bInsecureSkipVerify\s*:\s*true\b/, label: "InsecureSkipVerify" },
47338
- { pattern: /(^|\s)--no-verify\b/, label: "--no-verify" }
47339
- ];
47340
- var TEST_DECLARATIONS = [
47341
- /(?<![\w$.])(it|test|describe)(\.\w+)*\s*\(/,
47342
- /\bdef\s+test_/,
47343
- /\bfunc\s+Test\w*\s*\(/,
47344
- /@Test\b/
47345
- ];
47346
- var TEST_SKIPS = [
47347
- /(?<![\w$.])(it|test|describe)\.(skip|only|todo)\s*\(/,
47348
- /(?<![\w$.])[xf](it|test|describe)\s*\(/,
47349
- /@(Disabled|Ignore)\b/,
47350
- /@pytest\.mark\.skip/,
47351
- /\bt\.Skip(Now|f)?\s*\(/
47352
- ];
47353
- var textOf = (hunk, kind) => hunk.lines.flatMap((line) => line.kind === kind ? [line.text] : []);
47354
- var count = (lines, patterns) => lines.filter((line) => patterns.some((pattern) => pattern.test(line))).length;
47355
- var HUNK_RULES = [
47356
- (hunk) => {
47357
- const added = textOf(hunk, "add");
47358
- const labels = DANGEROUS_CALLS.filter(
47359
- ({ pattern }) => added.some((line) => pattern.test(line))
47360
- ).map(({ label }) => label);
47361
- return labels.length === 0 ? null : `adds ${labels.join(", ")}`;
47415
+ return (listed2.length > 0 ? listed2 : ["GET"]).map((method) => ({ method, path: path4 }));
47362
47416
  },
47363
- (hunk, file2) => {
47364
- if (!isTestFile(file2.path)) return null;
47365
- if (file2.status === "deleted") return "removes tests";
47366
- const removed = count(textOf(hunk, "del"), TEST_DECLARATIONS) - count(textOf(hunk, "add"), TEST_DECLARATIONS);
47367
- return removed > 0 ? "removes tests" : null;
47417
+ // Express, Fastify, Gin, Echo, Chi: app.get("/p", …), r.GET("/p", …).
47418
+ (line) => [
47419
+ ...line.matchAll(
47420
+ new RegExp(String.raw`(?<![\w@.])${RECEIVER}\.(${METHODS})\(\s*${PATH}`, "gi")
47421
+ )
47422
+ ].map(([, method = "", path4 = ""]) => ({ method: method.toUpperCase(), path: path4 })),
47423
+ // Spring: @GetMapping("/p"), @RequestMapping(value = "/p").
47424
+ (line) => {
47425
+ const match2 = new RegExp(
47426
+ String.raw`@(Get|Post|Put|Patch|Delete|Request)Mapping\(\s*(?:(?:value|path)\s*=\s*)?${PATH}`
47427
+ ).exec(line);
47428
+ if (match2 === null) return [];
47429
+ const [, verb = "", path4 = ""] = match2;
47430
+ return [{ method: verb === "Request" ? "ALL" : verb.toUpperCase(), path: path4 }];
47368
47431
  },
47369
- (hunk, file2) => isTestFile(file2.path) && count(textOf(hunk, "add"), TEST_SKIPS) > 0 ? "skips tests" : null
47432
+ // Go's net/http: mux.HandleFunc("/p", …) and, since Go 1.22, HandleFunc("GET /p", …).
47433
+ (line) => {
47434
+ const match2 = /\bHandle(?:Func)?\(\s*"(?:([A-Z]+) )?(\/[^"]*)"/.exec(line);
47435
+ if (match2 === null) return [];
47436
+ const [, method = "ALL", path4 = ""] = match2;
47437
+ return [{ method, path: path4 }];
47438
+ }
47370
47439
  ];
47371
- var raiseByRules = (assessments, rules) => {
47372
- const byHunk = new Map(rules.map((rule) => [rule.hunkId, rule]));
47373
- return assessments.map((assessment) => {
47374
- const rule = byHunk.get(assessment.hunkId);
47375
- if (rule === void 0 || rule.riskClass !== "contract") return assessment;
47376
- return assessment.riskClass === "contract" ? { ...assessment, reason: `${assessment.reason}; ${rule.reason}` } : rule;
47440
+ var PAGE_DIRECTORIES = /* @__PURE__ */ new Set(["routes", "pages", "app", "screens", "views"]);
47441
+ var isPageFile = (path4) => /\.(tsx|jsx)$/.test(path4) && path4.split("/").slice(0, -1).some((directory) => PAGE_DIRECTORIES.has(directory));
47442
+ var basename4 = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
47443
+ var entryOf = (file2, hunk, definitions) => {
47444
+ const added = hunk.lines.flatMap((line) => line.kind === "add" ? [line.text] : []);
47445
+ const routes2 = added.flatMap((line) => ROUTE_PATTERNS.flatMap((pattern) => pattern(line)));
47446
+ if (routes2.length > 0) return { kind: "route", routes: unique(routes2) };
47447
+ const components = definitions.filter((name2) => /^[A-Z]/.test(name2));
47448
+ if (isPageFile(file2.path) && components.length > 0) return { kind: "page", names: components };
47449
+ if (definitions.includes("main") || added.some((line) => /^\s*if\s+__name__\s*==\s*["']__main__["']/.test(line))) {
47450
+ return { kind: "command", name: "main", path: file2.path };
47451
+ }
47452
+ return null;
47453
+ };
47454
+ var unique = (routes2) => {
47455
+ const seen = /* @__PURE__ */ new Set();
47456
+ return routes2.filter((route) => {
47457
+ const key = `${route.method} ${route.path}`;
47458
+ if (seen.has(key)) return false;
47459
+ seen.add(key);
47460
+ return true;
47377
47461
  });
47378
47462
  };
47379
- var classifyByRules = (files, mechanicalHunkIds) => files.flatMap((file2) => {
47380
- const paths = file2.oldPath === null ? [file2.path] : [file2.path, file2.oldPath];
47381
- const pathReasons = PATH_RULES.flatMap(
47382
- (rule) => paths.map(rule).find((reason) => reason !== null) ?? []
47383
- );
47384
- return file2.hunks.filter((hunk) => !mechanicalHunkIds.has(hunk.id)).map((hunk) => {
47385
- const reasons = [...pathReasons, ...HUNK_RULES.flatMap((rule) => rule(hunk, file2) ?? [])];
47386
- return reasons.length === 0 ? { hunkId: hunk.id, riskClass: "logic", reason: NO_RULE, source: "rule" } : {
47387
- hunkId: hunk.id,
47388
- riskClass: "contract",
47389
- reason: [...new Set(reasons)].join("; "),
47390
- source: "rule"
47391
- };
47463
+ var sharedPrefix = (paths) => {
47464
+ const split = paths.map((path4) => path4.split("/"));
47465
+ const first = split[0] ?? [];
47466
+ let length = 0;
47467
+ while (length < first.length && split.every((parts2) => parts2[length] === first[length])) {
47468
+ length += 1;
47469
+ }
47470
+ return first.slice(0, length).join("/");
47471
+ };
47472
+ var routesLabel = (routes2) => {
47473
+ if (routes2.length === 1) return `${routes2[0]?.method} ${routes2[0]?.path}`;
47474
+ const prefix = sharedPrefix(routes2.map((route) => route.path));
47475
+ if (prefix === "") return routes2.map((route) => `${route.method} ${route.path}`).join(", ");
47476
+ const rest = routes2.map((route) => {
47477
+ const tail = route.path.slice(prefix.length);
47478
+ return tail === "" ? route.method : `${route.method} ${tail}`;
47392
47479
  });
47393
- });
47480
+ return `${prefix}: ${rest.join(", ")}`;
47481
+ };
47482
+ var entryLabel = (entries) => {
47483
+ const routes2 = entries.flatMap((entry) => entry.kind === "route" ? entry.routes : []);
47484
+ const pages = entries.flatMap((entry) => entry.kind === "page" ? entry.names : []);
47485
+ const commands = entries.flatMap((entry) => entry.kind === "command" ? [entry] : []);
47486
+ return [
47487
+ ...routes2.length > 0 ? [routesLabel(unique(routes2))] : [],
47488
+ ...pages.length > 0 ? [`Page: ${[...new Set(pages)].join(", ")}`] : [],
47489
+ ...[...new Set(commands.map((command) => `Command: main in ${basename4(command.path)}`))]
47490
+ ].join("; ");
47491
+ };
47394
47492
 
47395
47493
  // src/domain/review/code-tour.ts
47396
- var MAX_CHAIN = 3;
47397
47494
  var MAX_LISTED = 3;
47398
- var basename3 = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
47399
- var dirname3 = (path4) => path4.slice(0, Math.max(path4.lastIndexOf("/"), 0));
47400
- var stem = (name2) => {
47495
+ var basename5 = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
47496
+ var dirname4 = (path4) => path4.slice(0, Math.max(path4.lastIndexOf("/"), 0));
47497
+ var stem2 = (name2) => {
47401
47498
  const dot = name2.indexOf(".");
47402
47499
  return dot <= 0 ? name2 : name2.slice(0, dot);
47403
47500
  };
47404
47501
  var compare2 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
47405
- var subjectStem = (path4) => {
47406
- const name2 = basename3(path4);
47407
- const base = stem(name2);
47408
- return base.replace(/^test_/i, "").replace(/_(test|spec)$/i, "").replace(/Tests?$/, "");
47409
- };
47410
- var sharedDepth = (a, b) => {
47411
- const left = dirname3(a).split("/");
47412
- const right = dirname3(b).split("/");
47413
- let depth = 0;
47414
- while (depth < left.length && left[depth] === right[depth] && left[depth] !== "") depth += 1;
47415
- return depth;
47416
- };
47417
- var requiredHunks = (file2, required2) => file2.hunks.map((hunk) => hunk.id).filter((id) => required2.has(id));
47418
- var buildUnits = (files, required2, isContract) => {
47419
- const changed = files.filter((file2) => requiredHunks(file2, required2).length > 0);
47420
- const isDoc = (file2) => /\.(md|mdx|rst|adoc)$/i.test(file2.path);
47421
- const subjects = changed.filter((file2) => !isTestFile(file2.path) && !isDoc(file2));
47422
- const members2 = new Map(subjects.map((file2) => [file2.path, [file2]]));
47423
- const join8 = (owner, file2) => {
47424
- const list2 = owner === void 0 ? void 0 : members2.get(owner.path);
47425
- if (list2 === void 0) members2.set(file2.path, [file2]);
47426
- else list2.push(file2);
47427
- };
47428
- for (const test of changed.filter((file2) => isTestFile(file2.path) && !isDoc(file2))) {
47429
- const name2 = subjectStem(test.path);
47430
- const subject = subjects.filter((file2) => stem(basename3(file2.path)) === name2).sort(
47431
- (a, b) => sharedDepth(b.path, test.path) - sharedDepth(a.path, test.path) || compare2(a.path, b.path)
47432
- )[0];
47433
- join8(subject, test);
47434
- }
47435
- for (const doc of changed.filter(isDoc)) {
47436
- const neighbours = subjects.filter((file2) => dirname3(file2.path) === dirname3(doc.path));
47437
- join8(neighbours.length === 1 ? neighbours[0] : void 0, doc);
47438
- }
47439
- return [...members2].map(([path4, list2]) => {
47440
- const hunkIds = list2.flatMap((file2) => requiredHunks(file2, required2));
47441
- return { path: path4, files: list2, hunkIds, contract: hunkIds.filter(isContract).length };
47442
- });
47443
- };
47444
- var byRisk = (a, b) => b.contract - a.contract || compare2(a.path, b.path);
47445
- var area = (path4) => dirname3(path4).split("/").slice(0, 3).join("/");
47502
+ var isDoc = (path4) => /\.(md|mdx|rst|adoc)$/i.test(path4);
47503
+ var isSchema = (path4) => /^(openapi|swagger)\b/i.test(basename5(path4)) || /\.(graphql|gql|proto|avsc|prisma)$/i.test(path4) || /\.schema\.json$/i.test(path4);
47504
+ var looksGenerated = (content) => /@generated\b|auto-?generated|code generated|do not edit/i.test(
47505
+ content.split("\n").slice(0, 5).join("\n")
47506
+ );
47507
+ var subjectNames = (path4) => {
47508
+ const name2 = basename5(path4);
47509
+ const base = stem2(name2);
47510
+ const marked = /\.(test|spec)\./i.test(name2);
47511
+ const names = [
47512
+ base.replace(/^test_/i, "").replace(/_(test|spec)$/i, "").replace(/Tests?$/, ""),
47513
+ base.replace(/^(fakes?|mocks?|stubs?)_/i, "")
47514
+ ];
47515
+ return [...new Set(names)].filter((one) => one !== "" && (marked || one !== base));
47516
+ };
47517
+ var area = (path4) => dirname4(path4).split("/").slice(0, 3).join("/");
47446
47518
  var listed = (items) => {
47447
47519
  const shown = items.slice(0, MAX_LISTED);
47448
47520
  const rest = items.length - shown.length;
47449
47521
  const head = rest > 0 ? [...shown, `${rest} more`] : shown;
47450
47522
  return head.length <= 1 ? head.join("") : `${head.slice(0, -1).join(", ")} and ${head.at(-1)}`;
47451
47523
  };
47452
- var explain = (units) => {
47453
- const files = units.flatMap((unit) => unit.files);
47454
- const areas = [...new Set(files.map((file2) => dirname3(file2.path) || "the repository root"))];
47455
- const tests = files.filter((file2) => isTestFile(file2.path)).map((file2) => basename3(file2.path));
47456
- const count3 = files.length === 1 ? "1 file" : `${files.length} files`;
47457
- const where = `${count3} in ${listed(areas)}`;
47458
- return tests.length === 0 ? `${where}.` : `${where}, tested in ${listed(tests)}.`;
47459
- };
47460
- var codeTour = (files, requiredHunkIds, callGraph, risk) => {
47524
+ var KIND_RANK = { route: 0, page: 1, command: 2, root: 3 };
47525
+ var codeTour = (input2) => {
47526
+ const { files, required: required2, callGraph, risk, definitions } = input2;
47527
+ const generated = input2.generated ?? /* @__PURE__ */ new Set();
47528
+ const located = files.flatMap(
47529
+ (file2) => file2.hunks.filter((hunk) => required2.has(hunk.id)).map((hunk) => ({ file: file2, hunk }))
47530
+ );
47531
+ const ids2 = located.map(({ hunk }) => hunk.id);
47532
+ const order2 = new Map(ids2.map((id, at) => [id, at]));
47533
+ const fileOf = new Map(located.map(({ file: file2, hunk }) => [hunk.id, file2]));
47534
+ const pathOf = (id) => fileOf.get(id)?.path ?? "";
47535
+ const isTest = (id) => isTestFile(pathOf(id));
47536
+ const isCode = (id) => !isTest(id) && !isDoc(pathOf(id));
47537
+ const isSchemaLike = (id) => generated.has(pathOf(id)) || isSchema(pathOf(id));
47461
47538
  const contract = new Set(
47462
47539
  risk.flatMap((assessment) => assessment.riskClass === "contract" ? [assessment.hunkId] : [])
47463
47540
  );
47464
- const units = buildUnits(files, requiredHunkIds, (id) => contract.has(id));
47465
- const unitOf = new Map(units.flatMap((unit) => unit.hunkIds.map((id) => [id, unit])));
47466
- const callees = new Map(units.map((unit) => [unit, /* @__PURE__ */ new Map()]));
47467
- const callers = new Map(units.map((unit) => [unit, /* @__PURE__ */ new Set()]));
47468
- for (const hint of callGraph) {
47469
- const from = unitOf.get(hint.fromHunkId);
47470
- const to = unitOf.get(hint.toHunkId);
47471
- if (from === void 0 || to === void 0 || from === to) continue;
47472
- const edges = callees.get(from);
47473
- const symbol2 = edges?.get(to);
47474
- if (symbol2 === void 0 || hint.symbol < symbol2) edges?.set(to, hint.symbol);
47475
- callers.get(to)?.add(from);
47476
- }
47477
- const calleesOf = (unit) => [...callees.get(unit)?.keys() ?? []].sort(byRisk);
47478
- const linked = (unit) => (callees.get(unit)?.size ?? 0) > 0 || (callers.get(unit)?.size ?? 0) > 0;
47479
- const visited = /* @__PURE__ */ new Set();
47480
- const groups = [];
47481
- const connected = units.filter(linked);
47482
- const groupOf = /* @__PURE__ */ new Map();
47483
- for (const start3 of [...connected].sort(byRisk)) {
47484
- if (groupOf.has(start3)) continue;
47485
- const index = groups.length;
47486
- const queue = [start3];
47487
- for (let unit = queue.pop(); unit !== void 0; unit = queue.pop()) {
47488
- if (groupOf.has(unit)) continue;
47489
- groupOf.set(unit, index);
47490
- queue.push(...callees.get(unit)?.keys() ?? [], ...callers.get(unit) ?? []);
47491
- }
47492
- const members2 = connected.filter((unit) => groupOf.get(unit) === index);
47493
- const order2 = [];
47494
- const visit2 = (unit) => {
47495
- if (visited.has(unit)) return;
47496
- visited.add(unit);
47497
- order2.push(unit);
47498
- for (const callee of calleesOf(unit)) visit2(callee);
47541
+ const edges = () => new Map(ids2.map((id) => [id, []]));
47542
+ const [callees, callers, typeUses, usedAsType] = [edges(), edges(), edges(), edges()];
47543
+ for (const { fromHunkId: from, toHunkId: to, use } of [...callGraph].sort(
47544
+ (a, b) => a.line - b.line
47545
+ )) {
47546
+ if (from === to || !required2.has(from) || !required2.has(to)) continue;
47547
+ const [out2, back] = use === "call" ? [callees, callers] : [typeUses, usedAsType];
47548
+ if (!out2.get(from)?.includes(to)) out2.get(from)?.push(to);
47549
+ if (!back.get(to)?.includes(from)) back.get(to)?.push(from);
47550
+ }
47551
+ const codeCallees = (id) => (callees.get(id) ?? []).filter(isCode);
47552
+ const codeCallers = (id) => (callers.get(id) ?? []).filter(isCode);
47553
+ const reach = (starts2) => {
47554
+ const seen = [];
47555
+ const visit2 = (id) => {
47556
+ if (seen.includes(id)) return;
47557
+ seen.push(id);
47558
+ for (const callee of codeCallees(id)) visit2(callee);
47499
47559
  };
47500
- while (order2.length < members2.length) {
47501
- const left = members2.filter((unit) => !visited.has(unit));
47502
- const entries = left.filter(
47503
- (unit) => ![...callers.get(unit) ?? []].some((caller) => !visited.has(caller))
47504
- );
47505
- const next = (entries.length > 0 ? entries : left).sort(byRisk)[0];
47506
- if (next === void 0) break;
47507
- visit2(next);
47560
+ for (const start3 of starts2) visit2(start3);
47561
+ return seen;
47562
+ };
47563
+ const entryOfHunk = /* @__PURE__ */ new Map();
47564
+ for (const { file: file2, hunk } of located) {
47565
+ if (!isCode(hunk.id)) continue;
47566
+ const entry = entryOf(file2, hunk, definitions.get(hunk.id) ?? []);
47567
+ if (entry !== null) entryOfHunk.set(hunk.id, entry);
47568
+ }
47569
+ const entryGroups = /* @__PURE__ */ new Map();
47570
+ for (const [id, entry] of entryOfHunk) {
47571
+ const names = [...definitions.get(id) ?? []].sort().join(",");
47572
+ const key = entry.kind === "route" || names === "" ? id : `${pathOf(id)}#${names}`;
47573
+ entryGroups.set(key, [...entryGroups.get(key) ?? [], id]);
47574
+ }
47575
+ const wiring = /* @__PURE__ */ new Map();
47576
+ for (const id of ids2.filter(isCode)) {
47577
+ const [first, ...rest] = codeCallees(id);
47578
+ if (first !== void 0 && !entryOfHunk.has(id) && codeCallers(id).length === 0 && [first, ...rest].every((callee) => entryOfHunk.has(callee))) {
47579
+ wiring.set(id, first);
47580
+ }
47581
+ }
47582
+ const roots = ids2.filter(
47583
+ (id) => isCode(id) && !entryOfHunk.has(id) && !wiring.has(id) && codeCallers(id).length === 0 && codeCallees(id).length > 0
47584
+ );
47585
+ const starts = [
47586
+ ...[...entryGroups.values()].map((group) => {
47587
+ const entries = group.flatMap((id) => entryOfHunk.get(id) ?? []);
47588
+ return { starts: group, entries, kind: entries[0]?.kind ?? "root" };
47589
+ }),
47590
+ ...roots.map((root) => ({ starts: [root], entries: [], kind: "root" }))
47591
+ ];
47592
+ const reachesContract = (start3) => reach(start3.starts).some((id) => contract.has(id));
47593
+ const firstAt = (start3) => Math.min(...start3.starts.map((id) => order2.get(id) ?? 0));
47594
+ starts.sort(
47595
+ (a, b) => Number(reachesContract(b)) - Number(reachesContract(a)) || KIND_RANK[a.kind] - KIND_RANK[b.kind] || firstAt(a) - firstAt(b)
47596
+ );
47597
+ const owner = /* @__PURE__ */ new Map();
47598
+ const flows = [];
47599
+ const own2 = (flow, id) => {
47600
+ flow.hunks.push(id);
47601
+ owner.set(id, flow);
47602
+ };
47603
+ for (const start3 of starts) {
47604
+ const reached = reach(start3.starts);
47605
+ const read = reached.filter((id) => owner.has(id));
47606
+ const host = start3.kind === "root" && read.length * 2 >= reached.length - 1 ? mostCommon(read.map((id) => owner.get(id))) : void 0;
47607
+ if (host !== void 0) {
47608
+ for (const id of reached.filter((one) => !owner.has(one))) own2(host, id);
47609
+ continue;
47610
+ }
47611
+ const flow = { ...start3, hunks: [], via: [] };
47612
+ flows.push(flow);
47613
+ for (const id of reached) {
47614
+ if (owner.has(id)) flow.via.push(id);
47615
+ else own2(flow, id);
47508
47616
  }
47509
- groups.push(order2);
47510
47617
  }
47511
- const areas = /* @__PURE__ */ new Map();
47512
- for (const unit of units.filter((one) => !linked(one))) {
47513
- const key = area(unit.path);
47514
- areas.set(key, [...areas.get(key) ?? [], unit].sort(byRisk));
47618
+ for (const [id, entry] of wiring) {
47619
+ const flow = owner.get(entry);
47620
+ if (flow === void 0) continue;
47621
+ flow.hunks.unshift(id);
47622
+ owner.set(id, flow);
47515
47623
  }
47516
- const chainTitle = (group) => {
47517
- let best = [];
47518
- const walk3 = (unit, symbols, seen) => {
47519
- if (symbols.length > best.length) best = [...symbols];
47520
- if (symbols.length === MAX_CHAIN) return;
47521
- for (const callee of calleesOf(unit)) {
47522
- const symbol2 = callees.get(unit)?.get(callee);
47523
- if (symbol2 !== void 0 && !seen.has(callee)) {
47524
- walk3(callee, [...symbols, symbol2], /* @__PURE__ */ new Set([...seen, callee]));
47525
- }
47624
+ const flowWithMostOf = (path4, kind) => mostCommon([...owner].flatMap(([id, flow]) => pathOf(id) === path4 && kind(id) ? [flow] : []));
47625
+ const flowOfSubject = (names) => mostCommon(
47626
+ [...owner].flatMap(
47627
+ ([id, flow]) => isCode(id) && names.includes(stem2(basename5(pathOf(id)))) ? [flow] : []
47628
+ )
47629
+ );
47630
+ const belongsWith = (id) => {
47631
+ const path4 = pathOf(id);
47632
+ if (isSchemaLike(id)) return void 0;
47633
+ if (isCode(id)) {
47634
+ return mostCommon((usedAsType.get(id) ?? []).map((user) => owner.get(user))) ?? flowWithMostOf(path4, isCode);
47635
+ }
47636
+ if (isTest(id)) {
47637
+ const linked = [
47638
+ ...callees.get(id) ?? [],
47639
+ ...typeUses.get(id) ?? [],
47640
+ ...[...callers.get(id) ?? [], ...usedAsType.get(id) ?? []].filter(isTest)
47641
+ ];
47642
+ return mostCommon(linked.map((to) => owner.get(to))) ?? flowWithMostOf(path4, isTest) ?? flowOfSubject(subjectNames(path4));
47643
+ }
47644
+ const here = flows.filter(
47645
+ (flow) => flow.hunks.some((other) => isCode(other) && dirname4(pathOf(other)) === dirname4(path4))
47646
+ );
47647
+ return here.length === 1 ? here[0] : void 0;
47648
+ };
47649
+ for (let joined = true; joined; ) {
47650
+ joined = false;
47651
+ for (const id of ids2.filter((one) => !owner.has(one))) {
47652
+ const flow = belongsWith(id);
47653
+ if (flow !== void 0) {
47654
+ own2(flow, id);
47655
+ joined = true;
47526
47656
  }
47527
- };
47528
- for (const unit of group) walk3(unit, [], /* @__PURE__ */ new Set([unit]));
47529
- const chain = best.join(" \u2192 ");
47530
- const rest = group.length - (best.length + 1);
47531
- return rest > 0 ? `${chain} and ${rest} more` : chain;
47657
+ }
47658
+ }
47659
+ const byOrder = (a, b) => (order2.get(a) ?? 0) - (order2.get(b) ?? 0);
47660
+ for (const flow of flows) {
47661
+ const code2 = [];
47662
+ for (const id of flow.hunks.filter((one) => !isTest(one))) {
47663
+ if (code2.includes(id)) continue;
47664
+ const sameFile = flow.hunks.filter((other) => !isTest(other) && pathOf(other) === pathOf(id));
47665
+ code2.push(...sameFile.sort(byOrder));
47666
+ }
47667
+ flow.hunks.splice(0, flow.hunks.length, ...code2, ...flow.hunks.filter(isTest).sort(byOrder));
47668
+ }
47669
+ const stepOfFlow = new Map(flows.map((flow, at) => [flow, at + 1]));
47670
+ const stepOf = (id) => {
47671
+ const flow = owner.get(id);
47672
+ return flow === void 0 ? void 0 : stepOfFlow.get(flow);
47532
47673
  };
47533
47674
  const steps = [
47534
- ...groups.map((group) => ({ units: group, title: chainTitle(group) })),
47535
- ...[...areas].map(([key, group]) => ({
47536
- units: group,
47537
- title: group.length === 1 ? group[0]?.path ?? key : key || "Repository root"
47538
- }))
47675
+ ...flows.map((flow) => ({
47676
+ title: flowTitle(flow, pathOf, definitions),
47677
+ explanation: flowExplanation(flow, pathOf, isTest, stepOf),
47678
+ hunkIds: flow.hunks,
47679
+ kind: "flow",
47680
+ via: flow.via
47681
+ })),
47682
+ ...supportingSteps(
47683
+ ids2.filter((id) => !owner.has(id)),
47684
+ pathOf,
47685
+ isSchemaLike,
47686
+ isTest,
47687
+ contract
47688
+ )
47539
47689
  ];
47540
- const contractCount = (step) => step.units.reduce((sum, unit) => sum + unit.contract, 0);
47541
- const firstPath = (step) => step.units[0]?.path ?? "";
47542
47690
  return {
47543
- steps: steps.sort((a, b) => contractCount(b) - contractCount(a) || compare2(firstPath(a), firstPath(b))).map(
47544
- (step, index) => ({
47545
- id: TourStepId.parse(`s${index + 1}`),
47546
- title: step.title,
47547
- explanation: explain(step.units),
47548
- hunkIds: step.units.flatMap((unit) => unit.hunkIds)
47549
- })
47550
- ),
47691
+ steps: steps.map((step, index) => ({ id: TourStepId.parse(`s${index + 1}`), ...step })),
47551
47692
  builtBy: "code"
47552
47693
  };
47553
47694
  };
47695
+ var mostCommon = (values) => {
47696
+ const counts = /* @__PURE__ */ new Map();
47697
+ for (const value of values) {
47698
+ if (value !== void 0) counts.set(value, (counts.get(value) ?? 0) + 1);
47699
+ }
47700
+ let best;
47701
+ let most = 0;
47702
+ for (const [value, count3] of counts) {
47703
+ if (count3 > most) {
47704
+ best = value;
47705
+ most = count3;
47706
+ }
47707
+ }
47708
+ return best;
47709
+ };
47710
+ var flowTitle = (flow, pathOf, definitions) => {
47711
+ if (flow.entries.length > 0) return entryLabel(flow.entries);
47712
+ const start3 = flow.starts[0];
47713
+ const path4 = start3 === void 0 ? "" : pathOf(start3);
47714
+ const names = start3 === void 0 ? [] : definitions.get(start3) ?? [];
47715
+ return names.length === 0 ? path4 : `${listed(names)} in ${basename5(path4)}`;
47716
+ };
47717
+ var flowExplanation = (flow, pathOf, isTest, stepOf) => {
47718
+ const names = (ids2) => [...new Set(ids2.map((id) => basename5(pathOf(id))))];
47719
+ const tests = names(flow.hunks.filter(isTest));
47720
+ const earlier = [...new Set(flow.via.flatMap((id) => stepOf(id) ?? []))].sort((a, b) => a - b);
47721
+ const parts2 = [
47722
+ `Reads ${listed(names(flow.hunks.filter((id) => !isTest(id))))}`,
47723
+ ...tests.length > 0 ? [`tested in ${listed(tests)}`] : [],
47724
+ ...earlier.length === 0 ? [] : [
47725
+ `passes through ${earlier.length === 1 ? "step" : "steps"} ${listed(earlier.map(String))}`
47726
+ ]
47727
+ ];
47728
+ return `${parts2.join("; ")}.`;
47729
+ };
47730
+ var SUPPORTING_RANK = { "API schema": 0, Docs: 1, Tests: 2 };
47731
+ var supportingSteps = (left, pathOf, isSchemaLike, isTest, contract) => {
47732
+ const groups = /* @__PURE__ */ new Map();
47733
+ for (const id of left) {
47734
+ const path4 = pathOf(id);
47735
+ const where = area(path4);
47736
+ const title = isSchemaLike(id) ? "API schema" : isDoc(path4) ? "Docs" : isTest(id) ? "Tests" : `Other changes in ${where === "" ? "the repository root" : where}`;
47737
+ groups.set(title, [...groups.get(title) ?? [], id]);
47738
+ }
47739
+ const contractCount = (hunks) => hunks.filter((id) => contract.has(id)).length;
47740
+ const rank = (title) => SUPPORTING_RANK[title] ?? 3;
47741
+ return [...groups].sort(
47742
+ ([titleA, a], [titleB, b]) => contractCount(b) - contractCount(a) || rank(titleA) - rank(titleB) || compare2(titleA, titleB)
47743
+ ).map(([title, hunkIds]) => {
47744
+ const paths = [...new Set(hunkIds.map(pathOf))];
47745
+ const count3 = paths.length === 1 ? "1 file" : `${paths.length} files`;
47746
+ return {
47747
+ title,
47748
+ explanation: `${count3}: ${listed(paths.map(basename5))}. No flow runs ${paths.length === 1 ? "it" : "them"}.`,
47749
+ hunkIds,
47750
+ kind: "supporting",
47751
+ via: []
47752
+ };
47753
+ });
47754
+ };
47554
47755
 
47555
47756
  // src/domain/review/errors.ts
47556
47757
  var HostErrorKind = external_exports.enum([
@@ -47765,6 +47966,181 @@ var pullRequestUrl = (ref) => {
47765
47966
  }
47766
47967
  };
47767
47968
 
47969
+ // src/domain/review/risk-rules.ts
47970
+ var NO_RULE = "No contract rule matched.";
47971
+ var basename6 = (path4) => path4.slice(path4.lastIndexOf("/") + 1);
47972
+ var directories2 = (path4) => path4.split("/").slice(0, -1);
47973
+ var extension2 = (path4) => {
47974
+ const name2 = basename6(path4);
47975
+ const dot = name2.lastIndexOf(".");
47976
+ return dot <= 0 ? "" : name2.slice(dot).toLowerCase();
47977
+ };
47978
+ var pathWords = (path4) => (path4.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[0-9]+/g) ?? []).map((word) => word.toLowerCase());
47979
+ var MANIFESTS = /* @__PURE__ */ new Set([
47980
+ "package.json",
47981
+ "pnpm-workspace.yaml",
47982
+ "Cargo.toml",
47983
+ "go.mod",
47984
+ "pyproject.toml",
47985
+ "Pipfile",
47986
+ "Gemfile",
47987
+ "composer.json",
47988
+ "Podfile",
47989
+ "pubspec.yaml",
47990
+ "mix.exs",
47991
+ "flake.nix",
47992
+ "build.gradle",
47993
+ "build.gradle.kts",
47994
+ "pom.xml"
47995
+ ]);
47996
+ var SCHEMA_EXTENSIONS = /* @__PURE__ */ new Set([".sql", ".prisma", ".proto", ".graphql", ".gql", ".avsc"]);
47997
+ var SCHEMA_DIRECTORIES = /* @__PURE__ */ new Set(["migrations", "migrate"]);
47998
+ var CI_BASENAMES = /* @__PURE__ */ new Set([".gitlab-ci.yml", "bitbucket-pipelines.yml", "Jenkinsfile"]);
47999
+ var INFRASTRUCTURE_EXTENSIONS = /* @__PURE__ */ new Set([".tf", ".tfvars"]);
48000
+ var CONFIG_BASENAMES = /* @__PURE__ */ new Set([".npmrc", "CODEOWNERS", ".gitattributes"]);
48001
+ var APP_CONFIG_EXTENSIONS = /* @__PURE__ */ new Set([
48002
+ ".yaml",
48003
+ ".yml",
48004
+ ".json",
48005
+ ".toml",
48006
+ ".ini",
48007
+ ".properties",
48008
+ ".conf",
48009
+ ".cfg"
48010
+ ]);
48011
+ var APP_CONFIG_DIRECTORIES = /* @__PURE__ */ new Set(["config", "configs", "conf", "settings"]);
48012
+ var SECURITY_WORDS = /* @__PURE__ */ new Set([
48013
+ "admin",
48014
+ "auth",
48015
+ "authn",
48016
+ "authz",
48017
+ "authentication",
48018
+ "authorization",
48019
+ "oauth",
48020
+ "session",
48021
+ "sessions",
48022
+ "token",
48023
+ "tokens",
48024
+ "jwt",
48025
+ "permission",
48026
+ "permissions",
48027
+ "acl",
48028
+ "rbac",
48029
+ "crypto",
48030
+ "secret",
48031
+ "secrets",
48032
+ "password",
48033
+ "passwords",
48034
+ "keychain",
48035
+ "keyring",
48036
+ "credential",
48037
+ "credentials",
48038
+ "security",
48039
+ "csrf",
48040
+ "cors",
48041
+ "login",
48042
+ "saml",
48043
+ "sso"
48044
+ ]);
48045
+ var PATH_RULES = [
48046
+ (path4) => {
48047
+ const name2 = basename6(path4);
48048
+ const manifest = MANIFESTS.has(name2) || /^requirements.*\.txt$/.test(name2) || extension2(path4) === ".csproj";
48049
+ return manifest ? `changes dependencies (${name2})` : null;
48050
+ },
48051
+ (path4) => SCHEMA_EXTENSIONS.has(extension2(path4)) || directories2(path4).some((directory) => SCHEMA_DIRECTORIES.has(directory.toLowerCase())) || /^(openapi|swagger)/i.test(basename6(path4)) ? "changes a schema or migration" : null,
48052
+ (path4) => {
48053
+ const name2 = basename6(path4);
48054
+ const lower = name2.toLowerCase();
48055
+ return path4.startsWith(".github/workflows/") || path4.startsWith(".circleci/") || CI_BASENAMES.has(name2) || lower.startsWith("dockerfile") || lower.endsWith(".dockerfile") || lower.startsWith("docker-compose") || /^compose\.ya?ml$/.test(lower) || INFRASTRUCTURE_EXTENSIONS.has(extension2(path4)) ? "changes CI or infrastructure" : null;
48056
+ },
48057
+ (path4) => {
48058
+ const name2 = basename6(path4);
48059
+ return CONFIG_BASENAMES.has(name2) || name2.startsWith(".env") || name2.startsWith(".yarnrc") || /^tsconfig.*\.json$/.test(name2) ? `changes repository config (${name2})` : null;
48060
+ },
48061
+ (path4) => {
48062
+ const name2 = basename6(path4);
48063
+ const inConfig = directories2(path4).some(
48064
+ (directory) => APP_CONFIG_DIRECTORIES.has(directory.toLowerCase())
48065
+ );
48066
+ return APP_CONFIG_EXTENSIONS.has(extension2(path4)) && (inConfig || /^(config|settings|application)\./i.test(name2)) ? `changes app config (${name2})` : null;
48067
+ },
48068
+ (path4) => pathWords(path4).some((word) => SECURITY_WORDS.has(word)) ? "auth or security path" : null
48069
+ ];
48070
+ var DANGEROUS_CALLS = [
48071
+ { pattern: /(?<![\w$])eval\s*\(/, label: "eval()" },
48072
+ { pattern: /\bnew\s+Function\s*\(/, label: "new Function()" },
48073
+ { pattern: /\binnerHTML\b/, label: "innerHTML" },
48074
+ { pattern: /\bouterHTML\b/, label: "outerHTML" },
48075
+ { pattern: /\binsertAdjacentHTML\b/, label: "insertAdjacentHTML" },
48076
+ { pattern: /\bdocument\.write(ln)?\s*\(/, label: "document.write()" },
48077
+ { pattern: /\bdangerouslySetInnerHTML\b/, label: "dangerouslySetInnerHTML" },
48078
+ { pattern: /\bchild_process\b/, label: "child_process" },
48079
+ { pattern: /\bsubprocess\b/, label: "subprocess" },
48080
+ { pattern: /\bos\.system\s*\(/, label: "os.system()" },
48081
+ { pattern: /\bos\.popen\s*\(/, label: "os.popen()" },
48082
+ { pattern: /\bshell\s*=\s*True\b/, label: "shell=True" },
48083
+ { pattern: /\brejectUnauthorized\s*:\s*false\b/, label: "rejectUnauthorized: false" },
48084
+ { pattern: /\bNODE_TLS_REJECT_UNAUTHORIZED\b/, label: "NODE_TLS_REJECT_UNAUTHORIZED" },
48085
+ { pattern: /\bverify\s*=\s*False\b/, label: "verify=False" },
48086
+ { pattern: /\bInsecureSkipVerify\s*:\s*true\b/, label: "InsecureSkipVerify" },
48087
+ { pattern: /(^|\s)--no-verify\b/, label: "--no-verify" }
48088
+ ];
48089
+ var TEST_DECLARATIONS = [
48090
+ /(?<![\w$.])(it|test|describe)(\.\w+)*\s*\(/,
48091
+ /\bdef\s+test_/,
48092
+ /\bfunc\s+Test\w*\s*\(/,
48093
+ /@Test\b/
48094
+ ];
48095
+ var TEST_SKIPS = [
48096
+ /(?<![\w$.])(it|test|describe)\.(skip|only|todo)\s*\(/,
48097
+ /(?<![\w$.])[xf](it|test|describe)\s*\(/,
48098
+ /@(Disabled|Ignore)\b/,
48099
+ /@pytest\.mark\.skip/,
48100
+ /\bt\.Skip(Now|f)?\s*\(/
48101
+ ];
48102
+ var textOf = (hunk, kind) => hunk.lines.flatMap((line) => line.kind === kind ? [line.text] : []);
48103
+ var count = (lines, patterns) => lines.filter((line) => patterns.some((pattern) => pattern.test(line))).length;
48104
+ var HUNK_RULES = [
48105
+ (hunk) => {
48106
+ const added = textOf(hunk, "add");
48107
+ const labels = DANGEROUS_CALLS.filter(
48108
+ ({ pattern }) => added.some((line) => pattern.test(line))
48109
+ ).map(({ label }) => label);
48110
+ return labels.length === 0 ? null : `adds ${labels.join(", ")}`;
48111
+ },
48112
+ (hunk, file2) => {
48113
+ if (!isTestFile(file2.path)) return null;
48114
+ if (file2.status === "deleted") return "removes tests";
48115
+ const removed = count(textOf(hunk, "del"), TEST_DECLARATIONS) - count(textOf(hunk, "add"), TEST_DECLARATIONS);
48116
+ return removed > 0 ? "removes tests" : null;
48117
+ },
48118
+ (hunk, file2) => isTestFile(file2.path) && count(textOf(hunk, "add"), TEST_SKIPS) > 0 ? "skips tests" : null
48119
+ ];
48120
+ var raiseByRules = (assessments, rules) => {
48121
+ const byHunk = new Map(rules.map((rule) => [rule.hunkId, rule]));
48122
+ return assessments.map((assessment) => {
48123
+ const rule = byHunk.get(assessment.hunkId);
48124
+ if (rule === void 0 || rule.riskClass !== "contract") return assessment;
48125
+ return assessment.riskClass === "contract" ? { ...assessment, reason: `${assessment.reason}; ${rule.reason}` } : rule;
48126
+ });
48127
+ };
48128
+ var classifyByRules = (files, mechanicalHunkIds) => files.flatMap((file2) => {
48129
+ const paths = file2.oldPath === null ? [file2.path] : [file2.path, file2.oldPath];
48130
+ const pathReasons = PATH_RULES.flatMap(
48131
+ (rule) => paths.map(rule).find((reason) => reason !== null) ?? []
48132
+ );
48133
+ return file2.hunks.filter((hunk) => !mechanicalHunkIds.has(hunk.id)).map((hunk) => {
48134
+ const reasons = [...pathReasons, ...HUNK_RULES.flatMap((rule) => rule(hunk, file2) ?? [])];
48135
+ return reasons.length === 0 ? { hunkId: hunk.id, riskClass: "logic", reason: NO_RULE, source: "rule" } : {
48136
+ hunkId: hunk.id,
48137
+ riskClass: "contract",
48138
+ reason: [...new Set(reasons)].join("; "),
48139
+ source: "rule"
48140
+ };
48141
+ });
48142
+ });
48143
+
47768
48144
  // src/domain/review/ticket-keys.ts
47769
48145
  var TICKET_KEY = /\b[A-Z][A-Z0-9]+-\d+\b/g;
47770
48146
  var NOT_TICKETS = /* @__PURE__ */ new Set(["UTF-8", "UTF-16", "SHA-1", "SHA-256", "SHA-512", "ISO-8601"]);
@@ -48393,7 +48769,7 @@ var ModelRisk = external_exports.object({
48393
48769
  reason: external_exports.string()
48394
48770
  }).readonly();
48395
48771
  var DecisionDraft = Decision.unwrap().omit({ id: true }).readonly();
48396
- var TourStepDraft = TourStep.unwrap().omit({ id: true }).readonly();
48772
+ var TourStepDraft = TourStep.unwrap().omit({ id: true, kind: true, via: true }).readonly();
48397
48773
  var TourDraft = external_exports.object({ steps: external_exports.array(TourStepDraft).readonly() }).readonly();
48398
48774
 
48399
48775
  // src/adapters/claude/output-schema.ts
@@ -48415,24 +48791,24 @@ var KEPT = /* @__PURE__ */ new Set([
48415
48791
  "anyOf",
48416
48792
  "description"
48417
48793
  ]);
48418
- var isSchema = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
48794
+ var isSchema2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
48419
48795
  var strict = (schema) => {
48420
48796
  const result = {};
48421
48797
  for (const [name2, value] of Object.entries(schema)) {
48422
48798
  const key = name2 === "oneOf" ? "anyOf" : name2;
48423
48799
  if (!KEPT.has(key)) continue;
48424
- if (key === "properties" && isSchema(value)) {
48800
+ if (key === "properties" && isSchema2(value)) {
48425
48801
  result[key] = Object.fromEntries(
48426
48802
  Object.entries(value).map(([name3, property]) => [
48427
48803
  name3,
48428
- isSchema(property) ? strict(property) : property
48804
+ isSchema2(property) ? strict(property) : property
48429
48805
  ])
48430
48806
  );
48431
- } else if (key === "items" && isSchema(value)) {
48807
+ } else if (key === "items" && isSchema2(value)) {
48432
48808
  result[key] = strict(value);
48433
48809
  } else if (key === "anyOf" && Array.isArray(value)) {
48434
48810
  result[key] = value.map(
48435
- (variant) => isSchema(variant) ? strict(variant) : variant
48811
+ (variant) => isSchema2(variant) ? strict(variant) : variant
48436
48812
  );
48437
48813
  } else {
48438
48814
  result[key] = value;
@@ -54351,7 +54727,7 @@ var compose = (middleware, onError, onNotFound) => {
54351
54727
  };
54352
54728
 
54353
54729
  // node_modules/.pnpm/hono@4.13.13/node_modules/hono/dist/router.js
54354
- var METHODS = [
54730
+ var METHODS2 = [
54355
54731
  "get",
54356
54732
  "post",
54357
54733
  "put",
@@ -54396,7 +54772,7 @@ var Hono = class Hono2 {
54396
54772
  #path = "/";
54397
54773
  routes = [];
54398
54774
  constructor(options = {}) {
54399
- [...METHODS, "all"].forEach((method) => {
54775
+ [...METHODS2, "all"].forEach((method) => {
54400
54776
  this[method] = (args1, ...args2) => {
54401
54777
  const methodName = method.toUpperCase();
54402
54778
  if (typeof args1 === "string") this.#path = args1;
@@ -55543,8 +55919,8 @@ var registerEventsRoute = (app, deps) => {
55543
55919
  while (!stream3.aborted) {
55544
55920
  const event = queue.shift();
55545
55921
  if (event === void 0) {
55546
- await new Promise((resolve3) => {
55547
- wake = resolve3;
55922
+ await new Promise((resolve4) => {
55923
+ wake = resolve4;
55548
55924
  });
55549
55925
  wake = null;
55550
55926
  } else if (event.type === "done") {
@@ -55619,7 +55995,7 @@ var sessionToken = (token) => {
55619
55995
 
55620
55996
  // src/adapters/http/static-files.ts
55621
55997
  import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
55622
- import { join as join2 } from "node:path";
55998
+ import { join as join3 } from "node:path";
55623
55999
 
55624
56000
  // node_modules/.pnpm/hono@4.13.13/node_modules/hono/dist/utils/mime.js
55625
56001
  var getMimeType = (filename, mimes = baseMimes) => {
@@ -55720,12 +56096,12 @@ var registerStaticFiles = (app, staticDir) => {
55720
56096
  const segments = safeSegments(pathname);
55721
56097
  if (segments === null) return c.text("Not found", 404);
55722
56098
  const name2 = segments.at(-1);
55723
- const path4 = join2(staticDir, ...segments);
56099
+ const path4 = join3(staticDir, ...segments);
55724
56100
  if (name2 !== void 0 && name2 !== INDEX && await isFile(path4)) {
55725
56101
  const immutable = segments[0] === "assets";
55726
56102
  return serveFile(c, path4, name2, immutable ? "public, max-age=31536000, immutable" : null);
55727
56103
  }
55728
- const index = join2(staticDir, INDEX);
56104
+ const index = join3(staticDir, INDEX);
55729
56105
  if (!await isFile(index)) return c.text("Not found", 404);
55730
56106
  return serveFile(c, index, INDEX, "no-store");
55731
56107
  });
@@ -56174,7 +56550,7 @@ var readBodyDirect = (request2) => {
56174
56550
  request2[bodyBufferKey] = buffered;
56175
56551
  return Promise.resolve(buffered);
56176
56552
  }
56177
- const promise2 = new Promise((resolve3, reject) => {
56553
+ const promise2 = new Promise((resolve4, reject) => {
56178
56554
  const chunks = [];
56179
56555
  let settled = false;
56180
56556
  const finish = (callback) => {
@@ -56192,7 +56568,7 @@ var readBodyDirect = (request2) => {
56192
56568
  else if (recovered === void 0) reject(error62 ?? normalizeAbortError(request2, incoming));
56193
56569
  else {
56194
56570
  request2[bodyBufferKey] = recovered;
56195
- resolve3(recovered);
56571
+ resolve4(recovered);
56196
56572
  }
56197
56573
  });
56198
56574
  return true;
@@ -56204,7 +56580,7 @@ var readBodyDirect = (request2) => {
56204
56580
  finish(() => {
56205
56581
  const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
56206
56582
  request2[bodyBufferKey] = buffer;
56207
- resolve3(buffer);
56583
+ resolve4(buffer);
56208
56584
  });
56209
56585
  };
56210
56586
  const onError = (error62) => {
@@ -56751,7 +57127,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
56751
57127
  });
56752
57128
  if (!chunk) {
56753
57129
  if (i2 === 1) {
56754
- await new Promise((resolve3) => setTimeout(resolve3));
57130
+ await new Promise((resolve4) => setTimeout(resolve4));
56755
57131
  maxReadCount = 3;
56756
57132
  continue;
56757
57133
  }
@@ -56937,9 +57313,9 @@ var setupWebSocket = (options) => {
56937
57313
  }
56938
57314
  };
56939
57315
  const waitForWebSocket = (request2, connectionSymbol) => {
56940
- return new Promise((resolve3, reject) => {
57316
+ return new Promise((resolve4, reject) => {
56941
57317
  waiterMap.set(request2, {
56942
- resolve: resolve3,
57318
+ resolve: resolve4,
56943
57319
  reject,
56944
57320
  connectionSymbol
56945
57321
  });
@@ -57090,10 +57466,10 @@ var serve = (options, listeningListener) => {
57090
57466
  };
57091
57467
 
57092
57468
  // src/adapters/http/server.ts
57093
- var startHttpServer = (app, options) => new Promise((resolve3, reject) => {
57469
+ var startHttpServer = (app, options) => new Promise((resolve4, reject) => {
57094
57470
  const server = serve(
57095
57471
  { fetch: app.fetch, port: options.port, hostname: "127.0.0.1" },
57096
- (info2) => resolve3({
57472
+ (info2) => resolve4({
57097
57473
  port: info2.port,
57098
57474
  close: () => new Promise((closed, failed) => {
57099
57475
  server.close((error62) => error62 === void 0 ? closed() : failed(error62));
@@ -57366,12 +57742,12 @@ var createJiraTicketSource = (options) => {
57366
57742
  return {
57367
57743
  configured: true,
57368
57744
  async getTickets(keys) {
57369
- const unique = [...new Set(keys)];
57745
+ const unique2 = [...new Set(keys)];
57370
57746
  const tickets = /* @__PURE__ */ new Map();
57371
57747
  let next = 0;
57372
57748
  let failed = false;
57373
57749
  const worker = async () => {
57374
- for (let key = unique[next]; key !== void 0 && !failed; key = unique[next]) {
57750
+ for (let key = unique2[next]; key !== void 0 && !failed; key = unique2[next]) {
57375
57751
  next += 1;
57376
57752
  const ticket = await fetchTicket(key);
57377
57753
  if (!ticket.ok) {
@@ -57382,12 +57758,12 @@ var createJiraTicketSource = (options) => {
57382
57758
  }
57383
57759
  return null;
57384
57760
  };
57385
- const workers = Array.from({ length: Math.min(MAX_IN_FLIGHT, unique.length) }, worker);
57761
+ const workers = Array.from({ length: Math.min(MAX_IN_FLIGHT, unique2.length) }, worker);
57386
57762
  const failure2 = (await Promise.all(workers)).find((error62) => error62 !== null);
57387
57763
  if (failure2 !== void 0 && failure2 !== null) return err2(failure2);
57388
57764
  const lookup = {
57389
- found: unique.flatMap((key) => tickets.get(key) ?? []),
57390
- missing: unique.filter((key) => tickets.get(key) === null)
57765
+ found: unique2.flatMap((key) => tickets.get(key) ?? []),
57766
+ missing: unique2.filter((key) => tickets.get(key) === null)
57391
57767
  };
57392
57768
  options.logger.debug("Fetched Jira tickets", {
57393
57769
  found: lookup.found.length,
@@ -57703,7 +58079,7 @@ var openSqliteAnalysisStore = (options) => {
57703
58079
 
57704
58080
  // src/adapters/treesitter/tree-sitter-code-parser.ts
57705
58081
  import { readFile as readFile3 } from "node:fs/promises";
57706
- import { join as join3 } from "node:path";
58082
+ import { join as join4 } from "node:path";
57707
58083
 
57708
58084
  // node_modules/.pnpm/web-tree-sitter@0.27.1/node_modules/web-tree-sitter/web-tree-sitter.js
57709
58085
  var __defProp2 = Object.defineProperty;
@@ -59334,13 +59710,13 @@ async function Module2(moduleArg = {}) {
59334
59710
  }
59335
59711
  readAsync = /* @__PURE__ */ __name(async (url2) => {
59336
59712
  if (isFileURI(url2)) {
59337
- return new Promise((resolve3, reject) => {
59713
+ return new Promise((resolve4, reject) => {
59338
59714
  var xhr = new XMLHttpRequest();
59339
59715
  xhr.open("GET", url2, true);
59340
59716
  xhr.responseType = "arraybuffer";
59341
59717
  xhr.onload = () => {
59342
59718
  if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
59343
- resolve3(xhr.response);
59719
+ resolve4(xhr.response);
59344
59720
  return;
59345
59721
  }
59346
59722
  reject(xhr.status);
@@ -59536,9 +59912,9 @@ async function Module2(moduleArg = {}) {
59536
59912
  __name(receiveInstantiationResult, "receiveInstantiationResult");
59537
59913
  var info2 = getWasmImports();
59538
59914
  if (Module["instantiateWasm"]) {
59539
- return new Promise((resolve3, reject) => {
59915
+ return new Promise((resolve4, reject) => {
59540
59916
  Module["instantiateWasm"](info2, (mod, inst) => {
59541
- resolve3(receiveInstance(mod, inst));
59917
+ resolve4(receiveInstance(mod, inst));
59542
59918
  });
59543
59919
  });
59544
59920
  }
@@ -60871,8 +61247,8 @@ async function Module2(moduleArg = {}) {
60871
61247
  if (runtimeInitialized) {
60872
61248
  moduleRtn = Module;
60873
61249
  } else {
60874
- moduleRtn = new Promise((resolve3, reject) => {
60875
- readyPromiseResolve = resolve3;
61250
+ moduleRtn = new Promise((resolve4, reject) => {
61251
+ readyPromiseResolve = resolve4;
60876
61252
  readyPromiseReject = reject;
60877
61253
  });
60878
61254
  }
@@ -61770,16 +62146,18 @@ var byExtension = new Map(
61770
62146
  );
61771
62147
  var byName = new Map(LANGUAGES.map((spec) => [spec.name, spec]));
61772
62148
  var languageSpecFor = (path4) => {
61773
- const basename4 = path4.slice(path4.lastIndexOf("/") + 1);
61774
- const dot = basename4.lastIndexOf(".");
62149
+ const basename7 = path4.slice(path4.lastIndexOf("/") + 1);
62150
+ const dot = basename7.lastIndexOf(".");
61775
62151
  if (dot <= 0) return null;
61776
- return byExtension.get(basename4.slice(dot).toLowerCase()) ?? null;
62152
+ return byExtension.get(basename7.slice(dot).toLowerCase()) ?? null;
61777
62153
  };
61778
62154
  var languageSpecNamed = (name2) => byName.get(name2) ?? null;
61779
62155
 
61780
62156
  // src/adapters/treesitter/symbols.ts
61781
62157
  var KINDS = /* @__PURE__ */ new Set(["function", "method", "class", "type", "variable"]);
62158
+ var REFERENCE_KINDS = /* @__PURE__ */ new Set(["name", "member", "type"]);
61782
62159
  var isKind = (kind) => KINDS.has(kind);
62160
+ var isReferenceKind = (kind) => REFERENCE_KINDS.has(kind);
61783
62161
  var startLine = (node2) => node2.startPosition.row + 1;
61784
62162
  var endLine = (node2) => {
61785
62163
  const { row, column } = node2.endPosition;
@@ -61787,11 +62165,14 @@ var endLine = (node2) => {
61787
62165
  };
61788
62166
  var findSymbols = (tree, query) => {
61789
62167
  const definitions = /* @__PURE__ */ new Map();
61790
- const references = [];
62168
+ const references = /* @__PURE__ */ new Map();
62169
+ const imports = /* @__PURE__ */ new Map();
61791
62170
  for (const match2 of query.matches(tree.rootNode)) {
61792
- const name2 = match2.captures.find((capture) => capture.name === "name")?.node;
61793
- const whole = match2.captures.find((capture) => capture.name.startsWith("definition."));
61794
- const reference = match2.captures.find((capture) => capture.name === "reference")?.node;
62171
+ const captures = match2.captures.filter((capture) => !capture.name.startsWith("_"));
62172
+ const name2 = captures.find((capture) => capture.name === "name")?.node;
62173
+ const whole = captures.find((capture) => capture.name.startsWith("definition."));
62174
+ const reference = captures.find((capture) => capture.name.startsWith("reference."));
62175
+ const module2 = captures.find((capture) => capture.name === "import.module")?.node;
61795
62176
  if (name2 !== void 0 && whole !== void 0) {
61796
62177
  const kind = whole.name.slice("definition.".length);
61797
62178
  if (!isKind(kind)) throw new Error(`unknown definition kind in query: ${whole.name}`);
@@ -61807,24 +62188,43 @@ var findSymbols = (tree, query) => {
61807
62188
  }
61808
62189
  });
61809
62190
  } else if (reference !== void 0) {
61810
- references.push({
61811
- position: reference.startIndex,
61812
- reference: { name: reference.text, line: startLine(reference) }
62191
+ const kind = reference.name.slice("reference.".length);
62192
+ if (!isReferenceKind(kind)) throw new Error(`unknown reference kind: ${reference.name}`);
62193
+ const existing = references.get(reference.node.startIndex);
62194
+ if (existing !== void 0 && existing.patternIndex < match2.patternIndex) continue;
62195
+ references.set(reference.node.startIndex, {
62196
+ patternIndex: match2.patternIndex,
62197
+ reference: { name: reference.node.text, line: startLine(reference.node), kind }
61813
62198
  });
62199
+ } else if (module2 !== void 0) {
62200
+ const names = captures.flatMap(
62201
+ (capture) => capture.name === "import.name" ? [capture.node.text] : []
62202
+ );
62203
+ const existing = imports.get(module2.startIndex);
62204
+ const merged = existing === void 0 ? names.length === 0 ? null : names : existing.names === null || names.length === 0 ? null : [...existing.names, ...names];
62205
+ imports.set(module2.startIndex, { module: module2.text, names: merged });
61814
62206
  } else {
61815
62207
  throw new Error(
61816
- `query pattern ${match2.patternIndex} captures neither a definition nor a reference`
62208
+ `query pattern ${match2.patternIndex} captures no definition, reference or import`
61817
62209
  );
61818
62210
  }
61819
62211
  }
61820
- const unique = /* @__PURE__ */ new Map();
61821
- for (const { position, reference } of references) {
62212
+ const unique2 = /* @__PURE__ */ new Map();
62213
+ for (const [position, { reference }] of references) {
61822
62214
  if (definitions.has(position)) continue;
61823
- unique.set(`${reference.line}:${reference.name}`, reference);
62215
+ unique2.set(`${reference.line}:${reference.name}:${reference.kind}`, reference);
61824
62216
  }
61825
62217
  return {
61826
62218
  definitions: [...definitions.values()].map(({ definition }) => definition).sort((a, b) => a.startLine - b.startLine || compare3(a.name, b.name)),
61827
- references: [...unique.values()].sort((a, b) => a.line - b.line || compare3(a.name, b.name))
62219
+ references: [...unique2.values()].sort(
62220
+ (a, b) => a.line - b.line || compare3(a.name, b.name) || compare3(a.kind, b.kind)
62221
+ ),
62222
+ imports: [...imports.entries()].sort(([a], [b]) => a - b).map(
62223
+ ([, { module: module2, names }]) => ({
62224
+ module: module2,
62225
+ names: names === null ? null : [...new Set(names)]
62226
+ })
62227
+ )
61828
62228
  };
61829
62229
  };
61830
62230
  var compare3 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
@@ -61873,7 +62273,7 @@ var syntaxNodes = (tree, source) => {
61873
62273
  var runtime = null;
61874
62274
  var createTreeSitterCodeParser = async (options) => {
61875
62275
  const { grammarsDir, maxFileBytes = 1e6 } = options;
61876
- runtime ??= Parser.init({ locateFile: (file2) => join3(grammarsDir, file2) });
62276
+ runtime ??= Parser.init({ locateFile: (file2) => join4(grammarsDir, file2) });
61877
62277
  await runtime;
61878
62278
  const loaded = /* @__PURE__ */ new Map();
61879
62279
  const load = (spec) => {
@@ -61911,10 +62311,10 @@ var createTreeSitterCodeParser = async (options) => {
61911
62311
  };
61912
62312
  var loadLanguage = async (grammarsDir, spec) => {
61913
62313
  const language = await Language.load(
61914
- await readFile3(join3(grammarsDir, `tree-sitter-${spec.name}.wasm`))
62314
+ await readFile3(join4(grammarsDir, `tree-sitter-${spec.name}.wasm`))
61915
62315
  );
61916
62316
  const queries = await Promise.all(
61917
- spec.queries.map((name2) => readFile3(join3(grammarsDir, "queries", `${name2}.scm`), "utf8"))
62317
+ spec.queries.map((name2) => readFile3(join4(grammarsDir, "queries", `${name2}.scm`), "utf8"))
61918
62318
  );
61919
62319
  const parser = new Parser();
61920
62320
  parser.setLanguage(language);
@@ -61973,7 +62373,7 @@ var appError = (code2, message) => ({ code: code2, message });
61973
62373
  var fromHostError = (error62) => appError(error62.kind === "not-found" ? "not-found" : "host-error", error62.message);
61974
62374
 
61975
62375
  // src/application/use-cases/pipeline-version.ts
61976
- var PIPELINE_VERSION = "3";
62376
+ var PIPELINE_VERSION = "6";
61977
62377
  var pipelineVersion = (model, modelEnabled) => `${PIPELINE_VERSION}+${modelEnabled ? model.version : "no-model"}`;
61978
62378
 
61979
62379
  // src/application/use-cases/text.ts
@@ -62123,7 +62523,8 @@ var buildAnalysisInput = (input2) => {
62123
62523
  headContent: hunks.length > 0 ? input2.headContents.get(file2.path) ?? null : null
62124
62524
  };
62125
62525
  }),
62126
- callGraph: prepared.callGraph
62526
+ // The model follows calls; type uses would only lengthen its prompt.
62527
+ callGraph: prepared.callGraph.filter((hint) => hint.use === "call")
62127
62528
  };
62128
62529
  };
62129
62530
  var mechanicalHunk = (hunk, proof) => ({
@@ -62296,7 +62697,14 @@ var runTour = async (model, input2, context2, logger) => {
62296
62697
  logger
62297
62698
  );
62298
62699
  const fallback = (reason) => ({
62299
- tour: codeTour(context2.files, required2, context2.callGraph, context2.assessments),
62700
+ tour: codeTour({
62701
+ files: context2.files,
62702
+ required: required2,
62703
+ callGraph: context2.callGraph,
62704
+ risk: context2.assessments,
62705
+ definitions: context2.definitions,
62706
+ generated: context2.generated
62707
+ }),
62300
62708
  usage,
62301
62709
  warnings: [`${reason}, so the tour follows the call graph instead`]
62302
62710
  });
@@ -62310,7 +62718,9 @@ var runTour = async (model, input2, context2, logger) => {
62310
62718
  tour: {
62311
62719
  steps: outcome.value.value.steps.map((step, index) => ({
62312
62720
  ...step,
62313
- id: TourStepId.parse(`s${index + 1}`)
62721
+ id: TourStepId.parse(`s${index + 1}`),
62722
+ kind: "flow",
62723
+ via: []
62314
62724
  })),
62315
62725
  builtBy: "model"
62316
62726
  },
@@ -62356,6 +62766,12 @@ var prep = async (parser, collected) => {
62356
62766
  return {
62357
62767
  proofs,
62358
62768
  callGraph: buildCallGraphHints(files, symbolsByPath),
62769
+ definitions: changedDefinitionNames(files, symbolsByPath),
62770
+ generated: new Set(
62771
+ files.flatMap(
62772
+ (file2) => looksGenerated(headContents.get(file2.path) ?? "") ? [file2.path] : []
62773
+ )
62774
+ ),
62359
62775
  warnings: lockfileWarnings(files),
62360
62776
  required: new Set(
62361
62777
  files.flatMap((file2) => file2.hunks.map((hunk) => hunk.id)).filter((id) => !provedHunks.has(id))
@@ -62433,7 +62849,7 @@ var stages = async (deps, host, pullRequest, tracker) => {
62433
62849
  }));
62434
62850
  await tracker.setStage("prep", "running");
62435
62851
  const prepared = await prep(deps.parser, collected.value);
62436
- const { proofs, callGraph, required: required2 } = prepared;
62852
+ const { proofs, callGraph, required: required2, definitions, generated } = prepared;
62437
62853
  const proofRisk = proofs.flatMap(
62438
62854
  (proof) => proof.hunkId === null ? [] : [
62439
62855
  {
@@ -62451,7 +62867,7 @@ var stages = async (deps, host, pullRequest, tracker) => {
62451
62867
  await tracker.setStage("prep", "done", (analysis) => ({
62452
62868
  ...prepPatch,
62453
62869
  risk: risk2,
62454
- tour: codeTour(files, required2, callGraph, risk2),
62870
+ tour: codeTour({ files, required: required2, callGraph, risk: risk2, definitions, generated }),
62455
62871
  ...adding(prepared)(analysis)
62456
62872
  }));
62457
62873
  for (const stage of MODEL_STAGES) await tracker.setStage(stage, "skipped");
@@ -62528,6 +62944,8 @@ var stages = async (deps, host, pullRequest, tracker) => {
62528
62944
  files,
62529
62945
  required: required2,
62530
62946
  callGraph,
62947
+ definitions,
62948
+ generated,
62531
62949
  assessments: risk.value.assessments
62532
62950
  },
62533
62951
  logger
@@ -62915,7 +63333,7 @@ var compose2 = async (config2, options) => {
62915
63333
  } catch (error62) {
62916
63334
  return err2(`Can't create ${config2.home}: ${messageOf(error62)}`);
62917
63335
  }
62918
- const path4 = join4(config2.home, "db.sqlite");
63336
+ const path4 = join5(config2.home, "db.sqlite");
62919
63337
  let store;
62920
63338
  try {
62921
63339
  store = openSqliteAnalysisStore({ path: path4, clock, logger });
@@ -62953,7 +63371,7 @@ var compose2 = async (config2, options) => {
62953
63371
  // src/cli/config.ts
62954
63372
  import { execFile } from "node:child_process";
62955
63373
  import { homedir } from "node:os";
62956
- import { join as join5, resolve as resolve2 } from "node:path";
63374
+ import { join as join6, resolve as resolve3 } from "node:path";
62957
63375
  var LOG_LEVELS = ["debug", "info", "warn", "error"];
62958
63376
  var COMMAND_TIMEOUT_MS = 5e3;
62959
63377
  var runCommand = (file2, args2) => new Promise((done) => {
@@ -63010,7 +63428,7 @@ var loadConfig2 = async (options = {}) => {
63010
63428
  }
63011
63429
  }
63012
63430
  const homeValue = read("MEGAREVIEWER_HOME");
63013
- const home = homeValue === null ? join5(options.homeDir ?? homedir(), ".megareviewer") : resolve2(homeValue);
63431
+ const home = homeValue === null ? join6(options.homeDir ?? homedir(), ".megareviewer") : resolve3(homeValue);
63014
63432
  const logValue = read("MEGAREVIEWER_LOG")?.toLowerCase() ?? "info";
63015
63433
  const logLevel = LOG_LEVELS.find((level) => level === logValue);
63016
63434
  if (logLevel === void 0) {
@@ -63057,7 +63475,7 @@ var readGitHub = async (read, run3) => {
63057
63475
  // src/cli/doctor.ts
63058
63476
  init_sdk();
63059
63477
  import { mkdirSync as mkdirSync2 } from "node:fs";
63060
- import { join as join6 } from "node:path";
63478
+ import { join as join7 } from "node:path";
63061
63479
 
63062
63480
  // src/cli/node-version.ts
63063
63481
  var MIN_NODE = { major: 22, minor: 13 };
@@ -63190,7 +63608,7 @@ var createDoctorDeps = async (options) => {
63190
63608
  try {
63191
63609
  mkdirSync2(config2.home, { recursive: true, mode: 448 });
63192
63610
  const store = openSqliteAnalysisStore({
63193
- path: join6(config2.home, "db.sqlite"),
63611
+ path: join7(config2.home, "db.sqlite"),
63194
63612
  clock: systemClock,
63195
63613
  logger
63196
63614
  });
@@ -63275,13 +63693,13 @@ var serve2 = async (appFor, port) => {
63275
63693
  // src/cli/main.ts
63276
63694
  var { version: version2 } = package_default;
63277
63695
  var locateAssets = () => {
63278
- const here = dirname4(fileURLToPath(import.meta.url));
63279
- const bundled = join7(here, "grammars");
63696
+ const here = dirname5(fileURLToPath(import.meta.url));
63697
+ const bundled = join8(here, "grammars");
63280
63698
  if (!existsSync(bundled)) {
63281
- return { grammarsDir: join7(here, "../adapters/treesitter/grammars"), staticDir: null };
63699
+ return { grammarsDir: join8(here, "../adapters/treesitter/grammars"), staticDir: null };
63282
63700
  }
63283
- const web = join7(here, "web");
63284
- return { grammarsDir: bundled, staticDir: existsSync(join7(web, "index.html")) ? web : null };
63701
+ const web = join8(here, "web");
63702
+ return { grammarsDir: bundled, staticDir: existsSync(join8(web, "index.html")) ? web : null };
63285
63703
  };
63286
63704
  var printProblems = (problems) => {
63287
63705
  console.error("megareviewer can't start:");